@evomap/evolver-cli 2.0.19 → 2.0.24

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.
package/dist/skill2gep.js CHANGED
@@ -14,6 +14,19 @@ export const MAX_STRATEGY_STEPS = 28;
14
14
  const SKILL2GEP_ID_PREFIX = 'gene_s2g_';
15
15
  /** Default max-files constraint for a distilled gene (v1 skillDistiller.DISTILLED_MAX_FILES). */
16
16
  const SKILL_MAX_FILES = 12;
17
+ const WORKFLOW_SECTION_KEYWORDS = [
18
+ 'workflow', 'strategy', 'steps', 'procedure', 'quick start', 'how to',
19
+ 'human gate', 'output contract', 'release', 'rollback', 'promotion',
20
+ 'process each', 'request process', 'request path',
21
+ '工作流', '流程', '步骤', '核心方法', '方法', '快速规则', '规则',
22
+ '输出门', '输出门槛', '人工确认', '人工门', '回滚', '发布', '晋级',
23
+ ];
24
+ // 安全与请求章节属于策略,而不是可选说明;丢失它们会让蒸馏后的 Skill 缺少审批和信任边界契约。
25
+ const GOVERNANCE_SECTION_KEYWORDS = [
26
+ 'security', 'safety', 'credential', 'approval', 'adversarial',
27
+ 'trust boundary', 'content isolation', 'untrusted content',
28
+ 'protect x data', 'protect data', 'data protection', 'privacy', 'legal basis', 'consent',
29
+ ];
17
30
  function sectionHeadingMatches(heading, keyword) {
18
31
  if (/^[a-z0-9 ]+$/i.test(keyword)) {
19
32
  const forms = keyword === 'verify'
@@ -105,6 +118,49 @@ export function parseSkillMd(skillMd, opts = {}) {
105
118
  }
106
119
  return steps;
107
120
  };
121
+ /** 将只有 prose 的安全章节中的声明式防护规则保留为有界策略语句。 */
122
+ const extractGovernanceStatements = (blocks) => {
123
+ const statements = [];
124
+ for (const block of blocks) {
125
+ let fenceMarker;
126
+ for (const rawLine of String(block || '').split(/\n/)) {
127
+ const line = rawLine.trim();
128
+ if (fenceMarker !== undefined) {
129
+ const closingFence = line.match(/^(`+|~+)$/);
130
+ if (closingFence !== null
131
+ && closingFence[1][0] === fenceMarker.char
132
+ && closingFence[1].length >= fenceMarker.length) {
133
+ fenceMarker = undefined;
134
+ }
135
+ continue;
136
+ }
137
+ const openingFence = line.match(/^(`{3,}|~{3,})(?:.*)?$/);
138
+ if (openingFence !== null) {
139
+ fenceMarker = { char: openingFence[1][0], length: openingFence[1].length };
140
+ continue;
141
+ }
142
+ if (!line || /^<\/?[A-Z0-9_-]+(?:>|\s)/.test(line))
143
+ continue;
144
+ const listItem = line.match(/^(?:\d+\.|[-*])\s+(.+?)\s*$/);
145
+ const statement = (listItem ? listItem[1] : line).replace(/^>\s?/, '').trim();
146
+ if (statement.length >= 5 && statement.length <= 300 && !statements.includes(statement)) {
147
+ statements.push(statement);
148
+ }
149
+ }
150
+ }
151
+ return statements;
152
+ };
153
+ const matchingGovernanceBlocks = sectionOccurrences
154
+ .filter(({ key }) => GOVERNANCE_SECTION_KEYWORDS.some((kw) => sectionHeadingMatches(key, kw)))
155
+ .map(({ lines: occurrenceLines }) => occurrenceLines.join('\n').trim());
156
+ const selectStrategySteps = (workflowSteps, governanceSteps) => {
157
+ const workflow = [...new Set(workflowSteps)];
158
+ const governance = [...new Set(governanceSteps)];
159
+ if (workflow.length + governance.length <= MAX_STRATEGY_STEPS)
160
+ return [...workflow, ...governance];
161
+ return [...governance.slice(0, MAX_STRATEGY_STEPS), ...workflow]
162
+ .slice(0, MAX_STRATEGY_STEPS);
163
+ };
108
164
  // --- signals: frontmatter.description + the trigger/when section, tokenized to [a-z0-9_] (3..40, has-letter) ---
109
165
  const signals = [];
110
166
  const signalSource = (frontmatter['description'] || '') + '\n' + pickSection([
@@ -117,12 +173,7 @@ export function parseSkillMd(skillMd, opts = {}) {
117
173
  signals.push(s);
118
174
  });
119
175
  // --- strategy: workflow + governance-tail sections; avoid: anti-pattern sections ---
120
- const strategy = extractSteps(pickSectionsAll([
121
- 'workflow', 'strategy', 'steps', 'procedure', 'quick start', 'how to',
122
- 'human gate', 'output contract', 'release', 'rollback', 'promotion',
123
- '工作流', '流程', '步骤', '核心方法', '方法', '快速规则', '规则',
124
- '输出门', '输出门槛', '人工确认', '人工门', '回滚', '发布', '晋级',
125
- ]));
176
+ const strategy = selectStrategySteps(extractSteps(pickSectionsAll(WORKFLOW_SECTION_KEYWORDS)), extractGovernanceStatements(matchingGovernanceBlocks));
126
177
  const avoid = extractSteps(pickSectionsAll([
127
178
  'avoid', 'pitfall', 'anti-pattern', 'common mistake', 'do not', 'forbidden', "don't",
128
179
  '不要做', '不要', '常见错误', '避免', '陷阱', '禁止',
@@ -300,7 +351,17 @@ export function synthesizeGene(parsed, execution = {}, opts = {}) {
300
351
  strategy.push('Run the Skill validation commands and abort if any fails.');
301
352
  }
302
353
  const rawValidations = Array.isArray(parsed.validation) ? parsed.validation : [];
303
- const allowedValidations = rawValidations.map((v) => String(v || '').trim()).filter((v) => v && isValidationCommandAllowed(v));
354
+ const normalizedValidations = rawValidations.map((v) => String(v || '').trim()).filter(Boolean);
355
+ const sanitizedValidations = normalizedValidations.map((command) => verify.sanitizeExecutionCommand(command));
356
+ if (sanitizedValidations.some((command) => command.changed || command.blocked)) {
357
+ return {
358
+ gene: null,
359
+ errors: ['execution_validation_unsafe: validation commands must not contain credential-bearing arguments'],
360
+ generation_meta: { source, quality_score: computeQualityScore(source, parsed, execution) },
361
+ };
362
+ }
363
+ const allowedValidations = sanitizedValidations.map((command) => command.value)
364
+ .filter((command) => isValidationCommandAllowed(command));
304
365
  if (opts.strict && allowedValidations.length === 0) {
305
366
  return {
306
367
  gene: null,
@@ -432,7 +493,10 @@ export function assembleCapsule(gene, execution, opts = {}) {
432
493
  })),
433
494
  schema_version: '1.6.0',
434
495
  };
435
- return { ok: true, capsule };
496
+ const sanitized = verify.sanitizeExecutionPayload(capsule);
497
+ if (sanitized.blocked)
498
+ return { ok: false, reason: 'execution_trace_unsafe' };
499
+ return { ok: true, capsule: sanitized.value };
436
500
  }
437
501
  /**
438
502
  * Reverse-distill a parsed SKILL.md + its execution into GEP assets — the PURE core of v1 runOnSkillInvocation
@@ -9,7 +9,7 @@
9
9
  // tick the cadence check — this is the bus's first live built-in observer.
10
10
  import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
11
11
  import { dirname, join } from 'node:path';
12
- import { events, observers, ops } from '@evomap/evolver-core';
12
+ import { assetstore, events, observers, ops } from '@evomap/evolver-core';
13
13
  import { loadPriceTable } from '@evomap/evolver-adapter-public';
14
14
  /** Markdown file sink: appends each weekly digest to <home>/evolution/value-digest.md (inspectable history). */
15
15
  export function fileDigestSink(path) {
@@ -87,6 +87,13 @@ export function resolveValueDigestObserver(env = process.env, opts = {}) {
87
87
  events: events.readEvents(eventsPath),
88
88
  prices,
89
89
  }, window),
90
+ digestExtras: async () => {
91
+ const store = new assetstore.LocalJsonlProvider(events.assetsDir());
92
+ const review = assetstore.reviewLedgerForStore(store);
93
+ return {
94
+ pendingReviewCount: (await assetstore.pendingGeneReviewRecords(store, review)).length,
95
+ };
96
+ },
90
97
  sink: multiSink(sinks),
91
98
  state: new FileDigestState(join(home, 'evolution', 'value-digest-state.json')),
92
99
  });
@@ -0,0 +1,228 @@
1
+ import { acquireBootstrapOwnerLock } from './lifecycleBootstrapTransaction.js';
2
+ /** The only task names this module ever probes; nothing outside this set is ever touched. */
3
+ export declare const LEGACY_WINDOWS_TASK_NAMES: readonly ["EvoMapEvolverProxyDaemon", "EvoMapEvolverAutoexecDaemon"];
4
+ export type LegacyWindowsTaskName = (typeof LEGACY_WINDOWS_TASK_NAMES)[number];
5
+ export declare const LEGACY_TASK_SKIP_ENV = "EVOLVER_SKIP_LEGACY_TASK_PROBE";
6
+ export declare const LEGACY_TASK_COOLDOWN_FILE = "legacy-task-cleanup.json";
7
+ export declare const LEGACY_TASK_PREIMAGE_DIR = "legacy-task-preimages";
8
+ export declare const LEGACY_TASK_PROVENANCE_FILE = "legacy-task-provenance.json";
9
+ export declare const LEGACY_TASK_PROVENANCE_PUBLIC_KEY_ENV = "EVOLVER_LEGACY_TASK_PROVENANCE_PUBLIC_KEY";
10
+ export declare const LEGACY_TASK_PROVENANCE_SCHEMA = "evolver/windows-legacy-task-provenance/v1";
11
+ export declare const LEGACY_TASK_COOLDOWN_MS: number;
12
+ declare const COOLDOWN_MARKER_SCHEMA = "evolver/legacy-task-cleanup/v1";
13
+ export type LegacyTaskCleanupStatus = 'clean' | 'legacy_detected' | 'cleaned' | 'inconclusive' | 'failed' | 'skipped';
14
+ export type LegacyTaskClassification = 'absent' | 'legacy' | 'current' | 'foreign' | 'ambiguous';
15
+ export interface LegacyTaskRunResult {
16
+ status: number | null;
17
+ error?: Error;
18
+ stdout?: string;
19
+ stderr?: string;
20
+ }
21
+ /** Spawn seam: tests inject a fake PowerShell; production uses the trusted absolute path. */
22
+ export type LegacyTaskRun = (command: string, args: readonly string[], timeoutMs: number) => LegacyTaskRunResult;
23
+ export interface LegacyTaskEntry {
24
+ name: string;
25
+ classification: LegacyTaskClassification;
26
+ /** Bounded, operator-safe reason (no raw output, no absolute paths). */
27
+ reason?: string;
28
+ outcome?: 'removed' | 'kept' | 'removal-failed' | 'removal-aborted';
29
+ /** State-relative preimage filename, present once removal succeeded for this task. */
30
+ preimage?: string;
31
+ }
32
+ export interface LegacyTaskCleanupResult {
33
+ status: LegacyTaskCleanupStatus;
34
+ dryRun: boolean;
35
+ tasks: LegacyTaskEntry[];
36
+ /** Bounded detail for inconclusive/failed/skipped states. */
37
+ detail?: string;
38
+ }
39
+ export interface LegacyTaskCleanupOptions {
40
+ env: NodeJS.ProcessEnv;
41
+ stateDir?: string;
42
+ dryRun?: boolean;
43
+ platform?: NodeJS.Platform;
44
+ run?: LegacyTaskRun;
45
+ now?: () => number;
46
+ /**
47
+ * Caller already holds the bootstrap owner lock (post-commit bootstrap sweep). When set,
48
+ * this module asserts ownership through the seam instead of re-acquiring the lock.
49
+ */
50
+ assertOwner?: () => void;
51
+ lock?: {
52
+ maxTries?: number;
53
+ waitMs?: number;
54
+ };
55
+ }
56
+ export interface LegacyTaskProbeResult {
57
+ conclusive: boolean;
58
+ legacy: string[];
59
+ detail: string;
60
+ }
61
+ export interface LegacyTaskProvenancePayload {
62
+ schema: typeof LEGACY_TASK_PROVENANCE_SCHEMA;
63
+ taskName: LegacyWindowsTaskName;
64
+ taskPath: '\\';
65
+ definitionHash: string;
66
+ principalSid: string;
67
+ issuedAt: string;
68
+ expiresAt?: string;
69
+ signatureAlg: 'ed25519';
70
+ }
71
+ export interface LegacyTaskProvenanceReceipt extends LegacyTaskProvenancePayload {
72
+ signature: string;
73
+ }
74
+ interface LoadedLegacyTaskProvenance {
75
+ receipts: ReadonlyMap<LegacyWindowsTaskName, LegacyTaskProvenanceReceipt>;
76
+ detail?: string;
77
+ }
78
+ interface ProbedTaskRecord {
79
+ name?: unknown;
80
+ present?: unknown;
81
+ ambiguous?: unknown;
82
+ count?: unknown;
83
+ taskPath?: unknown;
84
+ actionCount?: unknown;
85
+ execute?: unknown;
86
+ arguments?: unknown;
87
+ workingDirectory?: unknown;
88
+ triggerCount?: unknown;
89
+ userId?: unknown;
90
+ principalSid?: unknown;
91
+ logonType?: unknown;
92
+ runLevel?: unknown;
93
+ enabled?: unknown;
94
+ restartCount?: unknown;
95
+ description?: unknown;
96
+ definitionHash?: unknown;
97
+ }
98
+ interface CooldownMarker {
99
+ schema: typeof COOLDOWN_MARKER_SCHEMA;
100
+ lastConclusiveAt: string;
101
+ status: 'clean' | 'cleaned' | 'inconclusive' | 'failed';
102
+ removed: string[];
103
+ /** Consecutive inconclusive/failed sweep count; present only on negative markers. */
104
+ attempts?: number;
105
+ /** Earliest instant the next automatic sweep may retry; present only on negative markers. */
106
+ nextRetryAt?: string;
107
+ }
108
+ declare function defaultLegacyTaskRun(): LegacyTaskRun;
109
+ export declare function canonicalLegacyTaskProvenanceBytes(payload: LegacyTaskProvenancePayload): Buffer;
110
+ declare function parseLegacyTaskProvenanceReceipt(value: unknown, publicKey: string, now: number): LegacyTaskProvenanceReceipt | undefined;
111
+ declare function loadLegacyTaskProvenance(stateDir: string, env: NodeJS.ProcessEnv, now: number): LoadedLegacyTaskProvenance;
112
+ /** True when the automatic entry points must never cross the Task Scheduler boundary. */
113
+ export declare function legacyTaskProbeSkipped(env: NodeJS.ProcessEnv): boolean;
114
+ declare function renderExportScript(name: LegacyWindowsTaskName, expectedHash?: string, receipt?: LegacyTaskProvenanceReceipt): string;
115
+ /**
116
+ * Fingerprint revalidation → stop → revalidation → unregister → absence verification for
117
+ * one task (the bootstrap rollback unregister pattern). Exit codes: 0 removed, 3 count
118
+ * drift, 4 action drift, 5 execute/provenance refusal, 6 TaskPath drift, 7 stop timeout, 8
119
+ * absence not confirmed, 9 scheduler error, 10 definition drift.
120
+ */
121
+ declare function renderMutationScript(name: LegacyWindowsTaskName, expectedHash?: string, receipt?: LegacyTaskProvenanceReceipt): string;
122
+ /**
123
+ * Restore refuses to overwrite: it re-registers a persisted preimage only when the known
124
+ * name is currently absent. Exit codes: 0 restored, 3 name already present, 4 registration
125
+ * verification failed after a guarded rollback, 5 preimage changed while restoring, 9
126
+ * scheduler error, 11 rollback could not prove that the just-registered generation was still
127
+ * present (the task is deliberately left for operator inspection).
128
+ */
129
+ declare function renderRestoreScript(name: LegacyWindowsTaskName, preimageReadPath: string, expectedHash?: string): string;
130
+ declare function parseProbeRecords(stdout: string): ProbedTaskRecord[] | undefined;
131
+ export declare function classifyProbedTask(record: ProbedTaskRecord | undefined, provenance?: LegacyTaskProvenanceReceipt): {
132
+ classification: LegacyTaskClassification;
133
+ reason?: string;
134
+ };
135
+ declare function preimageDirFor(stateDir: string): string;
136
+ declare function cooldownMarkerPath(stateDir: string): string;
137
+ declare function readCooldownMarker(stateDir: string): CooldownMarker | undefined;
138
+ /** Negative-backoff delay for inconclusive/failed sweeps: 1h base, doubling, capped at 24h. */
139
+ declare function legacyTaskNegativeBackoffMs(attempts: number): number;
140
+ declare function writeCooldownMarker(stateDir: string, status: 'clean' | 'cleaned', removed: string[], now: () => number): void;
141
+ declare function writeNegativeCooldownMarker(stateDir: string, status: 'inconclusive' | 'failed', attempts: number, now: () => number): void;
142
+ /**
143
+ * Manual cleanup owns the lifecycle lock before it probes. Without this outer lock a clean
144
+ * probe could race a concurrent bootstrap that registers a legacy-named task and then publish
145
+ * a positive cooldown marker, suppressing the next real sweep for 24 hours. Automatic callers
146
+ * already hold the same lock and pass `assertOwner`, while dry-run remains read-only.
147
+ */
148
+ export declare function cleanupLegacyWindowsDaemonTasks(options: LegacyTaskCleanupOptions): LegacyTaskCleanupResult;
149
+ /** Read-only probe for `evolver doctor` — never mutates, never throws. */
150
+ export declare function probeLegacyWindowsDaemonTasks(options: {
151
+ env: NodeJS.ProcessEnv;
152
+ platform?: NodeJS.Platform;
153
+ run?: LegacyTaskRun;
154
+ stateDir?: string;
155
+ }): LegacyTaskProbeResult;
156
+ /**
157
+ * Automatic entry point (SessionStart hook). Throttled by the cooldown marker: after a
158
+ * conclusive success the sweep skips re-probing for the cooldown window; an
159
+ * inconclusive/failed run writes a NEGATIVE backoff marker (1h base, doubling per
160
+ * consecutive failure, capped at 24h) and the sweep skips until `nextRetryAt`, so a
161
+ * constrained host does not spawn PowerShell on every session. A conclusive success
162
+ * overwrites the marker, resetting the backoff counter. Never throws.
163
+ */
164
+ export declare function maybeCleanupLegacyWindowsDaemonTasks(options: {
165
+ env: NodeJS.ProcessEnv;
166
+ platform?: NodeJS.Platform;
167
+ stateDir?: string;
168
+ run?: LegacyTaskRun;
169
+ now?: () => number;
170
+ cooldownMs?: number;
171
+ lock?: {
172
+ maxTries?: number;
173
+ waitMs?: number;
174
+ };
175
+ }): LegacyTaskCleanupResult | undefined;
176
+ /**
177
+ * Post-bootstrap sweep seam: runs under the already-held bootstrap owner lock and returns
178
+ * report lines for the bootstrap `actions`. Never throws and never fails the bootstrap —
179
+ * but a failed/inconclusive sweep is reported honestly instead of being dropped.
180
+ */
181
+ export declare function sweepLegacyWindowsDaemonTasksAfterBootstrap(options: {
182
+ env: NodeJS.ProcessEnv;
183
+ stateDir: string;
184
+ assertOwner: () => void;
185
+ platform?: NodeJS.Platform;
186
+ run?: LegacyTaskRun;
187
+ }): string[];
188
+ /**
189
+ * Manual restore of a persisted preimage. Only files named `<KnownTaskName>.<stamp>.xml`
190
+ * are accepted, the target name must be currently ABSENT (restore never overwrites), and
191
+ * the XML is validated before it reaches PowerShell. Never throws.
192
+ */
193
+ export declare function restoreLegacyTaskPreimage(preimagePath: string, options: {
194
+ env: NodeJS.ProcessEnv;
195
+ platform?: NodeJS.Platform;
196
+ run?: LegacyTaskRun;
197
+ stateDir?: string;
198
+ lock?: {
199
+ maxTries?: number;
200
+ waitMs?: number;
201
+ };
202
+ }): {
203
+ status: 'restored' | 'failed';
204
+ task?: string;
205
+ detail: string;
206
+ };
207
+ export declare const _legacyTaskInternalsForTest: {
208
+ PROBE_SCRIPT: string;
209
+ acquireBootstrapOwnerLock: typeof acquireBootstrapOwnerLock;
210
+ defaultLegacyTaskRun: typeof defaultLegacyTaskRun;
211
+ canonicalLegacyTaskProvenanceBytes: typeof canonicalLegacyTaskProvenanceBytes;
212
+ parseLegacyTaskProvenanceReceipt: typeof parseLegacyTaskProvenanceReceipt;
213
+ loadLegacyTaskProvenance: typeof loadLegacyTaskProvenance;
214
+ renderExportScript: typeof renderExportScript;
215
+ renderMutationScript: typeof renderMutationScript;
216
+ renderRestoreScript: typeof renderRestoreScript;
217
+ parseProbeRecords: typeof parseProbeRecords;
218
+ readCooldownMarker: typeof readCooldownMarker;
219
+ writeCooldownMarker: typeof writeCooldownMarker;
220
+ writeNegativeCooldownMarker: typeof writeNegativeCooldownMarker;
221
+ negativeBackoffMs: typeof legacyTaskNegativeBackoffMs;
222
+ cooldownMarkerPath: typeof cooldownMarkerPath;
223
+ preimageDirFor: typeof preimageDirFor;
224
+ cleanupClassifiedLegacyTasksForTest: typeof cleanupClassifiedLegacyTasksForTest;
225
+ };
226
+ /** Test-only wrapper for mutation mechanics; callers must supply preclassified legacy entries. */
227
+ declare function cleanupClassifiedLegacyTasksForTest(options: LegacyTaskCleanupOptions, entries: LegacyTaskEntry[], expectedDefinitionHashes?: ReadonlyMap<string, string>, expectedProvenanceReceipts?: ReadonlyMap<string, LegacyTaskProvenanceReceipt>): LegacyTaskCleanupResult;
228
+ export {};