principles-disciple 1.137.0 → 1.139.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,10 +16,11 @@ function scanEnvironment(wctx) {
16
16
  const tools = {};
17
17
  for (const tool of TOOLS_TO_SCAN) {
18
18
  try {
19
- const [versionLine] = execSync(tool.cmd.join(' '), { stdio: ['ignore', 'pipe', 'ignore'] }).toString().split('\n');
19
+ const lines = execSync(tool.cmd.join(' '), { stdio: ['ignore', 'pipe', 'ignore'] }).toString().split('\n');
20
+ const versionLine = lines[0];
20
21
  tools[tool.name] = {
21
22
  available: true,
22
- version: versionLine.trim(),
23
+ version: versionLine ? versionLine.trim() : undefined,
23
24
  };
24
25
  // eslint-disable-next-line @typescript-eslint/no-unused-vars -- Reason: catch parameter intentionally unused - we only care that the command failed
25
26
  }
@@ -108,7 +108,7 @@ export function handleDisableImplCommand(ctx) {
108
108
  const subcommand = parts[0] || '';
109
109
  const implId = subcommand === 'list' ? '' : subcommand;
110
110
  const reasonMatch = (/--reason\s+"([^"]+)"/.exec(args)) || (/--reason\s+(\S+)/.exec(args));
111
- const reason = reasonMatch ? reasonMatch[1] : null;
111
+ const reason = reasonMatch ? (reasonMatch[1] ?? null) : null;
112
112
  // Subcommand: list
113
113
  if (subcommand === 'list' || subcommand === '') {
114
114
  return _handleListActive(stateDir, isZh);
@@ -57,6 +57,8 @@ function compressFocusContent(content, workspaceDir) {
57
57
  };
58
58
  for (let i = 0; i < lines.length; i++) {
59
59
  const line = lines[i];
60
+ if (!line)
61
+ continue;
60
62
  const trimmedLine = line.trim();
61
63
  // 识别章节
62
64
  if (/^#{1,3}\s*.*状态快照|📍/.test(trimmedLine)) {
@@ -245,7 +247,8 @@ async function compressFocus(workspaceDir, isZh, api) {
245
247
  compressedContent = oldContent;
246
248
  }
247
249
  // 6. 更新版本号和日期
248
- const [majorVersion] = oldVersion.split('.');
250
+ const versionParts = oldVersion.split('.');
251
+ const majorVersion = versionParts[0] ?? '';
249
252
  const newVersion = `${(parseInt(majorVersion, 10) || 1) + 1}`;
250
253
  const [today] = new Date().toISOString().split('T');
251
254
  const newContent = compressedContent
@@ -314,6 +317,11 @@ function rollbackFocus(workspaceDir, index, isZh) {
314
317
  : `❌ Invalid index: ${index}\n\n💡 Please enter a number between 1-${files.length}`;
315
318
  }
316
319
  const targetFile = files[index - 1];
320
+ if (!targetFile) {
321
+ return isZh
322
+ ? `❌ 无效的序号: ${index}\n\n💡 请输入 1-${files.length} 之间的数字`
323
+ : `❌ Invalid index: ${index}\n\n💡 Please enter a number between 1-${files.length}`;
324
+ }
317
325
  const historyContent = fs.readFileSync(targetFile.path, 'utf-8');
318
326
  // 备份当前版本
319
327
  const currentContent = fs.existsSync(focusPath)
@@ -416,7 +424,7 @@ export async function handleFocusCommand(ctx, api) {
416
424
  break;
417
425
  case 'rollback':
418
426
  case 'rb': {
419
- const index = parseInt(args[1], 10);
427
+ const index = parseInt(args[1] ?? '', 10);
420
428
  if (isNaN(index)) {
421
429
  result = isZh
422
430
  ? '❌ 请指定要回滚的版本序号\n\n💡 输入 `/pd-focus history` 查看可用版本'
@@ -46,7 +46,7 @@ export function handleRollbackImplCommand(ctx) {
46
46
  const subcommand = args.split(/\s+/)[0] || '';
47
47
  const implId = subcommand === 'list' ? '' : subcommand;
48
48
  const reasonMatch = (/--reason\s+"([^"]+)"/.exec(args)) || (/--reason\s+(\S+)/.exec(args));
49
- const reason = reasonMatch ? reasonMatch[1] : null;
49
+ const reason = reasonMatch ? (reasonMatch[1] ?? null) : null;
50
50
  // List active
51
51
  if (subcommand === 'list' || subcommand === '') {
52
52
  return _handleListActiveRollback(stateDir, isZh);
@@ -16,7 +16,11 @@ function getModels(wctx) {
16
16
  for (const line of lines) {
17
17
  const match = /^###\s*(T-\d+):\s*(.*)/.exec(line);
18
18
  if (match) {
19
- models[match[1]] = match[2].trim();
19
+ const key = match[1];
20
+ const value = match[2];
21
+ if (key === undefined || value === undefined)
22
+ continue;
23
+ models[key] = value.trim();
20
24
  }
21
25
  }
22
26
  }
@@ -103,6 +103,8 @@ export class CorrectionCueLearner {
103
103
  if (keywordIndex < 0)
104
104
  continue;
105
105
  const keyword = this.store.keywords[keywordIndex];
106
+ if (!keyword)
107
+ continue;
106
108
  this.store.keywords[keywordIndex] = {
107
109
  ...keyword,
108
110
  hitCount: (keyword.hitCount ?? 0) + 1,
@@ -30,7 +30,7 @@ export class EventLog {
30
30
  return path.join(this.logsDir, `events_${date}.jsonl`);
31
31
  }
32
32
  getTodayStr() {
33
- return new Date().toISOString().split('T')[0];
33
+ return new Date().toISOString().split('T')[0] ?? '';
34
34
  }
35
35
  ensureEventsFile() {
36
36
  const today = this.getTodayStr();
@@ -255,7 +255,7 @@ export class EventLog {
255
255
  }
256
256
  }
257
257
  formatDate(date) {
258
- return date.toISOString().split('T')[0];
258
+ return date.toISOString().split('T')[0] ?? '';
259
259
  }
260
260
  loadStats() {
261
261
  if (fs.existsSync(this.statsFile)) {
@@ -343,11 +343,14 @@ export class EventLog {
343
343
  if (!stats.hooks.byType[data.hook]) {
344
344
  stats.hooks.byType[data.hook] = { total: 0, success: 0, failure: 0 };
345
345
  }
346
- stats.hooks.byType[data.hook].total++;
347
- if (entry.category === 'success')
348
- stats.hooks.byType[data.hook].success++;
349
- else
350
- stats.hooks.byType[data.hook].failure++;
346
+ const hookStats = stats.hooks.byType[data.hook];
347
+ if (hookStats) {
348
+ hookStats.total++;
349
+ if (entry.category === 'success')
350
+ hookStats.success++;
351
+ else
352
+ hookStats.failure++;
353
+ }
351
354
  }
352
355
  }
353
356
  else if (entry.type === 'empathy_rollback') {
@@ -383,13 +386,13 @@ export class EventLog {
383
386
  const raw = entry.data;
384
387
  if (Object.prototype.hasOwnProperty.call(raw, 'category')) {
385
388
  const cat = raw['category'];
386
- if (cat === 'success' || cat === 'missing_json' || cat === 'incomplete_fields') {
389
+ if (typeof cat === 'string' && (cat === 'success' || cat === 'missing_json' || cat === 'incomplete_fields')) {
387
390
  stats.evolution.diagnosticianReportsWritten++;
388
391
  }
389
- if (cat === 'missing_json') {
392
+ if (typeof cat === 'string' && cat === 'missing_json') {
390
393
  stats.evolution.reportsMissingJson++;
391
394
  }
392
- if (cat === 'incomplete_fields') {
395
+ if (typeof cat === 'string' && cat === 'incomplete_fields') {
393
396
  stats.evolution.reportsIncompleteFields++;
394
397
  }
395
398
  }
@@ -651,6 +654,8 @@ export class EventLog {
651
654
  const allEvents = this.getMergedEvents();
652
655
  for (let i = allEvents.length - 1; i >= 0; i--) {
653
656
  const entry = allEvents[i];
657
+ if (!entry)
658
+ continue;
654
659
  if (entry.sessionId === sessionId && entry.type === 'pain_signal') {
655
660
  const data = entry.data;
656
661
  if (data.source === 'user_empathy' && !data.deduped) {
@@ -664,6 +669,8 @@ export class EventLog {
664
669
  const allEvents = this.getMergedEvents();
665
670
  for (let i = allEvents.length - 1; i >= 0; i--) {
666
671
  const entry = allEvents[i];
672
+ if (!entry)
673
+ continue;
667
674
  if (entry.sessionId === sessionId && entry.type === "pain_signal") {
668
675
  return entry.data;
669
676
  }
@@ -503,7 +503,7 @@ export function recoverFromTemplate(focusPath, extensionRoot) {
503
503
  };
504
504
  }
505
505
  let template = fs.readFileSync(templatePath, 'utf-8');
506
- const [today] = new Date().toISOString().split('T');
506
+ const today = new Date().toISOString().split('T')[0] ?? '';
507
507
  template = template.replace(/{YYYY-MM-DD}/g, today);
508
508
  if (fs.existsSync(focusPath)) {
509
509
  const backupPath = `${focusPath}.corrupted.${Date.now()}.md`;
@@ -24,7 +24,7 @@ export class HygieneTracker {
24
24
  this.currentStats = this.loadStats();
25
25
  }
26
26
  loadStats() {
27
- const [today] = new Date().toISOString().split('T');
27
+ const today = new Date().toISOString().split('T')[0] ?? '';
28
28
  if (fs.existsSync(this.statsFile)) {
29
29
  try {
30
30
  const content = fs.readFileSync(this.statsFile, 'utf-8');
@@ -54,7 +54,7 @@ export class HygieneTracker {
54
54
  saveStats() {
55
55
  let allStats = {};
56
56
  // Check if we need to rotate date (reset currentStats if date changed)
57
- const [today] = new Date().toISOString().split('T');
57
+ const today = new Date().toISOString().split('T')[0] ?? '';
58
58
  if (this.currentStats.date !== today) {
59
59
  this.currentStats = createEmptyHygieneStats(today);
60
60
  }
@@ -101,7 +101,7 @@ export class HygieneTracker {
101
101
  }
102
102
  getStats() {
103
103
  // Check for date change on every get
104
- const [today] = new Date().toISOString().split('T');
104
+ const today = new Date().toISOString().split('T')[0] ?? '';
105
105
  if (this.currentStats.date !== today) {
106
106
  this.currentStats = createEmptyHygieneStats(today);
107
107
  }
@@ -244,6 +244,8 @@ export class PrincipleCompiler {
244
244
  if (patterns.length === 0)
245
245
  return [];
246
246
  const pattern = patterns[0];
247
+ if (!pattern)
248
+ return [];
247
249
  // Skip replay when the pattern has no regex qualifier -- the generated template
248
250
  // blocks ALL calls to the tool, making it impossible to construct a passing
249
251
  // positive case. Replay is only meaningful when the template is selective.
@@ -30,7 +30,7 @@ export class ReplayEngine {
30
30
  }
31
31
  getLatestReport(implementationId) {
32
32
  const reports = this.listReports(implementationId);
33
- return reports.length > 0 ? reports[0] : null;
33
+ return reports[0] ?? null;
34
34
  }
35
35
  hasPassingReport(implementationId) {
36
36
  return this.listReports(implementationId).some((report) => report.overallDecision === 'pass');
@@ -188,7 +188,9 @@ export class RuleHost {
188
188
  }
189
189
  }
190
190
  else {
191
- validRows.push(group[0]);
191
+ const row = group[0];
192
+ if (row)
193
+ validRows.push(row);
192
194
  }
193
195
  }
194
196
  const loaded = [];
@@ -23,7 +23,10 @@ function extractTag(content, tagName) {
23
23
  const match = content.match(regex);
24
24
  if (!match)
25
25
  return '';
26
- return match[1].trim().replace(/\s+/g, ' ');
26
+ const raw = match[1];
27
+ if (!raw)
28
+ return '';
29
+ return raw.trim().replace(/\s+/g, ' ');
27
30
  }
28
31
  /**
29
32
  * Parse THINKING_OS.md content and extract all <directive> blocks.
@@ -35,14 +38,20 @@ export function parseThinkingOsMd(content) {
35
38
  const directiveRegex = /<directive\s+([^>]*)>([\s\S]*?)<\/directive>/gi;
36
39
  let _match = null;
37
40
  while ((_match = directiveRegex.exec(content)) !== null) {
38
- const [, attrs, body] = _match;
41
+ const attrs = _match[1];
42
+ const body = _match[2];
43
+ if (!attrs || !body)
44
+ continue;
39
45
  const idMatch = /id="([^"]+)"/i.exec(attrs);
40
46
  const nameMatch = /name="([^"]+)"/i.exec(attrs);
41
47
  if (!idMatch)
42
48
  continue;
49
+ const id = idMatch[1];
50
+ if (!id)
51
+ continue;
43
52
  const directive = {
44
- id: idMatch[1],
45
- name: nameMatch ? nameMatch[1] : '',
53
+ id,
54
+ name: nameMatch ? (nameMatch[1] ?? '') : '',
46
55
  trigger: extractTag(body, 'trigger'),
47
56
  must: extractTag(body, 'must'),
48
57
  forbidden: extractTag(body, 'forbidden'),
@@ -1,9 +1,23 @@
1
1
  /**
2
2
  * Trajectory Collector - message write trajectory recording
3
3
  *
4
- * Records message data to memory/trajectories/ JSONL files.
5
- * PRI-347 removed tool_call and llm_output JSONL writers (no consumers).
6
- * PRI-346 will repurpose handleBeforeMessageWrite for SQLite collection.
4
+ * Fallback trajectory collection when llm_output is blocked by missing
5
+ * allowConversationAccess. before_message_write is NOT in
6
+ * CONVERSATION_HOOK_NAMES so OpenClaw always delivers it.
7
+ *
8
+ * SQLite writes are enqueued to an async queue because before_message_write is
9
+ * a SYNCHRONOUS OpenClaw hook — the handler must return immediately. better-sqlite3
10
+ * is synchronous, so calling it directly would block the message-write main path.
11
+ * Trade-off: in degradation mode the last few queued writes may be lost on
12
+ * process exit; this is acceptable because degradation mode is already caused
13
+ * by a config problem (missing allowConversationAccess), and the primary
14
+ * llm_output path is authoritative when authorized.
15
+ *
16
+ * JSONL writing was removed (no consumers — verified zero readers across the
17
+ * codebase; PRI-347 already removed tool_call/llm_output JSONL writers).
18
+ *
19
+ * ERR-002: fallback errors are logged, never silent.
20
+ * ERR-001/005: content is sanitized before persisting.
7
21
  */
8
22
  import type { PluginHookAgentContext, PluginHookBeforeMessageWriteEvent } from '../openclaw-sdk.js';
9
23
  /**
@@ -14,7 +28,9 @@ import type { PluginHookAgentContext, PluginHookBeforeMessageWriteEvent } from '
14
28
  * CONVERSATION_HOOK_NAMES, so it always fires — making it the natural fallback.
15
29
  *
16
30
  * De-duplication: only writes to SQLite when llm_output is blocked (unauthorized).
17
- * When llm_output is working (authorized), this hook degrades to JSONL-only.
31
+ * When llm_output is working (authorized), this hook is a no-op.
32
+ *
33
+ * SQLite writes are async-queued (see file header) to avoid blocking the sync hook.
18
34
  *
19
35
  * ERR-002: structured observability when fallback fires.
20
36
  * ERR-001/005: content is sanitized before persisting.
@@ -1,127 +1,79 @@
1
1
  /**
2
2
  * Trajectory Collector - message write trajectory recording
3
3
  *
4
- * Records message data to memory/trajectories/ JSONL files.
5
- * PRI-347 removed tool_call and llm_output JSONL writers (no consumers).
6
- * PRI-346 will repurpose handleBeforeMessageWrite for SQLite collection.
4
+ * Fallback trajectory collection when llm_output is blocked by missing
5
+ * allowConversationAccess. before_message_write is NOT in
6
+ * CONVERSATION_HOOK_NAMES so OpenClaw always delivers it.
7
+ *
8
+ * SQLite writes are enqueued to an async queue because before_message_write is
9
+ * a SYNCHRONOUS OpenClaw hook — the handler must return immediately. better-sqlite3
10
+ * is synchronous, so calling it directly would block the message-write main path.
11
+ * Trade-off: in degradation mode the last few queued writes may be lost on
12
+ * process exit; this is acceptable because degradation mode is already caused
13
+ * by a config problem (missing allowConversationAccess), and the primary
14
+ * llm_output path is authoritative when authorized.
15
+ *
16
+ * JSONL writing was removed (no consumers — verified zero readers across the
17
+ * codebase; PRI-347 already removed tool_call/llm_output JSONL writers).
18
+ *
19
+ * ERR-002: fallback errors are logged, never silent.
20
+ * ERR-001/005: content is sanitized before persisting.
7
21
  */
8
- import * as fs from 'fs';
9
- import * as path from 'path';
10
22
  import { MAX_STRING_LENGTH } from '../config/defaults/runtime.js';
11
23
  import { WorkspaceContext } from '../core/workspace-context.js';
12
24
  import { SystemLogger } from '../core/system-logger.js';
13
25
  import { sanitizeForEvidence } from './message-sanitize.js';
14
26
  import { checkConversationAccessConfig } from '../core/config-health.js';
15
- const TRAJECTORY_DIR = 'memory/trajectories/';
16
- // 敏感字段匹配正则
17
- const SENSITIVE_KEY_PATTERN = /password|token|authorization|secret|api[_-]?key|credential|cookie|session/i;
18
- /**
19
- * 递归脱敏处理:遍历对象/数组,移除敏感字段值
20
- */
21
- function scrubSensitive(obj, depth = 0) {
22
- // 防止无限递归
23
- if (depth > 10)
24
- return '[MAX_DEPTH]';
25
- // 处理 null/undefined
26
- if (obj == null)
27
- return obj;
28
- // 处理基本类型
29
- if (typeof obj !== 'object') {
30
- if (typeof obj === 'string' && obj.length > MAX_STRING_LENGTH) {
31
- return obj.slice(0, MAX_STRING_LENGTH) + '...[truncated]';
32
- }
33
- return obj;
34
- }
35
- // 处理数组
36
- if (Array.isArray(obj)) {
37
- return obj.map(item => scrubSensitive(item, depth + 1));
38
- }
39
- // 处理对象
40
- const result = {};
41
- for (const [key, value] of Object.entries(obj)) {
42
- if (SENSITIVE_KEY_PATTERN.test(key)) {
43
- result[key] = '[REDACTED]';
44
- }
45
- else {
46
- result[key] = scrubSensitive(value, depth + 1);
47
- }
48
- }
49
- return result;
50
- }
51
27
  /**
52
- * 异步写入队列 - 确保有序、非阻塞写入
28
+ * Async write queue — ensures ordered, non-blocking execution of SQLite writes.
29
+ * before_message_write is a sync hook; SQLite I/O must not block it.
30
+ *
31
+ * Tasks are deferred to the microtask queue via `queueMicrotask` so the sync
32
+ * hook handler returns before any synchronous better-sqlite3 work runs.
53
33
  */
54
34
  class AsyncWriteQueue {
55
35
  queue = [];
56
36
  processing = false;
57
- async enqueue(task) {
37
+ enqueue(task) {
58
38
  this.queue.push(task);
59
39
  if (!this.processing) {
60
- this.processNext();
40
+ this.processing = true;
41
+ queueMicrotask(() => { void this.processNext(); });
61
42
  }
62
43
  }
63
44
  async processNext() {
64
- if (this.queue.length === 0) {
65
- this.processing = false;
66
- return;
67
- }
68
- this.processing = true;
69
- const task = this.queue.shift();
70
- if (!task) {
71
- this.processing = false;
72
- return;
45
+ while (this.queue.length > 0) {
46
+ const task = this.queue.shift();
47
+ if (!task)
48
+ break;
49
+ try {
50
+ await task();
51
+ }
52
+ catch (err) {
53
+ // EP-03/ERR-002: safety net — tasks should catch their own errors with
54
+ // structured logging. This catches bugs where a task's try/catch is
55
+ // missing or re-throws. Never silently swallow (ERR-002).
56
+ console.warn('[PD:trajectory-queue] uncaught task error:', err);
57
+ }
73
58
  }
74
- try {
75
- await task();
76
- }
77
- catch {
78
- // Silently fail - trajectory collection should not block main functionality
79
- }
80
- // 处理下一个任务
81
- this.processNext();
59
+ this.processing = false;
82
60
  }
83
61
  }
84
- // 全局写入队列实例
85
62
  const writeQueue = new AsyncWriteQueue();
86
- // 目录缓存(避免重复检查)
87
- const dirCache = new Map();
88
63
  /**
89
- * 确保轨迹目录存在(异步)
64
+ * Extract text content from a message (string or content-part array).
90
65
  */
91
- async function ensureTrajectoryDirAsync(workspaceDir) {
92
- const dir = path.join(workspaceDir, TRAJECTORY_DIR);
93
- if (dirCache.get(dir)) {
94
- return dir;
95
- }
96
- try {
97
- await fs.promises.mkdir(dir, { recursive: true });
98
- dirCache.set(dir, true);
66
+ function extractContent(content) {
67
+ if (typeof content === 'string') {
68
+ return content;
99
69
  }
100
- catch {
101
- // 目录可能已存在,忽略错误
102
- dirCache.set(dir, true);
70
+ if (Array.isArray(content)) {
71
+ return content
72
+ .filter((part) => part && typeof part === 'object' && part.type === 'text')
73
+ .map((part) => part.text)
74
+ .join('\n');
103
75
  }
104
- return dir;
105
- }
106
- /**
107
- * 获取今日轨迹文件名
108
- */
109
- function getTodayFilename() {
110
- const now = new Date();
111
- const year = now.getUTCFullYear();
112
- const month = String(now.getUTCMonth() + 1).padStart(2, '0');
113
- return `${year}-${month}-${String(now.getUTCDate()).padStart(2, '0')}.jsonl`;
114
- }
115
- /**
116
- * 写入轨迹记录(JSON Lines 格式)- 异步版本
117
- */
118
- function writeTrajectoryRecord(workspaceDir, record) {
119
- const line = JSON.stringify(record) + '\n';
120
- writeQueue.enqueue(async () => {
121
- const dir = await ensureTrajectoryDirAsync(workspaceDir);
122
- const filepath = path.join(dir, getTodayFilename());
123
- await fs.promises.appendFile(filepath, line, 'utf8');
124
- });
76
+ return '';
125
77
  }
126
78
  /**
127
79
  * PRI-346: Message write hook with SQLite fallback trajectory recording.
@@ -131,7 +83,9 @@ function writeTrajectoryRecord(workspaceDir, record) {
131
83
  * CONVERSATION_HOOK_NAMES, so it always fires — making it the natural fallback.
132
84
  *
133
85
  * De-duplication: only writes to SQLite when llm_output is blocked (unauthorized).
134
- * When llm_output is working (authorized), this hook degrades to JSONL-only.
86
+ * When llm_output is working (authorized), this hook is a no-op.
87
+ *
88
+ * SQLite writes are async-queued (see file header) to avoid blocking the sync hook.
135
89
  *
136
90
  * ERR-002: structured observability when fallback fires.
137
91
  * ERR-001/005: content is sanitized before persisting.
@@ -146,73 +100,58 @@ export function handleBeforeMessageWrite(event, ctx) {
146
100
  // Only record user and assistant messages
147
101
  if (msg.role !== 'user' && msg.role !== 'assistant')
148
102
  return;
149
- // Extract text content (consistent with existing implementation)
150
- let content = '';
151
- if (typeof msg.content === 'string') {
152
- content = msg.content;
153
- }
154
- else if (Array.isArray(msg.content)) {
155
- content = msg.content
156
- .filter((part) => part && typeof part === 'object' && part.type === 'text')
157
- .map((part) => part.text)
158
- .join('\n');
159
- }
160
- // Sanitize content preview for JSONL
161
- const sanitizedPreview = scrubSensitive(content.slice(0, 200));
162
- // Existing JSONL write (always, for backward compatibility)
163
- writeTrajectoryRecord(workspaceDir, {
164
- type: 'message',
165
- timestamp: new Date().toISOString(),
166
- sessionId: event.sessionKey || event.sessionId || 'unknown',
167
- role: msg.role,
168
- contentLength: content.length,
169
- contentPreview: typeof sanitizedPreview === 'string' ? sanitizedPreview : '[sanitized]',
170
- agentId: event.agentId || null,
171
- fallback: 'before_message_write',
172
- });
173
103
  // ── SQLite fallback (PRI-346): only when conversation hooks are blocked ──
174
104
  const accessCheck = checkConversationAccessConfig(ctx.pluginConfig);
175
105
  if (accessCheck.authorized) {
176
106
  // llm_output is working — do NOT duplicate write to SQLite (de-dup, case D)
177
107
  return;
178
108
  }
179
- // Conversation hooks blocked — this hook is the fallback trajectory writer
109
+ // Conversation hooks blocked — this hook is the fallback trajectory writer.
110
+ // Enqueue SQLite writes to avoid blocking the sync before_message_write hook.
111
+ const logger = ctx.logger;
112
+ const content = extractContent(msg.content);
113
+ const sessionId = event.sessionKey ?? ctx.sessionId ?? 'unknown';
114
+ const createdAt = new Date().toISOString();
180
115
  if (msg.role === 'assistant') {
181
- try {
182
- const wctx = WorkspaceContext.fromHookContext({ workspaceDir, logger: ctx.logger });
183
- const sanitized = sanitizeForEvidence(content.slice(0, MAX_STRING_LENGTH), workspaceDir);
184
- const sessionId = event.sessionKey ?? ctx.sessionId ?? 'unknown';
185
- wctx.trajectory?.recordAssistantTurn?.({
186
- sessionId,
187
- runId: 'before_message_write_fallback',
188
- provider: 'unknown',
189
- model: 'unknown',
190
- rawText: content,
191
- sanitizedText: sanitized,
192
- usageJson: {},
193
- empathySignalJson: { detected: false, severity: 'mild', confidence: 1 },
194
- createdAt: new Date().toISOString(),
195
- });
196
- }
197
- catch (err) {
198
- ctx.logger?.warn?.(`[PD:before_message_write] SQLite fallback write failed: ${String(err)}`);
199
- }
116
+ writeQueue.enqueue(async () => {
117
+ try {
118
+ const wctx = WorkspaceContext.fromHookContext({ workspaceDir, logger });
119
+ const sanitized = sanitizeForEvidence(content.slice(0, MAX_STRING_LENGTH), workspaceDir);
120
+ wctx.trajectory?.recordAssistantTurn?.({
121
+ sessionId,
122
+ runId: 'before_message_write_fallback',
123
+ provider: 'unknown',
124
+ model: 'unknown',
125
+ rawText: content,
126
+ sanitizedText: sanitized,
127
+ usageJson: {},
128
+ empathySignalJson: { detected: false, severity: 'mild', confidence: 1 },
129
+ createdAt,
130
+ });
131
+ }
132
+ catch (err) {
133
+ // EP-03/ERR-002: observable degradation, never silent
134
+ logger?.warn?.(`[PD:before_message_write] SQLite fallback write failed: ${String(err)}`);
135
+ }
136
+ });
200
137
  }
201
138
  else if (msg.role === 'user') {
202
- try {
203
- const wctx = WorkspaceContext.fromHookContext({ workspaceDir, logger: ctx.logger });
204
- const sessionId = event.sessionKey ?? ctx.sessionId ?? 'unknown';
205
- wctx.trajectory?.recordUserTurn?.({
206
- sessionId,
207
- turnIndex: 0,
208
- rawText: content.slice(0, MAX_STRING_LENGTH),
209
- correctionDetected: false,
210
- createdAt: new Date().toISOString(),
211
- });
212
- }
213
- catch (err) {
214
- ctx.logger?.warn?.(`[PD:before_message_write] SQLite user turn fallback failed: ${String(err)}`);
215
- }
139
+ writeQueue.enqueue(async () => {
140
+ try {
141
+ const wctx = WorkspaceContext.fromHookContext({ workspaceDir, logger });
142
+ wctx.trajectory?.recordUserTurn?.({
143
+ sessionId,
144
+ turnIndex: 0,
145
+ rawText: content.slice(0, MAX_STRING_LENGTH),
146
+ correctionDetected: false,
147
+ createdAt,
148
+ });
149
+ }
150
+ catch (err) {
151
+ // EP-03/ERR-002: observable degradation, never silent
152
+ logger?.warn?.(`[PD:before_message_write] SQLite user turn fallback failed: ${String(err)}`);
153
+ }
154
+ });
216
155
  }
217
156
  // ERR-002: Structured observability — no silent fallback
218
157
  SystemLogger.log(workspaceDir, 'CONVERSATION_HOOK_BLOCKED', JSON.stringify({
package/dist/index.js CHANGED
@@ -266,6 +266,9 @@ const plugin = {
266
266
  }
267
267
  }));
268
268
  // ── Hook: Pain & Trust ──
269
+ // timeoutMs=10s: OpenClaw has no default timeout for after_tool_call; without
270
+ // this a stuck SQLite write (busy_timeout=5000ms) leaks the handler promise.
271
+ // 10s gives 2x headroom over busy_timeout. fail-open means agent is unaffected.
269
272
  api.on('after_tool_call', guardHook('hook:after_tool_call', api.logger, (event, ctx) => {
270
273
  const wsResult = resolveHookWorkspaceDir(ctx, api, 'after_tool_call');
271
274
  if (!wsResult.ok) {
@@ -294,8 +297,10 @@ const plugin = {
294
297
  }, { flushImmediately: true });
295
298
  api.logger.error(`[PD:EmpathyObserver] Error in after_tool_call: ${String(err)}`);
296
299
  }
297
- }));
300
+ }), { timeoutMs: 10_000 });
298
301
  // ── Hook: LLM Analysis ──
302
+ // timeoutMs=10s: OpenClaw has no default timeout for llm_output; without
303
+ // this a stuck SQLite write leaks the handler promise. See after_tool_call.
299
304
  api.on('llm_output', guardHook('hook:llm_output', api.logger, (event, ctx) => {
300
305
  const wsResult = resolveHookWorkspaceDir(ctx, api, 'llm_output');
301
306
  if (!wsResult.ok) {
@@ -325,7 +330,7 @@ const plugin = {
325
330
  });
326
331
  api.logger.error(`[PD] Error in llm_output: ${String(err)}`);
327
332
  }
328
- }));
333
+ }), { timeoutMs: 10_000 });
329
334
  // ── Hook: Lifecycle ──
330
335
  api.on('before_reset', guardHook('hook:before_reset', api.logger, (event, ctx) => {
331
336
  const wsResult = resolveHookWorkspaceDir(ctx, api, 'before_reset');
@@ -151,7 +151,10 @@ export interface OpenClawPluginApi {
151
151
  text: (content: string, code?: number) => void;
152
152
  }) => boolean | Promise<boolean>;
153
153
  }) => void;
154
- on: (event: string, handler: (...args: any[]) => unknown) => void;
154
+ on: (event: string, handler: (...args: any[]) => unknown, opts?: {
155
+ priority?: number;
156
+ timeoutMs?: number;
157
+ }) => void;
155
158
  }
156
159
  export interface PluginHookBeforePromptBuildEvent {
157
160
  agentId?: string;
@@ -93,7 +93,8 @@ export function purgeStaleFailedTasks(queue, logger) {
93
93
  // Remove purged items from the queue (mutates in place)
94
94
  const purgedIds = new Set(purged.map((t) => t.id));
95
95
  for (let i = queue.length - 1; i >= 0; i--) {
96
- if (purgedIds.has(queue[i].id))
96
+ const task = queue[i];
97
+ if (task && purgedIds.has(task.id))
97
98
  queue.splice(i, 1);
98
99
  }
99
100
  const summary = Object.entries(byReason)
@@ -377,17 +378,20 @@ async function processDetectionQueue(wctx, api, eventLog) {
377
378
  if (wctx.trajectory) {
378
379
  const searchResults = wctx.trajectory.searchPainEvents(text, 5);
379
380
  if (searchResults.length > 0) {
381
+ const topResult = searchResults[0];
382
+ if (!topResult)
383
+ continue;
380
384
  // Found similar pain events - record as L3 semantic hit
381
385
  if (eventLog) {
382
386
  eventLog.recordRuleMatch(undefined, {
383
387
  ruleId: 'l3_semantic',
384
388
  layer: 'L3',
385
- severity: searchResults[0].score,
389
+ severity: topResult.score,
386
390
  textPreview: text.substring(0, 100)
387
391
  });
388
392
  }
389
393
  // Update detection funnel cache with L3 hit result
390
- funnel.updateCache(text, { detected: true, severity: searchResults[0].score });
394
+ funnel.updateCache(text, { detected: true, severity: topResult.score });
391
395
  // Don't track as candidate - this is a confirmed L3 hit
392
396
  if (logger)
393
397
  logger.info(`[PD:EvolutionWorker] L3 semantic hit: found ${searchResults.length} similar pain events for "${text.substring(0, 50)}..."`);
@@ -290,7 +290,10 @@ export class RuntimeSummaryService {
290
290
  if (sessions.length === 0) {
291
291
  return { session: null, reason: 'none' };
292
292
  }
293
- return { session: sessions[0], reason: 'latest_active' };
293
+ const session = sessions[0];
294
+ if (!session)
295
+ return { session: null, reason: 'none' };
296
+ return { session, reason: 'latest_active' };
294
297
  }
295
298
  static mergeSessionSnapshots(persistedSessions, workspaceDir) {
296
299
  const merged = new Map();
@@ -392,6 +395,8 @@ export class RuntimeSummaryService {
392
395
  if (!m)
393
396
  continue;
394
397
  const fileDate = m[1];
398
+ if (!fileDate)
399
+ continue;
395
400
  if (fileDate > newestDate) {
396
401
  newestDate = fileDate;
397
402
  bestFile = path.join(dir, file);
@@ -463,6 +468,8 @@ export class RuntimeSummaryService {
463
468
  static findLastPainSignal(events, sessionId) {
464
469
  for (let i = events.length - 1; i >= 0; i--) {
465
470
  const entry = events[i];
471
+ if (!entry)
472
+ continue;
466
473
  if (entry.type !== 'pain_signal')
467
474
  continue;
468
475
  if (sessionId && entry.sessionId !== sessionId)
@@ -32,7 +32,8 @@ export async function runWorkflowWatchdog(wctx, api, logger) {
32
32
  const ageMin = Math.round((now - wf.created_at) / 60000);
33
33
  details.push(`stale_active: ${wf.workflow_id} (${wf.workflow_type}, ${ageMin}min old)`);
34
34
  const events = store.getEvents(wf.workflow_id);
35
- const lastEventReason = events.length > 0 ? events[events.length - 1].reason : 'unknown';
35
+ const lastEvent = events[events.length - 1];
36
+ const lastEventReason = lastEvent ? lastEvent.reason : 'unknown';
36
37
  if (isExpectedSubagentError(lastEventReason)) {
37
38
  logger?.debug?.(`[PD:Watchdog] Skipping stale active workflow ${wf.workflow_id}: expected subagent error (${lastEventReason})`);
38
39
  continue;
@@ -245,11 +245,13 @@ export function percentile(values, p) {
245
245
  const n = sorted.length;
246
246
  // For small samples, use median to avoid overfitting
247
247
  if (n < 10) {
248
- return sorted[Math.floor(n / 2)];
248
+ const median = sorted[Math.floor(n / 2)];
249
+ return median ?? 0;
249
250
  }
250
251
  // Standard percentile calculation (nearest-rank method)
251
252
  const rank = Math.ceil((p / 100) * n);
252
- return sorted[Math.min(rank, n) - 1];
253
+ const result = sorted[Math.min(rank, n) - 1];
254
+ return result ?? 0;
253
255
  }
254
256
  /**
255
257
  * Clamp timeout to safe bounds.
@@ -317,6 +319,9 @@ export function computeAdaptiveTimeout(history, fallbackMs, options = {}) {
317
319
  const sorted = [...history].sort((a, b) => a - b);
318
320
  const rank = Math.ceil((p / 100) * sorted.length);
319
321
  const pValue = sorted[Math.min(rank, sorted.length) - 1];
322
+ if (pValue === undefined) {
323
+ return Math.max(minTimeoutMs, Math.min(maxTimeoutMs, fallbackMs));
324
+ }
320
325
  const adaptive = pValue * safetyMultiplier;
321
326
  return Math.max(minTimeoutMs, Math.min(maxTimeoutMs, Math.round(adaptive)));
322
327
  }
@@ -13,6 +13,9 @@ export function extractAgentIdFromSessionKey(sessionKey) {
13
13
  const match = /^agent:([^:]+):/.exec(sessionKey);
14
14
  if (!match)
15
15
  return undefined;
16
- const agentId = match[1].trim();
16
+ const raw = match[1];
17
+ if (!raw)
18
+ return undefined;
19
+ const agentId = raw.trim();
17
20
  return agentId || undefined;
18
21
  }
@@ -2,7 +2,7 @@
2
2
  "id": "principles-disciple",
3
3
  "name": "Principles Disciple",
4
4
  "description": "Evolutionary programming agent framework with strategic guardrails and reflection loops.",
5
- "version": "1.137.0",
5
+ "version": "1.139.0",
6
6
  "activation": {
7
7
  "onCapabilities": [
8
8
  "hook"
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "principles-disciple",
3
- "version": "1.137.0",
3
+ "version": "1.139.0",
4
4
  "description": "Native OpenClaw plugin for Principles Disciple",
5
5
  "type": "module",
6
6
  "main": "./dist/bundle.js",