@evomap/evolver-cli 2.0.0-beta.0

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 (91) hide show
  1. package/dist/antiGeneBenchmark.d.ts +9 -0
  2. package/dist/antiGeneBenchmark.js +173 -0
  3. package/dist/antiGeneRollout.d.ts +14 -0
  4. package/dist/antiGeneRollout.js +276 -0
  5. package/dist/atp.d.ts +122 -0
  6. package/dist/atp.js +413 -0
  7. package/dist/atpAutoDeliver.d.ts +53 -0
  8. package/dist/atpAutoDeliver.js +197 -0
  9. package/dist/atpAutobuyPrompt.d.ts +48 -0
  10. package/dist/atpAutobuyPrompt.js +109 -0
  11. package/dist/autoDistillAntiGene.d.ts +63 -0
  12. package/dist/autoDistillAntiGene.js +396 -0
  13. package/dist/autoDistillLlm.d.ts +94 -0
  14. package/dist/autoDistillLlm.js +510 -0
  15. package/dist/autoDistillTranscript.d.ts +87 -0
  16. package/dist/autoDistillTranscript.js +364 -0
  17. package/dist/autoRecall.d.ts +25 -0
  18. package/dist/autoRecall.js +80 -0
  19. package/dist/autoexec.d.ts +237 -0
  20. package/dist/autoexec.js +1041 -0
  21. package/dist/cli.d.ts +2 -0
  22. package/dist/cli.js +7 -0
  23. package/dist/cliContracts.d.ts +72 -0
  24. package/dist/cliContracts.js +815 -0
  25. package/dist/commands.d.ts +9 -0
  26. package/dist/commands.js +10 -0
  27. package/dist/cursorRewrite.d.ts +42 -0
  28. package/dist/cursorRewrite.js +65 -0
  29. package/dist/cycleConsumer.d.ts +42 -0
  30. package/dist/cycleConsumer.js +519 -0
  31. package/dist/daemonLoop.d.ts +33 -0
  32. package/dist/daemonLoop.js +72 -0
  33. package/dist/dispatch.d.ts +10 -0
  34. package/dist/dispatch.js +75 -0
  35. package/dist/distillObserver.d.ts +33 -0
  36. package/dist/distillObserver.js +146 -0
  37. package/dist/distillPrimitives.d.ts +48 -0
  38. package/dist/distillPrimitives.js +142 -0
  39. package/dist/doctor.d.ts +54 -0
  40. package/dist/doctor.js +931 -0
  41. package/dist/geneValue.d.ts +37 -0
  42. package/dist/geneValue.js +97 -0
  43. package/dist/index.d.ts +193 -0
  44. package/dist/index.js +1135 -0
  45. package/dist/lifecycle.d.ts +75 -0
  46. package/dist/lifecycle.js +859 -0
  47. package/dist/login.d.ts +10 -0
  48. package/dist/login.js +38 -0
  49. package/dist/migrate/divergenceAudit.d.ts +29 -0
  50. package/dist/migrate/divergenceAudit.js +37 -0
  51. package/dist/migrate/fieldMap.d.ts +18 -0
  52. package/dist/migrate/fieldMap.js +68 -0
  53. package/dist/migrate/v1Import.d.ts +16 -0
  54. package/dist/migrate/v1Import.js +118 -0
  55. package/dist/phub.d.ts +18 -0
  56. package/dist/phub.js +284 -0
  57. package/dist/recall.d.ts +26 -0
  58. package/dist/recall.js +162 -0
  59. package/dist/recipe.d.ts +61 -0
  60. package/dist/recipe.js +564 -0
  61. package/dist/reflectionObserver.d.ts +8 -0
  62. package/dist/reflectionObserver.js +6 -0
  63. package/dist/reuse.d.ts +48 -0
  64. package/dist/reuse.js +300 -0
  65. package/dist/reuseReport.d.ts +20 -0
  66. package/dist/reuseReport.js +255 -0
  67. package/dist/reviewFilter.d.ts +4 -0
  68. package/dist/reviewFilter.js +6 -0
  69. package/dist/runtimeSessionSource.d.ts +9 -0
  70. package/dist/runtimeSessionSource.js +29 -0
  71. package/dist/setupHooks.d.ts +2 -0
  72. package/dist/setupHooks.js +410 -0
  73. package/dist/skill2gep.d.ts +144 -0
  74. package/dist/skill2gep.js +321 -0
  75. package/dist/skillDistill.d.ts +75 -0
  76. package/dist/skillDistill.js +342 -0
  77. package/dist/solo/breaker.d.ts +14 -0
  78. package/dist/solo/breaker.js +21 -0
  79. package/dist/solo/gitGuard.d.ts +17 -0
  80. package/dist/solo/gitGuard.js +62 -0
  81. package/dist/solo/mode.d.ts +12 -0
  82. package/dist/solo/mode.js +55 -0
  83. package/dist/thesis.d.ts +43 -0
  84. package/dist/thesis.js +179 -0
  85. package/dist/trajectoryExport.d.ts +1 -0
  86. package/dist/trajectoryExport.js +895 -0
  87. package/dist/valueDigest.d.ts +33 -0
  88. package/dist/valueDigest.js +94 -0
  89. package/dist/version.d.ts +2 -0
  90. package/dist/version.js +14 -0
  91. package/package.json +38 -0
@@ -0,0 +1,10 @@
1
+ /**
2
+ * `evolver login` — RFC 8628 device authorization grant against the public hub
3
+ * (like `gh auth login`): print a user code + verification URL, then poll until
4
+ * the user approves in the browser, storing the token at ~/.evomap/token.json.
5
+ *
6
+ * Hub URL comes from EVOMAP_HUB_URL (default https://evomap.ai); EVOMAP_DIR
7
+ * overrides the credential directory. The token replaces node_secret for
8
+ * publish + /a2a calls (it carries the `a2a` scope).
9
+ */
10
+ export declare function runLogin(_argv: readonly string[]): Promise<number>;
package/dist/login.js ADDED
@@ -0,0 +1,38 @@
1
+ import { homedir } from 'node:os';
2
+ import { join } from 'node:path';
3
+ import { PublicOAuthProvider, createOAuthHttpTransport } from '@evomap/evolver-adapter-public';
4
+ /**
5
+ * `evolver login` — RFC 8628 device authorization grant against the public hub
6
+ * (like `gh auth login`): print a user code + verification URL, then poll until
7
+ * the user approves in the browser, storing the token at ~/.evomap/token.json.
8
+ *
9
+ * Hub URL comes from EVOMAP_HUB_URL (default https://evomap.ai); EVOMAP_DIR
10
+ * overrides the credential directory. The token replaces node_secret for
11
+ * publish + /a2a calls (it carries the `a2a` scope).
12
+ */
13
+ export async function runLogin(_argv) {
14
+ const hubUrl = process.env.EVOMAP_HUB_URL ?? 'https://evomap.ai';
15
+ const dir = process.env.EVOMAP_DIR ?? join(homedir(), '.evomap');
16
+ const credPath = join(dir, 'token.json');
17
+ const provider = new PublicOAuthProvider({
18
+ credPath,
19
+ machine: { softIdPath: join(dir, 'machine-id') },
20
+ transport: createOAuthHttpTransport({ hubUrl }),
21
+ onUserCode: (d) => {
22
+ process.stdout.write(`\nTo authorize this device:\n` +
23
+ ` 1. open ${d.verificationUri}\n` +
24
+ ` 2. enter code: ${d.userCode}\n\n` +
25
+ `Waiting for approval (Ctrl-C to cancel)...\n`);
26
+ },
27
+ });
28
+ try {
29
+ const cred = await provider.login();
30
+ const exp = cred.expiresAt ? new Date(cred.expiresAt).toISOString() : 'n/a';
31
+ process.stdout.write(`\n✓ Logged in to ${hubUrl}. Token stored at ${credPath} (expires ${exp}).\n`);
32
+ return 0;
33
+ }
34
+ catch (e) {
35
+ process.stderr.write(`login failed: ${e instanceof Error ? e.message : String(e)}\n`);
36
+ return 1;
37
+ }
38
+ }
@@ -0,0 +1,29 @@
1
+ import type { shadow } from '@evomap/evolver-core';
2
+ type ShadowRecord = shadow.ShadowRecord;
3
+ /** v1 actual 对照基准(由 v1 资产/真 hub 回执历史导出). */
4
+ export interface V1Reference {
5
+ publishedAssetIds: readonly string[];
6
+ settleCount: number;
7
+ frozenAssetIds?: readonly string[];
8
+ }
9
+ export interface DivergenceReport {
10
+ publishDecisionMatchRate: number;
11
+ wouldPublishCount: number;
12
+ wouldSettleCount: number;
13
+ v1SettleCount: number;
14
+ settleDelta: number;
15
+ wouldStorePutCount: number;
16
+ dedupCollisionCount: number;
17
+ pushTypeDistribution: Record<string, number>;
18
+ schemaGateRejectCount: number;
19
+ green: boolean;
20
+ reasons: string[];
21
+ }
22
+ /**
23
+ * shadow 对账(M8-2-shadow-g). 比 v2 shadow 决策(WOULD_*) vs v1 actual, 算 divergenceMetrics.
24
+ * enforce 门槛数据源: green=true 才允许团队签字切 enforce(配合 money-safety 复核)。
25
+ */
26
+ export declare function divergenceAudit(records: readonly ShadowRecord[], v1: V1Reference, opts?: {
27
+ schemaGateRejectCount?: number;
28
+ }): DivergenceReport;
29
+ export {};
@@ -0,0 +1,37 @@
1
+ /**
2
+ * shadow 对账(M8-2-shadow-g). 比 v2 shadow 决策(WOULD_*) vs v1 actual, 算 divergenceMetrics.
3
+ * enforce 门槛数据源: green=true 才允许团队签字切 enforce(配合 money-safety 复核)。
4
+ */
5
+ export function divergenceAudit(records, v1, opts = {}) {
6
+ const publishes = records.filter((r) => r.action === 'WOULD_PUBLISH');
7
+ const wouldPublishIds = publishes.map((r) => r.assetId).filter((x) => !!x);
8
+ const v1Set = new Set(v1.publishedAssetIds);
9
+ const matched = [...new Set(wouldPublishIds)].filter((id) => v1Set.has(id)).length;
10
+ const publishDecisionMatchRate = v1Set.size > 0 ? matched / v1Set.size : (wouldPublishIds.length === 0 ? 1 : 0);
11
+ const wouldSettleCount = records.filter((r) => r.action === 'WOULD_SETTLE').length;
12
+ const settleDelta = wouldSettleCount - v1.settleCount;
13
+ // 去重碰撞: 同 asset_id 出现 >1 次 WOULD_PUBLISH/WOULD_STORE_PUT
14
+ const idCounts = new Map();
15
+ for (const r of records)
16
+ if ((r.action === 'WOULD_PUBLISH' || r.action === 'WOULD_STORE_PUT') && r.assetId)
17
+ idCounts.set(r.assetId, (idCounts.get(r.assetId) ?? 0) + 1);
18
+ const dedupCollisionCount = [...idCounts.values()].filter((c) => c > 1).length;
19
+ const pushTypeDistribution = {};
20
+ for (const r of records)
21
+ if (r.action === 'WOULD_PUSH' && r.envelopeType)
22
+ pushTypeDistribution[r.envelopeType] = (pushTypeDistribution[r.envelopeType] ?? 0) + 1;
23
+ const schemaGateRejectCount = opts.schemaGateRejectCount ?? 0;
24
+ const reasons = [];
25
+ if (publishDecisionMatchRate < 0.999)
26
+ reasons.push(`publish 决策重合率 ${(publishDecisionMatchRate * 100).toFixed(1)}% < 100%`);
27
+ if (settleDelta !== 0)
28
+ reasons.push(`结算差值 ${settleDelta}≠0(money-safety, 须逐条解释)`);
29
+ if (schemaGateRejectCount > 0)
30
+ reasons.push(`schema_gate 拒绝 ${schemaGateRejectCount}>0`);
31
+ return {
32
+ publishDecisionMatchRate, wouldPublishCount: publishes.length, wouldSettleCount, v1SettleCount: v1.settleCount, settleDelta,
33
+ wouldStorePutCount: records.filter((r) => r.action === 'WOULD_STORE_PUT').length,
34
+ dedupCollisionCount, pushTypeDistribution, schemaGateRejectCount,
35
+ green: reasons.length === 0, reasons,
36
+ };
37
+ }
@@ -0,0 +1,18 @@
1
+ export type V1Kind = 'Gene' | 'Capsule' | 'EvolutionEvent';
2
+ export interface MappedAsset {
3
+ record: Record<string, unknown>;
4
+ dropped: Record<string, unknown>;
5
+ recomputed: boolean;
6
+ }
7
+ /**
8
+ * v1 资产 → v2 wire(M8-2). 规则:
9
+ * - 只留 gep-sdk schema 允许字段, 其余(avoid 等)落 dropped→sidecar(不参与 canonicalize, 不动 asset_id).
10
+ * - Gene 缺 schema_version → 注入 wire.SCHEMA_VERSION(权威 1.6.0, 非 package version).
11
+ * - source_type 非标枚举 → generated; mutation_id null → ''.
12
+ * - asset_id: 有则**冻结**(原样); 仅 event 缺 asset_id 时新算(recomputed=true).
13
+ * - 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.
17
+ */
18
+ export declare function mapV1Asset(kind: V1Kind, v1: Record<string, unknown>): MappedAsset;
@@ -0,0 +1,68 @@
1
+ import { wire } from '@evomap/evolver-core';
2
+ // v1→v2 source_type 枚举转换(skill2gep_distillation 等非标 → generated).
3
+ const SOURCE_TYPE_MAP = { skill2gep_distillation: 'generated' };
4
+ const KNOWN_SOURCE = new Set(['generated', 'reused', 'reference']);
5
+ /**
6
+ * v1 资产 → v2 wire(M8-2). 规则:
7
+ * - 只留 gep-sdk schema 允许字段, 其余(avoid 等)落 dropped→sidecar(不参与 canonicalize, 不动 asset_id).
8
+ * - Gene 缺 schema_version → 注入 wire.SCHEMA_VERSION(权威 1.6.0, 非 package version).
9
+ * - source_type 非标枚举 → generated; mutation_id null → ''.
10
+ * - asset_id: 有则**冻结**(原样); 仅 event 缺 asset_id 时新算(recomputed=true).
11
+ * - 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
+ */
16
+ export function mapV1Asset(kind, v1) {
17
+ 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();
22
+ 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
24
+ // 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
26
+ // truthy — so a malformed hint (normalizes to null) would leak through un-normalized.
27
+ if (deltaKeys.has(k))
28
+ continue;
29
+ if (allowed.has(k))
30
+ record[k] = val;
31
+ else
32
+ dropped[k] = val;
33
+ }
34
+ if (kind === 'Gene') {
35
+ // 归一化后留在 record(保真). 一个"存在且非 null 却归一化为 null"的脏 hint(如 {tier:'ultra'})既进不了
36
+ // record, 也不该静默蒸发 —— 与 mapper 对其它非 schema 字段(avoid 等)"落 sidecar, 绝不静默丢"的契约一致,
37
+ // 把原始脏值留到 dropped 以便审计回溯. v1 的 null/缺省(无意见)仍干净省略, 不污染 sidecar.
38
+ const routingHint = wire.normalizeRoutingHint(v1['routing_hint']);
39
+ const toolPolicy = wire.normalizeToolPolicy(v1['tool_policy']);
40
+ if (routingHint)
41
+ record['routing_hint'] = routingHint;
42
+ else if (v1['routing_hint'] !== null && v1['routing_hint'] !== undefined)
43
+ dropped['routing_hint'] = v1['routing_hint'];
44
+ if (toolPolicy)
45
+ record['tool_policy'] = toolPolicy;
46
+ else if (v1['tool_policy'] !== null && v1['tool_policy'] !== undefined)
47
+ dropped['tool_policy'] = v1['tool_policy'];
48
+ }
49
+ if (allowed.has('schema_version') && record['schema_version'] === undefined)
50
+ record['schema_version'] = wire.SCHEMA_VERSION;
51
+ if (record['source_type'] !== undefined) {
52
+ const st = String(record['source_type']);
53
+ if (!KNOWN_SOURCE.has(st))
54
+ record['source_type'] = SOURCE_TYPE_MAP[st] ?? 'generated';
55
+ }
56
+ if ('mutation_id' in record && (record['mutation_id'] === null || record['mutation_id'] === undefined))
57
+ record['mutation_id'] = '';
58
+ let recomputed = false;
59
+ const claimed = record['asset_id'];
60
+ if (typeof claimed === 'string' && claimed.length > 0) {
61
+ // 冻结: 原样保留(硬化 A6, 不重算)
62
+ }
63
+ else if (allowed.has('asset_id')) {
64
+ record['asset_id'] = wire.computeAssetId(record); // 仅缺失时新算(verified=false)
65
+ recomputed = true;
66
+ }
67
+ return { record, dropped, recomputed };
68
+ }
@@ -0,0 +1,16 @@
1
+ import { assetstore } from '@evomap/evolver-core';
2
+ import { type V1Kind } from './fieldMap.js';
3
+ export interface ImportReport {
4
+ imported: Record<V1Kind, number>;
5
+ frozen: number;
6
+ recomputed: number;
7
+ deduped: number;
8
+ sidecarExtensions: number;
9
+ memoryGraphArchived: boolean;
10
+ candidatesSkipped: boolean;
11
+ }
12
+ /**
13
+ * v1→v2 只读迁移(M8-2). 只读 v1(无双写); 冻结存量 asset_id; 非 schema 字段(avoid)落 sidecar;
14
+ * memory_graph 不强转(语义不符)→ 归档只读; candidates 候选池不属 wire 资产 → 跳过.
15
+ */
16
+ export declare function importV1(v1Dir: string, store: assetstore.LocalJsonlProvider, outDir: string): Promise<ImportReport>;
@@ -0,0 +1,118 @@
1
+ import { createReadStream } from 'node:fs';
2
+ import { existsSync, mkdirSync, appendFileSync, copyFileSync } from 'node:fs';
3
+ import { join, dirname } from 'node:path';
4
+ import { assetstore } from '@evomap/evolver-core';
5
+ import { mapV1Asset } from './fieldMap.js';
6
+ const FILES = { Gene: 'genes.jsonl', Capsule: 'capsules.jsonl', EvolutionEvent: 'events.jsonl' };
7
+ const DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES = 16 * 1024 * 1024;
8
+ function maxJsonlLineBytes() {
9
+ const raw = Number(process.env['EVOLVER_IMPORT_JSONL_MAX_LINE_BYTES']);
10
+ return Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : DEFAULT_IMPORT_JSONL_MAX_LINE_BYTES;
11
+ }
12
+ async function* readJsonl(path) {
13
+ if (!existsSync(path))
14
+ return;
15
+ const maxLineBytes = maxJsonlLineBytes();
16
+ let parts = [];
17
+ let lineBytes = 0;
18
+ let dropping = false;
19
+ const finish = function* () {
20
+ if (dropping || lineBytes === 0) {
21
+ parts = [];
22
+ lineBytes = 0;
23
+ dropping = false;
24
+ return;
25
+ }
26
+ const text = Buffer.concat(parts, lineBytes).toString('utf8').trim();
27
+ parts = [];
28
+ lineBytes = 0;
29
+ if (!text)
30
+ return;
31
+ try {
32
+ yield JSON.parse(text);
33
+ }
34
+ catch { /* skip corrupt rows */ }
35
+ };
36
+ for await (const chunk of createReadStream(path)) {
37
+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
38
+ let start = 0;
39
+ for (let i = 0; i < buf.length; i += 1) {
40
+ if (buf[i] !== 0x0a)
41
+ continue;
42
+ const segment = buf.subarray(start, i);
43
+ if (!dropping) {
44
+ if (lineBytes + segment.length > maxLineBytes) {
45
+ parts = [];
46
+ lineBytes = 0;
47
+ dropping = true;
48
+ }
49
+ else {
50
+ parts.push(Buffer.from(segment));
51
+ lineBytes += segment.length;
52
+ }
53
+ }
54
+ for (const record of finish())
55
+ yield record;
56
+ start = i + 1;
57
+ }
58
+ if (start < buf.length && !dropping) {
59
+ const segment = buf.subarray(start);
60
+ if (lineBytes + segment.length > maxLineBytes) {
61
+ parts = [];
62
+ lineBytes = 0;
63
+ dropping = true;
64
+ }
65
+ else {
66
+ parts.push(Buffer.from(segment));
67
+ lineBytes += segment.length;
68
+ }
69
+ }
70
+ }
71
+ for (const record of finish())
72
+ yield record;
73
+ }
74
+ /**
75
+ * v1→v2 只读迁移(M8-2). 只读 v1(无双写); 冻结存量 asset_id; 非 schema 字段(avoid)落 sidecar;
76
+ * memory_graph 不强转(语义不符)→ 归档只读; candidates 候选池不属 wire 资产 → 跳过.
77
+ */
78
+ export async function importV1(v1Dir, store, outDir) {
79
+ const sidecarPath = join(outDir, 'migration', 'v1_extensions.jsonl');
80
+ const rep = {
81
+ imported: { Gene: 0, Capsule: 0, EvolutionEvent: 0 }, frozen: 0, recomputed: 0, deduped: 0,
82
+ sidecarExtensions: 0, memoryGraphArchived: false, candidatesSkipped: false,
83
+ };
84
+ const gepDir = join(v1Dir, 'assets', 'gep');
85
+ for (const kind of ['Gene', 'Capsule', 'EvolutionEvent']) {
86
+ for await (const v1 of readJsonl(join(gepDir, FILES[kind]))) {
87
+ const mapped = mapV1Asset(kind, v1);
88
+ const res = await store.putFrozen(mapped.record);
89
+ if (res.stored) {
90
+ rep.imported[kind] += 1;
91
+ if (mapped.recomputed)
92
+ rep.recomputed += 1;
93
+ else
94
+ rep.frozen += 1;
95
+ if (Object.keys(mapped.dropped).length > 0) {
96
+ mkdirSync(dirname(sidecarPath), { recursive: true });
97
+ appendFileSync(sidecarPath, `${JSON.stringify({ asset_id: res.asset_id, dropped: mapped.dropped })}\n`);
98
+ rep.sidecarExtensions += 1;
99
+ }
100
+ }
101
+ else {
102
+ rep.deduped += 1;
103
+ }
104
+ }
105
+ }
106
+ // memory_graph: 不迁移成 EvolutionEvent(缺 required + 无 intent/genes_used 语义, 强转=污染谱系). 归档只读.
107
+ const mg = join(v1Dir, 'memory', 'evolution', 'memory_graph.jsonl');
108
+ if (existsSync(mg)) {
109
+ const dest = join(outDir, 'migration', 'legacy_memory_graph.jsonl');
110
+ mkdirSync(dirname(dest), { recursive: true });
111
+ copyFileSync(mg, dest);
112
+ rep.memoryGraphArchived = true;
113
+ }
114
+ // candidates 候选池非 wire 资产 → 不迁移(留作 selection 输入)
115
+ if (existsSync(join(gepDir, 'candidates.jsonl')))
116
+ rep.candidatesSkipped = true;
117
+ return rep;
118
+ }
package/dist/phub.d.ts ADDED
@@ -0,0 +1,18 @@
1
+ import { type DoctorDeps } from './doctor.js';
2
+ type WriteTextFile = (path: string, data: string, options?: {
3
+ encoding?: BufferEncoding;
4
+ mode?: number;
5
+ flag?: string;
6
+ }) => void;
7
+ type MakeDir = (path: string, opts: {
8
+ recursive: true;
9
+ }) => void;
10
+ type RemoveFile = (path: string) => void;
11
+ export interface PhubDeps extends DoctorDeps {
12
+ cwd?: string;
13
+ writeFile?: WriteTextFile;
14
+ mkdir?: MakeDir;
15
+ removeFile?: RemoveFile;
16
+ }
17
+ export declare function runPhubCommand(argv: readonly string[], deps?: PhubDeps): Promise<number>;
18
+ export {};
package/dist/phub.js ADDED
@@ -0,0 +1,284 @@
1
+ import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { dirname, isAbsolute, resolve } from 'node:path';
3
+ import { expandHomePath } from '@evomap/evolver-mcp';
4
+ import { runDoctor } from './doctor.js';
5
+ const USAGE = [
6
+ 'usage: evolver phub <doctor|status> [--root <dir>] [--json] [--env-catalog]',
7
+ ' evolver phub init --env-file <path> [--hub <url>] [--subject <id>] [--adapter-module <module>] [--profile-descriptor <json>] [--force] [--json]',
8
+ '',
9
+ ].join('\n');
10
+ function parseFlags(argv) {
11
+ const out = {};
12
+ for (let i = 0; i < argv.length; i++) {
13
+ const a = argv[i];
14
+ if (!a?.startsWith('--'))
15
+ continue;
16
+ const key = a.slice(2);
17
+ const eq = key.indexOf('=');
18
+ if (eq >= 0)
19
+ out[key.slice(0, eq)] = key.slice(eq + 1);
20
+ else if (argv[i + 1] && !argv[i + 1].startsWith('--'))
21
+ out[key] = argv[++i];
22
+ else
23
+ out[key] = true;
24
+ }
25
+ return out;
26
+ }
27
+ function stringFlag(flags, name) {
28
+ const value = flags[name];
29
+ return typeof value === 'string' && value.trim().length > 0 ? value.trim() : undefined;
30
+ }
31
+ function missingFlagValue(flags, name) {
32
+ return flags[name] === true || (typeof flags[name] === 'string' && flags[name].trim().length === 0);
33
+ }
34
+ function resolveInitPath(raw, cwd) {
35
+ const expanded = raw.startsWith('~') ? expandHomePath(raw) : raw;
36
+ return isAbsolute(expanded) ? expanded : resolve(cwd, expanded);
37
+ }
38
+ function rejectControlValue(label, value) {
39
+ return /[\0\r\n]/.test(value) ? `--${label} must be a single-line value` : undefined;
40
+ }
41
+ function validateHubUrl(value) {
42
+ const control = rejectControlValue('hub', value);
43
+ if (control)
44
+ return control;
45
+ try {
46
+ const url = new URL(value);
47
+ if (url.protocol !== 'https:' && url.protocol !== 'http:')
48
+ return '--hub must use http or https';
49
+ }
50
+ catch {
51
+ return '--hub must be a valid URL';
52
+ }
53
+ return undefined;
54
+ }
55
+ function parseInitOptions(argv, cwd) {
56
+ const flags = parseFlags(argv);
57
+ const json = flags['json'] === true;
58
+ if (flags['help'] === true || flags['h'] === true)
59
+ return { ok: false, error: USAGE, json };
60
+ if (missingFlagValue(flags, 'env-file'))
61
+ return { ok: false, error: 'missing value for --env-file', json };
62
+ if (missingFlagValue(flags, 'profile-descriptor'))
63
+ return { ok: false, error: 'missing value for --profile-descriptor', json };
64
+ const envFileRaw = stringFlag(flags, 'env-file');
65
+ if (!envFileRaw)
66
+ return { ok: false, error: 'phub init requires --env-file <path>', json };
67
+ const hubUrl = stringFlag(flags, 'hub') ?? 'https://private-hub-test.example.com';
68
+ const adapterModule = stringFlag(flags, 'adapter-module') ?? '@evomap/evolver-adapter-private';
69
+ const subject = stringFlag(flags, 'subject');
70
+ const profileRaw = stringFlag(flags, 'profile-descriptor');
71
+ for (const [label, value] of [
72
+ ['env-file', envFileRaw],
73
+ ['adapter-module', adapterModule],
74
+ ...(subject ? [['subject', subject]] : []),
75
+ ...(profileRaw ? [['profile-descriptor', profileRaw]] : []),
76
+ ]) {
77
+ const error = rejectControlValue(label, value);
78
+ if (error)
79
+ return { ok: false, error, json };
80
+ }
81
+ const hubError = validateHubUrl(hubUrl);
82
+ if (hubError)
83
+ return { ok: false, error: hubError, json };
84
+ return {
85
+ ok: true,
86
+ opts: {
87
+ envFile: resolveInitPath(envFileRaw, cwd),
88
+ hubUrl,
89
+ ...(subject ? { subject } : {}),
90
+ adapterModule,
91
+ ...(profileRaw ? { profileDescriptor: resolveInitPath(profileRaw, cwd) } : {}),
92
+ force: flags['force'] === true,
93
+ json,
94
+ },
95
+ };
96
+ }
97
+ function renderEnvFile(opts) {
98
+ return [
99
+ '# PHub private runtime env file.',
100
+ '# Keep real credentials here only; runtime configs should reference this file through EVOLVER_ENV_FILE.',
101
+ 'EVOMAP_HUB_MODE=private',
102
+ `EVOMAP_HUB_URL=${opts.hubUrl}`,
103
+ '# Fill exactly one enterprise token alias before running live smoke or evolver-proxy.',
104
+ '# EVOMAP_ENTERPRISE_TOKEN=replace-with-enterprise-token',
105
+ '# EVOMAP_PRIVATE_HUB_TOKEN=replace-with-enterprise-token',
106
+ opts.subject ? `EVOMAP_ENTERPRISE_SUBJECT=${opts.subject}` : '# EVOMAP_ENTERPRISE_SUBJECT=alice@example.com',
107
+ `EVOMAP_PRIVATE_ADAPTER_MODULE=${opts.adapterModule}`,
108
+ '',
109
+ '# Local loopback proxy settings. Replace the IPC token with a long random value before real use.',
110
+ '# EVOLVER_IPC_TOKEN=replace-with-long-random-ipc-token',
111
+ 'EVOLVER_PROXY_URL=http://127.0.0.1:19820',
112
+ 'EVOLVER_REUSE_BEFORE_SOLVE=1',
113
+ 'NO_PROXY=127.0.0.1,localhost,::1',
114
+ '',
115
+ ].join('\n');
116
+ }
117
+ function renderProfileDescriptor(opts) {
118
+ return `${JSON.stringify({
119
+ envFile: opts.envFile,
120
+ manualHints: {
121
+ 'http-agent': [
122
+ 'Use the PHub HTTP/A2A endpoint supplied by the enterprise adapter.',
123
+ 'Keep Authorization material in EVOLVER_ENV_FILE; do not inline bearer tokens in runtime config.',
124
+ ],
125
+ openclaw: [
126
+ 'Register the OpenClaw MCP bridge with the evolver MCP stdio server.',
127
+ ],
128
+ },
129
+ }, null, 2)}\n`;
130
+ }
131
+ function writeChecked(path, content, deps, mode, overwrite) {
132
+ deps.mkdir(dirname(path), { recursive: true });
133
+ deps.writeFile(path, content, { encoding: 'utf8', mode, flag: overwrite ? 'w' : 'wx' });
134
+ }
135
+ function initTargetKey(path) {
136
+ const key = resolve(path);
137
+ return process.platform === 'win32' ? key.toLowerCase() : key;
138
+ }
139
+ function reportInitError(opts, error) {
140
+ if (opts.json)
141
+ process.stdout.write(`${JSON.stringify({ ok: false, error })}\n`);
142
+ else
143
+ process.stderr.write(`${error}\n`);
144
+ }
145
+ function backupInitTargets(targets, exists, readFile) {
146
+ const backups = new Map();
147
+ for (const path of targets) {
148
+ if (!exists(path)) {
149
+ backups.set(initTargetKey(path), { path, existed: false });
150
+ continue;
151
+ }
152
+ try {
153
+ backups.set(initTargetKey(path), { path, existed: true, content: readFile(path) });
154
+ }
155
+ catch (error) {
156
+ return { ok: false, error: `phub init failed to read existing file before overwrite: ${error instanceof Error ? error.message : String(error)}` };
157
+ }
158
+ }
159
+ return { ok: true, backups };
160
+ }
161
+ function uniqueRollbackPaths(paths) {
162
+ const seen = new Set();
163
+ const unique = [];
164
+ for (const path of paths) {
165
+ const key = initTargetKey(path);
166
+ if (seen.has(key))
167
+ continue;
168
+ seen.add(key);
169
+ unique.push(path);
170
+ }
171
+ return unique;
172
+ }
173
+ function rollbackInitWrites(paths, backups, writer) {
174
+ for (const path of uniqueRollbackPaths(paths).reverse()) {
175
+ const backup = backups.get(initTargetKey(path));
176
+ try {
177
+ if (backup?.existed)
178
+ writeChecked(path, backup.content ?? '', writer, 0o600, true);
179
+ else
180
+ writer.removeFile(path);
181
+ }
182
+ catch {
183
+ // Best-effort cleanup only. Preserve the original write error for the operator.
184
+ }
185
+ }
186
+ }
187
+ function runPhubInit(argv, deps = {}) {
188
+ const parsed = parseInitOptions(argv, deps.cwd ?? process.cwd());
189
+ if (!parsed.ok) {
190
+ if (parsed.json)
191
+ process.stdout.write(`${JSON.stringify({ ok: false, error: parsed.error })}\n`);
192
+ else {
193
+ const stream = parsed.error === USAGE ? process.stdout : process.stderr;
194
+ stream.write(`${parsed.error}${parsed.error.endsWith('\n') ? '' : '\n'}${parsed.error === USAGE ? '' : USAGE}`);
195
+ }
196
+ return parsed.error === USAGE ? 0 : 1;
197
+ }
198
+ const opts = parsed.opts;
199
+ if (opts.profileDescriptor && initTargetKey(opts.profileDescriptor) === initTargetKey(opts.envFile)) {
200
+ reportInitError(opts, 'phub init requires --env-file and --profile-descriptor to point to different files');
201
+ return 1;
202
+ }
203
+ const exists = deps.exists ?? existsSync;
204
+ const targets = [opts.envFile, ...(opts.profileDescriptor ? [opts.profileDescriptor] : [])];
205
+ const existing = targets.filter((path) => exists(path));
206
+ if (existing.length > 0 && !opts.force) {
207
+ reportInitError(opts, `phub init refused to overwrite existing file(s): ${existing.join(', ')} (use --force to overwrite)`);
208
+ return 1;
209
+ }
210
+ const writer = {
211
+ writeFile: deps.writeFile ?? ((path, content, options) => writeFileSync(path, content, options)),
212
+ mkdir: deps.mkdir ?? ((path, options) => { mkdirSync(path, options); }),
213
+ removeFile: deps.removeFile ?? ((path) => { rmSync(path, { force: true }); }),
214
+ };
215
+ const writes = [
216
+ ...(opts.profileDescriptor ? [{ path: opts.profileDescriptor, content: renderProfileDescriptor(opts) }] : []),
217
+ { path: opts.envFile, content: renderEnvFile(opts) },
218
+ ];
219
+ const reader = deps.readFile ?? ((path) => readFileSync(path, 'utf8'));
220
+ const backup = backupInitTargets(writes.map((write) => write.path), exists, reader);
221
+ if (!backup.ok) {
222
+ reportInitError(opts, backup.error);
223
+ return 1;
224
+ }
225
+ const created = [];
226
+ let activePath;
227
+ try {
228
+ for (const write of writes) {
229
+ activePath = write.path;
230
+ writeChecked(write.path, write.content, writer, 0o600, opts.force);
231
+ created.push(write.path);
232
+ activePath = undefined;
233
+ }
234
+ }
235
+ catch (error) {
236
+ rollbackInitWrites([...created, ...(activePath ? [activePath] : [])], backup.backups, writer);
237
+ const message = `phub init failed to write file: ${error instanceof Error ? error.message : String(error)}`;
238
+ reportInitError(opts, message);
239
+ return 1;
240
+ }
241
+ const next = [
242
+ `edit ${opts.envFile} and set exactly one enterprise token alias`,
243
+ `run evolver phub doctor --root <runtime-config-root> with EVOLVER_ENV_FILE=${opts.envFile}`,
244
+ opts.profileDescriptor
245
+ ? `run evolver setup-hooks --runtime=codex --profile-descriptor=${opts.profileDescriptor}`
246
+ : `run evolver setup-hooks --runtime=codex --env-file=${opts.envFile}`,
247
+ `start evolver-proxy with EVOLVER_ENV_FILE=${opts.envFile}`,
248
+ ];
249
+ const result = {
250
+ envFile: opts.envFile,
251
+ ...(opts.profileDescriptor ? { profileDescriptor: opts.profileDescriptor } : {}),
252
+ created,
253
+ next,
254
+ };
255
+ if (opts.json) {
256
+ process.stdout.write(`${JSON.stringify({ ok: true, ...result })}\n`);
257
+ }
258
+ else {
259
+ process.stdout.write([
260
+ `created PHub env file: ${opts.envFile}`,
261
+ ...(opts.profileDescriptor ? [`created PHub profile descriptor: ${opts.profileDescriptor}`] : []),
262
+ '',
263
+ 'next:',
264
+ ...next.map((line, i) => ` ${i + 1}. ${line}`),
265
+ '',
266
+ ].join('\n'));
267
+ }
268
+ return 0;
269
+ }
270
+ export async function runPhubCommand(argv, deps = {}) {
271
+ const sub = argv[0];
272
+ if (sub === 'init') {
273
+ return runPhubInit(argv.slice(1), deps);
274
+ }
275
+ if (sub === 'doctor' || sub === 'status') {
276
+ return runDoctor(['--private-runtime', ...argv.slice(1)], { ...deps, label: `evolver phub ${sub}` });
277
+ }
278
+ if (sub === undefined || sub === '--help' || sub === '-h') {
279
+ process.stdout.write(USAGE);
280
+ return 0;
281
+ }
282
+ process.stderr.write(USAGE);
283
+ return 1;
284
+ }
@@ -0,0 +1,26 @@
1
+ import { assetstore, events, ops } from '@evomap/evolver-core';
2
+ import { type NormalizedTurn } from '@evomap/evolver-runtime-adapters';
3
+ export interface RecallCliDeps {
4
+ store?: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>;
5
+ readFile?: (path: string) => string;
6
+ /** Test seam: parse a transcript file's content into turns. Default uses the runtime-adapter for the path. */
7
+ parseTranscript?: (path: string, content: string) => NormalizedTurn[];
8
+ /** Test seam: read root_events (for --from-inject). Default reads the real root_events log. */
9
+ readEvents?: (eventsPath?: string) => events.ReportEvent[];
10
+ log?: (line: string) => void;
11
+ err?: (line: string) => void;
12
+ }
13
+ /** Claude Code names a transcript `<session_id>.jsonl`, so the basename (minus extension) is the session id used to
14
+ * match the inject event that produced THIS session (#205). Other runtimes' names simply won't match any stamped
15
+ * sessionId, and the caller falls back to the most-recent inject — safe, never wrong, just less precise. */
16
+ export declare function sessionIdFromTranscript(p: string): string | undefined;
17
+ /** Pick the `value.inject` event for this run: the latest (max seq) one STAMPED with `sessionId` when that matches
18
+ * the transcript's session (#205 precise tie), else the latest inject overall (back-compat for un-stamped events
19
+ * and runtimes with no session id). Returns undefined when there is no inject event at all. */
20
+ export declare function pickInjectEvent(evts: readonly events.ReportEvent[], sessionId?: string): events.ReportEvent | undefined;
21
+ export declare function geneIdsOf(e: events.ReportEvent | undefined): string[];
22
+ export declare function geneFromAsset(a: assetstore.AssetRecord): ops.GeneRecallInput;
23
+ export declare function resolveGene(store: Pick<assetstore.AssetStoreProvider, 'get' | 'list'>, id: string): Promise<assetstore.AssetRecord | null>;
24
+ export declare function runRecall(argv: readonly string[], deps?: RecallCliDeps): Promise<number>;
25
+ /** Registry-shaped handler (argv -> exit code). */
26
+ export declare const runRecallCommand: (argv: string[]) => Promise<number>;