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

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 (68) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +2 -0
  3. package/dist/assetRepair.d.ts +24 -0
  4. package/dist/assetRepair.js +172 -0
  5. package/dist/autoDistillAntiGene.js +7 -5
  6. package/dist/autoDistillLlm.d.ts +20 -0
  7. package/dist/autoDistillLlm.js +77 -15
  8. package/dist/autoexec.d.ts +11 -0
  9. package/dist/autoexec.js +65 -10
  10. package/dist/autoexecConfig.js +2 -1
  11. package/dist/cliContracts.d.ts +10 -0
  12. package/dist/cliContracts.js +407 -81
  13. package/dist/commandCatalog.d.ts +72 -0
  14. package/dist/commandCatalog.js +120 -0
  15. package/dist/cycleConsumer.d.ts +9 -0
  16. package/dist/cycleConsumer.js +14 -3
  17. package/dist/dispatch.d.ts +0 -1
  18. package/dist/dispatch.js +10 -4
  19. package/dist/distillObserver.js +23 -6
  20. package/dist/doctor.d.ts +11 -0
  21. package/dist/doctor.js +81 -6
  22. package/dist/index.d.ts +5 -1
  23. package/dist/index.js +200 -68
  24. package/dist/lifecycle.d.ts +126 -3
  25. package/dist/lifecycle.js +4390 -188
  26. package/dist/lifecycleBootstrapTransaction.d.ts +235 -0
  27. package/dist/lifecycleBootstrapTransaction.js +2182 -0
  28. package/dist/localMemoryGraph.d.ts +90 -3
  29. package/dist/localMemoryGraph.js +2031 -231
  30. package/dist/materialSnapshot.d.ts +2 -0
  31. package/dist/materialSnapshot.js +8 -0
  32. package/dist/memoryGraphOps.d.ts +8 -0
  33. package/dist/memoryGraphOps.js +140 -0
  34. package/dist/migrate/assetFormatMap.d.ts +61 -0
  35. package/dist/migrate/assetFormatMap.js +53 -0
  36. package/dist/migrate/envTranslate.js +2 -0
  37. package/dist/migrate/fieldMap.d.ts +7 -5
  38. package/dist/migrate/fieldMap.js +20 -14
  39. package/dist/migrate/v1Import.d.ts +80 -1
  40. package/dist/migrate/v1Import.js +961 -120
  41. package/dist/modelCompatibility.d.ts +10 -0
  42. package/dist/modelCompatibility.js +296 -0
  43. package/dist/recipe.d.ts +7 -1
  44. package/dist/recipe.js +113 -11
  45. package/dist/repairedAssetStore.d.ts +2 -0
  46. package/dist/repairedAssetStore.js +12 -0
  47. package/dist/reuse.d.ts +4 -1
  48. package/dist/reuse.js +212 -107
  49. package/dist/reviewFilter.d.ts +3 -1
  50. package/dist/reviewFilter.js +3 -1
  51. package/dist/runtimeSessionSource.d.ts +5 -0
  52. package/dist/selectionPolicyConfig.d.ts +8 -0
  53. package/dist/selectionPolicyConfig.js +18 -0
  54. package/dist/semanticIdfConfig.d.ts +2 -0
  55. package/dist/semanticIdfConfig.js +4 -0
  56. package/dist/sessionIngest.d.ts +7 -1
  57. package/dist/sessionIngest.js +25 -1
  58. package/dist/setupHooks.js +12 -6
  59. package/dist/skill2gep.js +57 -6
  60. package/dist/skillDistill.js +1 -0
  61. package/dist/sync.d.ts +1 -1
  62. package/dist/sync.js +761 -174
  63. package/dist/thesis.js +2 -0
  64. package/dist/valueDigest.js +8 -1
  65. package/dist/windowsLegacyTaskCleanup.d.ts +228 -0
  66. package/dist/windowsLegacyTaskCleanup.js +1475 -0
  67. package/dist/workflowRuntime.js +7 -6
  68. package/package.json +7 -7
@@ -14,6 +14,8 @@ interface SnapshotSource {
14
14
  label: string;
15
15
  sessionId?: string;
16
16
  resumeIdentityProvenance?: 'canonical_native_transcript';
17
+ /** Optional resolved task domain slug; omitted for old snapshots / unresolved sources. */
18
+ taskDomain?: string;
17
19
  evidenceSummary: RuntimeSessionEvidenceSummary;
18
20
  turns: SnapshotTurn[];
19
21
  }
@@ -204,11 +204,15 @@ export function buildRuntimeSessionMaterialSnapshot(sources, maxChars = DEFAULT_
204
204
  const safeSessionId = source.sessionId
205
205
  ? snapshotIdentity(source.sessionId, SNAPSHOT_IDENTITY_MAX_CHARS)
206
206
  : '';
207
+ const safeTaskDomain = source.taskDomain
208
+ ? snapshotIdentity(source.taskDomain, SNAPSHOT_AGENT_MAX_CHARS)
209
+ : '';
207
210
  snapshotSources.push({
208
211
  agent: snapshotIdentity(source.agent, SNAPSHOT_AGENT_MAX_CHARS) || 'unknown',
209
212
  label: snapshotIdentity(source.label, SNAPSHOT_IDENTITY_MAX_CHARS) || 'unknown',
210
213
  ...(safeSessionId ? { sessionId: safeSessionId } : {}),
211
214
  ...(source.resumeIdentityProvenance ? { resumeIdentityProvenance: source.resumeIdentityProvenance } : {}),
215
+ ...(safeTaskDomain ? { taskDomain: safeTaskDomain } : {}),
212
216
  evidenceSummary,
213
217
  turns,
214
218
  });
@@ -274,11 +278,15 @@ function sourceFromSnapshot(value) {
274
278
  const resumeIdentityProvenance = value['resumeIdentityProvenance'] === 'canonical_native_transcript'
275
279
  ? value['resumeIdentityProvenance']
276
280
  : undefined;
281
+ const taskDomain = typeof value['taskDomain'] === 'string' && value['taskDomain'].trim()
282
+ ? value['taskDomain'].trim()
283
+ : undefined;
277
284
  return {
278
285
  agent,
279
286
  label,
280
287
  ...(sessionId ? { sessionId } : {}),
281
288
  ...(resumeIdentityProvenance ? { resumeIdentityProvenance } : {}),
289
+ ...(taskDomain ? { taskDomain } : {}),
282
290
  turns,
283
291
  };
284
292
  }
@@ -0,0 +1,8 @@
1
+ import { LocalMemoryGraph } from './localMemoryGraph.js';
2
+ export interface MemoryGraphOpsDeps {
3
+ env?: Record<string, string | undefined>;
4
+ stdout?: (text: string) => void;
5
+ stderr?: (text: string) => void;
6
+ createGraph?: (dir: string) => LocalMemoryGraph;
7
+ }
8
+ export declare function runMemoryGraphCommand(argv: readonly string[], deps?: MemoryGraphOpsDeps): Promise<number>;
@@ -0,0 +1,140 @@
1
+ /**
2
+ * Operator maintenance CLI for local MemoryGraph (Refs #674).
3
+ */
4
+ import { events } from '@evomap/evolver-core';
5
+ import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
6
+ import { join } from 'node:path';
7
+ import { LocalMemoryGraph, formatMemoryGraphOperatorStatus, loadMemoryGraphOperatorStatus, resolveLocalMemoryUserIdentity, } from './localMemoryGraph.js';
8
+ const USAGE = [
9
+ 'Usage:',
10
+ ' evolver memory-graph status [--json]',
11
+ ' evolver memory-graph maintain [--json] # recovery or threshold rotation + compaction',
12
+ ' evolver memory-graph prune [--json] # enforce rotated-archive retention',
13
+ ' evolver memory-graph recover [--json] # rebuild compact from retained current-epoch state',
14
+ ' evolver memory-graph reset --yes [--json] # copy a backup, then advance the local epoch',
15
+ '',
16
+ 'Graph dir: $EVOLVER_HOME/evolution, then $EVOMAP_HOME/evolution, then ~/.evomap/evolution.',
17
+ 'Destructive reset requires --yes. Predictive cross-epoch weighting remains deferred (#670).',
18
+ '',
19
+ ].join('\n');
20
+ function writeJson(write, value) {
21
+ write(`${JSON.stringify(value)}\n`);
22
+ }
23
+ function graphFor(env, deps) {
24
+ const home = events.evomapHome(env);
25
+ if (!home.trim())
26
+ throw new Error('memory_graph_home_rejected');
27
+ const dir = join(home, 'evolution');
28
+ if (deps.createGraph)
29
+ return deps.createGraph(dir);
30
+ return new LocalMemoryGraph({ dir, ...resolveLocalMemoryUserIdentity(dir) });
31
+ }
32
+ function renderMaintain(report, stdout) {
33
+ stdout([
34
+ `rotated=${report.rotated ? 1 : 0}`,
35
+ `compacted=${report.compactedRecords}`,
36
+ `corrupt=${report.corruptLines}`,
37
+ `oversized_lines=${report.oversizedLines}`,
38
+ `archives=${report.archives}`,
39
+ `recovery=${report.recovery}`,
40
+ ].join(' ') + '\n');
41
+ }
42
+ function renderReset(report, stdout) {
43
+ renderMaintain(report, stdout);
44
+ stdout(`backup_id=${report.backupId ?? 'none'} backup_files=${report.backupFiles} epoch_id=${report.epochId ?? 'unchanged'}\n`);
45
+ }
46
+ function writeFailure(command, reason, json, stdout, stderr, usage = false) {
47
+ if (json)
48
+ writeJson(stdout, { ok: false, command, reason });
49
+ else
50
+ stderr(`[memory-graph] ${reason}\n${usage ? USAGE : ''}`);
51
+ return reason === 'unknown_argument' || reason === 'confirmation_required' ? 2 : 1;
52
+ }
53
+ function writeMaintenance(command, report, json, stdout) {
54
+ const ok = report.recovery !== 'degraded';
55
+ if (json)
56
+ writeJson(stdout, { ok, command, report });
57
+ else
58
+ renderMaintain(report, stdout);
59
+ return ok ? 0 : 1;
60
+ }
61
+ function operationFailureReason(error) {
62
+ const message = error instanceof Error ? error.message : '';
63
+ return new Set([
64
+ 'memory_graph_busy',
65
+ 'memory_graph_dir_rejected',
66
+ 'memory_graph_epoch_rejected',
67
+ 'memory_graph_home_rejected',
68
+ 'memory_graph_append_rollback_failed',
69
+ 'memory_graph_path_rejected',
70
+ 'memory_graph_rotation_backup_failed',
71
+ 'memory_graph_rotation_journal_rejected',
72
+ 'memory_graph_rotation_recovery_failed',
73
+ 'memory_graph_reset_backup_failed',
74
+ 'memory_graph_reset_failed',
75
+ 'memory_graph_write_failed',
76
+ ]).has(message) ? message : 'memory_graph_operation_failed';
77
+ }
78
+ export async function runMemoryGraphCommand(argv, deps = {}) {
79
+ const stdout = deps.stdout ?? ((text) => { process.stdout.write(text); });
80
+ const stderr = deps.stderr ?? ((text) => { process.stderr.write(text); });
81
+ if (argv.length === 0 || argv.includes('--help') || argv.includes('-h')) {
82
+ stdout(USAGE);
83
+ return argv.length === 0 ? 1 : 0;
84
+ }
85
+ const sub = argv[0] ?? '';
86
+ const rest = argv.slice(1);
87
+ const json = rest.includes('--json') || argv.includes('--json');
88
+ const known = new Set(['status', 'maintain', 'prune', 'recover', 'reset']);
89
+ if (!known.has(sub)) {
90
+ if (json)
91
+ writeJson(stdout, { ok: false, command: sub, reason: 'unknown_subcommand' });
92
+ else
93
+ stderr(`unknown memory-graph subcommand: ${sub}\n${USAGE}`);
94
+ return 1;
95
+ }
96
+ const allowed = new Set(sub === 'reset' ? ['--json', '--yes'] : ['--json']);
97
+ if (rest.some((arg) => !allowed.has(arg))) {
98
+ return writeFailure(sub, 'unknown_argument', json, stdout, stderr, true);
99
+ }
100
+ if (sub === 'reset' && !rest.includes('--yes')) {
101
+ return writeFailure(sub, 'confirmation_required', json, stdout, stderr, true);
102
+ }
103
+ const env = { ...(deps.env ?? process.env) };
104
+ const envFile = loadEnvFileFromEnv(env);
105
+ if (envFile.error)
106
+ return writeFailure(sub, 'env_file_unavailable', json, stdout, stderr);
107
+ if (!events.evomapHome(env).trim()) {
108
+ return writeFailure(sub, 'memory_graph_home_rejected', json, stdout, stderr);
109
+ }
110
+ if (sub === 'status') {
111
+ const status = loadMemoryGraphOperatorStatus(env);
112
+ const ok = status.recovery !== 'degraded' && status.busy !== true;
113
+ if (json)
114
+ writeJson(stdout, { ok, command: 'status', status });
115
+ else
116
+ stdout(`${formatMemoryGraphOperatorStatus(status)}\n`);
117
+ return ok ? 0 : 1;
118
+ }
119
+ try {
120
+ const graph = graphFor(env, deps);
121
+ if (sub === 'maintain')
122
+ return writeMaintenance(sub, graph.maintain(), json, stdout);
123
+ if (sub === 'prune')
124
+ return writeMaintenance(sub, graph.prune(), json, stdout);
125
+ if (sub === 'recover')
126
+ return writeMaintenance(sub, graph.recoverFromArchives(), json, stdout);
127
+ const report = graph.resetGraph();
128
+ if (report.lockReleaseWarning) {
129
+ stderr(`[memory-graph] reset completed; lock release incomplete: ${report.lockReleaseWarning}\n`);
130
+ }
131
+ if (json)
132
+ writeJson(stdout, { ok: true, command: 'reset', report });
133
+ else
134
+ renderReset(report, stdout);
135
+ return 0;
136
+ }
137
+ catch (error) {
138
+ return writeFailure(sub, operationFailureReason(error), json, stdout, stderr);
139
+ }
140
+ }
@@ -0,0 +1,61 @@
1
+ /** V1→V2 asset path / schema mapping — Refs #684 (R4 Asset-format, 5 sub-items). */
2
+ export declare const CURRENT_WIRE_SCHEMA_VERSION: "1.13.0";
3
+ export declare const V1_EVENT_SCHEMA_VERSION_EXAMPLE: "1.6.0";
4
+ /** Machine-readable mapping for the five issue rows. */
5
+ export declare const ASSET_FORMAT_MAP: readonly [{
6
+ readonly id: 1;
7
+ readonly severity: "major";
8
+ readonly v1: "events.jsonl in the selected current store, or repository legacy assets/gep (EvolutionEvent plus ValidationReport rows; stored schema often 1.6.0)";
9
+ readonly v2: "content-addressed EvolutionEvent JSONL; existing schema_version is preserved";
10
+ readonly migrate: "import-v1 injects 1.13.0 only when schema_version is missing; frozen hash mismatches remain untrusted; ValidationReport rows are validated, counted, and preserved in the V1 source";
11
+ }, {
12
+ readonly id: 2;
13
+ readonly severity: "cosmetic";
14
+ readonly v1: "capsules.json(.l) in the selected current store, then repository legacy fallback";
15
+ readonly v2: "LocalJsonlProvider Capsule stream + migration/v1_extensions.jsonl for non-schema fields";
16
+ readonly migrate: "import-v1 combines the capsules envelope and JSONL overlay by id; JSONL wins";
17
+ }, {
18
+ readonly id: 3;
19
+ readonly severity: "cosmetic";
20
+ readonly v1: "candidates.jsonl in the selected current store, then repository legacy fallback";
21
+ readonly v2: "material/candidates (selection input — not wire assets)";
22
+ readonly migrate: "import-v1 skips candidates (report.candidatesSkipped=true); operators keep pool outside wire store";
23
+ }, {
24
+ readonly id: 4;
25
+ readonly severity: "cosmetic";
26
+ readonly v1: "failed_capsules.json";
27
+ readonly v2: "no automatic wire mapping";
28
+ readonly migrate: "not imported; preserve the V1 source for explicit operator recovery";
29
+ }, {
30
+ readonly id: 5;
31
+ readonly severity: "cosmetic";
32
+ readonly v1: "genes.json(.l) in the selected current store, then repository legacy fallback";
33
+ readonly v2: "LocalJsonlProvider Gene JSONL (content-addressed)";
34
+ readonly migrate: "import-v1 combines the genes envelope and JSONL overlay by id; JSONL wins";
35
+ }];
36
+ /** V1 path components used to select one current workspace plus the repository legacy fallback. */
37
+ export declare const V1_GEP_SOURCE_LAYOUT: {
38
+ readonly workspaceCurrent: readonly ["workspace", ".evolver", "gep"];
39
+ readonly rootCurrent: readonly [".evolver", "gep"];
40
+ readonly legacy: readonly ["assets", "gep"];
41
+ };
42
+ export declare const V1_GEP_WIRE_SOURCES: {
43
+ readonly Gene: {
44
+ readonly envelope: {
45
+ readonly basename: "genes.json";
46
+ readonly key: "genes";
47
+ };
48
+ readonly jsonl: "genes.jsonl";
49
+ };
50
+ readonly Capsule: {
51
+ readonly envelope: {
52
+ readonly basename: "capsules.json";
53
+ readonly key: "capsules";
54
+ };
55
+ readonly jsonl: "capsules.jsonl";
56
+ };
57
+ readonly EvolutionEvent: {
58
+ readonly jsonl: "events.jsonl";
59
+ };
60
+ };
61
+ export type AssetFormatMapEntry = (typeof ASSET_FORMAT_MAP)[number];
@@ -0,0 +1,53 @@
1
+ import { wire } from '@evomap/evolver-core';
2
+ /** V1→V2 asset path / schema mapping — Refs #684 (R4 Asset-format, 5 sub-items). */
3
+ export const CURRENT_WIRE_SCHEMA_VERSION = wire.SCHEMA_VERSION;
4
+ export const V1_EVENT_SCHEMA_VERSION_EXAMPLE = '1.6.0';
5
+ /** Machine-readable mapping for the five issue rows. */
6
+ export const ASSET_FORMAT_MAP = [
7
+ {
8
+ id: 1,
9
+ severity: 'major',
10
+ v1: 'events.jsonl in the selected current store, or repository legacy assets/gep (EvolutionEvent plus ValidationReport rows; stored schema often 1.6.0)',
11
+ v2: 'content-addressed EvolutionEvent JSONL; existing schema_version is preserved',
12
+ migrate: `import-v1 injects ${CURRENT_WIRE_SCHEMA_VERSION} only when schema_version is missing; frozen hash mismatches remain untrusted; ValidationReport rows are validated, counted, and preserved in the V1 source`,
13
+ },
14
+ {
15
+ id: 2,
16
+ severity: 'cosmetic',
17
+ v1: 'capsules.json(.l) in the selected current store, then repository legacy fallback',
18
+ v2: 'LocalJsonlProvider Capsule stream + migration/v1_extensions.jsonl for non-schema fields',
19
+ migrate: 'import-v1 combines the capsules envelope and JSONL overlay by id; JSONL wins',
20
+ },
21
+ {
22
+ id: 3,
23
+ severity: 'cosmetic',
24
+ v1: 'candidates.jsonl in the selected current store, then repository legacy fallback',
25
+ v2: 'material/candidates (selection input — not wire assets)',
26
+ migrate: 'import-v1 skips candidates (report.candidatesSkipped=true); operators keep pool outside wire store',
27
+ },
28
+ {
29
+ id: 4,
30
+ severity: 'cosmetic',
31
+ v1: 'failed_capsules.json',
32
+ v2: 'no automatic wire mapping',
33
+ migrate: 'not imported; preserve the V1 source for explicit operator recovery',
34
+ },
35
+ {
36
+ id: 5,
37
+ severity: 'cosmetic',
38
+ v1: 'genes.json(.l) in the selected current store, then repository legacy fallback',
39
+ v2: 'LocalJsonlProvider Gene JSONL (content-addressed)',
40
+ migrate: 'import-v1 combines the genes envelope and JSONL overlay by id; JSONL wins',
41
+ },
42
+ ];
43
+ /** V1 path components used to select one current workspace plus the repository legacy fallback. */
44
+ export const V1_GEP_SOURCE_LAYOUT = {
45
+ workspaceCurrent: ['workspace', '.evolver', 'gep'],
46
+ rootCurrent: ['.evolver', 'gep'],
47
+ legacy: ['assets', 'gep'],
48
+ };
49
+ export const V1_GEP_WIRE_SOURCES = {
50
+ Gene: { envelope: { basename: 'genes.json', key: 'genes' }, jsonl: 'genes.jsonl' },
51
+ Capsule: { envelope: { basename: 'capsules.json', key: 'capsules' }, jsonl: 'capsules.jsonl' },
52
+ EvolutionEvent: { jsonl: 'events.jsonl' },
53
+ };
@@ -31,6 +31,7 @@ export function formatMappedDotenvFragment(report) {
31
31
  '# Generated by: evolver migrate env --write-suggestions',
32
32
  '# Only MAP suggestions (V1 → V2 rename). Review before applying.',
33
33
  '# Manual and removed V1 keys are comments; resolve manual items before deleting them.',
34
+ ...(report.caveats ?? []).map((caveat) => `# CAVEAT ${caveat}`),
34
35
  '',
35
36
  ];
36
37
  for (const s of report.suggestions) {
@@ -121,6 +122,7 @@ export async function runMigrateEnvCommand(argv, io = {}) {
121
122
  manualCount: result.report.manualCount,
122
123
  removableCount: result.report.removableCount,
123
124
  githubTokenPresent: result.report.githubTokenPresent,
125
+ caveats: result.report.caveats ?? [],
124
126
  suggestions: result.report.suggestions.map((s) => ({
125
127
  v1Name: s.v1Name,
126
128
  action: s.action,
@@ -7,12 +7,14 @@ export interface MappedAsset {
7
7
  /**
8
8
  * v1 资产 → v2 wire(M8-2). 规则:
9
9
  * - 只留 gep-sdk schema 允许字段, 其余(avoid 等)落 dropped→sidecar(不参与 canonicalize, 不动 asset_id).
10
- * - Gene 缺 schema_version → 注入 wire.SCHEMA_VERSION(权威 1.6.0, 非 package version).
10
+ * - 缺 schema_version → 注入 wire.SCHEMA_VERSION 作为新记录 authoring default;已有版本原样保留。
11
+ * SDK package version 不是最低可接受 wire version。
11
12
  * - source_type 非标枚举 → generated; mutation_id null → ''.
12
- * - asset_id: 有则**冻结**(原样); 仅 event 缺 asset_id 时新算(recomputed=true).
13
+ * - asset_id: 有则**冻结**(原样); 缺失时新算(recomputed=true). 若映射改变正文,importer 会用
14
+ * content-bound provenance 隔离 frozen mismatch,而不是把它默认为可信资产(Refs #677).
13
15
  * - v2 新增 optional(resolution_status/proof_of_work/...) v1 无 → 自然省略(不合成).
14
- * - Gene 的 routing_hint/tool_policy 是 v2-delta(v1 PR #93): gep-sdk gene.schema.json 尚无 → schemaProperties
15
- * 不含它们, 默认会落 sidecar; 这里按已知 delta 归一化后保留在 record(保真). 存在但归一化为 null 的脏值
16
- * (如 {tier:'ultra'})落 sidecar(可审计, 不静默丢); v1 的 null/缺省干净省略, 不污染 sidecar.
16
+ * - Gene 的 routing_hint/tool_policy/generation_meta 需要先 normalize,不能走 raw-copy;这里维护迁移本地
17
+ * 的阻断集,避免 future schema promotion 让 `allowed.has(k)` 把原始脏值直接塞进 record。
18
+ * v1 的 null/缺省干净省略;存在但归一化失败的脏值落 dropped 便于审计。
17
19
  */
18
20
  export declare function mapV1Asset(kind: V1Kind, v1: Record<string, unknown>): MappedAsset;
@@ -1,30 +1,36 @@
1
1
  import { wire } from '@evomap/evolver-core';
2
2
  // v1→v2 source_type 枚举转换(skill2gep_distillation 等非标 → generated).
3
3
  const SOURCE_TYPE_MAP = { skill2gep_distillation: 'generated' };
4
- const KNOWN_SOURCE = new Set(['generated', 'reused', 'reference']);
4
+ const KNOWN_SOURCE = new Set(['generated', 'reused', 'reference', 'user_authored']);
5
+ const GENE_RAW_NORMALIZED_FIELDS = new Set(['routing_hint', 'tool_policy', 'generation_meta']);
5
6
  /**
6
7
  * v1 资产 → v2 wire(M8-2). 规则:
7
8
  * - 只留 gep-sdk schema 允许字段, 其余(avoid 等)落 dropped→sidecar(不参与 canonicalize, 不动 asset_id).
8
- * - Gene 缺 schema_version → 注入 wire.SCHEMA_VERSION(权威 1.6.0, 非 package version).
9
+ * - 缺 schema_version → 注入 wire.SCHEMA_VERSION 作为新记录 authoring default;已有版本原样保留。
10
+ * SDK package version 不是最低可接受 wire version。
9
11
  * - source_type 非标枚举 → generated; mutation_id null → ''.
10
- * - asset_id: 有则**冻结**(原样); 仅 event 缺 asset_id 时新算(recomputed=true).
12
+ * - asset_id: 有则**冻结**(原样); 缺失时新算(recomputed=true). 若映射改变正文,importer 会用
13
+ * content-bound provenance 隔离 frozen mismatch,而不是把它默认为可信资产(Refs #677).
11
14
  * - v2 新增 optional(resolution_status/proof_of_work/...) v1 无 → 自然省略(不合成).
12
- * - Gene 的 routing_hint/tool_policy 是 v2-delta(v1 PR #93): gep-sdk gene.schema.json 尚无 → schemaProperties
13
- * 不含它们, 默认会落 sidecar; 这里按已知 delta 归一化后保留在 record(保真). 存在但归一化为 null 的脏值
14
- * (如 {tier:'ultra'})落 sidecar(可审计, 不静默丢); v1 的 null/缺省干净省略, 不污染 sidecar.
15
+ * - Gene 的 routing_hint/tool_policy/generation_meta 需要先 normalize,不能走 raw-copy;这里维护迁移本地
16
+ * 的阻断集,避免 future schema promotion 让 `allowed.has(k)` 把原始脏值直接塞进 record。
17
+ * v1 的 null/缺省干净省略;存在但归一化失败的脏值落 dropped 便于审计。
15
18
  */
16
19
  export function mapV1Asset(kind, v1) {
17
20
  const allowed = new Set(wire.schemaProperties(kind));
18
- const record = {};
19
- const dropped = {};
20
- // v2-delta gene 提示字段不当作"非 schema 字段"丢 sidecar — 下方归一化后保留为 record 一等字段.
21
- const deltaKeys = kind === 'Gene' ? new Set(wire.GENE_HINT_FIELDS) : new Set();
21
+ // V1 rows are untrusted. Null prototypes keep keys such as `__proto__` auditable instead of invoking
22
+ // Object.prototype setters and silently losing extension data.
23
+ const record = Object.create(null);
24
+ const dropped = Object.create(null);
25
+ // Gene normalization is migration-local. wire.GENE_HINT_FIELDS is only the runtime strip list for local-only
26
+ // annotations; do not reuse it here or a future schema promotion can re-enable raw-copy leakage.
27
+ const geneNormalizedFields = kind === 'Gene' ? GENE_RAW_NORMALIZED_FIELDS : null;
22
28
  for (const [k, val] of Object.entries(v1)) {
23
- // Hint fields are owned EXCLUSIVELY by the normalize block below — never copied raw. This must hold even
29
+ // Normalized Gene fields are owned EXCLUSIVELY by the block below — never copied raw. This must hold even
24
30
  // after a future gep-sdk bump adds them to schemaProperties (allowed): otherwise `allowed.has(k)` would
25
- // copy the RAW v1 hint into record, and the normalize-overwrite below only fires when normalize returns
31
+ // copy the RAW v1 field into record, and the normalize-overwrite below only fires when normalize returns
26
32
  // truthy — so a malformed hint (normalizes to null) would leak through un-normalized.
27
- if (deltaKeys.has(k))
33
+ if (geneNormalizedFields?.has(k))
28
34
  continue;
29
35
  if (allowed.has(k))
30
36
  record[k] = val;
@@ -50,7 +56,7 @@ export function mapV1Asset(kind, v1) {
50
56
  // (forward-compat for a repo that carried the #302 branch). A `_source` whose generation_source normalizes away
51
57
  // (unknown enum) is NOT silently dropped — the raw `_source` stays in `dropped` for audit (it already landed there
52
58
  // above as a non-schema field). `generation_meta` itself (if a v1 gene already carried the v2 field name) is a
53
- // deltaKey so it was skipped above and is handled here by normalize, same as the hints.
59
+ // normalized field and is handled here by normalize, same as the hints.
54
60
  if (v1['_source'] !== undefined && v1['_source'] !== null) {
55
61
  const src = v1['_source'];
56
62
  if (src && typeof src === 'object') {
@@ -1,9 +1,81 @@
1
1
  import { assetstore } from '@evomap/evolver-core';
2
2
  import { type V1Kind } from './fieldMap.js';
3
+ declare const IMPORT_V1_PLAN_SCHEMA: "evolver.migration.import-v1-plan.v1";
4
+ declare const IMPORT_V1_SOURCE_ROLES: readonly ["gene-envelope", "gene-jsonl", "capsule-envelope", "capsule-jsonl", "event-jsonl", "mailbox-jsonl", "memory-graph-jsonl", "candidates-jsonl", "failed-capsules-json"];
5
+ type ImportV1SourceRole = (typeof IMPORT_V1_SOURCE_ROLES)[number];
6
+ export interface ImportV1PlanSource {
7
+ role: ImportV1SourceRole;
8
+ path: string;
9
+ bytes: number;
10
+ sha256: string;
11
+ records: number;
12
+ }
13
+ export interface ImportV1PlanReport {
14
+ schema: typeof IMPORT_V1_PLAN_SCHEMA;
15
+ sourceSchemaVersions: Readonly<Record<string, number>>;
16
+ targetAuthoringSchemaVersion: string;
17
+ sources: readonly ImportV1PlanSource[];
18
+ assets: Readonly<Record<V1Kind, {
19
+ candidates: number;
20
+ verified: number;
21
+ unverified: number;
22
+ frozen: number;
23
+ recomputed: number;
24
+ writes: number;
25
+ deduped: number;
26
+ }>>;
27
+ provenance: {
28
+ candidates: number;
29
+ writes: number;
30
+ preserved: number;
31
+ };
32
+ extensions: {
33
+ candidates: number;
34
+ appends: number;
35
+ deduped: number;
36
+ };
37
+ mailbox: {
38
+ found: boolean;
39
+ candidates: number;
40
+ inserts: number;
41
+ updates: number;
42
+ protected: number;
43
+ };
44
+ memoryGraph: {
45
+ found: boolean;
46
+ candidates: number;
47
+ importable: number;
48
+ deduped: number;
49
+ rejected: number;
50
+ deferred: number;
51
+ disposition: 'import' | 'defer' | 'absent';
52
+ };
53
+ validationReports: {
54
+ found: boolean;
55
+ candidates: number;
56
+ disposition: 'preserve_source_no_v2_mapping' | 'absent';
57
+ };
58
+ candidates: {
59
+ found: boolean;
60
+ candidates: number;
61
+ disposition: 'skip_non_wire' | 'absent';
62
+ };
63
+ failedCapsules: {
64
+ found: boolean;
65
+ candidates: number;
66
+ disposition: 'preserve_manual_recovery' | 'absent';
67
+ };
68
+ planDigest: string;
69
+ }
70
+ export interface ImportV1Plan {
71
+ readonly report: ImportV1PlanReport;
72
+ dispose(): void;
73
+ }
3
74
  export interface ImportReport {
4
75
  imported: Record<V1Kind, number>;
5
76
  frozen: number;
6
77
  recomputed: number;
78
+ unverifiedFrozen: number;
7
79
  deduped: number;
8
80
  sidecarExtensions: number;
9
81
  memoryGraphArchived: boolean;
@@ -26,9 +98,16 @@ export interface ImportV1Options {
26
98
  sidecarAppendTestHook?: (stage: 'before-append' | 'after-append', path: string) => void;
27
99
  /** Test seam used to exercise completion-marker publication failures. */
28
100
  memoryGraphMarkerTestHook?: (stage: 'before-publish', temporaryPath: string, markerPath: string) => void;
101
+ /** Test seam used to deterministically exercise output-root rebinding races. */
102
+ outputRootTestHook?: (stage: 'before-secure', path: string) => void;
103
+ /** Test seam used to deterministically exercise owned-plan cleanup failures. */
104
+ disposeTestHook?: (stage: 'before-remove', snapshotDir: string) => void;
29
105
  }
106
+ export declare function planImportV1(v1Dir: string, outDir: string, options?: ImportV1Options): Promise<ImportV1Plan>;
107
+ export declare function applyImportV1Plan(plan: ImportV1Plan, store: assetstore.LocalJsonlProvider | undefined, outDir: string, options?: ImportV1Options): Promise<ImportReport>;
30
108
  export declare function importV1(v1Dir: string, store: assetstore.LocalJsonlProvider, outDir: string, options?: ImportV1Options): Promise<ImportReport>;
31
109
  export declare function validateMigrationRoots(v1Dir: string, outDir: string): {
32
110
  sourceRoot: string;
33
111
  outputRoot: string;
34
- };
112
+ };
113
+ export {};