@evomap/evolver-cli 2.0.0-beta.9 → 2.0.1

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
@@ -0,0 +1,156 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { join, resolve } from 'node:path';
3
+ import { events, material as materialNs, signals } from '@evomap/evolver-core';
4
+ import { isCursorStateVscdbPath } from '@evomap/evolver-runtime-adapters';
5
+ import { emitSessionRecall } from './autoRecall.js';
6
+ import { buildRuntimeSessionMaterialSnapshot } from './materialSnapshot.js';
7
+ import { isRuntimeSessionSourcePath, parseRuntimeSessionSourcesWithDiagnostics, } from './runtimeSessionSource.js';
8
+ /** Material consumer group shared by ingestion and the downstream cycle consumer. */
9
+ export const INGEST_CONSUMER_GROUP = 'cycle';
10
+ export function resolveIngestDeps(deps) {
11
+ return {
12
+ materialStore: deps.materialStore ?? new materialNs.MaterialStore({ path: events.materialStorePath() }),
13
+ watermarkStore: deps.watermarkStore ?? new materialNs.WatermarkStore(events.materialWatermarkPath()),
14
+ ingestor: deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() }),
15
+ };
16
+ }
17
+ const MATERIAL_SOURCE_AGENTS = new Set([
18
+ 'claude-code',
19
+ 'codex',
20
+ 'cursor',
21
+ 'gemini',
22
+ 'antigravity',
23
+ 'kimi',
24
+ 'kiro',
25
+ 'opencode',
26
+ 'generic-chat',
27
+ ]);
28
+ export function toMaterialSourceAgent(agent) {
29
+ return MATERIAL_SOURCE_AGENTS.has(agent) ? agent : undefined;
30
+ }
31
+ function materialExistsFor(store, sourcePath, watermark) {
32
+ if (watermark.contentHash === undefined)
33
+ return false;
34
+ for (const material of store.iterate()) {
35
+ if (material.sourcePath === sourcePath
36
+ && material.watermark.size === watermark.size
37
+ && material.watermark.contentHash === watermark.contentHash)
38
+ return true;
39
+ }
40
+ return false;
41
+ }
42
+ export async function recordSessionMaterial(sourceAgent, absPath, signalCount, deps, recordCount = 1, payload, diagnostics) {
43
+ const previous = deps.watermarkStore.get(absPath);
44
+ const scan = materialNs.scanFile(absPath, previous);
45
+ if (previous && !scan.changed)
46
+ return { recorded: false, emitted: false };
47
+ const material = materialNs.buildMaterial({
48
+ sourceAgent,
49
+ sourceKind: 'runtime_session',
50
+ sourcePath: absPath,
51
+ kind: 'session_log',
52
+ watermark: scan.watermark,
53
+ consumerGroup: INGEST_CONSUMER_GROUP,
54
+ ...(payload ? { payload } : {}),
55
+ });
56
+ const isNew = !materialExistsFor(deps.materialStore, absPath, scan.watermark);
57
+ if (isNew)
58
+ await deps.materialStore.put(material);
59
+ const parseDiagnostics = diagnostics && diagnostics.invalidJson > 0
60
+ ? { rowsScanned: diagnostics.rowsScanned, rowsRead: diagnostics.rowsRead, invalidJson: diagnostics.invalidJson }
61
+ : undefined;
62
+ await deps.ingestor.ingest({
63
+ type: 'material.batch_ready',
64
+ payload: { source: absPath, recordCount, signalCount, ...(parseDiagnostics ? { parseDiagnostics } : {}) },
65
+ human: {
66
+ title: `material 已落地: ${sourceAgent} session`,
67
+ ...(parseDiagnostics ? { detail: `skipped ${parseDiagnostics.invalidJson} invalid JSONL row(s)` } : {}),
68
+ severity: 'info',
69
+ },
70
+ actor: { kind: 'machine' },
71
+ });
72
+ deps.watermarkStore.set(absPath, scan.watermark);
73
+ return { recorded: isNew, emitted: true, materialId: material.materialId };
74
+ }
75
+ /** Recursively enumerate recognized runtime-session sources, skipping inaccessible directories. */
76
+ export function scanSessionDirs(dirs) {
77
+ const out = [];
78
+ for (const dir of dirs) {
79
+ let entries;
80
+ try {
81
+ entries = readdirSync(resolve(dir), { recursive: true });
82
+ }
83
+ catch {
84
+ continue;
85
+ }
86
+ for (const entry of entries) {
87
+ const file = join(resolve(dir), entry);
88
+ if (isRuntimeSessionSourcePath(file))
89
+ out.push(file);
90
+ }
91
+ }
92
+ return out;
93
+ }
94
+ function sortedStrings(values) {
95
+ return [...new Set([...values].map(String).filter(Boolean))].sort();
96
+ }
97
+ /** Record all new or changed runtime sessions as material for the auto-distill loop. */
98
+ export async function runSessionIngestTick(dirs, deps = {}) {
99
+ const resolvedDeps = resolveIngestDeps(deps);
100
+ let recorded = 0;
101
+ const sourceAgents = new Set();
102
+ const signalKinds = new Set();
103
+ const signalStrengths = new Set();
104
+ let invalidJsonRows = 0;
105
+ let parseFailures = 0;
106
+ const autoRecallOn = process.env['EVOLVER_AUTO_RECALL'] === '1';
107
+ for (const file of scanSessionDirs(dirs)) {
108
+ let parsed;
109
+ try {
110
+ parsed = parseRuntimeSessionSourcesWithDiagnostics(file, undefined, deps.nativeSessionHome);
111
+ }
112
+ catch {
113
+ if (isCursorStateVscdbPath(file))
114
+ parseFailures += 1;
115
+ continue;
116
+ }
117
+ try {
118
+ const parsedSources = parsed.sources;
119
+ const agent = parsedSources[0] ? toMaterialSourceAgent(parsedSources[0].agent) : undefined;
120
+ if (parsedSources.length === 0 || !agent)
121
+ continue;
122
+ const signalsBySource = parsedSources.map((source) => signals.extractSignals(source.turns));
123
+ const snapshot = buildRuntimeSessionMaterialSnapshot(parsedSources);
124
+ const result = await recordSessionMaterial(agent, file, signalsBySource.reduce((sum, sourceSignals) => sum + sourceSignals.length, 0), resolvedDeps, parsedSources.length, snapshot, parsed.diagnostics);
125
+ if (result.emitted)
126
+ invalidJsonRows += parsed.diagnostics.invalidJson;
127
+ if (result.recorded) {
128
+ recorded += 1;
129
+ sourceAgents.add(agent);
130
+ for (const sourceSignals of signalsBySource) {
131
+ for (const signal of sourceSignals) {
132
+ signalKinds.add(signal.kind);
133
+ signalStrengths.add(signal.strength);
134
+ }
135
+ }
136
+ }
137
+ if (autoRecallOn && parsedSources.length === 1 && !parsedSources[0].sessionId) {
138
+ const turns = parsedSources[0].turns
139
+ .filter((turn) => !turn.isMeta)
140
+ .map((turn) => ({ role: turn.role, text: turn.text }));
141
+ await emitSessionRecall(file, turns, { ingestor: resolvedDeps.ingestor });
142
+ }
143
+ }
144
+ catch {
145
+ // Individual session files are best-effort and must not stop the daemon scan.
146
+ }
147
+ }
148
+ return {
149
+ recorded,
150
+ sourceAgents: sortedStrings(sourceAgents),
151
+ signalKinds: sortedStrings(signalKinds),
152
+ signalStrengths: sortedStrings(signalStrengths),
153
+ ...(invalidJsonRows > 0 ? { invalidJsonRows } : {}),
154
+ ...(parseFailures > 0 ? { parseFailures } : {}),
155
+ };
156
+ }
@@ -36,7 +36,7 @@ function parseFlags(argv) {
36
36
  }
37
37
  return out;
38
38
  }
39
- const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n`;
39
+ const USAGE = `usage: evolver setup-hooks [--runtime=${SETUP_RUNTIMES.join('|')}] [--scope=user|project|global] [--root=<dir>] [--env-file=<path>] [--profile-descriptor=<json>] [--service=${SERVICE_TARGETS.join('|')}] [--verify] [--uninstall] [--dry-run] [--force] [--json] [--hook-command="evolver inject session-start"] [--server-command=<cmd>] [--server-args=a,b] [--service-command=<cmd>] [--service-args=a,b]\n --verify is read-only for opencode and kiro\n`;
40
40
  export function commandNamesForPath(command, platform, pathExt) {
41
41
  if (platform !== 'win32' || /\.[^\\/]+$/.test(command))
42
42
  return [command];
@@ -402,7 +402,27 @@ function appendAdapterNotes(text, hints) {
402
402
  ? `${text}\n\nAdapter notes:\n${hints.map((hint) => ` - ${hint}`).join('\n')}`
403
403
  : text;
404
404
  }
405
+ const SETUP_VALUE_FLAGS = new Set([
406
+ 'runtime', 'platform', 'scope', 'root', 'env-file', 'profile-descriptor', 'service',
407
+ 'hook-command', 'server-command', 'server-args', 'service-command', 'service-args',
408
+ ]);
409
+ function setupHelpRequested(argv) {
410
+ if (argv.includes('--help'))
411
+ return true;
412
+ return argv.some((arg, index) => {
413
+ if (arg !== '-h')
414
+ return false;
415
+ const previous = argv[index - 1];
416
+ if (!previous?.startsWith('--') || previous.includes('='))
417
+ return true;
418
+ return !SETUP_VALUE_FLAGS.has(previous.slice(2));
419
+ });
420
+ }
405
421
  export async function runSetupHooks(argv, store, review, deps = {}) {
422
+ if (setupHelpRequested(argv)) {
423
+ process.stdout.write(USAGE);
424
+ return 0;
425
+ }
406
426
  const f = parseFlags(argv);
407
427
  const runtimeRaw = typeof f['runtime'] === 'string'
408
428
  ? f['runtime']
@@ -434,6 +454,80 @@ export async function runSetupHooks(argv, store, review, deps = {}) {
434
454
  const configRoot = typeof f['root'] === 'string' ? f['root'] : process.cwd();
435
455
  // claude-code: user scope targets ~/.claude.json regardless of --root; project scope uses configRoot.
436
456
  const scope = scopeResult.scope;
457
+ // V1 exposed setup-hooks --verify as a read-only operation. Silently ignoring it is unsafe: the command then
458
+ // falls through to installInjection and can rewrite runtime configuration while the operator asked only to
459
+ // inspect it. V2's JSON MCP installers already have a transaction-free dry-run preflight, so use that as the
460
+ // verifier for OpenCode and Kiro. Legacy installers do not have a proven read-only preflight and must refuse.
461
+ if (f['verify'] !== undefined) {
462
+ const verificationArgsValid = f['verify'] === true
463
+ && f['uninstall'] === undefined
464
+ && f['dry-run'] === undefined
465
+ && f['force'] === undefined;
466
+ if (!verificationArgsValid) {
467
+ const error = '--verify is read-only and cannot take a value or be combined with --uninstall, --dry-run, or --force';
468
+ if (json)
469
+ emit({ runtime, action: 'verify', ok: false, verified: false, files: [], error });
470
+ else
471
+ process.stderr.write(`${error}\n${USAGE}`);
472
+ return 2;
473
+ }
474
+ if (runtime !== 'opencode' && runtime !== 'kiro') {
475
+ const error = `--verify is not available for ${runtime}; no config was written`;
476
+ if (json)
477
+ emit({ runtime, action: 'verify', ok: false, verified: false, files: [], error });
478
+ else
479
+ process.stderr.write(`${error}\n`);
480
+ return 2;
481
+ }
482
+ const verifyDescriptor = profileDescriptorFromFlag(f);
483
+ if (!verifyDescriptor.ok) {
484
+ if (json)
485
+ emit({ runtime, action: 'verify', ok: false, verified: false, files: [], error: verifyDescriptor.error });
486
+ else
487
+ process.stderr.write(`${verifyDescriptor.error}\n`);
488
+ return 1;
489
+ }
490
+ let verification;
491
+ try {
492
+ const server = buildServer(f, verifyDescriptor.descriptor);
493
+ verification = installInjection(planInjection(runtime, server), {
494
+ configRoot,
495
+ server,
496
+ scope,
497
+ dryRun: true,
498
+ homeDir: homedir(),
499
+ kiroHome: process.env['KIRO_HOME'],
500
+ xdgConfigHome: process.env['XDG_CONFIG_HOME'],
501
+ opencodeConfig: process.env['OPENCODE_CONFIG'],
502
+ opencodeConfigDir: process.env['OPENCODE_CONFIG_DIR'],
503
+ });
504
+ }
505
+ catch (error) {
506
+ const message = safeSetupOperationError(error);
507
+ if (json)
508
+ emit({ runtime, action: 'verify', ok: false, verified: false, files: [], error: message });
509
+ else
510
+ process.stderr.write(`${message}\n`);
511
+ return 1;
512
+ }
513
+ if (!verification.ok) {
514
+ const message = safeSetupResultError(verification.error);
515
+ if (json)
516
+ emit({ runtime, action: 'verify', ok: false, verified: false, files: [], error: message });
517
+ else
518
+ process.stderr.write(`${message}\n`);
519
+ return 1;
520
+ }
521
+ const files = displayResultPaths(verification.files, configRoot, scope) ?? [];
522
+ const verified = verification.alreadyInstalled === true && verification.verified === true;
523
+ if (json)
524
+ emit({ runtime, action: 'verify', ok: verified, verified, files });
525
+ else
526
+ process.stdout.write(verified
527
+ ? `verified evolver setup for ${runtime}: ${files.join(', ')}\n`
528
+ : `evolver setup for ${runtime} is missing or does not match the requested configuration\n`);
529
+ return verified ? 0 : 1;
530
+ }
437
531
  if (f['dry-run'] === true && runtime !== 'opencode' && runtime !== 'kiro') {
438
532
  const error = `--dry-run is currently supported for opencode and kiro setup only; no config was written.`;
439
533
  if (json)
@@ -1,4 +1,6 @@
1
- import { type algo, type wire } from '@evomap/evolver-core';
1
+ import { type algo, type wire, verify } from '@evomap/evolver-core';
2
+ declare const isValidationCommandAllowed: typeof verify.isValidationCommandAllowed;
3
+ export { isValidationCommandAllowed };
2
4
  type GenerationSource = wire.GenerationSource;
3
5
  /** Max strategy steps kept from a skill (v1 parity: MAX_STRATEGY_STEPS). */
4
6
  export declare const MAX_STRATEGY_STEPS = 28;
@@ -14,16 +16,16 @@ export interface ParsedSkill {
14
16
  validation: string[];
15
17
  preconditions: string[];
16
18
  }
19
+ export interface ParseSkillMdOptions {
20
+ /** Preserve validation commands from every matching section for fail-closed callers. */
21
+ completeValidationPlan?: boolean;
22
+ }
17
23
  /**
18
24
  * Parse a SKILL.md into a structured intermediate — faithful port of v1 `parseSkillMd`. Pure. Section keywords are
19
25
  * matched against lower-cased headings and include CJK synonyms (skills authored in Chinese), though the signal
20
26
  * tokenizer keeps ASCII `[a-z0-9_]` only, so a CJK skill's signals come from its (English) frontmatter description.
21
27
  */
22
- export declare function parseSkillMd(skillMd: string): ParsedSkill;
23
- /** Whether a validation command is safe to run as a Gene.validation entry (faithful port of v1
24
- * policyCheck.isValidationCommandAllowed): a `node …` command with no command substitution, no shell
25
- * metacharacters (outside quoted strings), and no node eval flags (-e/--eval/--print/-p). */
26
- export declare function isValidationCommandAllowed(cmd: string): boolean;
28
+ export declare function parseSkillMd(skillMd: string, opts?: ParseSkillMdOptions): ParsedSkill;
27
29
  /** Infer a gene category from signals + description (v1 inferCategory): priority repair > innovate > optimize,
28
30
  * substring match (catches inflections + underscore signal tokens like `log_error`). */
29
31
  export declare function inferCategory(signals: readonly string[], description: string): string;
@@ -32,6 +34,7 @@ export interface SynthesizeOptions {
32
34
  skillName?: string;
33
35
  maxFiles?: number;
34
36
  }
37
+ export type SkillEvidenceMode = 'workflow_execution' | 'validation_only';
35
38
  export interface SynthesizeResult {
36
39
  gene: algo.GeneCandidate | null;
37
40
  errors: string[];
@@ -103,7 +106,7 @@ export interface SkillExecution {
103
106
  * hallucinating a successful run to pad the registry. Non-success executions are honest, so not checked. Returns
104
107
  * the rejection reason, or null when clean.
105
108
  */
106
- export declare function detectForgery(execution: SkillExecution): string | null;
109
+ export declare function detectForgery(execution: SkillExecution, evidenceMode?: SkillEvidenceMode): string | null;
107
110
  /** A synthesized Capsule (faithful to v1's shape; schema-conform / persistence is B3's concern). */
108
111
  export interface SkillCapsule {
109
112
  type: 'Capsule';
@@ -149,6 +152,7 @@ export type AssembleResult = {
149
152
  */
150
153
  export declare function assembleCapsule(gene: algo.GeneCandidate, execution: SkillExecution, opts?: {
151
154
  scenario?: string;
155
+ evidenceMode?: SkillEvidenceMode;
152
156
  }): AssembleResult;
153
157
  export interface ReverseDistillResult {
154
158
  gene: algo.GeneCandidate | null;
@@ -169,5 +173,5 @@ export interface ReverseDistillResult {
169
173
  */
170
174
  export declare function reverseDistill(parsed: ParsedSkill, execution?: SkillExecution, opts?: SynthesizeOptions & {
171
175
  scenario?: string;
172
- }): ReverseDistillResult;
173
- export {};
176
+ evidenceMode?: SkillEvidenceMode;
177
+ }): ReverseDistillResult;
package/dist/skill2gep.js CHANGED
@@ -4,21 +4,31 @@
4
4
  // faithful to v1 (golden-tested). B2 adds `synthesizeGene` + the Capsule contracts (trace-only / empty→Gene-only /
5
5
  // validation-coverage); the human-review + real-trace red lines live there.
6
6
  import { createHash } from 'node:crypto';
7
- import { bootstrap } from '@evomap/evolver-core';
7
+ import { bootstrap, verify } from '@evomap/evolver-core';
8
+ const { isValidationCommandAllowed } = verify;
9
+ // Re-export for backward compatibility (used by tests)
10
+ export { isValidationCommandAllowed };
8
11
  /** Max strategy steps kept from a skill (v1 parity: MAX_STRATEGY_STEPS). */
9
12
  export const MAX_STRATEGY_STEPS = 28;
10
13
  /** Gene id prefix for skill-distilled genes (v1 SKILL2GEP_ID_PREFIX). */
11
14
  const SKILL2GEP_ID_PREFIX = 'gene_s2g_';
12
15
  /** Default max-files constraint for a distilled gene (v1 skillDistiller.DISTILLED_MAX_FILES). */
13
16
  const SKILL_MAX_FILES = 12;
14
- /** Validation-command allowlist prefixes (v1 policyCheck): only `node …` is a runnable Gene.validation entry. */
15
- const VALIDATION_ALLOWED_PREFIXES = ['node '];
17
+ function sectionHeadingMatches(heading, keyword) {
18
+ if (/^[a-z0-9 ]+$/i.test(keyword)) {
19
+ const forms = keyword === 'verify'
20
+ ? ['verify', 'verification', 'verifications']
21
+ : [keyword, `${keyword}s`];
22
+ return forms.some((form) => new RegExp('(^|[^a-z0-9])' + form + '($|[^a-z0-9])', 'i').test(heading));
23
+ }
24
+ return heading.includes(keyword);
25
+ }
16
26
  /**
17
27
  * Parse a SKILL.md into a structured intermediate — faithful port of v1 `parseSkillMd`. Pure. Section keywords are
18
28
  * matched against lower-cased headings and include CJK synonyms (skills authored in Chinese), though the signal
19
29
  * tokenizer keeps ASCII `[a-z0-9_]` only, so a CJK skill's signals come from its (English) frontmatter description.
20
30
  */
21
- export function parseSkillMd(skillMd) {
31
+ export function parseSkillMd(skillMd, opts = {}) {
22
32
  const text = String(skillMd || '');
23
33
  // --- frontmatter (--- … --- block of key: value lines, keys lower-cased) ---
24
34
  const frontmatter = {};
@@ -35,15 +45,20 @@ export function parseSkillMd(skillMd) {
35
45
  // --- sections: split by `##+ heading`; content before the first heading is `_preamble`. A repeated heading
36
46
  // resets its block (last occurrence wins), matching v1. ---
37
47
  const lines = { _preamble: [] };
48
+ const sectionOccurrences = [{ key: '_preamble', lines: [] }];
38
49
  let currentKey = '_preamble';
50
+ let currentOccurrence = sectionOccurrences[0];
39
51
  body.split(/\n/).forEach((line) => {
40
52
  const hdr = line.match(/^##+\s+(.+?)\s*$/);
41
53
  if (hdr) {
42
54
  currentKey = hdr[1].toLowerCase().trim();
43
55
  lines[currentKey] = [];
56
+ currentOccurrence = { key: currentKey, lines: [] };
57
+ sectionOccurrences.push(currentOccurrence);
44
58
  }
45
59
  else {
46
60
  (lines[currentKey] ??= []).push(line);
61
+ currentOccurrence.lines.push(line);
47
62
  }
48
63
  });
49
64
  const sections = {};
@@ -70,6 +85,11 @@ export function parseSkillMd(skillMd) {
70
85
  }
71
86
  return out.join('\n');
72
87
  };
88
+ /** Every matching section occurrence, including repeated headings, in document order. */
89
+ const pickSectionOccurrencesAll = (keywords) => sectionOccurrences
90
+ .filter(({ key }) => keywords.some((kw) => sectionHeadingMatches(key, kw)))
91
+ .map(({ lines: occurrenceLines }) => occurrenceLines.join('\n').trim())
92
+ .join('\n');
73
93
  /** Every markdown list item → one step, in document order, length-bounded (default 5..300). */
74
94
  const extractSteps = (block, opts) => {
75
95
  const minLen = opts && typeof opts.minLen === 'number' ? opts.minLen : 5;
@@ -109,7 +129,10 @@ export function parseSkillMd(skillMd) {
109
129
  ]));
110
130
  // --- validation: the bash/sh fenced commands in the validation/test section (non-comment, ≤300) ---
111
131
  const validation = [];
112
- const valBlock = pickSection(['validation', 'test', 'verify', 'check', '校验', '验证', '测试', '检查']);
132
+ const validationKeywords = ['validation', 'test', 'verify', 'check', '校验', '验证', '测试', '检查'];
133
+ const valBlock = opts.completeValidationPlan
134
+ ? pickSectionOccurrencesAll(validationKeywords)
135
+ : pickSection(validationKeywords);
113
136
  const fenceRe = /```(?:bash|sh|shell)?\s*\n([\s\S]*?)\n```/g;
114
137
  let fence;
115
138
  while ((fence = fenceRe.exec(valBlock)) !== null) {
@@ -129,28 +152,10 @@ export function parseSkillMd(skillMd) {
129
152
  signals_match: signals.slice(0, 8),
130
153
  strategy: strategy.slice(0, MAX_STRATEGY_STEPS),
131
154
  avoid: avoid.slice(0, 5),
132
- validation: validation.slice(0, 5),
155
+ validation: opts.completeValidationPlan ? validation : validation.slice(0, 5),
133
156
  preconditions: preconditions.slice(0, 4),
134
157
  };
135
158
  }
136
- /** Whether a validation command is safe to run as a Gene.validation entry (faithful port of v1
137
- * policyCheck.isValidationCommandAllowed): a `node …` command with no command substitution, no shell
138
- * metacharacters (outside quoted strings), and no node eval flags (-e/--eval/--print/-p). */
139
- export function isValidationCommandAllowed(cmd) {
140
- const c = String(cmd || '').trim();
141
- if (!c)
142
- return false;
143
- if (!VALIDATION_ALLOWED_PREFIXES.some((p) => c.startsWith(p)))
144
- return false;
145
- if (/`|\$\(/.test(c))
146
- return false; // no command substitution
147
- const stripped = c.replace(/"[^"]*"/g, '').replace(/'[^']*'/g, ''); // ignore metachars inside quotes
148
- if (/[;&|><]/.test(stripped))
149
- return false; // no chaining / redirection
150
- if (/^node\s+(-e|--eval|--print|-p)\b/.test(c))
151
- return false; // no inline eval
152
- return true;
153
- }
154
159
  /** Stable slug for a skill-distilled gene id (v1 slugify). */
155
160
  function slugify(s) {
156
161
  return String(s || '').toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '').slice(0, 60);
@@ -351,7 +356,7 @@ const shortHash = (s) => createHash('sha256').update(String(s ?? '')).digest('he
351
356
  * hallucinating a successful run to pad the registry. Non-success executions are honest, so not checked. Returns
352
357
  * the rejection reason, or null when clean.
353
358
  */
354
- export function detectForgery(execution) {
359
+ export function detectForgery(execution, evidenceMode = 'workflow_execution') {
355
360
  const trace = Array.isArray(execution?.trace) ? execution.trace : [];
356
361
  const files = Number(execution?.blast_radius?.files ?? 0);
357
362
  const lines = Number(execution?.blast_radius?.lines ?? 0);
@@ -359,7 +364,7 @@ export function detectForgery(execution) {
359
364
  return null;
360
365
  if (trace.length === 0)
361
366
  return 'empty_execution_trace';
362
- if (files === 0 && lines === 0)
367
+ if (evidenceMode === 'workflow_execution' && files === 0 && lines === 0)
363
368
  return 'zero_blast_radius_with_success';
364
369
  if (!trace.some((t) => Number.isInteger(t?.exit)))
365
370
  return 'no_exit_code_in_trace';
@@ -410,9 +415,13 @@ export function assembleCapsule(gene, execution, opts = {}) {
410
415
  confidence: Math.max(0, Math.min(1, score)),
411
416
  blast_radius: { files, lines },
412
417
  outcome: { status, score },
413
- success_reason: status === 'success' ? (execution?.success_reason || 'Skill workflow completed and all declared validations passed.') : null,
418
+ success_reason: status === 'success'
419
+ ? (execution?.success_reason || (opts.evidenceMode === 'validation_only'
420
+ ? 'All declared validation commands passed in the local verifier.'
421
+ : 'Skill workflow completed and all declared validations passed.'))
422
+ : null,
414
423
  env_fingerprint: bootstrap.captureEnvFingerprint(),
415
- source_type: 'skill2gep_hook',
424
+ source_type: opts.evidenceMode === 'validation_only' ? 'skill2gep_validation' : 'skill2gep_hook',
416
425
  strategy: Array.isArray(gene.strategy) ? [...gene.strategy] : [],
417
426
  content: execution?.content_summary || buildContentSummary(trace, execution?.blast_radius),
418
427
  execution_trace: trace.map((t, i) => ({
@@ -438,12 +447,15 @@ export function reverseDistill(parsed, execution = {}, opts = {}) {
438
447
  let capsule = null;
439
448
  let capsuleDiagnostic = null;
440
449
  if (execution?.status) {
441
- const forgery = detectForgery(execution);
450
+ const forgery = detectForgery(execution, opts.evidenceMode);
442
451
  if (forgery) {
443
452
  capsuleDiagnostic = { reason: 'capsule_rejected_forgery', detail: forgery };
444
453
  }
445
454
  else {
446
- const r = assembleCapsule(gene, execution, opts.scenario ? { scenario: opts.scenario } : {});
455
+ const r = assembleCapsule(gene, execution, {
456
+ ...(opts.scenario ? { scenario: opts.scenario } : {}),
457
+ ...(opts.evidenceMode ? { evidenceMode: opts.evidenceMode } : {}),
458
+ });
447
459
  if (r.ok)
448
460
  capsule = r.capsule;
449
461
  else
@@ -1,5 +1,5 @@
1
1
  import { assetstore, events } from '@evomap/evolver-core';
2
- import { type SkillExecution, type SynthesizeOptions } from './skill2gep.js';
2
+ import { type SkillEvidenceMode, type SkillExecution, type SynthesizeOptions } from './skill2gep.js';
3
3
  export interface DiscoveredSkill {
4
4
  /** The skill's directory name (`<dir>/skills/<name>/`) — its canonical id, used for dedup. */
5
5
  name: string;
@@ -34,6 +34,12 @@ export interface SkillDistillResult {
34
34
  capsuleDiagnostic: string | null;
35
35
  errors: string[];
36
36
  }
37
+ export interface SkillDistillationOptions extends SynthesizeOptions {
38
+ scenario?: string;
39
+ evidenceMode?: SkillEvidenceMode;
40
+ geneIdentity?: 'signals' | 'semantic';
41
+ completeValidationPlan?: boolean;
42
+ }
37
43
  /**
38
44
  * Distill a SKILL.md + its real execution into a pooled gene (+ capsule evidence) (B3a). The gene lands
39
45
  * QUARANTINED — same human-review gate (A2a/A2b) as every auto-draft, so a skill-distilled gene never enters a
@@ -42,9 +48,7 @@ export interface SkillDistillResult {
42
48
  * diagnostic. Idempotent on the gene (intake dedups by signals; quarantine is sticky). NEVER throws on a bad
43
49
  * skill — returns errors instead, so a daemon scanning many skills is not broken by one.
44
50
  */
45
- export declare function recordSkillDistillation(skillMd: string, execution: SkillExecution, deps: SkillDistillDeps, opts?: SynthesizeOptions & {
46
- scenario?: string;
47
- }): Promise<SkillDistillResult>;
51
+ export declare function recordSkillDistillation(skillMd: string, execution: SkillExecution, deps: SkillDistillDeps, opts?: SkillDistillationOptions): Promise<SkillDistillResult>;
48
52
  /**
49
53
  * `evolver skill-distill --skill <SKILL.md|dir> [--execution <json|@file>] [--scenario <name>] [--strict]` (B3b-ii).
50
54
  *
@@ -5,9 +5,10 @@
5
5
  // the gene.distilled audit event, and persisting the capsule evidence. The session→execution-trace extraction that
6
6
  // turns a discovered skill into a Capsule-bearing distillation is B3b-ii (a separate slice).
7
7
  import { readdirSync, readFileSync, statSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
8
+ import { createHash } from 'node:crypto';
8
9
  import { join, resolve, dirname } from 'node:path';
9
10
  import { assetstore, algo, events } from '@evomap/evolver-core';
10
- import { parseSkillMd, reverseDistill } from './skill2gep.js';
11
+ import { parseSkillMd, reverseDistill, } from './skill2gep.js';
11
12
  import { reviewLedgerForStore } from './reviewFilter.js';
12
13
  /**
13
14
  * Discover procedural skills under the given roots (B3b-i): each `<root>/skills/<name>/SKILL.md`. Pure enumeration
@@ -51,16 +52,20 @@ export function discoverSkills(roots) {
51
52
  */
52
53
  export async function recordSkillDistillation(skillMd, execution, deps, opts = {}) {
53
54
  const review = deps.review ?? reviewLedgerForStore(deps.store);
54
- const parsed = parseSkillMd(skillMd);
55
+ const parsed = parseSkillMd(skillMd, { completeValidationPlan: opts.completeValidationPlan });
55
56
  const { gene, capsule, capsuleDiagnostic } = reverseDistill(parsed, execution, opts);
56
57
  const diag = capsuleDiagnostic ? (capsuleDiagnostic.detail ?? capsuleDiagnostic.reason) : null;
57
58
  if (!gene)
58
59
  return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: ['gene synthesis refused (strict mode or empty)'] };
59
- const existing = (await deps.store.list('Gene', 1000)).map((g) => ({
60
- id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
61
- signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
62
- }));
63
- const r = algo.intakeGene(gene, existing);
60
+ const semanticIdentity = opts.geneIdentity === 'semantic';
61
+ const existing = semanticIdentity
62
+ ? []
63
+ : (await deps.store.list('Gene', 1000)).map((g) => ({
64
+ id: typeof g['id'] === 'string' ? String(g['id']) : undefined,
65
+ signals_match: Array.isArray(g['signals_match']) ? g['signals_match'] : [],
66
+ }));
67
+ const candidate = semanticIdentity ? { ...gene, id: semanticGeneId(gene) } : gene;
68
+ const r = algo.intakeGene(candidate, existing);
64
69
  if (!r.ok || !r.gene)
65
70
  return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: r.errors };
66
71
  const assetId = String(r.gene.asset_id);
@@ -78,7 +83,7 @@ export async function recordSkillDistillation(skillMd, execution, deps, opts = {
78
83
  await deps.ingestor.ingest({
79
84
  type: 'gene.distilled',
80
85
  payload: { geneId, assetId: r.gene.asset_id, category: r.gene.category, source: 'skill2gep', skill: parsed.name },
81
- human: { title: `skill-distilled gene ${geneId} (UNPROVEN — awaiting review)`, severity: 'info' },
86
+ human: { title: `skill-distilled gene ${geneId} (UNPROVEN — awaiting review)`.slice(0, 80), severity: 'info' },
82
87
  actor: { kind: 'machine', id: 'skill2gep' },
83
88
  });
84
89
  }
@@ -90,7 +95,11 @@ export async function recordSkillDistillation(skillMd, execution, deps, opts = {
90
95
  // intakeGene may REWRITE the gene id (it only keeps an id already in the distilled-prefix namespace), so the
91
96
  // capsule — built from the pre-intake candidate id — must be re-pointed to the POOLED gene id, else it
92
97
  // references a gene that is not in the store.
93
- const pooledCapsule = { ...capsule, gene: geneId };
98
+ const pooledCapsule = {
99
+ ...capsule,
100
+ ...(semanticIdentity ? { id: semanticCapsuleId(geneId, capsule.id) } : {}),
101
+ gene: geneId,
102
+ };
94
103
  await deps.store.put(pooledCapsule); // evidence; references the (gated) gene
95
104
  capsuleId = pooledCapsule.id;
96
105
  }
@@ -102,6 +111,26 @@ export async function recordSkillDistillation(skillMd, execution, deps, opts = {
102
111
  return { geneId: null, geneAssetId: null, quarantined: false, capsuleId: null, capsuleDiagnostic: diag, errors: [e instanceof Error ? e.message : String(e)] };
103
112
  }
104
113
  }
114
+ function semanticGeneId(gene) {
115
+ const constraints = gene.constraints ?? {};
116
+ const normalized = JSON.stringify({
117
+ category: String(gene.category ?? ''),
118
+ signals: [...(gene.signals_match ?? [])].map((value) => String(value).trim().toLowerCase()).filter(Boolean).sort(),
119
+ strategy: [...(gene.strategy ?? [])].map((value) => String(value).trim()).filter(Boolean),
120
+ summary: String(gene.summary ?? ''),
121
+ preconditions: [...(gene.preconditions ?? [])].map((value) => String(value).trim()).filter(Boolean),
122
+ constraints: {
123
+ maxFiles: Number(constraints.max_files ?? 0),
124
+ forbiddenPaths: [...(constraints.forbidden_paths ?? [])].map((value) => String(value).trim()).filter(Boolean).sort(),
125
+ },
126
+ validation: [...(gene.validation ?? [])].map((value) => String(value).replace(/\s+/g, ' ').trim()).filter(Boolean),
127
+ });
128
+ return `gene_distilled_${createHash('sha256').update(normalized).digest('hex').slice(0, 24)}`;
129
+ }
130
+ function semanticCapsuleId(geneId, originalCapsuleId) {
131
+ const digest = createHash('sha256').update(`${geneId}|${originalCapsuleId}`).digest('hex').slice(0, 24);
132
+ return `cap_s2g_${digest}`;
133
+ }
105
134
  /** Resolve a `--skill` argument (a SKILL.md file OR a skill directory) to the SKILL.md path. */
106
135
  function resolveSkillMdPath(skillArg) {
107
136
  const p = resolve(skillArg);
package/dist/solo/mode.js CHANGED
@@ -34,6 +34,7 @@ export function applySoloLockdown(env = process.env) {
34
34
  EVOLVER_ATP: 'off',
35
35
  EVOLVER_ATP_AUTOBUY: 'off',
36
36
  EVOLVER_ATP_AUTODELIVER: 'off',
37
+ EVOLVER_LEARNING_TRACE_UPLOAD: '0',
37
38
  // Empty hub creds so any lower-level connector short-circuits.
38
39
  A2A_HUB_URL: '',
39
40
  EVOMAP_HUB_URL: '',
package/dist/sync.d.ts CHANGED
@@ -21,6 +21,18 @@ export interface SyncCliDeps {
21
21
  hub: PublicHubCapability;
22
22
  auth: hubNs.AuthProvider;
23
23
  };
24
+ connectPrivateHub?: (env: NodeJS.ProcessEnv) => Promise<SyncAccountAssetHub>;
25
+ /** Opaque identity supplied by an injected Hub adapter; it is hashed again before any checkpoint write. */
26
+ resumeIdentityFingerprint?: string;
24
27
  }
25
28
  export declare function runSyncCommand(argv: readonly string[], deps?: SyncCliDeps): Promise<number>;
29
+ export declare function preparePrivateSyncHub(runtime: {
30
+ hub: unknown;
31
+ hello(opts: {
32
+ rotate: boolean;
33
+ evolverVersion?: string;
34
+ }): Promise<{
35
+ ok: boolean;
36
+ }>;
37
+ }): Promise<SyncAccountAssetHub>;
26
38
  export {};