@evomap/evolver-cli 2.0.0-beta.19 → 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 (68) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +2 -0
  3. package/dist/assetRepair.d.ts +24 -0
  4. package/dist/assetRepair.js +172 -0
  5. package/dist/autoDistillAntiGene.js +7 -5
  6. package/dist/autoDistillLlm.d.ts +20 -0
  7. package/dist/autoDistillLlm.js +77 -15
  8. package/dist/autoexec.d.ts +11 -0
  9. package/dist/autoexec.js +65 -10
  10. package/dist/autoexecConfig.js +2 -1
  11. package/dist/cliContracts.d.ts +10 -0
  12. package/dist/cliContracts.js +407 -81
  13. package/dist/commandCatalog.d.ts +72 -0
  14. package/dist/commandCatalog.js +120 -0
  15. package/dist/cycleConsumer.d.ts +9 -0
  16. package/dist/cycleConsumer.js +14 -3
  17. package/dist/dispatch.d.ts +0 -1
  18. package/dist/dispatch.js +10 -4
  19. package/dist/distillObserver.js +23 -6
  20. package/dist/doctor.d.ts +11 -0
  21. package/dist/doctor.js +81 -6
  22. package/dist/index.d.ts +5 -1
  23. package/dist/index.js +200 -68
  24. package/dist/lifecycle.d.ts +126 -3
  25. package/dist/lifecycle.js +4390 -188
  26. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  27. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  28. package/dist/localMemoryGraph.d.ts +90 -3
  29. package/dist/localMemoryGraph.js +2031 -231
  30. package/dist/materialSnapshot.d.ts +2 -0
  31. package/dist/materialSnapshot.js +8 -0
  32. package/dist/memoryGraphOps.d.ts +8 -0
  33. package/dist/memoryGraphOps.js +140 -0
  34. package/dist/migrate/assetFormatMap.d.ts +61 -0
  35. package/dist/migrate/assetFormatMap.js +53 -0
  36. package/dist/migrate/envTranslate.js +2 -0
  37. package/dist/migrate/fieldMap.d.ts +7 -5
  38. package/dist/migrate/fieldMap.js +20 -14
  39. package/dist/migrate/v1Import.d.ts +80 -1
  40. package/dist/migrate/v1Import.js +961 -120
  41. package/dist/modelCompatibility.d.ts +10 -0
  42. package/dist/modelCompatibility.js +296 -0
  43. package/dist/recipe.d.ts +7 -1
  44. package/dist/recipe.js +113 -11
  45. package/dist/repairedAssetStore.d.ts +2 -0
  46. package/dist/repairedAssetStore.js +12 -0
  47. package/dist/reuse.d.ts +4 -1
  48. package/dist/reuse.js +212 -107
  49. package/dist/reviewFilter.d.ts +3 -1
  50. package/dist/reviewFilter.js +3 -1
  51. package/dist/runtimeSessionSource.d.ts +5 -0
  52. package/dist/selectionPolicyConfig.d.ts +8 -0
  53. package/dist/selectionPolicyConfig.js +18 -0
  54. package/dist/semanticIdfConfig.d.ts +2 -0
  55. package/dist/semanticIdfConfig.js +4 -0
  56. package/dist/sessionIngest.d.ts +7 -1
  57. package/dist/sessionIngest.js +25 -1
  58. package/dist/setupHooks.js +12 -6
  59. package/dist/skill2gep.js +57 -6
  60. package/dist/skillDistill.js +1 -0
  61. package/dist/sync.d.ts +1 -1
  62. package/dist/sync.js +761 -174
  63. package/dist/thesis.js +2 -0
  64. package/dist/valueDigest.js +8 -1
  65. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  66. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  67. package/dist/workflowRuntime.js +7 -6
  68. package/package.json +7 -7
package/dist/index.js CHANGED
@@ -5,17 +5,19 @@ 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';
12
+ import { isSyncCommandName, renderCommandGroups } from './commandCatalog.js';
12
13
  import { parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
13
14
  import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync, mkdirSync, } from 'node:fs';
14
15
  import { homedir } from 'node:os';
15
16
  import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
16
- import { importV1, validateMigrationRoots } from './migrate/v1Import.js';
17
+ import { applyImportV1Plan, planImportV1 } from './migrate/v1Import.js';
17
18
  import { explicitRecipeHomes } from './recipe.js';
18
19
  import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled, dailyConnectionStatus, lifecyclePaths } from './lifecycle.js';
20
+ import { maybeCleanupLegacyWindowsDaemonTasks } from './windowsLegacyTaskCleanup.js';
19
21
  import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
20
22
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
21
23
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
@@ -66,17 +68,7 @@ export function cliUsage() {
66
68
  ' --env-file <path> Environment file',
67
69
  '',
68
70
  'Commands:',
69
- ' Daemon: proxy, lifecycle, proxy-token, doctor, setup-hooks',
70
- ' Evolution: run, cycle, autoexec, solidify, distill, review, thesis',
71
- ' Memory: ingest, inject, recall, reuse, reuse-report, recall-verify-report',
72
- ' narrative, gene-value',
73
- ' Assets: asset-log, asset-trust, asset-health, material, recipe, skill',
74
- ' Hub: login, logout, phub, sync, publish, fetch, buy, orders, verify, atp',
75
- ' Operations: status, daily, workflow status, cycles, trigger, value,',
76
- ' retention, replay, rebuild-views, issue-report',
77
- ' Tools: dashboard, webui, trajectory-export, migrate',
78
- ' Advanced: anti-gene-benchmark, anti-gene-rollout, reset-local-secret',
79
- ' skill-distill, skill-md-update',
71
+ ...renderCommandGroups(),
80
72
  '',
81
73
  'Run evolver <command> --help for command-specific options.',
82
74
  '',
@@ -222,11 +214,34 @@ export function rebuildViews(opts = {}) {
222
214
  replayer.rebuild(ing.readAll());
223
215
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
224
216
  }
217
+ function migrationErrorCode(error) {
218
+ const structured = error;
219
+ const code = typeof structured?.code === 'string' ? structured.code : '';
220
+ if (code === 'LOCAL_ASSET_STORE_SNAPSHOT_CHANGED')
221
+ return 'migration_target_changed';
222
+ if (code === 'FROZEN_ASSET_ID_COLLISION')
223
+ return 'migration_asset_id_collision';
224
+ if (code === 'CORRUPT_LOCAL_ASSET_STORE')
225
+ return 'migration_corrupt_target';
226
+ if (code === 'LOCAL_ASSET_STORE_SNAPSHOT_LIMIT')
227
+ return 'migration_target_limit';
228
+ if (/^[a-z][a-z0-9_]{0,127}$/.test(code))
229
+ return `migration_${code}`;
230
+ const message = typeof structured?.message === 'string' ? structured.message : '';
231
+ return /^[a-z][a-z0-9_]{0,127}$/.test(message) ? message : 'migration_failed';
232
+ }
233
+ function writeMigrationFailure(code, json) {
234
+ process.stderr.write(json
235
+ ? `${JSON.stringify({ ok: false, error: code })}\n`
236
+ : `migrate: ${code}\n`);
237
+ }
225
238
  /** migrate import-v1 | migrate env | migrate oauth — V1→V2 migration tools. */
226
- export async function runMigrate(argv) {
239
+ export async function runMigrate(argv, deps = {}) {
227
240
  const usage = [
228
241
  'Usage:',
229
- ' evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]',
242
+ ' evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>] [--dry-run] [--json]',
243
+ ' evolver migrate gep-sdk <v1dir> [outDir] [--workspace <path>] [--json] # import-v1 --dry-run alias',
244
+ ' evolver migrate --gep-sdk <v1dir> [outDir] [--workspace <path>] [--json]',
230
245
  ' evolver migrate env [--file <dotenv>] [--json] [--write-suggestions <path>] [--no-process-env]',
231
246
  ' evolver migrate oauth [--from <oauth_token.json>] [--to <token.json>] [--force] [--dry-run] [--json]',
232
247
  '',
@@ -243,16 +258,20 @@ export async function runMigrate(argv) {
243
258
  const { runMigrateOAuthCommand } = await import('./migrate/oauthImport.js');
244
259
  return runMigrateOAuthCommand(argv.slice(1));
245
260
  }
246
- if (argv[0] !== 'import-v1' || !argv[1]) {
261
+ const alias = argv[0] === 'gep-sdk' || argv[0] === '--gep-sdk';
262
+ const migrationArgs = alias ? ['import-v1', ...argv.slice(1), '--dry-run'] : [...argv];
263
+ if (migrationArgs[0] !== 'import-v1' || !migrationArgs[1] || migrationArgs[1].startsWith('--')) {
247
264
  process.stderr.write(usage);
248
265
  return 1;
249
266
  }
250
267
  let outDir;
251
268
  let workspace;
252
- for (let index = 2; index < argv.length; index += 1) {
253
- const arg = argv[index] ?? '';
269
+ let dryRun = false;
270
+ let json = false;
271
+ for (let index = 2; index < migrationArgs.length; index += 1) {
272
+ const arg = migrationArgs[index] ?? '';
254
273
  if (arg === '--workspace') {
255
- const value = argv[index + 1];
274
+ const value = migrationArgs[index + 1];
256
275
  if (!value || value.startsWith('--')) {
257
276
  process.stderr.write(usage);
258
277
  return 1;
@@ -267,6 +286,12 @@ export async function runMigrate(argv) {
267
286
  return 1;
268
287
  }
269
288
  }
289
+ else if (arg === '--dry-run') {
290
+ dryRun = true;
291
+ }
292
+ else if (arg === '--json') {
293
+ json = true;
294
+ }
270
295
  else if (arg.startsWith('--') || outDir !== undefined) {
271
296
  process.stderr.write(usage);
272
297
  return 1;
@@ -277,21 +302,57 @@ export async function runMigrate(argv) {
277
302
  }
278
303
  const envFile = loadEnvFileFromEnv(process.env);
279
304
  if (envFile.error) {
280
- process.stderr.write('migrate: failed to load EVOLVER_ENV_FILE\n');
305
+ writeMigrationFailure('migration_env_file_load_failed', json);
281
306
  return 1;
282
307
  }
283
308
  const targetDir = outDir ?? events.evomapHome();
309
+ const options = { ...deps, ...(workspace ? { workspace } : {}) };
310
+ let plan;
284
311
  try {
285
- validateMigrationRoots(argv[1], targetDir);
312
+ plan = await planImportV1(migrationArgs[1], targetDir, options);
286
313
  }
287
314
  catch (error) {
288
- const code = error instanceof Error ? error.message : 'migration_path_rejected';
289
- process.stderr.write(`migrate: ${code}\n`);
315
+ writeMigrationFailure(migrationErrorCode(error), json);
316
+ return 1;
317
+ }
318
+ let successOutput;
319
+ try {
320
+ if (dryRun) {
321
+ if (json) {
322
+ successOutput = `${JSON.stringify({ mode: 'dry-run', plan: plan.report })}\n`;
323
+ }
324
+ else {
325
+ const assets = plan.report.assets;
326
+ successOutput = (`Migration plan ${plan.report.planDigest}: Gene=${assets.Gene.candidates} `
327
+ + `Capsule=${assets.Capsule.candidates} Event=${assets.EvolutionEvent.candidates}; `
328
+ + `verified=${assets.Gene.verified + assets.Capsule.verified + assets.EvolutionEvent.verified} `
329
+ + `unverified=${assets.Gene.unverified + assets.Capsule.unverified + assets.EvolutionEvent.unverified}; `
330
+ + `mailbox=${plan.report.mailbox.candidates}; memory_graph=${plan.report.memoryGraph.disposition}\n`);
331
+ }
332
+ }
333
+ else {
334
+ const report = await applyImportV1Plan(plan, undefined, targetDir, options);
335
+ successOutput = json
336
+ ? `${JSON.stringify({ mode: 'apply', plan: plan.report, result: report })}\n`
337
+ : `迁移完成: Gene=${report.imported.Gene} Capsule=${report.imported.Capsule} Event=${report.imported.EvolutionEvent} (冻结${report.frozen}[其中未验证${report.unverifiedFrozen}]/新算${report.recomputed}/去重${report.deduped}); sidecar=${report.sidecarExtensions}; mailbox 发现=${report.mailboxFound} 导入=${report.mailboxImported}; memory_graph 归档=${report.memoryGraphArchived} 可查询=${report.memoryGraphImported} 延后=${report.memoryGraphDeferred}\n`;
338
+ }
339
+ }
340
+ catch (error) {
341
+ try {
342
+ plan.dispose();
343
+ }
344
+ catch { /* preserve the mapped primary failure */ }
345
+ writeMigrationFailure(migrationErrorCode(error), json);
346
+ return 1;
347
+ }
348
+ try {
349
+ plan.dispose();
350
+ }
351
+ catch {
352
+ writeMigrationFailure('migration_cleanup_failed', json);
290
353
  return 1;
291
354
  }
292
- const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
293
- const rep = await importV1(argv[1], store, targetDir, workspace ? { workspace } : {});
294
- process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; mailbox 发现=${rep.mailboxFound} 导入=${rep.mailboxImported}; memory_graph 归档=${rep.memoryGraphArchived} 可查询=${rep.memoryGraphImported} 延后=${rep.memoryGraphDeferred}\n`);
355
+ process.stdout.write(successOutput);
295
356
  return 0;
296
357
  }
297
358
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -1086,10 +1147,22 @@ export async function runReview(argv, store, review, deps = {}) {
1086
1147
  .map((e) => String(e.payload?.['assetId'] ?? ''))
1087
1148
  .filter(Boolean));
1088
1149
  const autoPending = [...autoDrafted].filter((a) => rev.get(a)?.state === 'quarantined').length;
1089
- 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);
1090
1163
  if (genes.length === 0)
1091
- process.stdout.write('(no genes)\n'); // no early return: the auto-pending footer below is
1092
- 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
1093
1166
  const id = typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id);
1094
1167
  const view = await assetstore.aggregateLearningHistory(s, id);
1095
1168
  const cat = String(g['category'] ?? '?');
@@ -1102,8 +1175,10 @@ export async function runReview(argv, store, review, deps = {}) {
1102
1175
  const promote = state === 'quarantined' ? ` promote:${promoteHint(view)}` : '';
1103
1176
  process.stdout.write(`${id.padEnd(28)} ${cat.padEnd(10)} total=${view.total} succ=${rate} [${reviewStatus(view)}] {${state}}${promote}${auto}\n`);
1104
1177
  }
1178
+ if (manualPending > 0)
1179
+ process.stdout.write(`\n${manualPending} gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
1105
1180
  if (autoPending > 0)
1106
- 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`);
1107
1182
  const antiGenePending = (await listReviewVisibleAntiGenes(s, rev)).filter((asset) => rev.get(String(asset.asset_id))?.state === 'quarantined').length;
1108
1183
  if (antiGenePending > 0)
1109
1184
  process.stdout.write(`\n${antiGenePending} anti-gene(s) awaiting review - inspect with \`evolver review --anti-gene\`\n`);
@@ -1480,6 +1555,9 @@ export async function runInject(argv, deps = {}) {
1480
1555
  process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
1481
1556
  }
1482
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).
1483
1561
  maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
1484
1562
  }
1485
1563
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
@@ -1520,6 +1598,36 @@ export async function runInject(argv, deps = {}) {
1520
1598
  // them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
1521
1599
  if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0)
1522
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
+ }
1523
1631
  return 0;
1524
1632
  }
1525
1633
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
@@ -1584,6 +1692,9 @@ export function formatDailyReport(report) {
1584
1692
  L.push('Queue');
1585
1693
  L.push(` genes ${q.genesApproved} approved ${q.genesQuarantined} quarantined ${q.genesRejected} rejected`);
1586
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
+ }
1587
1698
  return `${L.join('\n')}\n`;
1588
1699
  }
1589
1700
  export async function collectDailyReport(deps = {}) {
@@ -1615,37 +1726,53 @@ export async function collectDailyReport(deps = {}) {
1615
1726
  const reviewRecords = review.records();
1616
1727
  const geneReviewCounts = { approved: 0, quarantined: 0, rejected: 0 };
1617
1728
  const antiGeneReviewCounts = { approved: 0, quarantined: 0, unreviewed: 0 };
1618
- // Build asset ID to type mapping
1619
- const allGenes = await store.list('Gene', 10_000);
1620
- const allAntiGenes = await store.list('AntiGene', 10_000);
1621
- const antiGeneIds = new Set(allAntiGenes.map((a) => a.asset_id));
1622
- // Count review records by asset type
1623
- for (const r of reviewRecords) {
1624
- if (antiGeneIds.has(r.assetId)) {
1625
- // AntiGene review record
1626
- if (r.state === 'quarantined')
1627
- antiGeneReviewCounts.quarantined++;
1628
- else if (r.state === 'approved')
1629
- antiGeneReviewCounts.approved++;
1630
- // rejected anti-gene: not shown separately per existing design
1631
- }
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';
1632
1744
  else {
1633
- // Gene review record (or unknown asset type)
1634
- if (r.state === 'quarantined')
1635
- geneReviewCounts.quarantined++;
1636
- else if (r.state === 'rejected')
1637
- geneReviewCounts.rejected++;
1638
- else if (r.state === 'approved')
1639
- geneReviewCounts.approved++;
1745
+ const asset = await store.get(record.assetId);
1746
+ kind = asset?.type;
1640
1747
  }
1641
- }
1642
- // Genes without review records are default-approved
1643
- const reviewedIds = new Set(reviewRecords.map((r) => r.assetId));
1644
- 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;
1645
1772
  geneReviewCounts.approved += unreviewedGeneCount;
1646
1773
  // AntiGenes without explicit approval are unreviewed (fail-closed)
1647
1774
  for (const ag of allAntiGenes) {
1648
- const r = review.get(ag.asset_id);
1775
+ const r = antiGeneReviewById.get(ag.asset_id);
1649
1776
  if (!r || (r.state !== 'approved' && r.state !== 'quarantined')) {
1650
1777
  antiGeneReviewCounts.unreviewed++;
1651
1778
  }
@@ -1710,6 +1837,21 @@ export function runCli(argv) {
1710
1837
  process.stdout.write(cliUsage());
1711
1838
  return 0;
1712
1839
  }
1840
+ // `cycle` is async-dispatched at the top level, but keep the legacy direct runCli seam for callers that still
1841
+ // invoke `cycle show` through this exported function.
1842
+ if (cmd === 'cycle') {
1843
+ if (argv[1] !== 'show' || !argv[2]) {
1844
+ process.stderr.write('用法: evolver cycle show <id>\n');
1845
+ return 1;
1846
+ }
1847
+ for (const t of showCycle(readEvents(), argv[2]).timeline)
1848
+ process.stdout.write(`#${t.seq} ${t.type} ${t.title}\n`);
1849
+ return 0;
1850
+ }
1851
+ if (!isSyncCommandName(cmd)) {
1852
+ process.stderr.write(`Unknown command: ${cmd}\n\n${cliUsage()}`);
1853
+ return 1;
1854
+ }
1713
1855
  switch (cmd) {
1714
1856
  case 'rebuild-views': {
1715
1857
  const r = rebuildViews();
@@ -1728,15 +1870,6 @@ export function runCli(argv) {
1728
1870
  process.stdout.write(`${c.cycleId} ${c.finalStage} (${c.events} events)\n`);
1729
1871
  return 0;
1730
1872
  }
1731
- case 'cycle': {
1732
- if (argv[1] !== 'show' || !argv[2]) {
1733
- process.stderr.write('用法: evolver cycle show <id>\n');
1734
- return 1;
1735
- }
1736
- for (const t of showCycle(readEvents(), argv[2]).timeline)
1737
- process.stdout.write(`#${t.seq} ${t.type} ${t.title}\n`);
1738
- return 0;
1739
- }
1740
1873
  case 'trigger': {
1741
1874
  for (const t of listTriggers(readEvents()))
1742
1875
  process.stdout.write(`${t.patternId} ${t.triggered ? '触发' : '抑制'} value=${t.value}\n`);
@@ -1755,8 +1888,7 @@ export function runCli(argv) {
1755
1888
  process.stdout.write(`replayed → MV: ${r.rebuilt.join(', ')}\n`);
1756
1889
  return 0;
1757
1890
  }
1758
- default:
1759
- process.stderr.write(`Unknown command: ${cmd}\n\n${cliUsage()}`);
1760
- return 1;
1761
1891
  }
1892
+ const unreachable = cmd;
1893
+ return unreachable;
1762
1894
  }
@@ -1,4 +1,8 @@
1
1
  import { spawn } from 'node:child_process';
2
+ import { bootstrap as coreBootstrap, util as coreUtil } from '@evomap/evolver-core';
3
+ import { type BootstrapTransactionJournal, type BootstrapArtifactIdentity, type LegacyBootstrapMarkerRead } from './lifecycleBootstrapTransaction.js';
4
+ import { type LegacyTaskCleanupResult, type LegacyTaskRun } from './windowsLegacyTaskCleanup.js';
5
+ export declare function selectExistingPosixCommand(candidates: readonly string[], exists?: (path: string) => boolean): string;
2
6
  export type ServiceTarget = 'launchd' | 'systemd' | 'windows';
3
7
  export interface DaemonCommand {
4
8
  command: string;
@@ -24,32 +28,89 @@ export interface LifecycleStatus {
24
28
  healthy?: boolean;
25
29
  reason?: string;
26
30
  logFile?: string;
31
+ startedAt?: string;
32
+ url?: string;
27
33
  }
28
34
  export interface LifecycleResult {
29
35
  status: string;
36
+ /** Durable transaction identity for bootstrap success results. */
37
+ transactionId?: string;
30
38
  pid?: number;
31
39
  pids?: number[];
32
40
  healthy?: boolean;
33
41
  reason?: string;
34
42
  logFile?: string;
35
43
  files?: string[];
44
+ /** Verified legacy companion files intentionally preserved and never removed. */
45
+ preservedFiles?: string[];
36
46
  service?: string;
37
47
  autoexecHome?: string;
38
48
  actions?: string[];
49
+ /** Files whose absent pre-state is owned by a first-run bootstrap transaction. */
50
+ bootstrapArtifacts?: string[];
51
+ /** Expected bytes recorded before a first-run bootstrap mutates the filesystem. */
52
+ bootstrapArtifactIdentities?: Record<string, BootstrapArtifactIdentity>;
39
53
  }
40
- type UnixRecoveryControllerModule = Pick<typeof import('@evomap/evolver-proxy'), 'provisionStableUnixRecoveryController' | 'stableUnixRecoveryControllerPathForTarget' | 'UNIX_RECOVERY_CONTROLLER_ARG'>;
54
+ type UnixRecoveryControllerModule = Pick<typeof import('@evomap/evolver-proxy'), 'provisionStableUnixRecoveryController' | 'stableUnixRecoveryControllerPathForTarget' | 'UNIX_RECOVERY_CONTROLLER_ARG'> & Partial<Pick<typeof import('@evomap/evolver-proxy'), 'provisionStableWindowsRecoveryController'>>;
41
55
  type LoadUnixRecoveryController = () => Promise<UnixRecoveryControllerModule>;
56
+ type InspectDurableSelfUpdate = typeof import('@evomap/evolver-proxy')['inspectDurableSelfUpdate'];
42
57
  interface RunLifecycleDeps {
43
58
  argv1?: string;
44
59
  env?: NodeJS.ProcessEnv;
45
60
  loadUnixRecoveryController?: LoadUnixRecoveryController;
46
61
  removeAutoexecService?: (target: ServiceTarget, dryRun: boolean) => LifecycleResult;
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
+ };
47
82
  stdout?: (text: string) => void;
48
83
  stderr?: (text: string) => void;
49
84
  }
85
+ export interface BootstrapServiceDeps {
86
+ platform?: NodeJS.Platform;
87
+ run?: (command: string, args: readonly string[], timeoutMs?: number) => ServiceControlResult;
88
+ uid?: number;
89
+ now?: () => number;
90
+ lock?: {
91
+ maxTries?: number;
92
+ waitMs?: number;
93
+ };
94
+ health?: (paths: LifecyclePaths, env: NodeJS.ProcessEnv) => Promise<LifecycleStatus>;
95
+ readiness?: (stateDir: string) => coreBootstrap.LifecycleBootstrapReadiness | undefined;
96
+ readinessOwnerProcessStatus?: (owner: Pick<coreUtil.FileLockOwnerRecord, 'pid' | 'processStartIdentity'>) => coreUtil.FileLockOwnerProcessStatus;
97
+ healthTimeoutMs?: number;
98
+ install?: (target: ServiceTarget, flags: Record<string, string | true>, env: NodeJS.ProcessEnv, argv1: string | undefined, loadUnixRecoveryController?: LoadUnixRecoveryController, options?: InstallServiceOptions) => Promise<LifecycleResult>;
99
+ writeMarker?: (path: string, marker: coreBootstrap.LifecycleBootstrapMarker) => void;
100
+ inspectSelfUpdate?: InspectDurableSelfUpdate;
101
+ /** Test seam for the post-activation legacy v1 Windows task sweep (#956). */
102
+ legacyTaskCleanupRun?: LegacyTaskRun;
103
+ }
50
104
  interface ServiceControlResult {
51
105
  status: number | null;
52
106
  error?: unknown;
107
+ stdout?: string;
108
+ }
109
+ interface InstallServiceOptions {
110
+ exclusive?: boolean;
111
+ transactionId?: string;
112
+ onArtifactPublished?: (path: string, claimPath: string) => void;
113
+ assertOwner?: () => void;
53
114
  }
54
115
  export interface RemoveAutoexecServiceDeps {
55
116
  paths?: Partial<Record<ServiceTarget, string>>;
@@ -94,8 +155,10 @@ export declare function renderSystemdUnit(opts?: {
94
155
  envFile?: string;
95
156
  workingDirectory?: string;
96
157
  execStart?: string;
158
+ lifecycleStateDir?: string;
97
159
  selfUpdateStateDir?: string;
98
160
  selfUpdateTarget?: string;
161
+ bootstrapTransactionId?: string;
99
162
  }): string;
100
163
  export declare function renderAutoexecSystemdUnit(opts: {
101
164
  envFile?: string;
@@ -109,11 +172,13 @@ export declare function renderLaunchdPlist(opts?: {
109
172
  proxyBin?: string;
110
173
  programArguments?: readonly string[];
111
174
  logDir?: string;
175
+ lifecycleStateDir?: string;
112
176
  selfUpdateStateDir?: string;
113
177
  selfUpdateTarget?: string;
114
178
  label?: string;
115
179
  logName?: string;
116
180
  selfUpdateSupervisor?: boolean;
181
+ bootstrapTransactionId?: string;
117
182
  }): string;
118
183
  export declare function renderAutoexecLaunchdPlist(opts: {
119
184
  envFile?: string;
@@ -121,13 +186,27 @@ export declare function renderAutoexecLaunchdPlist(opts: {
121
186
  programArguments: readonly string[];
122
187
  logDir?: string;
123
188
  }): string;
124
- export declare function renderWindowsInstaller(defaults?: {
189
+ interface WindowsInstallerDefaults {
125
190
  evolverBin?: string;
126
191
  nodePath?: string;
127
192
  proxyBin?: string;
128
193
  envFile?: string;
194
+ lifecycleStateDir?: string;
129
195
  selfUpdateStateDir?: string;
130
- }): string;
196
+ bootstrapTransactionId?: string;
197
+ wscriptPath?: string;
198
+ }
199
+ interface LegacyWindowsInstallerProof {
200
+ family: 'v907' | 'v918';
201
+ defaults: WindowsInstallerDefaults;
202
+ }
203
+ declare function parseLegacyWindowsInstallerDefaults(source: string): LegacyWindowsInstallerProof;
204
+ export declare const _parseLegacyWindowsInstallerDefaultsForTest: typeof parseLegacyWindowsInstallerDefaults;
205
+ export declare function trustedWindowsPowerShell(): string;
206
+ declare function renderWindowsProxyLauncherBytes(defaults: WindowsInstallerDefaults): Buffer;
207
+ declare function renderLegacyWindowsProxyLauncherBytes(proof: LegacyWindowsInstallerProof): Buffer;
208
+ export declare const _renderWindowsProxyLauncherBytesForTest: typeof renderWindowsProxyLauncherBytes;
209
+ export declare function renderWindowsInstaller(defaults?: WindowsInstallerDefaults): string;
131
210
  export declare function renderWindowsAutoexecInstaller(defaults?: {
132
211
  evolverBin?: string;
133
212
  nodePath?: string;
@@ -135,7 +214,51 @@ export declare function renderWindowsAutoexecInstaller(defaults?: {
135
214
  envFile?: string;
136
215
  autoexecHome?: string;
137
216
  workingDirectory?: string;
217
+ wscriptPath?: string;
138
218
  }): string;
219
+ export declare const _renderLegacyWindowsProxyLauncherBytesForTest: typeof renderLegacyWindowsProxyLauncherBytes;
220
+ declare function renderFrozenLegacySystemdUnit(opts: {
221
+ envFile?: string;
222
+ workingDirectory?: string;
223
+ execStart: string;
224
+ lifecycleStateDir?: string;
225
+ selfUpdateStateDir?: string;
226
+ selfUpdateTarget?: string;
227
+ }): string;
228
+ declare function renderFrozenLegacyLaunchdPlist(opts: {
229
+ envFile?: string;
230
+ workingDirectory: string;
231
+ programArguments: readonly string[];
232
+ logDir: string;
233
+ lifecycleStateDir?: string;
234
+ selfUpdateStateDir?: string;
235
+ selfUpdateTarget?: string;
236
+ }): string;
237
+ export declare const _renderFrozenLegacySystemdUnitForTest: typeof renderFrozenLegacySystemdUnit;
238
+ export declare const _renderFrozenLegacyLaunchdPlistForTest: typeof renderFrozenLegacyLaunchdPlist;
239
+ declare function legacyBootstrapArtifactPlan(legacy: LegacyBootstrapMarkerRead, planned: LifecycleResult, target: ServiceTarget, env: NodeJS.ProcessEnv, stateDir: string, legacyWindowsLauncherPath?: string, allowAbsentWindowsManager?: boolean, requireStateRootProof?: boolean, uid?: number): {
240
+ paths: string[];
241
+ expected: Record<string, BootstrapArtifactIdentity>;
242
+ preserved: coreBootstrap.LifecycleBootstrapMarker['artifacts'];
243
+ legacyStateRootProof?: coreBootstrap.LifecycleBootstrapLegacyStateRootProof;
244
+ };
245
+ export declare const _planLegacyBootstrapArtifactsForTest: typeof legacyBootstrapArtifactPlan;
246
+ declare function windowsTaskProbeCommand(): string;
247
+ export declare const _windowsTaskProbeCommandForTest: typeof windowsTaskProbeCommand;
248
+ declare function probeLegacyWindowsLauncherPath(run: (command: string, args: readonly string[], timeoutMs?: number) => ServiceControlResult, timeoutMs: number, expectedEnabled?: boolean): string;
249
+ export declare const _probeLegacyWindowsLauncherPathForTest: typeof probeLegacyWindowsLauncherPath;
250
+ export declare function validateSystemdBootstrapManagerBinding(journal: Pick<BootstrapTransactionJournal, 'transactionId' | 'managerBinding'>, unit: string, stdout: string, requireRunning?: boolean): number | undefined;
251
+ export declare function validateLaunchdBootstrapManagerBinding(journal: Pick<BootstrapTransactionJournal, 'transactionId' | 'managerBinding'>, plist: string, stdout: string, requireRunning?: boolean): number | undefined;
252
+ interface WindowsBootstrapLauncherBinding {
253
+ mode: 'controller' | 'direct';
254
+ proxyExecutable: string;
255
+ proxyScript?: string;
256
+ controllerExecutable?: string;
257
+ lifecycleStateDir?: string;
258
+ selfUpdateStateDir?: string;
259
+ }
260
+ export declare function parseWindowsBootstrapLauncherBinding(journal: Pick<BootstrapTransactionJournal, 'transactionId' | 'managerBinding' | 'artifacts'>, bytes: Buffer): WindowsBootstrapLauncherBinding;
261
+ export declare function bootstrapReadinessMatchesManager(journal: Pick<BootstrapTransactionJournal, 'target' | 'managerBinding' | 'artifacts'>, readiness: coreBootstrap.LifecycleBootstrapReadiness, managerPid: number | undefined): boolean;
139
262
  export declare function removeAutoexecService(target: ServiceTarget, dryRun: boolean, deps?: RemoveAutoexecServiceDeps): LifecycleResult;
140
263
  export declare function resolveDaemonCommand(env: NodeJS.ProcessEnv, execPath?: string, argv1?: string | undefined): DaemonCommand;
141
264
  export declare function resolveSelfUpdatingExecutable(execPath: string, argv1: string | undefined): DaemonCommand | undefined;