@evomap/evolver-cli 2.0.0-beta.8 → 2.0.0

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 (91) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillAdmission.d.ts +13 -0
  26. package/dist/distillAdmission.js +35 -0
  27. package/dist/distillObserver.js +4 -6
  28. package/dist/distillPrimitives.d.ts +11 -12
  29. package/dist/distillPrimitives.js +115 -21
  30. package/dist/doctor.js +120 -11
  31. package/dist/identityHome.d.ts +9 -0
  32. package/dist/identityHome.js +47 -0
  33. package/dist/index.d.ts +70 -40
  34. package/dist/index.js +586 -200
  35. package/dist/learningTrace.d.ts +15 -0
  36. package/dist/learningTrace.js +73 -0
  37. package/dist/lifecycle.d.ts +67 -1
  38. package/dist/lifecycle.js +738 -44
  39. package/dist/localMemoryGraph.d.ts +90 -3
  40. package/dist/localMemoryGraph.js +2031 -231
  41. package/dist/login.d.ts +1 -1
  42. package/dist/login.js +3 -3
  43. package/dist/materialPackage.js +3 -6
  44. package/dist/materialSnapshot.d.ts +9 -1
  45. package/dist/materialSnapshot.js +23 -6
  46. package/dist/memoryGraphOps.d.ts +8 -0
  47. package/dist/memoryGraphOps.js +140 -0
  48. package/dist/migrate/assetFormatMap.d.ts +61 -0
  49. package/dist/migrate/assetFormatMap.js +53 -0
  50. package/dist/migrate/envTranslate.d.ts +26 -0
  51. package/dist/migrate/envTranslate.js +147 -0
  52. package/dist/migrate/fieldMap.d.ts +4 -2
  53. package/dist/migrate/fieldMap.js +9 -5
  54. package/dist/migrate/oauthImport.d.ts +66 -0
  55. package/dist/migrate/oauthImport.js +667 -0
  56. package/dist/migrate/v1Import.d.ts +92 -1
  57. package/dist/migrate/v1Import.js +1481 -141
  58. package/dist/promptRecallHook.d.ts +24 -0
  59. package/dist/promptRecallHook.js +425 -0
  60. package/dist/recallVerifyReport.d.ts +37 -0
  61. package/dist/recallVerifyReport.js +244 -0
  62. package/dist/recipe.d.ts +7 -1
  63. package/dist/recipe.js +426 -56
  64. package/dist/requiredSandboxValidation.d.ts +5 -0
  65. package/dist/requiredSandboxValidation.js +4 -0
  66. package/dist/reuse.d.ts +9 -0
  67. package/dist/reuse.js +159 -58
  68. package/dist/runtimeCapabilities.js +15 -15
  69. package/dist/runtimeSessionSource.d.ts +3 -2
  70. package/dist/runtimeSessionSource.js +63 -11
  71. package/dist/selectionPolicyConfig.d.ts +8 -0
  72. package/dist/selectionPolicyConfig.js +18 -0
  73. package/dist/semanticIdfConfig.d.ts +2 -0
  74. package/dist/semanticIdfConfig.js +4 -0
  75. package/dist/sessionIngest.d.ts +37 -0
  76. package/dist/sessionIngest.js +156 -0
  77. package/dist/setupHooks.js +95 -1
  78. package/dist/skill2gep.d.ts +13 -9
  79. package/dist/skill2gep.js +42 -30
  80. package/dist/skillDistill.d.ts +8 -4
  81. package/dist/skillDistill.js +38 -9
  82. package/dist/solo/mode.js +1 -0
  83. package/dist/sync.d.ts +12 -0
  84. package/dist/sync.js +1246 -151
  85. package/dist/thesis.d.ts +1 -1
  86. package/dist/thesis.js +20 -3
  87. package/dist/trajectoryExport.js +21 -3
  88. package/dist/v1Compat.d.ts +1 -0
  89. package/dist/v1Compat.js +9 -0
  90. package/dist/workflowRuntime.js +24 -18
  91. package/package.json +11 -8
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
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';
@@ -7,30 +7,22 @@ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
7
  import { makeInjectEmitter } from './autoexec.js';
8
8
  import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from './reviewFilter.js';
9
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
10
- import { assessDraftAdmission, draftGeneCandidate } from './distillPrimitives.js';
11
- import { emitSessionRecall } from './autoRecall.js';
12
- import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
13
- import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
10
+ import { draftGeneCandidate } from './distillPrimitives.js';
11
+ import { assessDraftAdmissionFromStore } from './distillAdmission.js';
12
+ import { parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
13
+ import { closeSync, constants as fsConstants, existsSync, fstatSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, statSync, unlinkSync, writeFileSync, mkdirSync, } from 'node:fs';
14
14
  import { homedir } from 'node:os';
15
- import { dirname, join, resolve } from 'node:path';
16
- import { importV1 } from './migrate/v1Import.js';
15
+ import { dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
16
+ import { applyImportV1Plan, planImportV1 } from './migrate/v1Import.js';
17
17
  import { explicitRecipeHomes } from './recipe.js';
18
- import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
18
+ import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled, dailyConnectionStatus, lifecyclePaths } from './lifecycle.js';
19
19
  import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
20
20
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
21
21
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
22
- /**
23
- * Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
24
- * one place so the recorded Material and any future cycle consumer agree on the group name.
25
- */
26
- const INGEST_CONSUMER_GROUP = 'cycle';
27
- function resolveIngestDeps(deps) {
28
- return {
29
- materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
30
- watermarkStore: deps.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath()),
31
- ingestor: deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
32
- };
33
- }
22
+ import { asGeneCandidate, parseDistillOutput } from './autoDistillLlm.js';
23
+ import { runPromptRecallHook } from './promptRecallHook.js';
24
+ import { INGEST_CONSUMER_GROUP, recordSessionMaterial, resolveIngestDeps, toMaterialSourceAgent, } from './sessionIngest.js';
25
+ export { runSessionIngestTick, scanSessionDirs, } from './sessionIngest.js';
34
26
  /** Minimal `--flag value` parser (last wins); bare positionals are ignored. */
35
27
  function parseFlags(argv) {
36
28
  const out = {};
@@ -76,12 +68,13 @@ export function cliUsage() {
76
68
  'Commands:',
77
69
  ' Daemon: proxy, lifecycle, proxy-token, doctor, setup-hooks',
78
70
  ' Evolution: run, cycle, autoexec, solidify, distill, review, thesis',
79
- ' Memory: ingest, inject, recall, reuse, reuse-report, narrative, gene-value',
71
+ ' Memory: ingest, inject, recall, reuse, reuse-report, recall-verify-report',
72
+ ' narrative, gene-value',
80
73
  ' Assets: asset-log, asset-trust, asset-health, material, recipe, skill',
81
- ' Hub: login, logout, phub, sync, publish, fetch, buy, orders, atp',
82
- ' Operations: status, workflow status, cycles, trigger, value, retention, replay, rebuild-views',
83
- ' issue-report',
84
- ' Tools: dashboard, webui, trajectory-export, migrate, verify',
74
+ ' Hub: login, logout, phub, sync, publish, fetch, buy, orders, verify, atp',
75
+ ' Operations: status, daily, workflow status, cycles, trigger, value,',
76
+ ' retention, replay, rebuild-views, issue-report',
77
+ ' Tools: dashboard, webui, trajectory-export, migrate',
85
78
  ' Advanced: anti-gene-benchmark, anti-gene-rollout, reset-local-secret',
86
79
  ' skill-distill, skill-md-update',
87
80
  '',
@@ -229,19 +222,64 @@ export function rebuildViews(opts = {}) {
229
222
  replayer.rebuild(ing.readAll());
230
223
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
231
224
  }
232
- /** migrate import-v1 <v1dir> [outDir] --workspace <path>: v1→v2 read-only migration. */
233
- export async function runMigrate(argv) {
234
- const usage = '用法: evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]\n';
235
- if (argv[0] !== 'import-v1' || !argv[1]) {
225
+ function migrationErrorCode(error) {
226
+ const structured = error;
227
+ const code = typeof structured?.code === 'string' ? structured.code : '';
228
+ if (code === 'LOCAL_ASSET_STORE_SNAPSHOT_CHANGED')
229
+ return 'migration_target_changed';
230
+ if (code === 'FROZEN_ASSET_ID_COLLISION')
231
+ return 'migration_asset_id_collision';
232
+ if (code === 'CORRUPT_LOCAL_ASSET_STORE')
233
+ return 'migration_corrupt_target';
234
+ if (code === 'LOCAL_ASSET_STORE_SNAPSHOT_LIMIT')
235
+ return 'migration_target_limit';
236
+ if (/^[a-z][a-z0-9_]{0,127}$/.test(code))
237
+ return `migration_${code}`;
238
+ const message = typeof structured?.message === 'string' ? structured.message : '';
239
+ return /^[a-z][a-z0-9_]{0,127}$/.test(message) ? message : 'migration_failed';
240
+ }
241
+ function writeMigrationFailure(code, json) {
242
+ process.stderr.write(json
243
+ ? `${JSON.stringify({ ok: false, error: code })}\n`
244
+ : `migrate: ${code}\n`);
245
+ }
246
+ /** migrate import-v1 | migrate env | migrate oauth — V1→V2 migration tools. */
247
+ export async function runMigrate(argv, deps = {}) {
248
+ const usage = [
249
+ 'Usage:',
250
+ ' evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>] [--dry-run] [--json]',
251
+ ' evolver migrate gep-sdk <v1dir> [outDir] [--workspace <path>] [--json] # import-v1 --dry-run alias',
252
+ ' evolver migrate --gep-sdk <v1dir> [outDir] [--workspace <path>] [--json]',
253
+ ' evolver migrate env [--file <dotenv>] [--json] [--write-suggestions <path>] [--no-process-env]',
254
+ ' evolver migrate oauth [--from <oauth_token.json>] [--to <token.json>] [--force] [--dry-run] [--json]',
255
+ '',
256
+ ].join('\n');
257
+ if (argv[0] === '--help' || argv[0] === '-h' || argv.length === 0) {
258
+ process.stdout.write(usage);
259
+ return 0;
260
+ }
261
+ if (argv[0] === 'env') {
262
+ const { runMigrateEnvCommand } = await import('./migrate/envTranslate.js');
263
+ return runMigrateEnvCommand(argv.slice(1));
264
+ }
265
+ if (argv[0] === 'oauth') {
266
+ const { runMigrateOAuthCommand } = await import('./migrate/oauthImport.js');
267
+ return runMigrateOAuthCommand(argv.slice(1));
268
+ }
269
+ const alias = argv[0] === 'gep-sdk' || argv[0] === '--gep-sdk';
270
+ const migrationArgs = alias ? ['import-v1', ...argv.slice(1), '--dry-run'] : [...argv];
271
+ if (migrationArgs[0] !== 'import-v1' || !migrationArgs[1] || migrationArgs[1].startsWith('--')) {
236
272
  process.stderr.write(usage);
237
273
  return 1;
238
274
  }
239
275
  let outDir;
240
276
  let workspace;
241
- for (let index = 2; index < argv.length; index += 1) {
242
- const arg = argv[index] ?? '';
277
+ let dryRun = false;
278
+ let json = false;
279
+ for (let index = 2; index < migrationArgs.length; index += 1) {
280
+ const arg = migrationArgs[index] ?? '';
243
281
  if (arg === '--workspace') {
244
- const value = argv[index + 1];
282
+ const value = migrationArgs[index + 1];
245
283
  if (!value || value.startsWith('--')) {
246
284
  process.stderr.write(usage);
247
285
  return 1;
@@ -256,6 +294,12 @@ export async function runMigrate(argv) {
256
294
  return 1;
257
295
  }
258
296
  }
297
+ else if (arg === '--dry-run') {
298
+ dryRun = true;
299
+ }
300
+ else if (arg === '--json') {
301
+ json = true;
302
+ }
259
303
  else if (arg.startsWith('--') || outDir !== undefined) {
260
304
  process.stderr.write(usage);
261
305
  return 1;
@@ -266,13 +310,57 @@ export async function runMigrate(argv) {
266
310
  }
267
311
  const envFile = loadEnvFileFromEnv(process.env);
268
312
  if (envFile.error) {
269
- process.stderr.write('migrate: failed to load EVOLVER_ENV_FILE\n');
313
+ writeMigrationFailure('migration_env_file_load_failed', json);
270
314
  return 1;
271
315
  }
272
316
  const targetDir = outDir ?? events.evomapHome();
273
- const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
274
- const rep = await importV1(argv[1], store, targetDir, workspace ? { workspace } : {});
275
- process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; memory_graph 归档=${rep.memoryGraphArchived} 可查询=${rep.memoryGraphImported} 延后=${rep.memoryGraphDeferred}\n`);
317
+ const options = { ...deps, ...(workspace ? { workspace } : {}) };
318
+ let plan;
319
+ try {
320
+ plan = await planImportV1(migrationArgs[1], targetDir, options);
321
+ }
322
+ catch (error) {
323
+ writeMigrationFailure(migrationErrorCode(error), json);
324
+ return 1;
325
+ }
326
+ let successOutput;
327
+ try {
328
+ if (dryRun) {
329
+ if (json) {
330
+ successOutput = `${JSON.stringify({ mode: 'dry-run', plan: plan.report })}\n`;
331
+ }
332
+ else {
333
+ const assets = plan.report.assets;
334
+ successOutput = (`Migration plan ${plan.report.planDigest}: Gene=${assets.Gene.candidates} `
335
+ + `Capsule=${assets.Capsule.candidates} Event=${assets.EvolutionEvent.candidates}; `
336
+ + `verified=${assets.Gene.verified + assets.Capsule.verified + assets.EvolutionEvent.verified} `
337
+ + `unverified=${assets.Gene.unverified + assets.Capsule.unverified + assets.EvolutionEvent.unverified}; `
338
+ + `mailbox=${plan.report.mailbox.candidates}; memory_graph=${plan.report.memoryGraph.disposition}\n`);
339
+ }
340
+ }
341
+ else {
342
+ const report = await applyImportV1Plan(plan, undefined, targetDir, options);
343
+ successOutput = json
344
+ ? `${JSON.stringify({ mode: 'apply', plan: plan.report, result: report })}\n`
345
+ : `迁移完成: 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`;
346
+ }
347
+ }
348
+ catch (error) {
349
+ try {
350
+ plan.dispose();
351
+ }
352
+ catch { /* preserve the mapped primary failure */ }
353
+ writeMigrationFailure(migrationErrorCode(error), json);
354
+ return 1;
355
+ }
356
+ try {
357
+ plan.dispose();
358
+ }
359
+ catch {
360
+ writeMigrationFailure('migration_cleanup_failed', json);
361
+ return 1;
362
+ }
363
+ process.stdout.write(successOutput);
276
364
  return 0;
277
365
  }
278
366
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -286,8 +374,107 @@ export function formatAssetLine(a) {
286
374
  : '';
287
375
  return `${a.type.padEnd(15)} ${id} ${desc}`.trimEnd();
288
376
  }
289
- /** asset-log [Gene|Capsule|EvolutionEvent|AntiGene] [limit]: list recent local assets (observability; ported v1 CLI verb). */
290
- export async function runAssetLog(argv, store) {
377
+ const ASSET_CALL_ACTIONS = [
378
+ 'hub_search_hit', 'hub_search_miss',
379
+ 'asset_reuse', 'asset_reference',
380
+ 'asset_publish', 'asset_publish_skip',
381
+ 'asset_inject', 'asset_inject_shadow',
382
+ 'hub_review_submitted', 'hub_review_rejected', 'hub_review_failed',
383
+ ];
384
+ function isAssetCallAction(value) {
385
+ return ASSET_CALL_ACTIONS.includes(value);
386
+ }
387
+ /**
388
+ * Preserve V2's asset-store listing as the default. V1's call audit is available
389
+ * through the explicit `calls` mode so the two contracts do not overload an empty argv.
390
+ */
391
+ export async function runAssetLog(argv, store, deps = {}) {
392
+ const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
393
+ const CALL_FLAGS = ['--run', '--action', '--last', '--since', '--json'];
394
+ const explicitCallMode = argv[0] === 'calls' || argv[0] === '--calls';
395
+ const callMode = explicitCallMode || argv.some((arg) => CALL_FLAGS
396
+ .some((flag) => arg === flag || arg.startsWith(`${flag}=`)));
397
+ const assetMode = !callMode && (argv.length === 0
398
+ || argv[0] === 'assets'
399
+ || argv[0] === '--assets'
400
+ || KINDS.includes(argv[0] ?? '')
401
+ || /^\d+$/.test(argv[0] ?? ''));
402
+ if (assetMode)
403
+ return runAssetList(argv.filter((arg) => arg !== 'assets' && arg !== '--assets'), store);
404
+ if (!callMode)
405
+ return assetLogUsage(`unknown asset-log mode: ${argv[0] ?? '(missing)'}`);
406
+ const opts = {};
407
+ let json = false;
408
+ for (let i = explicitCallMode ? 1 : 0; i < argv.length; i += 1) {
409
+ const arg = argv[i];
410
+ if (!explicitCallMode && KINDS.includes(arg ?? ''))
411
+ continue;
412
+ if (arg === '--json') {
413
+ json = true;
414
+ continue;
415
+ }
416
+ const parsed = assetLogFlagValue(argv, i, '--run');
417
+ if (parsed) {
418
+ opts.run_id = parsed.value;
419
+ i += parsed.consumed;
420
+ continue;
421
+ }
422
+ const action = assetLogFlagValue(argv, i, '--action');
423
+ if (action) {
424
+ if (!isAssetCallAction(action.value))
425
+ return assetLogUsage(`invalid --action: ${action.value}`);
426
+ opts.action = action.value;
427
+ i += action.consumed;
428
+ continue;
429
+ }
430
+ const last = assetLogFlagValue(argv, i, '--last');
431
+ if (last) {
432
+ if (!/^\d+$/.test(last.value) || Number(last.value) < 1)
433
+ return assetLogUsage(`invalid --last: ${last.value}`);
434
+ opts.last = Number(last.value);
435
+ i += last.consumed;
436
+ continue;
437
+ }
438
+ const since = assetLogFlagValue(argv, i, '--since');
439
+ if (since) {
440
+ if (!Number.isFinite(Date.parse(since.value)))
441
+ return assetLogUsage(`invalid --since: ${since.value}`);
442
+ opts.since = since.value;
443
+ i += since.consumed;
444
+ continue;
445
+ }
446
+ return assetLogUsage(`unknown asset-log argument: ${arg ?? '(missing)'}`);
447
+ }
448
+ const logPath = deps.logPath ?? events.assetCallLogPath();
449
+ const callLog = deps.callLog ?? new hubNs.AssetCallLog(logPath);
450
+ if (json) {
451
+ process.stdout.write(`${JSON.stringify(callLog.read(opts), null, 2)}\n`);
452
+ return 0;
453
+ }
454
+ const summary = callLog.summarize(opts);
455
+ process.stdout.write('\n[Asset Call Log]\n');
456
+ process.stdout.write(` Total entries: ${summary.total_entries}\n`);
457
+ process.stdout.write(` Unique assets: ${summary.unique_assets}\n`);
458
+ process.stdout.write(` Unique runs: ${summary.unique_runs}\n`);
459
+ process.stdout.write(' By action:\n');
460
+ for (const [action, count] of Object.entries(summary.by_action)) {
461
+ process.stdout.write(` ${action}: ${count}\n`);
462
+ }
463
+ if (summary.entries.length === 0) {
464
+ process.stdout.write('\n No entries found.\n\n');
465
+ return 0;
466
+ }
467
+ process.stdout.write('\n Recent entries:\n');
468
+ for (const entry of summary.entries.slice(-10)) {
469
+ const timestamp = entry.timestamp ? entry.timestamp.slice(0, 19) : '?';
470
+ const asset = entry.asset_id ? `${entry.asset_id.slice(0, 20)}...` : '(none)';
471
+ const signals = Array.isArray(entry.signals) ? entry.signals.slice(0, 3).join(', ') : '';
472
+ process.stdout.write(` [${timestamp}] ${entry.action || '?'} asset=${asset} score=${entry.score ?? '-'} mode=${entry.mode ?? '-'} signals=[${signals}] run=${entry.run_id ?? '-'}\n`);
473
+ }
474
+ process.stdout.write('\n');
475
+ return 0;
476
+ }
477
+ async function runAssetList(argv, store) {
291
478
  const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
292
479
  let kind;
293
480
  let limit = 20;
@@ -296,6 +483,8 @@ export async function runAssetLog(argv, store) {
296
483
  kind = a;
297
484
  else if (/^\d+$/.test(a))
298
485
  limit = Number(a);
486
+ else
487
+ return assetLogUsage(`unknown asset list argument: ${a}`);
299
488
  }
300
489
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
301
490
  const assets = await s.list(kind, limit);
@@ -307,6 +496,120 @@ export async function runAssetLog(argv, store) {
307
496
  process.stdout.write(formatAssetLine(a) + '\n');
308
497
  return 0;
309
498
  }
499
+ function assetLogFlagValue(argv, index, flag) {
500
+ const arg = argv[index];
501
+ if (arg?.startsWith(`${flag}=`)) {
502
+ const value = arg.slice(flag.length + 1);
503
+ return value ? { value, consumed: 0 } : null;
504
+ }
505
+ if (arg !== flag)
506
+ return null;
507
+ const value = argv[index + 1];
508
+ return value && !value.startsWith('--') ? { value, consumed: 1 } : null;
509
+ }
510
+ function assetLogUsage(error) {
511
+ 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`);
512
+ return 1;
513
+ }
514
+ const DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES = 1024 * 1024;
515
+ function responseFileArg(argv) {
516
+ for (let index = 0; index < argv.length; index += 1) {
517
+ const arg = argv[index];
518
+ if (arg?.startsWith('--response-file='))
519
+ return arg.slice('--response-file='.length);
520
+ if (arg === '--response-file')
521
+ return argv[index + 1] ?? '';
522
+ }
523
+ return undefined;
524
+ }
525
+ function pathIsWithin(root, target) {
526
+ const rel = relative(root, target);
527
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
528
+ }
529
+ function sameResponseFileIdentity(left, right) {
530
+ const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
531
+ if (hasStableFileId)
532
+ return left.dev === right.dev && left.ino === right.ino;
533
+ // Some filesystems do not expose dev/ino. Birth time + mode is the strongest portable fallback Node provides.
534
+ return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
535
+ }
536
+ function sameResponseFileSnapshot(left, right) {
537
+ return sameResponseFileIdentity(left, right)
538
+ && left.size === right.size
539
+ && left.mtimeNs === right.mtimeNs
540
+ && left.ctimeNs === right.ctimeNs;
541
+ }
542
+ function readResponseFileDescriptor(fd, expectedSize) {
543
+ const content = Buffer.alloc(expectedSize);
544
+ let offset = 0;
545
+ while (offset < expectedSize) {
546
+ const bytesRead = readSync(fd, content, offset, expectedSize - offset, offset);
547
+ if (bytesRead === 0)
548
+ throw new Error('response-file changed while being read (truncated)');
549
+ offset += bytesRead;
550
+ }
551
+ const extra = Buffer.allocUnsafe(1);
552
+ if (readSync(fd, extra, 0, 1, expectedSize) !== 0) {
553
+ throw new Error('response-file changed while being read (grew beyond the validated size)');
554
+ }
555
+ return content.toString('utf8');
556
+ }
557
+ function candidateFromResponseFile(path, deps) {
558
+ if (!path)
559
+ throw new Error('response-file path is empty');
560
+ const requestedRoot = resolve(deps.responseFileRoot ?? process.cwd());
561
+ const root = realpathSync(requestedRoot);
562
+ const requested = resolve(requestedRoot, path);
563
+ if (!pathIsWithin(requestedRoot, requested))
564
+ throw new Error('response-file is outside the allowed root');
565
+ const beforeOpen = lstatSync(requested, { bigint: true });
566
+ if (!beforeOpen.isFile() || beforeOpen.isSymbolicLink())
567
+ throw new Error('response-file must be a regular non-symlink file');
568
+ const canonical = realpathSync(requested);
569
+ if (!pathIsWithin(root, canonical))
570
+ throw new Error('response-file resolves outside the allowed root');
571
+ const configuredMax = deps.maxResponseFileBytes ?? DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
572
+ const maxBytes = Number.isSafeInteger(Math.floor(configuredMax)) && configuredMax > 0
573
+ ? Math.floor(configuredMax)
574
+ : DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
575
+ if (beforeOpen.size > BigInt(maxBytes))
576
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
577
+ deps.responseFileReadTestHook?.('before-open', canonical);
578
+ const noFollow = process.platform !== 'win32' && typeof fsConstants.O_NOFOLLOW === 'number'
579
+ ? fsConstants.O_NOFOLLOW
580
+ : 0;
581
+ const fd = openSync(canonical, fsConstants.O_RDONLY | noFollow);
582
+ let raw;
583
+ try {
584
+ const opened = fstatSync(fd, { bigint: true });
585
+ if (!opened.isFile())
586
+ throw new Error('response-file must be a regular file');
587
+ if (!sameResponseFileSnapshot(beforeOpen, opened))
588
+ throw new Error('response-file changed before it could be opened');
589
+ if (opened.size > BigInt(maxBytes))
590
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
591
+ deps.responseFileReadTestHook?.('after-open', canonical);
592
+ raw = readResponseFileDescriptor(fd, Number(opened.size));
593
+ const afterRead = fstatSync(fd, { bigint: true });
594
+ if (!sameResponseFileSnapshot(opened, afterRead))
595
+ throw new Error('response-file changed while being read');
596
+ const afterPath = lstatSync(requested, { bigint: true });
597
+ if (!afterPath.isFile() || afterPath.isSymbolicLink() || !sameResponseFileSnapshot(afterRead, afterPath)) {
598
+ throw new Error('response-file path changed while being read');
599
+ }
600
+ const canonicalAfterRead = realpathSync(requested);
601
+ if (!pathIsWithin(root, canonicalAfterRead) || canonicalAfterRead !== canonical) {
602
+ throw new Error('response-file path changed outside the allowed root');
603
+ }
604
+ }
605
+ finally {
606
+ closeSync(fd);
607
+ }
608
+ const candidate = asGeneCandidate(parseDistillOutput(raw));
609
+ if (!candidate)
610
+ throw new Error('response-file does not contain a valid Gene JSON object');
611
+ return candidate;
612
+ }
310
613
  /**
311
614
  * distill: gate a learned approach into the gene pool (ported v1 CLI verb). Runs the structural intake
312
615
  * (schema + dedup + asset_id) and, only if it passes, writes the gene to the store. The agent/runtime is
@@ -315,17 +618,30 @@ export async function runAssetLog(argv, store) {
315
618
  */
316
619
  export async function runDistill(argv, store, deps = {}) {
317
620
  const f = parseFlags(argv);
318
- const candidate = {
319
- ...(f['id'] ? { id: f['id'] } : {}),
320
- category: f['category'] ?? 'innovate',
321
- signals_match: splitList(f['signals'], /,/),
322
- strategy: splitList(f['strategy'], /[;\n]/),
323
- ...(f['summary'] ? { summary: f['summary'] } : {}),
324
- // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
325
- // `manual` per V1 #302 classifyProvenance.
326
- generation_meta: { source: 'manual' },
327
- };
328
- if (candidate.signals_match.length === 0 || candidate.strategy.length === 0) {
621
+ const responseFile = responseFileArg(argv);
622
+ let candidate;
623
+ if (responseFile !== undefined) {
624
+ try {
625
+ candidate = candidateFromResponseFile(responseFile, deps);
626
+ }
627
+ catch (error) {
628
+ process.stderr.write(`[Distill] response-file error: ${error instanceof Error ? error.message : String(error)}\n`);
629
+ return 2;
630
+ }
631
+ }
632
+ else {
633
+ candidate = {
634
+ ...(f['id'] ? { id: f['id'] } : {}),
635
+ category: f['category'] ?? 'innovate',
636
+ signals_match: splitList(f['signals'], /,/),
637
+ strategy: splitList(f['strategy'], /[;\n]/),
638
+ ...(f['summary'] ? { summary: f['summary'] } : {}),
639
+ // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
640
+ // `manual` per V1 #302 classifyProvenance.
641
+ generation_meta: { source: 'manual' },
642
+ };
643
+ }
644
+ if ((candidate.signals_match ?? []).length === 0 || (candidate.strategy ?? []).length === 0) {
329
645
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
330
646
  return 1;
331
647
  }
@@ -340,15 +656,34 @@ export async function runDistill(argv, store, deps = {}) {
340
656
  process.stderr.write(`distill 拒绝: ${r.errors.join('; ')}\n`);
341
657
  return 1;
342
658
  }
343
- await s.put(r.gene);
344
- // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
345
659
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
346
- await ingestor.ingest({
347
- type: 'actor.human.teach',
348
- payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
349
- human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
350
- actor: { kind: 'human', id: operatorActorId() },
351
- });
660
+ if (responseFile !== undefined) {
661
+ // The gene is the commit point. Audit first (idempotently), quarantine second, then persist last so any
662
+ // partial failure remains retryable and can never expose an unaudited machine-produced gene in the pool.
663
+ const assetId = String(r.gene.asset_id);
664
+ const alreadyAudited = ingestor.readAll().some((event) => event.type === 'gene.distilled'
665
+ && String(event.payload?.['assetId'] ?? '') === assetId);
666
+ if (!alreadyAudited) {
667
+ await ingestor.ingest({
668
+ type: 'gene.distilled',
669
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, source: 'cli-response-file' },
670
+ human: { title: `LLM response-file distilled gene ${r.gene.id}`, severity: 'info' },
671
+ actor: { kind: 'machine', id: 'cli-response-file' },
672
+ });
673
+ }
674
+ reviewLedgerForStore(s).quarantineIfAbsent(assetId, 'LLM response-file distillation - review before use');
675
+ await s.put(r.gene);
676
+ }
677
+ else {
678
+ await s.put(r.gene);
679
+ // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
680
+ await ingestor.ingest({
681
+ type: 'actor.human.teach',
682
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
683
+ human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
684
+ actor: { kind: 'human', id: operatorActorId() },
685
+ });
686
+ }
352
687
  process.stdout.write(`distilled gene ${r.gene.id} (${String(r.gene.asset_id).slice(0, 19)}…) → pool\n`);
353
688
  return 0;
354
689
  }
@@ -370,12 +705,6 @@ function printTraceSignals(file, turnCount, sigs) {
370
705
  process.stdout.write(` [${s.strength}/${s.kind}] ${s.text.replace(/\s+/g, ' ').trim().slice(0, 160)}\n`);
371
706
  }
372
707
  }
373
- /** The runtime agents Material.sourceAgent can represent (closed enum on the schema). */
374
- const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'antigravity', 'kimi', 'kiro', 'opencode', 'generic-chat']);
375
- /** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
376
- function toMaterialSourceAgent(agent) {
377
- return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
378
- }
379
708
  /**
380
709
  * Is a Material for this EXACT file state already on the substrate? A Material's identity is its ULID, so `put`
381
710
  * cannot dedup across runs (each build mints a fresh id). Without this, a crash-retry — where a prior run put the
@@ -395,50 +724,6 @@ function materialExistsFor(store, sourcePath, wm) {
395
724
  }
396
725
  return false;
397
726
  }
398
- /**
399
- * Record a session log as Material on the M1 substrate (idempotent by file watermark), then emit a
400
- * `material.batch_ready` root_event so the AE is not bypassed. Re-ingesting the same UNCHANGED file records
401
- * no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
402
- * Returns whether new material landed + its materialId so the caller can report it.
403
- */
404
- async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1, payload, diagnostics) {
405
- const prev = d.watermarkStore.get(absPath);
406
- const scan = materialNs.scanFile(absPath, prev);
407
- // Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
408
- if (prev && !scan.changed)
409
- return { recorded: false, emitted: false };
410
- const m = materialNs.buildMaterial({
411
- sourceAgent,
412
- sourceKind: 'runtime_session',
413
- sourcePath: absPath,
414
- kind: 'session_log',
415
- watermark: scan.watermark,
416
- consumerGroup: INGEST_CONSUMER_GROUP,
417
- ...(payload ? { payload } : {}),
418
- });
419
- // Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
420
- // watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
421
- const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
422
- if (isNew)
423
- await d.materialStore.put(m);
424
- const parseDiagnostics = diagnostics && diagnostics.invalidJson > 0
425
- ? { rowsScanned: diagnostics.rowsScanned, rowsRead: diagnostics.rowsRead, invalidJson: diagnostics.invalidJson }
426
- : undefined;
427
- await d.ingestor.ingest({
428
- type: 'material.batch_ready',
429
- payload: { source: absPath, recordCount, signalCount, ...(parseDiagnostics ? { parseDiagnostics } : {}) },
430
- human: {
431
- title: `material 已落地: ${sourceAgent} session`,
432
- ...(parseDiagnostics ? { detail: `skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s)` } : {}),
433
- severity: 'info',
434
- },
435
- actor: { kind: 'machine' },
436
- });
437
- // Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
438
- // stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
439
- d.watermarkStore.set(absPath, scan.watermark);
440
- return { recorded: isNew, emitted: true, materialId: m.materialId };
441
- }
442
727
  /**
443
728
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
444
729
  * telemetry, so it carries sourceKind=proxy_trace + kind=llm_trace and NO sourceAgent — the origin taxonomy
@@ -473,90 +758,6 @@ async function recordTraceMaterial(absPath, signalCount, d) {
473
758
  d.watermarkStore.set(absPath, scan.watermark);
474
759
  return { recorded: isNew, materialId: m.materialId };
475
760
  }
476
- /**
477
- * Recursively enumerate recognized runtime-session sources under the given dirs — the daemon's auto-distill
478
- * producer source (#106). This includes text session files handled by runtime adapters (`*.jsonl` and Gemini
479
- * `*.json`) plus Cursor's sqlite `state.vscdb`. A missing/permission-denied dir is silently skipped (a daemon
480
- * must not crash on an absent home dir).
481
- */
482
- export function scanSessionDirs(dirs) {
483
- const out = [];
484
- for (const dir of dirs) {
485
- let entries;
486
- try {
487
- entries = readdirSync(resolve(dir), { recursive: true });
488
- }
489
- catch {
490
- continue;
491
- } // dir absent / unreadable → skip
492
- for (const e of entries) {
493
- const file = join(resolve(dir), e);
494
- if (isRuntimeSessionSourcePath(file))
495
- out.push(file);
496
- }
497
- }
498
- return out;
499
- }
500
- function sortedStrings(values) {
501
- return [...new Set([...values].map(String).filter(Boolean))].sort();
502
- }
503
- /**
504
- * One producer tick for the auto-distill loop (#106 slice 1): scan `dirs` for session logs and record any
505
- * NEW/CHANGED file as `runtime_session` Material via the injected (bus) Ingestor — which emits
506
- * `material.batch_ready`, the event the distillObserver claims off. Idempotent per file (watermark cursor), so
507
- * re-scanning an unchanged tree records nothing. Pure producer: it does NOT distill (the observer does). Returns
508
- * how many files landed new material. Inject `deps.ingestor = new Ingestor({ sink: bus })` so the event reaches
509
- * the daemon's ObserverBus; defaults to live paths otherwise.
510
- */
511
- export async function runSessionIngestTick(dirs, deps = {}) {
512
- const d = resolveIngestDeps(deps);
513
- let recorded = 0;
514
- const sourceAgents = new Set();
515
- const signalKinds = new Set();
516
- const signalStrengths = new Set();
517
- let invalidJsonRows = 0;
518
- // #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
519
- // experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
520
- // (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
521
- const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
522
- for (const file of scanSessionDirs(dirs)) {
523
- try {
524
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(file);
525
- const parsedSources = parsed.sources;
526
- const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
527
- if (parsedSources.length === 0 || !agent)
528
- continue; // not a recognized, schema-recordable runtime-session source
529
- const sigsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
530
- const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
531
- const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length, snapshot, parsed.diagnostics);
532
- if (r.emitted)
533
- invalidJsonRows += parsed.diagnostics.invalidJson;
534
- if (r.recorded) {
535
- recorded += 1;
536
- sourceAgents.add(agent);
537
- for (const sigs of sigsBySource) {
538
- for (const sig of sigs) {
539
- signalKinds.add(sig.kind);
540
- signalStrengths.add(sig.strength);
541
- }
542
- }
543
- }
544
- if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
545
- // Drop meta turns (heartbeats/empty) before judging, same as `evolver recall` — counting them would skew overlap.
546
- const turns = parsedSources[0].turns.filter((t) => !t.isMeta).map((t) => ({ role: t.role, text: t.text }));
547
- await emitSessionRecall(file, turns, { ingestor: d.ingestor });
548
- }
549
- }
550
- catch { /* unreadable / unparseable file → skip, never break the scan */ }
551
- }
552
- return {
553
- recorded,
554
- sourceAgents: sortedStrings(sourceAgents),
555
- signalKinds: sortedStrings(signalKinds),
556
- signalStrengths: sortedStrings(signalStrengths),
557
- ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
558
- };
559
- }
560
761
  /**
561
762
  * Read + parse one or more trace JSONL files, record each as proxy_trace Material on the M1 substrate (#95,
562
763
  * idempotent by file watermark), and report their signals as a single batch.
@@ -654,7 +855,7 @@ export async function runIngest(argv, store, deps = {}, review) {
654
855
  let parsedSources;
655
856
  let parseDiagnostics;
656
857
  try {
657
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
858
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path, undefined, deps.nativeSessionHome);
658
859
  parsedSources = parsed.sources;
659
860
  parseDiagnostics = parsed.diagnostics;
660
861
  }
@@ -706,10 +907,7 @@ export async function runIngest(argv, store, deps = {}, review) {
706
907
  // --distill: assemble + intake UNPROVEN draft genes per runtime session (shared draft logic — see distillPrimitives).
707
908
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
708
909
  const accepted = [];
709
- let existing = (await s.list('Gene', 1000)).map((g) => ({
710
- id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
711
- signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
712
- }));
910
+ const acceptedSignals = [];
713
911
  let candidateCount = 0;
714
912
  let admissionSkipped = 0;
715
913
  let lastAdmissionSkipReason = '';
@@ -721,7 +919,7 @@ export async function runIngest(argv, store, deps = {}, review) {
721
919
  // Same value/novelty gate as the live distillObserver (#562): without it, a bulk ingest over session
722
920
  // history floods the human review queue with thin / near-duplicate drafts (118 in one run). A non-admit
723
921
  // is a deliberate skip — the rest of the batch still distills; intake below stays the structural gate.
724
- const admission = assessDraftAdmission(candidate, existing);
922
+ const { admission, existing } = await assessDraftAdmissionFromStore(s, candidate, acceptedSignals);
725
923
  if (!admission.admit) {
726
924
  admissionSkipped += 1;
727
925
  lastAdmissionSkipReason = admission.reason ?? '';
@@ -734,7 +932,7 @@ export async function runIngest(argv, store, deps = {}, review) {
734
932
  return 1;
735
933
  }
736
934
  accepted.push({ source, candidate, gene: r.gene });
737
- existing = [...existing, { id: r.gene.id, signals_match: r.gene.signals_match }];
935
+ acceptedSignals.push({ id: r.gene.id, signals_match: r.gene.signals_match });
738
936
  }
739
937
  if (accepted.length === 0) {
740
938
  if (candidateCount > 0 && admissionSkipped === candidateCount) {
@@ -1328,8 +1526,16 @@ async function readHookSessionId(read) {
1328
1526
  */
1329
1527
  export async function runInject(argv, deps = {}) {
1330
1528
  const sub = argv[0];
1529
+ if (sub === 'prompt-recall') {
1530
+ return runPromptRecallHook(argv.slice(1), {
1531
+ ...(deps.store ? { store: deps.store } : {}),
1532
+ ...(deps.review ? { review: deps.review } : {}),
1533
+ ...(deps.provenance ? { provenance: deps.provenance } : {}),
1534
+ ...(deps.readHookInput ? { readHookInput: deps.readHookInput } : {}),
1535
+ });
1536
+ }
1331
1537
  if (sub !== 'session-start') {
1332
- process.stderr.write('用法: evolver inject session-start\n');
1538
+ process.stderr.write('用法: evolver inject session-start | evolver inject prompt-recall --hook-stdin\n');
1333
1539
  return sub === undefined ? 0 : 1;
1334
1540
  }
1335
1541
  const fromHookStdin = argv.includes('--hook-stdin');
@@ -1387,6 +1593,186 @@ export async function runInject(argv, deps = {}) {
1387
1593
  }
1388
1594
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
1389
1595
  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:';
1596
+ // ─── evolver daily ──────────────────────────────────────────────────────────
1597
+ 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';
1598
+ function formatDay(d) {
1599
+ return d.toISOString().slice(0, 10);
1600
+ }
1601
+ function dayPrefixFromOffset(nowMs, offsetDays) {
1602
+ const d = new Date(nowMs + offsetDays * 86_400_000);
1603
+ return formatDay(d);
1604
+ }
1605
+ function defaultLastDailyFile(env = process.env) {
1606
+ const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
1607
+ return join(home, '.last-daily');
1608
+ }
1609
+ function shouldRunDaily(lastDailyFile, today) {
1610
+ try {
1611
+ const lastRun = readFileSync(lastDailyFile, 'utf8').trim();
1612
+ return lastRun !== today;
1613
+ }
1614
+ catch {
1615
+ return true;
1616
+ }
1617
+ }
1618
+ function markDailyRun(lastDailyFile, today) {
1619
+ try {
1620
+ mkdirSync(dirname(lastDailyFile), { recursive: true });
1621
+ writeFileSync(lastDailyFile, today, 'utf8');
1622
+ }
1623
+ catch { /* best-effort */ }
1624
+ }
1625
+ export function formatDailyReport(report) {
1626
+ const L = [];
1627
+ L.push(`Evolver daily \u2014 ${report.date}`);
1628
+ L.push('');
1629
+ // Connection
1630
+ L.push('Connection');
1631
+ const c = report.connection;
1632
+ if (!c.proxyRunning) {
1633
+ L.push(' proxy not running');
1634
+ }
1635
+ else if (!c.proxyHealthy) {
1636
+ L.push(` proxy unhealthy (${c.reason ?? 'unknown'})`);
1637
+ }
1638
+ else {
1639
+ L.push(` proxy running${c.proxyPid ? ` (pid ${c.proxyPid})` : ''}${c.hubAuthStatus ? ` hub_auth=${c.hubAuthStatus}` : ''}`);
1640
+ }
1641
+ if (c.lastSyncAt)
1642
+ L.push(` last_sync ${c.lastSyncAt}`);
1643
+ L.push('');
1644
+ // Yesterday
1645
+ const y = report.yesterday;
1646
+ L.push(`Yesterday (${y.date})`);
1647
+ L.push(` cycles ${y.cycles} total ${y.solidified} solidified ${y.failed} failed`);
1648
+ L.push(` capsules ${y.capsules} produced`);
1649
+ L.push(` triggers ${y.triggered} triggered ${y.suppressed} suppressed`);
1650
+ L.push('');
1651
+ // Queue
1652
+ const q = report.queue;
1653
+ L.push('Queue');
1654
+ L.push(` genes ${q.genesApproved} approved ${q.genesQuarantined} quarantined ${q.genesRejected} rejected`);
1655
+ L.push(` anti-gene ${q.antiGeneApproved} approved ${q.antiGeneQuarantined} quarantined ${q.antiGeneUnreviewed} unreviewed`);
1656
+ return `${L.join('\n')}\n`;
1657
+ }
1658
+ export async function collectDailyReport(deps = {}) {
1659
+ const env = deps.env ?? process.env;
1660
+ const now = deps.now ? deps.now() : Date.now();
1661
+ const today = formatDay(new Date(now));
1662
+ const yesterdayPrefix = dayPrefixFromOffset(now, -1);
1663
+ // Events + daily summary
1664
+ const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
1665
+ const summary = events.dailySummary(evts, yesterdayPrefix);
1666
+ const capsules = dailyCapsuleCount(evts, yesterdayPrefix);
1667
+ // Connection status
1668
+ let connection = { proxyRunning: false, proxyHealthy: false };
1669
+ if (!deps.skipConnection) {
1670
+ const paths = deps.lifecyclePaths ?? lifecyclePaths(env);
1671
+ const conn = await dailyConnectionStatus(paths, env, { timeoutMs: 1500 });
1672
+ connection = {
1673
+ proxyRunning: conn.running,
1674
+ proxyHealthy: conn.healthy === true,
1675
+ proxyPid: conn.pid,
1676
+ hubAuthStatus: conn.hubAuthStatus,
1677
+ lastSyncAt: conn.lastSyncAt,
1678
+ reason: conn.reason,
1679
+ };
1680
+ }
1681
+ // Queue: gene review stats
1682
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
1683
+ const review = deps.review ?? reviewLedgerForStore(store);
1684
+ const reviewRecords = review.records();
1685
+ const geneReviewCounts = { approved: 0, quarantined: 0, rejected: 0 };
1686
+ const antiGeneReviewCounts = { approved: 0, quarantined: 0, unreviewed: 0 };
1687
+ // Build asset ID to type mapping
1688
+ const allGenes = await store.list('Gene', 10_000);
1689
+ const allAntiGenes = await store.list('AntiGene', 10_000);
1690
+ const antiGeneIds = new Set(allAntiGenes.map((a) => a.asset_id));
1691
+ // Count review records by asset type
1692
+ for (const r of reviewRecords) {
1693
+ if (antiGeneIds.has(r.assetId)) {
1694
+ // AntiGene review record
1695
+ if (r.state === 'quarantined')
1696
+ antiGeneReviewCounts.quarantined++;
1697
+ else if (r.state === 'approved')
1698
+ antiGeneReviewCounts.approved++;
1699
+ // rejected anti-gene: not shown separately per existing design
1700
+ }
1701
+ else {
1702
+ // Gene review record (or unknown asset type)
1703
+ if (r.state === 'quarantined')
1704
+ geneReviewCounts.quarantined++;
1705
+ else if (r.state === 'rejected')
1706
+ geneReviewCounts.rejected++;
1707
+ else if (r.state === 'approved')
1708
+ geneReviewCounts.approved++;
1709
+ }
1710
+ }
1711
+ // Genes without review records are default-approved
1712
+ const reviewedIds = new Set(reviewRecords.map((r) => r.assetId));
1713
+ const unreviewedGeneCount = allGenes.filter((g) => !reviewedIds.has(g.asset_id)).length;
1714
+ geneReviewCounts.approved += unreviewedGeneCount;
1715
+ // AntiGenes without explicit approval are unreviewed (fail-closed)
1716
+ for (const ag of allAntiGenes) {
1717
+ const r = review.get(ag.asset_id);
1718
+ if (!r || (r.state !== 'approved' && r.state !== 'quarantined')) {
1719
+ antiGeneReviewCounts.unreviewed++;
1720
+ }
1721
+ }
1722
+ return {
1723
+ date: today,
1724
+ connection,
1725
+ yesterday: {
1726
+ date: yesterdayPrefix,
1727
+ cycles: summary.cycles,
1728
+ solidified: summary.solidified,
1729
+ failed: summary.failed,
1730
+ capsules,
1731
+ triggered: summary.triggered,
1732
+ suppressed: summary.suppressed,
1733
+ },
1734
+ queue: {
1735
+ genesApproved: geneReviewCounts.approved,
1736
+ genesQuarantined: geneReviewCounts.quarantined,
1737
+ genesRejected: geneReviewCounts.rejected,
1738
+ antiGeneApproved: antiGeneReviewCounts.approved,
1739
+ antiGeneQuarantined: antiGeneReviewCounts.quarantined,
1740
+ antiGeneUnreviewed: antiGeneReviewCounts.unreviewed,
1741
+ },
1742
+ };
1743
+ }
1744
+ export async function runDaily(argv, deps = {}) {
1745
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
1746
+ const flags = parseFlags(argv);
1747
+ if ('help' in flags || 'h' in flags) {
1748
+ stdout(DAILY_USAGE);
1749
+ return 0;
1750
+ }
1751
+ const json = 'json' in flags;
1752
+ const auto = 'auto' in flags;
1753
+ const env = deps.env ?? process.env;
1754
+ const now = deps.now ? deps.now() : Date.now();
1755
+ const today = formatDay(new Date(now));
1756
+ // --auto: check if we already ran today
1757
+ if (auto) {
1758
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1759
+ if (!shouldRunDaily(lastDailyFile, today))
1760
+ return 0;
1761
+ }
1762
+ const report = await collectDailyReport(deps);
1763
+ if (json) {
1764
+ stdout(`${JSON.stringify({ ok: true, group: 'daily', ...report })}\n`);
1765
+ }
1766
+ else {
1767
+ stdout(formatDailyReport(report));
1768
+ }
1769
+ // Mark today as run (for --auto mode; harmless otherwise)
1770
+ if (auto) {
1771
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1772
+ markDailyRun(lastDailyFile, today);
1773
+ }
1774
+ return 0;
1775
+ }
1390
1776
  export function runCli(argv) {
1391
1777
  const cmd = argv[0];
1392
1778
  if (cmd === undefined || cmd === '--help' || cmd === '-h') {