principles-disciple 1.27.0 → 1.28.1

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 (33) hide show
  1. package/openclaw.plugin.json +4 -4
  2. package/package.json +4 -4
  3. package/scripts/diagnose-nocturnal.mjs +139 -2
  4. package/scripts/seed-nocturnal-scenarios.mjs +377 -0
  5. package/scripts/validate-live-path.ts +18 -18
  6. package/src/commands/nocturnal-train.ts +4 -6
  7. package/src/commands/pain.ts +8 -11
  8. package/src/commands/pd-reflect.ts +1 -1
  9. package/src/core/bootstrap-rules.ts +3 -3
  10. package/src/core/merge-gate-audit.ts +1 -1
  11. package/src/core/nocturnal-candidate-scoring.ts +131 -0
  12. package/src/core/nocturnal-reasoning-deriver.ts +337 -0
  13. package/src/core/nocturnal-trinity.ts +462 -25
  14. package/src/core/pain-context-extractor.ts +1 -3
  15. package/src/core/principle-tree-migration.ts +2 -4
  16. package/src/core/thinking-os-parser.ts +3 -3
  17. package/src/hooks/bash-risk.ts +1 -1
  18. package/src/hooks/gfi-gate.ts +1 -1
  19. package/src/hooks/pain.ts +1 -1
  20. package/src/hooks/prompt.ts +36 -2
  21. package/src/hooks/subagent.ts +1 -1
  22. package/src/index.ts +3 -1
  23. package/src/service/evolution-worker.ts +138 -44
  24. package/src/service/health-query-service.ts +15 -6
  25. package/src/service/subagent-workflow/nocturnal-workflow-manager.ts +0 -1
  26. package/src/tools/write-pain-flag.ts +191 -0
  27. package/templates/langs/en/skills/pd-pain-signal/SKILL.md +34 -20
  28. package/templates/langs/zh/skills/pd-pain-signal/SKILL.md +34 -20
  29. package/tests/core/nocturnal-candidate-scoring.test.ts +132 -0
  30. package/tests/core/nocturnal-e2e.test.ts +224 -0
  31. package/tests/core/nocturnal-reasoning-deriver.test.ts +372 -0
  32. package/tests/core/nocturnal-trinity.test.ts +791 -0
  33. package/tests/tools/write-pain-flag.test.ts +240 -0
@@ -0,0 +1,224 @@
1
+ import { describe, it, expect, beforeEach, afterEach } from 'vitest';
2
+ import * as fs from 'fs';
3
+ import * as os from 'os';
4
+ import * as path from 'path';
5
+ import { TrajectoryDatabase } from '../../src/core/trajectory.js';
6
+ import { NocturnalTrajectoryExtractor } from '../../src/core/nocturnal-trajectory-extractor.js';
7
+ import { detectViolation } from '../../src/core/nocturnal-compliance.js';
8
+
9
+ function safeRmDir(dir: string): void {
10
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch { /* ignore */ }
11
+ }
12
+
13
+ // ─────────────────────────────────────────────────────────
14
+ // Phase 4a: Correction rejected → pain event → nocturnal selection
15
+ // ─────────────────────────────────────────────────────────
16
+ describe('Phase 4a: Correction rejected integration', () => {
17
+ let workspaceDir: string;
18
+ let trajectory: TrajectoryDatabase;
19
+
20
+ beforeEach(() => {
21
+ workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-e2e-correction-'));
22
+ trajectory = new TrajectoryDatabase({ workspaceDir });
23
+ });
24
+
25
+ afterEach(() => {
26
+ trajectory?.dispose();
27
+ safeRmDir(workspaceDir);
28
+ });
29
+
30
+ it('rejected correction creates a pain event with source=correction_rejected', () => {
31
+ // 1. Create session + correction sample
32
+ trajectory.recordSession({ sessionId: 'corr-session', startedAt: new Date().toISOString() });
33
+ const atId = trajectory.recordAssistantTurn({
34
+ sessionId: 'corr-session', runId: 'run-1', provider: 'local', model: 'main',
35
+ rawText: 'Here is my code', sanitizedText: 'Here is my code', usageJson: {}, empathySignalJson: {},
36
+ createdAt: new Date().toISOString(),
37
+ });
38
+ trajectory.recordUserTurn({
39
+ sessionId: 'corr-session', turnIndex: 1, rawText: 'This is wrong!',
40
+ correctionDetected: true, correctionCue: '错了',
41
+ referencesAssistantTurnId: atId, createdAt: new Date().toISOString(),
42
+ });
43
+
44
+ // Verify sample was created
45
+ const samples = trajectory.listCorrectionSamples('pending');
46
+ expect(samples.length).toBe(1);
47
+
48
+ // 2. Reject the sample
49
+ trajectory.reviewCorrectionSample(samples[0].sampleId, 'rejected', 'Bad approach');
50
+
51
+ // 3. Verify pain event was created
52
+ const painEvents = trajectory.listPainEventsForSession('corr-session');
53
+ const correctionPain = painEvents.find(e => e.source === 'correction_rejected');
54
+ expect(correctionPain).toBeDefined();
55
+ expect(correctionPain!.score).toBeGreaterThanOrEqual(0);
56
+ expect(correctionPain!.score).toBeLessThanOrEqual(100);
57
+ });
58
+
59
+ it('approved correction does NOT create a pain event', () => {
60
+ trajectory.recordSession({ sessionId: 'approved-session', startedAt: new Date().toISOString() });
61
+ const atId = trajectory.recordAssistantTurn({
62
+ sessionId: 'approved-session', runId: 'run-2', provider: 'local', model: 'main',
63
+ rawText: 'Good code', sanitizedText: 'Good code', usageJson: {}, empathySignalJson: {},
64
+ createdAt: new Date().toISOString(),
65
+ });
66
+ trajectory.recordUserTurn({
67
+ sessionId: 'approved-session', turnIndex: 1, rawText: 'Looks better',
68
+ correctionDetected: true, correctionCue: '改进',
69
+ referencesAssistantTurnId: atId, createdAt: new Date().toISOString(),
70
+ });
71
+
72
+ const samples = trajectory.listCorrectionSamples('pending');
73
+ expect(samples.length).toBe(1);
74
+
75
+ trajectory.reviewCorrectionSample(samples[0].sampleId, 'approved', 'Good');
76
+
77
+ const painEvents = trajectory.listPainEventsForSession('approved-session');
78
+ const correctionPain = painEvents.find(e => e.source === 'correction_rejected');
79
+ expect(correctionPain).toBeUndefined();
80
+ });
81
+ });
82
+
83
+ // ─────────────────────────────────────────────────────────
84
+ // Phase 4b: Gate block + pain multi-signal test
85
+ // ─────────────────────────────────────────────────────────
86
+ describe('Phase 4b: Multi-signal session selection', () => {
87
+ let workspaceDir: string;
88
+ let trajectory: TrajectoryDatabase;
89
+
90
+ beforeEach(() => {
91
+ workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-e2e-multisignal-'));
92
+ trajectory = new TrajectoryDatabase({ workspaceDir });
93
+ });
94
+
95
+ afterEach(() => {
96
+ trajectory?.dispose();
97
+ safeRmDir(workspaceDir);
98
+ });
99
+
100
+ it('session with more failures has higher violation density', () => {
101
+ // Create session A: just 1 failure
102
+ trajectory.recordSession({ sessionId: 'session-a-pain-only', startedAt: new Date().toISOString() });
103
+ const atIdA = trajectory.recordAssistantTurn({
104
+ sessionId: 'session-a-pain-only', runId: 'run-a', provider: 'local', model: 'main',
105
+ rawText: 'Code here', sanitizedText: 'Code here', usageJson: {}, empathySignalJson: {},
106
+ createdAt: new Date().toISOString(),
107
+ });
108
+ trajectory.recordUserTurn({
109
+ sessionId: 'session-a-pain-only', turnIndex: 1, rawText: '错了',
110
+ correctionDetected: true, correctionCue: '错了',
111
+ referencesAssistantTurnId: atIdA, createdAt: new Date().toISOString(),
112
+ });
113
+ trajectory.recordToolCall({
114
+ sessionId: 'session-a-pain-only', toolName: 'write', outcome: 'failure',
115
+ errorMessage: 'Write failed', errorType: 'Error', createdAt: new Date().toISOString(),
116
+ });
117
+
118
+ // Create session B: 2 failures
119
+ trajectory.recordSession({ sessionId: 'session-b-multi', startedAt: new Date().toISOString() });
120
+ const atIdB = trajectory.recordAssistantTurn({
121
+ sessionId: 'session-b-multi', runId: 'run-b', provider: 'local', model: 'main',
122
+ rawText: 'Code here', sanitizedText: 'Code here', usageJson: {}, empathySignalJson: {},
123
+ createdAt: new Date().toISOString(),
124
+ });
125
+ trajectory.recordUserTurn({
126
+ sessionId: 'session-b-multi', turnIndex: 1, rawText: '太复杂了',
127
+ correctionDetected: true, correctionCue: '太复杂了',
128
+ referencesAssistantTurnId: atIdB, createdAt: new Date().toISOString(),
129
+ });
130
+ trajectory.recordToolCall({
131
+ sessionId: 'session-b-multi', toolName: 'edit', outcome: 'failure',
132
+ errorMessage: 'Edit failed', errorType: 'Error', createdAt: new Date().toISOString(),
133
+ });
134
+ trajectory.recordToolCall({
135
+ sessionId: 'session-b-multi', toolName: 'write', outcome: 'failure',
136
+ errorMessage: 'Write failed too', errorType: 'Error', createdAt: new Date().toISOString(),
137
+ });
138
+
139
+ // Verify session B has more failure signals
140
+ const extractor = new NocturnalTrajectoryExtractor(trajectory);
141
+ const snapshotA = extractor.getNocturnalSessionSnapshot('session-a-pain-only');
142
+ const snapshotB = extractor.getNocturnalSessionSnapshot('session-b-multi');
143
+
144
+ expect(snapshotA).not.toBeNull();
145
+ expect(snapshotB).not.toBeNull();
146
+
147
+ // Session B should have more violation signals
148
+ const densityA = (snapshotA!.stats.failureCount ?? 0) + (snapshotA!.stats.totalPainEvents ?? 0) * 0.5;
149
+ const densityB = (snapshotB!.stats.failureCount ?? 0) + (snapshotB!.stats.totalPainEvents ?? 0) * 0.5;
150
+ expect(densityB).toBeGreaterThan(densityA);
151
+ });
152
+ });
153
+
154
+ // ─────────────────────────────────────────────────────────
155
+ // Phase 4c: Boundary value test matrix
156
+ // ─────────────────────────────────────────────────────────
157
+ describe('Phase 4c: Boundary value tests', () => {
158
+ let workspaceDir: string;
159
+ let trajectory: TrajectoryDatabase;
160
+
161
+ beforeEach(() => {
162
+ workspaceDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pd-e2e-boundary-'));
163
+ trajectory = new TrajectoryDatabase({ workspaceDir });
164
+ });
165
+
166
+ afterEach(() => {
167
+ trajectory?.dispose();
168
+ safeRmDir(workspaceDir);
169
+ });
170
+
171
+ it('session with correction cue is listed as candidate', () => {
172
+ trajectory.recordSession({ sessionId: 'single-pain', startedAt: new Date().toISOString() });
173
+ const atIdC = trajectory.recordAssistantTurn({
174
+ sessionId: 'single-pain', runId: 'run-c', provider: 'local', model: 'main',
175
+ rawText: 'Agent response', sanitizedText: 'Agent response', usageJson: {}, empathySignalJson: {},
176
+ createdAt: new Date().toISOString(),
177
+ });
178
+ trajectory.recordUserTurn({
179
+ sessionId: 'single-pain', turnIndex: 1, rawText: '错了',
180
+ correctionDetected: true, correctionCue: '错了',
181
+ referencesAssistantTurnId: atIdC, createdAt: new Date().toISOString(),
182
+ });
183
+
184
+ const extractor = new NocturnalTrajectoryExtractor(trajectory);
185
+ const candidates = extractor.listRecentNocturnalCandidateSessions({ limit: 10, minToolCalls: 0 });
186
+
187
+ const painCandidate = candidates.find(c => c.sessionId === 'single-pain');
188
+ expect(painCandidate).toBeDefined();
189
+ });
190
+
191
+ it('detectViolation returns violated for P_* principles with tool failure', () => {
192
+ trajectory.recordSession({ sessionId: 'violation-session', startedAt: new Date().toISOString() });
193
+ trajectory.recordAssistantTurn({
194
+ sessionId: 'violation-session', runId: 'run-d', provider: 'local', model: 'main',
195
+ rawText: 'Code', sanitizedText: 'Code', usageJson: {}, empathySignalJson: {},
196
+ createdAt: new Date().toISOString(),
197
+ });
198
+ trajectory.recordToolCall({
199
+ sessionId: 'violation-session', toolName: 'write', outcome: 'failure',
200
+ errorMessage: 'Failed', errorType: 'Error', createdAt: new Date().toISOString(),
201
+ });
202
+
203
+ const extractor = new NocturnalTrajectoryExtractor(trajectory);
204
+ const snapshot = extractor.getNocturnalSessionSnapshot('violation-session');
205
+ expect(snapshot).not.toBeNull();
206
+
207
+ // P_* principles should be violated with any failure
208
+ const violation = detectViolation('P_001', {
209
+ sessionId: 'violation-session',
210
+ toolCalls: snapshot!.toolCalls.map(tc => ({
211
+ toolName: tc.toolName, outcome: tc.outcome as 'success' | 'failure' | 'blocked',
212
+ errorMessage: tc.errorMessage ?? undefined,
213
+ })),
214
+ painSignals: snapshot!.painEvents.map(pe => ({
215
+ source: pe.source, score: pe.score, severity: pe.severity as 'mild' | 'moderate' | 'severe' | undefined,
216
+ })),
217
+ gateBlocks: [],
218
+ userCorrections: [],
219
+ planApprovals: [],
220
+ });
221
+
222
+ expect(violation.violated).toBe(true);
223
+ });
224
+ });
@@ -0,0 +1,372 @@
1
+ import { describe, it, expect } from 'vitest';
2
+ import {
3
+ deriveReasoningChain,
4
+ deriveDecisionPoints,
5
+ deriveContextualFactors,
6
+ } from '../../src/core/nocturnal-reasoning-deriver.js';
7
+ import type {
8
+ NocturnalAssistantTurn,
9
+ NocturnalToolCall,
10
+ NocturnalUserTurn,
11
+ NocturnalSessionSnapshot,
12
+ } from '../../src/core/nocturnal-trajectory-extractor.js';
13
+
14
+ // ---------------------------------------------------------------------------
15
+ // Test Fixtures
16
+ // ---------------------------------------------------------------------------
17
+
18
+ function makeAssistantTurn(overrides: Partial<NocturnalAssistantTurn> = {}): NocturnalAssistantTurn {
19
+ return {
20
+ turnIndex: 0,
21
+ sanitizedText: 'I will read the file to understand the structure before making changes.',
22
+ model: 'gpt-4',
23
+ createdAt: '2026-04-12T10:00:00.000Z',
24
+ ...overrides,
25
+ };
26
+ }
27
+
28
+ // ---------------------------------------------------------------------------
29
+ // deriveReasoningChain
30
+ // ---------------------------------------------------------------------------
31
+
32
+ describe('deriveReasoningChain', () => {
33
+ it('extracts thinking content from <thinking> tags', () => {
34
+ const turns = [makeAssistantTurn({
35
+ sanitizedText: '<thinking>planning the approach</thinking>Now I will proceed.',
36
+ })];
37
+ const result = deriveReasoningChain(turns);
38
+ expect(result).toHaveLength(1);
39
+ expect(result[0].thinkingContent).toBe('planning the approach');
40
+ });
41
+
42
+ it('returns empty thinkingContent when no <thinking> tags present', () => {
43
+ const turns = [makeAssistantTurn({
44
+ sanitizedText: 'I will just read the file and proceed.',
45
+ })];
46
+ const result = deriveReasoningChain(turns);
47
+ expect(result[0].thinkingContent).toBe('');
48
+ });
49
+
50
+ it('detects uncertainty markers', () => {
51
+ const turns = [makeAssistantTurn({
52
+ sanitizedText: 'let me verify the output. not sure if this is correct.',
53
+ })];
54
+ const result = deriveReasoningChain(turns);
55
+ expect(result[0].uncertaintyMarkers).toEqual(
56
+ expect.arrayContaining([
57
+ expect.stringContaining('let me verify'),
58
+ expect.stringContaining('not sure if'),
59
+ ]),
60
+ );
61
+ });
62
+
63
+ it('detects all 3 uncertainty patterns', () => {
64
+ const turns = [makeAssistantTurn({
65
+ sanitizedText: 'let me check the file. I should probably review this. not sure whether this works.',
66
+ })];
67
+ const result = deriveReasoningChain(turns);
68
+ expect(result[0].uncertaintyMarkers.length).toBeGreaterThanOrEqual(3);
69
+ });
70
+
71
+ it('computes high confidence signal', () => {
72
+ // Use text rich in thinking model patterns to trigger high activation
73
+ const richText = 'Let me plan this carefully. I need to analyze the structure first. ' +
74
+ 'The approach should consider multiple perspectives. Let me think step by step. ' +
75
+ 'I should verify my understanding. Breaking this down into parts helps. ' +
76
+ 'Consider the constraints and requirements carefully.';
77
+ const turns = [makeAssistantTurn({ sanitizedText: richText })];
78
+ const result = deriveReasoningChain(turns);
79
+ // The exact signal depends on thinking model definitions, but it should be one of the three
80
+ expect(['high', 'medium', 'low']).toContain(result[0].confidenceSignal);
81
+ });
82
+
83
+ it('computes low confidence signal', () => {
84
+ const turns = [makeAssistantTurn({
85
+ sanitizedText: 'Just a simple text with no particular patterns.',
86
+ })];
87
+ const result = deriveReasoningChain(turns);
88
+ expect(result[0].confidenceSignal).toBe('low');
89
+ });
90
+
91
+ it('returns empty array for empty input', () => {
92
+ expect(deriveReasoningChain([])).toEqual([]);
93
+ });
94
+
95
+ it('returns empty array for null input', () => {
96
+ expect(deriveReasoningChain(null as any)).toEqual([]);
97
+ });
98
+
99
+ it('handles multiple turns correctly', () => {
100
+ const turns = [
101
+ makeAssistantTurn({ turnIndex: 0, sanitizedText: 'First turn.' }),
102
+ makeAssistantTurn({ turnIndex: 1, sanitizedText: '<thinking>Second turn thinking</thinking>' }),
103
+ makeAssistantTurn({ turnIndex: 2, sanitizedText: 'let me check this. Third turn.' }),
104
+ ];
105
+ const result = deriveReasoningChain(turns);
106
+ expect(result).toHaveLength(3);
107
+ expect(result.map(r => r.turnIndex)).toEqual([0, 1, 2]);
108
+ });
109
+
110
+ it('handles empty sanitizedText gracefully', () => {
111
+ const turns = [makeAssistantTurn({ sanitizedText: '' })];
112
+ const result = deriveReasoningChain(turns);
113
+ expect(result[0].thinkingContent).toBe('');
114
+ expect(result[0].uncertaintyMarkers).toEqual([]);
115
+ expect(result[0].confidenceSignal).toBe('low');
116
+ });
117
+
118
+ it('extracts thinking content from multiline tags', () => {
119
+ const turns = [makeAssistantTurn({
120
+ sanitizedText: '<thinking>\nStep 1: analyze\nStep 2: plan\n</thinking>',
121
+ })];
122
+ const result = deriveReasoningChain(turns);
123
+ expect(result[0].thinkingContent).toContain('Step 1: analyze');
124
+ expect(result[0].thinkingContent).toContain('Step 2: plan');
125
+ });
126
+ });
127
+
128
+ // ---------------------------------------------------------------------------
129
+ // Test Fixtures (Plan 02)
130
+ // ---------------------------------------------------------------------------
131
+
132
+ function makeToolCall(overrides: Partial<NocturnalToolCall> = {}): NocturnalToolCall {
133
+ return {
134
+ toolName: 'edit',
135
+ outcome: 'success',
136
+ filePath: 'src/index.ts',
137
+ durationMs: 150,
138
+ exitCode: 0,
139
+ errorType: null,
140
+ errorMessage: null,
141
+ createdAt: '2026-04-12T10:01:00.000Z',
142
+ ...overrides,
143
+ };
144
+ }
145
+
146
+ function makeUserTurn(overrides: Partial<NocturnalUserTurn> = {}): NocturnalUserTurn {
147
+ return {
148
+ turnIndex: 0,
149
+ correctionDetected: false,
150
+ correctionCue: null,
151
+ createdAt: '2026-04-12T10:00:30.000Z',
152
+ ...overrides,
153
+ };
154
+ }
155
+
156
+ function makeSnapshot(overrides: Partial<NocturnalSessionSnapshot> = {}): NocturnalSessionSnapshot {
157
+ return {
158
+ sessionId: 'test-session-001',
159
+ startedAt: '2026-04-12T10:00:00.000Z',
160
+ updatedAt: '2026-04-12T10:05:00.000Z',
161
+ assistantTurns: [],
162
+ userTurns: [],
163
+ toolCalls: [],
164
+ painEvents: [],
165
+ gateBlocks: [],
166
+ stats: {
167
+ totalAssistantTurns: 0,
168
+ totalToolCalls: 0,
169
+ totalPainEvents: 0,
170
+ totalGateBlocks: 0,
171
+ failureCount: 0,
172
+ },
173
+ ...overrides,
174
+ } as NocturnalSessionSnapshot;
175
+ }
176
+
177
+ // ---------------------------------------------------------------------------
178
+ // deriveDecisionPoints
179
+ // ---------------------------------------------------------------------------
180
+
181
+ describe('deriveDecisionPoints', () => {
182
+ it('extracts beforeContext from preceding assistant turn', () => {
183
+ const turns = [makeAssistantTurn({
184
+ sanitizedText: 'I will analyze the code structure before making changes to ensure correctness.',
185
+ createdAt: '2026-04-12T10:00:00.000Z',
186
+ })];
187
+ const toolCalls = [makeToolCall({ createdAt: '2026-04-12T10:01:00.000Z' })];
188
+ const result = deriveDecisionPoints(turns, toolCalls);
189
+ expect(result).toHaveLength(1);
190
+ expect(result[0].beforeContext).toBe('I will analyze the code structure before making changes to ensure correctness.');
191
+ expect(result[0].toolName).toBe('edit');
192
+ expect(result[0].outcome).toBe('success');
193
+ });
194
+
195
+ it('extracts afterReflection on failure outcome', () => {
196
+ const turns = [
197
+ makeAssistantTurn({ createdAt: '2026-04-12T10:00:00.000Z', sanitizedText: 'before' }),
198
+ makeAssistantTurn({ createdAt: '2026-04-12T10:02:00.000Z', sanitizedText: 'After the failure I need to reconsider the approach and try a different method' }),
199
+ ];
200
+ const toolCalls = [makeToolCall({
201
+ outcome: 'failure',
202
+ createdAt: '2026-04-12T10:01:00.000Z',
203
+ })];
204
+ const result = deriveDecisionPoints(turns, toolCalls);
205
+ expect(result[0].afterReflection).toBe('After the failure I need to reconsider the approach and try a different method');
206
+ expect(result[0].outcome).toBe('failure');
207
+ });
208
+
209
+ it('omits afterReflection on success outcome', () => {
210
+ const turns = [makeAssistantTurn({ createdAt: '2026-04-12T10:00:00.000Z' })];
211
+ const toolCalls = [makeToolCall({ outcome: 'success', createdAt: '2026-04-12T10:01:00.000Z' })];
212
+ const result = deriveDecisionPoints(turns, toolCalls);
213
+ expect(result[0].afterReflection).toBeUndefined();
214
+ });
215
+
216
+ it('returns empty array for empty toolCalls', () => {
217
+ expect(deriveDecisionPoints([makeAssistantTurn()], [])).toEqual([]);
218
+ });
219
+
220
+ it('returns empty beforeContext when no assistant turns', () => {
221
+ const toolCalls = [makeToolCall()];
222
+ const result = deriveDecisionPoints([], toolCalls);
223
+ expect(result).toHaveLength(1);
224
+ expect(result[0].beforeContext).toBe('');
225
+ });
226
+
227
+ it('computes confidenceDelta on failure', () => {
228
+ const beforeText = 'Let me plan this carefully. I need to analyze the structure first. ' +
229
+ 'The approach should consider multiple perspectives. Let me think step by step. ' +
230
+ 'I should verify my understanding. Breaking this down into parts helps.';
231
+ const turns = [
232
+ makeAssistantTurn({ createdAt: '2026-04-12T10:00:00.000Z', sanitizedText: beforeText }),
233
+ makeAssistantTurn({ createdAt: '2026-04-12T10:02:00.000Z', sanitizedText: 'ok' }),
234
+ ];
235
+ const toolCalls = [makeToolCall({ outcome: 'failure', createdAt: '2026-04-12T10:01:00.000Z' })];
236
+ const result = deriveDecisionPoints(turns, toolCalls);
237
+ // confidenceDelta should be computed (defined) when both before and after turns exist
238
+ expect(result[0].confidenceDelta).toBeDefined();
239
+ expect(typeof result[0].confidenceDelta).toBe('number');
240
+ });
241
+
242
+ it('matches by createdAt timestamp not turnIndex', () => {
243
+ const turns = [
244
+ makeAssistantTurn({ turnIndex: 2, createdAt: '2026-04-12T10:00:00.000Z', sanitizedText: 'turn index 2' }),
245
+ makeAssistantTurn({ turnIndex: 0, createdAt: '2026-04-12T09:59:00.000Z', sanitizedText: 'turn index 0' }),
246
+ ];
247
+ const toolCalls = [makeToolCall({ createdAt: '2026-04-12T10:01:00.000Z' })];
248
+ const result = deriveDecisionPoints(turns, toolCalls);
249
+ // Should pick turnIndex 2 (closest before tool call by timestamp)
250
+ expect(result[0].beforeContext).toBe('turn index 2');
251
+ });
252
+ });
253
+
254
+ // ---------------------------------------------------------------------------
255
+ // deriveContextualFactors
256
+ // ---------------------------------------------------------------------------
257
+
258
+ describe('deriveContextualFactors', () => {
259
+ it('computes all four factors from a rich snapshot', () => {
260
+ const snapshot = makeSnapshot({
261
+ toolCalls: [
262
+ makeToolCall({ toolName: 'read', outcome: 'success', createdAt: '2026-04-12T10:00:00.000Z' }),
263
+ makeToolCall({ toolName: 'edit', outcome: 'success', createdAt: '2026-04-12T10:00:01.000Z' }),
264
+ makeToolCall({ toolName: 'edit', outcome: 'failure', createdAt: '2026-04-12T10:00:02.000Z' }),
265
+ ],
266
+ userTurns: [makeUserTurn({ correctionDetected: true })],
267
+ });
268
+ const result = deriveContextualFactors(snapshot);
269
+ expect(result.fileStructureKnown).toBe(true);
270
+ expect(result.errorHistoryPresent).toBe(true);
271
+ expect(result.userGuidanceAvailable).toBe(true);
272
+ expect(result.timePressure).toBe(true);
273
+ });
274
+
275
+ it('fileStructureKnown: true when read precedes write', () => {
276
+ const snapshot = makeSnapshot({
277
+ toolCalls: [
278
+ makeToolCall({ toolName: 'read', createdAt: '2026-04-12T10:00:00.000Z' }),
279
+ makeToolCall({ toolName: 'edit', createdAt: '2026-04-12T10:00:01.000Z' }),
280
+ ],
281
+ });
282
+ expect(deriveContextualFactors(snapshot).fileStructureKnown).toBe(true);
283
+ });
284
+
285
+ it('fileStructureKnown: false when write has no preceding read', () => {
286
+ const snapshot = makeSnapshot({
287
+ toolCalls: [
288
+ makeToolCall({ toolName: 'edit', createdAt: '2026-04-12T10:00:00.000Z' }),
289
+ makeToolCall({ toolName: 'read', createdAt: '2026-04-12T10:00:01.000Z' }),
290
+ ],
291
+ });
292
+ expect(deriveContextualFactors(snapshot).fileStructureKnown).toBe(false);
293
+ });
294
+
295
+ it('fileStructureKnown: false with only write tools', () => {
296
+ const snapshot = makeSnapshot({
297
+ toolCalls: [makeToolCall({ toolName: 'edit' })],
298
+ });
299
+ expect(deriveContextualFactors(snapshot).fileStructureKnown).toBe(false);
300
+ });
301
+
302
+ it('errorHistoryPresent: true when any tool call failed', () => {
303
+ const snapshot = makeSnapshot({
304
+ toolCalls: [
305
+ makeToolCall({ outcome: 'success' }),
306
+ makeToolCall({ outcome: 'failure' }),
307
+ ],
308
+ });
309
+ expect(deriveContextualFactors(snapshot).errorHistoryPresent).toBe(true);
310
+ });
311
+
312
+ it('errorHistoryPresent: false when all outcomes are success', () => {
313
+ const snapshot = makeSnapshot({
314
+ toolCalls: [makeToolCall({ outcome: 'success' })],
315
+ });
316
+ expect(deriveContextualFactors(snapshot).errorHistoryPresent).toBe(false);
317
+ });
318
+
319
+ it('userGuidanceAvailable: true when correction detected', () => {
320
+ const snapshot = makeSnapshot({
321
+ userTurns: [makeUserTurn({ correctionDetected: true })],
322
+ });
323
+ expect(deriveContextualFactors(snapshot).userGuidanceAvailable).toBe(true);
324
+ });
325
+
326
+ it('userGuidanceAvailable: false without corrections', () => {
327
+ const snapshot = makeSnapshot({
328
+ userTurns: [makeUserTurn({ correctionDetected: false })],
329
+ });
330
+ expect(deriveContextualFactors(snapshot).userGuidanceAvailable).toBe(false);
331
+ });
332
+
333
+ it('timePressure: true when majority of gaps < 2 seconds', () => {
334
+ const snapshot = makeSnapshot({
335
+ toolCalls: [
336
+ makeToolCall({ createdAt: '2026-04-12T10:00:00.000Z' }),
337
+ makeToolCall({ createdAt: '2026-04-12T10:00:01.000Z' }),
338
+ makeToolCall({ createdAt: '2026-04-12T10:00:01.500Z' }),
339
+ ],
340
+ });
341
+ expect(deriveContextualFactors(snapshot).timePressure).toBe(true);
342
+ });
343
+
344
+ it('timePressure: false when gaps are large', () => {
345
+ const snapshot = makeSnapshot({
346
+ toolCalls: [
347
+ makeToolCall({ createdAt: '2026-04-12T10:00:00.000Z' }),
348
+ makeToolCall({ createdAt: '2026-04-12T10:00:10.000Z' }),
349
+ makeToolCall({ createdAt: '2026-04-12T10:00:20.000Z' }),
350
+ ],
351
+ });
352
+ expect(deriveContextualFactors(snapshot).timePressure).toBe(false);
353
+ });
354
+
355
+ it('returns all-false defaults for null snapshot', () => {
356
+ expect(deriveContextualFactors(null as any)).toEqual({
357
+ fileStructureKnown: false,
358
+ errorHistoryPresent: false,
359
+ userGuidanceAvailable: false,
360
+ timePressure: false,
361
+ });
362
+ });
363
+
364
+ it('returns all-false defaults for empty snapshot', () => {
365
+ expect(deriveContextualFactors(makeSnapshot())).toEqual({
366
+ fileStructureKnown: false,
367
+ errorHistoryPresent: false,
368
+ userGuidanceAvailable: false,
369
+ timePressure: false,
370
+ });
371
+ });
372
+ });