self-evolving-workflow 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +27 -0
- package/README.md +90 -2
- package/dist/agent-memory-prompts.d.ts +13 -0
- package/dist/agent-memory-prompts.js +55 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +6 -0
- package/dist/closeout.d.ts +105 -0
- package/dist/closeout.js +479 -0
- package/dist/code.d.ts +39 -0
- package/dist/code.js +124 -0
- package/dist/common.d.ts +9 -0
- package/dist/common.js +42 -0
- package/dist/context-envelope.d.ts +59 -0
- package/dist/context-envelope.js +23 -0
- package/dist/host-adapters.d.ts +34 -0
- package/dist/host-adapters.js +151 -0
- package/dist/http.d.ts +3 -0
- package/dist/http.js +90 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.js +13 -0
- package/dist/knowledge-cli.d.ts +183 -0
- package/dist/knowledge-cli.js +654 -0
- package/dist/knowledge-reads.d.ts +71 -0
- package/dist/knowledge-reads.js +193 -0
- package/dist/memory.d.ts +97 -0
- package/dist/memory.js +250 -0
- package/dist/retrospective.d.ts +57 -0
- package/dist/retrospective.js +248 -0
- package/dist/search.d.ts +36 -0
- package/dist/search.js +112 -0
- package/dist/skill-addition.d.ts +25 -0
- package/dist/skill-addition.js +89 -0
- package/dist/skill-design.d.ts +96 -0
- package/dist/skill-design.js +226 -0
- package/dist/skill-replay.d.ts +55 -0
- package/dist/skill-replay.js +451 -0
- package/dist/skill-route.d.ts +30 -0
- package/dist/skill-route.js +75 -0
- package/dist/transcript-evidence.d.ts +3 -0
- package/dist/transcript-evidence.js +58 -0
- package/dist/upstream/chunker.d.ts +24 -0
- package/dist/upstream/chunker.js +96 -0
- package/dist/upstream/file-protocol.d.ts +45 -0
- package/dist/upstream/file-protocol.js +117 -0
- package/dist/upstream/frontmatter.d.ts +47 -0
- package/dist/upstream/frontmatter.js +86 -0
- package/dist/upstream/graph-search.d.ts +33 -0
- package/dist/upstream/graph-search.js +67 -0
- package/dist/upstream/l1-extraction.d.ts +26 -0
- package/dist/upstream/l1-extraction.js +405 -0
- package/dist/upstream/llm.d.ts +8 -0
- package/dist/upstream/llm.js +1 -0
- package/dist/upstream/merge.d.ts +50 -0
- package/dist/upstream/merge.js +153 -0
- package/dist/upstream/prompts.d.ts +53 -0
- package/dist/upstream/prompts.js +185 -0
- package/dist/upstream/search-utils.d.ts +34 -0
- package/dist/upstream/search-utils.js +55 -0
- package/dist/upstream/slug.d.ts +26 -0
- package/dist/upstream/slug.js +103 -0
- package/dist/upstream/template.d.ts +29 -0
- package/dist/upstream/template.js +80 -0
- package/dist/upstream/tokenize.d.ts +4 -0
- package/dist/upstream/tokenize.js +29 -0
- package/dist/wiki-change.d.ts +76 -0
- package/dist/wiki-change.js +299 -0
- package/dist/wiki-entry.d.ts +26 -0
- package/dist/wiki-entry.js +93 -0
- package/dist/wiki-ingest.d.ts +12 -0
- package/dist/wiki-ingest.js +126 -0
- package/dist/wiki-migration.d.ts +16 -0
- package/dist/wiki-migration.js +268 -0
- package/dist/wiki-tokens.d.ts +1 -0
- package/dist/wiki-tokens.js +46 -0
- package/dist/wiki.d.ts +103 -0
- package/dist/wiki.js +330 -0
- package/dist/workflow-cli.d.ts +2 -0
- package/dist/workflow-cli.js +258 -0
- package/dist/workflow-install.d.ts +36 -0
- package/dist/workflow-install.js +148 -0
- package/dist/workflow-knowledge.d.ts +16 -0
- package/dist/workflow-knowledge.js +24 -0
- package/dist/workflow-mcp.d.ts +2 -0
- package/dist/workflow-mcp.js +144 -0
- package/dist/workflow-names.d.ts +4 -0
- package/dist/workflow-names.js +18 -0
- package/dist/workflow-runtime.d.ts +622 -0
- package/dist/workflow-runtime.js +627 -0
- package/dist/workflow-skills.d.ts +48 -0
- package/dist/workflow-skills.js +141 -0
- package/package.json +76 -4
- package/skills/ew-odyssey/SKILL.md +237 -0
- package/skills/ew-odyssey/references/audit-artifacts.md +7 -0
- package/skills/ew-odyssey/references/odyssey-base-codex.md +3 -0
- package/skills/ew-odyssey/references/odyssey-base.md +278 -0
- package/skills/ew-odyssey/references/odyssey-debug.codex.md +305 -0
- package/skills/ew-odyssey/references/odyssey-debug.md +283 -0
- package/skills/ew-odyssey/references/odyssey-defensive.codex.md +395 -0
- package/skills/ew-odyssey/references/odyssey-defensive.md +369 -0
- package/skills/ew-odyssey/references/odyssey-improve.codex.md +270 -0
- package/skills/ew-odyssey/references/odyssey-improve.md +248 -0
- package/skills/ew-odyssey/references/odyssey-planex.codex.md +352 -0
- package/skills/ew-odyssey/references/odyssey-planex.md +312 -0
- package/skills/ew-odyssey/references/odyssey-review.codex.md +283 -0
- package/skills/ew-odyssey/references/odyssey-review.md +251 -0
- package/skills/ew-odyssey/references/odyssey-security.md +249 -0
- package/skills/ew-odyssey/references/odyssey-ui.codex.md +294 -0
- package/skills/ew-odyssey/references/odyssey-ui.md +250 -0
- package/skills/ew-odyssey/references/prepare/odyssey-debug.md +105 -0
- package/skills/ew-odyssey/references/prepare/odyssey-defensive.md +121 -0
- package/skills/ew-odyssey/references/prepare/odyssey-improve.md +93 -0
- package/skills/ew-odyssey/references/prepare/odyssey-planex.md +104 -0
- package/skills/ew-odyssey/references/prepare/odyssey-review.md +98 -0
- package/skills/ew-odyssey/references/prepare/odyssey-security.md +94 -0
- package/skills/ew-odyssey/references/prepare/odyssey-ui.md +87 -0
- package/skills/ew-orchestrate/SKILL.md +236 -0
- package/skills/ew-orchestrate/references/auto-policy.md +165 -0
- package/skills/ew-orchestrate/references/companion-route.md +52 -0
- package/skills/ew-orchestrate/references/ew-orchestrate.md +27 -0
- package/skills/ew-orchestrate/references/goal.md +53 -0
- package/skills/ew-orchestrate/references/knowledge-route.md +163 -0
- package/skills/ew-orchestrate/references/orchestrator-run-loop.md +36 -0
- package/skills/ew-orchestrate/references/planning.md +137 -0
- package/skills/ew-orchestrate/steps/ew-analyze/SKILL.md +62 -0
- package/skills/ew-orchestrate/steps/ew-analyze/references/boundary-grill.md +50 -0
- package/skills/ew-orchestrate/steps/ew-analyze/references/issue-gaps-analyze.md +59 -0
- package/skills/ew-orchestrate/steps/ew-analyze/references/prepare.md +42 -0
- package/skills/ew-orchestrate/steps/ew-analyze/references/workflow.md +401 -0
- package/skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md +32 -0
- package/skills/ew-orchestrate/steps/ew-companion/SKILL.md +9 -0
- package/skills/ew-orchestrate/steps/ew-execute/SKILL.md +71 -0
- package/skills/ew-orchestrate/steps/ew-execute/references/prepare.md +69 -0
- package/skills/ew-orchestrate/steps/ew-execute/references/workflow.md +373 -0
- package/skills/ew-orchestrate/steps/ew-plan/SKILL.md +102 -0
- package/skills/ew-orchestrate/steps/ew-plan/references/boundary-grill.md +50 -0
- package/skills/ew-orchestrate/steps/ew-plan/references/prepare.md +51 -0
- package/skills/ew-orchestrate/steps/ew-plan/references/tdd.md +53 -0
- package/skills/ew-orchestrate/steps/ew-plan/references/workflow.md +278 -0
- package/skills/ew-orchestrate/steps/ew-review/SKILL.md +44 -0
- package/skills/ew-orchestrate/steps/ew-review/references/odyssey-base-codex.md +3 -0
- package/skills/ew-orchestrate/steps/ew-review/references/prepare.md +76 -0
- package/skills/ew-orchestrate/steps/ew-review/references/workflow.md +283 -0
- package/skills/ew-skill-design/SKILL.md +28 -0
- package/skills/ew-skill-design/references/package-contract.md +28 -0
- package/skills/ew-skill-design/references/validation.md +7 -0
- package/skills/team-swarm/SKILL.md +231 -0
- package/skills/team-swarm/references/mcp-coordination.md +10 -0
- package/skills/team-swarm/roles/analyst/role.md +181 -0
- package/skills/team-swarm/roles/ant/role.md +149 -0
- package/skills/team-swarm/roles/coordinator/commands/converge.md +154 -0
- package/skills/team-swarm/roles/coordinator/commands/init-swarm.md +134 -0
- package/skills/team-swarm/roles/coordinator/commands/iterate.md +202 -0
- package/skills/team-swarm/roles/coordinator/role.md +228 -0
- package/skills/team-swarm/roles/scorer/role.md +150 -0
- package/skills/team-swarm/scripts/aco.py +646 -0
- package/skills/team-swarm/scripts/pheromone.py +144 -0
- package/skills/team-swarm/scripts/scoring.py +111 -0
- package/skills/team-swarm/scripts/test_aco.py +606 -0
- package/skills/team-swarm/specs/ant-output-schema.md +127 -0
- package/skills/team-swarm/specs/convergence-criteria.md +108 -0
- package/skills/team-swarm/specs/pheromone-schema.md +125 -0
- package/skills/team-swarm/specs/swarm-config-template.json +71 -0
- package/skills/team-swarm/specs/swarm-protocol.md +123 -0
- package/skills/workflow-closeout/SKILL.md +10 -0
- package/skills/workflow-evolve/SKILL.md +79 -0
- package/skills/workflow-evolve/references/agy-gate.md +27 -0
- package/skills/workflow-evolve/references/auto-loop.md +20 -0
- package/skills/workflow-evolve/references/history-review.md +14 -0
- package/skills/workflow-evolve/scripts/codex-memory-replay.mjs +76 -0
- package/skills/workflow-evolve/scripts/codex-replay.mjs +1 -0
- package/skills/workflow-evolve/scripts/evolve-loop.mjs +259 -0
- package/skills/workflow-evolve/scripts/memory-codex-mcp.mjs +124 -0
- package/workflows/index.json +23 -0
|
@@ -0,0 +1,451 @@
|
|
|
1
|
+
import { execFileSync } from 'node:child_process';
|
|
2
|
+
import { createHash } from 'node:crypto';
|
|
3
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, rmdirSync, writeFileSync } from 'node:fs';
|
|
4
|
+
import { tmpdir } from 'node:os';
|
|
5
|
+
import { dirname, join, relative, resolve } from 'node:path';
|
|
6
|
+
import { InputError, requireText } from './common.js';
|
|
7
|
+
import { draftSkillAddition, learningDocument, learningIndex } from './skill-addition.js';
|
|
8
|
+
import { validateKnowledgeReads } from './knowledge-reads.js';
|
|
9
|
+
const sha256 = (value) => createHash('sha256').update(value).digest('hex');
|
|
10
|
+
function git(root, args, options = {}) {
|
|
11
|
+
return execFileSync('git', args, { cwd: root, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'], ...options });
|
|
12
|
+
}
|
|
13
|
+
function gitText(root, args, options) {
|
|
14
|
+
return git(root, args, options).toString('utf8').trimEnd();
|
|
15
|
+
}
|
|
16
|
+
function repoPath(root, path) {
|
|
17
|
+
const name = relative(root, resolve(root, path)).replaceAll('\\', '/');
|
|
18
|
+
if (!name || name.startsWith('../') || name === '..' || /[:\u0000-\u001f]/.test(name)) {
|
|
19
|
+
throw new InputError(`Skill path is outside the project: ${path}`);
|
|
20
|
+
}
|
|
21
|
+
return name;
|
|
22
|
+
}
|
|
23
|
+
function record(value) {
|
|
24
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
25
|
+
throw new InputError('Expected a JSON object');
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function loadDraft(root, data) {
|
|
29
|
+
const draft = record(data);
|
|
30
|
+
const baseline = record(draft.baseline);
|
|
31
|
+
if (draft.priority !== 'high' && draft.priority !== 'normal' && draft.priority !== 'low') {
|
|
32
|
+
throw new InputError('Invalid Skill draft priority');
|
|
33
|
+
}
|
|
34
|
+
if (!Array.isArray(draft.sources))
|
|
35
|
+
throw new InputError('Skill draft is missing its evidence sources');
|
|
36
|
+
const entry = realpathSync(resolve(root, requireText(baseline.path, 'Skill entry')));
|
|
37
|
+
const entryPath = repoPath(root, entry);
|
|
38
|
+
if (!entryPath.endsWith('/SKILL.md'))
|
|
39
|
+
throw new InputError('Expected a project Skill package entry');
|
|
40
|
+
const regenerated = draftSkillAddition({
|
|
41
|
+
entry, priority: draft.priority, instruction: requireText(draft.instruction, 'Skill instruction'),
|
|
42
|
+
sources: draft.sources.map(source => requireText(source, 'evidence reference')),
|
|
43
|
+
when: draft.when === undefined ? undefined : requireText(draft.when, 'learning trigger'),
|
|
44
|
+
});
|
|
45
|
+
const sameChanges = JSON.stringify(regenerated.changes) === JSON.stringify(draft.changes);
|
|
46
|
+
// 旧草稿可能只包含参考文档,回放时补齐入口与索引。
|
|
47
|
+
const legacyLowChanges = regenerated.priority === 'low' && JSON.stringify(draft.changes) === JSON.stringify(regenerated.changes.filter(change => change.path === resolve(dirname(entry), learningDocument(regenerated.id))));
|
|
48
|
+
if (regenerated.id !== draft.id || regenerated.baseline.sha256 !== baseline.sha256 || (!sameChanges && !legacyLowChanges)) {
|
|
49
|
+
throw new InputError('Skill draft or its baseline changed');
|
|
50
|
+
}
|
|
51
|
+
return { draft: regenerated, entryPath };
|
|
52
|
+
}
|
|
53
|
+
function packagePathForSkill(skillId) {
|
|
54
|
+
if (!/^[a-z0-9][a-z0-9-]*$/i.test(skillId))
|
|
55
|
+
throw new InputError('Invalid Skill ID for package design');
|
|
56
|
+
return `skills/${skillId}`;
|
|
57
|
+
}
|
|
58
|
+
function markdownLinks(content) {
|
|
59
|
+
const links = [];
|
|
60
|
+
for (const match of content.matchAll(/\[[^\]]*\]\(([^)]+)\)/g)) {
|
|
61
|
+
const target = match[1].trim().replace(/^<|>$/g, '').split(/\s+/, 1)[0];
|
|
62
|
+
if (!target || target.startsWith('#') || /^[a-z][a-z0-9+.-]*:/i.test(target))
|
|
63
|
+
continue;
|
|
64
|
+
links.push(target.split('#', 1)[0]);
|
|
65
|
+
}
|
|
66
|
+
return links.filter(Boolean);
|
|
67
|
+
}
|
|
68
|
+
function loadPackageDraft(root, data) {
|
|
69
|
+
const draft = record(data);
|
|
70
|
+
if (draft.mode !== 'package')
|
|
71
|
+
throw new InputError('Expected a multi-file Skill package draft');
|
|
72
|
+
const skillId = requireText(draft.skill_id, 'Skill package ID');
|
|
73
|
+
const packagePath = packagePathForSkill(skillId);
|
|
74
|
+
const entryPath = `${packagePath}/SKILL.md`;
|
|
75
|
+
if (draft.package_path !== packagePath || draft.entry !== entryPath) {
|
|
76
|
+
throw new InputError('Skill package target does not match its Skill ID');
|
|
77
|
+
}
|
|
78
|
+
if (!Array.isArray(draft.changes) || !draft.changes.length) {
|
|
79
|
+
throw new InputError('Skill package draft requires at least one file');
|
|
80
|
+
}
|
|
81
|
+
const changes = draft.changes.map((value, index) => {
|
|
82
|
+
const change = record(value);
|
|
83
|
+
const path = repoPath(root, requireText(change.path, `Skill package file ${index}`));
|
|
84
|
+
if (!path.startsWith(`${packagePath}/`))
|
|
85
|
+
throw new InputError(`Skill package file is outside the package: ${path}`);
|
|
86
|
+
const content = change.content;
|
|
87
|
+
if (typeof content !== 'string')
|
|
88
|
+
throw new InputError(`Skill package file content is invalid: ${path}`);
|
|
89
|
+
return { path, content };
|
|
90
|
+
});
|
|
91
|
+
if (new Set(changes.map(change => change.path)).size !== changes.length) {
|
|
92
|
+
throw new InputError('Skill package draft contains duplicate files');
|
|
93
|
+
}
|
|
94
|
+
const entry = changes.find(change => change.path === entryPath);
|
|
95
|
+
if (!entry)
|
|
96
|
+
throw new InputError(`Skill package draft must include ${entryPath}`);
|
|
97
|
+
const changed = new Map(changes.map(change => [change.path, change.content]));
|
|
98
|
+
for (const link of markdownLinks(entry.content)) {
|
|
99
|
+
const path = repoPath(root, resolve(root, dirname(entryPath), link));
|
|
100
|
+
if (!path.startsWith(`${packagePath}/`))
|
|
101
|
+
throw new InputError(`Skill Markdown link leaves the package: ${link}`);
|
|
102
|
+
if (!changed.has(path) && !existsSync(resolve(root, path))) {
|
|
103
|
+
throw new InputError(`Skill Markdown link has no package document: ${link}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
return { draft, skillId, packagePath, entryPath, changes };
|
|
107
|
+
}
|
|
108
|
+
function loadScenarios(data) {
|
|
109
|
+
if (!Array.isArray(data) || data.length < 2)
|
|
110
|
+
throw new InputError('Provide a failure replay and a passing regression scenario');
|
|
111
|
+
const ids = new Set();
|
|
112
|
+
const scenarios = data.map(value => {
|
|
113
|
+
const scenario = record(value);
|
|
114
|
+
const id = requireText(scenario.id, 'scenario ID');
|
|
115
|
+
if (ids.has(id) || typeof scenario.baseline !== 'boolean' || !('input' in scenario)) {
|
|
116
|
+
throw new InputError(`Invalid or duplicate replay scenario: ${id}`);
|
|
117
|
+
}
|
|
118
|
+
ids.add(id);
|
|
119
|
+
let knowledgeReads;
|
|
120
|
+
if (scenario.knowledge_reads !== undefined) {
|
|
121
|
+
const expected = record(scenario.knowledge_reads);
|
|
122
|
+
const sources = expected.searched_sources;
|
|
123
|
+
const ids = expected.loaded_ids;
|
|
124
|
+
const constraints = expected.bound_constraints;
|
|
125
|
+
if ((sources !== undefined && (!Array.isArray(sources) || sources.some(item => typeof item !== 'string'))) ||
|
|
126
|
+
(ids !== undefined && (!Array.isArray(ids) || ids.some(item => typeof item !== 'string'))) ||
|
|
127
|
+
(constraints !== undefined && (!Array.isArray(constraints) || constraints.some(item => typeof item !== 'string')))) {
|
|
128
|
+
throw new InputError(`Invalid knowledge read expectations: ${id}`);
|
|
129
|
+
}
|
|
130
|
+
knowledgeReads = {
|
|
131
|
+
...(sources === undefined ? {} : { searchedSources: [...new Set(sources)] }),
|
|
132
|
+
...(ids === undefined ? {} : { loadedIds: [...new Set(ids)] }),
|
|
133
|
+
...(constraints === undefined ? {} : { boundConstraints: [...new Set(constraints)] }),
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
return { id, input: scenario.input, baseline: scenario.baseline, knowledgeReads };
|
|
137
|
+
});
|
|
138
|
+
if (!scenarios.some(item => item.baseline) || !scenarios.some(item => !item.baseline)) {
|
|
139
|
+
throw new InputError('Replay requires both a baseline failure and a baseline pass');
|
|
140
|
+
}
|
|
141
|
+
return scenarios;
|
|
142
|
+
}
|
|
143
|
+
function runScenario(worktree, commit, runner, entry, scenario) {
|
|
144
|
+
const output = execFileSync(process.execPath, [runner], {
|
|
145
|
+
cwd: worktree,
|
|
146
|
+
windowsHide: true,
|
|
147
|
+
input: JSON.stringify({ id: scenario.id, input: scenario.input, entry, commit }),
|
|
148
|
+
encoding: 'utf8',
|
|
149
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
150
|
+
timeout: 120_000,
|
|
151
|
+
});
|
|
152
|
+
const proof = record(JSON.parse(output));
|
|
153
|
+
if (typeof proof.passed !== 'boolean' || !Array.isArray(proof.loaded)) {
|
|
154
|
+
throw new InputError(`Replay runner omitted its result or loaded files: ${scenario.id}`);
|
|
155
|
+
}
|
|
156
|
+
const packageRoot = dirname(entry).replaceAll('\\', '/') + '/';
|
|
157
|
+
const loaded = proof.loaded.map(value => {
|
|
158
|
+
const item = record(value);
|
|
159
|
+
const path = repoPath(worktree, requireText(item.path, 'loaded file'));
|
|
160
|
+
if (!path.startsWith(packageRoot))
|
|
161
|
+
throw new InputError(`Replay loaded a file outside the selected Skill: ${path}`);
|
|
162
|
+
const expected = sha256(git(worktree, ['show', `${commit}:${path}`]));
|
|
163
|
+
if (expected !== item.sha256)
|
|
164
|
+
throw new InputError(`Replay loaded different Skill bytes: ${path}`);
|
|
165
|
+
return { path, sha256: expected };
|
|
166
|
+
});
|
|
167
|
+
if (!loaded.some(item => item.path === entry))
|
|
168
|
+
throw new InputError(`Replay did not load the selected Skill: ${entry}`);
|
|
169
|
+
const knowledgeReads = proof.knowledge_reads === undefined ? undefined : validateKnowledgeReads(proof.knowledge_reads);
|
|
170
|
+
return { passed: proof.passed, loaded, ...(knowledgeReads ? { knowledgeReads } : {}) };
|
|
171
|
+
}
|
|
172
|
+
function runPackageScenario(worktree, commit, runner, entry, packagePath, scenario, requireEntry) {
|
|
173
|
+
const output = execFileSync(process.execPath, [runner], {
|
|
174
|
+
cwd: worktree,
|
|
175
|
+
windowsHide: true,
|
|
176
|
+
input: JSON.stringify({ id: scenario.id, input: scenario.input, entry, package_path: packagePath, commit, mode: 'package' }),
|
|
177
|
+
encoding: 'utf8',
|
|
178
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
179
|
+
timeout: 120_000,
|
|
180
|
+
});
|
|
181
|
+
const proof = record(JSON.parse(output));
|
|
182
|
+
if (typeof proof.passed !== 'boolean' || !Array.isArray(proof.loaded)) {
|
|
183
|
+
throw new InputError(`Replay runner omitted its result or loaded files: ${scenario.id}`);
|
|
184
|
+
}
|
|
185
|
+
const loaded = proof.loaded.map(value => {
|
|
186
|
+
const item = record(value);
|
|
187
|
+
const path = repoPath(worktree, requireText(item.path, 'loaded file'));
|
|
188
|
+
if (!path.startsWith(`${packagePath}/`))
|
|
189
|
+
throw new InputError(`Replay loaded a file outside the selected Skill: ${path}`);
|
|
190
|
+
const expected = sha256(git(worktree, ['show', `${commit}:${path}`]));
|
|
191
|
+
if (expected !== item.sha256)
|
|
192
|
+
throw new InputError(`Replay loaded different Skill bytes: ${path}`);
|
|
193
|
+
return { path, sha256: expected };
|
|
194
|
+
});
|
|
195
|
+
if (requireEntry && !loaded.some(item => item.path === entry)) {
|
|
196
|
+
throw new InputError(`Replay did not load the selected Skill: ${entry}`);
|
|
197
|
+
}
|
|
198
|
+
const knowledgeReads = proof.knowledge_reads === undefined ? undefined : validateKnowledgeReads(proof.knowledge_reads);
|
|
199
|
+
return { passed: proof.passed, loaded, ...(knowledgeReads ? { knowledgeReads } : {}) };
|
|
200
|
+
}
|
|
201
|
+
function assertKnowledgeReads(observation, expected, scenario) {
|
|
202
|
+
if (!expected)
|
|
203
|
+
return;
|
|
204
|
+
const receipt = observation.knowledgeReads;
|
|
205
|
+
if (!receipt)
|
|
206
|
+
throw new InputError(`Replay omitted knowledge reads: ${scenario}`);
|
|
207
|
+
if (expected.searchedSources?.some(source => !receipt.searches.some(search => search.source === source))) {
|
|
208
|
+
throw new InputError(`Replay omitted expected knowledge search: ${scenario}`);
|
|
209
|
+
}
|
|
210
|
+
if (expected.loadedIds?.some(id => !receipt.reads.some(read => read.id === id))) {
|
|
211
|
+
throw new InputError(`Replay omitted expected knowledge read: ${scenario}`);
|
|
212
|
+
}
|
|
213
|
+
if (expected.boundConstraints?.some(id => !receipt.constraints_bound.some(constraint => constraint.knowledge_id === id))) {
|
|
214
|
+
throw new InputError(`Replay omitted expected bound constraint: ${scenario}`);
|
|
215
|
+
}
|
|
216
|
+
for (const read of receipt.reads) {
|
|
217
|
+
if (!read.from_search_id || read.from_search_id === 'priors')
|
|
218
|
+
continue;
|
|
219
|
+
const search = receipt.searches.find(item => item.search_id === read.from_search_id);
|
|
220
|
+
if (!search || !search.returned_ids.includes(read.id)) {
|
|
221
|
+
throw new InputError(`Replay knowledge read is not backed by its search result: ${scenario}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function repoRoot(root) {
|
|
226
|
+
return realpathSync(gitText(root, ['rev-parse', '--show-toplevel']));
|
|
227
|
+
}
|
|
228
|
+
function receiptPath(root, id) {
|
|
229
|
+
if (!/^[a-f0-9]{64}$/.test(id))
|
|
230
|
+
throw new InputError('Expected an exact Skill replay receipt ID');
|
|
231
|
+
return join(gitText(root, ['rev-parse', '--absolute-git-dir']), 'evolve-replay', id + '.json');
|
|
232
|
+
}
|
|
233
|
+
export function replaySkillAddition(root, data, options) {
|
|
234
|
+
root = repoRoot(root);
|
|
235
|
+
const { draft, entryPath } = loadDraft(root, data);
|
|
236
|
+
const runner = realpathSync(options.runner);
|
|
237
|
+
const runnerSha256 = sha256(readFileSync(runner));
|
|
238
|
+
const scenarios = loadScenarios(options.scenarios);
|
|
239
|
+
const base = gitText(root, ['rev-parse', 'HEAD']);
|
|
240
|
+
const baseline = git(root, ['show', `${base}:${entryPath}`]).toString('utf8');
|
|
241
|
+
const normalizedBaseline = baseline.replace(/^\uFEFF/, '');
|
|
242
|
+
if (sha256(baseline) !== draft.baseline.sha256 &&
|
|
243
|
+
sha256(normalizedBaseline) !== draft.baseline.sha256 &&
|
|
244
|
+
sha256(normalizedBaseline.replace(/\r?\n/g, '\r\n')) !== draft.baseline.sha256 &&
|
|
245
|
+
sha256(normalizedBaseline.replace(/\r\n/g, '\n')) !== draft.baseline.sha256) {
|
|
246
|
+
throw new InputError('Commit the Skill baseline before replay');
|
|
247
|
+
}
|
|
248
|
+
const packagePath = dirname(entryPath).replaceAll('\\', '/');
|
|
249
|
+
if (gitText(root, ['status', '--porcelain', '--untracked-files=all', '--', packagePath])) {
|
|
250
|
+
throw new InputError('Commit the Skill package before replay');
|
|
251
|
+
}
|
|
252
|
+
const scratch = mkdtempSync(join(tmpdir(), 'evolve-replay-'));
|
|
253
|
+
const index = join(scratch, 'index');
|
|
254
|
+
const gitIndex = { env: { ...process.env, GIT_INDEX_FILE: index } };
|
|
255
|
+
const oldTree = join(scratch, 'baseline');
|
|
256
|
+
const newTree = join(scratch, 'candidate');
|
|
257
|
+
let oldAdded = false;
|
|
258
|
+
let newAdded = false;
|
|
259
|
+
let failure;
|
|
260
|
+
try {
|
|
261
|
+
git(root, ['read-tree', base], gitIndex);
|
|
262
|
+
const files = draft.changes.map(change => {
|
|
263
|
+
const path = repoPath(root, change.path);
|
|
264
|
+
const blob = gitText(root, ['hash-object', '-w', '--stdin'], { input: change.content.replace(/\r\n/g, '\n') });
|
|
265
|
+
git(root, ['update-index', '--add', '--cacheinfo', `100644,${blob},${path}`], gitIndex);
|
|
266
|
+
return path;
|
|
267
|
+
});
|
|
268
|
+
const tree = gitText(root, ['write-tree'], gitIndex);
|
|
269
|
+
const candidate = gitText(root, ['commit-tree', tree, '-p', base, '-m', 'chore: 生成 Skill 回放候选']);
|
|
270
|
+
if (!gitText(root, ['diff', '--name-only', base, candidate]))
|
|
271
|
+
throw new InputError('Skill draft has no changes');
|
|
272
|
+
git(root, ['worktree', 'add', '--detach', oldTree, base]);
|
|
273
|
+
oldAdded = true;
|
|
274
|
+
git(root, ['worktree', 'add', '--detach', newTree, candidate]);
|
|
275
|
+
newAdded = true;
|
|
276
|
+
const expectedReads = draft.priority === 'high' ? [entryPath] : [`${packagePath}/${learningDocument(draft.id)}`];
|
|
277
|
+
if (draft.priority === 'low')
|
|
278
|
+
expectedReads.push(`${packagePath}/${learningIndex}`);
|
|
279
|
+
const observations = scenarios.map(scenario => {
|
|
280
|
+
const baseline = runScenario(oldTree, base, runner, entryPath, scenario);
|
|
281
|
+
const proposed = runScenario(newTree, candidate, runner, entryPath, scenario);
|
|
282
|
+
if (baseline.passed !== scenario.baseline || !proposed.passed ||
|
|
283
|
+
(!scenario.baseline && !expectedReads.every(path => proposed.loaded.some(item => item.path === path)))) {
|
|
284
|
+
throw new InputError(`Skill replay failed: ${scenario.id}`);
|
|
285
|
+
}
|
|
286
|
+
assertKnowledgeReads(proposed, scenario.knowledgeReads, scenario.id);
|
|
287
|
+
return { id: scenario.id, inputSha256: sha256(JSON.stringify(scenario.input)), baseline, candidate: proposed };
|
|
288
|
+
});
|
|
289
|
+
if (sha256(readFileSync(runner)) !== runnerSha256)
|
|
290
|
+
throw new InputError('Replay runner changed during validation');
|
|
291
|
+
const receipt = { base, candidate, entry: entryPath, files, sources: draft.sources, runnerSha256, scenarios: observations };
|
|
292
|
+
const content = JSON.stringify(receipt);
|
|
293
|
+
const id = sha256(content);
|
|
294
|
+
const path = receiptPath(root, id);
|
|
295
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
296
|
+
git(root, ['update-ref', 'refs/evolve/replays/' + id, candidate]);
|
|
297
|
+
if (!existsSync(path))
|
|
298
|
+
writeFileSync(path, content, { flag: 'wx' });
|
|
299
|
+
else if (readFileSync(path, 'utf8') !== content)
|
|
300
|
+
throw new InputError('Skill replay receipt differs');
|
|
301
|
+
return { id, ...receipt };
|
|
302
|
+
}
|
|
303
|
+
catch (error) {
|
|
304
|
+
failure = error;
|
|
305
|
+
throw error;
|
|
306
|
+
}
|
|
307
|
+
finally {
|
|
308
|
+
const cleanup = [
|
|
309
|
+
...(newAdded ? [() => git(root, ['worktree', 'remove', '--force', newTree])] : []),
|
|
310
|
+
...(oldAdded ? [() => git(root, ['worktree', 'remove', '--force', oldTree])] : []),
|
|
311
|
+
() => rmSync(index, { force: true }),
|
|
312
|
+
() => rmdirSync(scratch),
|
|
313
|
+
];
|
|
314
|
+
const errors = [];
|
|
315
|
+
for (const remove of cleanup) {
|
|
316
|
+
try {
|
|
317
|
+
remove();
|
|
318
|
+
}
|
|
319
|
+
catch (error) {
|
|
320
|
+
errors.push(String(error));
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
if (errors.length) {
|
|
324
|
+
throw new Error([...(failure ? [String(failure)] : []), ...errors].join('\n'), { cause: failure });
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
}
|
|
328
|
+
export function replaySkillPackage(root, data, options) {
|
|
329
|
+
root = repoRoot(root);
|
|
330
|
+
const { draft, packagePath, entryPath, changes } = loadPackageDraft(root, data);
|
|
331
|
+
const runner = realpathSync(options.runner);
|
|
332
|
+
const runnerSha256 = sha256(readFileSync(runner));
|
|
333
|
+
const scenarios = loadScenarios(options.scenarios);
|
|
334
|
+
const base = gitText(root, ['rev-parse', 'HEAD']);
|
|
335
|
+
if (gitText(root, ['status', '--porcelain', '--untracked-files=all', '--', packagePath])) {
|
|
336
|
+
throw new InputError('Commit the Skill package before replay');
|
|
337
|
+
}
|
|
338
|
+
let entryExists = true;
|
|
339
|
+
try {
|
|
340
|
+
git(root, ['cat-file', '-e', `${base}:${entryPath}`]);
|
|
341
|
+
}
|
|
342
|
+
catch {
|
|
343
|
+
entryExists = false;
|
|
344
|
+
}
|
|
345
|
+
const scratch = mkdtempSync(join(tmpdir(), 'evolve-replay-'));
|
|
346
|
+
const index = join(scratch, 'index');
|
|
347
|
+
const gitIndex = { env: { ...process.env, GIT_INDEX_FILE: index } };
|
|
348
|
+
const oldTree = join(scratch, 'baseline');
|
|
349
|
+
const newTree = join(scratch, 'candidate');
|
|
350
|
+
let oldAdded = false;
|
|
351
|
+
let newAdded = false;
|
|
352
|
+
let failure;
|
|
353
|
+
try {
|
|
354
|
+
git(root, ['read-tree', base], gitIndex);
|
|
355
|
+
for (const change of changes) {
|
|
356
|
+
const blob = gitText(root, ['hash-object', '-w', '--stdin'], { input: change.content.replace(/\r\n/g, '\n') });
|
|
357
|
+
git(root, ['update-index', '--add', '--cacheinfo', `100644,${blob},${change.path}`], gitIndex);
|
|
358
|
+
}
|
|
359
|
+
const tree = gitText(root, ['write-tree'], gitIndex);
|
|
360
|
+
const candidate = gitText(root, ['commit-tree', tree, '-p', base, '-m', 'chore: 生成 Skill 包回放候选']);
|
|
361
|
+
if (!gitText(root, ['diff', '--name-only', base, candidate]))
|
|
362
|
+
throw new InputError('Skill package draft has no changes');
|
|
363
|
+
git(root, ['worktree', 'add', '--detach', oldTree, base]);
|
|
364
|
+
oldAdded = true;
|
|
365
|
+
git(root, ['worktree', 'add', '--detach', newTree, candidate]);
|
|
366
|
+
newAdded = true;
|
|
367
|
+
const observations = scenarios.map(scenario => {
|
|
368
|
+
const baseline = runPackageScenario(oldTree, base, runner, entryPath, packagePath, scenario, entryExists);
|
|
369
|
+
const proposed = runPackageScenario(newTree, candidate, runner, entryPath, packagePath, scenario, true);
|
|
370
|
+
if (baseline.passed !== scenario.baseline || !proposed.passed)
|
|
371
|
+
throw new InputError(`Skill package replay failed: ${scenario.id}`);
|
|
372
|
+
assertKnowledgeReads(proposed, scenario.knowledgeReads, scenario.id);
|
|
373
|
+
return { id: scenario.id, inputSha256: sha256(JSON.stringify(scenario.input)), baseline, candidate: proposed };
|
|
374
|
+
});
|
|
375
|
+
if (sha256(readFileSync(runner)) !== runnerSha256)
|
|
376
|
+
throw new InputError('Replay runner changed during validation');
|
|
377
|
+
const receipt = {
|
|
378
|
+
mode: 'package', base, candidate, entry: entryPath, package_path: packagePath,
|
|
379
|
+
files: changes.map(change => change.path), sources: Array.isArray(draft.sources) ? draft.sources.map(source => requireText(source, 'evidence reference')) : [],
|
|
380
|
+
runnerSha256, scenarios: observations,
|
|
381
|
+
};
|
|
382
|
+
const content = JSON.stringify(receipt);
|
|
383
|
+
const id = sha256(content);
|
|
384
|
+
const path = receiptPath(root, id);
|
|
385
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
386
|
+
git(root, ['update-ref', 'refs/evolve/replays/' + id, candidate]);
|
|
387
|
+
if (!existsSync(path))
|
|
388
|
+
writeFileSync(path, content, { flag: 'wx' });
|
|
389
|
+
else if (readFileSync(path, 'utf8') !== content)
|
|
390
|
+
throw new InputError('Skill replay receipt differs');
|
|
391
|
+
return { id, ...receipt };
|
|
392
|
+
}
|
|
393
|
+
catch (error) {
|
|
394
|
+
failure = error;
|
|
395
|
+
throw error;
|
|
396
|
+
}
|
|
397
|
+
finally {
|
|
398
|
+
const cleanup = [
|
|
399
|
+
...(newAdded ? [() => git(root, ['worktree', 'remove', '--force', newTree])] : []),
|
|
400
|
+
...(oldAdded ? [() => git(root, ['worktree', 'remove', '--force', oldTree])] : []),
|
|
401
|
+
() => rmSync(index, { force: true }),
|
|
402
|
+
() => rmdirSync(scratch),
|
|
403
|
+
];
|
|
404
|
+
const errors = [];
|
|
405
|
+
for (const remove of cleanup) {
|
|
406
|
+
try {
|
|
407
|
+
remove();
|
|
408
|
+
}
|
|
409
|
+
catch (error) {
|
|
410
|
+
errors.push(String(error));
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
if (errors.length)
|
|
414
|
+
throw new Error([...(failure ? [String(failure)] : []), ...errors].join('\n'), { cause: failure });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
export function changeSkillVersion(root, id, rollback = false) {
|
|
418
|
+
root = repoRoot(root);
|
|
419
|
+
const content = readFileSync(receiptPath(root, id), 'utf8');
|
|
420
|
+
if (sha256(content) !== id)
|
|
421
|
+
throw new InputError('Skill replay receipt changed');
|
|
422
|
+
const receipt = JSON.parse(content);
|
|
423
|
+
if (gitText(root, ['rev-parse', '--verify', 'refs/evolve/replays/' + id]) !== receipt.candidate) {
|
|
424
|
+
throw new InputError('Skill candidate no longer matches its replay receipt');
|
|
425
|
+
}
|
|
426
|
+
const head = gitText(root, ['rev-parse', 'HEAD']);
|
|
427
|
+
const changedFiles = gitText(root, ['diff', '--name-only', receipt.base, receipt.candidate]).split(/\r?\n/);
|
|
428
|
+
if (!changedFiles.length || changedFiles.some(path => !receipt.files.includes(path)) ||
|
|
429
|
+
gitText(root, ['rev-list', '--parents', '-n', '1', receipt.candidate]) !== `${receipt.candidate} ${receipt.base}`) {
|
|
430
|
+
throw new InputError('Skill candidate has unexpected changes or parent');
|
|
431
|
+
}
|
|
432
|
+
if (!rollback && head === receipt.candidate)
|
|
433
|
+
return { id, commit: head, replayed: true };
|
|
434
|
+
if (rollback && gitText(root, ['rev-list', '--parents', '-n', '1', head]) === `${head} ${receipt.candidate}` &&
|
|
435
|
+
gitText(root, ['rev-parse', `${head}^{tree}`]) === gitText(root, ['rev-parse', `${receipt.base}^{tree}`])) {
|
|
436
|
+
return { id, commit: head, replayed: true };
|
|
437
|
+
}
|
|
438
|
+
if (head !== (rollback ? receipt.candidate : receipt.base))
|
|
439
|
+
throw new InputError('Project version changed since Skill replay');
|
|
440
|
+
const packagePath = receipt.package_path ?? dirname(receipt.entry).replaceAll('\\', '/');
|
|
441
|
+
if (gitText(root, ['status', '--porcelain', '--untracked-files=all', '--', packagePath])) {
|
|
442
|
+
throw new InputError('Skill package has local changes');
|
|
443
|
+
}
|
|
444
|
+
if (gitText(root, ['diff', '--cached', '--name-only']))
|
|
445
|
+
throw new InputError('The Git index contains staged changes');
|
|
446
|
+
if (rollback)
|
|
447
|
+
git(root, ['revert', '--no-edit', receipt.candidate]);
|
|
448
|
+
else
|
|
449
|
+
git(root, ['merge', '--ff-only', receipt.candidate]);
|
|
450
|
+
return { id, commit: gitText(root, ['rev-parse', 'HEAD']), replayed: false };
|
|
451
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
export type SkillRetentionRoute = 'wiki' | 'skill-addition' | 'skill-design';
|
|
2
|
+
export interface SkillRouteContext {
|
|
3
|
+
content: string;
|
|
4
|
+
sources: string[];
|
|
5
|
+
matchedEntry?: string | null;
|
|
6
|
+
relatedEntries?: string[];
|
|
7
|
+
skillId?: string;
|
|
8
|
+
skillVersion?: string;
|
|
9
|
+
signalKinds?: string[];
|
|
10
|
+
repeatCount?: number;
|
|
11
|
+
stepCount?: number;
|
|
12
|
+
crossSkill?: boolean;
|
|
13
|
+
requiresNewContract?: boolean;
|
|
14
|
+
requiresNewArtifacts?: boolean;
|
|
15
|
+
requiresRouting?: boolean;
|
|
16
|
+
explicitSkillIntent?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface SkillRouteDecision {
|
|
19
|
+
route: SkillRetentionRoute;
|
|
20
|
+
confidence: 'high' | 'medium' | 'low';
|
|
21
|
+
reasons: string[];
|
|
22
|
+
invoke_meta_skill: boolean;
|
|
23
|
+
meta_skill?: {
|
|
24
|
+
id: 'ew-skill-design';
|
|
25
|
+
mode: 'design';
|
|
26
|
+
instruction: string;
|
|
27
|
+
};
|
|
28
|
+
priority?: 'high' | 'normal' | 'low';
|
|
29
|
+
}
|
|
30
|
+
export declare function decideSkillRoute(input: SkillRouteContext): SkillRouteDecision;
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { InputError, requireText } from './common.js';
|
|
2
|
+
function list(value, field) {
|
|
3
|
+
if (value === undefined)
|
|
4
|
+
return [];
|
|
5
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item.trim())) {
|
|
6
|
+
throw new InputError(`${field} must be a list of non-empty strings`);
|
|
7
|
+
}
|
|
8
|
+
return [...new Set(value.map(item => item.trim()))];
|
|
9
|
+
}
|
|
10
|
+
function count(value, field) {
|
|
11
|
+
if (value === undefined)
|
|
12
|
+
return 0;
|
|
13
|
+
if (!Number.isSafeInteger(value) || value < 0)
|
|
14
|
+
throw new InputError(`${field} must be a non-negative integer`);
|
|
15
|
+
return value;
|
|
16
|
+
}
|
|
17
|
+
export function decideSkillRoute(input) {
|
|
18
|
+
const content = requireText(input.content, 'Skill route content');
|
|
19
|
+
const normalized = content.toLowerCase();
|
|
20
|
+
const sources = list(input.sources, 'Skill route sources');
|
|
21
|
+
if (!sources.length)
|
|
22
|
+
throw new InputError('Skill route requires at least one evidence source');
|
|
23
|
+
const signalKinds = list(input.signalKinds, 'Skill route signal kinds');
|
|
24
|
+
const repeatCount = count(input.repeatCount, 'repeatCount');
|
|
25
|
+
const stepCount = count(input.stepCount, 'stepCount');
|
|
26
|
+
const reasons = [];
|
|
27
|
+
const inferredSkillIntent = /(?:新增|设计|创建|建立).{0,12}skill|new\s+skill|design\s+(?:a\s+)?skill/.test(normalized);
|
|
28
|
+
const inferredContract = /(?:新增|设计|创建).{0,12}(?:契约|contract)|new\s+skill\s+contract/.test(normalized);
|
|
29
|
+
const inferredArtifacts = /(?:新增|设计|创建).{0,12}(?:产物|artifact|output)/.test(normalized);
|
|
30
|
+
const inferredRouting = /(?:跨|多).{0,8}skill|(?:新|多阶段|多步骤).{0,8}(?:路由|分支|流程链)|cross[- ]skill|multi[- ]stage/.test(normalized);
|
|
31
|
+
const structural = Boolean(input.requiresNewContract || inferredContract || input.requiresNewArtifacts || inferredArtifacts ||
|
|
32
|
+
input.requiresRouting || inferredRouting || input.crossSkill || input.explicitSkillIntent || inferredSkillIntent || stepCount >= 3);
|
|
33
|
+
if (structural) {
|
|
34
|
+
if (input.requiresNewContract || inferredContract)
|
|
35
|
+
reasons.push('需要新的 Skill contract 或生命周期门禁');
|
|
36
|
+
if (input.requiresNewArtifacts || inferredArtifacts)
|
|
37
|
+
reasons.push('需要新的产物类型或验证输出');
|
|
38
|
+
if (input.requiresRouting || inferredRouting)
|
|
39
|
+
reasons.push('需要新增路由、分支或阶段链');
|
|
40
|
+
if (input.crossSkill)
|
|
41
|
+
reasons.push('影响多个 Skill 或需要跨 Skill 协作');
|
|
42
|
+
if (input.explicitSkillIntent || inferredSkillIntent)
|
|
43
|
+
reasons.push('上下文明确要求设计或新增 Skill');
|
|
44
|
+
if (stepCount >= 3)
|
|
45
|
+
reasons.push('可复用流程包含至少 3 个稳定步骤');
|
|
46
|
+
return {
|
|
47
|
+
route: 'skill-design', confidence: 'high', reasons,
|
|
48
|
+
invoke_meta_skill: true,
|
|
49
|
+
meta_skill: {
|
|
50
|
+
id: 'ew-skill-design', mode: 'design',
|
|
51
|
+
instruction: `基于已验证证据设计 Skill。保留当前入口约束,声明 Markdown 链接、契约、产物、恢复路径和验收场景。证据:${sources.join(', ')}`,
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
if (input.skillId) {
|
|
56
|
+
reasons.push(`信号可以归因到 Skill ${input.skillId}`);
|
|
57
|
+
if (input.skillVersion)
|
|
58
|
+
reasons.push(`已固定 Skill 版本 ${input.skillVersion}`);
|
|
59
|
+
if (repeatCount >= 2)
|
|
60
|
+
reasons.push('同类信号至少重复两次');
|
|
61
|
+
if (signalKinds.some(kind => ['correction', 'error', 'retry', 'workflow_issue'].includes(kind))) {
|
|
62
|
+
reasons.push('证据包含可修正的执行信号');
|
|
63
|
+
}
|
|
64
|
+
return {
|
|
65
|
+
route: 'skill-addition', confidence: input.skillVersion ? 'high' : 'medium', reasons,
|
|
66
|
+
invoke_meta_skill: false,
|
|
67
|
+
priority: repeatCount >= 2 || signalKinds.includes('workflow_issue') ? 'high' : 'normal',
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
if (input.matchedEntry || input.relatedEntries?.length)
|
|
71
|
+
reasons.push('候选已有 Wiki 关系,需要沿 Wiki 审查流程处理');
|
|
72
|
+
else
|
|
73
|
+
reasons.push('当前证据适合沉淀为项目级 Wiki reference');
|
|
74
|
+
return { route: 'wiki', confidence: input.matchedEntry ? 'high' : 'medium', reasons, invoke_meta_skill: false };
|
|
75
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
import { lstatSync, readFileSync, readdirSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { InputError, requireText } from './common.js';
|
|
5
|
+
export function readCompletionTranscriptRefs(refs) {
|
|
6
|
+
if (refs === undefined)
|
|
7
|
+
return [];
|
|
8
|
+
if (!Array.isArray(refs) || refs.some(ref => typeof ref !== 'string' || !/^transcript:[^:\p{Cc}]+:[^:\p{Cc}]+:[^:\p{Cc}]+:[a-f0-9]{16}$/u.test(ref))) {
|
|
9
|
+
throw new InputError('Invalid Session completion transcript references');
|
|
10
|
+
}
|
|
11
|
+
return refs;
|
|
12
|
+
}
|
|
13
|
+
export function readTranscriptSnapshots(sessionDirectory, refs) {
|
|
14
|
+
if (refs?.length === 0)
|
|
15
|
+
return [];
|
|
16
|
+
const selected = refs && new Set(refs);
|
|
17
|
+
const prefixes = refs && new Set(refs.map(ref => ref.split(':').at(-1)));
|
|
18
|
+
const directory = join(sessionDirectory, 'transcript-evidence');
|
|
19
|
+
const directoryInfo = lstatSync(directory, { throwIfNoEntry: false });
|
|
20
|
+
if (!directoryInfo && !selected)
|
|
21
|
+
return [];
|
|
22
|
+
if (!directoryInfo?.isDirectory())
|
|
23
|
+
throw new InputError('Invalid Session transcript snapshot directory');
|
|
24
|
+
const messages = readdirSync(directory, { withFileTypes: true }).filter(entry => entry.isFile() && /^[a-f0-9]{64}-[a-f0-9]{16}\.json$/.test(entry.name)).sort((left, right) => left.name.localeCompare(right.name)).flatMap(entry => {
|
|
25
|
+
if (prefixes && !prefixes.has(entry.name.slice(0, 16)))
|
|
26
|
+
return [];
|
|
27
|
+
const snapshot = JSON.parse(readFileSync(join(directory, entry.name), 'utf8'));
|
|
28
|
+
requireText(snapshot.quote, 'transcript fragment');
|
|
29
|
+
const quote = String(snapshot.quote);
|
|
30
|
+
const hash = createHash('sha256').update(quote).digest('hex');
|
|
31
|
+
const original = requireText(snapshot.sha256, 'transcript source hash');
|
|
32
|
+
const locator = [
|
|
33
|
+
requireText(snapshot.host_kind, 'host kind'),
|
|
34
|
+
requireText(snapshot.host_session_id, 'host session'),
|
|
35
|
+
requireText(snapshot.entry_id, 'entry ID'),
|
|
36
|
+
];
|
|
37
|
+
const locatorHash = createHash('sha256').update(locator.join('\0')).digest('hex').slice(0, 16);
|
|
38
|
+
if (snapshot.schema_version !== 'transcript-evidence/1.0' ||
|
|
39
|
+
hash !== snapshot.normalized_sha256 || entry.name !== `${original}-${locatorHash}.json` ||
|
|
40
|
+
locator.some(part => /[:\p{Cc}]/u.test(part))) {
|
|
41
|
+
throw new InputError(`Transcript evidence hash mismatch: ${entry.name}`);
|
|
42
|
+
}
|
|
43
|
+
const id = `transcript:${locator.join(':')}:${original.slice(0, 16)}`;
|
|
44
|
+
if (selected && !selected.has(id))
|
|
45
|
+
return [];
|
|
46
|
+
return [{
|
|
47
|
+
id,
|
|
48
|
+
role: 'tool',
|
|
49
|
+
timestamp: requireText(snapshot.captured_at, 'capture time'),
|
|
50
|
+
content: quote,
|
|
51
|
+
}];
|
|
52
|
+
});
|
|
53
|
+
const ids = new Set(messages.map(message => message.id));
|
|
54
|
+
if (ids.size !== messages.length || (selected && ids.size !== selected.size)) {
|
|
55
|
+
throw new InputError('Missing or ambiguous transcript evidence');
|
|
56
|
+
}
|
|
57
|
+
return messages;
|
|
58
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* chunker.ts — 超长源的分块。
|
|
3
|
+
*
|
|
4
|
+
* 当源字符数超过模型上下文预算时,把文本切成若干块逐块处理,
|
|
5
|
+
* 块间留少量重叠以保留上下文连续性(INTERFACE §6)。
|
|
6
|
+
*
|
|
7
|
+
* 切分单位(OQ-5 优化):优先按 markdown 标题(`#`~`######`)边界切,
|
|
8
|
+
* 让每个语义小节尽量完整地落在同一块里;超长小节再回退到按空行段落切,
|
|
9
|
+
* 仍超长的段落最后硬切。避免在句子/小节中间生硬截断。
|
|
10
|
+
*/
|
|
11
|
+
export interface ChunkOptions {
|
|
12
|
+
/** 单块目标字符数上限(默认 12000)。 */
|
|
13
|
+
targetChars?: number;
|
|
14
|
+
/** 块间重叠字符数(默认 400)。 */
|
|
15
|
+
overlapChars?: number;
|
|
16
|
+
}
|
|
17
|
+
/**
|
|
18
|
+
* 把文本聚合成若干块。每块尽量不超过 targetChars,按 markdown 小节边界聚合。
|
|
19
|
+
*
|
|
20
|
+
* @returns 块数组;输入为空返回 [],不超阈值返回单元素数组。
|
|
21
|
+
*/
|
|
22
|
+
export declare function chunkText(text: string, opts?: ChunkOptions): string[];
|
|
23
|
+
/** 粗略估算字符串的 token 数(保守 len/3)。用于判断是否需要分块。 */
|
|
24
|
+
export declare function estimateTokens(text: string): number;
|