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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.d.ts +6 -0
  4. package/dist/assetHealth.js +107 -0
  5. package/dist/assetRepair.d.ts +24 -0
  6. package/dist/assetRepair.js +172 -0
  7. package/dist/assetSidecarRecovery.d.ts +14 -0
  8. package/dist/assetSidecarRecovery.js +171 -0
  9. package/dist/assetTrust.d.ts +24 -0
  10. package/dist/assetTrust.js +231 -0
  11. package/dist/atp.d.ts +10 -5
  12. package/dist/atp.js +119 -26
  13. package/dist/atpAutoBuyer.d.ts +120 -0
  14. package/dist/atpAutoBuyer.js +814 -0
  15. package/dist/atpAutoDeliver.js +2 -2
  16. package/dist/autoDistillAntiGene.js +7 -5
  17. package/dist/autoDistillLlm.d.ts +26 -0
  18. package/dist/autoDistillLlm.js +119 -22
  19. package/dist/autoDistillTranscript.js +3 -2
  20. package/dist/autoexec.d.ts +111 -24
  21. package/dist/autoexec.js +887 -120
  22. package/dist/autoexecConfig.d.ts +10 -0
  23. package/dist/autoexecConfig.js +69 -0
  24. package/dist/cli.js +13 -0
  25. package/dist/cliContracts.d.ts +33 -2
  26. package/dist/cliContracts.js +818 -78
  27. package/dist/commandCatalog.d.ts +72 -0
  28. package/dist/commandCatalog.js +120 -0
  29. package/dist/commands.d.ts +1 -0
  30. package/dist/commands.js +1 -0
  31. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  32. package/dist/curriculumCapabilityGaps.js +24 -0
  33. package/dist/cycleConsumer.d.ts +17 -2
  34. package/dist/cycleConsumer.js +374 -50
  35. package/dist/dashboard.d.ts +13 -1
  36. package/dist/dashboard.js +235 -18
  37. package/dist/dispatch.d.ts +9 -2
  38. package/dist/dispatch.js +29 -6
  39. package/dist/distillAdmission.d.ts +13 -0
  40. package/dist/distillAdmission.js +35 -0
  41. package/dist/distillObserver.js +27 -12
  42. package/dist/distillPrimitives.d.ts +11 -8
  43. package/dist/distillPrimitives.js +116 -22
  44. package/dist/doctor.d.ts +13 -0
  45. package/dist/doctor.js +177 -10
  46. package/dist/identityHome.d.ts +9 -0
  47. package/dist/identityHome.js +47 -0
  48. package/dist/index.d.ts +73 -40
  49. package/dist/index.js +745 -207
  50. package/dist/issueReport.d.ts +7 -0
  51. package/dist/issueReport.js +291 -0
  52. package/dist/learningTrace.d.ts +15 -0
  53. package/dist/learningTrace.js +73 -0
  54. package/dist/lifecycle.d.ts +199 -2
  55. package/dist/lifecycle.js +4999 -152
  56. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  57. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  58. package/dist/localMemoryGraph.d.ts +184 -0
  59. package/dist/localMemoryGraph.js +2689 -0
  60. package/dist/login.d.ts +1 -1
  61. package/dist/login.js +3 -3
  62. package/dist/materialPackage.js +3 -6
  63. package/dist/materialSnapshot.d.ts +35 -1
  64. package/dist/materialSnapshot.js +265 -18
  65. package/dist/memoryGraphOps.d.ts +8 -0
  66. package/dist/memoryGraphOps.js +140 -0
  67. package/dist/migrate/assetFormatMap.d.ts +61 -0
  68. package/dist/migrate/assetFormatMap.js +53 -0
  69. package/dist/migrate/envTranslate.d.ts +26 -0
  70. package/dist/migrate/envTranslate.js +147 -0
  71. package/dist/migrate/fieldMap.d.ts +7 -5
  72. package/dist/migrate/fieldMap.js +20 -14
  73. package/dist/migrate/oauthImport.d.ts +66 -0
  74. package/dist/migrate/oauthImport.js +667 -0
  75. package/dist/migrate/v1Import.d.ts +98 -1
  76. package/dist/migrate/v1Import.js +1532 -71
  77. package/dist/modelCompatibility.d.ts +10 -0
  78. package/dist/modelCompatibility.js +296 -0
  79. package/dist/promptRecallHook.d.ts +24 -0
  80. package/dist/promptRecallHook.js +425 -0
  81. package/dist/recallVerifyReport.d.ts +37 -0
  82. package/dist/recallVerifyReport.js +244 -0
  83. package/dist/recipe.d.ts +14 -2
  84. package/dist/recipe.js +543 -65
  85. package/dist/repairedAssetStore.d.ts +2 -0
  86. package/dist/repairedAssetStore.js +12 -0
  87. package/dist/requiredSandboxValidation.d.ts +5 -0
  88. package/dist/requiredSandboxValidation.js +4 -0
  89. package/dist/reuse.d.ts +18 -4
  90. package/dist/reuse.js +375 -107
  91. package/dist/reviewFilter.d.ts +3 -1
  92. package/dist/reviewFilter.js +3 -1
  93. package/dist/runtimeCapabilities.d.ts +18 -0
  94. package/dist/runtimeCapabilities.js +81 -0
  95. package/dist/runtimeSessionSource.d.ts +8 -2
  96. package/dist/runtimeSessionSource.js +63 -11
  97. package/dist/selectionPolicyConfig.d.ts +8 -0
  98. package/dist/selectionPolicyConfig.js +18 -0
  99. package/dist/semanticIdfConfig.d.ts +2 -0
  100. package/dist/semanticIdfConfig.js +4 -0
  101. package/dist/sessionIngest.d.ts +43 -0
  102. package/dist/sessionIngest.js +180 -0
  103. package/dist/setupHooks.d.ts +5 -0
  104. package/dist/setupHooks.js +330 -14
  105. package/dist/skill2gep.d.ts +13 -9
  106. package/dist/skill2gep.js +99 -36
  107. package/dist/skillDistill.d.ts +8 -4
  108. package/dist/skillDistill.js +39 -9
  109. package/dist/solo/mode.js +1 -0
  110. package/dist/sync.d.ts +13 -1
  111. package/dist/sync.js +1947 -265
  112. package/dist/thesis.d.ts +1 -1
  113. package/dist/thesis.js +20 -3
  114. package/dist/trajectoryExport.js +21 -3
  115. package/dist/v1Compat.d.ts +1 -0
  116. package/dist/v1Compat.js +9 -0
  117. package/dist/valueDigest.js +8 -1
  118. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  119. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  120. package/dist/workflow.d.ts +39 -0
  121. package/dist/workflow.js +386 -0
  122. package/dist/workflowRuntime.d.ts +66 -0
  123. package/dist/workflowRuntime.js +638 -0
  124. package/package.json +14 -7
package/dist/index.js CHANGED
@@ -1,35 +1,30 @@
1
- import { events, ops, hooks, mailbox } from '@evomap/evolver-core';
2
- import { readEvents, statusReport, listCycles, showCycle, listTriggers, buildNarrativeSnapshot, buildRetentionReport } from './commands.js';
1
+ import { events, ops, hooks, mailbox, hub as hubNs } from '@evomap/evolver-core';
2
+ import { readEvents, statusReport, listCycles, showCycle, listTriggers, buildNarrativeSnapshot, buildRetentionReport, dailyCapsuleCount } from './commands.js';
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
- import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
8
+ import { listApprovedGenes, pendingGeneReviewRecords, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
8
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
9
10
  import { draftGeneCandidate } from './distillPrimitives.js';
10
- import { emitSessionRecall } from './autoRecall.js';
11
- import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
12
- import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
11
+ import { assessDraftAdmissionFromStore } from './distillAdmission.js';
12
+ import { isSyncCommandName, renderCommandGroups } from './commandCatalog.js';
13
+ import { parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
14
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync, mkdirSync, } from 'node:fs';
13
15
  import { homedir } from 'node:os';
14
- import { dirname, join, resolve } from 'node:path';
15
- import { importV1 } from './migrate/v1Import.js';
16
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
17
+ import { applyImportV1Plan, planImportV1 } from './migrate/v1Import.js';
16
18
  import { explicitRecipeHomes } from './recipe.js';
17
- import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
19
+ import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled, dailyConnectionStatus, lifecyclePaths } from './lifecycle.js';
20
+ import { maybeCleanupLegacyWindowsDaemonTasks } from './windowsLegacyTaskCleanup.js';
18
21
  import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
19
22
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
20
23
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
21
- /**
22
- * Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
23
- * one place so the recorded Material and any future cycle consumer agree on the group name.
24
- */
25
- const INGEST_CONSUMER_GROUP = 'cycle';
26
- function resolveIngestDeps(deps) {
27
- return {
28
- materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
29
- watermarkStore: deps.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath()),
30
- ingestor: deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
31
- };
32
- }
24
+ import { asGeneCandidate, parseDistillOutput } from './autoDistillLlm.js';
25
+ import { runPromptRecallHook } from './promptRecallHook.js';
26
+ import { INGEST_CONSUMER_GROUP, recordSessionMaterial, resolveIngestDeps, toMaterialSourceAgent, } from './sessionIngest.js';
27
+ export { runSessionIngestTick, scanSessionDirs, } from './sessionIngest.js';
33
28
  /** Minimal `--flag value` parser (last wins); bare positionals are ignored. */
34
29
  function parseFlags(argv) {
35
30
  const out = {};
@@ -57,6 +52,28 @@ function operatorActorId() {
57
52
  return process.env['EVOLVER_ACTOR_ID'] ?? process.env['USER'] ?? process.env['LOGNAME'] ?? 'cli';
58
53
  }
59
54
  export const PACKAGE = '@evomap/evolver-cli';
55
+ export function cliUsage() {
56
+ return [
57
+ 'Usage: evolver <command> [options]',
58
+ '',
59
+ 'Options:',
60
+ ' -h, --help Show this help',
61
+ ' -v, --version Show the installed version',
62
+ '',
63
+ 'Proxy options (evolver proxy):',
64
+ ' --home <dir> Root for assets, store, settings, and traces',
65
+ ' --evomap-home <dir> Identity home for node_id/node_secret; defaults to --home',
66
+ ' --store <path> Mailbox store path',
67
+ ' --settings <path> Proxy settings file',
68
+ ' --env-file <path> Environment file',
69
+ '',
70
+ 'Commands:',
71
+ ...renderCommandGroups(),
72
+ '',
73
+ 'Run evolver <command> --help for command-specific options.',
74
+ '',
75
+ ].join('\n');
76
+ }
60
77
  const LOCAL_SECRET_STATE_KEYS = ['node_secret', 'node_secret_source', 'node_secret_version'];
61
78
  const LOCAL_SECRET_ENV_VARS = [
62
79
  'EVOMAP_NODE_SECRET',
@@ -197,16 +214,145 @@ export function rebuildViews(opts = {}) {
197
214
  replayer.rebuild(ing.readAll());
198
215
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
199
216
  }
200
- /** migrate import-v1 <v1dir> [outDir]: v1→v2 只读迁移(异步, 由 cli.ts 调). */
201
- export async function runMigrate(argv) {
202
- if (argv[0] !== 'import-v1' || !argv[1]) {
203
- process.stderr.write('用法: evolver migrate import-v1 <v1dir> [outDir]\n');
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
+ }
238
+ /** migrate import-v1 | migrate env | migrate oauth — V1→V2 migration tools. */
239
+ export async function runMigrate(argv, deps = {}) {
240
+ const usage = [
241
+ 'Usage:',
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]',
245
+ ' evolver migrate env [--file <dotenv>] [--json] [--write-suggestions <path>] [--no-process-env]',
246
+ ' evolver migrate oauth [--from <oauth_token.json>] [--to <token.json>] [--force] [--dry-run] [--json]',
247
+ '',
248
+ ].join('\n');
249
+ if (argv[0] === '--help' || argv[0] === '-h' || argv.length === 0) {
250
+ process.stdout.write(usage);
251
+ return 0;
252
+ }
253
+ if (argv[0] === 'env') {
254
+ const { runMigrateEnvCommand } = await import('./migrate/envTranslate.js');
255
+ return runMigrateEnvCommand(argv.slice(1));
256
+ }
257
+ if (argv[0] === 'oauth') {
258
+ const { runMigrateOAuthCommand } = await import('./migrate/oauthImport.js');
259
+ return runMigrateOAuthCommand(argv.slice(1));
260
+ }
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('--')) {
264
+ process.stderr.write(usage);
265
+ return 1;
266
+ }
267
+ let outDir;
268
+ let workspace;
269
+ let dryRun = false;
270
+ let json = false;
271
+ for (let index = 2; index < migrationArgs.length; index += 1) {
272
+ const arg = migrationArgs[index] ?? '';
273
+ if (arg === '--workspace') {
274
+ const value = migrationArgs[index + 1];
275
+ if (!value || value.startsWith('--')) {
276
+ process.stderr.write(usage);
277
+ return 1;
278
+ }
279
+ workspace = value;
280
+ index += 1;
281
+ }
282
+ else if (arg.startsWith('--workspace=')) {
283
+ workspace = arg.slice('--workspace='.length);
284
+ if (!workspace) {
285
+ process.stderr.write(usage);
286
+ return 1;
287
+ }
288
+ }
289
+ else if (arg === '--dry-run') {
290
+ dryRun = true;
291
+ }
292
+ else if (arg === '--json') {
293
+ json = true;
294
+ }
295
+ else if (arg.startsWith('--') || outDir !== undefined) {
296
+ process.stderr.write(usage);
297
+ return 1;
298
+ }
299
+ else {
300
+ outDir = arg;
301
+ }
302
+ }
303
+ const envFile = loadEnvFileFromEnv(process.env);
304
+ if (envFile.error) {
305
+ writeMigrationFailure('migration_env_file_load_failed', json);
204
306
  return 1;
205
307
  }
206
- const outDir = argv[2] ?? process.cwd();
207
- const store = new assetstore.LocalJsonlProvider(`${outDir}/assets`);
208
- const rep = await importV1(argv[1], store, outDir);
209
- 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`);
308
+ const targetDir = outDir ?? events.evomapHome();
309
+ const options = { ...deps, ...(workspace ? { workspace } : {}) };
310
+ let plan;
311
+ try {
312
+ plan = await planImportV1(migrationArgs[1], targetDir, options);
313
+ }
314
+ catch (error) {
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);
353
+ return 1;
354
+ }
355
+ process.stdout.write(successOutput);
210
356
  return 0;
211
357
  }
212
358
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -220,8 +366,107 @@ export function formatAssetLine(a) {
220
366
  : '';
221
367
  return `${a.type.padEnd(15)} ${id} ${desc}`.trimEnd();
222
368
  }
223
- /** asset-log [Gene|Capsule|EvolutionEvent|AntiGene] [limit]: list recent local assets (observability; ported v1 CLI verb). */
224
- export async function runAssetLog(argv, store) {
369
+ const ASSET_CALL_ACTIONS = [
370
+ 'hub_search_hit', 'hub_search_miss',
371
+ 'asset_reuse', 'asset_reference',
372
+ 'asset_publish', 'asset_publish_skip',
373
+ 'asset_inject', 'asset_inject_shadow',
374
+ 'hub_review_submitted', 'hub_review_rejected', 'hub_review_failed',
375
+ ];
376
+ function isAssetCallAction(value) {
377
+ return ASSET_CALL_ACTIONS.includes(value);
378
+ }
379
+ /**
380
+ * Preserve V2's asset-store listing as the default. V1's call audit is available
381
+ * through the explicit `calls` mode so the two contracts do not overload an empty argv.
382
+ */
383
+ export async function runAssetLog(argv, store, deps = {}) {
384
+ const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
385
+ const CALL_FLAGS = ['--run', '--action', '--last', '--since', '--json'];
386
+ const explicitCallMode = argv[0] === 'calls' || argv[0] === '--calls';
387
+ const callMode = explicitCallMode || argv.some((arg) => CALL_FLAGS
388
+ .some((flag) => arg === flag || arg.startsWith(`${flag}=`)));
389
+ const assetMode = !callMode && (argv.length === 0
390
+ || argv[0] === 'assets'
391
+ || argv[0] === '--assets'
392
+ || KINDS.includes(argv[0] ?? '')
393
+ || /^\d+$/.test(argv[0] ?? ''));
394
+ if (assetMode)
395
+ return runAssetList(argv.filter((arg) => arg !== 'assets' && arg !== '--assets'), store);
396
+ if (!callMode)
397
+ return assetLogUsage(`unknown asset-log mode: ${argv[0] ?? '(missing)'}`);
398
+ const opts = {};
399
+ let json = false;
400
+ for (let i = explicitCallMode ? 1 : 0; i < argv.length; i += 1) {
401
+ const arg = argv[i];
402
+ if (!explicitCallMode && KINDS.includes(arg ?? ''))
403
+ continue;
404
+ if (arg === '--json') {
405
+ json = true;
406
+ continue;
407
+ }
408
+ const parsed = assetLogFlagValue(argv, i, '--run');
409
+ if (parsed) {
410
+ opts.run_id = parsed.value;
411
+ i += parsed.consumed;
412
+ continue;
413
+ }
414
+ const action = assetLogFlagValue(argv, i, '--action');
415
+ if (action) {
416
+ if (!isAssetCallAction(action.value))
417
+ return assetLogUsage(`invalid --action: ${action.value}`);
418
+ opts.action = action.value;
419
+ i += action.consumed;
420
+ continue;
421
+ }
422
+ const last = assetLogFlagValue(argv, i, '--last');
423
+ if (last) {
424
+ if (!/^\d+$/.test(last.value) || Number(last.value) < 1)
425
+ return assetLogUsage(`invalid --last: ${last.value}`);
426
+ opts.last = Number(last.value);
427
+ i += last.consumed;
428
+ continue;
429
+ }
430
+ const since = assetLogFlagValue(argv, i, '--since');
431
+ if (since) {
432
+ if (!Number.isFinite(Date.parse(since.value)))
433
+ return assetLogUsage(`invalid --since: ${since.value}`);
434
+ opts.since = since.value;
435
+ i += since.consumed;
436
+ continue;
437
+ }
438
+ return assetLogUsage(`unknown asset-log argument: ${arg ?? '(missing)'}`);
439
+ }
440
+ const logPath = deps.logPath ?? events.assetCallLogPath();
441
+ const callLog = deps.callLog ?? new hubNs.AssetCallLog(logPath);
442
+ if (json) {
443
+ process.stdout.write(`${JSON.stringify(callLog.read(opts), null, 2)}\n`);
444
+ return 0;
445
+ }
446
+ const summary = callLog.summarize(opts);
447
+ process.stdout.write('\n[Asset Call Log]\n');
448
+ process.stdout.write(` Total entries: ${summary.total_entries}\n`);
449
+ process.stdout.write(` Unique assets: ${summary.unique_assets}\n`);
450
+ process.stdout.write(` Unique runs: ${summary.unique_runs}\n`);
451
+ process.stdout.write(' By action:\n');
452
+ for (const [action, count] of Object.entries(summary.by_action)) {
453
+ process.stdout.write(` ${action}: ${count}\n`);
454
+ }
455
+ if (summary.entries.length === 0) {
456
+ process.stdout.write('\n No entries found.\n\n');
457
+ return 0;
458
+ }
459
+ process.stdout.write('\n Recent entries:\n');
460
+ for (const entry of summary.entries.slice(-10)) {
461
+ const timestamp = entry.timestamp ? entry.timestamp.slice(0, 19) : '?';
462
+ const asset = entry.asset_id ? `${entry.asset_id.slice(0, 20)}...` : '(none)';
463
+ const signals = Array.isArray(entry.signals) ? entry.signals.slice(0, 3).join(', ') : '';
464
+ process.stdout.write(` [${timestamp}] ${entry.action || '?'} asset=${asset} score=${entry.score ?? '-'} mode=${entry.mode ?? '-'} signals=[${signals}] run=${entry.run_id ?? '-'}\n`);
465
+ }
466
+ process.stdout.write('\n');
467
+ return 0;
468
+ }
469
+ async function runAssetList(argv, store) {
225
470
  const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
226
471
  let kind;
227
472
  let limit = 20;
@@ -230,6 +475,8 @@ export async function runAssetLog(argv, store) {
230
475
  kind = a;
231
476
  else if (/^\d+$/.test(a))
232
477
  limit = Number(a);
478
+ else
479
+ return assetLogUsage(`unknown asset list argument: ${a}`);
233
480
  }
234
481
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
235
482
  const assets = await s.list(kind, limit);
@@ -241,6 +488,120 @@ export async function runAssetLog(argv, store) {
241
488
  process.stdout.write(formatAssetLine(a) + '\n');
242
489
  return 0;
243
490
  }
491
+ function assetLogFlagValue(argv, index, flag) {
492
+ const arg = argv[index];
493
+ if (arg?.startsWith(`${flag}=`)) {
494
+ const value = arg.slice(flag.length + 1);
495
+ return value ? { value, consumed: 0 } : null;
496
+ }
497
+ if (arg !== flag)
498
+ return null;
499
+ const value = argv[index + 1];
500
+ return value && !value.startsWith('--') ? { value, consumed: 1 } : null;
501
+ }
502
+ function assetLogUsage(error) {
503
+ process.stderr.write(`${error}\nusage: evolver asset-log [assets] [Gene|Capsule|EvolutionEvent|AntiGene] [limit] | evolver asset-log calls [--run <id>] [--action <action>] [--last <n>] [--since <iso>] [--json]\n`);
504
+ return 1;
505
+ }
506
+ const DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES = 1024 * 1024;
507
+ function responseFileArg(argv) {
508
+ for (let index = 0; index < argv.length; index += 1) {
509
+ const arg = argv[index];
510
+ if (arg?.startsWith('--response-file='))
511
+ return arg.slice('--response-file='.length);
512
+ if (arg === '--response-file')
513
+ return argv[index + 1] ?? '';
514
+ }
515
+ return undefined;
516
+ }
517
+ function pathIsWithin(root, target) {
518
+ const rel = relative(root, target);
519
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
520
+ }
521
+ function sameResponseFileIdentity(left, right) {
522
+ const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
523
+ if (hasStableFileId)
524
+ return left.dev === right.dev && left.ino === right.ino;
525
+ // Some filesystems do not expose dev/ino. Birth time + mode is the strongest portable fallback Node provides.
526
+ return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
527
+ }
528
+ function sameResponseFileSnapshot(left, right) {
529
+ return sameResponseFileIdentity(left, right)
530
+ && left.size === right.size
531
+ && left.mtimeNs === right.mtimeNs
532
+ && left.ctimeNs === right.ctimeNs;
533
+ }
534
+ function readResponseFileDescriptor(fd, expectedSize) {
535
+ const content = Buffer.alloc(expectedSize);
536
+ let offset = 0;
537
+ while (offset < expectedSize) {
538
+ const bytesRead = readSync(fd, content, offset, expectedSize - offset, offset);
539
+ if (bytesRead === 0)
540
+ throw new Error('response-file changed while being read (truncated)');
541
+ offset += bytesRead;
542
+ }
543
+ const extra = Buffer.allocUnsafe(1);
544
+ if (readSync(fd, extra, 0, 1, expectedSize) !== 0) {
545
+ throw new Error('response-file changed while being read (grew beyond the validated size)');
546
+ }
547
+ return content.toString('utf8');
548
+ }
549
+ function candidateFromResponseFile(path, deps) {
550
+ if (!path)
551
+ throw new Error('response-file path is empty');
552
+ const requestedRoot = resolve(deps.responseFileRoot ?? process.cwd());
553
+ const root = realpathSync(requestedRoot);
554
+ const requested = resolve(requestedRoot, path);
555
+ if (!pathIsWithin(requestedRoot, requested))
556
+ throw new Error('response-file is outside the allowed root');
557
+ const beforeOpen = lstatSync(requested, { bigint: true });
558
+ if (!beforeOpen.isFile() || beforeOpen.isSymbolicLink())
559
+ throw new Error('response-file must be a regular non-symlink file');
560
+ const canonical = realpathSync(requested);
561
+ if (!pathIsWithin(root, canonical))
562
+ throw new Error('response-file resolves outside the allowed root');
563
+ const configuredMax = deps.maxResponseFileBytes ?? DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
564
+ const maxBytes = Number.isSafeInteger(Math.floor(configuredMax)) && configuredMax > 0
565
+ ? Math.floor(configuredMax)
566
+ : DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
567
+ if (beforeOpen.size > BigInt(maxBytes))
568
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
569
+ deps.responseFileReadTestHook?.('before-open', canonical);
570
+ const noFollow = process.platform !== 'win32' && typeof fsConstants.O_NOFOLLOW === 'number'
571
+ ? fsConstants.O_NOFOLLOW
572
+ : 0;
573
+ const fd = openSync(canonical, fsConstants.O_RDONLY | noFollow);
574
+ let raw;
575
+ try {
576
+ const opened = fstatSync(fd, { bigint: true });
577
+ if (!opened.isFile())
578
+ throw new Error('response-file must be a regular file');
579
+ if (!sameResponseFileSnapshot(beforeOpen, opened))
580
+ throw new Error('response-file changed before it could be opened');
581
+ if (opened.size > BigInt(maxBytes))
582
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
583
+ deps.responseFileReadTestHook?.('after-open', canonical);
584
+ raw = readResponseFileDescriptor(fd, Number(opened.size));
585
+ const afterRead = fstatSync(fd, { bigint: true });
586
+ if (!sameResponseFileSnapshot(opened, afterRead))
587
+ throw new Error('response-file changed while being read');
588
+ const afterPath = lstatSync(requested, { bigint: true });
589
+ if (!afterPath.isFile() || afterPath.isSymbolicLink() || !sameResponseFileSnapshot(afterRead, afterPath)) {
590
+ throw new Error('response-file path changed while being read');
591
+ }
592
+ const canonicalAfterRead = realpathSync(requested);
593
+ if (!pathIsWithin(root, canonicalAfterRead) || canonicalAfterRead !== canonical) {
594
+ throw new Error('response-file path changed outside the allowed root');
595
+ }
596
+ }
597
+ finally {
598
+ closeSync(fd);
599
+ }
600
+ const candidate = asGeneCandidate(parseDistillOutput(raw));
601
+ if (!candidate)
602
+ throw new Error('response-file does not contain a valid Gene JSON object');
603
+ return candidate;
604
+ }
244
605
  /**
245
606
  * distill: gate a learned approach into the gene pool (ported v1 CLI verb). Runs the structural intake
246
607
  * (schema + dedup + asset_id) and, only if it passes, writes the gene to the store. The agent/runtime is
@@ -249,17 +610,30 @@ export async function runAssetLog(argv, store) {
249
610
  */
250
611
  export async function runDistill(argv, store, deps = {}) {
251
612
  const f = parseFlags(argv);
252
- const candidate = {
253
- ...(f['id'] ? { id: f['id'] } : {}),
254
- category: f['category'] ?? 'innovate',
255
- signals_match: splitList(f['signals'], /,/),
256
- strategy: splitList(f['strategy'], /[;\n]/),
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' },
261
- };
262
- if (candidate.signals_match.length === 0 || candidate.strategy.length === 0) {
613
+ const responseFile = responseFileArg(argv);
614
+ let candidate;
615
+ if (responseFile !== undefined) {
616
+ try {
617
+ candidate = candidateFromResponseFile(responseFile, deps);
618
+ }
619
+ catch (error) {
620
+ process.stderr.write(`[Distill] response-file error: ${error instanceof Error ? error.message : String(error)}\n`);
621
+ return 2;
622
+ }
623
+ }
624
+ else {
625
+ candidate = {
626
+ ...(f['id'] ? { id: f['id'] } : {}),
627
+ category: f['category'] ?? 'innovate',
628
+ signals_match: splitList(f['signals'], /,/),
629
+ strategy: splitList(f['strategy'], /[;\n]/),
630
+ ...(f['summary'] ? { summary: f['summary'] } : {}),
631
+ // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
632
+ // `manual` per V1 #302 classifyProvenance.
633
+ generation_meta: { source: 'manual' },
634
+ };
635
+ }
636
+ if ((candidate.signals_match ?? []).length === 0 || (candidate.strategy ?? []).length === 0) {
263
637
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
264
638
  return 1;
265
639
  }
@@ -274,15 +648,34 @@ export async function runDistill(argv, store, deps = {}) {
274
648
  process.stderr.write(`distill 拒绝: ${r.errors.join('; ')}\n`);
275
649
  return 1;
276
650
  }
277
- await s.put(r.gene);
278
- // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
279
651
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
280
- await ingestor.ingest({
281
- type: 'actor.human.teach',
282
- payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
283
- human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
284
- actor: { kind: 'human', id: operatorActorId() },
285
- });
652
+ if (responseFile !== undefined) {
653
+ // The gene is the commit point. Audit first (idempotently), quarantine second, then persist last so any
654
+ // partial failure remains retryable and can never expose an unaudited machine-produced gene in the pool.
655
+ const assetId = String(r.gene.asset_id);
656
+ const alreadyAudited = ingestor.readAll().some((event) => event.type === 'gene.distilled'
657
+ && String(event.payload?.['assetId'] ?? '') === assetId);
658
+ if (!alreadyAudited) {
659
+ await ingestor.ingest({
660
+ type: 'gene.distilled',
661
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, source: 'cli-response-file' },
662
+ human: { title: `LLM response-file distilled gene ${r.gene.id}`, severity: 'info' },
663
+ actor: { kind: 'machine', id: 'cli-response-file' },
664
+ });
665
+ }
666
+ reviewLedgerForStore(s).quarantineIfAbsent(assetId, 'LLM response-file distillation - review before use');
667
+ await s.put(r.gene);
668
+ }
669
+ else {
670
+ await s.put(r.gene);
671
+ // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
672
+ await ingestor.ingest({
673
+ type: 'actor.human.teach',
674
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
675
+ human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
676
+ actor: { kind: 'human', id: operatorActorId() },
677
+ });
678
+ }
286
679
  process.stdout.write(`distilled gene ${r.gene.id} (${String(r.gene.asset_id).slice(0, 19)}…) → pool\n`);
287
680
  return 0;
288
681
  }
@@ -304,12 +697,6 @@ function printTraceSignals(file, turnCount, sigs) {
304
697
  process.stdout.write(` [${s.strength}/${s.kind}] ${s.text.replace(/\s+/g, ' ').trim().slice(0, 160)}\n`);
305
698
  }
306
699
  }
307
- /** The runtime agents Material.sourceAgent can represent (closed enum on the schema). */
308
- const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'antigravity', 'kimi', 'kiro', 'opencode', 'generic-chat']);
309
- /** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
310
- function toMaterialSourceAgent(agent) {
311
- return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
312
- }
313
700
  /**
314
701
  * Is a Material for this EXACT file state already on the substrate? A Material's identity is its ULID, so `put`
315
702
  * cannot dedup across runs (each build mints a fresh id). Without this, a crash-retry — where a prior run put the
@@ -329,50 +716,6 @@ function materialExistsFor(store, sourcePath, wm) {
329
716
  }
330
717
  return false;
331
718
  }
332
- /**
333
- * Record a session log as Material on the M1 substrate (idempotent by file watermark), then emit a
334
- * `material.batch_ready` root_event so the AE is not bypassed. Re-ingesting the same UNCHANGED file records
335
- * no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
336
- * Returns whether new material landed + its materialId so the caller can report it.
337
- */
338
- async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1, payload, diagnostics) {
339
- const prev = d.watermarkStore.get(absPath);
340
- const scan = materialNs.scanFile(absPath, prev);
341
- // Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
342
- if (prev && !scan.changed)
343
- return { recorded: false, emitted: false };
344
- const m = materialNs.buildMaterial({
345
- sourceAgent,
346
- sourceKind: 'runtime_session',
347
- sourcePath: absPath,
348
- kind: 'session_log',
349
- watermark: scan.watermark,
350
- consumerGroup: INGEST_CONSUMER_GROUP,
351
- ...(payload ? { payload } : {}),
352
- });
353
- // Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
354
- // watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
355
- const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
356
- if (isNew)
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;
361
- await d.ingestor.ingest({
362
- type: 'material.batch_ready',
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
- },
369
- actor: { kind: 'machine' },
370
- });
371
- // Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
372
- // stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
373
- d.watermarkStore.set(absPath, scan.watermark);
374
- return { recorded: isNew, emitted: true, materialId: m.materialId };
375
- }
376
719
  /**
377
720
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
378
721
  * telemetry, so it carries sourceKind=proxy_trace + kind=llm_trace and NO sourceAgent — the origin taxonomy
@@ -407,90 +750,6 @@ async function recordTraceMaterial(absPath, signalCount, d) {
407
750
  d.watermarkStore.set(absPath, scan.watermark);
408
751
  return { recorded: isNew, materialId: m.materialId };
409
752
  }
410
- /**
411
- * Recursively enumerate recognized runtime-session sources under the given dirs — the daemon's auto-distill
412
- * producer source (#106). This includes text session files handled by runtime adapters (`*.jsonl` and Gemini
413
- * `*.json`) plus Cursor's sqlite `state.vscdb`. A missing/permission-denied dir is silently skipped (a daemon
414
- * must not crash on an absent home dir).
415
- */
416
- export function scanSessionDirs(dirs) {
417
- const out = [];
418
- for (const dir of dirs) {
419
- let entries;
420
- try {
421
- entries = readdirSync(resolve(dir), { recursive: true });
422
- }
423
- catch {
424
- continue;
425
- } // dir absent / unreadable → skip
426
- for (const e of entries) {
427
- const file = join(resolve(dir), e);
428
- if (isRuntimeSessionSourcePath(file))
429
- out.push(file);
430
- }
431
- }
432
- return out;
433
- }
434
- function sortedStrings(values) {
435
- return [...new Set([...values].map(String).filter(Boolean))].sort();
436
- }
437
- /**
438
- * One producer tick for the auto-distill loop (#106 slice 1): scan `dirs` for session logs and record any
439
- * NEW/CHANGED file as `runtime_session` Material via the injected (bus) Ingestor — which emits
440
- * `material.batch_ready`, the event the distillObserver claims off. Idempotent per file (watermark cursor), so
441
- * re-scanning an unchanged tree records nothing. Pure producer: it does NOT distill (the observer does). Returns
442
- * how many files landed new material. Inject `deps.ingestor = new Ingestor({ sink: bus })` so the event reaches
443
- * the daemon's ObserverBus; defaults to live paths otherwise.
444
- */
445
- export async function runSessionIngestTick(dirs, deps = {}) {
446
- const d = resolveIngestDeps(deps);
447
- let recorded = 0;
448
- const sourceAgents = new Set();
449
- const signalKinds = new Set();
450
- const signalStrengths = new Set();
451
- let invalidJsonRows = 0;
452
- // #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
453
- // experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
454
- // (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
455
- const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
456
- for (const file of scanSessionDirs(dirs)) {
457
- try {
458
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(file);
459
- const parsedSources = parsed.sources;
460
- const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
461
- if (parsedSources.length === 0 || !agent)
462
- continue; // not a recognized, schema-recordable runtime-session source
463
- const sigsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
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;
468
- if (r.recorded) {
469
- recorded += 1;
470
- sourceAgents.add(agent);
471
- for (const sigs of sigsBySource) {
472
- for (const sig of sigs) {
473
- signalKinds.add(sig.kind);
474
- signalStrengths.add(sig.strength);
475
- }
476
- }
477
- }
478
- if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
479
- // Drop meta turns (heartbeats/empty) before judging, same as `evolver recall` — counting them would skew overlap.
480
- const turns = parsedSources[0].turns.filter((t) => !t.isMeta).map((t) => ({ role: t.role, text: t.text }));
481
- await emitSessionRecall(file, turns, { ingestor: d.ingestor });
482
- }
483
- }
484
- catch { /* unreadable / unparseable file → skip, never break the scan */ }
485
- }
486
- return {
487
- recorded,
488
- sourceAgents: sortedStrings(sourceAgents),
489
- signalKinds: sortedStrings(signalKinds),
490
- signalStrengths: sortedStrings(signalStrengths),
491
- ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
492
- };
493
- }
494
753
  /**
495
754
  * Read + parse one or more trace JSONL files, record each as proxy_trace Material on the M1 substrate (#95,
496
755
  * idempotent by file watermark), and report their signals as a single batch.
@@ -588,7 +847,7 @@ export async function runIngest(argv, store, deps = {}, review) {
588
847
  let parsedSources;
589
848
  let parseDiagnostics;
590
849
  try {
591
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
850
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path, undefined, deps.nativeSessionHome);
592
851
  parsedSources = parsed.sources;
593
852
  parseDiagnostics = parsed.diagnostics;
594
853
  }
@@ -640,23 +899,39 @@ export async function runIngest(argv, store, deps = {}, review) {
640
899
  // --distill: assemble + intake UNPROVEN draft genes per runtime session (shared draft logic — see distillPrimitives).
641
900
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
642
901
  const accepted = [];
643
- let existing = (await s.list('Gene', 1000)).map((g) => ({
644
- id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
645
- signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
646
- }));
902
+ const acceptedSignals = [];
903
+ let candidateCount = 0;
904
+ let admissionSkipped = 0;
905
+ let lastAdmissionSkipReason = '';
647
906
  for (const { source, sigs } of sourceSignalPairs) {
648
907
  const candidate = draftGeneCandidate(source.turns, sigs, source.agent);
649
908
  if (!candidate)
650
909
  continue;
910
+ candidateCount += 1;
911
+ // Same value/novelty gate as the live distillObserver (#562): without it, a bulk ingest over session
912
+ // history floods the human review queue with thin / near-duplicate drafts (118 in one run). A non-admit
913
+ // is a deliberate skip — the rest of the batch still distills; intake below stays the structural gate.
914
+ const { admission, existing } = await assessDraftAdmissionFromStore(s, candidate, acceptedSignals);
915
+ if (!admission.admit) {
916
+ admissionSkipped += 1;
917
+ lastAdmissionSkipReason = admission.reason ?? '';
918
+ process.stdout.write(`\ningest --distill skipped [${source.label}]: ${admission.reason}\n`);
919
+ continue;
920
+ }
651
921
  const r = algo.intakeGene(candidate, existing);
652
922
  if (!r.ok || !r.gene) {
653
923
  process.stderr.write(`\ningest --distill rejected: ${r.errors.join('; ')}\n`);
654
924
  return 1;
655
925
  }
656
926
  accepted.push({ source, candidate, gene: r.gene });
657
- existing = [...existing, { id: r.gene.id, signals_match: r.gene.signals_match }];
927
+ acceptedSignals.push({ id: r.gene.id, signals_match: r.gene.signals_match });
658
928
  }
659
929
  if (accepted.length === 0) {
930
+ if (candidateCount > 0 && admissionSkipped === candidateCount) {
931
+ const reason = lastAdmissionSkipReason ? ` Last skip reason: ${lastAdmissionSkipReason}.` : '';
932
+ process.stdout.write(`\ningest: all ${candidateCount} draft candidate(s) skipped by admission gate.${reason} Nothing stored.\n`);
933
+ return 0;
934
+ }
660
935
  process.stdout.write('\ningest: not enough to distill — need ≥1 strong signal and ≥1 substantive assistant step. Nothing stored.\n');
661
936
  return 0;
662
937
  }
@@ -872,10 +1147,22 @@ export async function runReview(argv, store, review, deps = {}) {
872
1147
  .map((e) => String(e.payload?.['assetId'] ?? ''))
873
1148
  .filter(Boolean));
874
1149
  const autoPending = [...autoDrafted].filter((a) => rev.get(a)?.state === 'quarantined').length;
875
- 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);
876
1163
  if (genes.length === 0)
877
- process.stdout.write('(no genes)\n'); // no early return: the auto-pending footer below is
878
- 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
879
1166
  const id = typeof g['id'] === 'string' ? String(g['id']) : String(g.asset_id);
880
1167
  const view = await assetstore.aggregateLearningHistory(s, id);
881
1168
  const cat = String(g['category'] ?? '?');
@@ -888,8 +1175,10 @@ export async function runReview(argv, store, review, deps = {}) {
888
1175
  const promote = state === 'quarantined' ? ` promote:${promoteHint(view)}` : '';
889
1176
  process.stdout.write(`${id.padEnd(28)} ${cat.padEnd(10)} total=${view.total} succ=${rate} [${reviewStatus(view)}] {${state}}${promote}${auto}\n`);
890
1177
  }
1178
+ if (manualPending > 0)
1179
+ process.stdout.write(`\n${manualPending} gene(s) awaiting review — approve with \`evolver review --approve <id>\`\n`);
891
1180
  if (autoPending > 0)
892
- 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`);
893
1182
  const antiGenePending = (await listReviewVisibleAntiGenes(s, rev)).filter((asset) => rev.get(String(asset.asset_id))?.state === 'quarantined').length;
894
1183
  if (antiGenePending > 0)
895
1184
  process.stdout.write(`\n${antiGenePending} anti-gene(s) awaiting review - inspect with \`evolver review --anti-gene\`\n`);
@@ -1243,8 +1532,16 @@ async function readHookSessionId(read) {
1243
1532
  */
1244
1533
  export async function runInject(argv, deps = {}) {
1245
1534
  const sub = argv[0];
1535
+ if (sub === 'prompt-recall') {
1536
+ return runPromptRecallHook(argv.slice(1), {
1537
+ ...(deps.store ? { store: deps.store } : {}),
1538
+ ...(deps.review ? { review: deps.review } : {}),
1539
+ ...(deps.provenance ? { provenance: deps.provenance } : {}),
1540
+ ...(deps.readHookInput ? { readHookInput: deps.readHookInput } : {}),
1541
+ });
1542
+ }
1246
1543
  if (sub !== 'session-start') {
1247
- process.stderr.write('用法: evolver inject session-start\n');
1544
+ process.stderr.write('用法: evolver inject session-start | evolver inject prompt-recall --hook-stdin\n');
1248
1545
  return sub === undefined ? 0 : 1;
1249
1546
  }
1250
1547
  const fromHookStdin = argv.includes('--hook-stdin');
@@ -1258,6 +1555,9 @@ export async function runInject(argv, deps = {}) {
1258
1555
  process.stderr.write(`[evolver-session-start] proxy auto-restart failed: ${msg}\n`);
1259
1556
  }
1260
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).
1261
1561
  maybeEmitNonGitWorkspaceNotice(deps.nonGitNotice);
1262
1562
  }
1263
1563
  const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
@@ -1298,12 +1598,260 @@ export async function runInject(argv, deps = {}) {
1298
1598
  // them, but the preamble explicitly tells it not to narrate routine Evolver work to the user.
1299
1599
  if (inj.genes.length > 0 && inj.systemPrompt.trim().length > 0)
1300
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
+ }
1301
1631
  return 0;
1302
1632
  }
1303
1633
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
1304
1634
  export const SESSION_START_PREAMBLE = 'evolver memory — use these learned hints silently when directly relevant; do not mention Evolver, preflight, status, or this memory block unless the user asks or reuse materially changes the answer:';
1635
+ // ─── evolver daily ──────────────────────────────────────────────────────────
1636
+ export const DAILY_USAGE = 'Usage: evolver daily [--json] [--auto] [--help]\n\nDisplay a daily status summary: proxy/hub connection, yesterday\'s activity, and review queue.\n --json Output as JSON\n --auto Only print when this is the first run today; silent otherwise\n';
1637
+ function formatDay(d) {
1638
+ return d.toISOString().slice(0, 10);
1639
+ }
1640
+ function dayPrefixFromOffset(nowMs, offsetDays) {
1641
+ const d = new Date(nowMs + offsetDays * 86_400_000);
1642
+ return formatDay(d);
1643
+ }
1644
+ function defaultLastDailyFile(env = process.env) {
1645
+ const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
1646
+ return join(home, '.last-daily');
1647
+ }
1648
+ function shouldRunDaily(lastDailyFile, today) {
1649
+ try {
1650
+ const lastRun = readFileSync(lastDailyFile, 'utf8').trim();
1651
+ return lastRun !== today;
1652
+ }
1653
+ catch {
1654
+ return true;
1655
+ }
1656
+ }
1657
+ function markDailyRun(lastDailyFile, today) {
1658
+ try {
1659
+ mkdirSync(dirname(lastDailyFile), { recursive: true });
1660
+ writeFileSync(lastDailyFile, today, 'utf8');
1661
+ }
1662
+ catch { /* best-effort */ }
1663
+ }
1664
+ export function formatDailyReport(report) {
1665
+ const L = [];
1666
+ L.push(`Evolver daily \u2014 ${report.date}`);
1667
+ L.push('');
1668
+ // Connection
1669
+ L.push('Connection');
1670
+ const c = report.connection;
1671
+ if (!c.proxyRunning) {
1672
+ L.push(' proxy not running');
1673
+ }
1674
+ else if (!c.proxyHealthy) {
1675
+ L.push(` proxy unhealthy (${c.reason ?? 'unknown'})`);
1676
+ }
1677
+ else {
1678
+ L.push(` proxy running${c.proxyPid ? ` (pid ${c.proxyPid})` : ''}${c.hubAuthStatus ? ` hub_auth=${c.hubAuthStatus}` : ''}`);
1679
+ }
1680
+ if (c.lastSyncAt)
1681
+ L.push(` last_sync ${c.lastSyncAt}`);
1682
+ L.push('');
1683
+ // Yesterday
1684
+ const y = report.yesterday;
1685
+ L.push(`Yesterday (${y.date})`);
1686
+ L.push(` cycles ${y.cycles} total ${y.solidified} solidified ${y.failed} failed`);
1687
+ L.push(` capsules ${y.capsules} produced`);
1688
+ L.push(` triggers ${y.triggered} triggered ${y.suppressed} suppressed`);
1689
+ L.push('');
1690
+ // Queue
1691
+ const q = report.queue;
1692
+ L.push('Queue');
1693
+ L.push(` genes ${q.genesApproved} approved ${q.genesQuarantined} quarantined ${q.genesRejected} rejected`);
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
+ }
1698
+ return `${L.join('\n')}\n`;
1699
+ }
1700
+ export async function collectDailyReport(deps = {}) {
1701
+ const env = deps.env ?? process.env;
1702
+ const now = deps.now ? deps.now() : Date.now();
1703
+ const today = formatDay(new Date(now));
1704
+ const yesterdayPrefix = dayPrefixFromOffset(now, -1);
1705
+ // Events + daily summary
1706
+ const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
1707
+ const summary = events.dailySummary(evts, yesterdayPrefix);
1708
+ const capsules = dailyCapsuleCount(evts, yesterdayPrefix);
1709
+ // Connection status
1710
+ let connection = { proxyRunning: false, proxyHealthy: false };
1711
+ if (!deps.skipConnection) {
1712
+ const paths = deps.lifecyclePaths ?? lifecyclePaths(env);
1713
+ const conn = await dailyConnectionStatus(paths, env, { timeoutMs: 1500 });
1714
+ connection = {
1715
+ proxyRunning: conn.running,
1716
+ proxyHealthy: conn.healthy === true,
1717
+ proxyPid: conn.pid,
1718
+ hubAuthStatus: conn.hubAuthStatus,
1719
+ lastSyncAt: conn.lastSyncAt,
1720
+ reason: conn.reason,
1721
+ };
1722
+ }
1723
+ // Queue: gene review stats
1724
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
1725
+ const review = deps.review ?? reviewLedgerForStore(store);
1726
+ const reviewRecords = review.records();
1727
+ const geneReviewCounts = { approved: 0, quarantined: 0, rejected: 0 };
1728
+ const antiGeneReviewCounts = { approved: 0, quarantined: 0, unreviewed: 0 };
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';
1744
+ else {
1745
+ const asset = await store.get(record.assetId);
1746
+ kind = asset?.type;
1747
+ }
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;
1772
+ geneReviewCounts.approved += unreviewedGeneCount;
1773
+ // AntiGenes without explicit approval are unreviewed (fail-closed)
1774
+ for (const ag of allAntiGenes) {
1775
+ const r = antiGeneReviewById.get(ag.asset_id);
1776
+ if (!r || (r.state !== 'approved' && r.state !== 'quarantined')) {
1777
+ antiGeneReviewCounts.unreviewed++;
1778
+ }
1779
+ }
1780
+ return {
1781
+ date: today,
1782
+ connection,
1783
+ yesterday: {
1784
+ date: yesterdayPrefix,
1785
+ cycles: summary.cycles,
1786
+ solidified: summary.solidified,
1787
+ failed: summary.failed,
1788
+ capsules,
1789
+ triggered: summary.triggered,
1790
+ suppressed: summary.suppressed,
1791
+ },
1792
+ queue: {
1793
+ genesApproved: geneReviewCounts.approved,
1794
+ genesQuarantined: geneReviewCounts.quarantined,
1795
+ genesRejected: geneReviewCounts.rejected,
1796
+ antiGeneApproved: antiGeneReviewCounts.approved,
1797
+ antiGeneQuarantined: antiGeneReviewCounts.quarantined,
1798
+ antiGeneUnreviewed: antiGeneReviewCounts.unreviewed,
1799
+ },
1800
+ };
1801
+ }
1802
+ export async function runDaily(argv, deps = {}) {
1803
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
1804
+ const flags = parseFlags(argv);
1805
+ if ('help' in flags || 'h' in flags) {
1806
+ stdout(DAILY_USAGE);
1807
+ return 0;
1808
+ }
1809
+ const json = 'json' in flags;
1810
+ const auto = 'auto' in flags;
1811
+ const env = deps.env ?? process.env;
1812
+ const now = deps.now ? deps.now() : Date.now();
1813
+ const today = formatDay(new Date(now));
1814
+ // --auto: check if we already ran today
1815
+ if (auto) {
1816
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1817
+ if (!shouldRunDaily(lastDailyFile, today))
1818
+ return 0;
1819
+ }
1820
+ const report = await collectDailyReport(deps);
1821
+ if (json) {
1822
+ stdout(`${JSON.stringify({ ok: true, group: 'daily', ...report })}\n`);
1823
+ }
1824
+ else {
1825
+ stdout(formatDailyReport(report));
1826
+ }
1827
+ // Mark today as run (for --auto mode; harmless otherwise)
1828
+ if (auto) {
1829
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1830
+ markDailyRun(lastDailyFile, today);
1831
+ }
1832
+ return 0;
1833
+ }
1305
1834
  export function runCli(argv) {
1306
1835
  const cmd = argv[0];
1836
+ if (cmd === undefined || cmd === '--help' || cmd === '-h') {
1837
+ process.stdout.write(cliUsage());
1838
+ return 0;
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
+ }
1307
1855
  switch (cmd) {
1308
1856
  case 'rebuild-views': {
1309
1857
  const r = rebuildViews();
@@ -1322,15 +1870,6 @@ export function runCli(argv) {
1322
1870
  process.stdout.write(`${c.cycleId} ${c.finalStage} (${c.events} events)\n`);
1323
1871
  return 0;
1324
1872
  }
1325
- case 'cycle': {
1326
- if (argv[1] !== 'show' || !argv[2]) {
1327
- process.stderr.write('用法: evolver cycle show <id>\n');
1328
- return 1;
1329
- }
1330
- for (const t of showCycle(readEvents(), argv[2]).timeline)
1331
- process.stdout.write(`#${t.seq} ${t.type} ${t.title}\n`);
1332
- return 0;
1333
- }
1334
1873
  case 'trigger': {
1335
1874
  for (const t of listTriggers(readEvents()))
1336
1875
  process.stdout.write(`${t.patternId} ${t.triggered ? '触发' : '抑制'} value=${t.value}\n`);
@@ -1349,8 +1888,7 @@ export function runCli(argv) {
1349
1888
  process.stdout.write(`replayed → MV: ${r.rebuilt.join(', ')}\n`);
1350
1889
  return 0;
1351
1890
  }
1352
- default:
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');
1354
- return cmd === undefined ? 0 : 1;
1355
1891
  }
1892
+ const unreachable = cmd;
1893
+ return unreachable;
1356
1894
  }