principles-disciple 1.28.0 → 1.28.2
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.
- package/openclaw.plugin.json +4 -4
- package/package.json +4 -4
- package/scripts/validate-live-path.ts +18 -18
- package/src/commands/context.ts +1 -0
- package/src/commands/disable-impl.ts +2 -0
- package/src/commands/evolution-status.ts +2 -0
- package/src/commands/focus.ts +2 -0
- package/src/commands/nocturnal-train.ts +4 -6
- package/src/commands/pain.ts +9 -11
- package/src/commands/pd-reflect.ts +1 -1
- package/src/commands/principle-rollback.ts +1 -0
- package/src/commands/rollback-impl.ts +1 -0
- package/src/core/adaptive-thresholds.ts +1 -0
- package/src/core/bootstrap-rules.ts +3 -3
- package/src/core/dictionary.ts +1 -0
- package/src/core/empathy-keyword-matcher.ts +1 -0
- package/src/core/event-log.ts +2 -0
- package/src/core/evolution-engine.ts +1 -0
- package/src/core/external-training-contract.ts +1 -0
- package/src/core/focus-history.ts +3 -0
- package/src/core/init.ts +1 -0
- package/src/core/merge-gate-audit.ts +1 -1
- package/src/core/nocturnal-arbiter.ts +3 -0
- package/src/core/nocturnal-candidate-scoring.ts +131 -0
- package/src/core/nocturnal-compliance.ts +1 -0
- package/src/core/nocturnal-dataset.ts +1 -0
- package/src/core/nocturnal-executability.ts +1 -0
- package/src/core/nocturnal-reasoning-deriver.ts +338 -0
- package/src/core/nocturnal-rule-implementation-validator.ts +1 -0
- package/src/core/nocturnal-trinity.ts +457 -18
- package/src/core/pain-context-extractor.ts +2 -3
- package/src/core/pain.ts +1 -0
- package/src/core/pd-task-reconciler.ts +1 -0
- package/src/core/pd-task-service.ts +1 -0
- package/src/core/principle-internalization/deprecated-readiness.ts +1 -0
- package/src/core/principle-internalization/principle-lifecycle-service.ts +1 -0
- package/src/core/principle-tree-migration.ts +3 -4
- package/src/core/replay-engine.ts +4 -0
- package/src/core/risk-calculator.ts +1 -0
- package/src/core/rule-host.ts +2 -0
- package/src/core/session-tracker.ts +2 -0
- package/src/core/thinking-models.ts +1 -0
- package/src/core/thinking-os-parser.ts +3 -3
- package/src/core/trajectory.ts +4 -0
- package/src/hooks/bash-risk.ts +1 -1
- package/src/hooks/gfi-gate.ts +1 -1
- package/src/hooks/lifecycle-routing.ts +1 -0
- package/src/hooks/pain.ts +2 -1
- package/src/hooks/prompt.ts +37 -2
- package/src/hooks/subagent.ts +1 -1
- package/src/hooks/trajectory-collector.ts +1 -0
- package/src/http/principles-console-route.ts +2 -0
- package/src/index.ts +1 -1
- package/src/service/central-database.ts +2 -0
- package/src/service/central-sync-service.ts +1 -0
- package/src/service/control-ui-query-service.ts +2 -0
- package/src/service/event-log-auditor.ts +2 -0
- package/src/service/evolution-worker.ts +2 -1
- package/src/service/health-query-service.ts +20 -6
- package/src/service/nocturnal-runtime.ts +4 -0
- package/src/service/runtime-summary-service.ts +5 -0
- package/src/service/subagent-workflow/deep-reflect-workflow-manager.ts +1 -0
- package/src/service/subagent-workflow/nocturnal-workflow-manager.ts +2 -1
- package/src/service/subagent-workflow/subagent-error-utils.ts +1 -0
- package/src/service/subagent-workflow/workflow-manager-base.ts +1 -0
- package/src/tools/critique-prompt.ts +1 -0
- package/src/utils/io.ts +1 -0
- package/tests/core/nocturnal-candidate-scoring.test.ts +132 -0
- package/tests/core/nocturnal-reasoning-deriver.test.ts +372 -0
- package/tests/core/nocturnal-trinity.test.ts +791 -0
package/openclaw.plugin.json
CHANGED
|
@@ -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.28.
|
|
5
|
+
"version": "1.28.2",
|
|
6
6
|
"skills": [
|
|
7
7
|
"./skills"
|
|
8
8
|
],
|
|
@@ -76,8 +76,8 @@
|
|
|
76
76
|
}
|
|
77
77
|
},
|
|
78
78
|
"buildFingerprint": {
|
|
79
|
-
"gitSha": "
|
|
80
|
-
"bundleMd5": "
|
|
81
|
-
"builtAt": "2026-04-
|
|
79
|
+
"gitSha": "25bfc2bb209f",
|
|
80
|
+
"bundleMd5": "b735aa483374dd2c7071295b11161676",
|
|
81
|
+
"builtAt": "2026-04-13T14:25:24.799Z"
|
|
82
82
|
}
|
|
83
83
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "1.28.
|
|
3
|
+
"version": "1.28.2",
|
|
4
4
|
"description": "Native OpenClaw plugin for Principles Disciple",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/bundle.js",
|
|
@@ -40,14 +40,14 @@
|
|
|
40
40
|
"@testing-library/react": "^16.3.0",
|
|
41
41
|
"@types/better-sqlite3": "^7.6.13",
|
|
42
42
|
"@types/micromatch": "^4.0.10",
|
|
43
|
-
"@types/node": "^25.
|
|
43
|
+
"@types/node": "^25.6.0",
|
|
44
44
|
"@types/react": "^19.2.2",
|
|
45
45
|
"@types/react-dom": "^19.2.2",
|
|
46
46
|
"@types/ws": "^8.5.13",
|
|
47
47
|
"@typescript-eslint/eslint-plugin": "^8.58.0",
|
|
48
48
|
"@typescript-eslint/parser": "^8.58.0",
|
|
49
49
|
"@vitest/coverage-v8": "^4.1.0",
|
|
50
|
-
"esbuild": "^0.
|
|
50
|
+
"esbuild": "^0.28.0",
|
|
51
51
|
"eslint": "^10.1.0",
|
|
52
52
|
"jsdom": "^29.0.1",
|
|
53
53
|
"typescript": "^6.0.2",
|
|
@@ -64,7 +64,7 @@
|
|
|
64
64
|
},
|
|
65
65
|
"dependencies": {
|
|
66
66
|
"@sinclair/typebox": "^0.34.48",
|
|
67
|
-
"better-sqlite3": "^12.
|
|
67
|
+
"better-sqlite3": "^12.9.0",
|
|
68
68
|
"lucide-react": "^1.7.0",
|
|
69
69
|
"micromatch": "^4.0.8",
|
|
70
70
|
"react": "^19.2.0",
|
|
@@ -20,6 +20,7 @@
|
|
|
20
20
|
* WORKSPACE_DIR - Optional workspace directory (defaults to process.cwd())
|
|
21
21
|
*/
|
|
22
22
|
|
|
23
|
+
import * as Database from 'better-sqlite3';
|
|
23
24
|
import * as fs from 'fs';
|
|
24
25
|
import * as path from 'path';
|
|
25
26
|
|
|
@@ -33,7 +34,6 @@ const LOCK_STALE_MS = 30_000;
|
|
|
33
34
|
const WORKSPACE_DIR = process.env.WORKSPACE_DIR || process.cwd();
|
|
34
35
|
const STATE_DIR = path.join(WORKSPACE_DIR, '.state');
|
|
35
36
|
const QUEUE_PATH = path.join(STATE_DIR, 'EVOLUTION_QUEUE');
|
|
36
|
-
const QUEUE_LOCK_PATH = QUEUE_PATH + LOCK_SUFFIX;
|
|
37
37
|
const LEDGER_PATH = path.join(STATE_DIR, 'principle_training_state.json');
|
|
38
38
|
const DB_PATH = path.join(STATE_DIR, 'subagent_workflows.db');
|
|
39
39
|
|
|
@@ -80,17 +80,14 @@ async function acquireLockAsync(filePath: string, options: {
|
|
|
80
80
|
baseRetryDelayMs?: number;
|
|
81
81
|
lockStaleMs?: number;
|
|
82
82
|
} = {}): Promise<LockContext> {
|
|
83
|
-
const
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
lockStaleMs: LOCK_STALE_MS,
|
|
88
|
-
...options,
|
|
89
|
-
};
|
|
83
|
+
const lockSuffix = options.lockSuffix ?? LOCK_SUFFIX;
|
|
84
|
+
const maxRetries = options.maxRetries ?? LOCK_MAX_RETRIES;
|
|
85
|
+
const baseRetryDelayMs = options.baseRetryDelayMs ?? LOCK_RETRY_DELAY_MS;
|
|
86
|
+
const lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS;
|
|
90
87
|
const { pid } = process;
|
|
91
|
-
const lockPath = filePath +
|
|
88
|
+
const lockPath = filePath + lockSuffix;
|
|
92
89
|
|
|
93
|
-
for (let attempt = 0; attempt <
|
|
90
|
+
for (let attempt = 0; attempt < maxRetries; attempt++) {
|
|
94
91
|
try {
|
|
95
92
|
// Check if lock file exists and is stale
|
|
96
93
|
if (fs.existsSync(lockPath)) {
|
|
@@ -100,11 +97,11 @@ async function acquireLockAsync(filePath: string, options: {
|
|
|
100
97
|
const lockAge = Date.now() - lockStats.mtimeMs;
|
|
101
98
|
|
|
102
99
|
// Clean up stale lock
|
|
103
|
-
if (lockAge >
|
|
100
|
+
if (lockAge > lockStaleMs) {
|
|
104
101
|
fs.unlinkSync(lockPath);
|
|
105
102
|
} else if (lockPid !== pid) {
|
|
106
103
|
// Lock held by another process
|
|
107
|
-
await new Promise(resolve => setTimeout(resolve,
|
|
104
|
+
await new Promise(resolve => setTimeout(resolve, baseRetryDelayMs));
|
|
108
105
|
continue;
|
|
109
106
|
}
|
|
110
107
|
}
|
|
@@ -125,17 +122,20 @@ async function acquireLockAsync(filePath: string, options: {
|
|
|
125
122
|
},
|
|
126
123
|
};
|
|
127
124
|
} catch (error: unknown) {
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
125
|
+
const err = error as { code?: string };
|
|
126
|
+
if (err.code === 'EEXIST') {
|
|
127
|
+
if (attempt < maxRetries - 1) {
|
|
128
|
+
await new Promise(resolve => setTimeout(resolve, baseRetryDelayMs));
|
|
131
129
|
continue;
|
|
132
130
|
}
|
|
133
131
|
}
|
|
134
|
-
|
|
132
|
+
const lockError = new Error(`Failed to acquire lock for ${filePath}: ${String(error)}`);
|
|
133
|
+
lockError.cause = error;
|
|
134
|
+
throw lockError;
|
|
135
135
|
}
|
|
136
136
|
}
|
|
137
137
|
|
|
138
|
-
throw new Error(`Failed to acquire lock for ${filePath} after ${
|
|
138
|
+
throw new Error(`Failed to acquire lock for ${filePath} after ${maxRetries} attempts`);
|
|
139
139
|
}
|
|
140
140
|
|
|
141
141
|
function releaseLock(ctx: LockContext): void {
|
|
@@ -225,7 +225,6 @@ function listNocturnalWorkflows(): WorkflowRow[] {
|
|
|
225
225
|
return [];
|
|
226
226
|
}
|
|
227
227
|
|
|
228
|
-
const Database = require('better-sqlite3');
|
|
229
228
|
const db = new Database(DB_PATH, { readonly: true });
|
|
230
229
|
const rows = db.prepare(`
|
|
231
230
|
SELECT workflow_id, workflow_type, state, metadata_json, created_at
|
|
@@ -279,6 +278,7 @@ async function main() {
|
|
|
279
278
|
const verbose = process.argv.includes('--verbose');
|
|
280
279
|
|
|
281
280
|
// 1. Check bootstrapped rules
|
|
281
|
+
// eslint-disable-next-line @typescript-eslint/init-declarations
|
|
282
282
|
let rules: LedgerRule[];
|
|
283
283
|
try {
|
|
284
284
|
rules = loadBootstrappedRules();
|
package/src/commands/context.ts
CHANGED
|
@@ -305,6 +305,7 @@ function showHelp(isZh: boolean): string {
|
|
|
305
305
|
/**
|
|
306
306
|
* Main command handler
|
|
307
307
|
*/
|
|
308
|
+
// eslint-disable-next-line complexity -- complexity 15, refactor candidate
|
|
308
309
|
export function handleContextCommand(ctx: PluginCommandContext): PluginCommandResult {
|
|
309
310
|
const workspaceDir = getWorkspaceDir(ctx);
|
|
310
311
|
const args = (ctx.args || '').trim().split(/\s+/);
|
|
@@ -70,6 +70,7 @@ function _handleListActive(
|
|
|
70
70
|
}
|
|
71
71
|
|
|
72
72
|
|
|
73
|
+
// eslint-disable-next-line complexity -- complexity 15, refactor candidate
|
|
73
74
|
function _handleDisableImpl(
|
|
74
75
|
workspaceDir: string,
|
|
75
76
|
stateDir: string,
|
|
@@ -130,6 +131,7 @@ function _handleDisableImpl(
|
|
|
130
131
|
* /pd-disable-impl <implId> - Disable an implementation
|
|
131
132
|
* /pd-disable-impl <implId> --reason "<reason>" - Disable with reason
|
|
132
133
|
*/
|
|
134
|
+
// eslint-disable-next-line complexity -- complexity 12, refactor candidate
|
|
133
135
|
export function handleDisableImplCommand(ctx: PluginCommandContext): PluginCommandResult {
|
|
134
136
|
const workspaceDir = (ctx.config?.workspaceDir as string) || process.cwd();
|
|
135
137
|
const {stateDir} = WorkspaceContext.fromHookContext({ ...ctx, workspaceDir });
|
|
@@ -46,6 +46,7 @@ function formatRouteRecommendations(
|
|
|
46
46
|
}
|
|
47
47
|
|
|
48
48
|
|
|
49
|
+
// eslint-disable-next-line complexity -- complexity 15, refactor candidate
|
|
49
50
|
function buildEnglishOutput(
|
|
50
51
|
workspaceDir: string,
|
|
51
52
|
sessionId: string | null,
|
|
@@ -98,6 +99,7 @@ function buildEnglishOutput(
|
|
|
98
99
|
}
|
|
99
100
|
|
|
100
101
|
|
|
102
|
+
// eslint-disable-next-line complexity -- complexity 15, refactor candidate
|
|
101
103
|
function buildChineseOutput(
|
|
102
104
|
workspaceDir: string,
|
|
103
105
|
sessionId: string | null,
|
package/src/commands/focus.ts
CHANGED
|
@@ -47,6 +47,7 @@ function getWorkspaceDir(ctx: PluginCommandContext): string {
|
|
|
47
47
|
* - 清理:Working Memory 超过 10 条记录时保留最近 10 条
|
|
48
48
|
* - 验证:文件引用指向不存在的文件时移除
|
|
49
49
|
*/
|
|
50
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
50
51
|
function compressFocusContent(content: string, workspaceDir?: string): string {
|
|
51
52
|
// 首先使用 cleanupStaleInfo 进行基础清理
|
|
52
53
|
let result = cleanupStaleInfo(content, workspaceDir);
|
|
@@ -346,6 +347,7 @@ ${milestoneNote ? `${milestoneNote}\n` : ''}
|
|
|
346
347
|
/**
|
|
347
348
|
* 回滚到历史版本
|
|
348
349
|
*/
|
|
350
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
349
351
|
function rollbackFocus(workspaceDir: string, index: number, isZh: boolean): string {
|
|
350
352
|
const wctx = WorkspaceContext.fromHookContext({ workspaceDir });
|
|
351
353
|
const focusPath = wctx.resolve('CURRENT_FOCUS');
|
|
@@ -30,6 +30,7 @@ import type { PluginCommandContext, PluginCommandResult } from '../openclaw-sdk.
|
|
|
30
30
|
import {
|
|
31
31
|
type TrainerBackendKind,
|
|
32
32
|
type HardwareTier,
|
|
33
|
+
type TrainingExperimentResult,
|
|
33
34
|
} from '../core/external-training-contract.js';
|
|
34
35
|
import {
|
|
35
36
|
TrainingProgram,
|
|
@@ -270,14 +271,11 @@ Hardware tiers:
|
|
|
270
271
|
// This closes the gap in the create-experiment -> trainer -> import-result chain.
|
|
271
272
|
// NOTE: This blocks until training completes (could be minutes).
|
|
272
273
|
if (runNow) {
|
|
273
|
-
|
|
274
|
-
const {spec} = createResult;
|
|
275
274
|
const baseDir = TRAINER_SCRIPTS_DIR;
|
|
276
275
|
const scriptPath = path.join(baseDir, 'main.py');
|
|
277
276
|
const specPath = path.join(baseDir, `experiment-${spec.experimentId}.json`);
|
|
278
|
-
|
|
279
|
-
const
|
|
280
|
-
const resultFilePath = path.join(outputDir, `result-${spec.experimentId}.json`);
|
|
277
|
+
|
|
278
|
+
const resultFilePath = path.join(spec.outputDir, `result-${spec.experimentId}.json`);
|
|
281
279
|
|
|
282
280
|
// Write spec file
|
|
283
281
|
const specDir = path.dirname(specPath);
|
|
@@ -287,7 +285,7 @@ Hardware tiers:
|
|
|
287
285
|
fs.writeFileSync(specPath, JSON.stringify(spec, null, 2), 'utf-8');
|
|
288
286
|
|
|
289
287
|
|
|
290
|
-
let trainerResult!:
|
|
288
|
+
let trainerResult!: TrainingExperimentResult;
|
|
291
289
|
|
|
292
290
|
try {
|
|
293
291
|
if (spec.backend === 'dry-run') {
|
package/src/commands/pain.ts
CHANGED
|
@@ -127,20 +127,17 @@ export function handlePainCommand(ctx: PluginCommandContext): PluginCommandResul
|
|
|
127
127
|
|
|
128
128
|
// Determine Mental Mode (aligned with prompt.ts logic)
|
|
129
129
|
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
else if (gfi >= 40) mentalMode = '🤝 CONCILIATORY';
|
|
138
|
-
else mentalMode = '⚡ EFFICIENT';
|
|
139
|
-
}
|
|
130
|
+
const mentalMode = isZh
|
|
131
|
+
? gfi >= 70 ? '🚑 救赎模式 (HUMBLE_RECOVERY)'
|
|
132
|
+
: gfi >= 40 ? '🤝 安抚模式 (CONCILIATORY)'
|
|
133
|
+
: '⚡ 高效模式 (EFFICIENT)'
|
|
134
|
+
: gfi >= 70 ? '🚑 HUMBLE_RECOVERY'
|
|
135
|
+
: gfi >= 40 ? '🤝 CONCILIATORY'
|
|
136
|
+
: '⚡ EFFICIENT';
|
|
140
137
|
|
|
141
138
|
// Determine health status based on GFI
|
|
142
139
|
|
|
143
|
-
let healthLabel
|
|
140
|
+
let healthLabel: string;
|
|
144
141
|
let suggestionText = '';
|
|
145
142
|
|
|
146
143
|
if (isZh) {
|
|
@@ -219,6 +216,7 @@ export function handlePainCommand(ctx: PluginCommandContext): PluginCommandResul
|
|
|
219
216
|
* Handle /pd-status empathy subcommand
|
|
220
217
|
*/
|
|
221
218
|
|
|
219
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
222
220
|
function handleEmpathySubcommand(
|
|
223
221
|
wctx: WorkspaceContext,
|
|
224
222
|
args: string,
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* This command must operate on an explicitly resolved active workspace.
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
|
-
import { PluginCommandDefinition, PluginCommandContext, PluginCommandResult, OpenClawPluginApi } from '../openclaw-sdk.js';
|
|
8
|
+
import type { PluginCommandDefinition, PluginCommandContext, PluginCommandResult, OpenClawPluginApi } from '../openclaw-sdk.js';
|
|
9
9
|
import { acquireQueueLock, EVOLUTION_QUEUE_LOCK_SUFFIX } from '../service/evolution-worker.js';
|
|
10
10
|
import * as fs from 'fs';
|
|
11
11
|
import * as path from 'path';
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { WorkspaceContext } from '../core/workspace-context.js';
|
|
2
2
|
import type { PluginCommandContext } from '../openclaw-sdk.js';
|
|
3
3
|
|
|
4
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
4
5
|
export function handlePrincipleRollbackCommand(ctx: PluginCommandContext): { text: string } {
|
|
5
6
|
const workspaceDir = (ctx.config?.workspaceDir as string) || process.cwd();
|
|
6
7
|
const argText = (ctx.args || '').trim();
|
|
@@ -41,6 +41,7 @@ function getAllImplementations(stateDir: string): Implementation[] {
|
|
|
41
41
|
* /pd-rollback-impl <implId> - Rollback current active
|
|
42
42
|
* /pd-rollback-impl <implId> --reason "<reason>" - Rollback with reason
|
|
43
43
|
*/
|
|
44
|
+
// eslint-disable-next-line complexity -- complexity 12, refactor candidate
|
|
44
45
|
export function handleRollbackImplCommand(ctx: PluginCommandContext): PluginCommandResult {
|
|
45
46
|
const workspaceDir = (ctx.config?.workspaceDir as string) || process.cwd();
|
|
46
47
|
const {stateDir} = WorkspaceContext.fromHookContext({ ...ctx, workspaceDir });
|
|
@@ -407,6 +407,7 @@ export function getDetailedThresholdState(
|
|
|
407
407
|
* @param signals - Observable signals
|
|
408
408
|
* @returns UpdateThresholdResult describing the most significant change
|
|
409
409
|
*/
|
|
410
|
+
// eslint-disable-next-line complexity -- complexity 15, refactor candidate
|
|
410
411
|
export function adjustThresholdsFromSignals(
|
|
411
412
|
stateDir: string,
|
|
412
413
|
signals: ThresholdSignals
|
|
@@ -30,7 +30,7 @@ export interface BootstrapResult {
|
|
|
30
30
|
* @returns Array of principle IDs sorted by observedViolationCount (descending)
|
|
31
31
|
* @throws Error if no deterministic principles found
|
|
32
32
|
*/
|
|
33
|
-
export function selectPrinciplesForBootstrap(stateDir: string, limit
|
|
33
|
+
export function selectPrinciplesForBootstrap(stateDir: string, limit = 3): string[] {
|
|
34
34
|
// Load training store to get evaluability and violation data
|
|
35
35
|
const store = loadStore(stateDir);
|
|
36
36
|
|
|
@@ -76,7 +76,7 @@ export function selectPrinciplesForBootstrap(stateDir: string, limit: number = 3
|
|
|
76
76
|
* @returns Array of results indicating created or skipped status
|
|
77
77
|
* @throws Error if no deterministic principles found
|
|
78
78
|
*/
|
|
79
|
-
export function bootstrapRules(stateDir: string, limit
|
|
79
|
+
export function bootstrapRules(stateDir: string, limit = 3): BootstrapResult[] {
|
|
80
80
|
// Select principles for bootstrap
|
|
81
81
|
const selectedPrincipleIds = selectPrinciplesForBootstrap(stateDir, limit);
|
|
82
82
|
|
|
@@ -107,7 +107,7 @@ export function bootstrapRules(stateDir: string, limit: number = 3): BootstrapRe
|
|
|
107
107
|
|
|
108
108
|
// Create stub rule
|
|
109
109
|
const now = new Date().toISOString();
|
|
110
|
-
|
|
110
|
+
createRule(stateDir, {
|
|
111
111
|
id: ruleId,
|
|
112
112
|
version: 1,
|
|
113
113
|
name: `Stub bootstrap rule for ${principleId}`,
|
package/src/core/dictionary.ts
CHANGED
|
@@ -116,6 +116,7 @@ export class PainDictionary {
|
|
|
116
116
|
}
|
|
117
117
|
}
|
|
118
118
|
|
|
119
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
119
120
|
match(text: string): { ruleId: string; severity: number } | undefined {
|
|
120
121
|
if (shouldIgnorePainProtocolText(text)) return undefined;
|
|
121
122
|
|
|
@@ -207,6 +207,7 @@ export function matchEmpathyKeywords(
|
|
|
207
207
|
* This is called when the empathy optimizer subagent completes its analysis
|
|
208
208
|
* and returns suggested updates to the keyword store.
|
|
209
209
|
*/
|
|
210
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
210
211
|
export function applyKeywordUpdates(
|
|
211
212
|
store: EmpathyKeywordStore,
|
|
212
213
|
updates: Record<string, {
|
package/src/core/event-log.ts
CHANGED
|
@@ -244,6 +244,7 @@ export class EventLog {
|
|
|
244
244
|
}
|
|
245
245
|
|
|
246
246
|
|
|
247
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
247
248
|
private getEventDedupKey(entry: EventLogEntry): string {
|
|
248
249
|
const eventId = typeof (entry.data as { eventId?: unknown } | undefined)?.eventId === 'string'
|
|
249
250
|
? String((entry.data as { eventId?: string }).eventId)
|
|
@@ -340,6 +341,7 @@ export class EventLog {
|
|
|
340
341
|
* @param range 'today' | 'week' | 'session'
|
|
341
342
|
* @param sessionId Optional session ID for session-scoped stats
|
|
342
343
|
*/
|
|
344
|
+
// eslint-disable-next-line complexity -- complexity 12, refactor candidate
|
|
343
345
|
getEmpathyStats(range: 'today' | 'week' | 'session', sessionId?: string): EmpathyEventStats {
|
|
344
346
|
const now = new Date();
|
|
345
347
|
const today = this.formatDate(now);
|
|
@@ -285,6 +285,7 @@ export interface ValidationResult {
|
|
|
285
285
|
* @param result - The trainer result to validate
|
|
286
286
|
* @returns ValidationResult indicating pass/fail and any errors
|
|
287
287
|
*/
|
|
288
|
+
// eslint-disable-next-line complexity -- complexity 11, slightly over threshold
|
|
288
289
|
export function validateTrainerResult(
|
|
289
290
|
spec: TrainingExperimentSpec,
|
|
290
291
|
result: TrainingExperimentResult
|
|
@@ -265,6 +265,7 @@ export function compressFocus(focusPath: string, newContent: string): {
|
|
|
265
265
|
* @param content CURRENT_FOCUS.md 内容
|
|
266
266
|
* @param maxLines 最大行数
|
|
267
267
|
*/
|
|
268
|
+
// eslint-disable-next-line complexity -- complexity 12, refactor candidate
|
|
268
269
|
export function extractSummary(content: string, maxLines = 30): string {
|
|
269
270
|
const lines = content.split('\n');
|
|
270
271
|
const sections: { [key: string]: string[] } = {
|
|
@@ -805,6 +806,7 @@ function generateWorkingMemorySection(snapshot: WorkingMemorySnapshot): string {
|
|
|
805
806
|
/**
|
|
806
807
|
* 生成工作记忆注入字符串(用于 prompt 注入)
|
|
807
808
|
*/
|
|
809
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
808
810
|
export function workingMemoryToInjection(snapshot: WorkingMemorySnapshot | null): string {
|
|
809
811
|
if (!snapshot) return '';
|
|
810
812
|
|
|
@@ -884,6 +886,7 @@ interface CompressionConfig {
|
|
|
884
886
|
* @param stateDir state 目录路径
|
|
885
887
|
* @returns 压缩配置
|
|
886
888
|
*/
|
|
889
|
+
// eslint-disable-next-line complexity -- complexity 11, slightly over threshold
|
|
887
890
|
function loadCompressionConfig(stateDir?: string): CompressionConfig {
|
|
888
891
|
if (!stateDir) {
|
|
889
892
|
return DEFAULT_COMPRESSION_CONFIG;
|
package/src/core/init.ts
CHANGED
|
@@ -34,6 +34,7 @@ function hasOutdatedCoreGuidance(file: string, content: string): boolean {
|
|
|
34
34
|
* Ensures that the workspace has the necessary template files for Principles Disciple.
|
|
35
35
|
* This function flattens 'core' templates to the root so OpenClaw can find them.
|
|
36
36
|
*/
|
|
37
|
+
// eslint-disable-next-line complexity -- complexity 14, refactor candidate
|
|
37
38
|
export function ensureWorkspaceTemplates(api: OpenClawPluginApi, workspaceDir: string, language = 'en') {
|
|
38
39
|
try {
|
|
39
40
|
const __filename = fileURLToPath(import.meta.url);
|
|
@@ -364,7 +364,7 @@ function validateSingleReplayReport(reportPath: string): ReplayValidationCategor
|
|
|
364
364
|
return 'missing_evidence_summary';
|
|
365
365
|
}
|
|
366
366
|
|
|
367
|
-
const evidenceSummary =
|
|
367
|
+
const evidenceSummary = parsed.evidenceSummary;
|
|
368
368
|
if (parsed.overallDecision === 'pass' && evidenceSummary.totalSamples === 0) {
|
|
369
369
|
return 'unsupported_pass';
|
|
370
370
|
}
|
|
@@ -159,6 +159,7 @@ export interface TrinityStageValidationResult {
|
|
|
159
159
|
* Validate a Dreamer output contract.
|
|
160
160
|
* Ensures the output is well-formed before passing to Philosopher.
|
|
161
161
|
*/
|
|
162
|
+
// eslint-disable-next-line complexity -- complexity 11, slightly over threshold
|
|
162
163
|
export function validateDreamerOutput(output: unknown): TrinityStageValidationResult {
|
|
163
164
|
const failures: string[] = [];
|
|
164
165
|
|
|
@@ -237,6 +238,7 @@ export function validateDreamerOutput(output: unknown): TrinityStageValidationRe
|
|
|
237
238
|
* Validate a Philosopher output contract.
|
|
238
239
|
* Ensures the output is well-formed before passing to Scribe.
|
|
239
240
|
*/
|
|
241
|
+
// eslint-disable-next-line complexity -- complexity 14, refactor candidate
|
|
240
242
|
export function validatePhilosopherOutput(output: unknown): TrinityStageValidationResult {
|
|
241
243
|
const failures: string[] = [];
|
|
242
244
|
|
|
@@ -260,6 +262,7 @@ export function validatePhilosopherOutput(output: unknown): TrinityStageValidati
|
|
|
260
262
|
failures.push('Philosopher output must have a judgments array');
|
|
261
263
|
} else {
|
|
262
264
|
// Validate each judgment
|
|
265
|
+
// eslint-disable-next-line complexity -- complexity 13, refactor candidate
|
|
263
266
|
obj.judgments.forEach((judgment: unknown, idx: number) => {
|
|
264
267
|
if (judgment === null || judgment === undefined || typeof judgment !== 'object') {
|
|
265
268
|
failures.push(`Philosopher judgment at index ${idx} is not an object`);
|
|
@@ -116,6 +116,23 @@ export const DEFAULT_SCORING_WEIGHTS: ScoringWeights = {
|
|
|
116
116
|
confidence: 0.15,
|
|
117
117
|
};
|
|
118
118
|
|
|
119
|
+
/**
|
|
120
|
+
* Result of diversity validation on Dreamer candidates.
|
|
121
|
+
* Soft enforcement: result is informational, never gates the pipeline.
|
|
122
|
+
*/
|
|
123
|
+
export interface DiversityValidationResult {
|
|
124
|
+
/** Whether candidates passed diversity checks */
|
|
125
|
+
diversityCheckPassed: boolean;
|
|
126
|
+
/** Whether at least 2 distinct risk levels were present */
|
|
127
|
+
riskLevelDiversity: boolean;
|
|
128
|
+
/** Whether no candidate pair exceeded keyword overlap threshold */
|
|
129
|
+
keywordOverlapPassed: boolean;
|
|
130
|
+
/** Highest pairwise keyword overlap score (for telemetry) */
|
|
131
|
+
maxOverlapScore: number;
|
|
132
|
+
/** Human-readable summary of check results */
|
|
133
|
+
details: string;
|
|
134
|
+
}
|
|
135
|
+
|
|
119
136
|
// ---------------------------------------------------------------------------
|
|
120
137
|
// Scoring Logic
|
|
121
138
|
// ---------------------------------------------------------------------------
|
|
@@ -232,6 +249,120 @@ export function checkThresholds(
|
|
|
232
249
|
return [failedThresholds.length === 0, failedThresholds];
|
|
233
250
|
}
|
|
234
251
|
|
|
252
|
+
/**
|
|
253
|
+
* Validate that Dreamer candidates are strategically diverse.
|
|
254
|
+
*
|
|
255
|
+
* DIVER-03: Checks risk level diversity (Set.size >= 2 when candidates >= 2)
|
|
256
|
+
* and keyword overlap similarity (reject if intersection / max(|A|, |B|) > 0.8
|
|
257
|
+
* for words > 3 chars per D-05).
|
|
258
|
+
*
|
|
259
|
+
* This is SOFT enforcement: returns a result, never throws.
|
|
260
|
+
* Pipeline continues regardless of diversityCheckPassed value.
|
|
261
|
+
*
|
|
262
|
+
* @param candidates - Dreamer candidates to validate
|
|
263
|
+
* @returns DiversityValidationResult with pass/fail details
|
|
264
|
+
*/
|
|
265
|
+
export function validateCandidateDiversity(
|
|
266
|
+
candidates: DreamerCandidate[],
|
|
267
|
+
): DiversityValidationResult {
|
|
268
|
+
// Edge cases: empty, null, or single candidate always passes
|
|
269
|
+
if (!candidates || candidates.length <= 1) {
|
|
270
|
+
return {
|
|
271
|
+
diversityCheckPassed: true,
|
|
272
|
+
riskLevelDiversity: true,
|
|
273
|
+
keywordOverlapPassed: true,
|
|
274
|
+
maxOverlapScore: 0,
|
|
275
|
+
details: candidates?.length === 1
|
|
276
|
+
? 'Single candidate — diversity check not applicable'
|
|
277
|
+
: 'No candidates to validate',
|
|
278
|
+
};
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Check 1: Risk level diversity (D-05)
|
|
282
|
+
const riskLevels = new Set(
|
|
283
|
+
candidates
|
|
284
|
+
.map(c => c.riskLevel)
|
|
285
|
+
.filter((r): r is "low" | "medium" | "high" => typeof r === 'string')
|
|
286
|
+
);
|
|
287
|
+
// If NO candidates have riskLevel, skip risk diversity check (graceful degradation)
|
|
288
|
+
const riskLevelDiversity = riskLevels.size === 0 || riskLevels.size >= 2;
|
|
289
|
+
|
|
290
|
+
// Check 2: Keyword overlap (D-05: intersection / max(|A|, |B|) for words > 3 chars)
|
|
291
|
+
let maxOverlapScore = 0;
|
|
292
|
+
let keywordOverlapPassed = true;
|
|
293
|
+
|
|
294
|
+
for (let i = 0; i < candidates.length; i++) {
|
|
295
|
+
for (let j = i + 1; j < candidates.length; j++) {
|
|
296
|
+
const overlap = computeKeywordOverlap(
|
|
297
|
+
candidates[i].betterDecision ?? '',
|
|
298
|
+
candidates[j].betterDecision ?? '',
|
|
299
|
+
);
|
|
300
|
+
if (overlap > maxOverlapScore) {
|
|
301
|
+
maxOverlapScore = overlap;
|
|
302
|
+
}
|
|
303
|
+
if (overlap > 0.8) {
|
|
304
|
+
keywordOverlapPassed = false;
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
const diversityCheckPassed = riskLevelDiversity && keywordOverlapPassed;
|
|
310
|
+
|
|
311
|
+
// Build details string
|
|
312
|
+
const parts: string[] = [];
|
|
313
|
+
if (!riskLevelDiversity) {
|
|
314
|
+
parts.push(`Risk levels not diverse (found: ${[...riskLevels].join(', ') || 'none'})`);
|
|
315
|
+
}
|
|
316
|
+
if (!keywordOverlapPassed) {
|
|
317
|
+
parts.push(`Keyword overlap too high (max: ${maxOverlapScore.toFixed(2)})`);
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
diversityCheckPassed,
|
|
322
|
+
riskLevelDiversity,
|
|
323
|
+
keywordOverlapPassed,
|
|
324
|
+
maxOverlapScore: Math.round(maxOverlapScore * 100) / 100,
|
|
325
|
+
details: diversityCheckPassed
|
|
326
|
+
? 'Diversity check passed'
|
|
327
|
+
: parts.join('; '),
|
|
328
|
+
};
|
|
329
|
+
}
|
|
330
|
+
|
|
331
|
+
/**
|
|
332
|
+
* Compute keyword overlap between two strings.
|
|
333
|
+
* Algorithm: intersection / max(|A|, |B|) for words > 3 chars (per D-05).
|
|
334
|
+
* Returns value between 0 and 1.
|
|
335
|
+
*/
|
|
336
|
+
function computeKeywordOverlap(textA: string, textB: string): number {
|
|
337
|
+
const wordsA = extractKeywords(textA);
|
|
338
|
+
const wordsB = extractKeywords(textB);
|
|
339
|
+
|
|
340
|
+
if (wordsA.length === 0 && wordsB.length === 0) return 0;
|
|
341
|
+
if (wordsA.length === 0 || wordsB.length === 0) return 0;
|
|
342
|
+
|
|
343
|
+
const setA = new Set(wordsA);
|
|
344
|
+
const setB = new Set(wordsB);
|
|
345
|
+
|
|
346
|
+
let intersection = 0;
|
|
347
|
+
for (const word of setA) {
|
|
348
|
+
if (setB.has(word)) intersection++;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const denominator = Math.max(setA.size, setB.size);
|
|
352
|
+
return denominator === 0 ? 0 : intersection / denominator;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/**
|
|
356
|
+
* Extract keywords from text: words > 3 characters, lowercased.
|
|
357
|
+
*/
|
|
358
|
+
function extractKeywords(text: string): string[] {
|
|
359
|
+
if (!text) return [];
|
|
360
|
+
return text
|
|
361
|
+
.toLowerCase()
|
|
362
|
+
.split(/[^a-z0-9]+/)
|
|
363
|
+
.filter(w => w.length > 3);
|
|
364
|
+
}
|
|
365
|
+
|
|
235
366
|
/**
|
|
236
367
|
* Score and rank all candidates deterministically.
|
|
237
368
|
*
|
|
@@ -513,6 +513,7 @@ function detectT09Opportunity(session: SessionEvents): OpportunityMatch {
|
|
|
513
513
|
* trigger pattern. Since P_* principles don't have T-xx specific detectors,
|
|
514
514
|
* we use the presence of negative signals as violation evidence.
|
|
515
515
|
*/
|
|
516
|
+
// eslint-disable-next-line complexity -- complexity 14, refactor candidate
|
|
516
517
|
export function detectViolation(principleId: string, session: SessionEvents): ViolationMatch {
|
|
517
518
|
// #216: P_* principles (pain-derived) — generic violation detection
|
|
518
519
|
if (principleId.startsWith('P_')) {
|
|
@@ -645,6 +645,7 @@ export function getDatasetStats(
|
|
|
645
645
|
* @param targetModelFamily - Default target family for migrated samples
|
|
646
646
|
* @returns Number of newly registered samples
|
|
647
647
|
*/
|
|
648
|
+
// eslint-disable-next-line complexity -- complexity 14, refactor candidate
|
|
648
649
|
export function migrateSampleArtifacts(
|
|
649
650
|
workspaceDir: string,
|
|
650
651
|
targetModelFamily: string | null = null
|
|
@@ -278,6 +278,7 @@ function isTooGeneric(text: string): boolean {
|
|
|
278
278
|
* @param artifact - The validated artifact from arbiter (passed = true)
|
|
279
279
|
* @returns ExecutabilityResult
|
|
280
280
|
*/
|
|
281
|
+
// eslint-disable-next-line complexity -- complexity 14, refactor candidate
|
|
281
282
|
export function validateExecutability(artifact: {
|
|
282
283
|
badDecision: string;
|
|
283
284
|
betterDecision: string;
|