@evomap/evolver-cli 2.0.0-beta.9 → 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 (87) 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/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. 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';
@@ -9,29 +9,20 @@ import { listApprovedGenes, provenanceStoreForStore, reviewLedgerForStore } from
9
9
  import { ADAPTERS, parseJsonlLines } from '@evomap/evolver-runtime-adapters';
10
10
  import { draftGeneCandidate } from './distillPrimitives.js';
11
11
  import { assessDraftAdmissionFromStore } from './distillAdmission.js';
12
- import { emitSessionRecall } from './autoRecall.js';
13
- import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics } from './runtimeSessionSource.js';
14
- import { existsSync, readFileSync, readdirSync, statSync, unlinkSync } from 'node:fs';
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';
15
14
  import { homedir } from 'node:os';
16
- import { dirname, join, resolve } from 'node:path';
17
- 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';
18
17
  import { explicitRecipeHomes } from './recipe.js';
19
- import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled } from './lifecycle.js';
18
+ import { maybeAutoRestartProxyForSessionStart, sessionStartHookVerboseEnabled, dailyConnectionStatus, lifecyclePaths } from './lifecycle.js';
20
19
  import { formatAntiGeneEvidenceAction, formatAntiGeneEvidenceSummary, summarizeAntiGeneEvidence } from './antiGeneEvidence.js';
21
20
  import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
22
21
  import { maybeEmitNonGitWorkspaceNotice } from './nonGitWorkspaceNotice.js';
23
- /**
24
- * Material consumer group for ingest: the cycle is the downstream that claims material → signals. Kept in
25
- * one place so the recorded Material and any future cycle consumer agree on the group name.
26
- */
27
- const INGEST_CONSUMER_GROUP = 'cycle';
28
- function resolveIngestDeps(deps) {
29
- return {
30
- materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
31
- watermarkStore: deps.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath()),
32
- ingestor: deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
33
- };
34
- }
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';
35
26
  /** Minimal `--flag value` parser (last wins); bare positionals are ignored. */
36
27
  function parseFlags(argv) {
37
28
  const out = {};
@@ -77,12 +68,13 @@ export function cliUsage() {
77
68
  'Commands:',
78
69
  ' Daemon: proxy, lifecycle, proxy-token, doctor, setup-hooks',
79
70
  ' Evolution: run, cycle, autoexec, solidify, distill, review, thesis',
80
- ' 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',
81
73
  ' Assets: asset-log, asset-trust, asset-health, material, recipe, skill',
82
- ' Hub: login, logout, phub, sync, publish, fetch, buy, orders, atp',
83
- ' Operations: status, workflow status, cycles, trigger, value, retention, replay, rebuild-views',
84
- ' issue-report',
85
- ' 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',
86
78
  ' Advanced: anti-gene-benchmark, anti-gene-rollout, reset-local-secret',
87
79
  ' skill-distill, skill-md-update',
88
80
  '',
@@ -230,19 +222,64 @@ export function rebuildViews(opts = {}) {
230
222
  replayer.rebuild(ing.readAll());
231
223
  return { rebuilt: events.DEFAULT_PROJECTORS.map((p) => p.name) };
232
224
  }
233
- /** migrate import-v1 <v1dir> [outDir] --workspace <path>: v1→v2 read-only migration. */
234
- export async function runMigrate(argv) {
235
- const usage = '用法: evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]\n';
236
- 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('--')) {
237
272
  process.stderr.write(usage);
238
273
  return 1;
239
274
  }
240
275
  let outDir;
241
276
  let workspace;
242
- for (let index = 2; index < argv.length; index += 1) {
243
- 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] ?? '';
244
281
  if (arg === '--workspace') {
245
- const value = argv[index + 1];
282
+ const value = migrationArgs[index + 1];
246
283
  if (!value || value.startsWith('--')) {
247
284
  process.stderr.write(usage);
248
285
  return 1;
@@ -257,6 +294,12 @@ export async function runMigrate(argv) {
257
294
  return 1;
258
295
  }
259
296
  }
297
+ else if (arg === '--dry-run') {
298
+ dryRun = true;
299
+ }
300
+ else if (arg === '--json') {
301
+ json = true;
302
+ }
260
303
  else if (arg.startsWith('--') || outDir !== undefined) {
261
304
  process.stderr.write(usage);
262
305
  return 1;
@@ -267,13 +310,57 @@ export async function runMigrate(argv) {
267
310
  }
268
311
  const envFile = loadEnvFileFromEnv(process.env);
269
312
  if (envFile.error) {
270
- process.stderr.write('migrate: failed to load EVOLVER_ENV_FILE\n');
313
+ writeMigrationFailure('migration_env_file_load_failed', json);
271
314
  return 1;
272
315
  }
273
316
  const targetDir = outDir ?? events.evomapHome();
274
- const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
275
- const rep = await importV1(argv[1], store, targetDir, workspace ? { workspace } : {});
276
- 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);
277
364
  return 0;
278
365
  }
279
366
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -287,8 +374,107 @@ export function formatAssetLine(a) {
287
374
  : '';
288
375
  return `${a.type.padEnd(15)} ${id} ${desc}`.trimEnd();
289
376
  }
290
- /** asset-log [Gene|Capsule|EvolutionEvent|AntiGene] [limit]: list recent local assets (observability; ported v1 CLI verb). */
291
- 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) {
292
478
  const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
293
479
  let kind;
294
480
  let limit = 20;
@@ -297,6 +483,8 @@ export async function runAssetLog(argv, store) {
297
483
  kind = a;
298
484
  else if (/^\d+$/.test(a))
299
485
  limit = Number(a);
486
+ else
487
+ return assetLogUsage(`unknown asset list argument: ${a}`);
300
488
  }
301
489
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
302
490
  const assets = await s.list(kind, limit);
@@ -308,6 +496,120 @@ export async function runAssetLog(argv, store) {
308
496
  process.stdout.write(formatAssetLine(a) + '\n');
309
497
  return 0;
310
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
+ }
311
613
  /**
312
614
  * distill: gate a learned approach into the gene pool (ported v1 CLI verb). Runs the structural intake
313
615
  * (schema + dedup + asset_id) and, only if it passes, writes the gene to the store. The agent/runtime is
@@ -316,17 +618,30 @@ export async function runAssetLog(argv, store) {
316
618
  */
317
619
  export async function runDistill(argv, store, deps = {}) {
318
620
  const f = parseFlags(argv);
319
- const candidate = {
320
- ...(f['id'] ? { id: f['id'] } : {}),
321
- category: f['category'] ?? 'innovate',
322
- signals_match: splitList(f['signals'], /,/),
323
- strategy: splitList(f['strategy'], /[;\n]/),
324
- ...(f['summary'] ? { summary: f['summary'] } : {}),
325
- // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
326
- // `manual` per V1 #302 classifyProvenance.
327
- generation_meta: { source: 'manual' },
328
- };
329
- 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) {
330
645
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
331
646
  return 1;
332
647
  }
@@ -341,15 +656,34 @@ export async function runDistill(argv, store, deps = {}) {
341
656
  process.stderr.write(`distill 拒绝: ${r.errors.join('; ')}\n`);
342
657
  return 1;
343
658
  }
344
- await s.put(r.gene);
345
- // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
346
659
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
347
- await ingestor.ingest({
348
- type: 'actor.human.teach',
349
- payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
350
- human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
351
- actor: { kind: 'human', id: operatorActorId() },
352
- });
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
+ }
353
687
  process.stdout.write(`distilled gene ${r.gene.id} (${String(r.gene.asset_id).slice(0, 19)}…) → pool\n`);
354
688
  return 0;
355
689
  }
@@ -371,12 +705,6 @@ function printTraceSignals(file, turnCount, sigs) {
371
705
  process.stdout.write(` [${s.strength}/${s.kind}] ${s.text.replace(/\s+/g, ' ').trim().slice(0, 160)}\n`);
372
706
  }
373
707
  }
374
- /** The runtime agents Material.sourceAgent can represent (closed enum on the schema). */
375
- const MATERIAL_SOURCE_AGENTS = new Set(['claude-code', 'codex', 'cursor', 'gemini', 'antigravity', 'kimi', 'kiro', 'opencode', 'generic-chat']);
376
- /** Narrow an adapter's free-string agent to the Material source enum (undefined → not recordable). */
377
- function toMaterialSourceAgent(agent) {
378
- return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
379
- }
380
708
  /**
381
709
  * Is a Material for this EXACT file state already on the substrate? A Material's identity is its ULID, so `put`
382
710
  * cannot dedup across runs (each build mints a fresh id). Without this, a crash-retry — where a prior run put the
@@ -396,50 +724,6 @@ function materialExistsFor(store, sourcePath, wm) {
396
724
  }
397
725
  return false;
398
726
  }
399
- /**
400
- * Record a session log as Material on the M1 substrate (idempotent by file watermark), then emit a
401
- * `material.batch_ready` root_event so the AE is not bypassed. Re-ingesting the same UNCHANGED file records
402
- * no new material and emits no event (scanFile reports `changed: false` against the persisted cursor).
403
- * Returns whether new material landed + its materialId so the caller can report it.
404
- */
405
- async function recordSessionMaterial(sourceAgent, absPath, signalCount, d, recordCount = 1, payload, diagnostics) {
406
- const prev = d.watermarkStore.get(absPath);
407
- const scan = materialNs.scanFile(absPath, prev);
408
- // Unchanged source already recorded once → idempotent skip (no duplicate material, no duplicate event).
409
- if (prev && !scan.changed)
410
- return { recorded: false, emitted: false };
411
- const m = materialNs.buildMaterial({
412
- sourceAgent,
413
- sourceKind: 'runtime_session',
414
- sourcePath: absPath,
415
- kind: 'session_log',
416
- watermark: scan.watermark,
417
- consumerGroup: INGEST_CONSUMER_GROUP,
418
- ...(payload ? { payload } : {}),
419
- });
420
- // Crash-retry idempotency (#100): if a prior run already put this file's material but threw before the
421
- // watermark advanced, don't append a duplicate row — reuse it and only (re-)emit the lost event below.
422
- const isNew = !materialExistsFor(d.materialStore, absPath, scan.watermark);
423
- if (isNew)
424
- await d.materialStore.put(m);
425
- const parseDiagnostics = diagnostics && diagnostics.invalidJson > 0
426
- ? { rowsScanned: diagnostics.rowsScanned, rowsRead: diagnostics.rowsRead, invalidJson: diagnostics.invalidJson }
427
- : undefined;
428
- await d.ingestor.ingest({
429
- type: 'material.batch_ready',
430
- payload: { source: absPath, recordCount, signalCount, ...(parseDiagnostics ? { parseDiagnostics } : {}) },
431
- human: {
432
- title: `material 已落地: ${sourceAgent} session`,
433
- ...(parseDiagnostics ? { detail: `skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s)` } : {}),
434
- severity: 'info',
435
- },
436
- actor: { kind: 'machine' },
437
- });
438
- // Watermark LAST — only after BOTH the put and its batch_ready event succeed. If ingest throws, the watermark
439
- // stays unset so a re-run re-emits the event; the content check above keeps that retry from duplicating the row.
440
- d.watermarkStore.set(absPath, scan.watermark);
441
- return { recorded: isNew, emitted: true, materialId: m.materialId };
442
- }
443
727
  /**
444
728
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
445
729
  * telemetry, so it carries sourceKind=proxy_trace + kind=llm_trace and NO sourceAgent — the origin taxonomy
@@ -474,90 +758,6 @@ async function recordTraceMaterial(absPath, signalCount, d) {
474
758
  d.watermarkStore.set(absPath, scan.watermark);
475
759
  return { recorded: isNew, materialId: m.materialId };
476
760
  }
477
- /**
478
- * Recursively enumerate recognized runtime-session sources under the given dirs — the daemon's auto-distill
479
- * producer source (#106). This includes text session files handled by runtime adapters (`*.jsonl` and Gemini
480
- * `*.json`) plus Cursor's sqlite `state.vscdb`. A missing/permission-denied dir is silently skipped (a daemon
481
- * must not crash on an absent home dir).
482
- */
483
- export function scanSessionDirs(dirs) {
484
- const out = [];
485
- for (const dir of dirs) {
486
- let entries;
487
- try {
488
- entries = readdirSync(resolve(dir), { recursive: true });
489
- }
490
- catch {
491
- continue;
492
- } // dir absent / unreadable → skip
493
- for (const e of entries) {
494
- const file = join(resolve(dir), e);
495
- if (isRuntimeSessionSourcePath(file))
496
- out.push(file);
497
- }
498
- }
499
- return out;
500
- }
501
- function sortedStrings(values) {
502
- return [...new Set([...values].map(String).filter(Boolean))].sort();
503
- }
504
- /**
505
- * One producer tick for the auto-distill loop (#106 slice 1): scan `dirs` for session logs and record any
506
- * NEW/CHANGED file as `runtime_session` Material via the injected (bus) Ingestor — which emits
507
- * `material.batch_ready`, the event the distillObserver claims off. Idempotent per file (watermark cursor), so
508
- * re-scanning an unchanged tree records nothing. Pure producer: it does NOT distill (the observer does). Returns
509
- * how many files landed new material. Inject `deps.ingestor = new Ingestor({ sink: bus })` so the event reaches
510
- * the daemon's ObserverBus; defaults to live paths otherwise.
511
- */
512
- export async function runSessionIngestTick(dirs, deps = {}) {
513
- const d = resolveIngestDeps(deps);
514
- let recorded = 0;
515
- const sourceAgents = new Set();
516
- const signalKinds = new Set();
517
- const signalStrengths = new Set();
518
- let invalidJsonRows = 0;
519
- // #274 auto-recall (default OFF): observe which injected genes were actually used, from the transcript, so the
520
- // experience loop is fed by observation instead of a self-reported tool call agents skip. Best-effort + idempotent
521
- // (one value.recall set per session); off → zero extra work. auto-OBSERVE only — it never quarantines.
522
- const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
523
- for (const file of scanSessionDirs(dirs)) {
524
- try {
525
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(file);
526
- const parsedSources = parsed.sources;
527
- const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
528
- if (parsedSources.length === 0 || !agent)
529
- continue; // not a recognized, schema-recordable runtime-session source
530
- const sigsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
531
- const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
532
- const r = await recordSessionMaterial(agent, file, sigsBySource.reduce((sum, sigs) => sum + sigs.length, 0), d, parsedSources.length, snapshot, parsed.diagnostics);
533
- if (r.emitted)
534
- invalidJsonRows += parsed.diagnostics.invalidJson;
535
- if (r.recorded) {
536
- recorded += 1;
537
- sourceAgents.add(agent);
538
- for (const sigs of sigsBySource) {
539
- for (const sig of sigs) {
540
- signalKinds.add(sig.kind);
541
- signalStrengths.add(sig.strength);
542
- }
543
- }
544
- }
545
- if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
546
- // Drop meta turns (heartbeats/empty) before judging, same as `evolver recall` — counting them would skew overlap.
547
- const turns = parsedSources[0].turns.filter((t) => !t.isMeta).map((t) => ({ role: t.role, text: t.text }));
548
- await emitSessionRecall(file, turns, { ingestor: d.ingestor });
549
- }
550
- }
551
- catch { /* unreadable / unparseable file → skip, never break the scan */ }
552
- }
553
- return {
554
- recorded,
555
- sourceAgents: sortedStrings(sourceAgents),
556
- signalKinds: sortedStrings(signalKinds),
557
- signalStrengths: sortedStrings(signalStrengths),
558
- ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
559
- };
560
- }
561
761
  /**
562
762
  * Read + parse one or more trace JSONL files, record each as proxy_trace Material on the M1 substrate (#95,
563
763
  * idempotent by file watermark), and report their signals as a single batch.
@@ -655,7 +855,7 @@ export async function runIngest(argv, store, deps = {}, review) {
655
855
  let parsedSources;
656
856
  let parseDiagnostics;
657
857
  try {
658
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
858
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path, undefined, deps.nativeSessionHome);
659
859
  parsedSources = parsed.sources;
660
860
  parseDiagnostics = parsed.diagnostics;
661
861
  }
@@ -1326,8 +1526,16 @@ async function readHookSessionId(read) {
1326
1526
  */
1327
1527
  export async function runInject(argv, deps = {}) {
1328
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
+ }
1329
1537
  if (sub !== 'session-start') {
1330
- process.stderr.write('用法: evolver inject session-start\n');
1538
+ process.stderr.write('用法: evolver inject session-start | evolver inject prompt-recall --hook-stdin\n');
1331
1539
  return sub === undefined ? 0 : 1;
1332
1540
  }
1333
1541
  const fromHookStdin = argv.includes('--hook-stdin');
@@ -1385,6 +1593,186 @@ export async function runInject(argv, deps = {}) {
1385
1593
  }
1386
1594
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
1387
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
+ }
1388
1776
  export function runCli(argv) {
1389
1777
  const cmd = argv[0];
1390
1778
  if (cmd === undefined || cmd === '--help' || cmd === '-h') {