@evomap/evolver-cli 2.0.0-beta.17 → 2.0.0-beta.19

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 (64) hide show
  1. package/dist/antiGeneRollout.js +7 -3
  2. package/dist/assetTrust.js +14 -1
  3. package/dist/atp.d.ts +8 -3
  4. package/dist/atp.js +82 -11
  5. package/dist/atpAutoBuyer.d.ts +120 -0
  6. package/dist/atpAutoBuyer.js +814 -0
  7. package/dist/atpAutoDeliver.js +2 -2
  8. package/dist/autoDistillLlm.js +2 -1
  9. package/dist/autoDistillTranscript.js +3 -2
  10. package/dist/autoexec.d.ts +90 -13
  11. package/dist/autoexec.js +731 -84
  12. package/dist/cli.js +13 -0
  13. package/dist/cliContracts.d.ts +5 -2
  14. package/dist/cliContracts.js +135 -8
  15. package/dist/commands.d.ts +1 -0
  16. package/dist/commands.js +1 -0
  17. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  18. package/dist/curriculumCapabilityGaps.js +24 -0
  19. package/dist/cycleConsumer.d.ts +4 -0
  20. package/dist/cycleConsumer.js +175 -20
  21. package/dist/dashboard.js +47 -9
  22. package/dist/dispatch.js +6 -2
  23. package/dist/distillPrimitives.js +18 -6
  24. package/dist/doctor.js +63 -5
  25. package/dist/identityHome.js +2 -1
  26. package/dist/index.d.ts +67 -39
  27. package/dist/index.js +504 -185
  28. package/dist/learningTrace.d.ts +4 -0
  29. package/dist/learningTrace.js +30 -3
  30. package/dist/lifecycle.d.ts +54 -1
  31. package/dist/lifecycle.js +489 -37
  32. package/dist/materialSnapshot.d.ts +9 -1
  33. package/dist/materialSnapshot.js +23 -6
  34. package/dist/migrate/envTranslate.d.ts +26 -0
  35. package/dist/migrate/envTranslate.js +145 -0
  36. package/dist/migrate/oauthImport.d.ts +66 -0
  37. package/dist/migrate/oauthImport.js +667 -0
  38. package/dist/migrate/v1Import.d.ts +13 -1
  39. package/dist/migrate/v1Import.js +621 -122
  40. package/dist/promptRecallHook.d.ts +24 -0
  41. package/dist/promptRecallHook.js +425 -0
  42. package/dist/recallVerifyReport.d.ts +37 -0
  43. package/dist/recallVerifyReport.js +244 -0
  44. package/dist/requiredSandboxValidation.d.ts +5 -0
  45. package/dist/requiredSandboxValidation.js +4 -0
  46. package/dist/reuse.d.ts +1 -0
  47. package/dist/reuse.js +45 -37
  48. package/dist/runtimeCapabilities.js +13 -13
  49. package/dist/runtimeSessionSource.d.ts +3 -2
  50. package/dist/runtimeSessionSource.js +63 -11
  51. package/dist/sessionIngest.d.ts +37 -0
  52. package/dist/sessionIngest.js +156 -0
  53. package/dist/setupHooks.js +95 -1
  54. package/dist/skill2gep.d.ts +4 -7
  55. package/dist/skill2gep.js +4 -21
  56. package/dist/solo/mode.js +1 -0
  57. package/dist/sync.js +125 -23
  58. package/dist/thesis.d.ts +1 -1
  59. package/dist/thesis.js +18 -3
  60. package/dist/trajectoryExport.js +21 -3
  61. package/dist/v1Compat.d.ts +1 -0
  62. package/dist/v1Compat.js +9 -0
  63. package/dist/workflowRuntime.js +24 -18
  64. package/package.json +10 -7
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 { importV1, validateMigrationRoots } 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,9 +222,27 @@ 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. */
225
+ /** migrate import-v1 | migrate env | migrate oauth — V1→V2 migration tools. */
234
226
  export async function runMigrate(argv) {
235
- const usage = '用法: evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]\n';
227
+ const usage = [
228
+ 'Usage:',
229
+ ' evolver migrate import-v1 <v1dir> [outDir] [--workspace <path>]',
230
+ ' evolver migrate env [--file <dotenv>] [--json] [--write-suggestions <path>] [--no-process-env]',
231
+ ' evolver migrate oauth [--from <oauth_token.json>] [--to <token.json>] [--force] [--dry-run] [--json]',
232
+ '',
233
+ ].join('\n');
234
+ if (argv[0] === '--help' || argv[0] === '-h' || argv.length === 0) {
235
+ process.stdout.write(usage);
236
+ return 0;
237
+ }
238
+ if (argv[0] === 'env') {
239
+ const { runMigrateEnvCommand } = await import('./migrate/envTranslate.js');
240
+ return runMigrateEnvCommand(argv.slice(1));
241
+ }
242
+ if (argv[0] === 'oauth') {
243
+ const { runMigrateOAuthCommand } = await import('./migrate/oauthImport.js');
244
+ return runMigrateOAuthCommand(argv.slice(1));
245
+ }
236
246
  if (argv[0] !== 'import-v1' || !argv[1]) {
237
247
  process.stderr.write(usage);
238
248
  return 1;
@@ -271,9 +281,17 @@ export async function runMigrate(argv) {
271
281
  return 1;
272
282
  }
273
283
  const targetDir = outDir ?? events.evomapHome();
284
+ try {
285
+ validateMigrationRoots(argv[1], targetDir);
286
+ }
287
+ catch (error) {
288
+ const code = error instanceof Error ? error.message : 'migration_path_rejected';
289
+ process.stderr.write(`migrate: ${code}\n`);
290
+ return 1;
291
+ }
274
292
  const store = new assetstore.LocalJsonlProvider(`${targetDir}/assets`);
275
293
  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`);
294
+ process.stdout.write(`迁移完成: Gene=${rep.imported.Gene} Capsule=${rep.imported.Capsule} Event=${rep.imported.EvolutionEvent} (冻结${rep.frozen}/新算${rep.recomputed}/去重${rep.deduped}); sidecar=${rep.sidecarExtensions}; mailbox 发现=${rep.mailboxFound} 导入=${rep.mailboxImported}; memory_graph 归档=${rep.memoryGraphArchived} 可查询=${rep.memoryGraphImported} 延后=${rep.memoryGraphDeferred}\n`);
277
295
  return 0;
278
296
  }
279
297
  /** One-line summary of an asset for `asset-log` (pure, testable). */
@@ -287,8 +305,107 @@ export function formatAssetLine(a) {
287
305
  : '';
288
306
  return `${a.type.padEnd(15)} ${id} ${desc}`.trimEnd();
289
307
  }
290
- /** asset-log [Gene|Capsule|EvolutionEvent|AntiGene] [limit]: list recent local assets (observability; ported v1 CLI verb). */
291
- export async function runAssetLog(argv, store) {
308
+ const ASSET_CALL_ACTIONS = [
309
+ 'hub_search_hit', 'hub_search_miss',
310
+ 'asset_reuse', 'asset_reference',
311
+ 'asset_publish', 'asset_publish_skip',
312
+ 'asset_inject', 'asset_inject_shadow',
313
+ 'hub_review_submitted', 'hub_review_rejected', 'hub_review_failed',
314
+ ];
315
+ function isAssetCallAction(value) {
316
+ return ASSET_CALL_ACTIONS.includes(value);
317
+ }
318
+ /**
319
+ * Preserve V2's asset-store listing as the default. V1's call audit is available
320
+ * through the explicit `calls` mode so the two contracts do not overload an empty argv.
321
+ */
322
+ export async function runAssetLog(argv, store, deps = {}) {
323
+ const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
324
+ const CALL_FLAGS = ['--run', '--action', '--last', '--since', '--json'];
325
+ const explicitCallMode = argv[0] === 'calls' || argv[0] === '--calls';
326
+ const callMode = explicitCallMode || argv.some((arg) => CALL_FLAGS
327
+ .some((flag) => arg === flag || arg.startsWith(`${flag}=`)));
328
+ const assetMode = !callMode && (argv.length === 0
329
+ || argv[0] === 'assets'
330
+ || argv[0] === '--assets'
331
+ || KINDS.includes(argv[0] ?? '')
332
+ || /^\d+$/.test(argv[0] ?? ''));
333
+ if (assetMode)
334
+ return runAssetList(argv.filter((arg) => arg !== 'assets' && arg !== '--assets'), store);
335
+ if (!callMode)
336
+ return assetLogUsage(`unknown asset-log mode: ${argv[0] ?? '(missing)'}`);
337
+ const opts = {};
338
+ let json = false;
339
+ for (let i = explicitCallMode ? 1 : 0; i < argv.length; i += 1) {
340
+ const arg = argv[i];
341
+ if (!explicitCallMode && KINDS.includes(arg ?? ''))
342
+ continue;
343
+ if (arg === '--json') {
344
+ json = true;
345
+ continue;
346
+ }
347
+ const parsed = assetLogFlagValue(argv, i, '--run');
348
+ if (parsed) {
349
+ opts.run_id = parsed.value;
350
+ i += parsed.consumed;
351
+ continue;
352
+ }
353
+ const action = assetLogFlagValue(argv, i, '--action');
354
+ if (action) {
355
+ if (!isAssetCallAction(action.value))
356
+ return assetLogUsage(`invalid --action: ${action.value}`);
357
+ opts.action = action.value;
358
+ i += action.consumed;
359
+ continue;
360
+ }
361
+ const last = assetLogFlagValue(argv, i, '--last');
362
+ if (last) {
363
+ if (!/^\d+$/.test(last.value) || Number(last.value) < 1)
364
+ return assetLogUsage(`invalid --last: ${last.value}`);
365
+ opts.last = Number(last.value);
366
+ i += last.consumed;
367
+ continue;
368
+ }
369
+ const since = assetLogFlagValue(argv, i, '--since');
370
+ if (since) {
371
+ if (!Number.isFinite(Date.parse(since.value)))
372
+ return assetLogUsage(`invalid --since: ${since.value}`);
373
+ opts.since = since.value;
374
+ i += since.consumed;
375
+ continue;
376
+ }
377
+ return assetLogUsage(`unknown asset-log argument: ${arg ?? '(missing)'}`);
378
+ }
379
+ const logPath = deps.logPath ?? events.assetCallLogPath();
380
+ const callLog = deps.callLog ?? new hubNs.AssetCallLog(logPath);
381
+ if (json) {
382
+ process.stdout.write(`${JSON.stringify(callLog.read(opts), null, 2)}\n`);
383
+ return 0;
384
+ }
385
+ const summary = callLog.summarize(opts);
386
+ process.stdout.write('\n[Asset Call Log]\n');
387
+ process.stdout.write(` Total entries: ${summary.total_entries}\n`);
388
+ process.stdout.write(` Unique assets: ${summary.unique_assets}\n`);
389
+ process.stdout.write(` Unique runs: ${summary.unique_runs}\n`);
390
+ process.stdout.write(' By action:\n');
391
+ for (const [action, count] of Object.entries(summary.by_action)) {
392
+ process.stdout.write(` ${action}: ${count}\n`);
393
+ }
394
+ if (summary.entries.length === 0) {
395
+ process.stdout.write('\n No entries found.\n\n');
396
+ return 0;
397
+ }
398
+ process.stdout.write('\n Recent entries:\n');
399
+ for (const entry of summary.entries.slice(-10)) {
400
+ const timestamp = entry.timestamp ? entry.timestamp.slice(0, 19) : '?';
401
+ const asset = entry.asset_id ? `${entry.asset_id.slice(0, 20)}...` : '(none)';
402
+ const signals = Array.isArray(entry.signals) ? entry.signals.slice(0, 3).join(', ') : '';
403
+ process.stdout.write(` [${timestamp}] ${entry.action || '?'} asset=${asset} score=${entry.score ?? '-'} mode=${entry.mode ?? '-'} signals=[${signals}] run=${entry.run_id ?? '-'}\n`);
404
+ }
405
+ process.stdout.write('\n');
406
+ return 0;
407
+ }
408
+ async function runAssetList(argv, store) {
292
409
  const KINDS = ['Gene', 'Capsule', 'EvolutionEvent', 'AntiGene'];
293
410
  let kind;
294
411
  let limit = 20;
@@ -297,6 +414,8 @@ export async function runAssetLog(argv, store) {
297
414
  kind = a;
298
415
  else if (/^\d+$/.test(a))
299
416
  limit = Number(a);
417
+ else
418
+ return assetLogUsage(`unknown asset list argument: ${a}`);
300
419
  }
301
420
  const s = store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
302
421
  const assets = await s.list(kind, limit);
@@ -308,6 +427,120 @@ export async function runAssetLog(argv, store) {
308
427
  process.stdout.write(formatAssetLine(a) + '\n');
309
428
  return 0;
310
429
  }
430
+ function assetLogFlagValue(argv, index, flag) {
431
+ const arg = argv[index];
432
+ if (arg?.startsWith(`${flag}=`)) {
433
+ const value = arg.slice(flag.length + 1);
434
+ return value ? { value, consumed: 0 } : null;
435
+ }
436
+ if (arg !== flag)
437
+ return null;
438
+ const value = argv[index + 1];
439
+ return value && !value.startsWith('--') ? { value, consumed: 1 } : null;
440
+ }
441
+ function assetLogUsage(error) {
442
+ 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`);
443
+ return 1;
444
+ }
445
+ const DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES = 1024 * 1024;
446
+ function responseFileArg(argv) {
447
+ for (let index = 0; index < argv.length; index += 1) {
448
+ const arg = argv[index];
449
+ if (arg?.startsWith('--response-file='))
450
+ return arg.slice('--response-file='.length);
451
+ if (arg === '--response-file')
452
+ return argv[index + 1] ?? '';
453
+ }
454
+ return undefined;
455
+ }
456
+ function pathIsWithin(root, target) {
457
+ const rel = relative(root, target);
458
+ return rel === '' || (!isAbsolute(rel) && rel !== '..' && !rel.startsWith(`..${sep}`));
459
+ }
460
+ function sameResponseFileIdentity(left, right) {
461
+ const hasStableFileId = left.dev !== 0n || left.ino !== 0n || right.dev !== 0n || right.ino !== 0n;
462
+ if (hasStableFileId)
463
+ return left.dev === right.dev && left.ino === right.ino;
464
+ // Some filesystems do not expose dev/ino. Birth time + mode is the strongest portable fallback Node provides.
465
+ return left.birthtimeNs === right.birthtimeNs && left.mode === right.mode;
466
+ }
467
+ function sameResponseFileSnapshot(left, right) {
468
+ return sameResponseFileIdentity(left, right)
469
+ && left.size === right.size
470
+ && left.mtimeNs === right.mtimeNs
471
+ && left.ctimeNs === right.ctimeNs;
472
+ }
473
+ function readResponseFileDescriptor(fd, expectedSize) {
474
+ const content = Buffer.alloc(expectedSize);
475
+ let offset = 0;
476
+ while (offset < expectedSize) {
477
+ const bytesRead = readSync(fd, content, offset, expectedSize - offset, offset);
478
+ if (bytesRead === 0)
479
+ throw new Error('response-file changed while being read (truncated)');
480
+ offset += bytesRead;
481
+ }
482
+ const extra = Buffer.allocUnsafe(1);
483
+ if (readSync(fd, extra, 0, 1, expectedSize) !== 0) {
484
+ throw new Error('response-file changed while being read (grew beyond the validated size)');
485
+ }
486
+ return content.toString('utf8');
487
+ }
488
+ function candidateFromResponseFile(path, deps) {
489
+ if (!path)
490
+ throw new Error('response-file path is empty');
491
+ const requestedRoot = resolve(deps.responseFileRoot ?? process.cwd());
492
+ const root = realpathSync(requestedRoot);
493
+ const requested = resolve(requestedRoot, path);
494
+ if (!pathIsWithin(requestedRoot, requested))
495
+ throw new Error('response-file is outside the allowed root');
496
+ const beforeOpen = lstatSync(requested, { bigint: true });
497
+ if (!beforeOpen.isFile() || beforeOpen.isSymbolicLink())
498
+ throw new Error('response-file must be a regular non-symlink file');
499
+ const canonical = realpathSync(requested);
500
+ if (!pathIsWithin(root, canonical))
501
+ throw new Error('response-file resolves outside the allowed root');
502
+ const configuredMax = deps.maxResponseFileBytes ?? DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
503
+ const maxBytes = Number.isSafeInteger(Math.floor(configuredMax)) && configuredMax > 0
504
+ ? Math.floor(configuredMax)
505
+ : DEFAULT_DISTILL_RESPONSE_FILE_MAX_BYTES;
506
+ if (beforeOpen.size > BigInt(maxBytes))
507
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
508
+ deps.responseFileReadTestHook?.('before-open', canonical);
509
+ const noFollow = process.platform !== 'win32' && typeof fsConstants.O_NOFOLLOW === 'number'
510
+ ? fsConstants.O_NOFOLLOW
511
+ : 0;
512
+ const fd = openSync(canonical, fsConstants.O_RDONLY | noFollow);
513
+ let raw;
514
+ try {
515
+ const opened = fstatSync(fd, { bigint: true });
516
+ if (!opened.isFile())
517
+ throw new Error('response-file must be a regular file');
518
+ if (!sameResponseFileSnapshot(beforeOpen, opened))
519
+ throw new Error('response-file changed before it could be opened');
520
+ if (opened.size > BigInt(maxBytes))
521
+ throw new Error(`response-file is too large (max ${maxBytes} bytes)`);
522
+ deps.responseFileReadTestHook?.('after-open', canonical);
523
+ raw = readResponseFileDescriptor(fd, Number(opened.size));
524
+ const afterRead = fstatSync(fd, { bigint: true });
525
+ if (!sameResponseFileSnapshot(opened, afterRead))
526
+ throw new Error('response-file changed while being read');
527
+ const afterPath = lstatSync(requested, { bigint: true });
528
+ if (!afterPath.isFile() || afterPath.isSymbolicLink() || !sameResponseFileSnapshot(afterRead, afterPath)) {
529
+ throw new Error('response-file path changed while being read');
530
+ }
531
+ const canonicalAfterRead = realpathSync(requested);
532
+ if (!pathIsWithin(root, canonicalAfterRead) || canonicalAfterRead !== canonical) {
533
+ throw new Error('response-file path changed outside the allowed root');
534
+ }
535
+ }
536
+ finally {
537
+ closeSync(fd);
538
+ }
539
+ const candidate = asGeneCandidate(parseDistillOutput(raw));
540
+ if (!candidate)
541
+ throw new Error('response-file does not contain a valid Gene JSON object');
542
+ return candidate;
543
+ }
311
544
  /**
312
545
  * distill: gate a learned approach into the gene pool (ported v1 CLI verb). Runs the structural intake
313
546
  * (schema + dedup + asset_id) and, only if it passes, writes the gene to the store. The agent/runtime is
@@ -316,17 +549,30 @@ export async function runAssetLog(argv, store) {
316
549
  */
317
550
  export async function runDistill(argv, store, deps = {}) {
318
551
  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) {
552
+ const responseFile = responseFileArg(argv);
553
+ let candidate;
554
+ if (responseFile !== undefined) {
555
+ try {
556
+ candidate = candidateFromResponseFile(responseFile, deps);
557
+ }
558
+ catch (error) {
559
+ process.stderr.write(`[Distill] response-file error: ${error instanceof Error ? error.message : String(error)}\n`);
560
+ return 2;
561
+ }
562
+ }
563
+ else {
564
+ candidate = {
565
+ ...(f['id'] ? { id: f['id'] } : {}),
566
+ category: f['category'] ?? 'innovate',
567
+ signals_match: splitList(f['signals'], /,/),
568
+ strategy: splitList(f['strategy'], /[;\n]/),
569
+ ...(f['summary'] ? { summary: f['summary'] } : {}),
570
+ // `evolver distill` is a human teaching the system a gene (actor.kind = human, see the audit below) →
571
+ // `manual` per V1 #302 classifyProvenance.
572
+ generation_meta: { source: 'manual' },
573
+ };
574
+ }
575
+ if ((candidate.signals_match ?? []).length === 0 || (candidate.strategy ?? []).length === 0) {
330
576
  process.stderr.write('用法: evolver distill --category <c> --signals <s1,s2> --strategy "<step1; step2>" [--summary <t>]\n');
331
577
  return 1;
332
578
  }
@@ -341,15 +587,34 @@ export async function runDistill(argv, store, deps = {}) {
341
587
  process.stderr.write(`distill 拒绝: ${r.errors.join('; ')}\n`);
342
588
  return 1;
343
589
  }
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
590
  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
- });
591
+ if (responseFile !== undefined) {
592
+ // The gene is the commit point. Audit first (idempotently), quarantine second, then persist last so any
593
+ // partial failure remains retryable and can never expose an unaudited machine-produced gene in the pool.
594
+ const assetId = String(r.gene.asset_id);
595
+ const alreadyAudited = ingestor.readAll().some((event) => event.type === 'gene.distilled'
596
+ && String(event.payload?.['assetId'] ?? '') === assetId);
597
+ if (!alreadyAudited) {
598
+ await ingestor.ingest({
599
+ type: 'gene.distilled',
600
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, source: 'cli-response-file' },
601
+ human: { title: `LLM response-file distilled gene ${r.gene.id}`, severity: 'info' },
602
+ actor: { kind: 'machine', id: 'cli-response-file' },
603
+ });
604
+ }
605
+ reviewLedgerForStore(s).quarantineIfAbsent(assetId, 'LLM response-file distillation - review before use');
606
+ await s.put(r.gene);
607
+ }
608
+ else {
609
+ await s.put(r.gene);
610
+ // AE (#91 item 1): a manual distill IS a human teaching the system a gene — record it on the audit spine.
611
+ await ingestor.ingest({
612
+ type: 'actor.human.teach',
613
+ payload: { geneId: r.gene.id, assetId: r.gene.asset_id, category: r.gene.category },
614
+ human: { title: `teach gene ${r.gene.id}`, severity: 'info' },
615
+ actor: { kind: 'human', id: operatorActorId() },
616
+ });
617
+ }
353
618
  process.stdout.write(`distilled gene ${r.gene.id} (${String(r.gene.asset_id).slice(0, 19)}…) → pool\n`);
354
619
  return 0;
355
620
  }
@@ -371,12 +636,6 @@ function printTraceSignals(file, turnCount, sigs) {
371
636
  process.stdout.write(` [${s.strength}/${s.kind}] ${s.text.replace(/\s+/g, ' ').trim().slice(0, 160)}\n`);
372
637
  }
373
638
  }
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
639
  /**
381
640
  * Is a Material for this EXACT file state already on the substrate? A Material's identity is its ULID, so `put`
382
641
  * cannot dedup across runs (each build mints a fresh id). Without this, a crash-retry — where a prior run put the
@@ -396,50 +655,6 @@ function materialExistsFor(store, sourcePath, wm) {
396
655
  }
397
656
  return false;
398
657
  }
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
658
  /**
444
659
  * Record a proxy LLM-trace file as Material on the M1 substrate (#95). A trace is agent-agnostic gateway
445
660
  * telemetry, so it carries sourceKind=proxy_trace + kind=llm_trace and NO sourceAgent — the origin taxonomy
@@ -474,90 +689,6 @@ async function recordTraceMaterial(absPath, signalCount, d) {
474
689
  d.watermarkStore.set(absPath, scan.watermark);
475
690
  return { recorded: isNew, materialId: m.materialId };
476
691
  }
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
692
  /**
562
693
  * Read + parse one or more trace JSONL files, record each as proxy_trace Material on the M1 substrate (#95,
563
694
  * idempotent by file watermark), and report their signals as a single batch.
@@ -655,7 +786,7 @@ export async function runIngest(argv, store, deps = {}, review) {
655
786
  let parsedSources;
656
787
  let parseDiagnostics;
657
788
  try {
658
- const parsed = parseRuntimeSessionSourcesWithDiagnostics(path);
789
+ const parsed = parseRuntimeSessionSourcesWithDiagnostics(path, undefined, deps.nativeSessionHome);
659
790
  parsedSources = parsed.sources;
660
791
  parseDiagnostics = parsed.diagnostics;
661
792
  }
@@ -1326,8 +1457,16 @@ async function readHookSessionId(read) {
1326
1457
  */
1327
1458
  export async function runInject(argv, deps = {}) {
1328
1459
  const sub = argv[0];
1460
+ if (sub === 'prompt-recall') {
1461
+ return runPromptRecallHook(argv.slice(1), {
1462
+ ...(deps.store ? { store: deps.store } : {}),
1463
+ ...(deps.review ? { review: deps.review } : {}),
1464
+ ...(deps.provenance ? { provenance: deps.provenance } : {}),
1465
+ ...(deps.readHookInput ? { readHookInput: deps.readHookInput } : {}),
1466
+ });
1467
+ }
1329
1468
  if (sub !== 'session-start') {
1330
- process.stderr.write('用法: evolver inject session-start\n');
1469
+ process.stderr.write('用法: evolver inject session-start | evolver inject prompt-recall --hook-stdin\n');
1331
1470
  return sub === undefined ? 0 : 1;
1332
1471
  }
1333
1472
  const fromHookStdin = argv.includes('--hook-stdin');
@@ -1385,6 +1524,186 @@ export async function runInject(argv, deps = {}) {
1385
1524
  }
1386
1525
  /** Fixed preamble for the SessionStart injection (the head block the recap + gene lines hang off of). */
1387
1526
  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:';
1527
+ // ─── evolver daily ──────────────────────────────────────────────────────────
1528
+ 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';
1529
+ function formatDay(d) {
1530
+ return d.toISOString().slice(0, 10);
1531
+ }
1532
+ function dayPrefixFromOffset(nowMs, offsetDays) {
1533
+ const d = new Date(nowMs + offsetDays * 86_400_000);
1534
+ return formatDay(d);
1535
+ }
1536
+ function defaultLastDailyFile(env = process.env) {
1537
+ const home = env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? join(homedir(), '.evomap');
1538
+ return join(home, '.last-daily');
1539
+ }
1540
+ function shouldRunDaily(lastDailyFile, today) {
1541
+ try {
1542
+ const lastRun = readFileSync(lastDailyFile, 'utf8').trim();
1543
+ return lastRun !== today;
1544
+ }
1545
+ catch {
1546
+ return true;
1547
+ }
1548
+ }
1549
+ function markDailyRun(lastDailyFile, today) {
1550
+ try {
1551
+ mkdirSync(dirname(lastDailyFile), { recursive: true });
1552
+ writeFileSync(lastDailyFile, today, 'utf8');
1553
+ }
1554
+ catch { /* best-effort */ }
1555
+ }
1556
+ export function formatDailyReport(report) {
1557
+ const L = [];
1558
+ L.push(`Evolver daily \u2014 ${report.date}`);
1559
+ L.push('');
1560
+ // Connection
1561
+ L.push('Connection');
1562
+ const c = report.connection;
1563
+ if (!c.proxyRunning) {
1564
+ L.push(' proxy not running');
1565
+ }
1566
+ else if (!c.proxyHealthy) {
1567
+ L.push(` proxy unhealthy (${c.reason ?? 'unknown'})`);
1568
+ }
1569
+ else {
1570
+ L.push(` proxy running${c.proxyPid ? ` (pid ${c.proxyPid})` : ''}${c.hubAuthStatus ? ` hub_auth=${c.hubAuthStatus}` : ''}`);
1571
+ }
1572
+ if (c.lastSyncAt)
1573
+ L.push(` last_sync ${c.lastSyncAt}`);
1574
+ L.push('');
1575
+ // Yesterday
1576
+ const y = report.yesterday;
1577
+ L.push(`Yesterday (${y.date})`);
1578
+ L.push(` cycles ${y.cycles} total ${y.solidified} solidified ${y.failed} failed`);
1579
+ L.push(` capsules ${y.capsules} produced`);
1580
+ L.push(` triggers ${y.triggered} triggered ${y.suppressed} suppressed`);
1581
+ L.push('');
1582
+ // Queue
1583
+ const q = report.queue;
1584
+ L.push('Queue');
1585
+ L.push(` genes ${q.genesApproved} approved ${q.genesQuarantined} quarantined ${q.genesRejected} rejected`);
1586
+ L.push(` anti-gene ${q.antiGeneApproved} approved ${q.antiGeneQuarantined} quarantined ${q.antiGeneUnreviewed} unreviewed`);
1587
+ return `${L.join('\n')}\n`;
1588
+ }
1589
+ export async function collectDailyReport(deps = {}) {
1590
+ const env = deps.env ?? process.env;
1591
+ const now = deps.now ? deps.now() : Date.now();
1592
+ const today = formatDay(new Date(now));
1593
+ const yesterdayPrefix = dayPrefixFromOffset(now, -1);
1594
+ // Events + daily summary
1595
+ const evts = readEvents(deps.eventsPath ?? events.rootEventsPath());
1596
+ const summary = events.dailySummary(evts, yesterdayPrefix);
1597
+ const capsules = dailyCapsuleCount(evts, yesterdayPrefix);
1598
+ // Connection status
1599
+ let connection = { proxyRunning: false, proxyHealthy: false };
1600
+ if (!deps.skipConnection) {
1601
+ const paths = deps.lifecyclePaths ?? lifecyclePaths(env);
1602
+ const conn = await dailyConnectionStatus(paths, env, { timeoutMs: 1500 });
1603
+ connection = {
1604
+ proxyRunning: conn.running,
1605
+ proxyHealthy: conn.healthy === true,
1606
+ proxyPid: conn.pid,
1607
+ hubAuthStatus: conn.hubAuthStatus,
1608
+ lastSyncAt: conn.lastSyncAt,
1609
+ reason: conn.reason,
1610
+ };
1611
+ }
1612
+ // Queue: gene review stats
1613
+ const store = deps.store ?? new assetstore.LocalJsonlProvider(events.assetsDir());
1614
+ const review = deps.review ?? reviewLedgerForStore(store);
1615
+ const reviewRecords = review.records();
1616
+ const geneReviewCounts = { approved: 0, quarantined: 0, rejected: 0 };
1617
+ const antiGeneReviewCounts = { approved: 0, quarantined: 0, unreviewed: 0 };
1618
+ // Build asset ID to type mapping
1619
+ const allGenes = await store.list('Gene', 10_000);
1620
+ const allAntiGenes = await store.list('AntiGene', 10_000);
1621
+ const antiGeneIds = new Set(allAntiGenes.map((a) => a.asset_id));
1622
+ // Count review records by asset type
1623
+ for (const r of reviewRecords) {
1624
+ if (antiGeneIds.has(r.assetId)) {
1625
+ // AntiGene review record
1626
+ if (r.state === 'quarantined')
1627
+ antiGeneReviewCounts.quarantined++;
1628
+ else if (r.state === 'approved')
1629
+ antiGeneReviewCounts.approved++;
1630
+ // rejected anti-gene: not shown separately per existing design
1631
+ }
1632
+ else {
1633
+ // Gene review record (or unknown asset type)
1634
+ if (r.state === 'quarantined')
1635
+ geneReviewCounts.quarantined++;
1636
+ else if (r.state === 'rejected')
1637
+ geneReviewCounts.rejected++;
1638
+ else if (r.state === 'approved')
1639
+ geneReviewCounts.approved++;
1640
+ }
1641
+ }
1642
+ // Genes without review records are default-approved
1643
+ const reviewedIds = new Set(reviewRecords.map((r) => r.assetId));
1644
+ const unreviewedGeneCount = allGenes.filter((g) => !reviewedIds.has(g.asset_id)).length;
1645
+ geneReviewCounts.approved += unreviewedGeneCount;
1646
+ // AntiGenes without explicit approval are unreviewed (fail-closed)
1647
+ for (const ag of allAntiGenes) {
1648
+ const r = review.get(ag.asset_id);
1649
+ if (!r || (r.state !== 'approved' && r.state !== 'quarantined')) {
1650
+ antiGeneReviewCounts.unreviewed++;
1651
+ }
1652
+ }
1653
+ return {
1654
+ date: today,
1655
+ connection,
1656
+ yesterday: {
1657
+ date: yesterdayPrefix,
1658
+ cycles: summary.cycles,
1659
+ solidified: summary.solidified,
1660
+ failed: summary.failed,
1661
+ capsules,
1662
+ triggered: summary.triggered,
1663
+ suppressed: summary.suppressed,
1664
+ },
1665
+ queue: {
1666
+ genesApproved: geneReviewCounts.approved,
1667
+ genesQuarantined: geneReviewCounts.quarantined,
1668
+ genesRejected: geneReviewCounts.rejected,
1669
+ antiGeneApproved: antiGeneReviewCounts.approved,
1670
+ antiGeneQuarantined: antiGeneReviewCounts.quarantined,
1671
+ antiGeneUnreviewed: antiGeneReviewCounts.unreviewed,
1672
+ },
1673
+ };
1674
+ }
1675
+ export async function runDaily(argv, deps = {}) {
1676
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
1677
+ const flags = parseFlags(argv);
1678
+ if ('help' in flags || 'h' in flags) {
1679
+ stdout(DAILY_USAGE);
1680
+ return 0;
1681
+ }
1682
+ const json = 'json' in flags;
1683
+ const auto = 'auto' in flags;
1684
+ const env = deps.env ?? process.env;
1685
+ const now = deps.now ? deps.now() : Date.now();
1686
+ const today = formatDay(new Date(now));
1687
+ // --auto: check if we already ran today
1688
+ if (auto) {
1689
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1690
+ if (!shouldRunDaily(lastDailyFile, today))
1691
+ return 0;
1692
+ }
1693
+ const report = await collectDailyReport(deps);
1694
+ if (json) {
1695
+ stdout(`${JSON.stringify({ ok: true, group: 'daily', ...report })}\n`);
1696
+ }
1697
+ else {
1698
+ stdout(formatDailyReport(report));
1699
+ }
1700
+ // Mark today as run (for --auto mode; harmless otherwise)
1701
+ if (auto) {
1702
+ const lastDailyFile = deps.lastDailyFile ?? defaultLastDailyFile(env);
1703
+ markDailyRun(lastDailyFile, today);
1704
+ }
1705
+ return 0;
1706
+ }
1388
1707
  export function runCli(argv) {
1389
1708
  const cmd = argv[0];
1390
1709
  if (cmd === undefined || cmd === '--help' || cmd === '-h') {