principles-disciple 1.175.0 → 1.177.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.
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'fs';
2
2
  import * as path from 'path';
3
- import { clearInjectedProbationIds, getSession, resetFriction, setInjectedProbationIds, trackFriction, decayGfi, getGfiDecayElapsed } from '../core/session-tracker.js';
3
+ import { clearInjectedProbationIds, getSession, resetFriction, setInjectedProbationIds, decayGfi, getGfiDecayElapsed } from '../core/session-tracker.js';
4
4
  import { WorkspaceContext } from '../core/workspace-context.js';
5
5
  import { defaultContextConfig } from '../types.js';
6
6
  // local-worker-routing module and its routing helpers removed entirely per PRI-448.
@@ -8,25 +8,16 @@ import { defaultContextConfig } from '../types.js';
8
8
  import { extractSummary, getHistoryVersions, parseWorkingMemorySection, workingMemoryToInjection, autoCompressFocus, safeReadCurrentFocus } from '../core/focus-history.js';
9
9
  import { PathResolver } from '../core/path-resolver.js';
10
10
  import { selectPrinciplesForInjection, DEFAULT_PRINCIPLE_BUDGET } from '../core/principle-injection.js';
11
- import { getCachedMaskedPrincipleSet, WorkflowFunnelLoader, PiAiRuntimeAdapter, EmpathyObserver, AgentScheduler, RUNTIME_V2_PRINCIPLE_BUDGET, trimToBudget, renderPrinciplesToDirectives } from '@principles/core/runtime-v2';
11
+ import { getCachedMaskedPrincipleSet, RUNTIME_V2_PRINCIPLE_BUDGET, trimToBudget, renderPrinciplesToDirectives } from '@principles/core/runtime-v2';
12
12
  import { truncateInjectionToBudget } from '@principles/core/prompt-builder';
13
13
  import { PromptActivationReader } from '../core/runtime-v2-prompt-activation-reader.js';
14
- import { matchEmpathyKeywords, loadKeywordStore, saveKeywordStore, applyKeywordUpdates, getKeywordStoreSummary, } from '../core/empathy-keyword-matcher.js';
15
- import { severityToPenalty, DEFAULT_EMPATHY_KEYWORD_CONFIG } from '../core/empathy-types.js';
16
- import { evaluatePainDiagnosticGate } from '../core/pain-diagnostic-gate.js';
17
- import { emitPainDetectedEvent, buildTrajectoryEvidence } from './pain.js';
18
- import { evaluateTriggerController } from '@principles/core/runtime-v2';
19
- import { isSharedCooldownActive, markSharedEpisodeAsDiagnosed } from './trigger-cooldown-tracker.js';
20
- import { buildEmpathyObservation, resolveSourceKind } from './raw-observation-adapter.js';
21
- import { evaluateEvidenceTriage } from './triage-adapter.js';
22
14
  import { loadFeatureFlagFromConfig } from '../core/pd-config-loader.js';
23
15
  import { safeReadIntentDoc, resetIntentDocCacheForTest } from '../core/intent-doc-reader.js';
24
16
  import { resolveIntentLang } from '../core/intent-doc-reader-adapter.js';
25
17
  import { buildIntentFrictionBlock } from '@principles/core/runtime-v2';
26
- import { CorrectionCueLearner } from '../core/correction-cue-learner.js';
27
- import { detectCorrectionCue as coreDetectCorrectionCue, escapeXml, extractMessageContent, isMinimalTrigger, } from '@principles/core/prompt-builder';
28
- import { sanitizeForEvidence } from './message-sanitize.js';
29
- import { buildAgentIdentity, buildEmpathySilenceConstraint, extractUserMessageFromPrompt, assembleHeartbeatChecklist, formatCorePrinciples, formatEvolutionPrinciples, assembleAppendSystemContext, extractPhrasesFromReason, } from './prompt-helpers.js';
18
+ import { escapeXml, extractMessageContent, isMinimalTrigger, } from '@principles/core/prompt-builder';
19
+ import { buildAgentIdentity, buildEmpathySilenceConstraint, extractUserMessageFromPrompt, assembleHeartbeatChecklist, formatCorePrinciples, formatEvolutionPrinciples, assembleAppendSystemContext, } from './prompt-helpers.js';
20
+ import { SignalCollectorHost, createSignalLlmClassifierFromConfig } from '../core/signal-collector-host.js';
30
21
  // ---------------------------------------------------------------------------
31
22
  // Static file cache — avoids re-reading rarely-changing files every message
32
23
  // ---------------------------------------------------------------------------
@@ -85,19 +76,6 @@ function cachedReadFile(filePath, workspaceDir) {
85
76
  return '';
86
77
  }
87
78
  }
88
- /**
89
- * Per-workspace empathy state. Keyed by workspaceDir to avoid cross-workspace
90
- * state pollution. Previously module-level variables.
91
- */
92
- const _empathyState = new Map();
93
- function getEmpathyState(workspaceDir) {
94
- let state = _empathyState.get(workspaceDir);
95
- if (!state) {
96
- state = { turnCounter: 0, keywordCache: null };
97
- _empathyState.set(workspaceDir, state);
98
- }
99
- return state;
100
- }
101
79
  /**
102
80
  * Reset all module-level prompt state for a workspace.
103
81
  * Intended for test isolation — call in beforeEach().
@@ -105,14 +83,30 @@ function getEmpathyState(workspaceDir) {
105
83
  export function resetPromptStateForTest(workspaceDir) {
106
84
  if (workspaceDir) {
107
85
  _staticFileCache.delete(workspaceDir);
108
- _empathyState.delete(workspaceDir);
109
86
  resetIntentDocCacheForTest(workspaceDir);
110
87
  }
111
88
  else {
112
89
  _staticFileCache.clear();
113
- _empathyState.clear();
114
90
  resetIntentDocCacheForTest();
115
91
  }
92
+ // CodeRabbit #6: 清理 host 缓存,避免 rate-limit/classifier 状态跨测试泄漏
93
+ _signalCollectorHosts.clear();
94
+ }
95
+ /**
96
+ * SignalCollectorHost 实例缓存(per-workspace)。
97
+ * 避免每条用户消息 new 一个 host;host 内部有 rate limit 状态需跨消息保留。
98
+ */
99
+ const _signalCollectorHosts = new Map();
100
+ function getSignalCollectorHost(wctx, logger) {
101
+ let host = _signalCollectorHosts.get(wctx.workspaceDir);
102
+ if (!host) {
103
+ // 从 .pd/config.yaml 的 signalCollector runtimeProfile 构造 LLM classifier(配置单轨化)。
104
+ // 未配置/降级时返回 null,host 走纯关键词模式(spec §3.3 决策3)。
105
+ const llmClassifier = createSignalLlmClassifierFromConfig(wctx, logger);
106
+ host = new SignalCollectorHost(wctx, { llmClassifier });
107
+ _signalCollectorHosts.set(wctx.workspaceDir, host);
108
+ }
109
+ return host;
116
110
  }
117
111
  function parseContextInjectionConfig(value) {
118
112
  if (typeof value !== 'object' || value === null || Array.isArray(value))
@@ -204,53 +198,28 @@ export async function handleBeforePromptBuild(event, ctx) {
204
198
  if (sessionId) {
205
199
  wctx.trajectory?.recordSession?.({ sessionId });
206
200
  }
201
+ // 提前计算 lineage + userTurnCount(不依赖 isAgentToAgent),供后续 detectSync 使用。
202
+ // detectSync 调用延后到 isAgentToAgent 解析之后(CodeRabbit #7: 避免 agent-to-agent 误判)。
203
+ let correctionUserText = null;
204
+ let correctionReferencesAssistantTurnId = null;
205
+ let correctionTurnIndex = 0;
207
206
  if (sessionId && trigger === 'user' && Array.isArray(event.messages) && event.messages.length > 0) {
208
207
  const latestUserIndex = [...event.messages]
209
208
  .map((message, index) => ({ message, index }))
210
209
  .reverse()
211
210
  .find((entry) => entry.message?.role === 'user');
212
211
  if (latestUserIndex) {
213
- const userText = extractMessageContent(latestUserIndex.message);
214
- // Use CorrectionCueLearner for detection supports learned keywords, not just hardcoded list
215
- let correctionCue = null;
216
- try {
217
- const learner = CorrectionCueLearner.get(wctx.stateDir);
218
- const matchResult = learner.match(userText);
219
- if (matchResult.matched) {
220
- correctionCue = matchResult.matchedTerms[0] ?? null;
221
- learner.recordHits(matchResult.matchedTerms);
222
- // TP for high-confidence; flush hitCount for low-confidence
223
- if (correctionCue && matchResult.confidence >= 0.5) {
224
- learner.recordTruePositive(correctionCue);
225
- }
226
- else {
227
- learner.flush();
228
- }
229
- }
230
- }
231
- catch (learnerErr) {
232
- // Fallback to hardcoded detection if learner fails — log for observability
233
- correctionCue = coreDetectCorrectionCue(userText);
234
- logger?.warn?.(`[PD:Prompt] CorrectionCueLearner.match() failed (${String(learnerErr)}), fallback=${correctionCue ? `matched="${correctionCue}"` : 'no-match'}`);
235
- }
236
- let referencesAssistantTurnId = null;
212
+ correctionUserText = extractMessageContent(latestUserIndex.message);
213
+ // lineage: 关联到前置 assistant turn(诊断 evidence JOIN 用)。host 不感知 trajectory 结构,由这里算好传入。
237
214
  const hasPriorAssistant = event.messages
238
215
  .slice(0, latestUserIndex.index)
239
216
  .some((message) => message?.role === 'assistant');
240
217
  if (hasPriorAssistant) {
241
218
  const turns = wctx.trajectory?.listAssistantTurns?.(sessionId) ?? [];
242
219
  const lastAssistant = turns[turns.length - 1];
243
- referencesAssistantTurnId = lastAssistant?.id ?? null;
220
+ correctionReferencesAssistantTurnId = lastAssistant?.id ?? null;
244
221
  }
245
- const userTurnCount = event.messages.filter((message) => message?.role === 'user').length;
246
- wctx.trajectory?.recordUserTurn?.({
247
- sessionId,
248
- turnIndex: userTurnCount,
249
- rawText: userText,
250
- correctionDetected: Boolean(correctionCue),
251
- correctionCue,
252
- referencesAssistantTurnId,
253
- });
222
+ correctionTurnIndex = event.messages.filter((message) => message?.role === 'user').length;
254
223
  }
255
224
  }
256
225
  // Load context injection configuration
@@ -281,402 +250,21 @@ export async function handleBeforePromptBuild(event, ctx) {
281
250
  // Also detects empathy observer output (prevent recursion) and agent-to-agent messages.
282
251
  const { message: latestUserMessage, isAgentToAgent } = extractUserMessageFromPrompt(event.prompt || '', sessionId);
283
252
  const isUserInteraction = trigger === 'user' || trigger === 'api' || !trigger;
284
- // Empathy Observer: keyword fast-path + optional LLM deep analysis (zero latency async dispatch)
285
- const empathyEnabled = wctx.config.get('empathy_engine.enabled') !== false;
286
- logger?.info?.(`[PD:Empathy] Conditions: enabled=${empathyEnabled}, isUser=${isUserInteraction}, sessionId=${!!sessionId}, api=${!!api}, !agentToAgent=${!isAgentToAgent}, workspaceDir=${!!workspaceDir}, hasMessage=${!!latestUserMessage}`);
287
253
  // Track if we should inject behavioral constraints (will be added to appendSystemContext later)
254
+ // 注:原 empathy 检测门控(empathyEnabled)已移除,检测职责由 SignalCollectorHost 接管。
255
+ // behavioral 约束注入是独立职责,保留门控。
288
256
  let shouldInjectBehavioralConstraints = false;
289
- if (empathyEnabled && isUserInteraction && sessionId && api && !isAgentToAgent) {
257
+ if (isUserInteraction && sessionId && api && !isAgentToAgent) {
290
258
  shouldInjectBehavioralConstraints = true;
291
- // ── Empathy Hybrid Matching (keyword + subagent sampling) ──
292
- // Fast keyword scan on every turn, with strategic subagent sampling
293
- // for boundary cases and random discovery of new expressions.
294
- if (workspaceDir && latestUserMessage) {
295
- try {
296
- const msgPreview = latestUserMessage.substring(0, 200).replace(/\n/g, ' ');
297
- logger?.info?.(`[PD:Empathy] Processing user message: "${msgPreview}" (trigger=${trigger}, promptLen=${latestUserMessage.length})`);
298
- const lang = wctx.config.get('language') || 'zh';
299
- // Load keyword store once, cache per-workspace (Finding #7: avoid per-turn I/O)
300
- const empathyState = getEmpathyState(workspaceDir);
301
- if (!empathyState.keywordCache || empathyState.keywordCache.lang !== lang) {
302
- empathyState.keywordCache = { store: loadKeywordStore(wctx.stateDir, lang), lang };
303
- }
304
- const keywordStore = empathyState.keywordCache.store;
305
- const matchResult = matchEmpathyKeywords(latestUserMessage, keywordStore);
306
- // Increment turn counter (Finding #3: session.turnCount doesn't exist)
307
- empathyState.turnCounter++;
308
- const turnCount = empathyState.turnCounter;
309
- const painTrigger = wctx.config.get('thresholds.pain_trigger') || 40;
310
- const highGfiThreshold = Math.max(wctx.config.get('severity_thresholds.high') || 70, painTrigger + 30);
311
- if (matchResult.matched) {
312
- const penalty = severityToPenalty(matchResult.severity, DEFAULT_EMPATHY_KEYWORD_CONFIG);
313
- // trackFriction signature: (sessionId, deltaF: number, hash: string, workspaceDir?, options?)
314
- trackFriction(sessionId, penalty, 'empathy_keyword_match', workspaceDir, {
315
- source: 'user_empathy',
316
- });
317
- logger?.info?.(`[PD:Empathy] MATCH: "${matchResult.matchedTerms.join(', ')}" → severity=${matchResult.severity}, score=${matchResult.score.toFixed(2)}, penalty=${penalty}`);
318
- const currentSession = getSession(sessionId);
319
- const currentGfi = currentSession?.currentGfi ?? 0;
320
- if (currentGfi >= highGfiThreshold) {
321
- const gfiPainScore = Math.min(Math.round(currentGfi), 60);
322
- logger?.info?.(`[PD:Empathy] GFI-TRIGGERED: currentGfi=${currentGfi.toFixed(1)} >= highGfi=${highGfiThreshold}, emitting pain signal (score=${gfiPainScore})`);
323
- // PRI-454: Dual-gate migration. When both flags ON → Gate B (TriggerController).
324
- // When either OFF → Gate A (PainDiagnosticGate, rollback).
325
- const triageFlag = loadFeatureFlagFromConfig(workspaceDir, 'painEvidenceAdmission');
326
- const defaultFlag = loadFeatureFlagFromConfig(workspaceDir, 'painEvidenceAdmissionDefault');
327
- const useGateB = triageFlag.enabled && defaultFlag.enabled;
328
- wctx.eventLog.recordPainSignal(sessionId, {
329
- score: gfiPainScore,
330
- source: 'user_empathy',
331
- reason: `Accumulated GFI (${currentGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Matched: ${matchResult.matchedTerms.join(', ')}`,
332
- isRisky: false,
333
- origin: 'system_infer',
334
- severity: gfiPainScore >= 40 ? 'moderate' : 'mild',
335
- confidence: 0.5,
336
- detection_mode: 'structured',
337
- deduped: false,
338
- trigger_text_excerpt: sanitizeForEvidence(latestUserMessage, workspaceDir).substring(0, 120),
339
- raw_score: gfiPainScore,
340
- calibrated_score: gfiPainScore,
341
- eventId: `empathy_gfi_${Date.now()}`,
342
- });
343
- // PRI-453: Generate painId early and write to trajectory.db via legacy
344
- // recordPainEvent so that disabling SDK observability path does not lose
345
- // trajectory coverage. canonicalPainId enables dedup.
346
- const gfiPainId = `empathy_gfi_${Date.now()}`;
347
- wctx.trajectory?.recordPainEvent?.({
348
- sessionId,
349
- source: 'user_empathy',
350
- score: gfiPainScore,
351
- reason: `Accumulated GFI (${currentGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Matched: ${matchResult.matchedTerms.join(', ')}`,
352
- origin: 'system_infer',
353
- canonicalPainId: gfiPainId,
354
- });
355
- if (useGateB) {
356
- // PRI-454: Gate B path — TriggerController owns admission
357
- const rawObs = buildEmpathyObservation({
358
- detectionSource: 'user_empathy',
359
- isGfiTriggered: true,
360
- sessionId,
361
- });
362
- const sourceKind = resolveSourceKind(rawObs);
363
- const triage = evaluateEvidenceTriage(sourceKind, gfiPainScore);
364
- if (triage.decision !== 'admit') {
365
- logger?.info?.(`[PD:Empathy] Triage ${triage.decision}: ${triage.reason}`);
366
- }
367
- else {
368
- const cooldownActive = isSharedCooldownActive(sourceKind, sessionId, 'empathy_gfi_threshold');
369
- const triggerDecision = evaluateTriggerController({
370
- triageResult: triage,
371
- isOwnerManual: false,
372
- isCooldownActive: cooldownActive,
373
- isValid: true,
374
- score: gfiPainScore,
375
- sessionId,
376
- });
377
- if (triggerDecision.shouldCreateDiagnosticTask) {
378
- markSharedEpisodeAsDiagnosed(sourceKind, sessionId, 'empathy_gfi_threshold');
379
- logger?.info?.(`[PD:Empathy] Gate B approved, calling emitPainDetectedEvent...`);
380
- try {
381
- const evidence = buildTrajectoryEvidence(wctx, sessionId);
382
- await emitPainDetectedEvent(wctx, {
383
- ts: new Date().toISOString(),
384
- type: 'pain_detected',
385
- data: {
386
- painId: gfiPainId,
387
- painType: 'user_frustration',
388
- source: 'user_empathy',
389
- reason: `Accumulated GFI (${currentGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Matched: ${matchResult.matchedTerms.join(', ')}`,
390
- score: gfiPainScore,
391
- sessionId,
392
- agentId: 'main',
393
- provenance: 'openclaw_context_bound',
394
- evidence,
395
- },
396
- }, { recordObservability: false });
397
- logger?.info?.(`[PD:Empathy] emitPainDetectedEvent completed (GFI-triggered)`);
398
- }
399
- catch (emitErr) {
400
- console.error(`[PD:Empathy] FAILED to emit GFI-triggered pain event: ${String(emitErr)}`);
401
- logger?.warn?.(`[PD:Empathy] Failed to emit GFI-triggered pain event: ${String(emitErr)}`);
402
- }
403
- }
404
- else {
405
- logger?.info?.(`[PD:Empathy] Gate B skipped: ${triggerDecision.reason}`);
406
- }
407
- }
408
- }
409
- else {
410
- // PRI-454: Gate A path (rollback when either flag is OFF)
411
- const gate = evaluatePainDiagnosticGate({
412
- source: 'user_empathy',
413
- score: gfiPainScore,
414
- currentGfi,
415
- consecutiveErrors: currentSession?.consecutiveErrors ?? 0,
416
- sessionId,
417
- errorHash: 'empathy_gfi_threshold',
418
- thresholds: {
419
- painTrigger,
420
- highSeverity: wctx.config.get('severity_thresholds.high') || 70,
421
- semanticPain: Math.max(painTrigger, 60),
422
- },
423
- });
424
- if (gate.shouldDiagnose) {
425
- logger?.info?.(`[PD:Empathy] Gate approved, calling emitPainDetectedEvent...`);
426
- try {
427
- const evidence = buildTrajectoryEvidence(wctx, sessionId);
428
- await emitPainDetectedEvent(wctx, {
429
- ts: new Date().toISOString(),
430
- type: 'pain_detected',
431
- data: {
432
- painId: gfiPainId,
433
- painType: 'user_frustration',
434
- source: 'user_empathy',
435
- reason: `Accumulated GFI (${currentGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Matched: ${matchResult.matchedTerms.join(', ')}`,
436
- score: gfiPainScore,
437
- sessionId,
438
- agentId: 'main',
439
- provenance: 'openclaw_context_bound',
440
- evidence,
441
- },
442
- }, { recordObservability: false });
443
- logger?.info?.(`[PD:Empathy] emitPainDetectedEvent completed (GFI-triggered)`);
444
- }
445
- catch (emitErr) {
446
- console.error(`[PD:Empathy] FAILED to emit GFI-triggered pain event: ${String(emitErr)}`);
447
- logger?.warn?.(`[PD:Empathy] Failed to emit GFI-triggered pain event: ${String(emitErr)}`);
448
- }
449
- }
450
- else {
451
- logger?.info?.(`[PD:Empathy] GFI-triggered gate rejected: ${gate.detail}`);
452
- }
453
- }
454
- }
455
- }
456
- else {
457
- // ── Pipeline: Observer only runs when keyword matcher misses ──
458
- const observer = resolveEmpathyObserver(wctx, logger);
459
- if (observer) {
460
- const scheduler = new AgentScheduler();
461
- scheduler.register({
462
- agentId: 'empathy-observer',
463
- mode: 'realtime',
464
- runner: observer,
465
- });
466
- logger?.info?.(`[PD:Empathy] Pipeline: Triggering background Empathy Observer for unmatched message: "${msgPreview}"`);
467
- void scheduler.dispatch('empathy-observer', { userMessage: latestUserMessage })
468
- .then(async (result) => {
469
- if (result.damageDetected) {
470
- logger?.info?.(`[PD:Empathy] Pipeline: Background Empathy Observer detected damage. Severity: ${result.severity}, Reason: ${result.reason}`);
471
- // ── Persistence Contract ──
472
- const painScore = scoreFromSeverityForSpec(result.severity, wctx);
473
- trackFriction(sessionId, painScore, `observer_empathy_${result.severity}`, workspaceDir, { source: 'user_empathy' });
474
- // ── Pipeline: feed back newly detected expressions into keyword store ──
475
- if (result.reason) {
476
- const rawLang = wctx.config.get('language');
477
- const lang = rawLang === 'en' ? 'en' : 'zh';
478
- const phrases = extractPhrasesFromReason(result.reason, lang);
479
- if (phrases.length > 0) {
480
- const updates = {};
481
- for (const phrase of phrases) {
482
- if (!Object.hasOwn(keywordStore.terms, phrase)) {
483
- updates[phrase] = {
484
- action: 'add',
485
- weight: 0.4,
486
- falsePositiveRate: 0.3,
487
- reasoning: `Discovered by empathy observer: ${result.reason.substring(0, 100)}`,
488
- };
489
- }
490
- }
491
- if (Object.keys(updates).length > 0) {
492
- const { added } = applyKeywordUpdates(keywordStore, updates);
493
- if (added > 0) {
494
- saveKeywordStore(wctx.stateDir, keywordStore);
495
- logger?.info?.(`[PD:Empathy] Pipeline: added ${added} new terms from observer feedback`);
496
- }
497
- }
498
- }
499
- }
500
- const eventId = `emp_obs_${Date.now()}_${Math.random().toString(36).substring(2, 8)}`;
501
- wctx.eventLog.recordPainSignal(sessionId, {
502
- score: painScore,
503
- source: 'user_empathy',
504
- reason: result.reason || 'Empathy observer detected likely user frustration.',
505
- isRisky: false,
506
- origin: 'system_infer',
507
- severity: result.severity,
508
- confidence: result.confidence,
509
- detection_mode: 'structured',
510
- deduped: false,
511
- trigger_text_excerpt: sanitizeForEvidence(latestUserMessage, workspaceDir).substring(0, 120),
512
- raw_score: painScore,
513
- calibrated_score: painScore,
514
- eventId,
515
- });
516
- // PRI-453: Generate painId early to pass as canonicalPainId for dedup.
517
- // Declared outside try block so it's accessible to emitPainDetectedEvent
518
- // later (lineage consistency: same id for trajectory + emitted event).
519
- const observerPainId = `empathy_gfi_${Date.now()}`;
520
- try {
521
- wctx.trajectory?.recordPainEvent?.({
522
- sessionId,
523
- source: 'user_empathy',
524
- score: painScore,
525
- reason: result.reason || 'Empathy observer detected likely user frustration.',
526
- severity: result.severity,
527
- origin: 'system_infer',
528
- confidence: result.confidence,
529
- text: sanitizeForEvidence(latestUserMessage, workspaceDir),
530
- canonicalPainId: observerPainId,
531
- });
532
- }
533
- catch (error) {
534
- logger?.warn?.(`[PD:Empathy] Failed to persist trajectory: ${String(error)}`);
535
- }
536
- // Check if GFI triggers a pain event post-LLM validation
537
- const freshSession = getSession(sessionId);
538
- const freshGfi = freshSession?.currentGfi ?? 0;
539
- if (freshGfi >= highGfiThreshold) {
540
- const freshGfiPainScore = Math.min(Math.round(freshGfi), 60);
541
- // PRI-454: Dual-gate migration. When both flags ON → Gate B (TriggerController).
542
- // When either OFF → Gate A (PainDiagnosticGate, rollback).
543
- const triageFlag = loadFeatureFlagFromConfig(workspaceDir, 'painEvidenceAdmission');
544
- const defaultFlag = loadFeatureFlagFromConfig(workspaceDir, 'painEvidenceAdmissionDefault');
545
- const useGateB = triageFlag.enabled && defaultFlag.enabled;
546
- if (useGateB) {
547
- // PRI-454: Gate B path — TriggerController owns admission
548
- const rawObs = buildEmpathyObservation({
549
- detectionSource: 'user_empathy',
550
- isGfiTriggered: true,
551
- sessionId,
552
- });
553
- const sourceKind = resolveSourceKind(rawObs);
554
- const triage = evaluateEvidenceTriage(sourceKind, freshGfiPainScore);
555
- if (triage.decision !== 'admit') {
556
- logger?.info?.(`[PD:Empathy] Pipeline observer triage ${triage.decision}: ${triage.reason}`);
557
- }
558
- else {
559
- const cooldownActive = isSharedCooldownActive(sourceKind, sessionId, 'empathy_gfi_observer');
560
- const triggerDecision = evaluateTriggerController({
561
- triageResult: triage,
562
- isOwnerManual: false,
563
- isCooldownActive: cooldownActive,
564
- isValid: true,
565
- score: freshGfiPainScore,
566
- sessionId,
567
- });
568
- if (triggerDecision.shouldCreateDiagnosticTask) {
569
- markSharedEpisodeAsDiagnosed(sourceKind, sessionId, 'empathy_gfi_observer');
570
- logger?.info?.(`[PD:Empathy] Pipeline Gate B approved (observer), calling emitPainDetectedEvent...`);
571
- try {
572
- const evidence = buildTrajectoryEvidence(wctx, sessionId);
573
- // PRI-453: Reuse observerPainId for lineage consistency —
574
- // the same id is used as canonicalPainId in recordPainEvent
575
- // and as painId in the emitted event, so EvidenceChainConsoleModel
576
- // can JOIN pain_events.canonical_pain_id = tasks.input_ref.
577
- await emitPainDetectedEvent(wctx, {
578
- ts: new Date().toISOString(),
579
- type: 'pain_detected',
580
- data: {
581
- painId: observerPainId,
582
- painType: 'user_frustration',
583
- source: 'user_empathy',
584
- reason: `Accumulated GFI (${freshGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Verified by Empathy Observer.`,
585
- score: freshGfiPainScore,
586
- sessionId,
587
- agentId: 'main',
588
- provenance: 'openclaw_context_bound',
589
- evidence,
590
- },
591
- }, { recordObservability: false });
592
- }
593
- catch (emitErr) {
594
- logger?.error?.(`[PD:Empathy] Pipeline FAILED to emit observer-triggered pain event: ${String(emitErr)}`);
595
- }
596
- }
597
- else {
598
- logger?.info?.(`[PD:Empathy] Pipeline Gate B skipped (observer): ${triggerDecision.reason}`);
599
- }
600
- }
601
- }
602
- else {
603
- // PRI-454: Gate A path (rollback when either flag is OFF)
604
- const gate = evaluatePainDiagnosticGate({
605
- source: 'user_empathy',
606
- score: freshGfiPainScore,
607
- currentGfi: freshGfi,
608
- consecutiveErrors: freshSession?.consecutiveErrors ?? 0,
609
- sessionId,
610
- errorHash: 'empathy_gfi_threshold',
611
- thresholds: {
612
- painTrigger,
613
- highSeverity: wctx.config.get('severity_thresholds.high') || 70,
614
- semanticPain: Math.max(painTrigger, 60),
615
- },
616
- });
617
- if (gate.shouldDiagnose) {
618
- logger?.info?.(`[PD:Empathy] Pipeline GFI threshold crossed after background observer. Emitting pain signal...`);
619
- try {
620
- const evidence = buildTrajectoryEvidence(wctx, sessionId);
621
- // PRI-453: Reuse observerPainId for lineage consistency —
622
- // the same id is used as canonicalPainId in recordPainEvent
623
- // and as painId in the emitted event, so EvidenceChainConsoleModel
624
- // can JOIN pain_events.canonical_pain_id = tasks.input_ref.
625
- await emitPainDetectedEvent(wctx, {
626
- ts: new Date().toISOString(),
627
- type: 'pain_detected',
628
- data: {
629
- painId: observerPainId,
630
- painType: 'user_frustration',
631
- source: 'user_empathy',
632
- reason: `Accumulated GFI (${freshGfi.toFixed(1)}) crossed highGfi threshold (${highGfiThreshold}). Verified by Empathy Observer.`,
633
- score: freshGfiPainScore,
634
- sessionId,
635
- agentId: 'main',
636
- provenance: 'openclaw_context_bound',
637
- evidence,
638
- },
639
- }, { recordObservability: false });
640
- }
641
- catch (emitErr) {
642
- logger?.error?.(`[PD:Empathy] Pipeline FAILED to emit observer-triggered pain event: ${String(emitErr)}`);
643
- }
644
- }
645
- }
646
- }
647
- }
648
- else {
649
- logger?.info?.(`[PD:Empathy] Pipeline: Background Empathy Observer did not detect any damage.`);
650
- }
651
- })
652
- .catch((err) => {
653
- logger?.warn?.(`[PD:Empathy] Pipeline: Background analysis failed or rejected: ${String(err)}`);
654
- });
655
- }
656
- // Log unmatched messages periodically for coverage analysis
657
- if (turnCount > 0 && turnCount % 50 === 0) {
658
- const sampleMsg = latestUserMessage.substring(0, 80).replace(/\n/g, ' ');
659
- logger?.debug?.(`[PD:Empathy] NO_MATCH: "${sampleMsg}" (turn ${turnCount}, keywords_in_store=${Object.keys(keywordStore.terms).length})`);
660
- }
661
- }
662
- // Periodic summary (every 100 turns)
663
- if (turnCount > 0 && turnCount % 100 === 0) {
664
- const s = getKeywordStoreSummary(keywordStore);
665
- const highFP = s.highFalsePositiveTerms.slice(0, 5).map(t => `${t.term}(${t.falsePositiveRate.toFixed(2)})`).join(', ');
666
- logger?.info?.(`[PD:Empathy] SUMMARY(turn=${turnCount}): terms=${s.totalTerms}, hits=${keywordStore.stats.totalHits}, zero_hit=${s.totalTerms - (s.seedTerms + s.discoveredTerms)}, high_fp=[${highFP}]`);
667
- }
668
- // Save keyword store on every match
669
- if (matchResult.matched) {
670
- saveKeywordStore(wctx.stateDir, keywordStore);
671
- const { totalHits } = keywordStore.stats;
672
- logger?.info?.(`[PD:Empathy] Keyword store saved after match: terms=${matchResult.matchedTerms.join(',')}, totalHits=${totalHits}`);
673
- }
674
- }
675
- catch (e) {
676
- logger?.warn?.(`[PD:Empathy] ERROR: ${String(e)}`);
677
- }
678
- }
679
259
  }
260
+ // SignalCollectorHost 统一接管 correction + empathy 检测(spec §3.3 决策1)。
261
+ // 在 isAgentToAgent 解析之后调用,避免 agent-to-agent 流量被误当用户纠正(CodeRabbit #7)。
262
+ if (correctionUserText && sessionId && trigger === 'user' && !isAgentToAgent) {
263
+ getSignalCollectorHost(wctx, logger).detectSync(correctionUserText, sessionId, trigger, { referencesAssistantTurnId: correctionReferencesAssistantTurnId, turnIndex: correctionTurnIndex });
264
+ }
265
+ // 注:SignalCollectorHost.detectSync 已在上文 correction 段(:259)统一调用一次,
266
+ // 覆盖 correction + empathy 全部检测职责(含 lineage + turnIndex)。
267
+ // 此处不再重复调用,避免同一消息双重写入 user_turns 和重复触发 STRONG 分流。
680
268
  // ──── 4. Heartbeat-specific checklist (also fires for cron-triggered sessions) ────
681
269
  if (trigger === 'heartbeat' || trigger === 'cron') {
682
270
  // ──── 4a. GFI Time-based Decay ────
@@ -975,65 +563,3 @@ export async function handleBeforePromptBuild(event, ctx) {
975
563
  appendSystemContext
976
564
  };
977
565
  }
978
- // ── Empathy Observer Hybrid Deep Analysis Helpers (Unified SDK Migration) ──
979
- function scoreFromSeverityForSpec(severity, wctx) {
980
- if (severity === 'severe')
981
- return Number(wctx.config.get('empathy_engine.penalties.severe') ?? 40);
982
- if (severity === 'moderate')
983
- return Number(wctx.config.get('empathy_engine.penalties.moderate') ?? 25);
984
- return Number(wctx.config.get('empathy_engine.penalties.mild') ?? 10);
985
- }
986
- function resolveEmpathyObserver(wctx, logger) {
987
- // F15 (PRI-442): empathy_observer flag is registered as MVP-Quiet (default
988
- // off) per ADR-0014 §2.5. Previously this flag was a dead registration —
989
- // registered in feature-flag-contract.ts but never read anywhere, violating
990
- // the PRI-239 constraint "Only flags with real consumption paths are
991
- // registered". Now resolveEmpathyObserver consumes the flag: when disabled
992
- // (the default), the LLM observer pipeline is short-circuited and the
993
- // keyword-matcher path (gated by empathy_engine.enabled above) continues
994
- // to run independently. This mirrors the pattern used by
995
- // shouldStartEvolutionWorker / shouldStartCorrectionObserver.
996
- const empathyFlag = loadFeatureFlagFromConfig(wctx.workspaceDir, 'empathy_observer', logger);
997
- if (!empathyFlag.enabled) {
998
- logger?.debug?.(`[PD:Empathy] empathy_observer flag disabled (source=${empathyFlag.source}) — LLM observer pipeline skipped`);
999
- return null;
1000
- }
1001
- try {
1002
- const loader = new WorkflowFunnelLoader(wctx.stateDir);
1003
- const funnel = loader.getFunnel('pd-empathy-observer');
1004
- const policy = funnel?.policy;
1005
- if (!policy || policy.runtimeKind !== 'pi-ai') {
1006
- logger?.debug?.('[PD:Empathy] workflows.yaml pd-empathy-observer policy not found. Falling back to environment variables.');
1007
- const provider = process.env.PD_EMPATHY_PROVIDER || 'anthropic';
1008
- const model = process.env.PD_EMPATHY_MODEL || 'anthropic/claude-3-5-sonnet';
1009
- const apiKeyEnv = process.env.PD_EMPATHY_API_KEY_ENV || 'ANTHROPIC_API_KEY';
1010
- const baseUrl = process.env.PD_EMPATHY_BASE_URL;
1011
- if (!process.env[apiKeyEnv]) {
1012
- logger?.debug?.(`[PD:Empathy] Empathy observer API key env ${apiKeyEnv} is not set. Background analysis disabled.`);
1013
- return null;
1014
- }
1015
- const adapter = new PiAiRuntimeAdapter({
1016
- provider,
1017
- model,
1018
- apiKeyEnv,
1019
- baseUrl,
1020
- workspace: wctx.workspaceDir,
1021
- });
1022
- return new EmpathyObserver({ runtimeAdapter: adapter });
1023
- }
1024
- const adapter = new PiAiRuntimeAdapter({
1025
- provider: String(policy.provider),
1026
- model: String(policy.model),
1027
- apiKeyEnv: String(policy.apiKeyEnv),
1028
- maxRetries: policy.maxRetries,
1029
- timeoutMs: policy.timeoutMs ?? 30_000,
1030
- baseUrl: policy.baseUrl,
1031
- workspace: wctx.workspaceDir,
1032
- });
1033
- return new EmpathyObserver({ runtimeAdapter: adapter }, { timeoutMs: policy.timeoutMs });
1034
- }
1035
- catch (err) {
1036
- logger?.warn?.(`[PD:Empathy] Failed to resolve EmpathyObserver: ${String(err)}`);
1037
- return null;
1038
- }
1039
- }
@@ -1,2 +1,2 @@
1
- export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuleHostUnhealthyEventData, ToolCallStats, ErrorStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
1
+ export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuleHostUnhealthyEventData, RuleHostSkippedEventData, ToolCallStats, ErrorStats, EmpathyEventStats, GfiStats, EvolutionStats as EventEvolutionStats, HookStats, DailyStats, } from '@principles/core/runtime-v2';
2
2
  export { createEmptyDailyStats, } from '@principles/core/runtime-v2';