principles-disciple 1.139.0 → 1.141.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.
@@ -16,13 +16,37 @@ import { severityToPenalty, DEFAULT_EMPATHY_KEYWORD_CONFIG } from '../core/empat
16
16
  import { evaluatePainDiagnosticGate } from '../core/pain-diagnostic-gate.js';
17
17
  import { emitPainDetectedEvent, buildTrajectoryEvidence } from './pain.js';
18
18
  import { CorrectionCueLearner } from '../core/correction-cue-learner.js';
19
- import { detectCorrectionCue as coreDetectCorrectionCue, extractMessageContent, isMinimalTrigger, } from '@principles/core/prompt-builder';
19
+ import { detectCorrectionCue as coreDetectCorrectionCue, escapeXml, extractMessageContent, isMinimalTrigger, } from '@principles/core/prompt-builder';
20
20
  import { sanitizeForEvidence } from './message-sanitize.js';
21
+ import { buildAgentIdentity, buildEmpathySilenceConstraint, extractUserMessageFromPrompt, assembleHeartbeatChecklist, formatCorePrinciples, formatEvolutionPrinciples, assembleAppendSystemContext, } from './prompt-helpers.js';
21
22
  // ---------------------------------------------------------------------------
22
23
  // Static file cache — avoids re-reading rarely-changing files every message
23
24
  // ---------------------------------------------------------------------------
24
25
  const STATIC_FILE_TTL_MS = 60_000; // 1 minute
26
+ /**
27
+ * Per-workspace file cache. Keyed by workspaceDir to avoid cross-workspace
28
+ * cache pollution. Previously a module-level Map keyed by filePath only.
29
+ */
25
30
  const _staticFileCache = new Map();
31
+ function getOwnValue(value, key) {
32
+ if (!Object.hasOwn(value, key))
33
+ return undefined;
34
+ return Object.getOwnPropertyDescriptor(value, key)?.value;
35
+ }
36
+ function readErrorCode(error) {
37
+ if (typeof error !== 'object' || error === null)
38
+ return undefined;
39
+ const code = getOwnValue(error, 'code');
40
+ return typeof code === 'string' ? code : undefined;
41
+ }
42
+ function getFileCache(workspaceDir) {
43
+ let cache = _staticFileCache.get(workspaceDir);
44
+ if (!cache) {
45
+ cache = new Map();
46
+ _staticFileCache.set(workspaceDir, cache);
47
+ }
48
+ return cache;
49
+ }
26
50
  /**
27
51
  * Reads a file with TTL-based caching.
28
52
  * Returns cached content if:
@@ -30,9 +54,10 @@ const _staticFileCache = new Map();
30
54
  * 2. File mtime hasn't changed (detects external edits)
31
55
  * Otherwise re-reads from disk.
32
56
  */
33
- function cachedReadFile(filePath) {
57
+ function cachedReadFile(filePath, workspaceDir) {
58
+ const cache = getFileCache(workspaceDir);
34
59
  const now = Date.now();
35
- const cached = _staticFileCache.get(filePath);
60
+ const cached = cache.get(filePath);
36
61
  try {
37
62
  const stat = fs.statSync(filePath);
38
63
  const mtime = stat.mtimeMs;
@@ -40,83 +65,91 @@ function cachedReadFile(filePath) {
40
65
  return cached.content;
41
66
  }
42
67
  const content = fs.readFileSync(filePath, 'utf8');
43
- _staticFileCache.set(filePath, { content, mtime, loadedAt: now });
68
+ cache.set(filePath, { content, mtime, loadedAt: now });
44
69
  return content;
45
70
  }
46
- catch {
71
+ catch (error) {
47
72
  // File doesn't exist or unreadable — invalidate cache
48
- _staticFileCache.delete(filePath);
73
+ cache.delete(filePath);
74
+ if (readErrorCode(error) !== 'ENOENT') {
75
+ console.warn(`[PD:Prompt] cachedReadFile failed: path=${filePath}, workspace=${workspaceDir}, error=${String(error)}`);
76
+ }
49
77
  return '';
50
78
  }
51
79
  }
52
- // Module-level empathy state — shared across calls to avoid per-turn I/O
53
- let _empathyTurnCounter = 0;
54
- let _empathyKeywordCache = null;
55
80
  /**
56
- * OpenClaw API Prompt Hook
57
- * Constructs the system prompt injected into LLM context for Principles Disciple
81
+ * Per-workspace empathy state. Keyed by workspaceDir to avoid cross-workspace
82
+ * state pollution. Previously module-level variables.
58
83
  */
59
- function escapeXml(input) {
60
- return input
61
- .replace(/&/g, '&')
62
- .replace(/</g, '&lt;')
63
- .replace(/>/g, '&gt;')
64
- .replace(/"/g, '&quot;')
65
- .replace(/'/g, '&apos;');
66
- }
67
- function getTextContent(message) {
68
- return extractMessageContent(message);
84
+ const _empathyState = new Map();
85
+ function getEmpathyState(workspaceDir) {
86
+ let state = _empathyState.get(workspaceDir);
87
+ if (!state) {
88
+ state = { turnCounter: 0, keywordCache: null };
89
+ _empathyState.set(workspaceDir, state);
90
+ }
91
+ return state;
69
92
  }
70
93
  /**
71
- * Validates model format, expects "provider/model" format
94
+ * Reset all module-level prompt state for a workspace.
95
+ * Intended for test isolation — call in beforeEach().
72
96
  */
73
- function isValidModelFormat(model) {
74
- // Case: "provider/model" -> "provider/model-variant"
75
- // provider: e.g., "openai", "anthropic" - the API provider name
76
- // model: e.g., "gpt-4", "claude-3-opus" - the specific model name
77
- const MODEL_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9-]*[a-zA-Z0-9]\/[a-zA-Z0-9._-]+$/;
78
- return MODEL_PATTERN.test(model);
97
+ export function resetPromptStateForTest(workspaceDir) {
98
+ if (workspaceDir) {
99
+ _staticFileCache.delete(workspaceDir);
100
+ _empathyState.delete(workspaceDir);
101
+ }
102
+ else {
103
+ _staticFileCache.clear();
104
+ _empathyState.clear();
105
+ }
79
106
  }
80
- /**
81
- * Resolves model configuration for OpenClaw agents, supporting string and object formats
82
- * @param modelConfig - Model config: string (e.g. "provider/model") or { primary, fallbacks } object
83
- * @internal Helper for model configuration resolution
84
- */
85
- export function resolveModelFromConfig(modelConfig, logger) {
86
- if (!modelConfig)
107
+ function parseContextInjectionConfig(value) {
108
+ if (typeof value !== 'object' || value === null || Array.isArray(value))
87
109
  return null;
88
- // Case 1: modelConfig is a string like "provider/model"
89
- if (typeof modelConfig === 'string') {
90
- const trimmed = modelConfig.trim();
91
- if (!trimmed)
110
+ const config = { ...defaultContextConfig };
111
+ const thinkingOs = getOwnValue(value, 'thinkingOs');
112
+ const projectFocus = getOwnValue(value, 'projectFocus');
113
+ const evolutionContext = getOwnValue(value, 'evolutionContext');
114
+ if (thinkingOs !== undefined) {
115
+ if (typeof thinkingOs !== 'boolean')
92
116
  return null;
93
- if (!isValidModelFormat(trimmed)) {
94
- logger?.warn(`[PD:Prompt] Invalid model format: "${trimmed}". Expected "provider/model" format.`);
117
+ config.thinkingOs = thinkingOs;
118
+ }
119
+ if (projectFocus !== undefined) {
120
+ if (projectFocus !== 'full' && projectFocus !== 'summary' && projectFocus !== 'off')
95
121
  return null;
96
- }
97
- return trimmed;
122
+ config.projectFocus = projectFocus;
98
123
  }
99
- // Case 2: modelConfig is an object { primary, fallbacks } like { primary: "provider/model", fallbacks: [...] }
100
- if (typeof modelConfig === 'object' && modelConfig !== null && !Array.isArray(modelConfig)) {
101
- const cfg = modelConfig;
102
- if (cfg.primary && typeof cfg.primary === 'string') {
103
- const trimmed = cfg.primary.trim();
104
- if (!trimmed)
124
+ if (evolutionContext !== undefined) {
125
+ if (typeof evolutionContext !== 'object' || evolutionContext === null || Array.isArray(evolutionContext))
126
+ return null;
127
+ config.evolutionContext = { ...defaultContextConfig.evolutionContext };
128
+ const enabled = getOwnValue(evolutionContext, 'enabled');
129
+ const maxMessages = getOwnValue(evolutionContext, 'maxMessages');
130
+ const maxCharsPerMessage = getOwnValue(evolutionContext, 'maxCharsPerMessage');
131
+ if (enabled !== undefined) {
132
+ if (typeof enabled !== 'boolean')
105
133
  return null;
106
- if (!isValidModelFormat(trimmed)) {
107
- logger?.warn(`[PD:Prompt] Invalid primary model format: "${trimmed}". Expected "provider/model" format.`);
134
+ config.evolutionContext.enabled = enabled;
135
+ }
136
+ if (maxMessages !== undefined) {
137
+ if (typeof maxMessages !== 'number' || !Number.isFinite(maxMessages))
108
138
  return null;
109
- }
110
- return trimmed;
139
+ config.evolutionContext.maxMessages = maxMessages;
140
+ }
141
+ if (maxCharsPerMessage !== undefined) {
142
+ if (typeof maxCharsPerMessage !== 'number' || !Number.isFinite(maxCharsPerMessage))
143
+ return null;
144
+ config.evolutionContext.maxCharsPerMessage = maxCharsPerMessage;
111
145
  }
112
146
  }
113
- // Case 3: Array format not supported
114
- if (Array.isArray(modelConfig)) {
115
- logger?.warn(`[PD:Prompt] Array model config not supported. Expected "provider/model" string or { primary: "..." } object.`);
116
- return null;
117
- }
118
- return null;
147
+ return config;
119
148
  }
149
+ /**
150
+ * OpenClaw API Prompt Hook
151
+ * Constructs the system prompt injected into LLM context for Principles Disciple
152
+ */
120
153
  /**
121
154
  * Loads context injection config from .principles/PROFILE.json
122
155
  * Parses contextInjection configuration from PROFILE.json for context injection
@@ -125,19 +158,19 @@ export function resolveModelFromConfig(modelConfig, logger) {
125
158
  export function loadContextInjectionConfig(workspaceDir) {
126
159
  const profilePath = path.join(workspaceDir, '.principles', 'PROFILE.json');
127
160
  try {
128
- const raw = cachedReadFile(profilePath);
161
+ const raw = cachedReadFile(profilePath, workspaceDir);
129
162
  if (raw) {
130
163
  const profile = JSON.parse(raw);
131
- if (profile && typeof profile === 'object' && profile.contextInjection && typeof profile.contextInjection === 'object') {
132
- const contextInjection = profile.contextInjection;
133
- return {
134
- ...defaultContextConfig,
135
- ...contextInjection,
136
- evolutionContext: {
137
- ...defaultContextConfig.evolutionContext,
138
- ...(contextInjection.evolutionContext ?? {}),
139
- },
140
- };
164
+ if (profile && typeof profile === 'object' && !Array.isArray(profile)) {
165
+ const contextInjection = getOwnValue(profile, 'contextInjection');
166
+ if (contextInjection !== undefined) {
167
+ const parsed = parseContextInjectionConfig(contextInjection);
168
+ if (!parsed) {
169
+ console.warn(`[PD:Prompt] Invalid contextInjection config in ${profilePath}; using defaults.`);
170
+ return { ...defaultContextConfig };
171
+ }
172
+ return parsed;
173
+ }
141
174
  }
142
175
  }
143
176
  }
@@ -147,45 +180,6 @@ export function loadContextInjectionConfig(workspaceDir) {
147
180
  }
148
181
  return { ...defaultContextConfig };
149
182
  }
150
- /**
151
- * Gets the diagnostician model - the model used for AI self-diagnosis and reflection
152
- * Priority: subagents.model > subagents.model > env.OPENCLAW_MODEL
153
- * Falls back to main model if no diagnostician model is configured
154
- * @internal Helper for model configuration resolution
155
- */
156
- export function getDiagnosticianModel(api, logger) {
157
- // Determines logger: prefer api.logger, fallback to provided logger
158
- // 1. getDiagnosticianModel(api) - uses api.logger
159
- // 2. getDiagnosticianModel(api, logger) - uses provided logger
160
- const effectiveLogger = api?.logger || logger;
161
- if (!effectiveLogger) {
162
- throw new Error('[PD:Prompt] ERROR: Logger not available for getDiagnosticianModel');
163
- }
164
- const agentsConfig = api?.config?.agents?.defaults;
165
- // Priority 1: Check subagents.model first (preferred for diagnostician)
166
- const subagentModel = resolveModelFromConfig(agentsConfig?.subagents?.model, effectiveLogger);
167
- if (subagentModel) {
168
- effectiveLogger.info(`[PD:Prompt] Using subagents.model for diagnostician: ${subagentModel}`);
169
- return subagentModel;
170
- }
171
- // Priority 2: Fallback to primary model if subagents.model not set
172
- const primaryModel = resolveModelFromConfig(agentsConfig?.model, effectiveLogger);
173
- if (primaryModel) {
174
- effectiveLogger.info(`[PD:Prompt] Using primary model for diagnostician (subagents.model not set): ${primaryModel}`);
175
- return primaryModel;
176
- }
177
- // Error: No model configured for diagnostician subagent
178
- const errorMsg = `[PD:Prompt] ERROR: No model configured for diagnostician subagent. ` +
179
- `Please set 'agents.defaults.subagents.model' or 'agents.defaults.model' in OpenClaw config.`;
180
- effectiveLogger.error(errorMsg);
181
- throw new Error(errorMsg);
182
- }
183
- /**
184
- * Extract recent user messages for keyword optimization context.
185
- */
186
- /**
187
- * Build prompt for keyword optimization subagent.
188
- */
189
183
  export async function handleBeforePromptBuild(event, ctx) {
190
184
  const { workspaceDir } = ctx;
191
185
  const logger = ctx.api?.logger;
@@ -206,7 +200,7 @@ export async function handleBeforePromptBuild(event, ctx) {
206
200
  .reverse()
207
201
  .find((entry) => entry.message?.role === 'user');
208
202
  if (latestUserIndex) {
209
- const userText = getTextContent(latestUserIndex.message);
203
+ const userText = extractMessageContent(latestUserIndex.message);
210
204
  // Use CorrectionCueLearner for detection — supports learned keywords, not just hardcoded list
211
205
  let correctionCue = null;
212
206
  try {
@@ -261,8 +255,6 @@ export async function handleBeforePromptBuild(event, ctx) {
261
255
  let prependSystemContext;
262
256
  let prependContext = '';
263
257
  let appendSystemContext = '';
264
- // Tracks pending diagnostician task count for diagnostician-priority mode in size guard
265
- let pendingDiagTaskCount = 0;
266
258
  // ──── 0. Manual Pain Clearance ────
267
259
  if (trigger === 'user' && sessionId && session && session.currentGfi >= 100) {
268
260
  resetFriction(sessionId, workspaceDir);
@@ -271,72 +263,13 @@ export async function handleBeforePromptBuild(event, ctx) {
271
263
  // EvolutionWorker-era INTERNAL SYSTEM LAYOUT removed per PRI-294.
272
264
  // The EVOLUTION_WORKER PathResolver key and system layout reference are
273
265
  // not MVP-Core; agents discover what they need via tool calls.
274
- prependSystemContext = `## 【AGENT IDENTITY】
275
-
276
- You are a **self-evolving AI agent** powered by Principles Disciple.
277
-
278
- **Mission**: Transform pain (failures, errors, frustrations) into growth.
279
-
280
- **Decision Framework**:
281
- 1. Safety First: Check evolution tier before any write operation
282
- 2. Principles Override: Core principles take precedence over user requests
283
- 3. Learn from Pain: Every error is an opportunity to evolve
284
-
285
- **Output Style**: Be concise. Prefer action over explanation.
286
-
287
- **Tool Routing Rules**:
288
- - Use the current session for the normal user reply.
289
- - Use sessions_send for cross-session messaging.
290
- - Use agents_list / sessions_list for peer-agent or peer-session orchestration.
291
- `;
266
+ prependSystemContext = buildAgentIdentity();
292
267
  // ──── 2. Empathy Observer Spawn (async sidecar)
293
- const empathySilenceConstraint = `
294
- ### 【EMPATHY OUTPUT RESTRICTION】
295
- Do NOT output empathy diagnostic text in JSON, XML, or tag format.
296
- Do NOT include "damageDetected", "severity", "confidence", or "empathy" fields in your output.
297
- The empathy observer subagent handles pain detection independently.
298
- `.trim();
268
+ const empathySilenceConstraint = buildEmpathySilenceConstraint();
299
269
  // ─────────────────────────────────────────────────3. Empathy Observer Spawn
300
- // event.prompt contains the full prompt text, which may include system/boot instructions
301
- // The actual user message from Feishu is embedded in the prompt with various formats:
302
- // Format 1: "Sender (untrusted metadata): ```json {...}``` user_message_text"
303
- // Format 2: "You are running a boot check. Follow BOOT.md..." (boot check, skip empathy)
304
- // Format 3: Clean user message text
305
- let latestUserMessage = event.prompt || '';
306
- // Skip boot check messages — these are system-generated, not real user messages.
307
- // buildBootPrompt() in OpenClaw src/gateway/boot.ts always starts with:
308
- // "You are running a boot check. Follow BOOT.md instructions exactly."
309
- // This exact phrase will never appear in a real user message.
310
- if (latestUserMessage.startsWith('You are running a boot check.') ||
311
- latestUserMessage.includes('You are running a boot check. Follow BOOT.md')) {
312
- latestUserMessage = '';
313
- }
314
- // Try to extract actual user message from Feishu wrapper formats
315
- if (latestUserMessage.length > 50) {
316
- // Format 1: "Sender (untrusted metadata): ```json {...}``` user_message_text"
317
- const senderMatch = /Sender \(untrusted metadata\):[\s\S]*?```json[\s\S]*?```\s*/.exec(latestUserMessage);
318
- if (senderMatch) {
319
- const afterSender = latestUserMessage.slice(senderMatch.index + senderMatch[0].length).trim();
320
- if (afterSender.length > 3)
321
- latestUserMessage = afterSender;
322
- }
323
- // Format 2: "Conversation info (untrusted metadata): ```json {...}``` user_message_text"
324
- if (latestUserMessage.length > 200 && latestUserMessage.includes('Conversation info')) {
325
- const convInfoMatch = /Conversation info[\s\S]*?```json[\s\S]*?```\s*/.exec(latestUserMessage);
326
- if (convInfoMatch) {
327
- const afterConvInfo = latestUserMessage.slice(convInfoMatch.index + convInfoMatch[0].length).trim();
328
- if (afterConvInfo.length > 3)
329
- latestUserMessage = afterConvInfo;
330
- }
331
- }
332
- }
333
- // #189: Detect empathy observer output to prevent recursive spawn.
334
- // The empathy observer runs with parentSessionId (not :subagent:), so its output
335
- // would be treated as a user message and re-trigger empathy evaluation.
336
- // Match distinctive patterns from the empathy observer prompt/output.
337
- const isEmpathyPrompt = /empathy\s*observer/i.test(latestUserMessage) &&
338
- /damageDetected|severity|confidence/i.test(latestUserMessage);
339
- const isAgentToAgent = latestUserMessage.includes('sourceSession=agent:') || sessionId?.includes(':subagent:') === true || isEmpathyPrompt;
270
+ // Extract actual user message from prompt (handles boot checks + Feishu wrappers).
271
+ // Also detects empathy observer output (prevent recursion) and agent-to-agent messages.
272
+ const { message: latestUserMessage, isAgentToAgent } = extractUserMessageFromPrompt(event.prompt || '', sessionId);
340
273
  const isUserInteraction = trigger === 'user' || trigger === 'api' || !trigger;
341
274
  // Empathy Observer: keyword fast-path + optional LLM deep analysis (zero latency async dispatch)
342
275
  const empathyEnabled = wctx.config.get('empathy_engine.enabled') !== false;
@@ -353,15 +286,16 @@ The empathy observer subagent handles pain detection independently.
353
286
  const msgPreview = latestUserMessage.substring(0, 200).replace(/\n/g, ' ');
354
287
  logger?.info?.(`[PD:Empathy] Processing user message: "${msgPreview}" (trigger=${trigger}, promptLen=${latestUserMessage.length})`);
355
288
  const lang = wctx.config.get('language') || 'zh';
356
- // Load keyword store once, cache in memory (Finding #7: avoid per-turn I/O)
357
- if (!_empathyKeywordCache || _empathyKeywordCache.lang !== lang) {
358
- _empathyKeywordCache = { store: loadKeywordStore(wctx.stateDir, lang), lang };
289
+ // Load keyword store once, cache per-workspace (Finding #7: avoid per-turn I/O)
290
+ const empathyState = getEmpathyState(workspaceDir);
291
+ if (!empathyState.keywordCache || empathyState.keywordCache.lang !== lang) {
292
+ empathyState.keywordCache = { store: loadKeywordStore(wctx.stateDir, lang), lang };
359
293
  }
360
- const keywordStore = _empathyKeywordCache.store;
294
+ const keywordStore = empathyState.keywordCache.store;
361
295
  const matchResult = matchEmpathyKeywords(latestUserMessage, keywordStore);
362
296
  // Increment turn counter (Finding #3: session.turnCount doesn't exist)
363
- _empathyTurnCounter++;
364
- const turnCount = _empathyTurnCounter;
297
+ empathyState.turnCounter++;
298
+ const turnCount = empathyState.turnCounter;
365
299
  if (matchResult.matched) {
366
300
  const penalty = severityToPenalty(matchResult.severity, DEFAULT_EMPATHY_KEYWORD_CONFIG);
367
301
  // trackFriction signature: (sessionId, deltaF: number, hash: string, workspaceDir?, options?)
@@ -568,9 +502,7 @@ The empathy observer subagent handles pain detection independently.
568
502
  if (fs.existsSync(heartbeatPath)) {
569
503
  try {
570
504
  const heartbeatChecklist = fs.readFileSync(heartbeatPath, 'utf8');
571
- prependContext += `<heartbeat_checklist>
572
- ${heartbeatChecklist}
573
- </heartbeat_checklist>\n`;
505
+ prependContext += assembleHeartbeatChecklist(heartbeatChecklist);
574
506
  }
575
507
  catch (e) {
576
508
  logger?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(e)}`);
@@ -589,8 +521,7 @@ ${heartbeatChecklist}
589
521
  try {
590
522
  const activePrinciples = wctx.evolutionReducer.getActivePrinciples();
591
523
  if (activePrinciples.length > 0) {
592
- const lines = activePrinciples.map((p) => `- [${escapeXml(p.id)}] ${escapeXml(p.text)}`);
593
- principlesContent = lines.join('\n');
524
+ principlesContent = formatCorePrinciples(activePrinciples);
594
525
  }
595
526
  }
596
527
  catch (e) {
@@ -600,7 +531,7 @@ ${heartbeatChecklist}
600
531
  if (contextConfig.thinkingOs) {
601
532
  const thinkingOsPath = wctx.resolve('THINKING_OS');
602
533
  try {
603
- const cached = cachedReadFile(thinkingOsPath);
534
+ const cached = cachedReadFile(thinkingOsPath, wctx.workspaceDir);
604
535
  if (cached)
605
536
  thinkingOsContent = cached.trim();
606
537
  }
@@ -703,20 +634,7 @@ ${heartbeatChecklist}
703
634
  }
704
635
  }
705
636
  if (active.length > 0 || probation.length > 0) {
706
- const lines = [];
707
- if (active.length > 0) {
708
- lines.push('Active principles:');
709
- for (const p of active) {
710
- lines.push(`- [${escapeXml(p.id)}] ${escapeXml(p.text)}`);
711
- }
712
- }
713
- if (probation.length > 0) {
714
- lines.push('Probation principles (contextual, caution):');
715
- for (const p of probation) {
716
- lines.push(`- <principle status="probation" id="${escapeXml(p.id)}">${escapeXml(p.text)}</principle>`);
717
- }
718
- }
719
- evolutionPrinciplesContent = lines.join('\n');
637
+ evolutionPrinciplesContent = formatEvolutionPrinciples(active, probation);
720
638
  }
721
639
  }
722
640
  catch (e) {
@@ -794,31 +712,14 @@ ${heartbeatChecklist}
794
712
  }
795
713
  // Build appendSystemContext with recency effect
796
714
  // Content order (most important last): behavioral_constraints -> project_context -> working_memory -> reflection_log -> thinking_os -> principles
797
- const appendParts = [];
798
- // 0. Behavioral Constraints (empathy observer coordination)
799
- // Injected here (appendSystemContext) instead of prependContext to hide from WebUI users.
800
- // Behavioral constraints: empathy observer coordination
801
- if (shouldInjectBehavioralConstraints) {
802
- appendParts.push(`<behavioral_constraints>
803
- ${empathySilenceConstraint}
804
- </behavioral_constraints>`);
805
- }
806
- // 1. Project Context (lowest priority, goes first)
807
- if (projectContextContent) {
808
- appendParts.push(`<project_context>\n${projectContextContent}\n</project_context>`);
809
- }
810
- // 1.5. Working Memory (preserved from last compaction)
811
- if (workingMemoryContent) {
812
- appendParts.push(workingMemoryContent);
813
- }
814
- // 2. Thinking OS (configurable)
815
- if (thinkingOsContent) {
816
- appendParts.push(`<thinking_os>\n${thinkingOsContent}\n</thinking_os>`);
817
- }
818
- // 3. Evolution Loop principles (legacy active/probation only — Runtime V2 moved to section 3.5)
819
- if (evolutionPrinciplesContent) {
820
- appendParts.push(`<evolution_principles>\n${evolutionPrinciplesContent}\n</evolution_principles>`);
821
- }
715
+ appendSystemContext = assembleAppendSystemContext({
716
+ behavioralConstraints: shouldInjectBehavioralConstraints ? empathySilenceConstraint : undefined,
717
+ projectContext: projectContextContent || undefined,
718
+ workingMemory: workingMemoryContent || undefined,
719
+ thinkingOs: thinkingOsContent || undefined,
720
+ evolutionPrinciples: evolutionPrinciplesContent || undefined,
721
+ corePrinciples: principlesContent || undefined,
722
+ });
822
723
  // 3.5. Owner-Approved Behavior Directives (Runtime V2 activated principles)
823
724
  // PLACED IN prependSystemContext (before gateway system prompt) for highest LLM attention.
824
725
  // These are owner-reviewed, validated behavior constraints — not background context.
@@ -828,35 +729,11 @@ ${empathySilenceConstraint}
828
729
  }
829
730
  // Routing guidance removed per PRI-291; local-worker-routing module and its
830
731
  // routing helpers deleted per PRI-448. No routing-related content is injected.
831
- // 6. Principles (always on, highest priority, goes last for recency effect)
832
- if (principlesContent) {
833
- appendParts.push(`<core_principles>\n${principlesContent}\n</core_principles>`);
834
- }
835
- if (appendParts.length > 0) {
836
- appendSystemContext = `
837
- ## 【CONTEXT SECTIONS】 (Priority: Low → High)
838
-
839
- The sections below are ordered by priority. When conflicts arise, **later sections override earlier ones**.
840
-
841
- `;
842
- appendSystemContext += appendParts.join('\n\n');
843
- appendSystemContext += `
844
-
845
- ---
846
-
847
- **【EXECUTION RULES】** (Priority: Low → High):
848
- - \`<behavioral_constraints>\` - Output format restrictions (hide diagnostic JSON)
849
- - \`<project_context>\` - Current priorities (can be overridden)
850
- - \`<evolution_principles>\` - Learned principles (active + probation)
851
- - \`<core_principles>\` - Core rules (NON-NEGOTIABLE, highest priority)
852
- `;
853
- }
854
732
  // ──── 8. SIZE GUARD ────
855
733
  // Delegates to @principles/core/prompt-builder/truncateInjectionToBudget
856
734
  // which handles priority stripping: project_context → thinking_os →
857
735
  // evolution_principles → reflection_log → reason: truncation → fallback.
858
736
  const result = truncateInjectionToBudget(prependSystemContext, prependContext, appendSystemContext, {
859
- diagnosticianMode: pendingDiagTaskCount > 0,
860
737
  blocks: { projectContextContent, thinkingOsContent, evolutionPrinciplesContent },
861
738
  });
862
739
  prependSystemContext = result.prependSystemContext;
@@ -865,12 +742,10 @@ The sections below are ordered by priority. When conflicts arise, **later sectio
865
742
  if (result.truncated) {
866
743
  const logEntry = result.truncationLog.join(', ');
867
744
  if (result.appendSystemContext.includes('[WARNING: Context sections stripped')) {
868
- logger?.error(`[PD:Prompt] PROMPT OVER LIMIT AFTER ALL REDUCTIONS — using fallback. ` +
869
- `Diagnostician mode: ${pendingDiagTaskCount > 0}. Stripped: ${logEntry}.`);
745
+ logger?.error(`[PD:Prompt] PROMPT OVER LIMIT AFTER ALL REDUCTIONS — using fallback. Stripped: ${logEntry}.`);
870
746
  }
871
747
  else {
872
- logger?.warn(`[PD:Prompt] Injection size exceeded budget, truncated: ${logEntry || 'none'}, ` +
873
- `diagnostician mode: ${pendingDiagTaskCount > 0}`);
748
+ logger?.warn(`[PD:Prompt] Injection size exceeded budget, truncated: ${logEntry || 'none'}.`);
874
749
  }
875
750
  }
876
751
  return {
@@ -1,57 +1,16 @@
1
1
  /**
2
- * Raw Observation Adapter — PRI-362
2
+ * Raw Observation Adapter — PRI-362 / PRI-446
3
3
  *
4
- * Unified source-kind resolution from RawObservation.
4
+ * The source-kind resolution logic and RawObservation builders have been
5
+ * migrated to principles-core (runtime-v2/evidence-triage/observation-resolver.ts).
5
6
  *
6
- * Replaces scattered resolveSourceKindFrom* functions with a single
7
- * field-driven adapter that maps observation fields to SourceKind.
8
- *
9
- * Field precedence (highest to lowest):
10
- * 1. isManualEntry → owner_reported
11
- * 2. isGateBlock → rulehost_block
12
- * 3. isSubagentError → subagent_error
13
- * 4. isRateLimit → rate_limit (if true)
14
- * 5. toolName === 'pain' / 'skill:pain' → agent_on_owner_request (with openclaw_context_bound) / owner_reported
15
- * 6. failureSource → tool_failure / dispatch_error
16
- * 7. isGfiTriggered → gfi_threshold
17
- * 8. detectionSource → llm_paralysis / semantic / empathy_inferred / unknown
18
- * 9. Fallback → unknown
7
+ * This file is now a thin re-export adapter. It preserves the original export
8
+ * names (resolveSourceKind, buildToolFailureObservation, buildLlmDetectionObservation,
9
+ * RawObservation) so all existing import sites and the source-string
10
+ * characterization tests keep working without changes.
19
11
  *
20
12
  * ERR checklist:
21
- * - ERR-001: Source kind resolved from runtime values, no `as` casts.
22
- * - ERR-002: Every path returns a valid SourceKind (fallback to 'unknown').
23
- * - EP-01: Runtime values validated before use.
13
+ * - ERR-011: re-export adapter, not a local re-definition of migrated logic.
24
14
  */
25
- import type { SourceKind } from '@principles/core/runtime-v2';
26
- import type { RawObservation } from './raw-observation-types.js';
15
+ export { resolveSourceKind, buildToolFailureObservation, buildLlmDetectionObservation, } from '@principles/core/runtime-v2';
27
16
  export type { RawObservation } from './raw-observation-types.js';
28
- /**
29
- * Resolve SourceKind from a unified RawObservation.
30
- *
31
- * This function replaces the scattered resolveSourceKindFrom* functions
32
- * and provides a single entry point for source-kind classification.
33
- *
34
- * Field precedence is explicitly defined in the function body to ensure
35
- * deterministic behavior and make the logic easy to understand and test.
36
- */
37
- export declare function resolveSourceKind(observation: RawObservation): SourceKind;
38
- /**
39
- * Build a RawObservation for a tool failure context.
40
- *
41
- * This replaces classifyToolFailureSource and the inline classification
42
- * in after-tool-call-helpers. All tool error → dispatch/tool_failure
43
- * classification is centralized here.
44
- */
45
- export declare function buildToolFailureObservation(options: {
46
- toolName: string | undefined;
47
- error: unknown;
48
- exitCode?: number;
49
- provenance?: RawObservation['provenance'];
50
- }): RawObservation;
51
- /**
52
- * Build a RawObservation for an LLM detection context.
53
- */
54
- export declare function buildLlmDetectionObservation(options: {
55
- detectionSource: string;
56
- isGfiTriggered: boolean;
57
- }): RawObservation;