@evomap/evolver-cli 2.0.50 → 2.0.51

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.
@@ -0,0 +1,9 @@
1
+ import { ops } from '@evomap/evolver-core';
2
+ export interface AssetEvolutionDeps {
3
+ assetsDir?: string;
4
+ readEvents?: () => readonly ops.EvolutionRootEvent[];
5
+ now?: () => number;
6
+ stdout?: (text: string) => void;
7
+ }
8
+ /** `evolver asset-evolution`: the local reuse/evolution read model as one versioned JSON envelope. */
9
+ export declare function runAssetEvolutionCommand(argv: readonly string[], deps?: AssetEvolutionDeps): Promise<number>;
@@ -0,0 +1,164 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { assetstore, events, ops } from '@evomap/evolver-core';
3
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
4
+ const DEFAULT_LIMIT = 100;
5
+ const MAX_LIMIT = 1_000;
6
+ const MAX_GENES = 5_000;
7
+ const MAX_CAPSULES = 20_000;
8
+ const MAX_EVENTS = 100_000;
9
+ const ASSET_REF = /^(?:sha256:[a-f0-9]{64}|[A-Za-z0-9][A-Za-z0-9_.:-]{0,199})$/;
10
+ const USAGE = [
11
+ 'Usage:',
12
+ ' evolver asset-evolution --json [--limit=N] overview of local experiences, reuse and lineage',
13
+ ' evolver asset-evolution --json --asset=<id> [--limit=N] one asset by content id or logical id',
14
+ '',
15
+ 'Read-only. Reads the local asset store, review/provenance sidecars and root events; never calls the Hub.',
16
+ '',
17
+ ].join('\n');
18
+ class AssetEvolutionFailure extends Error {
19
+ code;
20
+ constructor(code, message) {
21
+ super(message);
22
+ this.code = code;
23
+ }
24
+ }
25
+ function flagValue(argv, index, name) {
26
+ const arg = argv[index];
27
+ if (arg.startsWith(`--${name}=`))
28
+ return { value: arg.slice(name.length + 3), next: index + 1 };
29
+ if (arg !== `--${name}`)
30
+ return null;
31
+ const value = argv[index + 1];
32
+ if (value === undefined || value.startsWith('--'))
33
+ throw new AssetEvolutionFailure('INPUT_INVALID', `--${name} 需要填写内容。`);
34
+ return { value, next: index + 2 };
35
+ }
36
+ function parseLimit(value) {
37
+ if (!/^\d+$/.test(value) || Number(value) < 1)
38
+ throw new AssetEvolutionFailure('INPUT_INVALID', '--limit 需要正整数。');
39
+ return Math.min(MAX_LIMIT, Number(value));
40
+ }
41
+ function operationOf(argv) {
42
+ return argv.some((arg) => arg === '--asset' || arg.startsWith('--asset=')) ? 'asset' : 'overview';
43
+ }
44
+ function parseRequest(argv) {
45
+ const request = { operation: operationOf(argv), limit: DEFAULT_LIMIT, help: false };
46
+ for (let index = 0; index < argv.length;) {
47
+ const arg = argv[index];
48
+ if (arg === '--json') {
49
+ index += 1;
50
+ continue;
51
+ }
52
+ if (arg === '--help' || arg === '-h') {
53
+ request.help = true;
54
+ index += 1;
55
+ continue;
56
+ }
57
+ const limit = flagValue(argv, index, 'limit');
58
+ const asset = limit ? null : flagValue(argv, index, 'asset');
59
+ if (!limit && !asset)
60
+ throw new AssetEvolutionFailure('INPUT_INVALID', `不支持的参数:${arg.slice(0, 40)}`);
61
+ if (limit)
62
+ request.limit = parseLimit(limit.value);
63
+ if (asset && !ASSET_REF.test(asset.value))
64
+ throw new AssetEvolutionFailure('INPUT_INVALID', '--asset 需要资产 ID(sha256:…)或逻辑 ID。');
65
+ if (asset)
66
+ request.asset = asset.value;
67
+ index = (limit ?? asset).next;
68
+ }
69
+ return request;
70
+ }
71
+ // The provider loads its whole index either way, so the caps bound the projection's work and output, not the read;
72
+ // they keep the newest records, and a cut is reported so absence is never read as proof.
73
+ async function readStore(dir) {
74
+ if (!existsSync(dir))
75
+ return { genes: [], capsules: [], ok: true, truncated: false };
76
+ try {
77
+ const store = new assetstore.LocalJsonlProvider(dir);
78
+ const allGenes = await store.list('Gene', Number.MAX_SAFE_INTEGER);
79
+ const allCapsules = await store.list('Capsule', Number.MAX_SAFE_INTEGER);
80
+ return {
81
+ genes: allGenes.slice(-MAX_GENES), capsules: allCapsules.slice(-MAX_CAPSULES), ok: true,
82
+ truncated: allGenes.length > MAX_GENES || allCapsules.length > MAX_CAPSULES,
83
+ };
84
+ }
85
+ catch {
86
+ return { genes: [], capsules: [], ok: false, truncated: false };
87
+ }
88
+ }
89
+ function readSidecars(dir) {
90
+ if (!existsSync(dir))
91
+ return { reviewHistory: [], provenance: new Map(), ok: true };
92
+ try {
93
+ return { reviewHistory: new assetstore.ReviewLedger(dir).history(), provenance: new assetstore.ProvenanceStore(dir).snapshot(), ok: true };
94
+ }
95
+ catch {
96
+ return { reviewHistory: [], provenance: new Map(), ok: false };
97
+ }
98
+ }
99
+ /** Root events go through the core reader, which reaches the protected-audit store over RPC where one is installed. */
100
+ function readRootEvents(deps) {
101
+ try {
102
+ const all = deps.readEvents ? deps.readEvents() : events.readEvents(events.rootEventsPath());
103
+ return { events: all.slice(-MAX_EVENTS), ok: true, truncated: all.length > MAX_EVENTS };
104
+ }
105
+ catch {
106
+ return { events: [], ok: false, truncated: false };
107
+ }
108
+ }
109
+ async function readInput(deps) {
110
+ if (loadEnvFileFromEnv(process.env).error)
111
+ throw new AssetEvolutionFailure('UNAVAILABLE', '无法读取 EVOLVER_ENV_FILE,请检查本地 Evolver 配置。');
112
+ const dir = deps.assetsDir ?? events.assetsDir();
113
+ const stored = await readStore(dir);
114
+ const sidecars = readSidecars(dir);
115
+ const rootEvents = readRootEvents(deps);
116
+ return {
117
+ now: (deps.now ?? Date.now)(),
118
+ genes: stored.genes,
119
+ capsules: stored.capsules,
120
+ reviewHistory: sidecars.reviewHistory,
121
+ provenance: sidecars.provenance,
122
+ events: rootEvents.events,
123
+ sources: { assets: stored.ok, review: sidecars.ok, rootEvents: rootEvents.ok, truncated: stored.truncated || rootEvents.truncated },
124
+ };
125
+ }
126
+ function unavailable(input) {
127
+ return !input.sources.assets && !input.sources.review && !input.sources.rootEvents;
128
+ }
129
+ async function resultFor(request, deps) {
130
+ const input = await readInput(deps);
131
+ if (unavailable(input))
132
+ throw new AssetEvolutionFailure('UNAVAILABLE', '本地经验库和事件记录暂时都读不到,请检查 Evolver 安装与目录权限。');
133
+ if (request.operation === 'overview')
134
+ return ops.projectAssetEvolutionOverview(input, { limit: request.limit });
135
+ const dossier = ops.projectAssetEvolutionDossier(input, request.asset, { limit: request.limit });
136
+ if (dossier)
137
+ return dossier;
138
+ if (!input.sources.assets || !input.sources.rootEvents)
139
+ throw new AssetEvolutionFailure('UNAVAILABLE', '部分本地记录暂时读不到,无法确认这条经验。');
140
+ if (input.sources.truncated)
141
+ throw new AssetEvolutionFailure('UNAVAILABLE', '本地记录超出本次读取范围,无法确认这条经验是否存在。');
142
+ throw new AssetEvolutionFailure('NOT_FOUND', '本机没有这条经验的记录。');
143
+ }
144
+ /** `evolver asset-evolution`: the local reuse/evolution read model as one versioned JSON envelope. */
145
+ export async function runAssetEvolutionCommand(argv, deps = {}) {
146
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
147
+ const operation = operationOf(argv);
148
+ const emit = (payload) => stdout(`${JSON.stringify({ schema: ops.ASSET_EVOLUTION_SCHEMA, operation, ...payload })}\n`);
149
+ try {
150
+ const request = parseRequest(argv);
151
+ if (request.help) {
152
+ stdout(USAGE);
153
+ return 0;
154
+ }
155
+ emit({ ok: true, result: await resultFor(request, deps) });
156
+ return 0;
157
+ }
158
+ catch (error) {
159
+ const failure = error instanceof AssetEvolutionFailure ? error
160
+ : new AssetEvolutionFailure('UNAVAILABLE', '未能读取资产演进记录,请检查本地 Evolver 安装与目录权限。');
161
+ emit({ ok: false, code: failure.code, error: failure.message });
162
+ return failure.code === 'INPUT_INVALID' ? 2 : 1;
163
+ }
164
+ }
@@ -22,6 +22,8 @@ export declare const COMMAND_GROUPS: {
22
22
  readonly inject: "Memory";
23
23
  readonly recall: "Memory";
24
24
  readonly experience: "Memory";
25
+ readonly gene: "Memory";
26
+ readonly redact: "Tools";
25
27
  readonly 'mcp-stdio': "Tools";
26
28
  readonly reuse: "Memory";
27
29
  readonly 'reuse-report': "Memory";
@@ -33,6 +35,7 @@ export declare const COMMAND_GROUPS: {
33
35
  readonly 'asset-log': "Assets";
34
36
  readonly 'asset-trust': "Assets";
35
37
  readonly 'asset-health': "Assets";
38
+ readonly 'asset-evolution': "Assets";
36
39
  readonly 'asset-repair': "Assets";
37
40
  readonly material: "Assets";
38
41
  readonly reference: "Assets";
@@ -43,6 +46,7 @@ export declare const COMMAND_GROUPS: {
43
46
  readonly phub: "Hub";
44
47
  readonly sync: "Hub";
45
48
  readonly publish: "Hub";
49
+ readonly 'publish-policy': "Hub";
46
50
  readonly fetch: "Hub";
47
51
  readonly buy: "Hub";
48
52
  readonly orders: "Hub";
@@ -35,6 +35,8 @@ export const COMMAND_GROUPS = {
35
35
  inject: 'Memory',
36
36
  recall: 'Memory',
37
37
  experience: 'Memory',
38
+ gene: 'Memory',
39
+ redact: 'Tools',
38
40
  'mcp-stdio': 'Tools',
39
41
  reuse: 'Memory',
40
42
  'reuse-report': 'Memory',
@@ -46,6 +48,7 @@ export const COMMAND_GROUPS = {
46
48
  'asset-log': 'Assets',
47
49
  'asset-trust': 'Assets',
48
50
  'asset-health': 'Assets',
51
+ 'asset-evolution': 'Assets',
49
52
  'asset-repair': 'Assets',
50
53
  material: 'Assets',
51
54
  reference: 'Assets',
@@ -56,6 +59,7 @@ export const COMMAND_GROUPS = {
56
59
  phub: 'Hub',
57
60
  sync: 'Hub',
58
61
  publish: 'Hub',
62
+ 'publish-policy': 'Hub',
59
63
  fetch: 'Hub',
60
64
  buy: 'Hub',
61
65
  orders: 'Hub',
@@ -0,0 +1,8 @@
1
+ export type ContainedWriteResult = {
2
+ ok: true;
3
+ } | {
4
+ ok: false;
5
+ reason: 'exists' | 'unsafe_path';
6
+ };
7
+ export declare function relativePathInsideRoot(root: string, requested: string): string | null;
8
+ export declare function writeFileInsideRoot(root: string, relPath: string, content: string, overwrite: boolean): ContainedWriteResult;
@@ -0,0 +1,79 @@
1
+ import { closeSync, constants, lstatSync, mkdirSync, openSync, writeFileSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, resolve, sep } from 'node:path';
3
+ // Windows has no O_NOFOLLOW; there the lstat check before open is the only guard against a linked target.
4
+ const NO_FOLLOW = constants.O_NOFOLLOW ?? 0;
5
+ export function relativePathInsideRoot(root, requested) {
6
+ const fromRoot = relative(resolve(root), resolve(root, requested));
7
+ const escapes = fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot);
8
+ if (escapes)
9
+ return null;
10
+ return fromRoot || '.';
11
+ }
12
+ export function writeFileInsideRoot(root, relPath, content, overwrite) {
13
+ const parts = relPath.split(sep).filter((part) => part && part !== '.');
14
+ const fileName = parts.pop();
15
+ if (!fileName || parts.includes('..'))
16
+ return { ok: false, reason: 'unsafe_path' };
17
+ let dir = resolve(root);
18
+ for (const part of parts) {
19
+ dir = join(dir, part);
20
+ if (!ensureRealDirectory(dir))
21
+ return { ok: false, reason: 'unsafe_path' };
22
+ }
23
+ return writeRegularFile(join(dir, fileName), content, overwrite);
24
+ }
25
+ function ensureRealDirectory(path) {
26
+ if (!lstatOrNull(path)) {
27
+ try {
28
+ mkdirSync(path);
29
+ }
30
+ catch (error) {
31
+ if (!isErrno(error, 'EEXIST'))
32
+ throw error;
33
+ }
34
+ }
35
+ const stat = lstatOrNull(path);
36
+ return Boolean(stat && stat.isDirectory() && !stat.isSymbolicLink());
37
+ }
38
+ function writeRegularFile(path, content, overwrite) {
39
+ const existing = lstatOrNull(path);
40
+ if (existing && !isUnsharedRegularFile(existing))
41
+ return { ok: false, reason: 'unsafe_path' };
42
+ if (existing && !overwrite)
43
+ return { ok: false, reason: 'exists' };
44
+ const createMode = overwrite ? constants.O_TRUNC : constants.O_EXCL;
45
+ let fd;
46
+ try {
47
+ fd = openSync(path, constants.O_WRONLY | constants.O_CREAT | createMode | NO_FOLLOW, 0o644);
48
+ }
49
+ catch (error) {
50
+ if (isErrno(error, 'EEXIST'))
51
+ return { ok: false, reason: 'exists' };
52
+ if (isErrno(error, 'ELOOP'))
53
+ return { ok: false, reason: 'unsafe_path' };
54
+ throw error;
55
+ }
56
+ try {
57
+ writeFileSync(fd, content, 'utf8');
58
+ }
59
+ finally {
60
+ closeSync(fd);
61
+ }
62
+ return { ok: true };
63
+ }
64
+ function isUnsharedRegularFile(stat) {
65
+ return stat.isFile() && stat.nlink === 1;
66
+ }
67
+ function lstatOrNull(path) {
68
+ try {
69
+ return lstatSync(path);
70
+ }
71
+ catch (error) {
72
+ if (isErrno(error, 'ENOENT'))
73
+ return null;
74
+ throw error;
75
+ }
76
+ }
77
+ function isErrno(error, code) {
78
+ return typeof error === 'object' && error !== null && error.code === code;
79
+ }
package/dist/dispatch.js CHANGED
@@ -18,6 +18,9 @@ import { runRecipeCommand } from './recipe.js';
18
18
  import { runReuseCommand } from './reuse.js';
19
19
  import { runPublishCommand } from './cliContracts.js';
20
20
  import { runExperienceCommand } from './experience.js';
21
+ import { runGeneCommand } from './gene.js';
22
+ import { runRedactCommand } from './redact.js';
23
+ import { runPublishPolicyCommand } from './publishPolicy.js';
21
24
  import { runMcpStdioCommand } from './mcpStdio.js';
22
25
  import { runRecallCommand } from './recall.js';
23
26
  import { runReuseReportCommand } from './reuseReport.js';
@@ -39,6 +42,7 @@ import { runDashboardCommand } from './dashboard.js';
39
42
  import { runIssueReportCommand } from './issueReport.js';
40
43
  import { runAssetTrustCommand } from './assetTrust.js';
41
44
  import { runAssetHealthCommand } from './assetHealth.js';
45
+ import { runAssetEvolutionCommand } from './assetEvolution.js';
42
46
  import { runAssetRepairCommand } from './assetRepair.js';
43
47
  import { runV1FetchCompat, runV1RunCompat, runV1SolidifyCompat, runV1WebuiCompat, runV1ExecCompat } from './v1Compat.js';
44
48
  import { runWorkflowCommand } from './workflow.js';
@@ -81,6 +85,9 @@ const ASYNC_COMMAND_TABLE = {
81
85
  sync: runSyncCommand,
82
86
  recall: runRecallCommand,
83
87
  experience: runExperienceCommand,
88
+ gene: runGeneCommand,
89
+ redact: runRedactCommand,
90
+ 'publish-policy': runPublishPolicyCommand,
84
91
  'mcp-stdio': runMcpStdioCommand,
85
92
  'reuse-report': runReuseReportCommand,
86
93
  'recall-verify-report': runRecallVerifyReportCommand,
@@ -98,6 +105,7 @@ const ASYNC_COMMAND_TABLE = {
98
105
  'issue-report': runIssueReportCommand,
99
106
  'asset-trust': runAssetTrustCommand,
100
107
  'asset-health': runAssetHealthCommand,
108
+ 'asset-evolution': runAssetEvolutionCommand,
101
109
  'asset-repair': runAssetRepairCommand,
102
110
  proxy: runProxyCommand,
103
111
  run: runV1RunCompat,
@@ -1,6 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { deflateRawSync, inflateRawSync, brotliCompressSync, brotliDecompressSync, constants as zlibConstants } from 'node:zlib';
3
3
  import * as assetstore from '@evomap/evolver-core/experience';
4
+ import { RUNTIME_NAME, pluginDrafts } from './pluginDrafts.js';
4
5
  const LIMIT = 64 * 1024;
5
6
  async function input() {
6
7
  const chunks = [];
@@ -91,6 +92,11 @@ function flags(argv) {
91
92
  }
92
93
  return result;
93
94
  }
95
+ const ASSET_DISTILL_CAPABILITIES = { authoring: true, redaction: true, geneDistill: true, evidence: true, publishControl: true, contract: 'asset-distill.v1' };
96
+ function evidenceView(row) {
97
+ return { evidenceId: row.evidenceId, kind: row.kind, outcome: row.outcome, summary: row.summary, metrics: row.metrics,
98
+ ...(row.taskId ? { taskId: row.taskId } : {}), at: row.at, capsule: row.capsule };
99
+ }
94
100
  function diagnostic(error) {
95
101
  if (process.env['EVOLVER_EXPERIENCE_DIAGNOSTICS'] !== '1')
96
102
  return;
@@ -119,7 +125,8 @@ export async function runExperienceCommand(argv) {
119
125
  throw new assetstore.ExperienceError('INPUT_INVALID', '只用参数的模式只支持生成检查码、检查和查询。');
120
126
  }
121
127
  if (operation === 'capabilities') {
122
- emit({ ok: true, capabilities: { library: true, confirmedMutations: true, fullPlanBinding: true, durableRecovery: true, compactConfirmation: true, sourceRecovery: true, localOnly: true, originalMaterialsShared: false, activity: true, mcpStdio: true } });
128
+ emit({ ok: true, capabilities: { library: true, confirmedMutations: true, fullPlanBinding: true, durableRecovery: true, compactConfirmation: true, sourceRecovery: true, localOnly: true, originalMaterialsShared: false, activity: true, mcpStdio: true,
129
+ ...ASSET_DISTILL_CAPABILITIES } });
123
130
  return 0;
124
131
  }
125
132
  const library = new assetstore.ExperienceLibrary(assetstore.assetsDir());
@@ -170,9 +177,34 @@ export async function runExperienceCommand(argv) {
170
177
  emit({ ok: true, result: await library.list(f['query'] ?? '', Number(f['limit'] ?? 50), Number(f['offset'] ?? 0)) });
171
178
  return 0;
172
179
  }
180
+ if (operation === 'drafts') {
181
+ const request = await input();
182
+ if (request.runtime !== undefined && !(typeof request.runtime === 'string' && RUNTIME_NAME.test(request.runtime))) {
183
+ throw new assetstore.ExperienceError('INPUT_INVALID', 'runtime 只能是小写字母、数字和连字符。');
184
+ }
185
+ let drafts;
186
+ try {
187
+ drafts = pluginDrafts(process.env, request.runtime);
188
+ }
189
+ catch {
190
+ throw new assetstore.ExperienceError('UNAVAILABLE', '读不到插件草稿目录(~/.evolver/state),请检查目录权限。');
191
+ }
192
+ emit({ ok: true, result: drafts });
193
+ return 0;
194
+ }
195
+ if (operation === 'evidence') {
196
+ const row = await library.recordEvidence(await input());
197
+ emit({ ok: true, result: { evidenceId: row.evidenceId, capsule: row.capsule } });
198
+ return 0;
199
+ }
200
+ if (operation === 'evidence-list') {
201
+ const request = await input();
202
+ emit({ ok: true, result: { evidence: (await library.evidence(request.assetId)).map(evidenceView) } });
203
+ return 0;
204
+ }
173
205
  if (operation === 'plan') {
174
206
  const request = await input();
175
- const plan = await library.plan(f['action'], request.assetId, request.input);
207
+ const plan = await library.plan(f['action'], request.assetId, request.input, { gene: request.gene, capsule: request.capsule, antiGene: request.antiGene });
176
208
  const confirmation = confirmationFor(plan);
177
209
  emit({ ok: true, plan, ...(confirmation ? { confirmation } : {}) });
178
210
  return 0;
package/dist/gene.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import { type JsonCommandIo } from './jsonCommand.js';
2
+ /** `evolver gene <operation> --json`: author, check and distill Genes locally. Nothing is stored, published or sent to a model. */
3
+ export declare function runGeneCommand(argv: string[], io?: JsonCommandIo): Promise<number>;
package/dist/gene.js ADDED
@@ -0,0 +1,174 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { assetstore, authoring, events, hub } from '@evomap/evolver-core';
3
+ import { JsonCommandError, LARGE_REQUEST_BYTES, SMALL_REQUEST_BYTES, inputError, operationOf, optionalEnum, optionalString, optionalStrings, readJsonRequest, requestLocale, requiredEnum, requiredObject, requiredString, runJsonCommand, } from './jsonCommand.js';
4
+ const GENE_SCHEMA = 'evolver.gene.v1';
5
+ const OPERATIONS = ['template', 'build', 'get', 'lint', 'probe', 'ir-prompt', 'distill', 'prepare-publish'];
6
+ const CATEGORIES = ['repair', 'optimize', 'innovate', 'explore'];
7
+ const PLATFORMS = ['claude-code', 'codex', 'paste'];
8
+ const MAX_PROBE_TASKS = 5;
9
+ const MAX_TASK_CHARS = 300;
10
+ const SNAPSHOT_BUDGET = { maxRecords: 20_000, maxFileBytes: 16 * 1024 * 1024, maxTotalBytes: 48 * 1024 * 1024 };
11
+ function template(request, locale) {
12
+ const category = optionalEnum(request, 'category', CATEGORIES, locale) ?? 'repair';
13
+ return {
14
+ markdown: authoring.geneTemplateMarkdown(category, locale),
15
+ gene: { type: 'Gene', category, signals_match: [], strategy: [], constraints: { max_files: 1, forbidden_paths: [...authoring.DEFAULT_FORBIDDEN_PATHS] }, validation: [] },
16
+ };
17
+ }
18
+ function build(request, locale) {
19
+ const format = requiredEnum(request, 'format', ['markdown', 'json'], locale);
20
+ const source = requiredString(request, 'source', locale, SMALL_REQUEST_BYTES);
21
+ const supersedes = optionalString(request, 'supersedes', locale, 80);
22
+ return authoring.buildGene({ format, source, locale, ...(supersedes === undefined ? {} : { supersedes }) });
23
+ }
24
+ function probeState(gene, snapshot) {
25
+ if (snapshot.provenance.get(gene.asset_id)?.trusted === false)
26
+ return null;
27
+ const review = snapshot.review.get(gene.asset_id);
28
+ if (review?.state === 'quarantined')
29
+ return 'pending';
30
+ if (review?.state === 'rejected')
31
+ return review.reason === 'experience:paused' ? 'paused' : null;
32
+ return 'active';
33
+ }
34
+ async function localCandidates(locale) {
35
+ const dir = events.assetsDir();
36
+ if (!existsSync(dir))
37
+ return [];
38
+ let snapshot;
39
+ try {
40
+ snapshot = await assetstore.readLocalGeneSnapshot(dir, { ...SNAPSHOT_BUDGET, deadlineAt: Date.now() + 10_000 });
41
+ }
42
+ catch {
43
+ throw new JsonCommandError('UNAVAILABLE', authoring.say(locale, '暂时读不到本地经验库,无法比较相似经验。', 'The local experience library cannot be read right now.'));
44
+ }
45
+ return snapshot.genes.flatMap((gene) => {
46
+ const state = probeState(gene, snapshot);
47
+ return state ? [{ gene, state }] : [];
48
+ });
49
+ }
50
+ async function probe(request, locale) {
51
+ const gene = requiredObject(request, 'gene', locale);
52
+ const tasks = optionalStrings(request, 'tasks', locale, MAX_PROBE_TASKS, MAX_TASK_CHARS) ?? [];
53
+ if (tasks.length === 0 || tasks.some((task) => !task.trim())) {
54
+ throw inputError(locale, `请给 1–${MAX_PROBE_TASKS} 个任务描述,每个不超过 ${MAX_TASK_CHARS} 字。`, `Give 1–${MAX_PROBE_TASKS} task descriptions of at most ${MAX_TASK_CHARS} characters.`);
55
+ }
56
+ return authoring.probeGene(gene, tasks, await localCandidates(locale));
57
+ }
58
+ function recordsOf(request, locale) {
59
+ const records = request['records'];
60
+ if (records === undefined)
61
+ return undefined;
62
+ if (!Array.isArray(records) || records.some((line) => !line || typeof line !== 'object' || typeof line['kind'] !== 'string' || typeof line['text'] !== 'string')) {
63
+ throw inputError(locale, 'records 需要是 {kind, text, exit?, failed?} 记录行列表。', 'records must be a list of {kind, text, exit?, failed?} record lines.');
64
+ }
65
+ return records;
66
+ }
67
+ function irPrompt(request, locale) {
68
+ const kind = optionalEnum(request, 'kind', authoring.IR_KINDS, locale);
69
+ const outcome = optionalEnum(request, 'outcome', ['success', 'failed'], locale);
70
+ const focus = optionalString(request, 'focus', locale, 600);
71
+ return {
72
+ irVersion: hub.SESSION_GENE_IR_VERSION,
73
+ prompt: authoring.irPrompt({ records: recordsOf(request, locale) ?? [], ...(kind ? { kind } : {}), ...(outcome ? { outcome } : {}), ...(focus ? { focus } : {}) }),
74
+ outputSchema: authoring.IR_OUTPUT_SCHEMA,
75
+ answerSchema: authoring.IR_ANSWER_SCHEMA,
76
+ };
77
+ }
78
+ async function distill(request, locale) {
79
+ const records = recordsOf(request, locale);
80
+ if (request['ir'] !== undefined && (typeof request['ir'] !== 'object' || request['ir'] === null || Array.isArray(request['ir']))) {
81
+ throw inputError(locale, 'ir 需要是一个 IR 对象。', 'ir must be one IR object.');
82
+ }
83
+ const draft = {
84
+ outcome: requiredEnum(request, 'outcome', ['success', 'failed'], locale),
85
+ platform: requiredEnum(request, 'platform', PLATFORMS, locale),
86
+ };
87
+ const text = (key, max) => {
88
+ const value = optionalString(request, key, locale, max);
89
+ if (value !== undefined)
90
+ draft[key] = value;
91
+ };
92
+ const list = (key) => {
93
+ const value = optionalStrings(request, key, locale);
94
+ if (value !== undefined)
95
+ draft[key] = value;
96
+ };
97
+ text('transcript', LARGE_REQUEST_BYTES);
98
+ text('summary', 2000);
99
+ text('title', 200);
100
+ text('userPrompt', 20_000);
101
+ text('finalAnswer', 20_000);
102
+ for (const key of ['strategy', 'signals', 'preconditions', 'validation', 'identifiers'])
103
+ list(key);
104
+ if (records)
105
+ draft.records = records;
106
+ if (request['ir'] !== undefined)
107
+ draft.ir = request['ir'];
108
+ return authoring.distillDraft(draft);
109
+ }
110
+ /** Library failures keep their meaning across the envelope: a bad id stays an input error, a missing Gene stays not found. */
111
+ async function fromLibrary(locale, read) {
112
+ try {
113
+ return await read(new assetstore.ExperienceLibrary(events.assetsDir()));
114
+ }
115
+ catch (error) {
116
+ if (!(error instanceof assetstore.ExperienceError))
117
+ throw error;
118
+ const code = error.code === 'INPUT_INVALID' || error.code === 'NOT_FOUND' ? error.code : 'UNAVAILABLE';
119
+ throw new JsonCommandError(code, code === 'UNAVAILABLE' ? authoring.say(locale, '暂时读不到本地经验库。', 'The local experience library cannot be read right now.') : error.message);
120
+ }
121
+ }
122
+ async function getGene(request, locale) {
123
+ const { gene, item } = await fromLibrary(locale, (library) => library.gene(request['assetId']));
124
+ return { gene, markdown: authoring.renderGeneMarkdown(gene, locale), state: item.state, title: item.title };
125
+ }
126
+ /** The stored Gene and one of its evidence Capsules: the named one, else the latest successful trial. */
127
+ async function storedBundle(request, locale) {
128
+ const evidenceId = optionalString(request, 'evidenceId', locale, 200);
129
+ return fromLibrary(locale, async (library) => {
130
+ const { gene } = await library.gene(request['assetId']);
131
+ const rows = (await library.evidence(gene.asset_id)).filter((row) => row.capsule !== null);
132
+ const chosen = evidenceId ? rows.find((row) => row.evidenceId === evidenceId) : rows.filter((row) => row.outcome === 'success').at(-1);
133
+ if (!chosen?.capsule)
134
+ throw new JsonCommandError('NOT_FOUND', authoring.say(locale, '没有可以一起发布的试用记录。', 'No trial evidence to publish with this Gene.'));
135
+ return { gene, capsule: chosen.capsule };
136
+ });
137
+ }
138
+ async function preparePublish(request, locale, env) {
139
+ const keep = request['keep'] && typeof request['keep'] === 'object' ? request['keep'] : {};
140
+ const kept = { excerpt: keep['excerpt'] === true, prompt: keep['prompt'] === true };
141
+ if (request['assetId'] !== undefined) {
142
+ const { gene, capsule } = await storedBundle(request, locale);
143
+ return authoring.preparePublication(gene, capsule, kept, env);
144
+ }
145
+ const gene = requiredObject(request, 'gene', locale);
146
+ const capsule = request['capsule'] === undefined ? undefined : requiredObject(request, 'capsule', locale);
147
+ if (gene['type'] !== 'Gene' || (capsule && capsule['type'] !== 'Capsule'))
148
+ throw inputError(locale, '需要一条 Gene 和可选的一个 Capsule。', 'Expected one Gene and an optional Capsule.');
149
+ return authoring.preparePublication(gene, capsule, kept, env);
150
+ }
151
+ async function resultFor(operation, request, io) {
152
+ const locale = requestLocale(request, io);
153
+ const env = io.env ?? process.env;
154
+ switch (operation) {
155
+ case 'template': return template(request, locale);
156
+ case 'build': return build(request, locale);
157
+ case 'get': return getGene(request, locale);
158
+ case 'lint': return authoring.lintGene(requiredObject(request, 'gene', locale), locale, env);
159
+ case 'probe': return probe(request, locale);
160
+ case 'ir-prompt': return irPrompt(request, locale);
161
+ case 'distill': return distill(request, locale);
162
+ case 'prepare-publish': return preparePublish(request, locale, env);
163
+ }
164
+ }
165
+ /** `evolver gene <operation> --json`: author, check and distill Genes locally. Nothing is stored, published or sent to a model. */
166
+ export async function runGeneCommand(argv, io = {}) {
167
+ const { operation, error } = operationOf(argv, OPERATIONS, io);
168
+ return runJsonCommand(GENE_SCHEMA, operation, io, async () => {
169
+ if (error)
170
+ throw error;
171
+ const request = await readJsonRequest(operation === 'distill' ? LARGE_REQUEST_BYTES : SMALL_REQUEST_BYTES, io);
172
+ return resultFor(operation, request, io);
173
+ });
174
+ }
@@ -0,0 +1,34 @@
1
+ import { authoring } from '@evomap/evolver-core';
2
+ export type JsonCommandCode = 'INPUT_INVALID' | 'NOT_FOUND' | 'UNAVAILABLE' | 'INTERNAL';
3
+ export declare class JsonCommandError extends Error {
4
+ readonly code: JsonCommandCode;
5
+ constructor(code: JsonCommandCode, message: string);
6
+ }
7
+ export declare const SMALL_REQUEST_BYTES: number;
8
+ export declare const LARGE_REQUEST_BYTES: number;
9
+ export type Request = Record<string, unknown>;
10
+ export type Locale = authoring.AuthoringLocale;
11
+ export interface JsonCommandIo {
12
+ stdin?: NodeJS.ReadableStream & {
13
+ isTTY?: boolean;
14
+ };
15
+ stdout?: (text: string) => void;
16
+ env?: NodeJS.ProcessEnv;
17
+ }
18
+ export declare function requestLocale(request: Request, io: JsonCommandIo): Locale;
19
+ export declare function inputError(locale: Locale, zh: string, en: string): JsonCommandError;
20
+ /** One JSON object on stdin (an interactive terminal counts as `{}`), bounded before it is parsed. */
21
+ export declare function readJsonRequest(limit: number, io: JsonCommandIo): Promise<Request>;
22
+ /** The versioned envelope every Desktop-facing command shares: one line of JSON, exit 0 when ok and 1 otherwise. */
23
+ export declare function runJsonCommand(schema: string, operation: string, io: JsonCommandIo, run: () => Promise<object>): Promise<number>;
24
+ export declare function optionalString(request: Request, key: string, locale: Locale, maxChars?: number): string | undefined;
25
+ export declare function requiredString(request: Request, key: string, locale: Locale, maxChars?: number): string;
26
+ export declare function optionalStrings(request: Request, key: string, locale: Locale, maxItems?: number, maxChars?: number): string[] | undefined;
27
+ export declare function optionalEnum<T extends string>(request: Request, key: string, values: readonly T[], locale: Locale): T | undefined;
28
+ export declare function requiredEnum<T extends string>(request: Request, key: string, values: readonly T[], locale: Locale): T;
29
+ export declare function requiredObject(request: Request, key: string, locale: Locale): Record<string, unknown>;
30
+ /** The operation word and that the remaining flags are only `--json`; anything else is an input error. */
31
+ export declare function operationOf(argv: readonly string[], operations: readonly string[], io: JsonCommandIo): {
32
+ operation: string;
33
+ error?: JsonCommandError;
34
+ };
@@ -0,0 +1,118 @@
1
+ import { authoring } from '@evomap/evolver-core';
2
+ export class JsonCommandError extends Error {
3
+ code;
4
+ constructor(code, message) {
5
+ super(message);
6
+ this.code = code;
7
+ this.name = 'JsonCommandError';
8
+ }
9
+ }
10
+ export const SMALL_REQUEST_BYTES = 64 * 1024;
11
+ export const LARGE_REQUEST_BYTES = 512 * 1024;
12
+ const MAX_ERROR_CHARS = 300;
13
+ function envLocale(io) {
14
+ return authoring.authoringLocale(undefined, io.env ?? process.env);
15
+ }
16
+ export function requestLocale(request, io) {
17
+ return authoring.authoringLocale(request['locale'], io.env ?? process.env);
18
+ }
19
+ export function inputError(locale, zh, en) {
20
+ return new JsonCommandError('INPUT_INVALID', authoring.say(locale, zh, en));
21
+ }
22
+ /** One JSON object on stdin (an interactive terminal counts as `{}`), bounded before it is parsed. */
23
+ export async function readJsonRequest(limit, io) {
24
+ const stdin = io.stdin ?? process.stdin;
25
+ const locale = envLocale(io);
26
+ if (stdin.isTTY)
27
+ return {};
28
+ const chunks = [];
29
+ let bytes = 0;
30
+ for await (const chunk of stdin) {
31
+ const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
32
+ bytes += buffer.length;
33
+ if (bytes > limit)
34
+ throw inputError(locale, `请求超过 ${limit / 1024} KiB 上限。`, `The request exceeds the ${limit / 1024} KiB limit.`);
35
+ chunks.push(buffer);
36
+ }
37
+ let parsed;
38
+ try {
39
+ parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)) || '{}');
40
+ }
41
+ catch {
42
+ throw inputError(locale, '请求不是有效的 JSON。', 'The request is not valid JSON.');
43
+ }
44
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))
45
+ throw inputError(locale, '请求需要是一个 JSON 对象。', 'The request must be a JSON object.');
46
+ return parsed;
47
+ }
48
+ function clipped(message) {
49
+ return message.length > MAX_ERROR_CHARS ? `${message.slice(0, MAX_ERROR_CHARS - 1)}…` : message;
50
+ }
51
+ /** The versioned envelope every Desktop-facing command shares: one line of JSON, exit 0 when ok and 1 otherwise. */
52
+ export async function runJsonCommand(schema, operation, io, run) {
53
+ const stdout = io.stdout ?? ((text) => { process.stdout.write(text); });
54
+ const emit = (payload) => stdout(`${JSON.stringify({ schema, operation, ...payload })}\n`);
55
+ try {
56
+ emit({ ok: true, result: await run() });
57
+ return 0;
58
+ }
59
+ catch (error) {
60
+ const failure = error instanceof JsonCommandError ? error
61
+ : new JsonCommandError('INTERNAL', authoring.say(envLocale(io), '命令执行失败,请检查本地 Evolver 安装与目录权限。', 'The command failed; check the local Evolver installation and directory permissions.'));
62
+ emit({ ok: false, code: failure.code, error: clipped(failure.message) });
63
+ return 1;
64
+ }
65
+ }
66
+ export function optionalString(request, key, locale, maxChars = 100_000) {
67
+ const value = request[key];
68
+ if (value === undefined || value === null)
69
+ return undefined;
70
+ if (typeof value !== 'string' || value.length > maxChars || value.includes('\0'))
71
+ throw inputError(locale, `${key} 需要是不超过 ${maxChars} 字的文本。`, `${key} must be text of at most ${maxChars} characters.`);
72
+ return value;
73
+ }
74
+ export function requiredString(request, key, locale, maxChars = 100_000) {
75
+ const value = optionalString(request, key, locale, maxChars);
76
+ if (value === undefined)
77
+ throw inputError(locale, `缺少 ${key}。`, `Missing ${key}.`);
78
+ return value;
79
+ }
80
+ export function optionalStrings(request, key, locale, maxItems = 200, maxChars = 2000) {
81
+ const value = request[key];
82
+ if (value === undefined || value === null)
83
+ return undefined;
84
+ if (!Array.isArray(value) || value.length > maxItems || value.some((item) => typeof item !== 'string' || item.length > maxChars || item.includes('\0'))) {
85
+ throw inputError(locale, `${key} 需要是最多 ${maxItems} 条文本的列表。`, `${key} must be a list of at most ${maxItems} strings.`);
86
+ }
87
+ return value;
88
+ }
89
+ export function optionalEnum(request, key, values, locale) {
90
+ const value = request[key];
91
+ if (value === undefined || value === null)
92
+ return undefined;
93
+ if (!values.includes(value))
94
+ throw inputError(locale, `${key} 只能是 ${values.join('、')}。`, `${key} must be one of ${values.join(', ')}.`);
95
+ return value;
96
+ }
97
+ export function requiredEnum(request, key, values, locale) {
98
+ const value = optionalEnum(request, key, values, locale);
99
+ if (value === undefined)
100
+ throw inputError(locale, `缺少 ${key}(${values.join('、')})。`, `Missing ${key} (${values.join(', ')}).`);
101
+ return value;
102
+ }
103
+ export function requiredObject(request, key, locale) {
104
+ const value = request[key];
105
+ if (!value || typeof value !== 'object' || Array.isArray(value))
106
+ throw inputError(locale, `缺少 ${key} 对象。`, `Missing the ${key} object.`);
107
+ return value;
108
+ }
109
+ /** The operation word and that the remaining flags are only `--json`; anything else is an input error. */
110
+ export function operationOf(argv, operations, io) {
111
+ const operation = argv[0] ?? '';
112
+ const locale = envLocale(io);
113
+ if (!operations.includes(operation)) {
114
+ return { operation, error: inputError(locale, `不支持的操作,可用:${operations.join('、')}。`, `Unsupported operation; use one of ${operations.join(', ')}.`) };
115
+ }
116
+ const extra = argv.slice(1).find((arg) => arg !== '--json');
117
+ return extra ? { operation, error: inputError(locale, `不支持的参数:${extra.slice(0, 40)}`, `Unsupported argument: ${extra.slice(0, 40)}`) } : { operation };
118
+ }
@@ -0,0 +1,19 @@
1
+ interface PluginDraft {
2
+ id: string;
3
+ runtime: string;
4
+ title: string;
5
+ summary: string;
6
+ score: number | null;
7
+ createdAt: string;
8
+ gene: Record<string, unknown> | null;
9
+ capsule: Record<string, unknown> | null;
10
+ }
11
+ export interface PluginDrafts {
12
+ drafts: PluginDraft[];
13
+ /** Runtimes whose drafts file exists but could not be read: missing drafts there are unknown, not absent. */
14
+ unreadable: string[];
15
+ }
16
+ export declare const RUNTIME_NAME: RegExp;
17
+ /** The agent plugin's unconfirmed distillation drafts (`~/.evolver/state/<runtime>-distill-drafts.json`), read in place. */
18
+ export declare function pluginDrafts(env: Readonly<Record<string, string | undefined>>, runtime?: string): PluginDrafts;
19
+ export {};
@@ -0,0 +1,87 @@
1
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, readdirSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ export const RUNTIME_NAME = /^[a-z0-9][a-z0-9-]{0,39}$/;
5
+ const DRAFTS_FILE = /^([a-z0-9][a-z0-9-]{0,39})-distill-drafts\.json$/;
6
+ const MAX_FILE_BYTES = 16 * 1024 * 1024;
7
+ const isRecord = (value) => !!value && typeof value === 'object' && !Array.isArray(value);
8
+ function stateDir(env) {
9
+ return join(env['HOME'] || env['USERPROFILE'] || homedir(), '.evolver', 'state');
10
+ }
11
+ const MAX_DATE_MS = 8.64e15;
12
+ /** One malformed timestamp blanks that draft's date; it must not make the whole file unreadable. */
13
+ function isoTime(value) {
14
+ const time = typeof value === 'number' ? value : typeof value === 'string' ? Date.parse(value) : Number.NaN;
15
+ return Number.isFinite(time) && Math.abs(time) <= MAX_DATE_MS ? new Date(time).toISOString() : '';
16
+ }
17
+ function assetOf(assets, type) {
18
+ return Array.isArray(assets) ? assets.find((asset) => isRecord(asset) && asset['type'] === type) ?? null : null;
19
+ }
20
+ /**
21
+ * Reads through one descriptor, so the size checked is the size read. The path must be a regular file before opening and the
22
+ * opened file must be that same file, which also holds where `O_NOFOLLOW` does not exist (Windows).
23
+ */
24
+ function readBounded(path) {
25
+ const before = lstatSync(path);
26
+ if (!before.isFile())
27
+ throw new Error('drafts_file_unreadable');
28
+ const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
29
+ try {
30
+ const stat = fstatSync(fd);
31
+ if (!stat.isFile() || stat.dev !== before.dev || stat.ino !== before.ino || stat.size > MAX_FILE_BYTES)
32
+ throw new Error('drafts_file_unreadable');
33
+ const buffer = Buffer.alloc(MAX_FILE_BYTES + 1);
34
+ let length = 0;
35
+ for (let read = -1; read !== 0 && length <= MAX_FILE_BYTES;) {
36
+ read = readSync(fd, buffer, length, buffer.length - length, length);
37
+ length += read;
38
+ }
39
+ if (length > MAX_FILE_BYTES)
40
+ throw new Error('drafts_file_unreadable');
41
+ return new TextDecoder('utf-8', { fatal: true }).decode(buffer.subarray(0, length));
42
+ }
43
+ finally {
44
+ closeSync(fd);
45
+ }
46
+ }
47
+ function draftsIn(path, runtime) {
48
+ const rows = JSON.parse(readBounded(path));
49
+ if (!Array.isArray(rows))
50
+ throw new Error('drafts_file_unreadable');
51
+ return rows.filter(isRecord).filter((row) => typeof row['id'] === 'string' || typeof row['id'] === 'number').map((row) => ({
52
+ id: String(row['id']),
53
+ runtime,
54
+ title: typeof row['title'] === 'string' ? row['title'] : '',
55
+ summary: typeof row['summary'] === 'string' ? row['summary'] : '',
56
+ score: typeof row['score'] === 'number' ? row['score'] : null,
57
+ createdAt: isoTime(row['createdAt']),
58
+ gene: assetOf(row['assets'], 'Gene'),
59
+ capsule: assetOf(row['assets'], 'Capsule'),
60
+ }));
61
+ }
62
+ /** The agent plugin's unconfirmed distillation drafts (`~/.evolver/state/<runtime>-distill-drafts.json`), read in place. */
63
+ export function pluginDrafts(env, runtime) {
64
+ let names;
65
+ try {
66
+ names = readdirSync(stateDir(env));
67
+ }
68
+ catch (error) {
69
+ if (error.code === 'ENOENT')
70
+ return { drafts: [], unreadable: [] };
71
+ throw new Error('drafts_state_unreadable', { cause: error });
72
+ }
73
+ const drafts = [];
74
+ const unreadable = [];
75
+ for (const name of names) {
76
+ const owner = DRAFTS_FILE.exec(name)?.[1];
77
+ if (!owner || (runtime !== undefined && owner !== runtime))
78
+ continue;
79
+ try {
80
+ drafts.push(...draftsIn(join(stateDir(env), name), owner));
81
+ }
82
+ catch {
83
+ unreadable.push(owner);
84
+ }
85
+ }
86
+ return { drafts: drafts.sort((a, b) => b.createdAt.localeCompare(a.createdAt)), unreadable };
87
+ }
@@ -0,0 +1,6 @@
1
+ import { type JsonCommandIo } from './jsonCommand.js';
2
+ /**
3
+ * `evolver publish-policy get|set --json`. In `manual` the Proxy's background curation still promotes trial Genes but
4
+ * never enqueues a publish; the policy lives with this node's asset store and the Proxy rereads it every pass.
5
+ */
6
+ export declare function runPublishPolicyCommand(argv: string[], io?: JsonCommandIo): Promise<number>;
@@ -0,0 +1,19 @@
1
+ import { assetstore, events } from '@evomap/evolver-core';
2
+ import { SMALL_REQUEST_BYTES, operationOf, readJsonRequest, requestLocale, requiredEnum, runJsonCommand } from './jsonCommand.js';
3
+ const PUBLISH_POLICY_COMMAND_SCHEMA = 'evolver.publish-policy.v1';
4
+ /**
5
+ * `evolver publish-policy get|set --json`. In `manual` the Proxy's background curation still promotes trial Genes but
6
+ * never enqueues a publish; the policy lives with this node's asset store and the Proxy rereads it every pass.
7
+ */
8
+ export async function runPublishPolicyCommand(argv, io = {}) {
9
+ const { operation, error } = operationOf(argv, ['get', 'set'], io);
10
+ return runJsonCommand(PUBLISH_POLICY_COMMAND_SCHEMA, operation, io, async () => {
11
+ if (error)
12
+ throw error;
13
+ const dir = events.assetsDir(io.env ?? process.env);
14
+ if (operation === 'get')
15
+ return assetstore.readPublishPolicy(dir);
16
+ const request = await readJsonRequest(SMALL_REQUEST_BYTES, io);
17
+ return assetstore.writePublishPolicy(dir, requiredEnum(request, 'mode', assetstore.PUBLISH_MODES, requestLocale(request, io)));
18
+ });
19
+ }
@@ -0,0 +1,3 @@
1
+ import { type JsonCommandIo } from './jsonCommand.js';
2
+ /** `evolver redact --json`: what would be removed from each text before it leaves this machine, with exact offsets. Read-only. */
3
+ export declare function runRedactCommand(argv: string[], io?: JsonCommandIo): Promise<number>;
package/dist/redact.js ADDED
@@ -0,0 +1,27 @@
1
+ import { authoring } from '@evomap/evolver-core';
2
+ import { LARGE_REQUEST_BYTES, inputError, operationOf, optionalStrings, readJsonRequest, requestLocale, runJsonCommand, } from './jsonCommand.js';
3
+ const REDACT_SCHEMA = 'evolver.redact.v1';
4
+ const MAX_TEXTS = 500;
5
+ const MAX_TERMS = 200;
6
+ const MAX_TERM_CHARS = 200;
7
+ /** `evolver redact --json`: what would be removed from each text before it leaves this machine, with exact offsets. Read-only. */
8
+ export async function runRedactCommand(argv, io = {}) {
9
+ const { error } = operationOf(['redact', ...argv], ['redact'], io);
10
+ return runJsonCommand(REDACT_SCHEMA, 'redact', io, async () => {
11
+ if (error)
12
+ throw error;
13
+ const request = await readJsonRequest(LARGE_REQUEST_BYTES, io);
14
+ const locale = requestLocale(request, io);
15
+ const texts = optionalStrings(request, 'texts', locale, MAX_TEXTS, LARGE_REQUEST_BYTES);
16
+ if (!texts)
17
+ throw inputError(locale, `缺少 texts(最多 ${MAX_TEXTS} 段文本)。`, `Missing texts (at most ${MAX_TEXTS}).`);
18
+ const terms = optionalStrings(request, 'terms', locale, MAX_TERMS, MAX_TERM_CHARS);
19
+ const identifiers = optionalStrings(request, 'identifiers', locale, MAX_TERMS, MAX_TERM_CHARS);
20
+ const items = texts.map((text) => {
21
+ const { text: redacted, findings } = authoring.redactWithFindings({ text, env: io.env ?? process.env, locale,
22
+ ...(terms ? { terms } : {}), ...(identifiers ? { identifiers } : {}) });
23
+ return { text: redacted, findings };
24
+ });
25
+ return { rulesVersion: authoring.REDACTION_RULES_VERSION, items };
26
+ });
27
+ }
@@ -44,6 +44,7 @@ export type SessionContextDeliveryRecovery = {
44
44
  } | {
45
45
  status: 'unknown';
46
46
  reason: 'recovery_failed' | 'deadline';
47
+ journal?: events.ContextDeliveryStatus;
47
48
  };
48
49
  /** Resolve context ownership before any recovery/index I/O. Physical aliases
49
50
  * alone are insufficient: protected audit namespaces retain the exact logical
@@ -192,13 +192,16 @@ function finishSessionIndexCleanup(path) {
192
192
  export async function runSessionIngestTick(dirs, deps = {}) {
193
193
  const resolvedDeps = resolveIngestDeps(deps);
194
194
  const contextIngestor = resolveContextObservationWriter(resolvedDeps.ingestor, deps.contextIngestor);
195
- const contextDeliveryRecovery = contextIngestor
195
+ let contextDeliveryRecovery = contextIngestor
196
196
  ? await recoverSessionDeliveries(contextIngestor) : undefined;
197
197
  if (contextIngestor) {
198
198
  // A failed/late protected RPC can outlive its client wait. The existing
199
199
  // ordered status RPC joins the service's turn before deciding root admission.
200
- const journal = contextDeliveryRecovery && 'journal' in contextDeliveryRecovery
201
- ? contextDeliveryRecovery.journal : events.Ingestor.contextDeliveryStatus(contextIngestor.path);
200
+ const journal = contextDeliveryRecovery?.journal ?? events.Ingestor.contextDeliveryStatus(contextIngestor.path);
201
+ // Preserve the admission snapshot without upgrading a late or failed recovery.
202
+ if (contextDeliveryRecovery && contextDeliveryRecovery.journal === undefined) {
203
+ contextDeliveryRecovery = { ...contextDeliveryRecovery, journal };
204
+ }
202
205
  if (journal.confirmedPending > 0 || journal.reasons.cleanup_pending)
203
206
  return {
204
207
  recorded: 0, sourceAgents: [], signalKinds: [], signalStrengths: [],
@@ -8,6 +8,7 @@ export interface SkillFetchHub {
8
8
  export interface SkillFetchDeps {
9
9
  hub?: SkillFetchHub;
10
10
  env?: NodeJS.ProcessEnv;
11
+ cwd?: string;
11
12
  stdout?: (line: string) => void;
12
13
  stderr?: (line: string) => void;
13
14
  connectHub?: (opts: ConnectPublicOptions) => {
@@ -1,8 +1,8 @@
1
- import { existsSync, mkdirSync, writeFileSync } from 'node:fs';
2
- import { dirname, isAbsolute, relative, resolve } from 'node:path';
1
+ import { join } from 'node:path';
3
2
  import { assetstore, wire } from '@evomap/evolver-core';
4
3
  import { AuthError, HubClientError, HubUnreachableError, connectPublicHub, isHubDryRunEnabled, } from '@evomap/evolver-adapter-public';
5
4
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
5
+ import { relativePathInsideRoot, writeFileInsideRoot } from './containedWrite.js';
6
6
  import { createRecipeHubFromEnv } from './recipe.js';
7
7
  import { geneToSkillMd } from './skillDistill.js';
8
8
  const GROUP = 'skill.fetch';
@@ -53,13 +53,11 @@ async function runSkillFetchCommand(argv, deps = {}) {
53
53
  stdout: deps.stdout ?? ((line) => { process.stdout.write(`${line}\n`); }),
54
54
  stderr: deps.stderr ?? ((line) => { process.stderr.write(`${line}\n`); }),
55
55
  };
56
- const parsed = parseSkillFetchArgs(argv);
56
+ const cwd = deps.cwd ?? process.cwd();
57
+ const parsed = parseSkillFetchArgs(argv, cwd);
57
58
  if (!parsed.ok)
58
59
  return emitFailure(parsed.reason, parsed.message, argv.includes('--json'), io);
59
60
  const opts = parsed.value;
60
- if (opts.source.kind === 'asset' && !opts.write && opts.outDir) {
61
- // Preview with --out is still read-only; target paths are shown below.
62
- }
63
61
  try {
64
62
  const env = deps.env ?? process.env;
65
63
  loadEnvFileFromEnv(env);
@@ -68,7 +66,7 @@ async function runSkillFetchCommand(argv, deps = {}) {
68
66
  return 0;
69
67
  }
70
68
  const hub = deps.hub ?? createSkillFetchHubFromEnv(deps, env);
71
- const run = await buildSkillFetchResult(hub, opts);
69
+ const run = await buildSkillFetchResult(hub, opts, cwd);
72
70
  if (!run.ok)
73
71
  return emitFailure(run.reason, run.message, opts.json, io);
74
72
  emitSuccess(run.value, opts.json, io);
@@ -79,7 +77,7 @@ async function runSkillFetchCommand(argv, deps = {}) {
79
77
  return emitFailure(mapped.reason, mapped.message, opts.json, io);
80
78
  }
81
79
  }
82
- function parseSkillFetchArgs(argv) {
80
+ function parseSkillFetchArgs(argv, cwd) {
83
81
  if (argv.includes('--help') || argv.includes('-h')) {
84
82
  return { ok: false, reason: 'usage', message: USAGE };
85
83
  }
@@ -97,9 +95,12 @@ function parseSkillFetchArgs(argv) {
97
95
  if (!Number.isSafeInteger(limit) || limit <= 0)
98
96
  return { ok: false, reason: 'invalid_arg', message: '--limit must be a positive integer' };
99
97
  const write = argv.includes('--write');
100
- const outDir = flagValue(argv, '--out') ?? undefined;
101
- if (write && !outDir)
98
+ const outRaw = flagValue(argv, '--out') || undefined;
99
+ if (write && !outRaw)
102
100
  return { ok: false, reason: 'invalid_arg', message: 'skill fetch --write requires --out <dir>' };
101
+ const outDir = outRaw === undefined ? undefined : relativePathInsideRoot(cwd, outRaw);
102
+ if (outDir === null)
103
+ return { ok: false, reason: 'invalid_arg', message: '--out must resolve to a path inside the current working directory' };
103
104
  const select = flagValue(argv, '--select') ?? undefined;
104
105
  const source = asset
105
106
  ? { kind: 'asset', id: asset.trim() }
@@ -127,7 +128,7 @@ function parseSkillFetchArgs(argv) {
127
128
  },
128
129
  };
129
130
  }
130
- async function buildSkillFetchResult(hub, opts) {
131
+ async function buildSkillFetchResult(hub, opts, cwd) {
131
132
  const direct = opts.source.kind === 'asset' ? await fetchGeneById(hub, opts.source.id) : null;
132
133
  if (direct && !direct.ok)
133
134
  return direct;
@@ -157,7 +158,7 @@ async function buildSkillFetchResult(hub, opts) {
157
158
  if (selected.asset.asset_id !== previewed.assetId) {
158
159
  return { ok: false, reason: 'integrity_error', message: 'selected Gene asset_id changed after preview' };
159
160
  }
160
- const written = writeSkill(selected.asset, opts.outDir, opts.force);
161
+ const written = writeSkill(selected.asset, cwd, opts.outDir, opts.force);
161
162
  if (!written.ok)
162
163
  return written;
163
164
  return { ok: true, value: { mode: 'write', candidates: [candidateFromGene(selected.asset, opts.outDir)], written: written.value } };
@@ -231,16 +232,14 @@ function candidateFromGene(gene, outDir) {
231
232
  candidate.target = relativeSkillPath(name);
232
233
  return candidate;
233
234
  }
234
- function writeSkill(gene, outDir, force) {
235
+ function writeSkill(gene, cwd, outDir, force) {
235
236
  const name = skillNameForGene(gene);
236
237
  const target = relativeSkillPath(name);
237
- const targetPath = targetSkillPath(outDir, name);
238
- if (!isInside(resolve(outDir), resolve(targetPath)))
239
- return { ok: false, reason: 'invalid_arg', message: 'resolved skill target escapes --out directory' };
240
- if (existsSync(targetPath) && !force)
238
+ const write = writeFileInsideRoot(cwd, join(outDir, target), geneToSkillMd(gene, { name }), force);
239
+ if (!write.ok && write.reason === 'exists')
241
240
  return { ok: false, reason: 'conflict', message: `SKILL.md already exists for skill ${name}; use --force to overwrite` };
242
- mkdirSync(dirname(targetPath), { recursive: true });
243
- writeFileSync(targetPath, geneToSkillMd(gene, { name }), 'utf8');
241
+ if (!write.ok)
242
+ return { ok: false, reason: 'invalid_arg', message: 'skill target path must not pass through a symlink, junction, hard link, or non-directory' };
244
243
  const written = { target, assetId: gene.asset_id, name };
245
244
  const geneId = stringField(gene, 'id');
246
245
  if (geneId)
@@ -361,16 +360,9 @@ function safeSkillName(value) {
361
360
  .slice(0, 80);
362
361
  return slug || 'skill';
363
362
  }
364
- function targetSkillPath(outDir, name) {
365
- return resolve(outDir, 'skills', safeSkillName(name), 'SKILL.md');
366
- }
367
363
  function relativeSkillPath(name) {
368
364
  return `skills/${safeSkillName(name)}/SKILL.md`;
369
365
  }
370
- function isInside(parent, child) {
371
- const rel = relative(parent, child);
372
- return rel.length > 0 && !rel.startsWith('..') && !isAbsolute(rel);
373
- }
374
366
  function arrayOfStrings(value) {
375
367
  return Array.isArray(value) ? value.map((item) => String(item).trim()).filter(Boolean) : [];
376
368
  }
@@ -1,6 +1,6 @@
1
1
  import { workflow } from '@evomap/evolver-core';
2
2
  import { type ProductionWorkflowRuntimeOptions } from './workflowRuntime.js';
3
- export declare const WORKFLOW_SUBCOMMANDS: readonly ["start", "submit", "list", "status", "history", "pause", "resume", "cancel", "approve", "reject"];
3
+ export declare const WORKFLOW_SUBCOMMANDS: readonly ["start", "submit", "list", "status", "inspect", "history", "pause", "resume", "cancel", "approve", "reject"];
4
4
  type OutputStream = Pick<NodeJS.WriteStream, 'write'>;
5
5
  type RuntimeControlOptions = {
6
6
  actor: string;
@@ -18,6 +18,7 @@ type WorkflowRuntimeLike = {
18
18
  };
19
19
  type WorkflowStoreLike = {
20
20
  read(runId: string): workflow.WorkflowRunState;
21
+ inspect?: (runId: string) => workflow.WorkflowRunState;
21
22
  listRunIds(): string[];
22
23
  history?: (runId: string) => unknown;
23
24
  readHistory?: (runId: string) => unknown;
package/dist/workflow.js CHANGED
@@ -7,7 +7,7 @@ const MAX_SPEC_BYTES = 1_048_576;
7
7
  const MAX_REASON_LENGTH = 500;
8
8
  const DEFAULT_ACTOR = 'local-operator';
9
9
  export const WORKFLOW_SUBCOMMANDS = [
10
- 'start', 'submit', 'list', 'status', 'history', 'pause', 'resume', 'cancel', 'approve', 'reject',
10
+ 'start', 'submit', 'list', 'status', 'inspect', 'history', 'pause', 'resume', 'cancel', 'approve', 'reject',
11
11
  ];
12
12
  class WorkflowCliError extends Error {
13
13
  code;
@@ -23,6 +23,7 @@ function usage(stderr) {
23
23
  ' evolver workflow start|submit <spec-file> [--run-id <id>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
24
24
  ' evolver workflow list [--state-dir <path>] [--autoexec-home <path>] [--json]',
25
25
  ' evolver workflow status|history <run-id> [--state-dir <path>] [--autoexec-home <path>] [--json]',
26
+ ' evolver workflow inspect <run-id> [--state-dir <path>] [--json] # stored checkpoint; no writes or recovery',
26
27
  ' evolver workflow pause|resume|cancel <run-id> [--actor <id>] [--reason <text>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
27
28
  ' evolver workflow approve|reject <run-id> <gate-id> [--actor <id>] [--reason <text>] [--state-dir <path>] [--autoexec-home <path>] [--json]',
28
29
  ].join('\n') + '\n');
@@ -157,24 +158,34 @@ function statusPayload(state) {
157
158
  attempts: current?.attempts ?? 0,
158
159
  maxAttempts: current?.maxAttempts ?? 0,
159
160
  lastErrorClass: safeMetadataToken(state.lastErrorClass),
160
- createdAt: state.createdAt,
161
- updatedAt: state.updatedAt,
162
- completedAt: state.completedAt ?? null,
161
+ createdAt: safeString(state.createdAt, 64),
162
+ updatedAt: safeString(state.updatedAt, 64),
163
+ completedAt: safeString(state.completedAt, 64),
163
164
  };
164
165
  }
165
166
  function safeString(value, maxLength = 500) {
166
167
  if (typeof value !== 'string' || value.length > maxLength || workflow.containsWorkflowSensitiveText(value))
167
168
  return null;
168
- const hasControlCharacter = [...value].some((character) => {
169
- const code = character.charCodeAt(0);
170
- return code <= 0x1f || code === 0x7f;
171
- });
172
- return hasControlCharacter ? null : value;
169
+ return /[\p{Cc}\p{Bidi_Control}\p{Zl}\p{Zp}]/u.test(value) ? null : value;
173
170
  }
174
- function safeMetadataToken(value) {
175
- const candidate = safeString(value, 64);
171
+ function safeMetadataToken(value, maxLength = 64) {
172
+ const candidate = safeString(value, maxLength);
176
173
  return candidate !== null && /^[A-Za-z0-9._-]+$/.test(candidate) ? candidate : null;
177
174
  }
175
+ function inspectionPayload(state) {
176
+ const gateId = state.status === 'waiting_approval' ? safeMetadataToken(state.approval?.gateId, 128) : null;
177
+ const nextAction = state.status === 'waiting_approval' && gateId !== null ? 'review_approval'
178
+ : state.status === 'unsafe_to_resume' ? 'manual_reconciliation'
179
+ : state.status === 'failed' || state.status === 'waiting_approval' ? 'inspect_history'
180
+ : state.status === 'paused' ? 'review_before_resume'
181
+ : state.status === 'succeeded' || state.status === 'cancelled' ? 'none' : 'observe';
182
+ const step = state.currentStep ? state.steps[state.currentStep] : undefined;
183
+ const metadata = Object.fromEntries(Object.entries(statusPayload(state))
184
+ .map(([key, value]) => [key, typeof value === 'string' ? safeString(value)
185
+ : typeof value === 'number' && Number.isFinite(value) ? value : null]));
186
+ return { ...metadata, view: 'stored_checkpoint', nextAction, approvalGateId: gateId,
187
+ nextAttemptAt: state.status === 'retry_wait' ? safeString(step?.nextAttemptAt, 64) : null };
188
+ }
178
189
  function historyPayload(entry) {
179
190
  if (!isRecord(entry))
180
191
  return { type: 'unknown' };
@@ -350,6 +361,18 @@ export async function runWorkflowCommand(argv, deps = {}) {
350
361
  return 0;
351
362
  }
352
363
  runId = validateId(parsed.positionals[0] ?? '', 'runId');
364
+ if (parsed.command === 'inspect') {
365
+ if (!store.inspect)
366
+ throw new WorkflowCliError('INSPECTION_NOT_SUPPORTED');
367
+ const payload = inspectionPayload(store.inspect(runId));
368
+ if (parsed.json)
369
+ writeJson(stdout, { ok: true, ...payload });
370
+ else {
371
+ writeStatusText(stdout, payload);
372
+ stdout.write(`view=stored_checkpoint action=${String(payload['nextAction'])} gate=${String(payload['approvalGateId'] ?? '-')}\n`);
373
+ }
374
+ return 0;
375
+ }
353
376
  if (parsed.command === 'status') {
354
377
  const payload = statusPayload(store.read(runId));
355
378
  if (parsed.json)
@@ -378,7 +401,7 @@ export async function runWorkflowCommand(argv, deps = {}) {
378
401
  catch (error) {
379
402
  const code = errorCode(error, parsed.command);
380
403
  if (parsed.json)
381
- writeJson(stdout, { ok: false, command: parsed.command, ...(runId ? { runId } : {}), error: code });
404
+ writeJson(stdout, { ok: false, command: parsed.command, ...(runId && safeString(runId, 128) !== null ? { runId } : {}), error: code });
382
405
  else
383
406
  stderr.write(`workflow ${parsed.command} failed: ${code}\n`);
384
407
  return 1;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@evomap/evolver-cli",
3
- "version": "2.0.50",
3
+ "version": "2.0.51",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -27,12 +27,12 @@
27
27
  }
28
28
  },
29
29
  "dependencies": {
30
- "@evomap/evolver-core": "2.0.50",
31
- "@evomap/evolver-adapter-public": "2.0.50",
32
- "@evomap/evolver-mcp": "2.0.50",
33
- "@evomap/evolver-proxy": "2.0.50",
34
- "@evomap/evolver-runtime-adapters": "2.0.50",
35
- "@evomap/evolver-webui": "2.0.50"
30
+ "@evomap/evolver-core": "2.0.51",
31
+ "@evomap/evolver-adapter-public": "2.0.51",
32
+ "@evomap/evolver-mcp": "2.0.51",
33
+ "@evomap/evolver-proxy": "2.0.51",
34
+ "@evomap/evolver-runtime-adapters": "2.0.51",
35
+ "@evomap/evolver-webui": "2.0.51"
36
36
  },
37
37
  "repository": {
38
38
  "type": "git",