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.
Files changed (173) hide show
  1. package/LICENSE +27 -0
  2. package/README.md +90 -2
  3. package/dist/agent-memory-prompts.d.ts +13 -0
  4. package/dist/agent-memory-prompts.js +55 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +6 -0
  7. package/dist/closeout.d.ts +105 -0
  8. package/dist/closeout.js +479 -0
  9. package/dist/code.d.ts +39 -0
  10. package/dist/code.js +124 -0
  11. package/dist/common.d.ts +9 -0
  12. package/dist/common.js +42 -0
  13. package/dist/context-envelope.d.ts +59 -0
  14. package/dist/context-envelope.js +23 -0
  15. package/dist/host-adapters.d.ts +34 -0
  16. package/dist/host-adapters.js +151 -0
  17. package/dist/http.d.ts +3 -0
  18. package/dist/http.js +90 -0
  19. package/dist/index.d.ts +16 -0
  20. package/dist/index.js +13 -0
  21. package/dist/knowledge-cli.d.ts +183 -0
  22. package/dist/knowledge-cli.js +654 -0
  23. package/dist/knowledge-reads.d.ts +71 -0
  24. package/dist/knowledge-reads.js +193 -0
  25. package/dist/memory.d.ts +97 -0
  26. package/dist/memory.js +250 -0
  27. package/dist/retrospective.d.ts +57 -0
  28. package/dist/retrospective.js +248 -0
  29. package/dist/search.d.ts +36 -0
  30. package/dist/search.js +112 -0
  31. package/dist/skill-addition.d.ts +25 -0
  32. package/dist/skill-addition.js +89 -0
  33. package/dist/skill-design.d.ts +96 -0
  34. package/dist/skill-design.js +226 -0
  35. package/dist/skill-replay.d.ts +55 -0
  36. package/dist/skill-replay.js +451 -0
  37. package/dist/skill-route.d.ts +30 -0
  38. package/dist/skill-route.js +75 -0
  39. package/dist/transcript-evidence.d.ts +3 -0
  40. package/dist/transcript-evidence.js +58 -0
  41. package/dist/upstream/chunker.d.ts +24 -0
  42. package/dist/upstream/chunker.js +96 -0
  43. package/dist/upstream/file-protocol.d.ts +45 -0
  44. package/dist/upstream/file-protocol.js +117 -0
  45. package/dist/upstream/frontmatter.d.ts +47 -0
  46. package/dist/upstream/frontmatter.js +86 -0
  47. package/dist/upstream/graph-search.d.ts +33 -0
  48. package/dist/upstream/graph-search.js +67 -0
  49. package/dist/upstream/l1-extraction.d.ts +26 -0
  50. package/dist/upstream/l1-extraction.js +405 -0
  51. package/dist/upstream/llm.d.ts +8 -0
  52. package/dist/upstream/llm.js +1 -0
  53. package/dist/upstream/merge.d.ts +50 -0
  54. package/dist/upstream/merge.js +153 -0
  55. package/dist/upstream/prompts.d.ts +53 -0
  56. package/dist/upstream/prompts.js +185 -0
  57. package/dist/upstream/search-utils.d.ts +34 -0
  58. package/dist/upstream/search-utils.js +55 -0
  59. package/dist/upstream/slug.d.ts +26 -0
  60. package/dist/upstream/slug.js +103 -0
  61. package/dist/upstream/template.d.ts +29 -0
  62. package/dist/upstream/template.js +80 -0
  63. package/dist/upstream/tokenize.d.ts +4 -0
  64. package/dist/upstream/tokenize.js +29 -0
  65. package/dist/wiki-change.d.ts +76 -0
  66. package/dist/wiki-change.js +299 -0
  67. package/dist/wiki-entry.d.ts +26 -0
  68. package/dist/wiki-entry.js +93 -0
  69. package/dist/wiki-ingest.d.ts +12 -0
  70. package/dist/wiki-ingest.js +126 -0
  71. package/dist/wiki-migration.d.ts +16 -0
  72. package/dist/wiki-migration.js +268 -0
  73. package/dist/wiki-tokens.d.ts +1 -0
  74. package/dist/wiki-tokens.js +46 -0
  75. package/dist/wiki.d.ts +103 -0
  76. package/dist/wiki.js +330 -0
  77. package/dist/workflow-cli.d.ts +2 -0
  78. package/dist/workflow-cli.js +258 -0
  79. package/dist/workflow-install.d.ts +36 -0
  80. package/dist/workflow-install.js +148 -0
  81. package/dist/workflow-knowledge.d.ts +16 -0
  82. package/dist/workflow-knowledge.js +24 -0
  83. package/dist/workflow-mcp.d.ts +2 -0
  84. package/dist/workflow-mcp.js +144 -0
  85. package/dist/workflow-names.d.ts +4 -0
  86. package/dist/workflow-names.js +18 -0
  87. package/dist/workflow-runtime.d.ts +622 -0
  88. package/dist/workflow-runtime.js +627 -0
  89. package/dist/workflow-skills.d.ts +48 -0
  90. package/dist/workflow-skills.js +141 -0
  91. package/package.json +76 -4
  92. package/skills/ew-odyssey/SKILL.md +237 -0
  93. package/skills/ew-odyssey/references/audit-artifacts.md +7 -0
  94. package/skills/ew-odyssey/references/odyssey-base-codex.md +3 -0
  95. package/skills/ew-odyssey/references/odyssey-base.md +278 -0
  96. package/skills/ew-odyssey/references/odyssey-debug.codex.md +305 -0
  97. package/skills/ew-odyssey/references/odyssey-debug.md +283 -0
  98. package/skills/ew-odyssey/references/odyssey-defensive.codex.md +395 -0
  99. package/skills/ew-odyssey/references/odyssey-defensive.md +369 -0
  100. package/skills/ew-odyssey/references/odyssey-improve.codex.md +270 -0
  101. package/skills/ew-odyssey/references/odyssey-improve.md +248 -0
  102. package/skills/ew-odyssey/references/odyssey-planex.codex.md +352 -0
  103. package/skills/ew-odyssey/references/odyssey-planex.md +312 -0
  104. package/skills/ew-odyssey/references/odyssey-review.codex.md +283 -0
  105. package/skills/ew-odyssey/references/odyssey-review.md +251 -0
  106. package/skills/ew-odyssey/references/odyssey-security.md +249 -0
  107. package/skills/ew-odyssey/references/odyssey-ui.codex.md +294 -0
  108. package/skills/ew-odyssey/references/odyssey-ui.md +250 -0
  109. package/skills/ew-odyssey/references/prepare/odyssey-debug.md +105 -0
  110. package/skills/ew-odyssey/references/prepare/odyssey-defensive.md +121 -0
  111. package/skills/ew-odyssey/references/prepare/odyssey-improve.md +93 -0
  112. package/skills/ew-odyssey/references/prepare/odyssey-planex.md +104 -0
  113. package/skills/ew-odyssey/references/prepare/odyssey-review.md +98 -0
  114. package/skills/ew-odyssey/references/prepare/odyssey-security.md +94 -0
  115. package/skills/ew-odyssey/references/prepare/odyssey-ui.md +87 -0
  116. package/skills/ew-orchestrate/SKILL.md +236 -0
  117. package/skills/ew-orchestrate/references/auto-policy.md +165 -0
  118. package/skills/ew-orchestrate/references/companion-route.md +52 -0
  119. package/skills/ew-orchestrate/references/ew-orchestrate.md +27 -0
  120. package/skills/ew-orchestrate/references/goal.md +53 -0
  121. package/skills/ew-orchestrate/references/knowledge-route.md +163 -0
  122. package/skills/ew-orchestrate/references/orchestrator-run-loop.md +36 -0
  123. package/skills/ew-orchestrate/references/planning.md +137 -0
  124. package/skills/ew-orchestrate/steps/ew-analyze/SKILL.md +62 -0
  125. package/skills/ew-orchestrate/steps/ew-analyze/references/boundary-grill.md +50 -0
  126. package/skills/ew-orchestrate/steps/ew-analyze/references/issue-gaps-analyze.md +59 -0
  127. package/skills/ew-orchestrate/steps/ew-analyze/references/prepare.md +42 -0
  128. package/skills/ew-orchestrate/steps/ew-analyze/references/workflow.md +401 -0
  129. package/skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md +32 -0
  130. package/skills/ew-orchestrate/steps/ew-companion/SKILL.md +9 -0
  131. package/skills/ew-orchestrate/steps/ew-execute/SKILL.md +71 -0
  132. package/skills/ew-orchestrate/steps/ew-execute/references/prepare.md +69 -0
  133. package/skills/ew-orchestrate/steps/ew-execute/references/workflow.md +373 -0
  134. package/skills/ew-orchestrate/steps/ew-plan/SKILL.md +102 -0
  135. package/skills/ew-orchestrate/steps/ew-plan/references/boundary-grill.md +50 -0
  136. package/skills/ew-orchestrate/steps/ew-plan/references/prepare.md +51 -0
  137. package/skills/ew-orchestrate/steps/ew-plan/references/tdd.md +53 -0
  138. package/skills/ew-orchestrate/steps/ew-plan/references/workflow.md +278 -0
  139. package/skills/ew-orchestrate/steps/ew-review/SKILL.md +44 -0
  140. package/skills/ew-orchestrate/steps/ew-review/references/odyssey-base-codex.md +3 -0
  141. package/skills/ew-orchestrate/steps/ew-review/references/prepare.md +76 -0
  142. package/skills/ew-orchestrate/steps/ew-review/references/workflow.md +283 -0
  143. package/skills/ew-skill-design/SKILL.md +28 -0
  144. package/skills/ew-skill-design/references/package-contract.md +28 -0
  145. package/skills/ew-skill-design/references/validation.md +7 -0
  146. package/skills/team-swarm/SKILL.md +231 -0
  147. package/skills/team-swarm/references/mcp-coordination.md +10 -0
  148. package/skills/team-swarm/roles/analyst/role.md +181 -0
  149. package/skills/team-swarm/roles/ant/role.md +149 -0
  150. package/skills/team-swarm/roles/coordinator/commands/converge.md +154 -0
  151. package/skills/team-swarm/roles/coordinator/commands/init-swarm.md +134 -0
  152. package/skills/team-swarm/roles/coordinator/commands/iterate.md +202 -0
  153. package/skills/team-swarm/roles/coordinator/role.md +228 -0
  154. package/skills/team-swarm/roles/scorer/role.md +150 -0
  155. package/skills/team-swarm/scripts/aco.py +646 -0
  156. package/skills/team-swarm/scripts/pheromone.py +144 -0
  157. package/skills/team-swarm/scripts/scoring.py +111 -0
  158. package/skills/team-swarm/scripts/test_aco.py +606 -0
  159. package/skills/team-swarm/specs/ant-output-schema.md +127 -0
  160. package/skills/team-swarm/specs/convergence-criteria.md +108 -0
  161. package/skills/team-swarm/specs/pheromone-schema.md +125 -0
  162. package/skills/team-swarm/specs/swarm-config-template.json +71 -0
  163. package/skills/team-swarm/specs/swarm-protocol.md +123 -0
  164. package/skills/workflow-closeout/SKILL.md +10 -0
  165. package/skills/workflow-evolve/SKILL.md +79 -0
  166. package/skills/workflow-evolve/references/agy-gate.md +27 -0
  167. package/skills/workflow-evolve/references/auto-loop.md +20 -0
  168. package/skills/workflow-evolve/references/history-review.md +14 -0
  169. package/skills/workflow-evolve/scripts/codex-memory-replay.mjs +76 -0
  170. package/skills/workflow-evolve/scripts/codex-replay.mjs +1 -0
  171. package/skills/workflow-evolve/scripts/evolve-loop.mjs +259 -0
  172. package/skills/workflow-evolve/scripts/memory-codex-mcp.mjs +124 -0
  173. package/workflows/index.json +23 -0
@@ -0,0 +1,20 @@
1
+ # Automatic loop
2
+
3
+ The loop is deterministic around four external calls. The runner executes the real task, Agent Memory reviews history, Agy discusses and confirms the proposed change, and Git worktrees replay the baseline and candidate.
4
+
5
+ ## Round order
6
+
7
+ 1. Read the current `HEAD` and verify that the target Skill package has no uncommitted changes.
8
+ 2. Run every scenario with the current Skill. At least one scenario must reproduce the known failure and one must already pass.
9
+ 3. Review history with `agent-memory session review <id>` or `agent-memory evolve review <execution-id> --project <id>`. An explicit `--history` JSON file is accepted when no committed receipt exists. Keep the returned signals, Skill reference, Skill reads and `knowledge_reads` evidence in the round directory.
10
+ 4. Ask Agy for one minimal, evidence-linked draft. Agy returns `approved`, `priority`, `instruction`, `when`, `evidence` and `needs_revision`. Reject a draft that lacks a stable source or changes an unrelated behavior. Retry only up to `--max-retries`.
11
+ 5. Create the draft through `agent-memory evolve draft`. Replay it with `agent-memory evolve replay` against the accumulated scenario set. The replay must keep every baseline pass green and make every baseline failure pass.
12
+ 6. Ask Agy to confirm the replay receipt. The confirmation includes the draft ID, candidate commit, scenario observations and loaded Skill documents. `approved: false` stops the round without applying the candidate.
13
+ 7. With `--auto`, apply the receipt. Run the same scenarios from the applied commit. If any scenario fails, immediately call `agent-memory evolve rollback <receipt-id>` and record the failed verification. Without `--auto`, leave the confirmed receipt pending.
14
+ 8. Persist the round state and continue until the requested count, a zero-signal review, an Agy rejection, or retry exhaustion stops the loop.
15
+
16
+ ## State and stop conditions
17
+
18
+ `state.json` is the only machine state source. Each round records `base`, `draft`, `replay`, `history`, Agy responses, application status and verification observations. Stop with `completed` after the requested count, `agy_rejected` after bounded Agy retries, `confirmation_rejected` after replay review, or `rolled_back` after an applied verification failure. A process error is `failed` and keeps the round directory for recovery.
19
+
20
+ The loop resolves Session IDs from the supplied inputs, records exact reads behind each search, and applies drafts with an Agy confirmation receipt. A history source is mandatory. `--allow-empty-history` serves an explicitly history-free fixture and records that exception in the round state.
@@ -0,0 +1,14 @@
1
+ # History review
2
+
3
+ Use committed execution evidence whenever possible. `session review` reconstructs Run transitions, retries, Skill references, loaded Skill files and `knowledge_reads`. `evolve review` performs the equivalent review for a standalone Skill completion. The review result is the input to Agy and to the draft evidence list.
4
+
5
+ When a transcript file is supplied, keep its message IDs and pair every quoted fragment with a receipt or verification source. If the review returns no attributable signal, finish the loop with a zero-change result.
6
+
7
+ The history summary should answer these questions.
8
+
9
+ - Which Run or standalone execution used the affected Skill revision?
10
+ - What user correction, failure, retry and verified fix are linked to that execution?
11
+ - Which Skill documents and memory searches were actually read?
12
+ - Is the defect in the Skill instructions, the runner, the host adapter or a transient external dependency?
13
+
14
+ Only a defect attributable to the Skill package can produce an `evolve draft`. Host outages and missing runtime capabilities stay in the round report for later workflow repair.
@@ -0,0 +1,76 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { existsSync, mkdtempSync, readFileSync, realpathSync, rmSync } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { join, posix, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { parse } from 'yaml';
7
+
8
+ const { id, input, entry: rawEntry, commit } = JSON.parse(readFileSync(0, 'utf8').replace(/^\uFEFF/, ''));
9
+ const entry = rawEntry?.replaceAll('\\', '/');
10
+ if (!/^skills\/[a-z0-9]+(?:-[a-z0-9]+)*\/SKILL\.md$/.test(entry) ||
11
+ !/^(?:[a-f0-9]{40}|[a-f0-9]{64})$/.test(commit) ||
12
+ typeof input?.task !== 'string' || !input.task.trim() ||
13
+ typeof input.expected !== 'string' || !input.expected.trim()) {
14
+ throw new Error('Replay requires a Skill entry, Git commit, task and expected output');
15
+ }
16
+
17
+ const root = process.cwd();
18
+ const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8', windowsHide: true });
19
+ if (git('rev-parse', 'HEAD').trim() !== commit) throw new Error('Replay checkout must match the requested commit');
20
+ const markdown = git('show', commit + ':' + entry);
21
+ const header = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown.replace(/^\uFEFF/, ''));
22
+ const required = (header ? parse(header[1])?.required_links : undefined) ?? [];
23
+ if (!Array.isArray(required) || required.some(link => typeof link !== 'string' || !link.trim())) {
24
+ throw new Error('Skill required_links must contain Markdown destinations');
25
+ }
26
+
27
+ const defaultCli = fileURLToPath(new URL('../../../dist/cli.js', import.meta.url));
28
+ const memoryCli = realpathSync(process.env.AGENT_MEMORY_CLI || defaultCli);
29
+ const codex = process.env.CODEX_REPLAY_EXECUTABLE || (process.platform === 'win32' ? 'codex.exe' : 'codex');
30
+ const codexEntry = /\.[cm]?js$/i.test(codex) ? [resolve(codex)] : [];
31
+ const server = fileURLToPath(new URL('./memory-codex-mcp.mjs', import.meta.url));
32
+ const scratch = mkdtempSync(join(tmpdir(), 'evolve-codex-task-'));
33
+ try {
34
+ const db = process.env.AGENT_MEMORY_DB ? resolve(process.env.AGENT_MEMORY_DB) : join(scratch, 'memory.db');
35
+ const loadedPath = join(scratch, 'skill-reads.json');
36
+ const tracePath = join(scratch, 'knowledge-reads.json');
37
+ const prompt = [
38
+ 'Run one Skill replay. First use memory_search for the task, then read_skill with no arguments.',
39
+ 'Use memory_get for relevant IDs returned by the search. Treat memory results as evidence.',
40
+ 'Follow required_links and applicable conditional links through read_skill. Pass the returned source path as from and the declared link as destination.',
41
+ 'Return the requested task output as plain text.',
42
+ '',
43
+ input.task,
44
+ ].join('\n');
45
+ const stdout = execFileSync(codexEntry.length ? process.execPath : codex, [...codexEntry, '-a', 'never', 'exec', '--ephemeral', '--ignore-user-config',
46
+ '--skip-git-repo-check', '--json', '--sandbox', 'read-only',
47
+ '-c', 'mcp_servers.evolve_replay.command=' + JSON.stringify(process.execPath),
48
+ '-c', 'mcp_servers.evolve_replay.args=' + JSON.stringify([server, memoryCli, root, db, entry, commit, loadedPath, tracePath]),
49
+ '-c', 'mcp_servers.evolve_replay.required=true',
50
+ '-c', 'mcp_servers.evolve_replay.default_tools_approval_mode="writes"', '-'], {
51
+ input: prompt, cwd: scratch, encoding: 'utf8', windowsHide: true,
52
+ stdio: ['pipe', 'pipe', 'pipe'], timeout: 110_000, maxBuffer: 8 * 1024 * 1024,
53
+ shell: process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(codex),
54
+ });
55
+ const events = stdout.trim().split(/\r?\n/).map(line => JSON.parse(line));
56
+ const answer = events.findLast(event => event.type === 'item.completed' && event.item?.type === 'agent_message')?.item.text;
57
+ if (typeof answer !== 'string' || !events.some(event => event.type === 'turn.completed')) {
58
+ throw new Error('Codex replay did not complete: ' + id);
59
+ }
60
+ const loaded = existsSync(loadedPath) ? JSON.parse(readFileSync(loadedPath, 'utf8')) : [];
61
+ const expected = [entry, ...required.map(link => posix.join(posix.dirname(entry), link.split('#', 1)[0]))];
62
+ const missing = expected.filter(path => !loaded.some(read => read.path === path));
63
+ if (missing.length) throw new Error('Codex replay needs Skill reads for: ' + missing.join(', '));
64
+ const knowledgeReads = existsSync(tracePath) ? JSON.parse(readFileSync(tracePath, 'utf8')) : undefined;
65
+ if (!knowledgeReads?.searches.some(search => search.source === 'memory')) {
66
+ throw new Error('Codex replay needs an Agent Memory search for: ' + id);
67
+ }
68
+ const calls = events.filter(event => event.type === 'item.completed' && event.item?.type === 'agent_message');
69
+ console.log(JSON.stringify({
70
+ passed: answer.trim() === input.expected.trim(), loaded, knowledge_reads: knowledgeReads,
71
+ transcript: calls.map(event => event.item.text), answer: answer.trim(),
72
+ }));
73
+ } finally {
74
+ // 临时目录由本次回放独占。
75
+ rmSync(scratch, { recursive: true, force: true });
76
+ }
@@ -0,0 +1 @@
1
+ await import('./codex-memory-replay.mjs');
@@ -0,0 +1,259 @@
1
+ import { execFileSync } from 'node:child_process';
2
+ import { createHash, randomUUID } from 'node:crypto';
3
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+
7
+ const root = process.cwd();
8
+ const args = process.argv.slice(2);
9
+
10
+ function option(name, fallback) {
11
+ const index = args.indexOf(name);
12
+ return index < 0 ? fallback : args[index + 1];
13
+ }
14
+
15
+ function has(name) { return args.includes(name); }
16
+
17
+ function required(name) {
18
+ const value = option(name);
19
+ if (!value || value.startsWith('--')) throw new Error(`Missing ${name}`);
20
+ return value;
21
+ }
22
+
23
+ const iterations = Number(required('--iterations'));
24
+ if (!Number.isInteger(iterations) || iterations < 1) throw new Error('--iterations must be a positive integer');
25
+ const entry = resolve(root, required('--skill'));
26
+ const scenariosPath = resolve(root, required('--scenarios'));
27
+ const runner = resolve(root, option('--runner', fileURLToPath(new URL('./codex-memory-replay.mjs', import.meta.url))));
28
+ const memoryCli = resolve(root, option('--memory-cli', process.env.AGENT_MEMORY_CLI ||
29
+ fileURLToPath(new URL('../../../dist/cli.js', import.meta.url))));
30
+ const agy = option('--agy', 'agy');
31
+ const maxRetries = Number(option('--max-retries', '1'));
32
+ if (!Number.isInteger(maxRetries) || maxRetries < 0) throw new Error('--max-retries must be a non-negative integer');
33
+ const historyFlags = ['--session', '--execution', '--history'].filter(name => option(name) !== undefined);
34
+ if (historyFlags.length > 1) throw new Error('Use only one of --session, --execution or --history');
35
+ if (!historyFlags.length && !has('--allow-empty-history')) {
36
+ throw new Error('Provide --session, --execution or --history. Use --allow-empty-history only for an explicitly history-free fixture.');
37
+ }
38
+ if (!existsSync(entry)) throw new Error(`Skill entry not found: ${entry}`);
39
+ if (!existsSync(scenariosPath)) throw new Error(`Scenario file not found: ${scenariosPath}`);
40
+ if (!existsSync(runner)) throw new Error(`Replay runner not found: ${runner}`);
41
+ if (!existsSync(memoryCli)) throw new Error(`Agent Memory CLI not found: ${memoryCli}`);
42
+ process.env.AGENT_MEMORY_CLI = memoryCli;
43
+ if (process.env.AGENT_MEMORY_DB) process.env.AGENT_MEMORY_DB = resolve(root, process.env.AGENT_MEMORY_DB);
44
+
45
+ const skillEntry = entry.replaceAll('\\', '/').replace(`${root.replaceAll('\\', '/')}/`, '');
46
+ if (!/^skills\/[a-z0-9]+(?:-[a-z0-9]+)*\/SKILL\.md$/i.test(skillEntry)) {
47
+ throw new Error('--skill must point to skills/<id>/SKILL.md');
48
+ }
49
+ const scenarios = JSON.parse(readFileSync(scenariosPath, 'utf8'));
50
+ if (!Array.isArray(scenarios) || scenarios.length < 2 ||
51
+ !scenarios.some(item => item.baseline === false) || !scenarios.some(item => item.baseline === true)) {
52
+ throw new Error('--scenarios must contain at least one baseline failure and one baseline pass');
53
+ }
54
+ let scenarioSet = scenarios.map(scenario => ({ ...scenario }));
55
+
56
+ const timestamp = new Date().toISOString().replace(/[:.]/g, '-');
57
+ const outputDir = resolve(root, option('--output-dir', join('.workflow', 'evolution', timestamp)));
58
+ mkdirSync(outputDir, { recursive: true });
59
+ const statePath = join(outputDir, 'state.json');
60
+ const state = {
61
+ schema_version: 'workflow-evolve/1.0', target: skillEntry, iterations_requested: iterations,
62
+ max_retries: maxRetries, auto: has('--auto'), rounds: [], status: 'running',
63
+ };
64
+
65
+ function run(command, commandArgs, options = {}) {
66
+ const output = execFileSync(command, commandArgs, {
67
+ cwd: options.cwd ?? root, env: { ...process.env, ...options.env }, encoding: 'utf8', windowsHide: true,
68
+ stdio: ['pipe', 'pipe', 'pipe'], input: options.input, timeout: options.timeout ?? 180_000,
69
+ });
70
+ return output.trim();
71
+ }
72
+
73
+ function jsonCommand(command, commandArgs, options = {}) {
74
+ const output = run(command, commandArgs, options);
75
+ try { return JSON.parse(output); } catch (error) { throw new Error(`Expected JSON from ${command}: ${output.slice(-2000)}`, { cause: error }); }
76
+ }
77
+
78
+ function git(args) { return run('git', args); }
79
+
80
+ function runReplay(scenario, commit) {
81
+ const output = run(process.execPath, [runner], {
82
+ input: JSON.stringify({ id: `${scenario.id}-round-${state.rounds.length + 1}`, input: scenario.input,
83
+ entry: skillEntry, commit }),
84
+ });
85
+ return JSON.parse(output);
86
+ }
87
+
88
+ function parseAgyResponse(output) {
89
+ const outer = JSON.parse(output);
90
+ const text = typeof outer.response === 'string' ? outer.response : typeof outer.result === 'string' ? outer.result : outer.output;
91
+ if (typeof text !== 'string') throw new Error('Agy did not return a text response');
92
+ const clean = text.trim().replace(/^```json\s*/i, '').replace(/\s*```$/, '');
93
+ return JSON.parse(clean);
94
+ }
95
+
96
+ function askAgy(prompt) {
97
+ const output = run(agy, ['--dangerously-skip-permissions', '--output-format', 'json', '--effort', 'medium', '--mode', 'plan', `--print=${prompt}`], { timeout: 600_000 });
98
+ return parseAgyResponse(output);
99
+ }
100
+
101
+ function validateDiscussion(value) {
102
+ if (!value || typeof value !== 'object') throw new Error('Agy discussion must be a JSON object');
103
+ if (typeof value.approved !== 'boolean' || !['high', 'normal', 'low'].includes(value.priority) ||
104
+ typeof value.instruction !== 'string' || !value.instruction.trim() ||
105
+ !Array.isArray(value.evidence) || value.evidence.length === 0 || value.evidence.some(item => typeof item !== 'string' || !item.trim())) {
106
+ throw new Error('Agy discussion omitted approved, priority, instruction or evidence');
107
+ }
108
+ return value;
109
+ }
110
+
111
+ function validateConfirmation(value) {
112
+ if (!value || typeof value !== 'object' || typeof value.approved !== 'boolean' || typeof value.reason !== 'string') {
113
+ throw new Error('Agy confirmation must include approved and reason');
114
+ }
115
+ return value;
116
+ }
117
+
118
+ function reviewHistory(roundDir) {
119
+ const session = option('--session');
120
+ const execution = option('--execution');
121
+ const historyFile = option('--history');
122
+ if (historyFile) {
123
+ const history = JSON.parse(readFileSync(resolve(root, historyFile), 'utf8'));
124
+ writeFileSync(join(roundDir, 'history.json'), JSON.stringify(history, null, 2) + '\n');
125
+ return { source: historyFile, history };
126
+ }
127
+ if (session) {
128
+ const review = jsonCommand(process.execPath, [memoryCli, '--root', root, 'session', 'review', session]);
129
+ writeFileSync(join(roundDir, 'history.json'), JSON.stringify(review, null, 2) + '\n');
130
+ return { source: `session:${session}`, history: review };
131
+ }
132
+ if (execution) {
133
+ const project = option('--project', 'workflow-evolve');
134
+ const review = jsonCommand(process.execPath, [memoryCli, '--root', root, 'evolve', 'review', execution, '--project', project]);
135
+ writeFileSync(join(roundDir, 'history.json'), JSON.stringify(review, null, 2) + '\n');
136
+ return { source: `execution:${execution}`, history: review };
137
+ }
138
+ const history = { signals: [], note: 'No committed Session/Skill receipt was supplied for this round.' };
139
+ writeFileSync(join(roundDir, 'history.json'), JSON.stringify(history, null, 2) + '\n');
140
+ return { source: 'none', history };
141
+ }
142
+
143
+ function promptForDiscussion(roundDir, baseline, history, previous) {
144
+ const instruction = [
145
+ 'You are the Agy discussion gate for workflow-evolve.',
146
+ `Read the Skill entry at ${entry} and the round files in ${roundDir}.`,
147
+ 'Review the real Codex task result, memory search trace, and supplied execution history.',
148
+ 'Propose one minimal Skill instruction that fixes the attributed failure while preserving the passing scenario.',
149
+ 'Return strict JSON with fields approved, priority, instruction, when, evidence, rationale, needs_revision.',
150
+ 'approved is true only when the suggestion is evidence-backed and bounded. priority is high, normal, or low.',
151
+ 'instruction must be one concise line. evidence must be an array of source strings. Do not edit files.',
152
+ `Previous Agy response: ${previous ? JSON.stringify(previous) : 'none'}`,
153
+ `Baseline observations: ${JSON.stringify(baseline)}`,
154
+ `History: ${JSON.stringify(history)}`,
155
+ ].join('\n');
156
+ return askAgy(instruction);
157
+ }
158
+
159
+ function promptForConfirmation(roundDir, discussion, replay) {
160
+ return askAgy([
161
+ 'You are the final Agy confirmation gate for workflow-evolve.',
162
+ `Read the Skill entry at ${entry} and the round files in ${roundDir}.`,
163
+ 'Confirm whether the proposed Skill change is safe to apply after the baseline/candidate replay.',
164
+ 'Return strict JSON with fields approved, reason, required_changes. approved must be false if any baseline pass regresses, the evidence is missing, or the replay is incomplete.',
165
+ `Discussion: ${JSON.stringify(discussion)}`,
166
+ `Replay receipt: ${JSON.stringify(replay)}`,
167
+ ].join('\n'));
168
+ }
169
+
170
+ try {
171
+ for (let round = 1; round <= iterations; round += 1) {
172
+ const roundDir = join(outputDir, `round-${round}`);
173
+ mkdirSync(roundDir, { recursive: true });
174
+ const base = git(['rev-parse', 'HEAD']);
175
+ const baseline = scenarioSet.map(scenario => ({ id: scenario.id, expected: scenario.input?.expected,
176
+ observation: runReplay(scenario, base) }));
177
+ writeFileSync(join(roundDir, 'baseline.json'), JSON.stringify(baseline, null, 2) + '\n');
178
+ const regressions = baseline.filter(item => scenarioSet.find(scenario => scenario.id === item.id)?.baseline && !item.observation.passed);
179
+ if (regressions.length) {
180
+ state.rounds.push({ round, base, status: 'regression_detected', regressions });
181
+ break;
182
+ }
183
+ const unresolved = baseline.filter(item => {
184
+ const scenario = scenarioSet.find(candidate => candidate.id === item.id);
185
+ return scenario?.baseline === false && !item.observation.passed;
186
+ });
187
+ scenarioSet = scenarioSet.map(scenario => {
188
+ const result = baseline.find(item => item.id === scenario.id);
189
+ return result?.observation.passed ? { ...scenario, baseline: true } : scenario;
190
+ });
191
+ if (!unresolved.length) {
192
+ state.rounds.push({ round, base, status: 'converged', history: 'all scenarios passed' });
193
+ break;
194
+ }
195
+ const history = reviewHistory(roundDir);
196
+ let discussion;
197
+ let attempt = 0;
198
+ while (attempt <= maxRetries) {
199
+ discussion = validateDiscussion(promptForDiscussion(roundDir, baseline, history.history, discussion));
200
+ writeFileSync(join(roundDir, 'agy-discussion.json'), JSON.stringify(discussion, null, 2) + '\n');
201
+ if (discussion.approved) break;
202
+ attempt += 1;
203
+ }
204
+ if (!discussion?.approved) {
205
+ state.rounds.push({ round, base, status: 'agy_rejected', retries: attempt, history: history.source });
206
+ break;
207
+ }
208
+ const evidence = Array.isArray(discussion.evidence) ? discussion.evidence : [`workflow-evolve:round-${round}`];
209
+ const draft = jsonCommand(process.execPath, [memoryCli, '--root', root, 'evolve', 'draft', entry,
210
+ discussion.instruction, '--priority', discussion.priority, ...(discussion.when ? ['--when', discussion.when] : []),
211
+ ...evidence.flatMap(item => ['--evidence', item])]);
212
+ const draftPath = join(roundDir, 'draft.json');
213
+ writeFileSync(draftPath, JSON.stringify(draft, null, 2) + '\n');
214
+ const scenarioPath = join(roundDir, 'scenarios.json');
215
+ writeFileSync(scenarioPath, JSON.stringify(scenarioSet, null, 2) + '\n');
216
+ const replay = jsonCommand(process.execPath, [memoryCli, '--root', root, 'evolve', 'replay', draftPath, '--runner', runner, '--scenarios', scenarioPath]);
217
+ writeFileSync(join(roundDir, 'replay.json'), JSON.stringify(replay, null, 2) + '\n');
218
+ const confirmation = validateConfirmation(promptForConfirmation(roundDir, discussion, replay));
219
+ writeFileSync(join(roundDir, 'agy-confirmation.json'), JSON.stringify(confirmation, null, 2) + '\n');
220
+ const result = { round, base, draft: draft.id, replay: replay.id, history: history.source, agy: confirmation };
221
+ if (!confirmation.approved) {
222
+ state.rounds.push({ ...result, status: 'confirmation_rejected' });
223
+ break;
224
+ }
225
+ if (has('--auto')) {
226
+ const applied = jsonCommand(process.execPath, [memoryCli, '--root', root, 'evolve', 'apply', replay.id]);
227
+ const verified = scenarioSet.map(scenario => ({ id: scenario.id, observation: runReplay(scenario, applied.commit) }));
228
+ const passed = verified.every(item => item.observation.passed);
229
+ if (!passed) {
230
+ jsonCommand(process.execPath, [memoryCli, '--root', root, 'evolve', 'rollback', replay.id]);
231
+ state.rounds.push({ ...result, status: 'rolled_back', applied, verified });
232
+ break;
233
+ }
234
+ state.rounds.push({ ...result, status: 'applied', applied, verified });
235
+ } else {
236
+ state.rounds.push({ ...result, status: 'confirmed_pending_apply' });
237
+ break;
238
+ }
239
+ writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n');
240
+ }
241
+ state.status = 'completed';
242
+ state.finished_at = new Date().toISOString();
243
+ state.state_sha256 = createHash('sha256').update(JSON.stringify(state)).digest('hex');
244
+ writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n');
245
+ const report = { output_dir: outputDir, ...state };
246
+ const runDir = option('--run-dir', process.env.RUN_DIR);
247
+ const reportPath = runDir ? join(runDir, 'outputs', 'evolution-report.json') : join(outputDir, 'evolution-report.json');
248
+ mkdirSync(dirname(reportPath), { recursive: true });
249
+ const artifact = runDir ? { ...report, _meta: {
250
+ kind: 'workflow-evolution-report', schema: 'workflow-evolution/1.0', role: 'primary', alias: 'latest-workflow-evolution',
251
+ } } : report;
252
+ writeFileSync(reportPath, JSON.stringify(artifact, null, 2) + '\n');
253
+ console.log(JSON.stringify(report, null, 2));
254
+ } catch (error) {
255
+ state.status = 'failed';
256
+ state.error = error instanceof Error ? error.message : String(error);
257
+ writeFileSync(statePath, JSON.stringify(state, null, 2) + '\n');
258
+ throw error;
259
+ }
@@ -0,0 +1,124 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { readFileSync, writeFileSync } from 'node:fs';
4
+ import { posix } from 'node:path';
5
+ import { createInterface } from 'node:readline';
6
+
7
+ const [memoryCli, root, db, entry, commit, statePath, tracePath] = process.argv.slice(2);
8
+ const packageRoot = posix.dirname(entry);
9
+ const files = new Map();
10
+ const loaded = new Map();
11
+ for (const record of git('ls-tree', '-r', '-z', commit, '--', packageRoot).toString('utf8').split('\0')) {
12
+ const match = /^100(?:644|755) blob ([a-f0-9]+)\t(.+)$/s.exec(record);
13
+ if (match && /\.md$/i.test(match[2])) files.set(match[2], match[1]);
14
+ }
15
+
16
+ function git(...args) {
17
+ return execFileSync('git', args, { cwd: root, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
18
+ }
19
+
20
+ const toolDefinitions = [
21
+ {
22
+ name: 'read_skill',
23
+ description: 'Read the bound Skill entry. Follow a declared Markdown link by supplying its destination and the path of the source document.',
24
+ annotations: { readOnlyHint: true, openWorldHint: false },
25
+ inputSchema: {
26
+ type: 'object', properties: { destination: { type: 'string' }, from: { type: 'string' } },
27
+ additionalProperties: false,
28
+ },
29
+ },
30
+ {
31
+ name: 'memory_search',
32
+ description: 'Search Agent Memory for guidance relevant to the current task.',
33
+ annotations: { readOnlyHint: true, openWorldHint: false },
34
+ inputSchema: {
35
+ type: 'object', properties: { query: { type: 'string' } }, required: ['query'], additionalProperties: false,
36
+ },
37
+ },
38
+ {
39
+ name: 'memory_get',
40
+ description: 'Read one Agent Memory item returned by memory_search.',
41
+ annotations: { readOnlyHint: true, openWorldHint: false },
42
+ inputSchema: {
43
+ type: 'object', properties: { id: { type: 'string' } }, required: ['id'], additionalProperties: false,
44
+ },
45
+ },
46
+ ];
47
+
48
+ function callMemory(...args) {
49
+ const output = execFileSync(process.execPath, [memoryCli, '--root', root, '--db', db, '--reads', tracePath, ...args], {
50
+ cwd: root, encoding: 'utf8', windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'],
51
+ });
52
+ return JSON.parse(output);
53
+ }
54
+
55
+ function readSkill({ from, destination }) {
56
+ let path = entry;
57
+ if (from !== undefined || destination !== undefined) {
58
+ const source = loaded.get(from);
59
+ if (!source || typeof destination !== 'string') {
60
+ throw new Error('Supply the destination and a previously read source path');
61
+ }
62
+ const links = [...source.markdown.matchAll(/\[[^\]]*\]\(\s*(<[^>]+>|[^\s)]+)/g)]
63
+ .map(match => match[1].replace(/^<|>$/g, ''));
64
+ const target = destination.split('#', 1)[0];
65
+ if (!target || /[\\:]/.test(target) || posix.isAbsolute(target) || !links.includes(destination)) {
66
+ throw new Error('Select a declared relative Markdown link from the source');
67
+ }
68
+ path = posix.join(posix.dirname(from), target);
69
+ }
70
+ const blob = files.get(path);
71
+ if (!blob) throw new Error(`Skill document is unavailable in the bound package: ${path}`);
72
+ const bytes = git('cat-file', 'blob', blob);
73
+ const markdown = bytes.toString('utf8');
74
+ loaded.set(path, { markdown, sha256: createHash('sha256').update(bytes).digest('hex') });
75
+ writeFileSync(statePath, JSON.stringify([...loaded].map(([path, { sha256 }]) => ({ path, sha256 }))));
76
+ return { path, markdown };
77
+ }
78
+
79
+ function getMemory(id) {
80
+ const { searches } = JSON.parse(readFileSync(tracePath, 'utf8'));
81
+ const search = searches.findLast(item => item.returned_ids.includes(id));
82
+ if (!search) throw new Error('Select a memory ID returned by a search in this replay');
83
+ return callMemory('memory', 'get', id, '--from-search', search.search_id);
84
+ }
85
+
86
+ async function handle(line) {
87
+ const request = JSON.parse(line);
88
+ if (request.id === undefined) return;
89
+ try {
90
+ let value;
91
+ switch (request.method) {
92
+ case 'initialize':
93
+ value = { protocolVersion: request.params?.protocolVersion, capabilities: { tools: {} }, serverInfo: { name: 'workflow-evolve-memory', version: '1.0.0' } };
94
+ break;
95
+ case 'ping': value = {}; break;
96
+ case 'tools/list': value = { tools: toolDefinitions }; break;
97
+ case 'tools/call': {
98
+ const name = request.params?.name;
99
+ const args = request.params?.arguments ?? {};
100
+ if (name === 'read_skill') value = readSkill(args);
101
+ else if (name === 'memory_search' && typeof args.query === 'string' && args.query.trim()) value = callMemory('memory', 'search', args.query);
102
+ else if (name === 'memory_get' && typeof args.id === 'string' && args.id.trim()) value = getMemory(args.id);
103
+ else throw new Error(`Unsupported memory tool call: ${name}`);
104
+ break;
105
+ }
106
+ default: process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, error: { code: -32601, message: 'Method not found' } }) + '\n'); return;
107
+ }
108
+ const result = request.method === 'tools/call'
109
+ ? { content: [{ type: 'text', text: JSON.stringify(value) }] }
110
+ : value;
111
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id, result }) + '\n');
112
+ } catch (error) {
113
+ const message = error instanceof Error ? error.message : String(error);
114
+ if (request.method === 'tools/call') {
115
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id,
116
+ result: { isError: true, content: [{ type: 'text', text: message }] } }) + '\n');
117
+ } else {
118
+ process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: request.id,
119
+ error: { code: -32000, message } }) + '\n');
120
+ }
121
+ }
122
+ }
123
+
124
+ for await (const line of createInterface({ input: process.stdin, crlfDelay: Infinity })) await handle(line.replace(/^\uFEFF/, ''));
@@ -0,0 +1,23 @@
1
+ [
2
+ { "id": "session-run", "path": "skills/ew-orchestrate/references/orchestrator-run-loop.md" },
3
+ { "id": "ew-orchestrate", "path": "skills/ew-orchestrate/references/ew-orchestrate.md" },
4
+ { "id": "ew-companion", "path": "skills/ew-orchestrate/references/companion-route.md" },
5
+ { "id": "ew-brainstorm", "path": "skills/ew-orchestrate/steps/ew-brainstorm/SKILL.md" },
6
+ { "id": "ew-analyze", "path": "skills/ew-orchestrate/steps/ew-analyze/references/workflow.md" },
7
+ { "id": "ew-plan", "path": "skills/ew-orchestrate/steps/ew-plan/references/workflow.md" },
8
+ { "id": "ew-execute", "path": "skills/ew-orchestrate/steps/ew-execute/references/workflow.md" },
9
+ { "id": "ew-review", "path": "skills/ew-orchestrate/steps/ew-review/references/workflow.md" },
10
+ { "id": "ew-odyssey", "path": "skills/ew-odyssey/references/odyssey-base.md" },
11
+ { "id": "ew-odyssey-debug", "path": "skills/ew-odyssey/references/odyssey-debug.md" },
12
+ { "id": "ew-odyssey-improve", "path": "skills/ew-odyssey/references/odyssey-improve.md" },
13
+ { "id": "ew-odyssey-planex", "path": "skills/ew-odyssey/references/odyssey-planex.md" },
14
+ { "id": "ew-odyssey-review", "path": "skills/ew-odyssey/references/odyssey-review.md" },
15
+ { "id": "ew-odyssey-security", "path": "skills/ew-odyssey/references/odyssey-security.md" },
16
+ { "id": "ew-odyssey-defensive", "path": "skills/ew-odyssey/references/odyssey-defensive.md" },
17
+ { "id": "ew-odyssey-ui", "path": "skills/ew-odyssey/references/odyssey-ui.md" },
18
+ { "id": "swarm", "path": "skills/team-swarm/specs/swarm-protocol.md" },
19
+ { "id": "knowledge", "path": "skills/ew-orchestrate/references/knowledge-route.md" },
20
+ { "id": "ew-skill-design", "path": "skills/ew-skill-design/references/package-contract.md" },
21
+ { "id": "workflow-evolve", "path": "skills/workflow-evolve/references/auto-loop.md" },
22
+ { "id": "release-gate", "path": "skills/release-gate/SKILL.md" }
23
+ ]