@evomap/evolver-cli 2.0.0-beta.1 → 2.0.0-beta.4

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 (73) hide show
  1. package/dist/antiGeneBenchmark.js +12 -0
  2. package/dist/antiGeneEvidence.d.ts +15 -0
  3. package/dist/antiGeneEvidence.js +49 -0
  4. package/dist/antiGeneRollout.d.ts +3 -1
  5. package/dist/antiGeneRollout.js +16 -2
  6. package/dist/assetHealth.d.ts +6 -0
  7. package/dist/assetHealth.js +105 -0
  8. package/dist/assetSidecarRecovery.d.ts +14 -0
  9. package/dist/assetSidecarRecovery.js +171 -0
  10. package/dist/assetTrust.d.ts +24 -0
  11. package/dist/assetTrust.js +218 -0
  12. package/dist/atp.js +4 -2
  13. package/dist/autoDistillLlm.js +4 -1
  14. package/dist/autoexec.d.ts +13 -3
  15. package/dist/autoexec.js +71 -13
  16. package/dist/cli.js +12 -5
  17. package/dist/cliContracts.js +8 -2
  18. package/dist/cliLifecycle.d.ts +7 -0
  19. package/dist/cliLifecycle.js +9 -0
  20. package/dist/cycleConsumer.d.ts +61 -1
  21. package/dist/cycleConsumer.js +551 -16
  22. package/dist/dashboard.d.ts +23 -0
  23. package/dist/dashboard.js +191 -0
  24. package/dist/dispatch.d.ts +10 -1
  25. package/dist/dispatch.js +36 -2
  26. package/dist/distillObserver.js +2 -2
  27. package/dist/distillPrimitives.d.ts +1 -1
  28. package/dist/distillPrimitives.js +29 -2
  29. package/dist/doctor.d.ts +2 -0
  30. package/dist/doctor.js +33 -3
  31. package/dist/index.d.ts +7 -2
  32. package/dist/index.js +292 -36
  33. package/dist/lifecycle.d.ts +19 -1
  34. package/dist/lifecycle.js +226 -29
  35. package/dist/localMemoryGraph.d.ts +97 -0
  36. package/dist/localMemoryGraph.js +889 -0
  37. package/dist/login.d.ts +20 -4
  38. package/dist/login.js +58 -8
  39. package/dist/materialPackage.d.ts +52 -0
  40. package/dist/materialPackage.js +404 -0
  41. package/dist/materialSnapshot.d.ts +30 -0
  42. package/dist/materialSnapshot.js +148 -0
  43. package/dist/memoryEventMirror.d.ts +23 -0
  44. package/dist/memoryEventMirror.js +140 -0
  45. package/dist/migrate/fieldMap.js +25 -0
  46. package/dist/migrate/v1Import.d.ts +7 -1
  47. package/dist/migrate/v1Import.js +132 -11
  48. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  49. package/dist/nonGitWorkspaceNotice.js +122 -0
  50. package/dist/proxyToken.d.ts +10 -0
  51. package/dist/proxyToken.js +80 -0
  52. package/dist/recipe.d.ts +10 -2
  53. package/dist/recipe.js +349 -7
  54. package/dist/reuseReport.js +16 -16
  55. package/dist/runtimeCapabilities.d.ts +18 -0
  56. package/dist/runtimeCapabilities.js +81 -0
  57. package/dist/runtimeSessionSource.d.ts +10 -0
  58. package/dist/runtimeSessionSource.js +32 -5
  59. package/dist/setupHooks.d.ts +6 -1
  60. package/dist/setupHooks.js +5 -2
  61. package/dist/skill2gep.d.ts +38 -9
  62. package/dist/skill2gep.js +147 -14
  63. package/dist/skillDistill.d.ts +1 -0
  64. package/dist/skillDistill.js +4 -4
  65. package/dist/skillFetch.d.ts +18 -0
  66. package/dist/skillFetch.js +391 -0
  67. package/dist/solo/mode.js +5 -0
  68. package/dist/sync.d.ts +26 -0
  69. package/dist/sync.js +988 -0
  70. package/dist/trajectoryExport.js +23 -12
  71. package/dist/v1Compat.d.ts +24 -0
  72. package/dist/v1Compat.js +249 -0
  73. package/package.json +12 -6
package/dist/index.js CHANGED
@@ -3,18 +3,22 @@ import { readEvents, statusReport, listCycles, showCycle, listTriggers, buildNar
3
3
  import { runGeneValue } from './geneValue.js';
4
4
  import { assetstore, algo, signals, material as materialNs } from '@evomap/evolver-core';
5
5
  import { loadPriceTable } from '@evomap/evolver-adapter-public';
6
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
6
7
  import { makeInjectEmitter } from './autoexec.js';
7
8
  import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
8
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
9
10
  import { draftGeneCandidate } from './distillPrimitives.js';
10
11
  import { emitSessionRecall } from './autoRecall.js';
11
- import { isRuntimeSessionSourcePath, parseRuntimeSessionSources } from './runtimeSessionSource.js';
12
+ import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
12
13
  import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
13
14
  import { homedir } from 'node:os';
14
- import { join, resolve } from 'node:path';
15
+ import { dirname, join, resolve } from 'node:path';
15
16
  import { importV1 } from './migrate/v1Import.js';
16
17
  import { explicitRecipeHomes } from './recipe.js';
17
18
  import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
19
+ import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
20
+ import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
21
+ import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
18
22
  /**
19
23
  * Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
20
24
  * one place so the recorded Material and any future cycle consumer agree on the group name.
@@ -194,16 +198,50 @@ export function rebuildViews(opts = {}) {
194
198
  replayer.rebuild(ing.readAll());
195
199
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
196
200
  }
197
- /** migrate import-v1 <v1dir> [outDir]: v1→v2 只读迁移(异步, 由 cli.ts 调). */
201
+ /** migrate import-v1 <v1dir> [outDir] --workspace <path>: v1→v2 read-only migration. */
198
202
  export async function runMigrate(argv) {
203
+ const usage = '用法: evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]\n';
199
204
  if (argv[0] !== 'import-v1' || !argv[1]) {
200
- process.stderr.write('用法: evolver migrate import-v1 <v1dir> [outDir]\n');
205
+ process.stderr.write(usage);
201
206
  return 1;
202
207
  }
203
- const outDir = argv[2] ?? process.cwd();
204
- const store = new assetstore.LocalJsonlProvider(`${outDir}/assets`);
205
- const rep = await importV1(argv[1], store, outDir);
206
- process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived}\n`);
208
+ let outDir;
209
+ let workspace;
210
+ for (let index = 2; index < argv.length; index += 1) {
211
+ const arg = argv[index] ?? '';
212
+ if (arg === '--workspace') {
213
+ const value = argv[index + 1];
214
+ if (!value || value.startsWith('--')) {
215
+ process.stderr.write(usage);
216
+ return 1;
217
+ }
218
+ workspace = value;
219
+ index += 1;
220
+ }
221
+ else if (arg.startsWith('--workspace=')) {
222
+ workspace = arg.slice('--workspace='.length);
223
+ if (!workspace) {
224
+ process.stderr.write(usage);
225
+ return 1;
226
+ }
227
+ }
228
+ else if (arg.startsWith('--') || outDir !== undefined) {
229
+ process.stderr.write(usage);
230
+ return 1;
231
+ }
232
+ else {
233
+ outDir = arg;
234
+ }
235
+ }
236
+ const envFile = loadEnvFileFromEnv(process.env);
237
+ if (envFile.error) {
238
+ process.stderr.write('migrate: failed to load EVOLVER_ENV_FILE\n');
239
+ return 1;
240
+ }
241
+ const targetDir = outDir ?? events.evomapHome();
242
+ const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
243
+ const rep = await importV1(argv[1], store, targetDir, workspace ? { workspace } : {});
244
+ process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived} 可查询=${rep.memoryGraphImported} 延后=${rep.memoryGraphDeferred}\n`);
207
245
  return 0;
208
246
  }
209
247
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -252,6 +290,9 @@ export async function runDistill(argv, store, deps = {}) {
252
290
  signals_match: splitList(f['signals'], /,/),
253
291
  strategy: splitList(f['strategy'], /[;\n]/),
254
292
  ...(f['summary'] ? { summary: f['summary'] } : {}),
293
+ // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
294
+ // `manual` per V1 #302 classifyProvenance.
295
+ generation_meta: { source: 'manual' },
255
296
  };
256
297
  if (candidate.signals_match.length === 0 || candidate.strategy.length === 0) {
257
298
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
@@ -299,7 +340,7 @@ function printTraceSignals(file, turnCount, sigs) {
299
340
  }
300
341
  }
301
342
  /** The runtime agents Material.sourceAgent can represent (closed enum on the schema). */
302
- const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'kimi', 'kiro', 'opencode', 'generic-chat']);
343
+ const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'antigravity', 'kimi', 'kiro', 'opencode', 'generic-chat']);
303
344
  /** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
304
345
  function toMaterialSourceAgent(agent) {
305
346
  return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
@@ -329,12 +370,12 @@ function materialExistsFor(store, sourcePath, wm) {
329
370
  * no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
330
371
  * Returns whether new material landed + its materialId so the caller can report it.
331
372
  */
332
- async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1) {
373
+ async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1, payload, diagnostics) {
333
374
  const prev = d.watermarkStore.get(absPath);
334
375
  const scan = materialNs.scanFile(absPath, prev);
335
376
  // Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
336
377
  if (prev && !scan.changed)
337
- return { recorded: false };
378
+ return { recorded: false, emitted: false };
338
379
  const m = materialNs.buildMaterial({
339
380
  sourceAgent,
340
381
  sourceKind: 'runtime_session',
@@ -342,22 +383,30 @@ async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recor
342
383
  kind: 'session_log',
343
384
  watermark: scan.watermark,
344
385
  consumerGroup: INGEST_CONSUMER_GROUP,
386
+ ...(payload ? { payload } : {}),
345
387
  });
346
388
  // Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
347
389
  // watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
348
390
  const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
349
391
  if (isNew)
350
392
  await d.materialStore.put(m);
393
+ const parseDiagnostics = diagnostics && diagnostics.invalidJson > 0
394
+ ? { rowsScanned: diagnostics.rowsScanned, rowsRead: diagnostics.rowsRead, invalidJson: diagnostics.invalidJson }
395
+ : undefined;
351
396
  await d.ingestor.ingest({
352
397
  type: 'material.batch_ready',
353
- payload: { source: absPath, recordCount, signalCount },
354
- human: { title: `material 已落地: ${sourceAgent} session`, severity: 'info' },
398
+ payload: { source: absPath, recordCount, signalCount, ...(parseDiagnostics ? { parseDiagnostics } : {}) },
399
+ human: {
400
+ title: `material 已落地: ${sourceAgent} session`,
401
+ ...(parseDiagnostics ? { detail: `skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s)` } : {}),
402
+ severity: 'info',
403
+ },
355
404
  actor: { kind: 'machine' },
356
405
  });
357
406
  // Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
358
407
  // stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
359
408
  d.watermarkStore.set(absPath, scan.watermark);
360
- return { recorded: isNew, materialId: m.materialId };
409
+ return { recorded: isNew, emitted: true, materialId: m.materialId };
361
410
  }
362
411
  /**
363
412
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
@@ -434,18 +483,23 @@ export async function runSessionIngestTick(dirs, deps = {}) {
434
483
  const sourceAgents = new Set();
435
484
  const signalKinds = new Set();
436
485
  const signalStrengths = new Set();
486
+ let invalidJsonRows = 0;
437
487
  // #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
438
488
  // experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
439
489
  // (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
440
490
  const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
441
491
  for (const file of scanSessionDirs(dirs)) {
442
492
  try {
443
- const parsedSources = parseRuntimeSessionSources(file);
493
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(file);
494
+ const parsedSources = parsed.sources;
444
495
  const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
445
496
  if (parsedSources.length === 0 || !agent)
446
497
  continue; // not a recognized, schema-recordable runtime-session source
447
498
  const sigsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
448
- const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length);
499
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
500
+ const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length, snapshot, parsed.diagnostics);
501
+ if (r.emitted)
502
+ invalidJsonRows += parsed.diagnostics.invalidJson;
449
503
  if (r.recorded) {
450
504
  recorded += 1;
451
505
  sourceAgents.add(agent);
@@ -469,6 +523,7 @@ export async function runSessionIngestTick(dirs, deps = {}) {
469
523
  sourceAgents: sortedStrings(sourceAgents),
470
524
  signalKinds: sortedStrings(signalKinds),
471
525
  signalStrengths: sortedStrings(signalStrengths),
526
+ ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
472
527
  };
473
528
  }
474
529
  /**
@@ -566,8 +621,11 @@ export async function runIngest(argv, store, deps = {}, review) {
566
621
  if (TRACE_FILE_RE.test(path))
567
622
  return ingestTraceFiles([resolve(path)], distill, deps);
568
623
  let parsedSources;
624
+ let parseDiagnostics;
569
625
  try {
570
- parsedSources = parseRuntimeSessionSources(path);
626
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
627
+ parsedSources = parsed.sources;
628
+ parseDiagnostics = parsed.diagnostics;
571
629
  }
572
630
  catch (e) {
573
631
  process.stderr.write(`ingest: cannot read ${path}: ${e instanceof Error ? e.message : String(e)}\n`);
@@ -585,6 +643,9 @@ export async function runIngest(argv, store, deps = {}, review) {
585
643
  return 1;
586
644
  }
587
645
  const sourceSignalPairs = parsedSources.map((source) => ({ source, sigs: signals.extractSignals(source.turns) }));
646
+ if (parseDiagnostics && parseDiagnostics.invalidJson > 0) {
647
+ process.stderr.write(`ingest: skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s) in ${path}\n`);
648
+ }
588
649
  for (const { source, sigs } of sourceSignalPairs) {
589
650
  process.stdout.write(`ingest [${source.label}] ${path}: ${source.turns.length} turn(s) → ${sigs.length} signal(s)\n`);
590
651
  for (const s of sigs) {
@@ -600,7 +661,8 @@ export async function runIngest(argv, store, deps = {}, review) {
600
661
  if (sourceAgent) {
601
662
  const d = resolveIngestDeps(deps);
602
663
  const signalCount = sourceSignalPairs.reduce((sum, pair) => sum + pair.sigs.length, 0);
603
- const r = await recordSessionMaterial(sourceAgent, resolve(path), signalCount, d, parsedSources.length);
664
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
665
+ const r = await recordSessionMaterial(sourceAgent, resolve(path), signalCount, d, parsedSources.length, snapshot, parseDiagnostics);
604
666
  if (r.recorded)
605
667
  process.stdout.write(` → recorded as material ${r.materialId} (material.batch_ready)\n`);
606
668
  else
@@ -694,22 +756,22 @@ function stringArrayField(value) {
694
756
  function optionalStringField(value) {
695
757
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
696
758
  }
697
- function countField(value) {
698
- return Array.isArray(value) ? String(value.length) : '0';
699
- }
700
- function numberField(value) {
701
- return typeof value === 'number' && Number.isFinite(value) ? String(value) : '-';
759
+ function antiGeneReviewState(rev, assetId) {
760
+ return rev.get(assetId)?.state ?? 'unreviewed';
702
761
  }
703
762
  function antiGeneReviewLine(asset, rev) {
704
763
  const assetId = String(asset.asset_id);
705
764
  const id = optionalStringField(asset['id']) ?? assetId;
706
- const state = rev.get(assetId)?.state ?? 'approved';
765
+ const state = antiGeneReviewState(rev, assetId);
707
766
  const severity = optionalStringField(asset['severity']) ?? '-';
708
767
  const trigger = stringArrayField(asset['trigger']).slice(0, 6).join(',') || '-';
709
768
  const avoid = stringArrayField(asset['avoid']).slice(0, 2).join(' | ') || '-';
710
- const evidence = `failures=${numberField(asset['failure_count'])} clusters=${countField(asset['source_clusters'])} evidence=${countField(asset['evidence_capsules'])}`;
711
- const next = state === 'quarantined'
712
- ? `next: evolver review --approve ${id} <reason> | evolver review --reject ${id} <reason>`
769
+ const summary = summarizeAntiGeneEvidence(asset);
770
+ const evidence = `${formatAntiGeneEvidenceSummary(summary)} ${formatAntiGeneEvidenceAction(summary, state)}`;
771
+ const next = state === 'quarantined' || state === 'unreviewed'
772
+ ? summary.strength === 'weak'
773
+ ? `next: reject/defer, or override with evolver review --approve ${id} --allow-weak-evidence <reason>`
774
+ : `next: approve after manual guardrail review with evolver review --approve ${id} <reason> | reject with evolver review --reject ${id} <reason>`
713
775
  : state === 'approved'
714
776
  ? 'next: approved guardrail can be injected when signals match'
715
777
  : state === 'rejected'
@@ -745,12 +807,12 @@ async function runAntiGeneReview(store, rev) {
745
807
  process.stdout.write('(no anti-genes)\n');
746
808
  return 0;
747
809
  }
748
- const counts = { approved: 0, quarantined: 0, rejected: 0 };
810
+ const counts = { approved: 0, quarantined: 0, rejected: 0, unreviewed: 0 };
749
811
  for (const asset of antiGenes) {
750
- const state = rev.get(String(asset.asset_id))?.state ?? 'approved';
812
+ const state = antiGeneReviewState(rev, String(asset.asset_id));
751
813
  counts[state] += 1;
752
814
  }
753
- process.stdout.write(`anti-gene review queue: ${antiGenes.length} AntiGene asset(s); approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected}\n`);
815
+ process.stdout.write(`anti-gene review queue: ${antiGenes.length} AntiGene asset(s); approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected} unreviewed=${counts.unreviewed}\n`);
754
816
  for (const asset of antiGenes)
755
817
  process.stdout.write(`${antiGeneReviewLine(asset, rev)}\n`);
756
818
  return 0;
@@ -760,7 +822,7 @@ async function runAntiGeneReview(store, rev) {
760
822
  * gene); `--approve`/`--reject <id>` is the audited human act that lifts an auto-distilled draft out of (or
761
823
  * confirms it out of) quarantine. Approval is what lets a distilled gene's strategy be embedded into a real run
762
824
  * (the gate lives in makeTrustedGeneResolver, #45+review). The id may be a logical id or an asset_id.
763
- * Usage: evolver review [limit] | evolver review --approve <id> [reason…] | evolver review --reject <id> [reason…]
825
+ * Usage: evolver review [limit] | evolver review --approve <id> [--allow-weak-evidence] [reason…] | evolver review --reject <id> [reason…]
764
826
  */
765
827
  export async function runReview(argv, store, review, deps = {}) {
766
828
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
@@ -770,10 +832,12 @@ export async function runReview(argv, store, review, deps = {}) {
770
832
  // Audited approve/reject: resolve the gene (by logical id or asset_id) to its asset_id and record the act.
771
833
  const verb = argv.includes('--approve') ? 'approve' : argv.includes('--reject') ? 'reject' : null;
772
834
  if (verb) {
835
+ const allowWeakEvidence = argv.includes('--allow-weak-evidence');
773
836
  const flagIdx = argv.indexOf(verb === 'approve' ? '--approve' : '--reject');
774
837
  const target = argv[flagIdx + 1];
775
838
  if (!target || target.startsWith('--')) {
776
- process.stderr.write(`用法: evolver review --${verb} <id> [reason…]\n`);
839
+ const approveExtra = verb === 'approve' ? ' [--allow-weak-evidence]' : '';
840
+ process.stderr.write(`用法: evolver review --${verb} <id>${approveExtra} [reason…]\n`);
777
841
  return 1;
778
842
  }
779
843
  // An asset_id resolves directly via store.get, so a reviewable asset past the bounded list() window is still
@@ -794,6 +858,12 @@ export async function runReview(argv, store, review, deps = {}) {
794
858
  const assetId = String(g.asset_id);
795
859
  const geneId = typeof g['id'] === 'string' ? String(g['id']) : assetId;
796
860
  const assetType = g.type;
861
+ const evidence = assetType === 'AntiGene' ? summarizeAntiGeneEvidence(g) : null;
862
+ const explicitlyApproved = rev.isExplicitlyApproved(assetId);
863
+ if (verb === 'approve' && assetType === 'AntiGene' && evidence?.strength === 'weak' && !explicitlyApproved && !allowWeakEvidence) {
864
+ process.stderr.write(`review --approve: AntiGene ${geneId} has weak evidence (${evidence.weakReasons.join('+')}); use --allow-weak-evidence only after manual verification or reject/defer it.\n`);
865
+ return 1;
866
+ }
797
867
  const by = operatorActorId();
798
868
  const reason = argv.slice(flagIdx + 2).filter((a) => !a.startsWith('--')).join(' ') || `${verb}d via CLI`;
799
869
  if (verb === 'approve')
@@ -803,7 +873,21 @@ export async function runReview(argv, store, review, deps = {}) {
803
873
  const { ingestor } = resolveIngestDeps(deps);
804
874
  await ingestor.ingest({
805
875
  type: verb === 'approve' ? 'actor.human.review.approve' : 'actor.human.review.reject',
806
- payload: { geneId, assetId, assetType, reason },
876
+ payload: {
877
+ geneId,
878
+ assetId,
879
+ assetType,
880
+ reason,
881
+ ...(evidence
882
+ ? {
883
+ evidenceQuality: evidence.strength,
884
+ weakReasons: evidence.weakReasons,
885
+ failureCount: evidence.failureCount,
886
+ sourceClusterCount: evidence.sourceClusterCount,
887
+ evidenceCapsuleCount: evidence.evidenceCapsuleCount,
888
+ }
889
+ : {}),
890
+ },
807
891
  human: { title: `${verb} ${assetType} ${geneId}`, severity: 'info' },
808
892
  actor: { kind: 'human', id: by },
809
893
  });
@@ -898,11 +982,177 @@ export function runNarrative(argv, deps = {}) {
898
982
  }
899
983
  return 0;
900
984
  }
985
+ function formatRootEventArchive(result) {
986
+ if (result.mode === 'preview') {
987
+ return `retention archive-root: mode=preview active=${result.activeRecords} keep=${result.keepEvents} wouldArchive=${result.wouldArchive} retained=${result.retainedRecords} archiveId=${result.archiveId ?? '-'}\n`;
988
+ }
989
+ return `retention archive-root: mode=write activeBefore=${result.activeRecordsBefore} keep=${result.keepEvents} archived=${result.archivedRecords} retained=${result.retainedRecords} archiveId=${result.archiveId ?? '-'} reused=${result.reusedSegment}\n`;
990
+ }
991
+ function formatMaterialArchive(result) {
992
+ if (result.mode === 'preview') {
993
+ return `retention archive-material: mode=preview active=${result.activeRecords} archive=${result.archiveRecords} history=${result.historyRecords} keep=${result.keepRecords} minCursor=${result.minCursor} wouldArchive=${result.wouldArchive} retained=${result.retainedRecords} archiveId=${result.archiveId ?? '-'}\n`;
994
+ }
995
+ return `retention archive-material: mode=write activeBefore=${result.activeRecordsBefore} archived=${result.archivedRecords} archive=${result.archiveRecords} history=${result.historyRecords} keep=${result.keepRecords} minCursor=${result.minCursor} retained=${result.retainedRecords} recoveredOverlap=${result.recoveredOverlap} archiveId=${result.archiveId ?? '-'}\n`;
996
+ }
997
+ function archiveFailureCode(error) {
998
+ const code = typeof error === 'object' && error !== null && 'code' in error
999
+ ? String(error.code ?? '')
1000
+ : '';
1001
+ if (code === 'ROOT_EVENT_ARCHIVE_INVALID_LOG')
1002
+ return 'root_event_archive_invalid_log';
1003
+ if (code === 'ROOT_EVENT_ARCHIVE_INVALID_ARCHIVE')
1004
+ return 'root_event_archive_invalid_archive';
1005
+ if (code === 'ROOT_EVENT_HISTORY_GAP')
1006
+ return 'root_event_archive_history_gap';
1007
+ if (code === 'ROOT_EVENT_ARCHIVE_SEGMENT_CONFLICT')
1008
+ return 'root_event_archive_conflict';
1009
+ if (code === 'LOCK_TIMEOUT')
1010
+ return 'root_event_archive_locked';
1011
+ return 'root_event_archive_failed';
1012
+ }
1013
+ function materialArchiveFailureCode(error) {
1014
+ const code = typeof error === 'object' && error !== null && 'code' in error
1015
+ ? String(error.code ?? '')
1016
+ : '';
1017
+ if (code === 'MATERIAL_ARCHIVE_INVALID_LOG')
1018
+ return 'material_archive_invalid_log';
1019
+ if (code === 'MATERIAL_ARCHIVE_INVALID_ARCHIVE')
1020
+ return 'material_archive_invalid_archive';
1021
+ if (code === 'MATERIAL_ARCHIVE_RANGE_INVALID')
1022
+ return 'material_archive_range_invalid';
1023
+ if (code === 'MATERIAL_ARCHIVE_SEGMENT_CONFLICT')
1024
+ return 'material_archive_conflict';
1025
+ if (code === 'MATERIAL_ARCHIVE_CURSOR_INVALID')
1026
+ return 'material_archive_cursor_invalid';
1027
+ if (code === 'LOCK_TIMEOUT')
1028
+ return 'material_archive_locked';
1029
+ return 'material_archive_failed';
1030
+ }
1031
+ function parseRootArchiveArgs(argv) {
1032
+ const parsed = { help: false, json: false, write: false };
1033
+ for (let index = 0; index < argv.length; index += 1) {
1034
+ const arg = argv[index];
1035
+ if (arg === '--help')
1036
+ parsed.help = true;
1037
+ else if (arg === '--json')
1038
+ parsed.json = true;
1039
+ else if (arg === '--write')
1040
+ parsed.write = true;
1041
+ else if (arg === '--keep-events') {
1042
+ const value = argv[index + 1];
1043
+ const keepEvents = parsePositiveInt(value);
1044
+ if (value === undefined || value.startsWith('--') || keepEvents === undefined) {
1045
+ parsed.error = 'invalid_keep_events';
1046
+ return parsed;
1047
+ }
1048
+ parsed.keepEvents = keepEvents;
1049
+ index += 1;
1050
+ }
1051
+ else {
1052
+ parsed.error = 'invalid_arguments';
1053
+ return parsed;
1054
+ }
1055
+ }
1056
+ return parsed;
1057
+ }
1058
+ function runRootEventArchive(argv, deps) {
1059
+ const parsed = parseRootArchiveArgs(argv);
1060
+ if (parsed.help) {
1061
+ process.stdout.write('usage: evolver retention archive-root [--keep-events N] [--write] [--json]\n');
1062
+ return 0;
1063
+ }
1064
+ if (parsed.error !== undefined) {
1065
+ process.stderr.write(`retention archive-root: ${parsed.error}\n`);
1066
+ return 2;
1067
+ }
1068
+ const options = {
1069
+ path: deps.rootEventsPath ?? events.rootEventsPath(),
1070
+ ...(parsed.keepEvents !== undefined ? { keepEvents: parsed.keepEvents } : {}),
1071
+ };
1072
+ try {
1073
+ const result = parsed.write
1074
+ ? events.archiveRootEvents(options)
1075
+ : events.planRootEventArchive(options);
1076
+ if (parsed.json)
1077
+ process.stdout.write(`${JSON.stringify({ ok: true, group: 'retention.archive_root', ...result })}\n`);
1078
+ else
1079
+ process.stdout.write(formatRootEventArchive(result));
1080
+ return 0;
1081
+ }
1082
+ catch (error) {
1083
+ process.stderr.write(`retention archive-root: ${archiveFailureCode(error)}\n`);
1084
+ return 1;
1085
+ }
1086
+ }
1087
+ function parseMaterialArchiveArgs(argv) {
1088
+ const parsed = { help: false, json: false, write: false };
1089
+ for (let index = 0; index < argv.length; index += 1) {
1090
+ const arg = argv[index];
1091
+ if (arg === '--help')
1092
+ parsed.help = true;
1093
+ else if (arg === '--json')
1094
+ parsed.json = true;
1095
+ else if (arg === '--write')
1096
+ parsed.write = true;
1097
+ else if (arg === '--keep-records') {
1098
+ const value = argv[index + 1];
1099
+ const keepRecords = parsePositiveInt(value);
1100
+ if (value === undefined || value.startsWith('--') || keepRecords === undefined) {
1101
+ parsed.error = 'invalid_keep_records';
1102
+ return parsed;
1103
+ }
1104
+ parsed.keepRecords = keepRecords;
1105
+ index += 1;
1106
+ }
1107
+ else {
1108
+ parsed.error = 'invalid_arguments';
1109
+ return parsed;
1110
+ }
1111
+ }
1112
+ return parsed;
1113
+ }
1114
+ function runMaterialArchive(argv, deps) {
1115
+ const parsed = parseMaterialArchiveArgs(argv);
1116
+ if (parsed.help) {
1117
+ process.stdout.write('usage: evolver retention archive-material [--keep-records N] [--write] [--json]\n');
1118
+ return 0;
1119
+ }
1120
+ if (parsed.error !== undefined) {
1121
+ process.stderr.write(`retention archive-material: ${parsed.error}\n`);
1122
+ return 2;
1123
+ }
1124
+ const path = deps.materialStorePath ?? events.materialStorePath();
1125
+ const cursorPaths = deps.materialCursorPaths
1126
+ ?? (deps.materialCursorPath !== undefined
1127
+ ? [deps.materialCursorPath]
1128
+ : [join(dirname(path), 'cycle-consumer.json'), join(dirname(path), 'distill-consumer.json')]);
1129
+ const options = {
1130
+ path,
1131
+ cursorPaths,
1132
+ ...(parsed.keepRecords !== undefined ? { keepRecords: parsed.keepRecords } : {}),
1133
+ };
1134
+ try {
1135
+ const result = parsed.write
1136
+ ? materialNs.archiveMaterialStore(options)
1137
+ : materialNs.planMaterialArchive(options);
1138
+ if (parsed.json) {
1139
+ process.stdout.write(`${JSON.stringify({ ok: true, group: 'retention.archive_material', ...result })}\n`);
1140
+ }
1141
+ else {
1142
+ process.stdout.write(formatMaterialArchive(result));
1143
+ }
1144
+ return 0;
1145
+ }
1146
+ catch (error) {
1147
+ process.stderr.write(`retention archive-material: ${materialArchiveFailureCode(error)}\n`);
1148
+ return 1;
1149
+ }
1150
+ }
901
1151
  export function formatRetentionReport(report) {
902
1152
  const lines = [
903
1153
  `retention: mode=${report.mode} prune=${report.destructivePruneSupported ? 'enabled' : 'disabled'} generatedAt=${report.generatedAt}`,
904
- ` root_events: state=${report.rootEvents.state} records=${report.rootEvents.records} bytes=${report.rootEvents.bytes} invalid=${report.rootEvents.invalidLines} firstSeq=${report.rootEvents.firstSeq ?? '-'} lastSeq=${report.rootEvents.lastSeq ?? '-'} protectTail=${report.rootEvents.protectTailEvents}`,
905
- ` material: state=${report.material.state} records=${report.material.records} bytes=${report.material.bytes} invalid=${report.material.invalidLines} cursor=${report.material.cursor} effectiveCursor=${report.material.effectiveCursor} cursorValid=${report.material.cursorValid} cursorInRange=${report.material.cursorInRange} consumedPrefix=${report.material.consumedPrefix} pending=${report.material.pending}`,
1154
+ ` root_events: state=${report.rootEvents.state} records=${report.rootEvents.records} bytes=${report.rootEvents.bytes} invalid=${report.rootEvents.invalidLines} archiveSegments=${report.rootEvents.archiveSegments} archiveRecords=${report.rootEvents.archiveRecords} archiveBytes=${report.rootEvents.archiveBytes} archiveInvalid=${report.rootEvents.archiveInvalidLines} historyRecords=${report.rootEvents.historyRecords} historyConflicts=${report.rootEvents.historyConflicts} historyGaps=${report.rootEvents.historyGaps} historyIntegrityErrors=${report.rootEvents.historyIntegrityErrors} firstSeq=${report.rootEvents.firstSeq ?? '-'} lastSeq=${report.rootEvents.lastSeq ?? '-'} protectTail=${report.rootEvents.protectTailEvents}`,
1155
+ ` material: state=${report.material.state} records=${report.material.records} bytes=${report.material.bytes} invalid=${report.material.invalidLines} archiveSegments=${report.material.archiveSegments} archiveRecords=${report.material.archiveRecords} archiveBytes=${report.material.archiveBytes} archiveInvalid=${report.material.archiveInvalidLines} historyRecords=${report.material.historyRecords} cursorCount=${report.material.cursorCount} minCursor=${report.material.minCursor} cursor=${report.material.cursor} effectiveCursor=${report.material.effectiveCursor} cursorValid=${report.material.cursorValid} cursorInRange=${report.material.cursorInRange} consumedPrefix=${report.material.consumedPrefix} pending=${report.material.pending} archiveSafe=${report.material.archiveRotationSafe}`,
906
1156
  ];
907
1157
  if (report.warnings.length > 0) {
908
1158
  lines.push(' warnings:');
@@ -918,11 +1168,16 @@ export function formatRetentionReport(report) {
918
1168
  return `${lines.join('\n')}\n`;
919
1169
  }
920
1170
  export function runRetention(argv, deps = {}) {
1171
+ if (argv[0] === 'archive-root')
1172
+ return runRootEventArchive(argv.slice(1), deps);
1173
+ if (argv[0] === 'archive-material')
1174
+ return runMaterialArchive(argv.slice(1), deps);
921
1175
  const f = parseFlags(argv);
922
1176
  const report = buildRetentionReport({
923
1177
  rootEventsPath: deps.rootEventsPath,
924
1178
  materialStorePath: deps.materialStorePath,
925
1179
  materialCursorPath: deps.materialCursorPath,
1180
+ materialCursorPaths: deps.materialCursorPaths,
926
1181
  now: deps.now,
927
1182
  maxRootEvents: parsePositiveInt(f['max-root-events']),
928
1183
  maxRootBytes: parsePositiveInt(f['max-root-bytes']),
@@ -1038,6 +1293,7 @@ export async function runInject(argv, deps = {}) {
1038
1293
  process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
1039
1294
  }
1040
1295
  }
1296
+ maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
1041
1297
  }
1042
1298
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
1043
1299
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: deps.eventsPath ?? events.rootEventsPath() });
@@ -1129,7 +1385,7 @@ export function runCli(argv) {
1129
1385
  return 0;
1130
1386
  }
1131
1387
  default:
1132
- process.stderr.write('用法: evolver [--version|-v] <status|cycles|cycle show <id>|cycle status [--json]|cycle recover [--limit N] [--json]|trigger|value [--window 7d|30d|all]|narrative [--limit N] [--json]|retention [--json]|trajectory-export [--input <trace-file-or-dir>] [--output <jsonl>]|gene-value [--gene <id>] [--json]|inject session-start|lifecycle <start|stop|restart|status|check|watch|install-service>|phub <init|doctor|status>|replay|rebuild-views|reset-local-secret|asset-log [kind] [limit]|distill ...|review [limit]|recipe build|reuse ...|publish ...|skill-distill --skill <path> [--execution <json|@file>]|skill-md-update --gene <id> --skill <path> [--dry-run]|autoexec [home]|setup-hooks [--runtime] [--root] [--uninstall]|buy|orders|verify|atp|recall <transcript> (--gene <id> ...|--from-inject)>\n');
1388
+ process.stderr.write('用法: evolver [--version|-v] <status|cycles|cycle capabilities [--json]|cycle show <id>|cycle status [--json]|cycle recover [--limit N] [--json]|cycle watch --repo <path> [--state-file <path>] [--validation-cmd <cmd>] [--json]|trigger|value [--window 7d|30d|all]|narrative [--limit N] [--json]|retention [--json]|retention archive-root [--keep-events N] [--write] [--json]|retention archive-material [--keep-records N] [--write] [--json]|dashboard [--port N] [--no-open]|webui [--port N] [--no-open]|trajectory-export [--input <trace-file-or-dir>] [--output <jsonl>]|gene-value [--gene <id>] [--json]|login|logout|proxy|proxy-token [--settings <file>]|inject session-start|lifecycle <start|stop|restart|status|check|watch|install-service>|phub <init|doctor|status>|replay|rebuild-views|reset-local-secret|asset-log [kind] [limit]|asset-trust <list|show|promote|revoke>|asset-health [--json]|asset-health repair-sidecar --sidecar <kind> --replacement <file> [--write --acknowledge-corrupt-history] [--json]|distill ...|review [limit|--approve <id> [--allow-weak-evidence]|--reject <id>]|recipe build|from-skills|reuse ...|publish ...|sync [--write] [--force] [--scope all|purchased|published] [--export <file.gepx>|--import <file.gepx>] [--json]|material package-gene --material <id> [--write] [--json]|skill fetch ...|fetch (--skill <id>|-s <id>|<id>) [--out <dir>] [--force] [--json]|skill-distill --skill <path> [--execution <json|@file>]|skill-md-update --gene <id> --skill <path> [--dry-run]|autoexec [home]|run [-v|--verbose] [--loop|--mad-dog] [--json]|solidify [--dry-run] [--json]|setup-hooks [--runtime] [--root] [--uninstall]|buy|orders|verify|atp|recall <transcript> (--gene <id> ...|--from-inject)>\n');
1133
1389
  return cmd === undefined ? 0 : 1;
1134
1390
  }
1135
1391
  }
@@ -1,4 +1,9 @@
1
1
  import { spawn } from 'node:child_process';
2
+ export interface DaemonCommand {
3
+ command: string;
4
+ args: string[];
5
+ display: string;
6
+ }
2
7
  interface ProcessIdentity {
3
8
  executable?: string;
4
9
  parentPid?: number;
@@ -59,15 +64,28 @@ export declare function renderSystemdUnit(opts?: {
59
64
  envFile?: string;
60
65
  workingDirectory?: string;
61
66
  execStart?: string;
67
+ selfUpdateStateDir?: string;
68
+ selfUpdateTarget?: string;
62
69
  }): string;
63
70
  export declare function renderLaunchdPlist(opts?: {
64
71
  envFile?: string;
65
72
  workingDirectory?: string;
66
73
  nodePath?: string;
67
74
  proxyBin?: string;
75
+ programArguments?: readonly string[];
68
76
  logDir?: string;
77
+ selfUpdateStateDir?: string;
78
+ selfUpdateTarget?: string;
79
+ }): string;
80
+ export declare function renderWindowsInstaller(defaults?: {
81
+ evolverBin?: string;
82
+ nodePath?: string;
83
+ proxyBin?: string;
84
+ envFile?: string;
85
+ selfUpdateStateDir?: string;
69
86
  }): string;
70
- export declare function renderWindowsInstaller(): string;
87
+ export declare function resolveDaemonCommand(env: NodeJS.ProcessEnv, execPath?: string, argv1?: string | undefined): DaemonCommand;
88
+ export declare function resolveSelfUpdatingExecutable(execPath: string, argv1: string | undefined): DaemonCommand | undefined;
71
89
  export declare function resolveProxyBinPath(): string | undefined;
72
90
  export declare function resolveStableNodePath(): string;
73
91
  export declare function sessionStartHookVerboseEnabled(env?: NodeJS.ProcessEnv): boolean;