@evomap/evolver-cli 2.0.23 → 2.0.25

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.
@@ -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 });
@@ -167,14 +167,16 @@ async function collectDistillInput(store, maxCapsules, minSuccessScore) {
167
167
  const successCapsules = capsules.filter((record) => isSuccessCapsule(record, minSuccessScore)).slice(-maxCapsules);
168
168
  return { dataHash: hashCapsules(successCapsules), successCapsules, existingGenes };
169
169
  }
170
- function buildDistillPrompt(input) {
171
- const capsules = hub.redactDeep(input.successCapsules.map(capsuleDigestView));
172
- 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) => ({
173
173
  id: gene['id'],
174
174
  category: gene['category'],
175
175
  signals_match: gene['signals_match'],
176
176
  summary: gene['summary'],
177
- })));
177
+ }));
178
+ const capsules = redact ? hub.redactDeep(rawCapsules) : rawCapsules;
179
+ const genes = redact ? hub.redactDeep(rawGenes) : rawGenes;
178
180
  // Scope-language alignment (review ②): show the model the signals the store ACTUALLY uses BEFORE it chooses a
179
181
  // scope facet. The autonomous-scope experiment (result-recovery-autoscope-joint-metric.json) isolated the
180
182
  // failure as structural, not a model weakness — the distiller reads solved source code and never observes the
@@ -537,16 +539,12 @@ export async function autoDistillLlm(options) {
537
539
  }
538
540
  const runner = options.runner ?? resolveDistillRunner(env);
539
541
  const timeoutMs = envInt(env, 'EVOLVE_DISTILL_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
540
- const prompt = buildDistillPrompt(input);
541
- // Egress-floor parity: buildDistillPrompt already pattern-redacts via hub.redactDeep, but the Hub publish path
542
- // additionally runs a REVERSE env-value scan (hub.detectEnvValueLeaks) that flags any process-env value
543
- // appearing verbatim in the payload — catching custom-format secrets no pattern matches. The prompt is an
544
- // off-box egress (stdin to a spawned `claude`), so hold it to the same floor the repo enforces on publish: if a
545
- // daemon env secret leaked into a capsule, fail CLOSED and never send it. This is a data-hygiene block, not a
546
- // deterministic claude failure, so — like a transient exit below — it does NOT bump failed_attempts.
547
- if (hub.detectEnvValueLeaks(prompt, env).length > 0) {
542
+ // LLM prompt 属于外部输出边界。先对脱敏前的同构内容执行反向环境变量扫描,
543
+ // 避免高熵模式先替换秘密后让泄漏检查误判为安全;该阻断不计入确定性失败次数。
544
+ if (hub.detectEnvValueLeaks(buildDistillPrompt(input, false), env).length > 0) {
548
545
  return { ok: false, mode, reason: 'prompt_env_leak_blocked', dataHash: input.dataHash };
549
546
  }
547
+ const prompt = buildDistillPrompt(input);
550
548
  const llm = await runner(prompt, { cwd, timeoutMs, env });
551
549
  if (llm.exitCode !== 0) {
552
550
  // V1 parity: a PROCESS-level claude failure — spawn error/ENOENT or timeout→SIGKILL (exitCode === null), OR a
package/dist/autoexec.js CHANGED
@@ -194,7 +194,8 @@ function isAutoExecVerdict(value, taskId) {
194
194
  || candidate.status === 'skipped'
195
195
  || candidate.status === 'solidified'
196
196
  || candidate.status === 'failed'
197
- || candidate.status === 'innovated');
197
+ || candidate.status === 'innovated'
198
+ || candidate.status === 'unsafe_to_replay');
198
199
  }
199
200
  function persistedClaimReceipt(dirs, claim, taskId) {
200
201
  try {
@@ -209,7 +210,7 @@ function persistedClaimReceipt(dirs, claim, taskId) {
209
210
  || (receipt.destination !== 'done' && receipt.destination !== 'refused')
210
211
  || !isAutoExecVerdict(receipt.verdict, taskId))
211
212
  return null;
212
- const expectedDestination = receipt.verdict.status === 'refused' ? 'refused' : 'done';
213
+ const expectedDestination = receipt.verdict.status === 'refused' || receipt.verdict.status === 'unsafe_to_replay' ? 'refused' : 'done';
213
214
  if (receipt.destination !== expectedDestination)
214
215
  return null;
215
216
  return receipt;
@@ -329,7 +330,7 @@ export async function autoExecPass(dirs, runOne, options = {}) {
329
330
  const startedPath = join(dirs.inflight, startedName);
330
331
  renameSync(taskPath, startedPath);
331
332
  const v = await runOne(task).catch((e) => ({ taskId: task.id, status: 'failed', reason: e instanceof Error ? e.message : String(e) }));
332
- const destination = v.status === 'refused' ? 'refused' : 'done';
333
+ const destination = v.status === 'refused' || v.status === 'unsafe_to_replay' ? 'refused' : 'done';
333
334
  const dest = destination === 'refused' ? dirs.refused : dirs.done;
334
335
  persistClaimReceipt(dirs, { claimName: startedName, destination, verdict: v });
335
336
  writeFileSync(join(dest, claim.originalName), JSON.stringify(v, null, 2));
@@ -628,7 +629,7 @@ const DISTILL_TICK_EXPLORATION_SIGNALS = ['stable_success_plateau', 'runtime_ses
628
629
  * refused/skipped ran no cycle — there is nothing to attribute, so no report.
629
630
  */
630
631
  export function verdictToOutcomeStatus(status) {
631
- if (status === 'solidified' || status === 'innovated')
632
+ if (status === 'solidified')
632
633
  return 'success';
633
634
  if (status === 'failed')
634
635
  return 'failed';
@@ -1579,8 +1580,20 @@ export async function runAutoExec(argv) {
1579
1580
  const selectionFloor = selectionFloorFromEnv();
1580
1581
  // File-only and best-effort: tracing must never fail or slow a task.
1581
1582
  const learningTrace = resolveLearningTrace(process.env);
1583
+ const executionBindingAuthority = {
1584
+ claimLease: () => false,
1585
+ acceptanceSpec: () => false,
1586
+ budget: () => false,
1587
+ consent: () => false,
1588
+ };
1582
1589
  const deps = withAutoExecSelectionConfig({
1583
1590
  engine, store, provenance, review, personality: personalityStore, memoryGraph,
1591
+ executionBinding: {
1592
+ journal: new exec.ExecutionBindingJournal(ingestor),
1593
+ authority: executionBindingAuthority,
1594
+ now: () => Date.now(),
1595
+ maxRuntimeMs: cfg.timeoutMs,
1596
+ },
1584
1597
  ...(learningTrace.config ? { learningTrace: learningTrace.config } : {}),
1585
1598
  // Probation (#306, gated, default OFF via EVOLVER_GENE_PROBATION): try unproven auto-distilled genes (with their
1586
1599
  // strategy embedded) so the cross-AI loop self-closes — contained by the proven exec gates + worktree isolation.
@@ -1592,13 +1605,32 @@ export async function runAutoExec(argv) {
1592
1605
  // Validate through the hardened sandbox verifier so a validation command can't exfiltrate or phone home to game
1593
1606
  // the result. Validation is bounded by the sandbox's own per-command cap (NOT the agent exec timeout, a
1594
1607
  // different unit) so a long suite is not silently SIGKILL'd against the wrong budget.
1595
- validate: (task) => async (_m, _d, cwd) => {
1608
+ validate: (task) => async (_m, _d, cwd, signal) => {
1596
1609
  const cmds = task.validationCmds ?? [];
1597
- const r = await runRequiredSandboxedValidation(cmds, cwd);
1610
+ const bindingRuntimeMs = task.execution_binding?.resource_grant.max_runtime_ms;
1611
+ const safetyRuntimeMs = cfg.timeoutMs;
1612
+ const validationTimeoutMs = bindingRuntimeMs === undefined
1613
+ ? safetyRuntimeMs
1614
+ : Math.min(bindingRuntimeMs, safetyRuntimeMs);
1615
+ const r = await runRequiredSandboxedValidation(cmds, cwd, { timeoutMs: validationTimeoutMs, ...(signal ? { signal } : {}) });
1598
1616
  const validationSummary = summarizeSandboxedValidation(r);
1599
1617
  if (validationSummary)
1600
1618
  process.stdout.write(` validation: ${validationSummary}\n`);
1601
- return { passed: r.passed, score: r.score };
1619
+ return {
1620
+ passed: r.passed,
1621
+ score: r.score,
1622
+ validator: {
1623
+ id: 'required_sandboxed_validation',
1624
+ version: 'sandboxed_validation.v1',
1625
+ status: 'ran',
1626
+ plan_digest: exec.computeValidationPlanDigest(cmds),
1627
+ passed: r.passed,
1628
+ score: r.score,
1629
+ results: r.results,
1630
+ skipped: r.skipped,
1631
+ isolated: r.isolated,
1632
+ },
1633
+ };
1602
1634
  },
1603
1635
  }, process.env);
1604
1636
  const safety = { allowedRoots: cfg.allowedRoots, timeoutMs: cfg.timeoutMs, runner: cfg.runner };
@@ -28,8 +28,10 @@ interface GateSummary {
28
28
  schema?: 'pass' | 'fail';
29
29
  bundle?: 'pass' | 'fail';
30
30
  quality?: 'pass' | 'fail';
31
+ quality_evidence?: PublishQualityEvidenceSource;
31
32
  validation_command?: 'pass' | 'fail';
32
33
  }
34
+ type PublishQualityEvidenceSource = 'local_history' | 'bundle_seed' | 'none' | 'unavailable';
33
35
  interface PublishAssetSummary {
34
36
  asset_id?: string;
35
37
  type?: assetstore.AssetKind;
@@ -283,6 +283,7 @@ export async function runPublishCommand(args, deps = {}) {
283
283
  ...(bundleId ? { bundle_id: bundleId } : {}),
284
284
  ...(recipeId ? { recipe_id: recipeId } : {}),
285
285
  ...(safetyCandidate ? { hub_reason: hubReason } : {}),
286
+ gates: bundle.gates,
286
287
  // What the Hub actually holds — after a repair that is the mended record, not the one first submitted.
287
288
  assets: repairApplied?.applied === true ? summarizePublishAssets(effectiveAssets) : bundle.assets,
288
289
  ...(publishCredits ? { credits: publishCredits } : {}),
@@ -582,6 +583,7 @@ export async function buildPublishBundle(refs, deps = {}) {
582
583
  schema: 'pass',
583
584
  bundle: 'pass',
584
585
  quality: geneProven ? 'pass' : 'fail',
586
+ quality_evidence: geneEvidence?.source ?? 'unavailable',
585
587
  validation_command: validationCommandResult.allowed ? 'pass' : 'fail',
586
588
  };
587
589
  const blockReasons = [];
@@ -606,10 +608,9 @@ export async function buildPublishBundle(refs, deps = {}) {
606
608
  assets: summarizePublishAssets(sanitized),
607
609
  };
608
610
  }
609
- // Assess whether the bundle's Gene has proven success in the local capsule
610
- // history. Fail-open (returns null) when there is no gene id or the store read
611
- // throws — the pre-check only ADDS a local gate; the Hub still gates, so an
612
- // infra hiccup must not block an otherwise-valid publish.
611
+ // 评估 bundle 中 Gene 的成功证据。历史记录来自本地 Capsule store;显式提交的、
612
+ // 通过完整校验的成功 Capsule 也可作为首次发布的 seed。没有 gene id 或 store
613
+ // 读取失败时保持 fail-open,因为这道预检只增加本地门槛,最终质量判定仍由 Hub 负责。
613
614
  async function assessPublishGeneEvidence(original, deps) {
614
615
  const gene = original.find((asset) => asset.type === 'Gene');
615
616
  if (!gene)
@@ -619,6 +620,8 @@ async function assessPublishGeneEvidence(original, deps) {
619
620
  const geneId = businessId ?? assetId;
620
621
  if (!geneId)
621
622
  return null;
623
+ const geneIds = new Set([businessId, assetId].filter((id) => Boolean(id)));
624
+ const hasBundleSeed = hasVerifiedSuccessfulBundleCapsule(original, geneIds);
622
625
  try {
623
626
  const store = deps.assetStore ?? new assetstore.LocalJsonlProvider(contractAssetsDir(deps));
624
627
  const primary = await algo.assessGenePublishEvidence(store, geneId);
@@ -627,28 +630,43 @@ async function assessPublishGeneEvidence(original, deps) {
627
630
  // contain failures under the business id and a success under asset_id, so
628
631
  // both aliases must contribute to the gate rather than only falling back
629
632
  // when the primary alias has no rows at all.
630
- if (assetId && assetId !== geneId) {
631
- const byAssetId = await algo.assessGenePublishEvidence(store, assetId);
632
- const combined = {
633
- success: primary.success + byAssetId.success,
634
- failed: primary.failed + byAssetId.failed,
635
- inert: primary.inert + byAssetId.inert,
636
- total: primary.total + byAssetId.total,
637
- };
638
- const eligible = algo.isGenePublishEligible(combined);
639
- return {
640
- geneId,
641
- ...combined,
642
- eligible,
643
- reason: eligible ? 'eligible' : 'no_proven_success',
644
- };
645
- }
646
- return primary;
633
+ const byAssetId = assetId && assetId !== geneId
634
+ ? await algo.assessGenePublishEvidence(store, assetId)
635
+ : undefined;
636
+ const localEvidence = {
637
+ success: primary.success + (byAssetId?.success ?? 0),
638
+ inert: primary.inert + (byAssetId?.inert ?? 0),
639
+ };
640
+ if (algo.isGenePublishEligible(localEvidence))
641
+ return { eligible: true, source: 'local_history' };
642
+ if (hasBundleSeed)
643
+ return { eligible: true, source: 'bundle_seed' };
644
+ return { eligible: false, source: 'none' };
647
645
  }
648
646
  catch {
647
+ // 本地 store 不可用时保持历史 fail-open 行为。显式 Capsule 只有在上面的
648
+ // content hash 和 wire schema 校验都通过后才会计入,非法文件不会变成证据。
649
+ if (hasBundleSeed)
650
+ return { eligible: true, source: 'bundle_seed' };
649
651
  return null;
650
652
  }
651
653
  }
654
+ /**
655
+ * 首次发布可以把已经生成的成功 Capsule 作为同一 bundle 的证据提交。
656
+ * 之前这里只读取本地 capsules.jsonl,导致 `--gene file --capsule file`
657
+ * 即使带有成功 Capsule 也在到达 Hub 前被 `gene_unproven` 拦截。
658
+ *
659
+ * 外部文件不是本地历史,必须先通过完整 wire schema 和 content hash 校验;
660
+ * 失败或缺少成功 outcome 的 Capsule 不会解锁 quality gate。该证据只用于
661
+ * 本地预检,Hub 仍然负责最终质量判定和持久化。
662
+ */
663
+ function hasVerifiedSuccessfulBundleCapsule(original, geneIds) {
664
+ const capsule = original.find((asset) => (asset.type === 'Capsule' && geneIds.has(stringField(asset, 'gene') ?? '')));
665
+ if (!capsule || !wire.validateWireDeep(capsule).ok || !wire.verifyAssetId(capsule)) {
666
+ return false;
667
+ }
668
+ return stringField(asRecord(capsule['outcome']), 'status') === 'success';
669
+ }
652
670
  /**
653
671
  * 检查 Gene 资产中的验证命令是否安全。
654
672
  * 只检查 Gene 类型的资产,不影响 Capsule 或 EvolutionEvent。
@@ -86,11 +86,11 @@ function makeCycleValidationHook(validationCmds, fallback, runSandboxedValidatio
86
86
  return fallback;
87
87
  return (task) => {
88
88
  const fallbackHook = fallback?.(task);
89
- return async (mutation, decision, cwd) => {
90
- const fallbackResult = fallbackHook ? await fallbackHook(mutation, decision, cwd) : null;
89
+ return async (mutation, decision, cwd, signal) => {
90
+ const fallbackResult = fallbackHook ? await fallbackHook(mutation, decision, cwd, signal) : null;
91
91
  if (fallbackResult && !fallbackResult.passed)
92
92
  return fallbackResult;
93
- const result = await runRequiredSandboxedValidation(task.validationCmds ?? validationCmds, cwd, {}, runSandboxedValidation);
93
+ const result = await runRequiredSandboxedValidation(task.validationCmds ?? validationCmds, cwd, { signal }, runSandboxedValidation);
94
94
  return { passed: result.passed, score: result.score };
95
95
  };
96
96
  };
@@ -5,10 +5,12 @@
5
5
  // gene.distilled. It reuses the exact same `draftGeneCandidate` as `evolver ingest --distill`, so the one-shot and
6
6
  // the auto path never drift.
7
7
  //
8
- // WIRING (#117 / #106): this composition is ready to register on the resident daemon's ObserverBus, but the
9
- // PRODUCER of material.batch_ready (a daemon ingesting session dirs onto the same bus Ingestor) is a #106 item.
10
- // Until that lands, the composition is verified by its integration test (real bus + Ingestor dispatch) but not yet
11
- // wired into autoexec — a tracked dependency, not dead code. See distillObserver.test.ts.
8
+ // WIRING (#117 / #106): LIVE. `autoexec.ts` imports `resolveDistillObserver`, builds it inside
9
+ // `resolveDistillProducer`, registers it on the daemon's ObserverBus, drives `distill.tick()` every beat, and
10
+ // `kick()`s it on boot to drain any backlog left un-acked by a prior run. The `material.batch_ready` producer is
11
+ // the session-ingest tick on the same Ingestor. See distillObserver.test.ts for the isolated proof.
12
+ // (This said "not yet wired into autoexec" long after it was wired. A stale WIRING note is worse than none: it
13
+ // reads as a real gap, and a 2026-08 audit did misreport this composition as unwired on the strength of it.)
12
14
  import { assetstore, events, observers, signals, algo } from '@evomap/evolver-core';
13
15
  import { readFileSync } from 'node:fs';
14
16
  import { draftGeneCandidate } from './distillPrimitives.js';
package/dist/doctor.d.ts CHANGED
@@ -38,6 +38,17 @@ export interface DoctorDeps {
38
38
  profile?: DoctorProfile;
39
39
  label?: string;
40
40
  memoryGraphStatus?: (env: Record<string, string | undefined>) => MemoryGraphOperatorStatus;
41
+ /** Runtime platform override (tests). Defaults to process.platform. */
42
+ platform?: NodeJS.Platform;
43
+ /** Test seam for the read-only legacy v1 Windows scheduled-task probe (#956). */
44
+ legacyWindowsTasks?: (options: {
45
+ env: NodeJS.ProcessEnv;
46
+ platform?: NodeJS.Platform;
47
+ }) => {
48
+ conclusive: boolean;
49
+ legacy: string[];
50
+ detail: string;
51
+ };
41
52
  }
42
53
  export interface EnvCatalogResult {
43
54
  profile: DoctorProfile;
package/dist/doctor.js CHANGED
@@ -7,6 +7,7 @@ import { isAbsolute, join } from 'node:path';
7
7
  import { bootstrap, events, issueReporter } from '@evomap/evolver-core';
8
8
  import { expandHomePath, parseEnvFile } from '@evomap/evolver-mcp';
9
9
  import { formatMemoryGraphOperatorStatus, loadMemoryGraphOperatorStatus } from './localMemoryGraph.js';
10
+ import { LEGACY_TASK_SKIP_ENV, probeLegacyWindowsDaemonTasks } from './windowsLegacyTaskCleanup.js';
10
11
  // Secrets that must live ONLY behind the EVOLVER_ENV_FILE pointer — never inlined into a runtime config (#217).
11
12
  const SECRET_KEYS = [
12
13
  'A2A_NODE_SECRET',
@@ -696,6 +697,29 @@ export function runDoctorChecks(deps = {}) {
696
697
  catch {
697
698
  checks.push({ name: 'memory-graph', status: 'warn', detail: 'state=degraded corrupt=1 oversized_lines=0 oversized_files=0 archives=0' });
698
699
  }
700
+ // 5. windows-legacy-tasks (#956): read-only probe for legacy V1 scheduled-task residue
701
+ // (win32 only). A detected residue warns with the manual fix; an INCONCLUSIVE probe
702
+ // also warns — it must never be reported as a confirmed-negative pass.
703
+ if ((deps.platform ?? process.platform) === 'win32') {
704
+ try {
705
+ const probe = (deps.legacyWindowsTasks ?? probeLegacyWindowsDaemonTasks)({
706
+ env: effectiveEnv,
707
+ platform: 'win32',
708
+ });
709
+ if (!probe.conclusive) {
710
+ checks.push({ name: 'windows-legacy-tasks', status: 'warn', detail: `probe inconclusive (${probe.detail}); legacy v1 residue cannot be ruled out — run evolver lifecycle cleanup-legacy-tasks --dry-run, or set ${LEGACY_TASK_SKIP_ENV}=1 to silence the automatic probes on restricted hosts` });
711
+ }
712
+ else if (probe.legacy.length > 0) {
713
+ checks.push({ name: 'windows-legacy-tasks', status: 'warn', detail: `detected legacy v1 scheduled task(s): ${probe.legacy.join(', ')} — run evolver lifecycle cleanup-legacy-tasks` });
714
+ }
715
+ else {
716
+ checks.push({ name: 'windows-legacy-tasks', status: 'pass', detail: 'no legacy v1-style scheduled tasks registered' });
717
+ }
718
+ }
719
+ catch {
720
+ checks.push({ name: 'windows-legacy-tasks', status: 'warn', detail: `probe inconclusive (internal error); legacy v1 residue cannot be ruled out — run evolver lifecycle cleanup-legacy-tasks --dry-run, or set ${LEGACY_TASK_SKIP_ENV}=1 to silence the automatic probes on restricted hosts` });
721
+ }
722
+ }
699
723
  return checks;
700
724
  }
701
725
  export function buildEnvCatalog(deps = {}) {
package/dist/index.d.ts CHANGED
@@ -160,6 +160,8 @@ export interface InjectDeps {
160
160
  readHookInput?: () => string | undefined;
161
161
  /** Test seam for the hook-time proxy daemon recovery path. Default is maybeAutoRestartProxyForSessionStart. */
162
162
  ensureProxyAutostart?: () => Promise<void>;
163
+ /** Test seam for the hook-time legacy v1 Windows scheduled-task sweep (#956). */
164
+ legacyTaskSweep?: () => void;
163
165
  /** Test seam for the non-git workspace notice. Production uses cwd + ~/.evomap throttle state. */
164
166
  nonGitNotice?: NonGitWorkspaceNoticeOptions;
165
167
  }
package/dist/index.js CHANGED
@@ -5,7 +5,7 @@ import { assetstore, algo, signals, material as materialNs } from '@evomap/evolv
5
5
  import { loadPriceTable } from '@evomap/evolver-adapter-public';
6
6
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
7
  import { makeInjectEmitter } from './autoexec.js';
8
- import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
8
+ import { listApprovedGenes, pendingGeneReviewRecords, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
9
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
10
10
  import { draftGeneCandidate } from './distillPrimitives.js';
11
11
  import { assessDraftAdmissionFromStore } from './distillAdmission.js';
@@ -17,6 +17,7 @@ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
17
17
  import { applyImportV1Plan, planImportV1 } from './migrate/v1Import.js';
18
18
  import { explicitRecipeHomes } from './recipe.js';
19
19
  import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled, dailyConnectionStatus, lifecyclePaths } from './lifecycle.js';
20
+ import { maybeCleanupLegacyWindowsDaemonTasks } from './windowsLegacyTaskCleanup.js';
20
21
  import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
21
22
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
22
23
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
@@ -1146,10 +1147,22 @@ export async function runReview(argv, store, review, deps = {}) {
1146
1147
  .map((e) => String(e.payload?.['assetId'] ?? ''))
1147
1148
  .filter(Boolean));
1148
1149
  const autoPending = [...autoDrafted].filter((a) => rev.get(a)?.state === 'quarantined').length;
1149
- const genes = await s.list('Gene', limit);
1150
+ const pending = await pendingGeneReviewRecords(s, rev);
1151
+ const pendingRows = [];
1152
+ for (const record of pending) {
1153
+ const gene = await s.get(record.assetId);
1154
+ if (gene && gene.type === 'Gene')
1155
+ pendingRows.push(gene);
1156
+ }
1157
+ const autoPendingRows = pendingRows.filter((gene) => autoDrafted.has(String(gene.asset_id))).length;
1158
+ const manualPending = pendingRows.length - autoPendingRows;
1159
+ const listed = await s.list('Gene', Math.max(limit, 1));
1160
+ const pendingIds = new Set(pendingRows.map((gene) => String(gene.asset_id)));
1161
+ const rest = listed.filter((gene) => !pendingIds.has(String(gene.asset_id)));
1162
+ const genes = [...pendingRows, ...rest].slice(0, limit);
1150
1163
  if (genes.length === 0)
1151
- process.stdout.write('(no genes)\n'); // no early return: the auto-pending footer below is
1152
- for (const g of genes) { // computed from the full event set, so it must print
1164
+ process.stdout.write('(no genes)\n'); // no early return: the pending footer below is
1165
+ for (const g of genes) { // computed from the full ledger, so it must print
1153
1166
  const id = typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id);
1154
1167
  const view = await assetstore.aggregateLearningHistory(s, id);
1155
1168
  const cat = String(g['category'] ?? '?');
@@ -1162,8 +1175,10 @@ export async function runReview(argv, store, review, deps = {}) {
1162
1175
  const promote = state === 'quarantined' ? ` promote:${promoteHint(view)}` : '';
1163
1176
  process.stdout.write(`${id.padEnd(28)} ${cat.padEnd(10)} total=${view.total} succ=${rate} [${reviewStatus(view)}] {${state}}${promote}${auto}\n`);
1164
1177
  }
1178
+ if (manualPending > 0)
1179
+ process.stdout.write(`\n${manualPending} gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
1165
1180
  if (autoPending > 0)
1166
- process.stdout.write(`\n${autoPending} auto-drafted gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
1181
+ process.stdout.write(`${manualPending > 0 ? '' : '\n'}${autoPending} auto-drafted gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
1167
1182
  const antiGenePending = (await listReviewVisibleAntiGenes(s, rev)).filter((asset) => rev.get(String(asset.asset_id))?.state === 'quarantined').length;
1168
1183
  if (antiGenePending > 0)
1169
1184
  process.stdout.write(`\n${antiGenePending} anti-gene(s) awaiting review - inspect with \`evolver review --anti-gene\`\n`);
@@ -1540,6 +1555,9 @@ export async function runInject(argv, deps = {}) {
1540
1555
  process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
1541
1556
  }
1542
1557
  }
1558
+ // NOTE: the legacy v1 Windows scheduled-task sweep (#956) deliberately runs AFTER the injection
1559
+ // is written to stdout below — a worst-case sweep (probe + lock wait + cleanup ≈ 170s) must never
1560
+ // delay the injection past the host SessionStart hook timeout (see the write-out point below).
1543
1561
  maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
1544
1562
  }
1545
1563
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
@@ -1580,6 +1598,36 @@ export async function runInject(argv, deps = {}) {
1580
1598
  // them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
1581
1599
  if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0)
1582
1600
  process.stdout.write(inj.systemPrompt + '\n');
1601
+ // Legacy v1 Windows scheduled-task sweep (#956): runs AFTER the injection is on stdout so a worst-case
1602
+ // sweep (probe 20s + lock wait 3s + 2×(export 20s + mutation 40s) ≈ 143s) can never push the injection
1603
+ // past the host SessionStart hook timeout and lose it — injection lands first, sweep is trailing.
1604
+ // The owner-lock wait budget is tightened to 3s for the hook path: a held lock almost always means
1605
+ // another evolver process is sweeping right now, and the negative backoff marker covers the retry.
1606
+ // Throttled by a 24h cooldown marker (negative backoff on inconclusive/failed), opt-out via
1607
+ // EVOLVER_SKIP_LEGACY_TASK_PROBE (read AFTER the env-file load so a pointer in the env file is
1608
+ // honored), never throws, and never reports an unprobed host clean.
1609
+ if (fromHookStdin) {
1610
+ try {
1611
+ (deps.legacyTaskSweep ?? (() => {
1612
+ loadEnvFileFromEnv(process.env);
1613
+ const result = maybeCleanupLegacyWindowsDaemonTasks({ env: process.env, lock: { maxTries: 30, waitMs: 100 } });
1614
+ if (result && (result.status === 'cleaned' || result.status === 'failed' || result.status === 'inconclusive')
1615
+ && sessionStartHookVerboseEnabled(process.env)) {
1616
+ const names = result.tasks.filter((task) => task.outcome === 'removed').map((task) => task.name);
1617
+ const suffix = result.status === 'cleaned' && names.length > 0 ? `: removed ${names.join(', ')}` : result.detail ? `: ${result.detail}` : '';
1618
+ process.stderr.write(`[evolver-session-start] legacy v1 scheduled-task cleanup ${result.status}${suffix}\n`);
1619
+ }
1620
+ }))();
1621
+ }
1622
+ catch {
1623
+ if (sessionStartHookVerboseEnabled(process.env)) {
1624
+ // Do not surface raw PowerShell/OS errors here: they may contain lifecycle paths,
1625
+ // usernames, or command arguments. The cleanup module already returns bounded detail
1626
+ // for structured outcomes; an unexpected throw gets a generic diagnostic.
1627
+ process.stderr.write('[evolver-session-start] legacy task sweep failed\n');
1628
+ }
1629
+ }
1630
+ }
1583
1631
  return 0;
1584
1632
  }
1585
1633
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
@@ -1644,6 +1692,9 @@ export function formatDailyReport(report) {
1644
1692
  L.push('Queue');
1645
1693
  L.push(` genes ${q.genesApproved} approved ${q.genesQuarantined} quarantined ${q.genesRejected} rejected`);
1646
1694
  L.push(` anti-gene ${q.antiGeneApproved} approved ${q.antiGeneQuarantined} quarantined ${q.antiGeneUnreviewed} unreviewed`);
1695
+ if (q.genesQuarantined > 0) {
1696
+ L.push(` → ${q.genesQuarantined} gene(s) awaiting review — evolver review --approve <id>`);
1697
+ }
1647
1698
  return `${L.join('\n')}\n`;
1648
1699
  }
1649
1700
  export async function collectDailyReport(deps = {}) {
@@ -1675,37 +1726,53 @@ export async function collectDailyReport(deps = {}) {
1675
1726
  const reviewRecords = review.records();
1676
1727
  const geneReviewCounts = { approved: 0, quarantined: 0, rejected: 0 };
1677
1728
  const antiGeneReviewCounts = { approved: 0, quarantined: 0, unreviewed: 0 };
1678
- // Build asset ID to type mapping
1679
- const allGenes = await store.list('Gene', 10_000);
1680
- const allAntiGenes = await store.list('AntiGene', 10_000);
1681
- const antiGeneIds = new Set(allAntiGenes.map((a) => a.asset_id));
1682
- // Count review records by asset type
1683
- for (const r of reviewRecords) {
1684
- if (antiGeneIds.has(r.assetId)) {
1685
- // AntiGene review record
1686
- if (r.state === 'quarantined')
1687
- antiGeneReviewCounts.quarantined++;
1688
- else if (r.state === 'approved')
1689
- antiGeneReviewCounts.approved++;
1690
- // rejected anti-gene: not shown separately per existing design
1691
- }
1729
+ // LocalJsonlProvider 可读取完整索引;其他 provider 使用有界 list,并对未解析记录回退到 get。
1730
+ const localStore = store instanceof assetstore.LocalJsonlProvider;
1731
+ const allGenes = localStore ? store.listAll('Gene') : await store.list('Gene', 10_000);
1732
+ const allAntiGenes = localStore ? store.listAll('AntiGene') : await store.list('AntiGene', 10_000);
1733
+ const geneIds = new Set(allGenes.map((asset) => asset.asset_id));
1734
+ const antiGeneIds = new Set(allAntiGenes.map((asset) => asset.asset_id));
1735
+ const geneReviewRecords = [];
1736
+ const antiGeneReviewRecords = [];
1737
+ // ReviewLedger 可能保留已删除资产或超出 provider list 窗口的资产;get 是这些记录的类型权威。
1738
+ for (const record of reviewRecords) {
1739
+ let kind;
1740
+ if (geneIds.has(record.assetId))
1741
+ kind = 'Gene';
1742
+ else if (antiGeneIds.has(record.assetId))
1743
+ kind = 'AntiGene';
1692
1744
  else {
1693
- // Gene review record (or unknown asset type)
1694
- if (r.state === 'quarantined')
1695
- geneReviewCounts.quarantined++;
1696
- else if (r.state === 'rejected')
1697
- geneReviewCounts.rejected++;
1698
- else if (r.state === 'approved')
1699
- geneReviewCounts.approved++;
1745
+ const asset = await store.get(record.assetId);
1746
+ kind = asset?.type;
1700
1747
  }
1701
- }
1702
- // Genes without review records are default-approved
1703
- const reviewedIds = new Set(reviewRecords.map((r) => r.assetId));
1704
- const unreviewedGeneCount = allGenes.filter((g) => !reviewedIds.has(g.asset_id)).length;
1748
+ if (kind === 'Gene')
1749
+ geneReviewRecords.push(record);
1750
+ else if (kind === 'AntiGene')
1751
+ antiGeneReviewRecords.push(record);
1752
+ }
1753
+ // Count only review records whose asset still exists and has the matching type.
1754
+ for (const record of geneReviewRecords) {
1755
+ if (record.state === 'quarantined')
1756
+ geneReviewCounts.quarantined++;
1757
+ else if (record.state === 'rejected')
1758
+ geneReviewCounts.rejected++;
1759
+ else if (record.state === 'approved')
1760
+ geneReviewCounts.approved++;
1761
+ }
1762
+ for (const record of antiGeneReviewRecords) {
1763
+ if (record.state === 'quarantined')
1764
+ antiGeneReviewCounts.quarantined++;
1765
+ else if (record.state === 'approved')
1766
+ antiGeneReviewCounts.approved++;
1767
+ }
1768
+ // Gene without a review record remains default-approved.
1769
+ const reviewedGeneIds = new Set(geneReviewRecords.map((record) => record.assetId));
1770
+ const antiGeneReviewById = new Map(antiGeneReviewRecords.map((record) => [record.assetId, record]));
1771
+ const unreviewedGeneCount = allGenes.filter((gene) => !reviewedGeneIds.has(gene.asset_id)).length;
1705
1772
  geneReviewCounts.approved += unreviewedGeneCount;
1706
1773
  // AntiGenes without explicit approval are unreviewed (fail-closed)
1707
1774
  for (const ag of allAntiGenes) {
1708
- const r = review.get(ag.asset_id);
1775
+ const r = antiGeneReviewById.get(ag.asset_id);
1709
1776
  if (!r || (r.state !== 'approved' && r.state !== 'quarantined')) {
1710
1777
  antiGeneReviewCounts.unreviewed++;
1711
1778
  }
@@ -1,6 +1,7 @@
1
1
  import { spawn } from 'node:child_process';
2
2
  import { bootstrap as coreBootstrap, util as coreUtil } from '@evomap/evolver-core';
3
3
  import { type BootstrapTransactionJournal, type BootstrapArtifactIdentity, type LegacyBootstrapMarkerRead } from './lifecycleBootstrapTransaction.js';
4
+ import { type LegacyTaskCleanupResult, type LegacyTaskRun } from './windowsLegacyTaskCleanup.js';
4
5
  export declare function selectExistingPosixCommand(candidates: readonly string[], exists?: (path: string) => boolean): string;
5
6
  export type ServiceTarget = 'launchd' | 'systemd' | 'windows';
6
7
  export interface DaemonCommand {
@@ -59,6 +60,25 @@ interface RunLifecycleDeps {
59
60
  loadUnixRecoveryController?: LoadUnixRecoveryController;
60
61
  removeAutoexecService?: (target: ServiceTarget, dryRun: boolean) => LifecycleResult;
61
62
  bootstrap?: BootstrapServiceDeps;
63
+ /** Test seam for the legacy v1 Windows scheduled-task cleanup subcommand (#956). */
64
+ cleanupLegacyTasks?: (options: {
65
+ env: NodeJS.ProcessEnv;
66
+ stateDir?: string;
67
+ dryRun?: boolean;
68
+ platform?: NodeJS.Platform;
69
+ run?: LegacyTaskRun;
70
+ }) => LegacyTaskCleanupResult;
71
+ /** Test seam for the legacy v1 task preimage restore subcommand (#956). */
72
+ restoreLegacyTaskPreimage?: (preimagePath: string, options: {
73
+ env: NodeJS.ProcessEnv;
74
+ platform?: NodeJS.Platform;
75
+ run?: LegacyTaskRun;
76
+ stateDir?: string;
77
+ }) => {
78
+ status: 'restored' | 'failed';
79
+ task?: string;
80
+ detail: string;
81
+ };
62
82
  stdout?: (text: string) => void;
63
83
  stderr?: (text: string) => void;
64
84
  }
@@ -78,6 +98,8 @@ export interface BootstrapServiceDeps {
78
98
  install?: (target: ServiceTarget, flags: Record<string, string | true>, env: NodeJS.ProcessEnv, argv1: string | undefined, loadUnixRecoveryController?: LoadUnixRecoveryController, options?: InstallServiceOptions) => Promise<LifecycleResult>;
79
99
  writeMarker?: (path: string, marker: coreBootstrap.LifecycleBootstrapMarker) => void;
80
100
  inspectSelfUpdate?: InspectDurableSelfUpdate;
101
+ /** Test seam for the post-activation legacy v1 Windows task sweep (#956). */
102
+ legacyTaskCleanupRun?: LegacyTaskRun;
81
103
  }
82
104
  interface ServiceControlResult {
83
105
  status: number | null;
@@ -180,6 +202,7 @@ interface LegacyWindowsInstallerProof {
180
202
  }
181
203
  declare function parseLegacyWindowsInstallerDefaults(source: string): LegacyWindowsInstallerProof;
182
204
  export declare const _parseLegacyWindowsInstallerDefaultsForTest: typeof parseLegacyWindowsInstallerDefaults;
205
+ export declare function trustedWindowsPowerShell(): string;
183
206
  declare function renderWindowsProxyLauncherBytes(defaults: WindowsInstallerDefaults): Buffer;
184
207
  declare function renderLegacyWindowsProxyLauncherBytes(proof: LegacyWindowsInstallerProof): Buffer;
185
208
  export declare const _renderWindowsProxyLauncherBytesForTest: typeof renderWindowsProxyLauncherBytes;