principles-disciple 1.32.0 → 1.34.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 (37) hide show
  1. package/openclaw.plugin.json +4 -4
  2. package/package.json +1 -1
  3. package/src/core/correction-cue-learner.ts +203 -0
  4. package/src/core/correction-types.ts +88 -0
  5. package/src/core/evolution-logger.ts +3 -3
  6. package/src/core/init.ts +67 -0
  7. package/src/service/correction-observer-types.ts +58 -0
  8. package/src/service/correction-observer-workflow-manager.ts +218 -0
  9. package/src/service/evolution-worker.ts +172 -146
  10. package/src/service/nocturnal-service.ts +4 -1
  11. package/src/service/subagent-workflow/index.ts +14 -0
  12. package/src/service/subagent-workflow/nocturnal-workflow-manager.ts +3 -1
  13. package/tests/service/evolution-worker.nocturnal.test.ts +14 -1
  14. package/tests/service/evolution-worker.timeout.test.ts +350 -0
  15. package/tests/commands/implementation-lifecycle.test.ts +0 -362
  16. package/tests/core/detection-funnel.test.ts +0 -63
  17. package/tests/core/evolution-e2e.test.ts +0 -58
  18. package/tests/core/evolution-engine-gate-integration.test.ts +0 -543
  19. package/tests/core/evolution-engine.test.ts +0 -562
  20. package/tests/core/evolution-reducer.test.ts +0 -180
  21. package/tests/core/evolution-user-stories.e2e.test.ts +0 -249
  22. package/tests/core/local-worker-routing.test.ts +0 -757
  23. package/tests/core/rule-host.test.ts +0 -389
  24. package/tests/core/trajectory-correction-pain.test.ts +0 -180
  25. package/tests/hooks/gate-edit-verification.test.ts +0 -435
  26. package/tests/hooks/llm.test.ts +0 -308
  27. package/tests/hooks/progressive-trust-gate.test.ts +0 -277
  28. package/tests/hooks/prompt.test.ts +0 -1473
  29. package/tests/index.integration.test.ts +0 -179
  30. package/tests/index.shadow-routing.integration.test.ts +0 -140
  31. package/tests/service/evolution-worker.test.ts +0 -462
  32. package/tests/service/nocturnal-service.test.ts +0 -577
  33. package/tests/service/nocturnal-workflow-manager.test.ts +0 -441
  34. package/tests/tools/critique-prompt.test.ts +0 -260
  35. package/tests/tools/deep-reflect.test.ts +0 -232
  36. package/tests/tools/model-index.test.ts +0 -246
  37. package/tests/ui/app.test.tsx +0 -114
@@ -1,180 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as os from 'os';
3
- import * as path from 'path';
4
- import { afterEach, describe, expect, it } from 'vitest';
5
- import { EvolutionReducerImpl } from '../../src/core/evolution-reducer.js';
6
-
7
- const tempDirs: string[] = [];
8
-
9
- function makeTempDir(): string {
10
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-evolution-reducer-'));
11
- tempDirs.push(dir);
12
- return dir;
13
- }
14
-
15
- afterEach(() => {
16
- for (const dir of tempDirs.splice(0)) {
17
- fs.rmSync(dir, { recursive: true, force: true });
18
- }
19
- });
20
-
21
- describe('EvolutionReducerImpl', () => {
22
- it('appends emitted events to evolution stream jsonl', () => {
23
- const workspace = makeTempDir();
24
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
25
-
26
- reducer.emitSync({
27
- ts: new Date().toISOString(),
28
- type: 'pain_detected',
29
- data: { painId: 'pain-1', painType: 'tool_failure', source: 'write', reason: 'write failed' },
30
- });
31
-
32
- const streamPath = path.join(workspace, 'memory', 'evolution.jsonl');
33
- const lines = fs.readFileSync(streamPath, 'utf8').trim().split('\n');
34
-
35
- expect(lines.length).toBeGreaterThan(0);
36
- expect(lines.some(line => JSON.parse(line).type === 'pain_detected')).toBe(true);
37
- });
38
-
39
- it('creates principle from diagnosis and auto-promotes to probation', () => {
40
- const workspace = makeTempDir();
41
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
42
-
43
- // Pain detected no longer creates principle automatically
44
- reducer.emitSync({
45
- ts: new Date().toISOString(),
46
- type: 'pain_detected',
47
- data: {
48
- painId: 'pain-1',
49
- painType: 'tool_failure',
50
- source: 'write',
51
- reason: 'Tool write failed',
52
- },
53
- });
54
-
55
- // No principle created yet
56
- expect(reducer.getCandidatePrinciples()).toHaveLength(0);
57
- expect(reducer.getProbationPrinciples()).toHaveLength(0);
58
-
59
- // Create principle from diagnostician analysis
60
- const principleId = reducer.createPrincipleFromDiagnosis({
61
- painId: 'pain-1',
62
- painType: 'tool_failure',
63
- triggerPattern: 'file write operation fails',
64
- action: 'check file permissions and disk space',
65
- source: 'write',
66
- });
67
-
68
- expect(principleId).not.toBeNull();
69
- expect(reducer.getCandidatePrinciples()).toHaveLength(0);
70
- expect(reducer.getProbationPrinciples()).toHaveLength(1);
71
- const stats = reducer.getStats();
72
- expect(stats.probationCount).toBe(1);
73
- });
74
-
75
- it('ignores protocol-token pain before creating principles', () => {
76
- const workspace = makeTempDir();
77
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
78
-
79
- reducer.emitSync({
80
- ts: new Date().toISOString(),
81
- type: 'pain_detected',
82
- data: {
83
- painId: 'pain-protocol-1',
84
- painType: 'tool_failure',
85
- source: 'llm_p_frustration_023',
86
- reason: '[EVOLUTION_ACK] previous failure context',
87
- },
88
- });
89
-
90
- expect(reducer.getCandidatePrinciples()).toHaveLength(0);
91
- expect(reducer.getProbationPrinciples()).toHaveLength(0);
92
- expect(reducer.getActivePrinciples()).toHaveLength(0);
93
- });
94
-
95
- it('opens circuit breaker after 3 subagent errors on same task', () => {
96
- const workspace = makeTempDir();
97
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
98
-
99
- for (let i = 0; i < 3; i++) {
100
- reducer.emitSync({
101
- ts: new Date(2026, 0, 1, 0, 0, i).toISOString(),
102
- type: 'pain_detected',
103
- data: {
104
- painId: `pain-${i}`,
105
- painType: 'subagent_error',
106
- source: 'subagent_error',
107
- taskId: 'task-1',
108
- reason: 'subagent failed',
109
- },
110
- });
111
- }
112
-
113
- const breakerEvents = reducer.getEventLog().filter(e => e.type === 'circuit_breaker_opened');
114
- expect(breakerEvents).toHaveLength(1);
115
- expect((breakerEvents[0].data as any).taskId).toBe('task-1');
116
- });
117
-
118
-
119
-
120
- it('promotes probation to active after feedback threshold', () => {
121
- const workspace = makeTempDir();
122
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
123
-
124
- // Create principle from diagnosis
125
- const principleId = reducer.createPrincipleFromDiagnosis({
126
- painId: 'pain-1',
127
- painType: 'tool_failure',
128
- triggerPattern: 'file write operation fails',
129
- action: 'check file permissions',
130
- source: 'write',
131
- });
132
-
133
- const principle = reducer.getProbationPrinciples()[0];
134
- reducer.recordProbationFeedback(principle.id, true);
135
- reducer.recordProbationFeedback(principle.id, true);
136
- reducer.recordProbationFeedback(principle.id, true);
137
-
138
- expect(reducer.getPrincipleById(principle.id)?.status).toBe('active');
139
- });
140
-
141
- it('rebuildState skips malformed lines without crashing', () => {
142
- const workspace = makeTempDir();
143
- const streamPath = path.join(workspace, 'memory', 'evolution.jsonl');
144
- fs.mkdirSync(path.dirname(streamPath), { recursive: true });
145
- fs.writeFileSync(streamPath, '{bad json}\n' + JSON.stringify({
146
- ts: new Date().toISOString(),
147
- type: 'pain_detected',
148
- data: { painId: 'p1', painType: 'tool_failure', source: 'write', reason: 'oops' },
149
- }) + '\n');
150
-
151
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
152
- expect(reducer.getProbationPrinciples()).toHaveLength(0);
153
- expect(reducer.getEventLog().length).toBeGreaterThan(0);
154
- });
155
-
156
- it('rolls back principle and persists blacklist', () => {
157
- const workspace = makeTempDir();
158
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
159
-
160
- // Create principle from diagnosis
161
- const principleId = reducer.createPrincipleFromDiagnosis({
162
- painId: 'pain-1',
163
- painType: 'tool_failure',
164
- triggerPattern: 'file write operation fails',
165
- action: 'check file permissions',
166
- source: 'write',
167
- });
168
-
169
- const principle = reducer.getProbationPrinciples()[0];
170
- reducer.rollbackPrinciple(principle.id, 'bad quality');
171
-
172
- const updated = reducer.getPrincipleById(principle.id);
173
- expect(updated?.status).toBe('deprecated');
174
-
175
- const blacklistPath = path.join(workspace, '.state', 'principle_blacklist.json');
176
- const blacklist = JSON.parse(fs.readFileSync(blacklistPath, 'utf8'));
177
- expect(Array.isArray(blacklist)).toBe(true);
178
- expect(blacklist[0].pattern).toContain('file write operation fails');
179
- });
180
- });
@@ -1,249 +0,0 @@
1
- import * as fs from 'fs';
2
- import * as os from 'os';
3
- import * as path from 'path';
4
- import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
5
-
6
- import { handleAfterToolCall } from '../../src/hooks/pain.js';
7
- import { handleSubagentEnded } from '../../src/hooks/subagent.js';
8
- import { handleBeforePromptBuild } from '../../src/hooks/prompt.js';
9
- import { handleEvolutionStatusCommand } from '../../src/commands/evolution-status.js';
10
- import { handlePrincipleRollbackCommand } from '../../src/commands/principle-rollback.js';
11
- import { EvolutionReducerImpl } from '../../src/core/evolution-reducer.js';
12
- import { WorkspaceContext } from '../../src/core/workspace-context.js';
13
-
14
- vi.mock('../../src/core/workspace-context.js');
15
- const tempDirs: string[] = [];
16
- const reducerCache = new Map<string, EvolutionReducerImpl>();
17
-
18
- function makeWorkspace(): string {
19
- const workspace = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-user-stories-'));
20
- tempDirs.push(workspace);
21
-
22
- fs.mkdirSync(path.join(workspace, '.principles'), { recursive: true });
23
- fs.mkdirSync(path.join(workspace, '.state'), { recursive: true });
24
- fs.mkdirSync(path.join(workspace, 'memory', 'okr'), { recursive: true });
25
-
26
- fs.writeFileSync(path.join(workspace, '.principles', 'PRINCIPLES.md'), '# Core Principles\n- Be deterministic\n');
27
- fs.writeFileSync(path.join(workspace, '.principles', 'THINKING_OS.md'), '# Thinking OS\n- First principles\n');
28
- fs.writeFileSync(path.join(workspace, '.principles', 'PROFILE.json'), JSON.stringify({ risk_paths: ['src/critical'] }));
29
- fs.writeFileSync(path.join(workspace, 'memory', 'reflection-log.md'), '# Reflection\n- Keep context short\n');
30
- fs.writeFileSync(path.join(workspace, 'memory', 'okr', 'CURRENT_FOCUS.md'), '# Focus\n- Stabilize evolution loop\n');
31
-
32
- return workspace;
33
- }
34
-
35
- function buildWctx(workspaceDir: string) {
36
- const stateDir = path.join(workspaceDir, '.state');
37
- return {
38
- workspaceDir,
39
- stateDir,
40
- config: {
41
- get: (key: string) => {
42
- if (key === 'scores.tool_failure_friction') return 30;
43
- if (key === 'scores') {
44
- return {
45
- subagent_error_penalty: 80,
46
- subagent_timeout_penalty: 65,
47
- };
48
- }
49
- if (key === 'language') return 'en';
50
- return undefined;
51
- },
52
- },
53
- eventLog: {
54
- recordToolCall: vi.fn(),
55
- recordPainSignal: vi.fn(),
56
- recordTrustChange: vi.fn(),
57
- getEmpathyStats: vi.fn().mockReturnValue({ totalEvents: 0 }),
58
- },
59
- trust: {
60
- recordFailure: vi.fn(),
61
- recordSuccess: vi.fn(),
62
- getScore: vi.fn().mockReturnValue(80),
63
- getStage: vi.fn().mockReturnValue(3),
64
- },
65
- hygiene: {
66
- recordPersistence: vi.fn(),
67
- getStats: vi.fn().mockReturnValue({ planWrites: 0, memoryWrites: 0, sessionMemoryStores: 0 }),
68
- },
69
- evolutionReducer: reducerCache.get(workspaceDir) || (() => {
70
- const r = new EvolutionReducerImpl({ workspaceDir });
71
- reducerCache.set(workspaceDir, r);
72
- return r;
73
- })(),
74
- resolve: (key: string) => {
75
- const map: Record<string, string> = {
76
- PROFILE: path.join(workspaceDir, '.principles', 'PROFILE.json'),
77
- EVOLUTION_QUEUE: path.join(workspaceDir, '.state', 'evolution_queue.json'),
78
- PAIN_FLAG: path.join(workspaceDir, '.state', '.pain_flag'),
79
- PRINCIPLES: path.join(workspaceDir, '.principles', 'PRINCIPLES.md'),
80
- THINKING_OS: path.join(workspaceDir, '.principles', 'THINKING_OS.md'),
81
- REFLECTION_LOG: path.join(workspaceDir, 'memory', 'reflection-log.md'),
82
- CURRENT_FOCUS: path.join(workspaceDir, 'memory', 'okr', 'CURRENT_FOCUS.md'),
83
- };
84
- return map[key] ?? '';
85
- },
86
- };
87
- }
88
-
89
- beforeEach(() => {
90
- vi.clearAllMocks();
91
- vi.mocked(WorkspaceContext.fromHookContext).mockImplementation((ctx: any) => buildWctx(ctx.workspaceDir));
92
- });
93
-
94
- afterEach(() => {
95
- for (const dir of tempDirs.splice(0)) {
96
- fs.rmSync(dir, { recursive: true, force: true });
97
- }
98
- reducerCache.clear();
99
- });
100
-
101
- describe('Evolution loop user stories e2e', () => {
102
- it('story 1: manual /pain intervention should emit pain signal', () => {
103
- const workspace = makeWorkspace();
104
-
105
- handleAfterToolCall(
106
- { toolName: 'pain', params: { input: 'User is frustrated' }, result: { exitCode: 0 } } as any,
107
- { workspaceDir: workspace, sessionId: 's-manual' } as any,
108
- );
109
-
110
- // Pain signal is emitted but principle is NOT created automatically
111
- // It requires diagnostician analysis to create a generalized principle
112
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
113
- expect(reducer.getProbationPrinciples()).toHaveLength(0);
114
-
115
- // After diagnostician analysis, principle is created
116
- reducer.createPrincipleFromDiagnosis({
117
- painId: 'pain-manual',
118
- painType: 'user_frustration',
119
- triggerPattern: 'user expresses frustration',
120
- action: 'pause and clarify requirements',
121
- source: 'pain',
122
- });
123
-
124
- const status = handleEvolutionStatusCommand({ config: { workspaceDir: workspace, language: 'en' } } as any);
125
- expect(status.text).toContain('probation principles: 1');
126
- });
127
-
128
- it('story 2: write failure should emit pain, create pain_flag', async () => {
129
- const workspace = makeWorkspace();
130
-
131
- handleAfterToolCall(
132
- {
133
- toolName: 'write',
134
- params: { file_path: 'src/main.ts' },
135
- error: 'Permission denied',
136
- result: { exitCode: 1 },
137
- } as any,
138
- { workspaceDir: workspace, sessionId: 's-write' } as any,
139
- );
140
-
141
- expect(fs.existsSync(path.join(workspace, '.state', '.pain_flag'))).toBe(true);
142
-
143
- // Pain signal is emitted but principle is NOT created automatically
144
- // Use buildWctx to get the cached reducer
145
- const wctx = buildWctx(workspace);
146
- expect(wctx.evolutionReducer.getProbationPrinciples()).toHaveLength(0);
147
-
148
- // After diagnostician analysis, principle is created
149
- wctx.evolutionReducer.createPrincipleFromDiagnosis({
150
- painId: 'pain-write',
151
- painType: 'tool_failure',
152
- triggerPattern: 'file write operation fails with permission denied',
153
- action: 'check file permissions before writing',
154
- source: 'write',
155
- });
156
-
157
- const promptResult = await handleBeforePromptBuild({ prompt: '', messages: [] } as any, {
158
- workspaceDir: workspace,
159
- trigger: 'user',
160
- api: { config: {}, runtime: {}, logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } },
161
- } as any);
162
-
163
- expect(promptResult?.appendSystemContext).toContain('<evolution_principles>');
164
- expect(promptResult?.appendSystemContext).toContain('status="probation"');
165
- });
166
-
167
- it('story 3: repeated subagent errors should trigger circuit breaker without breaking old flows', async () => {
168
- const workspace = makeWorkspace();
169
-
170
- for (let i = 0; i < 3; i++) {
171
- await handleSubagentEnded(
172
- {
173
- targetSessionKey: 'agent:main:subagent:diag-1',
174
- targetKind: 'subagent',
175
- reason: 'failed',
176
- outcome: 'error',
177
- } as any,
178
- { workspaceDir: workspace, sessionId: 's-subagent' } as any,
179
- );
180
- }
181
-
182
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
183
- const breaker = reducer.getEventLog().filter((e) => e.type === 'circuit_breaker_opened');
184
- expect(breaker).toHaveLength(1);
185
- });
186
-
187
- it('story 4: principle rollback should deprecate and prevent re-creating same blacklisted principle', () => {
188
- const workspace = makeWorkspace();
189
- const reducer = new EvolutionReducerImpl({ workspaceDir: workspace });
190
-
191
- // Create principle from diagnosis
192
- const principleId = reducer.createPrincipleFromDiagnosis({
193
- painId: 'pain-black-1',
194
- painType: 'tool_failure',
195
- triggerPattern: 'file write operation fails',
196
- action: 'check permissions before writing',
197
- source: 'write',
198
- });
199
-
200
- const pid = reducer.getProbationPrinciples()[0].id;
201
- const rollbackText = handlePrincipleRollbackCommand({
202
- args: `${pid} quality issue`,
203
- config: { workspaceDir: workspace, language: 'en' },
204
- } as any).text;
205
-
206
- expect(rollbackText).toContain(`Rolled back principle ${pid}`);
207
-
208
- // Attempt to create same principle again - should be blocked by blacklist
209
- reducer.createPrincipleFromDiagnosis({
210
- painId: 'pain-black-2',
211
- painType: 'tool_failure',
212
- triggerPattern: 'file write operation fails',
213
- action: 'check permissions before writing',
214
- source: 'write',
215
- });
216
-
217
- const stats = new EvolutionReducerImpl({ workspaceDir: workspace }).getStats();
218
- expect(stats.deprecatedCount).toBe(1);
219
- expect(stats.probationCount).toBe(0);
220
- });
221
-
222
- it('story 5: diagnostician completion should close only the linked evolution task', async () => {
223
- const workspace = makeWorkspace();
224
- const queuePath = path.join(workspace, '.state', 'evolution_queue.json');
225
- const painFlagPath = path.join(workspace, '.state', '.pain_flag');
226
-
227
- fs.writeFileSync(queuePath, JSON.stringify([{
228
- id: 't1',
229
- status: 'in_progress',
230
- timestamp: new Date().toISOString(),
231
- assigned_session_key: 'agent:diagnostician:diag-ok',
232
- }]));
233
- fs.writeFileSync(painFlagPath, 'status: queued\ntask_id: t1\n');
234
-
235
- await handleSubagentEnded(
236
- {
237
- targetSessionKey: 'agent:diagnostician:diag-ok',
238
- targetKind: 'subagent',
239
- reason: 'done',
240
- outcome: 'ok',
241
- } as any,
242
- { workspaceDir: workspace, sessionId: 's-ok' } as any,
243
- );
244
-
245
- const queue = JSON.parse(fs.readFileSync(queuePath, 'utf8'));
246
- expect(queue[0].status).toBe('completed');
247
- expect(fs.existsSync(painFlagPath)).toBe(false);
248
- });
249
- });