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

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 (60) 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/atp.js +4 -2
  7. package/dist/autoDistillLlm.js +4 -1
  8. package/dist/autoexec.d.ts +4 -1
  9. package/dist/autoexec.js +23 -5
  10. package/dist/cli.js +12 -5
  11. package/dist/cliContracts.js +8 -2
  12. package/dist/cliLifecycle.d.ts +7 -0
  13. package/dist/cliLifecycle.js +9 -0
  14. package/dist/cycleConsumer.d.ts +59 -1
  15. package/dist/cycleConsumer.js +382 -5
  16. package/dist/dashboard.d.ts +21 -0
  17. package/dist/dashboard.js +173 -0
  18. package/dist/dispatch.d.ts +1 -0
  19. package/dist/dispatch.js +27 -2
  20. package/dist/distillObserver.js +2 -2
  21. package/dist/distillPrimitives.d.ts +1 -1
  22. package/dist/distillPrimitives.js +29 -2
  23. package/dist/doctor.js +15 -3
  24. package/dist/index.d.ts +6 -1
  25. package/dist/index.js +251 -30
  26. package/dist/lifecycle.js +6 -2
  27. package/dist/login.d.ts +20 -4
  28. package/dist/login.js +58 -8
  29. package/dist/materialPackage.d.ts +52 -0
  30. package/dist/materialPackage.js +404 -0
  31. package/dist/materialSnapshot.d.ts +30 -0
  32. package/dist/materialSnapshot.js +148 -0
  33. package/dist/memoryEventMirror.d.ts +23 -0
  34. package/dist/memoryEventMirror.js +140 -0
  35. package/dist/migrate/fieldMap.js +25 -0
  36. package/dist/nonGitWorkspaceNotice.d.ts +24 -0
  37. package/dist/nonGitWorkspaceNotice.js +122 -0
  38. package/dist/proxyToken.d.ts +10 -0
  39. package/dist/proxyToken.js +80 -0
  40. package/dist/recipe.d.ts +10 -2
  41. package/dist/recipe.js +349 -7
  42. package/dist/reuseReport.js +16 -16
  43. package/dist/runtimeSessionSource.d.ts +10 -0
  44. package/dist/runtimeSessionSource.js +32 -5
  45. package/dist/setupHooks.d.ts +6 -1
  46. package/dist/setupHooks.js +5 -2
  47. package/dist/skill2gep.d.ts +38 -9
  48. package/dist/skill2gep.js +147 -14
  49. package/dist/skillDistill.d.ts +1 -0
  50. package/dist/skillDistill.js +4 -4
  51. package/dist/skillFetch.d.ts +18 -0
  52. package/dist/skillFetch.js +391 -0
  53. package/dist/solo/mode.js +5 -0
  54. package/dist/sync.d.ts +26 -0
  55. package/dist/sync.js +988 -0
  56. package/dist/trajectoryExport.js +23 -12
  57. package/dist/v1Compat.d.ts +24 -0
  58. package/dist/v1Compat.js +249 -0
  59. package/dist/version.js +2 -0
  60. package/package.json +8 -6
package/dist/index.js CHANGED
@@ -8,13 +8,16 @@ import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from
8
8
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
9
9
  import { draftGeneCandidate } from './distillPrimitives.js';
10
10
  import { emitSessionRecall } from './autoRecall.js';
11
- import { isRuntimeSessionSourcePath, parseRuntimeSessionSources } from './runtimeSessionSource.js';
11
+ import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
12
12
  import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
13
13
  import { homedir } from 'node:os';
14
- import { join, resolve } from 'node:path';
14
+ import { dirname, join, resolve } from 'node:path';
15
15
  import { importV1 } from './migrate/v1Import.js';
16
16
  import { explicitRecipeHomes } from './recipe.js';
17
17
  import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
18
+ import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
19
+ import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
20
+ import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
18
21
  /**
19
22
  * Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
20
23
  * one place so the recorded Material and any future cycle consumer agree on the group name.
@@ -252,6 +255,9 @@ export async function runDistill(argv, store, deps = {}) {
252
255
  signals_match: splitList(f['signals'], /,/),
253
256
  strategy: splitList(f['strategy'], /[;\n]/),
254
257
  ...(f['summary'] ? { summary: f['summary'] } : {}),
258
+ // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
259
+ // `manual` per V1 #302 classifyProvenance.
260
+ generation_meta: { source: 'manual' },
255
261
  };
256
262
  if (candidate.signals_match.length === 0 || candidate.strategy.length === 0) {
257
263
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
@@ -299,7 +305,7 @@ function printTraceSignals(file, turnCount, sigs) {
299
305
  }
300
306
  }
301
307
  /** 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']);
308
+ const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'antigravity', 'kimi', 'kiro', 'opencode', 'generic-chat']);
303
309
  /** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
304
310
  function toMaterialSourceAgent(agent) {
305
311
  return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
@@ -329,12 +335,12 @@ function materialExistsFor(store, sourcePath, wm) {
329
335
  * no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
330
336
  * Returns whether new material landed + its materialId so the caller can report it.
331
337
  */
332
- async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1) {
338
+ async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1, payload, diagnostics) {
333
339
  const prev = d.watermarkStore.get(absPath);
334
340
  const scan = materialNs.scanFile(absPath, prev);
335
341
  // Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
336
342
  if (prev && !scan.changed)
337
- return { recorded: false };
343
+ return { recorded: false, emitted: false };
338
344
  const m = materialNs.buildMaterial({
339
345
  sourceAgent,
340
346
  sourceKind: 'runtime_session',
@@ -342,22 +348,30 @@ async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recor
342
348
  kind: 'session_log',
343
349
  watermark: scan.watermark,
344
350
  consumerGroup: INGEST_CONSUMER_GROUP,
351
+ ...(payload ? { payload } : {}),
345
352
  });
346
353
  // Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
347
354
  // watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
348
355
  const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
349
356
  if (isNew)
350
357
  await d.materialStore.put(m);
358
+ const parseDiagnostics = diagnostics && diagnostics.invalidJson > 0
359
+ ? { rowsScanned: diagnostics.rowsScanned, rowsRead: diagnostics.rowsRead, invalidJson: diagnostics.invalidJson }
360
+ : undefined;
351
361
  await d.ingestor.ingest({
352
362
  type: 'material.batch_ready',
353
- payload: { source: absPath, recordCount, signalCount },
354
- human: { title: `material 已落地: ${sourceAgent} session`, severity: 'info' },
363
+ payload: { source: absPath, recordCount, signalCount, ...(parseDiagnostics ? { parseDiagnostics } : {}) },
364
+ human: {
365
+ title: `material 已落地: ${sourceAgent} session`,
366
+ ...(parseDiagnostics ? { detail: `skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s)` } : {}),
367
+ severity: 'info',
368
+ },
355
369
  actor: { kind: 'machine' },
356
370
  });
357
371
  // Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
358
372
  // stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
359
373
  d.watermarkStore.set(absPath, scan.watermark);
360
- return { recorded: isNew, materialId: m.materialId };
374
+ return { recorded: isNew, emitted: true, materialId: m.materialId };
361
375
  }
362
376
  /**
363
377
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
@@ -434,18 +448,23 @@ export async function runSessionIngestTick(dirs, deps = {}) {
434
448
  const sourceAgents = new Set();
435
449
  const signalKinds = new Set();
436
450
  const signalStrengths = new Set();
451
+ let invalidJsonRows = 0;
437
452
  // #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
438
453
  // experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
439
454
  // (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
440
455
  const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
441
456
  for (const file of scanSessionDirs(dirs)) {
442
457
  try {
443
- const parsedSources = parseRuntimeSessionSources(file);
458
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(file);
459
+ const parsedSources = parsed.sources;
444
460
  const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
445
461
  if (parsedSources.length === 0 || !agent)
446
462
  continue; // not a recognized, schema-recordable runtime-session source
447
463
  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);
464
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
465
+ const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length, snapshot, parsed.diagnostics);
466
+ if (r.emitted)
467
+ invalidJsonRows += parsed.diagnostics.invalidJson;
449
468
  if (r.recorded) {
450
469
  recorded += 1;
451
470
  sourceAgents.add(agent);
@@ -469,6 +488,7 @@ export async function runSessionIngestTick(dirs, deps = {}) {
469
488
  sourceAgents: sortedStrings(sourceAgents),
470
489
  signalKinds: sortedStrings(signalKinds),
471
490
  signalStrengths: sortedStrings(signalStrengths),
491
+ ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
472
492
  };
473
493
  }
474
494
  /**
@@ -566,8 +586,11 @@ export async function runIngest(argv, store, deps = {}, review) {
566
586
  if (TRACE_FILE_RE.test(path))
567
587
  return ingestTraceFiles([resolve(path)], distill, deps);
568
588
  let parsedSources;
589
+ let parseDiagnostics;
569
590
  try {
570
- parsedSources = parseRuntimeSessionSources(path);
591
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
592
+ parsedSources = parsed.sources;
593
+ parseDiagnostics = parsed.diagnostics;
571
594
  }
572
595
  catch (e) {
573
596
  process.stderr.write(`ingest: cannot read ${path}: ${e instanceof Error ? e.message : String(e)}\n`);
@@ -585,6 +608,9 @@ export async function runIngest(argv, store, deps = {}, review) {
585
608
  return 1;
586
609
  }
587
610
  const sourceSignalPairs = parsedSources.map((source) => ({ source, sigs: signals.extractSignals(source.turns) }));
611
+ if (parseDiagnostics && parseDiagnostics.invalidJson > 0) {
612
+ process.stderr.write(`ingest: skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s) in ${path}\n`);
613
+ }
588
614
  for (const { source, sigs } of sourceSignalPairs) {
589
615
  process.stdout.write(`ingest [${source.label}] ${path}: ${source.turns.length} turn(s) → ${sigs.length} signal(s)\n`);
590
616
  for (const s of sigs) {
@@ -600,7 +626,8 @@ export async function runIngest(argv, store, deps = {}, review) {
600
626
  if (sourceAgent) {
601
627
  const d = resolveIngestDeps(deps);
602
628
  const signalCount = sourceSignalPairs.reduce((sum, pair) => sum + pair.sigs.length, 0);
603
- const r = await recordSessionMaterial(sourceAgent, resolve(path), signalCount, d, parsedSources.length);
629
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
630
+ const r = await recordSessionMaterial(sourceAgent, resolve(path), signalCount, d, parsedSources.length, snapshot, parseDiagnostics);
604
631
  if (r.recorded)
605
632
  process.stdout.write(` → recorded as material ${r.materialId} (material.batch_ready)\n`);
606
633
  else
@@ -694,22 +721,22 @@ function stringArrayField(value) {
694
721
  function optionalStringField(value) {
695
722
  return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
696
723
  }
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) : '-';
724
+ function antiGeneReviewState(rev, assetId) {
725
+ return rev.get(assetId)?.state ?? 'unreviewed';
702
726
  }
703
727
  function antiGeneReviewLine(asset, rev) {
704
728
  const assetId = String(asset.asset_id);
705
729
  const id = optionalStringField(asset['id']) ?? assetId;
706
- const state = rev.get(assetId)?.state ?? 'approved';
730
+ const state = antiGeneReviewState(rev, assetId);
707
731
  const severity = optionalStringField(asset['severity']) ?? '-';
708
732
  const trigger = stringArrayField(asset['trigger']).slice(0, 6).join(',') || '-';
709
733
  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>`
734
+ const summary = summarizeAntiGeneEvidence(asset);
735
+ const evidence = `${formatAntiGeneEvidenceSummary(summary)} ${formatAntiGeneEvidenceAction(summary, state)}`;
736
+ const next = state === 'quarantined' || state === 'unreviewed'
737
+ ? summary.strength === 'weak'
738
+ ? `next: reject/defer, or override with evolver review --approve ${id} --allow-weak-evidence <reason>`
739
+ : `next: approve after manual guardrail review with evolver review --approve ${id} <reason> | reject with evolver review --reject ${id} <reason>`
713
740
  : state === 'approved'
714
741
  ? 'next: approved guardrail can be injected when signals match'
715
742
  : state === 'rejected'
@@ -745,12 +772,12 @@ async function runAntiGeneReview(store, rev) {
745
772
  process.stdout.write('(no anti-genes)\n');
746
773
  return 0;
747
774
  }
748
- const counts = { approved: 0, quarantined: 0, rejected: 0 };
775
+ const counts = { approved: 0, quarantined: 0, rejected: 0, unreviewed: 0 };
749
776
  for (const asset of antiGenes) {
750
- const state = rev.get(String(asset.asset_id))?.state ?? 'approved';
777
+ const state = antiGeneReviewState(rev, String(asset.asset_id));
751
778
  counts[state] += 1;
752
779
  }
753
- process.stdout.write(`anti-gene review queue: ${antiGenes.length} AntiGene asset(s); approved=${counts.approved} quarantined=${counts.quarantined} rejected=${counts.rejected}\n`);
780
+ 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
781
  for (const asset of antiGenes)
755
782
  process.stdout.write(`${antiGeneReviewLine(asset, rev)}\n`);
756
783
  return 0;
@@ -760,7 +787,7 @@ async function runAntiGeneReview(store, rev) {
760
787
  * gene); `--approve`/`--reject <id>` is the audited human act that lifts an auto-distilled draft out of (or
761
788
  * confirms it out of) quarantine. Approval is what lets a distilled gene's strategy be embedded into a real run
762
789
  * (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…]
790
+ * Usage: evolver review [limit] | evolver review --approve <id> [--allow-weak-evidence] [reason…] | evolver review --reject <id> [reason…]
764
791
  */
765
792
  export async function runReview(argv, store, review, deps = {}) {
766
793
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
@@ -770,10 +797,12 @@ export async function runReview(argv, store, review, deps = {}) {
770
797
  // Audited approve/reject: resolve the gene (by logical id or asset_id) to its asset_id and record the act.
771
798
  const verb = argv.includes('--approve') ? 'approve' : argv.includes('--reject') ? 'reject' : null;
772
799
  if (verb) {
800
+ const allowWeakEvidence = argv.includes('--allow-weak-evidence');
773
801
  const flagIdx = argv.indexOf(verb === 'approve' ? '--approve' : '--reject');
774
802
  const target = argv[flagIdx + 1];
775
803
  if (!target || target.startsWith('--')) {
776
- process.stderr.write(`用法: evolver review --${verb} <id> [reason…]\n`);
804
+ const approveExtra = verb === 'approve' ? ' [--allow-weak-evidence]' : '';
805
+ process.stderr.write(`用法: evolver review --${verb} <id>${approveExtra} [reason…]\n`);
777
806
  return 1;
778
807
  }
779
808
  // An asset_id resolves directly via store.get, so a reviewable asset past the bounded list() window is still
@@ -794,6 +823,12 @@ export async function runReview(argv, store, review, deps = {}) {
794
823
  const assetId = String(g.asset_id);
795
824
  const geneId = typeof g['id'] === 'string' ? String(g['id']) : assetId;
796
825
  const assetType = g.type;
826
+ const evidence = assetType === 'AntiGene' ? summarizeAntiGeneEvidence(g) : null;
827
+ const explicitlyApproved = rev.isExplicitlyApproved(assetId);
828
+ if (verb === 'approve' && assetType === 'AntiGene' && evidence?.strength === 'weak' && !explicitlyApproved && !allowWeakEvidence) {
829
+ 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`);
830
+ return 1;
831
+ }
797
832
  const by = operatorActorId();
798
833
  const reason = argv.slice(flagIdx + 2).filter((a) => !a.startsWith('--')).join(' ') || `${verb}d via CLI`;
799
834
  if (verb === 'approve')
@@ -803,7 +838,21 @@ export async function runReview(argv, store, review, deps = {}) {
803
838
  const { ingestor } = resolveIngestDeps(deps);
804
839
  await ingestor.ingest({
805
840
  type: verb === 'approve' ? 'actor.human.review.approve' : 'actor.human.review.reject',
806
- payload: { geneId, assetId, assetType, reason },
841
+ payload: {
842
+ geneId,
843
+ assetId,
844
+ assetType,
845
+ reason,
846
+ ...(evidence
847
+ ? {
848
+ evidenceQuality: evidence.strength,
849
+ weakReasons: evidence.weakReasons,
850
+ failureCount: evidence.failureCount,
851
+ sourceClusterCount: evidence.sourceClusterCount,
852
+ evidenceCapsuleCount: evidence.evidenceCapsuleCount,
853
+ }
854
+ : {}),
855
+ },
807
856
  human: { title: `${verb} ${assetType} ${geneId}`, severity: 'info' },
808
857
  actor: { kind: 'human', id: by },
809
858
  });
@@ -898,11 +947,177 @@ export function runNarrative(argv, deps = {}) {
898
947
  }
899
948
  return 0;
900
949
  }
950
+ function formatRootEventArchive(result) {
951
+ if (result.mode === 'preview') {
952
+ return `retention archive-root: mode=preview active=${result.activeRecords} keep=${result.keepEvents} wouldArchive=${result.wouldArchive} retained=${result.retainedRecords} archiveId=${result.archiveId ?? '-'}\n`;
953
+ }
954
+ 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`;
955
+ }
956
+ function formatMaterialArchive(result) {
957
+ if (result.mode === 'preview') {
958
+ 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`;
959
+ }
960
+ 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`;
961
+ }
962
+ function archiveFailureCode(error) {
963
+ const code = typeof error === 'object' && error !== null && 'code' in error
964
+ ? String(error.code ?? '')
965
+ : '';
966
+ if (code === 'ROOT_EVENT_ARCHIVE_INVALID_LOG')
967
+ return 'root_event_archive_invalid_log';
968
+ if (code === 'ROOT_EVENT_ARCHIVE_INVALID_ARCHIVE')
969
+ return 'root_event_archive_invalid_archive';
970
+ if (code === 'ROOT_EVENT_HISTORY_GAP')
971
+ return 'root_event_archive_history_gap';
972
+ if (code === 'ROOT_EVENT_ARCHIVE_SEGMENT_CONFLICT')
973
+ return 'root_event_archive_conflict';
974
+ if (code === 'LOCK_TIMEOUT')
975
+ return 'root_event_archive_locked';
976
+ return 'root_event_archive_failed';
977
+ }
978
+ function materialArchiveFailureCode(error) {
979
+ const code = typeof error === 'object' && error !== null && 'code' in error
980
+ ? String(error.code ?? '')
981
+ : '';
982
+ if (code === 'MATERIAL_ARCHIVE_INVALID_LOG')
983
+ return 'material_archive_invalid_log';
984
+ if (code === 'MATERIAL_ARCHIVE_INVALID_ARCHIVE')
985
+ return 'material_archive_invalid_archive';
986
+ if (code === 'MATERIAL_ARCHIVE_RANGE_INVALID')
987
+ return 'material_archive_range_invalid';
988
+ if (code === 'MATERIAL_ARCHIVE_SEGMENT_CONFLICT')
989
+ return 'material_archive_conflict';
990
+ if (code === 'MATERIAL_ARCHIVE_CURSOR_INVALID')
991
+ return 'material_archive_cursor_invalid';
992
+ if (code === 'LOCK_TIMEOUT')
993
+ return 'material_archive_locked';
994
+ return 'material_archive_failed';
995
+ }
996
+ function parseRootArchiveArgs(argv) {
997
+ const parsed = { help: false, json: false, write: false };
998
+ for (let index = 0; index < argv.length; index += 1) {
999
+ const arg = argv[index];
1000
+ if (arg === '--help')
1001
+ parsed.help = true;
1002
+ else if (arg === '--json')
1003
+ parsed.json = true;
1004
+ else if (arg === '--write')
1005
+ parsed.write = true;
1006
+ else if (arg === '--keep-events') {
1007
+ const value = argv[index + 1];
1008
+ const keepEvents = parsePositiveInt(value);
1009
+ if (value === undefined || value.startsWith('--') || keepEvents === undefined) {
1010
+ parsed.error = 'invalid_keep_events';
1011
+ return parsed;
1012
+ }
1013
+ parsed.keepEvents = keepEvents;
1014
+ index += 1;
1015
+ }
1016
+ else {
1017
+ parsed.error = 'invalid_arguments';
1018
+ return parsed;
1019
+ }
1020
+ }
1021
+ return parsed;
1022
+ }
1023
+ function runRootEventArchive(argv, deps) {
1024
+ const parsed = parseRootArchiveArgs(argv);
1025
+ if (parsed.help) {
1026
+ process.stdout.write('usage: evolver retention archive-root [--keep-events N] [--write] [--json]\n');
1027
+ return 0;
1028
+ }
1029
+ if (parsed.error !== undefined) {
1030
+ process.stderr.write(`retention archive-root: ${parsed.error}\n`);
1031
+ return 2;
1032
+ }
1033
+ const options = {
1034
+ path: deps.rootEventsPath ?? events.rootEventsPath(),
1035
+ ...(parsed.keepEvents !== undefined ? { keepEvents: parsed.keepEvents } : {}),
1036
+ };
1037
+ try {
1038
+ const result = parsed.write
1039
+ ? events.archiveRootEvents(options)
1040
+ : events.planRootEventArchive(options);
1041
+ if (parsed.json)
1042
+ process.stdout.write(`${JSON.stringify({ ok: true, group: 'retention.archive_root', ...result })}\n`);
1043
+ else
1044
+ process.stdout.write(formatRootEventArchive(result));
1045
+ return 0;
1046
+ }
1047
+ catch (error) {
1048
+ process.stderr.write(`retention archive-root: ${archiveFailureCode(error)}\n`);
1049
+ return 1;
1050
+ }
1051
+ }
1052
+ function parseMaterialArchiveArgs(argv) {
1053
+ const parsed = { help: false, json: false, write: false };
1054
+ for (let index = 0; index < argv.length; index += 1) {
1055
+ const arg = argv[index];
1056
+ if (arg === '--help')
1057
+ parsed.help = true;
1058
+ else if (arg === '--json')
1059
+ parsed.json = true;
1060
+ else if (arg === '--write')
1061
+ parsed.write = true;
1062
+ else if (arg === '--keep-records') {
1063
+ const value = argv[index + 1];
1064
+ const keepRecords = parsePositiveInt(value);
1065
+ if (value === undefined || value.startsWith('--') || keepRecords === undefined) {
1066
+ parsed.error = 'invalid_keep_records';
1067
+ return parsed;
1068
+ }
1069
+ parsed.keepRecords = keepRecords;
1070
+ index += 1;
1071
+ }
1072
+ else {
1073
+ parsed.error = 'invalid_arguments';
1074
+ return parsed;
1075
+ }
1076
+ }
1077
+ return parsed;
1078
+ }
1079
+ function runMaterialArchive(argv, deps) {
1080
+ const parsed = parseMaterialArchiveArgs(argv);
1081
+ if (parsed.help) {
1082
+ process.stdout.write('usage: evolver retention archive-material [--keep-records N] [--write] [--json]\n');
1083
+ return 0;
1084
+ }
1085
+ if (parsed.error !== undefined) {
1086
+ process.stderr.write(`retention archive-material: ${parsed.error}\n`);
1087
+ return 2;
1088
+ }
1089
+ const path = deps.materialStorePath ?? events.materialStorePath();
1090
+ const cursorPaths = deps.materialCursorPaths
1091
+ ?? (deps.materialCursorPath !== undefined
1092
+ ? [deps.materialCursorPath]
1093
+ : [join(dirname(path), 'cycle-consumer.json'), join(dirname(path), 'distill-consumer.json')]);
1094
+ const options = {
1095
+ path,
1096
+ cursorPaths,
1097
+ ...(parsed.keepRecords !== undefined ? { keepRecords: parsed.keepRecords } : {}),
1098
+ };
1099
+ try {
1100
+ const result = parsed.write
1101
+ ? materialNs.archiveMaterialStore(options)
1102
+ : materialNs.planMaterialArchive(options);
1103
+ if (parsed.json) {
1104
+ process.stdout.write(`${JSON.stringify({ ok: true, group: 'retention.archive_material', ...result })}\n`);
1105
+ }
1106
+ else {
1107
+ process.stdout.write(formatMaterialArchive(result));
1108
+ }
1109
+ return 0;
1110
+ }
1111
+ catch (error) {
1112
+ process.stderr.write(`retention archive-material: ${materialArchiveFailureCode(error)}\n`);
1113
+ return 1;
1114
+ }
1115
+ }
901
1116
  export function formatRetentionReport(report) {
902
1117
  const lines = [
903
1118
  `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}`,
1119
+ ` 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}`,
1120
+ ` 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
1121
  ];
907
1122
  if (report.warnings.length > 0) {
908
1123
  lines.push(' warnings:');
@@ -918,11 +1133,16 @@ export function formatRetentionReport(report) {
918
1133
  return `${lines.join('\n')}\n`;
919
1134
  }
920
1135
  export function runRetention(argv, deps = {}) {
1136
+ if (argv[0] === 'archive-root')
1137
+ return runRootEventArchive(argv.slice(1), deps);
1138
+ if (argv[0] === 'archive-material')
1139
+ return runMaterialArchive(argv.slice(1), deps);
921
1140
  const f = parseFlags(argv);
922
1141
  const report = buildRetentionReport({
923
1142
  rootEventsPath: deps.rootEventsPath,
924
1143
  materialStorePath: deps.materialStorePath,
925
1144
  materialCursorPath: deps.materialCursorPath,
1145
+ materialCursorPaths: deps.materialCursorPaths,
926
1146
  now: deps.now,
927
1147
  maxRootEvents: parsePositiveInt(f['max-root-events']),
928
1148
  maxRootBytes: parsePositiveInt(f['max-root-bytes']),
@@ -1038,6 +1258,7 @@ export async function runInject(argv, deps = {}) {
1038
1258
  process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
1039
1259
  }
1040
1260
  }
1261
+ maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
1041
1262
  }
1042
1263
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
1043
1264
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: deps.eventsPath ?? events.rootEventsPath() });
@@ -1129,7 +1350,7 @@ export function runCli(argv) {
1129
1350
  return 0;
1130
1351
  }
1131
1352
  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');
1353
+ process.stderr.write('用法: evolver [--version|-v] <status|cycles|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-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]|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
1354
  return cmd === undefined ? 0 : 1;
1134
1355
  }
1135
1356
  }
package/dist/lifecycle.js CHANGED
@@ -216,16 +216,20 @@ export function lifecyclePaths(env = process.env) {
216
216
  const stateDir = env['EVOLVER_LIFECYCLE_STATE_DIR'] ?? join(home, 'lifecycle');
217
217
  const logDir = env['EVOLVER_LIFECYCLE_LOG_DIR'] ?? join(home, 'logs');
218
218
  const name = env['EVOLVER_LIFECYCLE_NAME'] ?? DEFAULT_DAEMON_NAME;
219
- const settingsHome = env['EVOLVER_SETTINGS_DIR'] ?? join(homedir(), '.evolver');
219
+ const settingsHome = nonBlankEnv(env, 'EVOLVER_SETTINGS_DIR') ?? join(homedir(), '.evolver');
220
220
  return {
221
221
  home,
222
222
  stateDir,
223
223
  logDir,
224
224
  pidFile: env['EVOLVER_LIFECYCLE_PID_FILE'] ?? join(stateDir, `${name}.pid`),
225
225
  logFile: env['EVOLVER_LIFECYCLE_LOG_FILE'] ?? join(logDir, `${name}.log`),
226
- settingsFile: env['EVOLVER_PROXY_SETTINGS_FILE'] ?? join(settingsHome, 'settings.json'),
226
+ settingsFile: nonBlankEnv(env, 'EVOLVER_PROXY_SETTINGS_FILE') ?? join(settingsHome, 'settings.json'),
227
227
  };
228
228
  }
229
+ function nonBlankEnv(env, key) {
230
+ const value = env[key]?.trim();
231
+ return value ? value : undefined;
232
+ }
229
233
  export function renderSystemdUnit(opts = {}) {
230
234
  return [
231
235
  '# Linux systemd user unit -- ~/.config/systemd/user/evolver-proxy.service',
package/dist/login.d.ts CHANGED
@@ -1,10 +1,26 @@
1
+ export interface PublicAuthPathOptions {
2
+ env?: NodeJS.ProcessEnv;
3
+ homeDir?: string;
4
+ }
5
+ export interface LogoutOptions extends PublicAuthPathOptions {
6
+ exists?: (path: string) => boolean;
7
+ unlink?: (path: string) => void;
8
+ }
9
+ export interface LogoutResult {
10
+ tokenPath: string;
11
+ removed: boolean;
12
+ }
13
+ export declare function publicOAuthTokenPath(opts?: PublicAuthPathOptions): string;
1
14
  /**
2
15
  * `evolver login` — RFC 8628 device authorization grant against the public hub
3
16
  * (like `gh auth login`): print a user code + verification URL, then poll until
4
17
  * the user approves in the browser, storing the token at ~/.evomap/token.json.
5
18
  *
6
- * Hub URL comes from EVOMAP_HUB_URL (default https://evomap.ai); EVOMAP_DIR
7
- * overrides the credential directory. The token replaces node_secret for
8
- * publish + /a2a calls (it carries the `a2a` scope).
19
+ * Hub URL follows A2A_HUB_URL -> EVOMAP_HUB_URL -> EVOLVER_DEFAULT_HUB_URL -> https://evomap.ai. Credential
20
+ * home follows the same public Hub precedence as publish/ATP:
21
+ * EVOMAP_DIR → EVOLVER_HOME → EVOMAP_HOME → ~/.evomap. The token replaces
22
+ * node_secret for publish + /a2a calls (it carries the `a2a` scope).
9
23
  */
10
- export declare function runLogin(_argv: readonly string[]): Promise<number>;
24
+ export declare function runLogin(argv: readonly string[]): Promise<number>;
25
+ export declare function logoutPublicOAuth(opts?: LogoutOptions): LogoutResult;
26
+ export declare function runLogout(argv: readonly string[], opts?: LogoutOptions): Promise<number>;
package/dist/login.js CHANGED
@@ -1,19 +1,39 @@
1
+ import { existsSync, unlinkSync } from 'node:fs';
1
2
  import { homedir } from 'node:os';
2
3
  import { join } from 'node:path';
3
- import { PublicOAuthProvider, createOAuthHttpTransport } from '@evomap/evolver-adapter-public';
4
+ import { PublicOAuthProvider, createOAuthHttpTransport, resolveHubUrl } from '@evomap/evolver-adapter-public';
5
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
6
+ const LOGIN_USAGE = 'usage: evolver login\n';
7
+ function publicAuthDir(opts = {}) {
8
+ const env = opts.env ?? process.env;
9
+ return env.EVOMAP_DIR ?? env.EVOLVER_HOME ?? env.EVOMAP_HOME ?? join(opts.homeDir ?? homedir(), '.evomap');
10
+ }
11
+ export function publicOAuthTokenPath(opts = {}) {
12
+ return join(publicAuthDir(opts), 'token.json');
13
+ }
4
14
  /**
5
15
  * `evolver login` — RFC 8628 device authorization grant against the public hub
6
16
  * (like `gh auth login`): print a user code + verification URL, then poll until
7
17
  * the user approves in the browser, storing the token at ~/.evomap/token.json.
8
18
  *
9
- * Hub URL comes from EVOMAP_HUB_URL (default https://evomap.ai); EVOMAP_DIR
10
- * overrides the credential directory. The token replaces node_secret for
11
- * publish + /a2a calls (it carries the `a2a` scope).
19
+ * Hub URL follows A2A_HUB_URL -> EVOMAP_HUB_URL -> EVOLVER_DEFAULT_HUB_URL -> https://evomap.ai. Credential
20
+ * home follows the same public Hub precedence as publish/ATP:
21
+ * EVOMAP_DIR → EVOLVER_HOME → EVOMAP_HOME → ~/.evomap. The token replaces
22
+ * node_secret for publish + /a2a calls (it carries the `a2a` scope).
12
23
  */
13
- export async function runLogin(_argv) {
14
- const hubUrl = process.env.EVOMAP_HUB_URL ?? 'https://evomap.ai';
15
- const dir = process.env.EVOMAP_DIR ?? join(homedir(), '.evomap');
16
- const credPath = join(dir, 'token.json');
24
+ export async function runLogin(argv) {
25
+ if (argv[0] === '--help' || argv[0] === '-h') {
26
+ process.stdout.write(LOGIN_USAGE);
27
+ return 0;
28
+ }
29
+ if (argv.length > 0) {
30
+ process.stderr.write(LOGIN_USAGE);
31
+ return 1;
32
+ }
33
+ loadEnvFileFromEnv(process.env);
34
+ const hubUrl = resolveHubUrl(process.env);
35
+ const dir = publicAuthDir();
36
+ const credPath = publicOAuthTokenPath();
17
37
  const provider = new PublicOAuthProvider({
18
38
  credPath,
19
39
  machine: { softIdPath: join(dir, 'machine-id') },
@@ -35,4 +55,34 @@ export async function runLogin(_argv) {
35
55
  process.stderr.write(`login failed: ${e instanceof Error ? e.message : String(e)}\n`);
36
56
  return 1;
37
57
  }
58
+ }
59
+ export function logoutPublicOAuth(opts = {}) {
60
+ const tokenPath = publicOAuthTokenPath(opts);
61
+ const exists = opts.exists ?? existsSync;
62
+ if (!exists(tokenPath))
63
+ return { tokenPath, removed: false };
64
+ (opts.unlink ?? unlinkSync)(tokenPath);
65
+ return { tokenPath, removed: true };
66
+ }
67
+ export async function runLogout(argv, opts = {}) {
68
+ if (argv[0] === '--help' || argv[0] === '-h') {
69
+ process.stdout.write('用法: evolver logout\n');
70
+ return 0;
71
+ }
72
+ if (argv.length > 0) {
73
+ process.stderr.write('用法: evolver logout\n');
74
+ return 1;
75
+ }
76
+ try {
77
+ const result = logoutPublicOAuth(opts);
78
+ if (result.removed)
79
+ process.stdout.write(`Logged out. Removed OAuth token at ${result.tokenPath}\n`);
80
+ else
81
+ process.stdout.write(`Already logged out. No OAuth token at ${result.tokenPath}\n`);
82
+ return 0;
83
+ }
84
+ catch (err) {
85
+ process.stderr.write(`logout failed: ${err instanceof Error ? err.message : String(err)}\n`);
86
+ return 1;
87
+ }
38
88
  }