principles-disciple 1.201.0 → 1.202.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.
Files changed (140) hide show
  1. package/dist/bundle.js +166 -166
  2. package/dist/commands/archive-impl.d.ts +18 -0
  3. package/dist/commands/capabilities.d.ts +3 -0
  4. package/dist/commands/context.d.ts +5 -0
  5. package/dist/commands/disable-impl.d.ts +22 -0
  6. package/dist/commands/evolution-status.d.ts +4 -0
  7. package/dist/commands/export.d.ts +2 -0
  8. package/dist/commands/focus.d.ts +14 -0
  9. package/dist/commands/pain.d.ts +6 -0
  10. package/dist/commands/principle-rollback.d.ts +4 -0
  11. package/dist/commands/promote-impl.d.ts +22 -0
  12. package/dist/commands/rollback-impl.d.ts +32 -0
  13. package/dist/commands/rollback.d.ts +19 -0
  14. package/dist/commands/samples.d.ts +2 -0
  15. package/dist/commands/strategy.d.ts +2 -0
  16. package/dist/commands/thinking-os.d.ts +2 -0
  17. package/dist/commands/workflow-debug.d.ts +4 -0
  18. package/dist/config/defaults/runtime.d.ts +58 -0
  19. package/dist/config/errors.d.ts +86 -0
  20. package/dist/config/index.d.ts +7 -0
  21. package/dist/constants/tools.d.ts +17 -0
  22. package/dist/core/__tests__/focus-history.test.d.ts +1 -0
  23. package/dist/core/behavior-example-pack-assembler.d.ts +38 -0
  24. package/dist/core/bootstrap-rules.d.ts +50 -0
  25. package/dist/core/code-implementation-storage.d.ts +71 -0
  26. package/dist/core/config-health.d.ts +17 -0
  27. package/dist/core/config-service.d.ts +15 -0
  28. package/dist/core/config.d.ts +111 -0
  29. package/dist/core/control-ui-db.d.ts +117 -0
  30. package/dist/core/correction-cue-learner.d.ts +33 -0
  31. package/dist/core/correction-types.d.ts +3 -0
  32. package/dist/core/detection-funnel.d.ts +47 -0
  33. package/dist/core/detection-service.d.ts +15 -0
  34. package/dist/core/dictionary-service.d.ts +15 -0
  35. package/dist/core/dictionary.d.ts +38 -0
  36. package/dist/core/empathy-keyword-matcher.d.ts +5 -0
  37. package/dist/core/empathy-types.d.ts +2 -0
  38. package/dist/core/event-log.d.ts +98 -0
  39. package/dist/core/evolution-engine.d.ts +119 -0
  40. package/dist/core/evolution-logger.d.ts +137 -0
  41. package/dist/core/evolution-reducer.d.ts +116 -0
  42. package/dist/core/evolution-types.d.ts +50 -0
  43. package/dist/core/file-store.d.ts +41 -0
  44. package/dist/core/focus-history.d.ts +50 -0
  45. package/dist/core/hygiene/tracker.d.ts +22 -0
  46. package/dist/core/init.d.ts +30 -0
  47. package/dist/core/intent-doc-reader-adapter.d.ts +36 -0
  48. package/dist/core/intent-doc-reader.d.ts +89 -0
  49. package/dist/core/migration.d.ts +6 -0
  50. package/dist/core/pain-diagnostic-gate.d.ts +45 -0
  51. package/dist/core/pain.d.ts +24 -0
  52. package/dist/core/path-resolver.d.ts +60 -0
  53. package/dist/core/paths.d.ts +59 -0
  54. package/dist/core/pd-config-loader.d.ts +96 -0
  55. package/dist/core/pd-task-reconciler.d.ts +89 -0
  56. package/dist/core/pd-task-service.d.ts +2 -0
  57. package/dist/core/pd-task-store.d.ts +5 -0
  58. package/dist/core/pd-task-types.d.ts +8 -0
  59. package/dist/core/principle-compiler/__tests__/compiler-replay-gate.test.d.ts +1 -0
  60. package/dist/core/principle-compiler/code-validator.d.ts +14 -0
  61. package/dist/core/principle-compiler/compiler.d.ts +45 -0
  62. package/dist/core/principle-compiler/index.d.ts +12 -0
  63. package/dist/core/principle-compiler/ledger-registrar.d.ts +28 -0
  64. package/dist/core/principle-compiler/template-generator.d.ts +7 -0
  65. package/dist/core/principle-injection.d.ts +10 -0
  66. package/dist/core/principle-internalization/filesystem-lifecycle-datasource.d.ts +15 -0
  67. package/dist/core/principle-internalization/lifecycle-read-model.d.ts +17 -0
  68. package/dist/core/principle-internalization/lifecycle-refresh.d.ts +2 -0
  69. package/dist/core/principle-internalization/principle-lifecycle-service.d.ts +28 -0
  70. package/dist/core/principle-training-state.d.ts +47 -0
  71. package/dist/core/principle-tree-ledger.d.ts +30 -0
  72. package/dist/core/profile.d.ts +62 -0
  73. package/dist/core/reflection/reflection-context.d.ts +31 -0
  74. package/dist/core/replay-engine.d.ts +12 -0
  75. package/dist/core/rule-context-assembler.d.ts +45 -0
  76. package/dist/core/rule-host.d.ts +178 -0
  77. package/dist/core/rule-implementation-runtime.d.ts +18 -0
  78. package/dist/core/runtime-v2-prompt-activation-reader.d.ts +22 -0
  79. package/dist/core/session-tracker.d.ts +119 -0
  80. package/dist/core/signal-collector-host.d.ts +113 -0
  81. package/dist/core/system-logger.d.ts +24 -0
  82. package/dist/core/thinking-models.d.ts +25 -0
  83. package/dist/core/thinking-os-parser.d.ts +35 -0
  84. package/dist/core/trajectory-types.d.ts +247 -0
  85. package/dist/core/trajectory.d.ts +279 -0
  86. package/dist/core/workflow-funnel-loader.d.ts +72 -0
  87. package/dist/core/workspace-context.d.ts +114 -0
  88. package/dist/core/workspace-dir-validation.d.ts +11 -0
  89. package/dist/core/workspace-guidance-migrator.d.ts +12 -0
  90. package/dist/hooks/after-tool-call-helpers.d.ts +97 -0
  91. package/dist/hooks/after-tool-call-types.d.ts +86 -0
  92. package/dist/hooks/gate-block-helper.d.ts +44 -0
  93. package/dist/hooks/gate.d.ts +16 -0
  94. package/dist/hooks/lifecycle.d.ts +5 -0
  95. package/dist/hooks/llm.d.ts +21 -0
  96. package/dist/hooks/message-sanitize.d.ts +24 -0
  97. package/dist/hooks/pain.d.ts +35 -0
  98. package/dist/hooks/prompt-helpers.d.ts +105 -0
  99. package/dist/hooks/prompt-types.d.ts +74 -0
  100. package/dist/hooks/prompt.d.ts +22 -0
  101. package/dist/hooks/raw-observation-adapter.d.ts +16 -0
  102. package/dist/hooks/raw-observation-types.d.ts +11 -0
  103. package/dist/hooks/trajectory-collector.d.ts +41 -0
  104. package/dist/hooks/trajectory-evidence.d.ts +11 -0
  105. package/dist/hooks/triage-adapter.d.ts +58 -0
  106. package/dist/hooks/trigger-cooldown-tracker.d.ts +42 -0
  107. package/dist/i18n/commands.d.ts +26 -0
  108. package/dist/index.d.ts +52 -0
  109. package/dist/openclaw-sdk.d.ts +338 -0
  110. package/dist/openclaw.plugin.json +1 -1
  111. package/dist/rulehost-evidence.d.ts +4 -0
  112. package/dist/service/correction-observer-service.d.ts +19 -0
  113. package/dist/service/evolution-dedup.d.ts +27 -0
  114. package/dist/service/evolution-worker.d.ts +105 -0
  115. package/dist/service/internalization-auto-consumer-service.d.ts +8 -0
  116. package/dist/service/keyword-optimization-service.d.ts +44 -0
  117. package/dist/service/phase3-input-filter.d.ts +73 -0
  118. package/dist/service/queue-io.d.ts +30 -0
  119. package/dist/service/queue-migration.d.ts +84 -0
  120. package/dist/service/runtime-summary-service.d.ts +156 -0
  121. package/dist/service/subagent-workflow/subagent-error-utils.d.ts +8 -0
  122. package/dist/service/subagent-workflow/types.d.ts +264 -0
  123. package/dist/service/subagent-workflow/workflow-store.d.ts +44 -0
  124. package/dist/service/trajectory-service.d.ts +2 -0
  125. package/dist/service/workflow-watchdog.d.ts +23 -0
  126. package/dist/types/event-types.d.ts +2 -0
  127. package/dist/types/hygiene-types.d.ts +2 -0
  128. package/dist/types/principle-tree-schema.d.ts +29 -0
  129. package/dist/types/queue.d.ts +2 -0
  130. package/dist/types/runtime-summary.d.ts +1 -0
  131. package/dist/types.d.ts +13 -0
  132. package/dist/utils/file-lock.d.ts +68 -0
  133. package/dist/utils/hashing.d.ts +9 -0
  134. package/dist/utils/io.d.ts +11 -0
  135. package/dist/utils/node-vm-polyfill.d.ts +9 -0
  136. package/dist/utils/retry.d.ts +210 -0
  137. package/dist/utils/session-key.d.ts +10 -0
  138. package/dist/utils/workspace-resolver.d.ts +82 -0
  139. package/openclaw.plugin.json +1 -1
  140. package/package.json +3 -2
@@ -0,0 +1,111 @@
1
+ export interface GfiGateSettings {
2
+ enabled: boolean;
3
+ thresholds: {
4
+ low_risk_block: number;
5
+ high_risk_block: number;
6
+ large_change_block: number;
7
+ };
8
+ large_change_lines: number;
9
+ ep_tier_multipliers: {
10
+ '1': number;
11
+ '2': number;
12
+ '3': number;
13
+ '4': number;
14
+ '5': number;
15
+ };
16
+ bash_safe_patterns: string[];
17
+ bash_dangerous_patterns: string[];
18
+ }
19
+ export interface DiagnosticianSettings {
20
+ context: {
21
+ time_window_minutes: number;
22
+ max_message_length: number;
23
+ max_summary_length: number;
24
+ };
25
+ }
26
+ export interface PainSettings {
27
+ language: 'en' | 'zh';
28
+ trajectory?: {
29
+ blob_inline_threshold_bytes?: number;
30
+ busy_timeout_ms?: number;
31
+ orphan_blob_grace_days?: number;
32
+ };
33
+ diagnostician?: DiagnosticianSettings;
34
+ thresholds: {
35
+ pain_trigger: number;
36
+ cognitive_paralysis_input: number;
37
+ stuck_loops_trigger: number;
38
+ semantic_min_score: number;
39
+ promotion_count_threshold: number;
40
+ promotion_similarity_threshold: number;
41
+ };
42
+ scores: {
43
+ paralysis: number;
44
+ default_confusion: number;
45
+ default_loop: number;
46
+ tool_failure_friction: number;
47
+ exit_code_penalty: number;
48
+ spiral_penalty: number;
49
+ missing_test_command_penalty: number;
50
+ subagent_error_penalty: number;
51
+ subagent_timeout_penalty: number;
52
+ };
53
+ severity_thresholds: {
54
+ high: number;
55
+ medium: number;
56
+ low: number;
57
+ };
58
+ intervals: {
59
+ worker_poll_ms: number;
60
+ initial_delay_ms: number;
61
+ task_timeout_ms: number;
62
+ };
63
+ empathy_engine?: {
64
+ enabled?: boolean;
65
+ dedupe_window_ms?: number;
66
+ penalties?: {
67
+ mild?: number;
68
+ moderate?: number;
69
+ severe?: number;
70
+ };
71
+ rate_limit?: {
72
+ max_per_turn?: number;
73
+ max_per_hour?: number;
74
+ };
75
+ model_calibration?: Record<string, number>;
76
+ };
77
+ gfi_gate?: GfiGateSettings;
78
+ compression?: {
79
+ /** 触发自动压缩的行数阈值 */
80
+ line_threshold?: number;
81
+ /** 触发自动压缩的字节阈值 */
82
+ size_threshold_kb?: number;
83
+ /** 自动压缩间隔(小时) */
84
+ interval_hours?: number;
85
+ /** 保留的已完成任务数 */
86
+ keep_completed_tasks?: number;
87
+ /** Working Memory 最大条数 */
88
+ max_working_memory_artifacts?: number;
89
+ };
90
+ }
91
+ export declare const DEFAULT_SETTINGS: PainSettings;
92
+ export declare class PainConfig {
93
+ private settings;
94
+ private readonly filePath;
95
+ constructor(stateDir: string);
96
+ load(): void;
97
+ save(): void;
98
+ private deepMerge;
99
+ /**
100
+ * Basic validation for critical settings
101
+ */
102
+ private validate;
103
+ /**
104
+ * Gets a value using dot notation (e.g. 'thresholds.pain_trigger')
105
+ */
106
+ get(keyPath: string): any;
107
+ /**
108
+ * Returns all settings as a plain object.
109
+ */
110
+ getAll(): PainSettings;
111
+ }
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Control UI database stores ANALYTICS READ MODELS.
3
+ *
4
+ * PURPOSE: Aggregated data for dashboard visualization and historical insights.
5
+ * USAGE: Control UI queries and dashboard displays.
6
+ * NOT FOR: Control decisions, Phase 3 eligibility, or real-time operations.
7
+ *
8
+ * Runtime truth comes from: queue state, workspace trust scorecard, active sessions
9
+ */
10
+ export interface ThinkingModelEventInput {
11
+ sessionId: string;
12
+ runId: string;
13
+ assistantTurnId: number;
14
+ modelId: string;
15
+ matchedPattern: string;
16
+ scenarioJson: unknown;
17
+ toolContextJson: unknown;
18
+ painContextJson: unknown;
19
+ principleContextJson: unknown;
20
+ triggerExcerpt: string;
21
+ createdAt: string;
22
+ }
23
+ export interface ControlUiDatabaseOptions {
24
+ workspaceDir: string;
25
+ busyTimeoutMs?: number;
26
+ }
27
+ export interface RecentThinkingContext {
28
+ toolCalls: {
29
+ id: number;
30
+ toolName: string;
31
+ outcome: 'success' | 'failure' | 'blocked';
32
+ errorType: string | null;
33
+ errorMessage: string | null;
34
+ createdAt: string;
35
+ }[];
36
+ painEvents: {
37
+ id: number;
38
+ source: string;
39
+ score: number;
40
+ reason: string | null;
41
+ createdAt: string;
42
+ }[];
43
+ gateBlocks: {
44
+ id: number;
45
+ toolName: string;
46
+ reason: string;
47
+ filePath: string | null;
48
+ createdAt: string;
49
+ }[];
50
+ userCorrections: {
51
+ id: number;
52
+ correctionCue: string | null;
53
+ rawExcerpt: string | null;
54
+ createdAt: string;
55
+ }[];
56
+ principleEvents: {
57
+ id: number;
58
+ principleId: string | null;
59
+ eventType: string;
60
+ createdAt: string;
61
+ }[];
62
+ }
63
+ export declare class ControlUiDatabase {
64
+ private readonly workspaceDir;
65
+ private readonly dbPath;
66
+ private readonly blobDir;
67
+ private readonly db;
68
+ constructor(opts: ControlUiDatabaseOptions);
69
+ dispose(): void;
70
+ recordThinkingModelEvent(input: ThinkingModelEventInput): number;
71
+ /**
72
+ * Get recent thinking context for a session.
73
+ *
74
+ * Returns: Analytics data (read model) aggregated from trajectory database.
75
+ * Not: Runtime truth or real-time queue state.
76
+ */
77
+ getRecentThinkingContext(sessionId: string, beforeCreatedAt: string, limit?: number): RecentThinkingContext;
78
+ /**
79
+ * Execute SQL query and return all rows.
80
+ *
81
+ * Returns: Analytics data (read model) aggregated from trajectory database.
82
+ * Not: Runtime truth or real-time queue state.
83
+ */
84
+ all<T>(sql: string, ...params: unknown[]): T[];
85
+ /**
86
+ * Execute SQL query and return first row.
87
+ *
88
+ * Returns: Analytics data (read model) aggregated from trajectory database.
89
+ * Not: Runtime truth or real-time queue state.
90
+ */
91
+ get<T>(sql: string, ...params: unknown[]): T | undefined;
92
+ /**
93
+ * Execute SQL statement that does not return rows (DDL, CREATE TABLE, etc.).
94
+ *
95
+ * Returns: void (executes directly)
96
+ * Not for: SELECT queries (use all() or get() instead)
97
+ */
98
+ execute(sql: string): void;
99
+ /**
100
+ * Execute a parameterized write statement (INSERT, UPDATE, DELETE).
101
+ */
102
+ run(sql: string, ...params: unknown[]): void;
103
+ restoreRawText(inlineText?: string | null, blobRef?: string | null): string;
104
+ private initSchema;
105
+ /**
106
+ * Create or replace a view, tolerating missing dependency tables.
107
+ *
108
+ * Views in ControlUiDatabase depend on tables created by TrajectoryDatabase
109
+ * (assistant_turns, tool_calls, pain_events, user_turns, correction_samples).
110
+ * If ControlUiDatabase is constructed before TrajectoryDatabase has created
111
+ * those tables, CREATE VIEW would throw. We DROP+CREATE with try/catch so
112
+ * missing-dependency views are skipped with a warning (rc-9: surfaced via
113
+ * console.info) rather than aborting schema initialization.
114
+ */
115
+ private createViewSafely;
116
+ private withWrite;
117
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Correction Cue Learner
3
+ *
4
+ * Persistent, learnable keyword store for correction cue detection.
5
+ * Replaces the hardcoded cue list in detectCorrectionCue() with a
6
+ * crash-safe JSON store that can grow over time.
7
+ *
8
+ * Persistence contract:
9
+ * - Atomic write: temp-file-then-rename (T-38-02)
10
+ * - Cache invalidated after every write (D-05)
11
+ * - 200-term hard cap enforced before any write (T-38-01)
12
+ */
13
+ import type { CorrectionKeyword, CorrectionKeywordStore, CorrectionMatchResult } from './correction-types.js';
14
+ export declare function _resetCorrectionCueCache(): void;
15
+ export declare function loadCorrectionKeywordStore(stateDir: string): CorrectionKeywordStore;
16
+ export declare function saveCorrectionKeywordStore(stateDir: string, store: CorrectionKeywordStore): void;
17
+ export declare function _resetCorrectionCueLearnerInstance(): void;
18
+ export declare class CorrectionCueLearner {
19
+ private readonly store;
20
+ private readonly stateDir;
21
+ constructor(stateDir: string);
22
+ match(text: string): CorrectionMatchResult;
23
+ recordHits(terms: string[]): void;
24
+ recordTruePositive(term: string): void;
25
+ recordFalsePositive(term: string): void;
26
+ add(keyword: Omit<CorrectionKeyword, 'addedAt'>): void;
27
+ updateWeight(term: string, weight: number): void;
28
+ remove(term: string): void;
29
+ getStore(): CorrectionKeywordStore;
30
+ getLastOptimizedAt(): string;
31
+ flush(): void;
32
+ static get(stateDir: string): CorrectionCueLearner;
33
+ }
@@ -0,0 +1,3 @@
1
+ import type { CorrectionKeyword, CorrectionKeywordStore, CorrectionMatchResult } from '@principles/core/runtime-v2';
2
+ export type { CorrectionKeyword, CorrectionKeywordStore, CorrectionMatchResult, };
3
+ export { MAX_CORRECTION_KEYWORDS, CORRECTION_SEED_KEYWORDS, } from '@principles/core/runtime-v2';
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Detection Funnel — PRI-446 thin adapter
3
+ *
4
+ * The pure three-layer funnel logic (LRU cache, async queue, layer dispatch)
5
+ * now lives in principles-core
6
+ * (runtime-v2/detection/detection-funnel-policy.ts). This file is a thin shell
7
+ * that wires DetectionFunnelCore with the two environment-coupled dependencies
8
+ * the plugin owns:
9
+ * - crypto.createHash (the L2 cache key hasher)
10
+ * - PainDictionary.match (the L1 exact matcher)
11
+ * - shouldIgnorePainProtocolText (the protocol-token gate)
12
+ *
13
+ * It re-exports DetectionFunnel (same class name + constructor signature) and
14
+ * DetectionResult so DetectionService, llm.ts, and evolution-worker keep working
15
+ * unchanged.
16
+ *
17
+ * ERR checklist:
18
+ * - ERR-011: this is a thin adapter delegating to core pure logic.
19
+ */
20
+ import { type PainDictionary } from './dictionary.js';
21
+ import { type DetectionResult } from '@principles/core/runtime-v2';
22
+ export type { DetectionResult };
23
+ /**
24
+ * Orchestrates the three-layer detection funnel for pain signals.
25
+ *
26
+ * Delegates to the core DetectionFunnelCore, injecting the crypto hasher,
27
+ * the dictionary matcher, and the protocol-token gate.
28
+ */
29
+ export declare class DetectionFunnel {
30
+ private readonly core;
31
+ constructor(dictionary: PainDictionary);
32
+ /**
33
+ * Detects pain in the given text using L1 (Exact), L2 (Cache), and L3 (Async).
34
+ */
35
+ detect(text: string): DetectionResult;
36
+ /**
37
+ * Internal method for the worker to update the cache after a semantic hit.
38
+ */
39
+ updateCache(text: string, result: {
40
+ detected: boolean;
41
+ severity?: number;
42
+ }): void;
43
+ /**
44
+ * Retrieves and clears the current asynchronous queue.
45
+ */
46
+ flushQueue(): string[];
47
+ }
@@ -0,0 +1,15 @@
1
+ import { DetectionFunnel } from './detection-funnel.js';
2
+ /**
3
+ * Singleton service to manage the Semantic Detection Funnel.
4
+ */
5
+ export declare const DetectionService: {
6
+ /**
7
+ * Gets or initializes the Detection Funnel instance.
8
+ * @param stateDir The directory used to initialize the dictionary.
9
+ */
10
+ get(stateDir: string): DetectionFunnel;
11
+ /**
12
+ * Resets the singleton instance (primarily for testing).
13
+ */
14
+ reset(): void;
15
+ };
@@ -0,0 +1,15 @@
1
+ import { PainDictionary } from './dictionary.js';
2
+ /**
3
+ * Singleton service to manage the Pain Dictionary.
4
+ */
5
+ export declare const DictionaryService: {
6
+ /**
7
+ * Gets or initializes the Pain Dictionary instance.
8
+ * @param stateDir The directory where the dictionary JSON is stored.
9
+ */
10
+ get(stateDir: string): PainDictionary;
11
+ /**
12
+ * Resets the singleton instance (primarily for testing).
13
+ */
14
+ reset(): void;
15
+ };
@@ -0,0 +1,38 @@
1
+ export type RuleType = 'regex' | 'exact_match';
2
+ export interface PainRule {
3
+ type: RuleType;
4
+ pattern?: string;
5
+ phrases?: string[];
6
+ severity: number;
7
+ hits: number;
8
+ status: 'active' | 'dormant' | 'archived';
9
+ }
10
+ export interface PainDictionaryData {
11
+ rules: Record<string, PainRule>;
12
+ }
13
+ export declare const PAIN_PROTOCOL_TOKENS: readonly ['[EVOLUTION_ACK]', 'HEARTBEAT_OK', 'HEARTBEAT_CHECK'];
14
+ export declare function shouldIgnorePainProtocolText(text: string): boolean;
15
+ export declare class PainDictionary {
16
+ private readonly stateDir;
17
+ private data;
18
+ private readonly store;
19
+ private readonly compiledRegex;
20
+ constructor(stateDir: string);
21
+ load(): void;
22
+ private compile;
23
+ getRule(id: string): PainRule | undefined;
24
+ getAllRules(): Record<string, PainRule>;
25
+ /**
26
+ * Adds a new rule or updates an existing one.
27
+ */
28
+ addRule(id: string, rule: Omit<PainRule, 'hits'>): void;
29
+ match(text: string): {
30
+ ruleId: string;
31
+ severity: number;
32
+ } | undefined;
33
+ flush(): void;
34
+ getStats(): {
35
+ totalRules: number;
36
+ totalHits: number;
37
+ };
38
+ }
@@ -0,0 +1,5 @@
1
+ import type { EmpathyKeywordStore } from '@principles/core/prompt-builder';
2
+ export { matchEmpathyKeywords, createDefaultKeywordStore, applyKeywordUpdates, shouldTriggerOptimization, getKeywordStoreSummary, } from '@principles/core/prompt-builder';
3
+ export type { EmpathyKeywordStore, EmpathyKeywordEntry, EmpathyKeywordStats, EmpathyMatchResult, EmpathyKeywordConfig, } from '@principles/core/prompt-builder';
4
+ export declare function loadKeywordStore(stateDir: string, language?: 'zh' | 'en'): EmpathyKeywordStore;
5
+ export declare function saveKeywordStore(stateDir: string, store: EmpathyKeywordStore): void;
@@ -0,0 +1,2 @@
1
+ export type { EmpathyKeywordStore, EmpathyKeywordEntry, EmpathyKeywordStats, EmpathyMatchResult, EmpathyKeywordUpdate, EmpathyOptimizationResult, SeedKeywordEntry, EmpathyKeywordConfig, } from '@principles/core/prompt-builder';
2
+ export { EMPATHY_SEED_KEYWORDS, DEFAULT_EMPATHY_KEYWORD_CONFIG, scoreToSeverity, severityToPenalty, normalizeSeverity, } from '@principles/core/prompt-builder';
@@ -0,0 +1,98 @@
1
+ import type { EventLogEntry, DailyStats, EmpathyEventStats, ToolCallEventData, PainSignalEventData, RulePromotionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, PlanApprovalEventData, EvolutionTaskEventData, EmpathyRollbackEventData, DiagnosisTaskEventData, HeartbeatDiagnosisEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimeV2PromptActivationsInjectedEventData, RuleHostUnhealthyEventData, RuleHostSkippedEventData } from '../types/event-types.js';
2
+ import type { PluginLogger } from '../openclaw-sdk.js';
3
+ export declare class EventLog {
4
+ private readonly logsDir;
5
+ private readonly statsFile;
6
+ private readonly logger?;
7
+ private readonly statsCache;
8
+ private eventBuffer;
9
+ private readonly maxBufferSize;
10
+ private readonly flushIntervalMs;
11
+ private flushTimer?;
12
+ private currentEventsFile;
13
+ private currentDate;
14
+ constructor(stateDir: string, logger?: PluginLogger);
15
+ private getEventsFile;
16
+ private getTodayStr;
17
+ private ensureEventsFile;
18
+ private cleanupOldEventFiles;
19
+ recordToolCall(sessionId: string | undefined, data: ToolCallEventData): void;
20
+ recordPainSignal(sessionId: string | undefined, data: PainSignalEventData): void;
21
+ recordRulePromotion(data: RulePromotionEventData): void;
22
+ recordHookExecution(data: HookExecutionEventData, opts?: {
23
+ flushImmediately?: boolean;
24
+ }): void;
25
+ recordGateBlock(sessionId: string | undefined, data: GateBlockEventData): void;
26
+ recordGateBypass(sessionId: string | undefined, data: GateBypassEventData): void;
27
+ recordPlanApproval(sessionId: string | undefined, data: PlanApprovalEventData): void;
28
+ recordEvolutionTask(data: EvolutionTaskEventData): void;
29
+ recordEvolutionTaskCompleted(data: EvolutionTaskEventData): void;
30
+ recordEmpathyRollback(sessionId: string | undefined, data: EmpathyRollbackEventData): void;
31
+ recordError(sessionId: string | undefined, message: string, context?: Record<string, unknown>): void;
32
+ recordWarn(sessionId: string | undefined, message: string, context?: Record<string, unknown>): void;
33
+ recordDiagnosisTask(data: DiagnosisTaskEventData): void;
34
+ recordHeartbeatDiagnosis(data: HeartbeatDiagnosisEventData): void;
35
+ recordDiagnosticianReport(data: DiagnosticianReportEventData): void;
36
+ recordPrincipleCandidate(data: PrincipleCandidateEventData): void;
37
+ recordRuleEnforced(data: RuleEnforcedEventData): void;
38
+ recordRuleHostEvaluated(data: RuleHostEvaluatedEventData): void;
39
+ recordRuleHostBlocked(data: RuleHostBlockedEventData): void;
40
+ recordRuleHostRequireApproval(data: RuleHostRequireApprovalEventData): void;
41
+ recordRuleHostAutoCorrectProposed(data: RuleHostAutoCorrectProposedEventData): void;
42
+ recordRuleHostAutoCorrectApplied(data: RuleHostAutoCorrectAppliedEventData): void;
43
+ recordRuntimeV2ActivationsInjected(data: RuntimeV2PromptActivationsInjectedEventData): void;
44
+ /**
45
+ * PRI-437: Record that an approved rule failed to compile or load.
46
+ *
47
+ * This is NOT just a logger.warn — the unhealthy state is persisted to EventLog
48
+ * so it's visible to CLI (pd runtime health) and Console API.
49
+ *
50
+ * ERR-002: degradation includes a reason and nextAction (not silent).
51
+ */
52
+ recordRuleHostUnhealthy(data: RuleHostUnhealthyEventData): void;
53
+ /**
54
+ * PRI-491: Record that an active activation was skipped at load time for a
55
+ * structured reason (flag-off v2, unsupported action, unsupported context
56
+ * version, missing target_ref). Unlike rulehost_unhealthy (compile/load
57
+ * failures), these are configuration/flag issues — the RuleCode itself may
58
+ * be valid, but the runtime chose not to execute it.
59
+ *
60
+ * ERR-002: degradation/suspension includes reason + nextAction (rc-9).
61
+ */
62
+ recordRuleHostSkipped(data: RuleHostSkippedEventData): void;
63
+ /**
64
+ * Redact telemetry-sensitive string values in event data before persistence.
65
+ * Applies redactTelemetryString to known high-risk fields (filePath, command,
66
+ * reason, args, new_string, old_string, text, paramsSummary values) and to all
67
+ * string values in tool_call/rulehost_* data as a safety net.
68
+ *
69
+ * ERR-002: never throws; returns data unchanged on error.
70
+ * ERR-045/046: covers composite command strings, Authorization headers, env vars.
71
+ */
72
+ private redactEventData;
73
+ private record;
74
+ private formatDate;
75
+ private loadStats;
76
+ private updateStats;
77
+ private startFlushTimer;
78
+ flush(): void;
79
+ getBufferedEvents(): EventLogEntry[];
80
+ private getEventDedupKey;
81
+ private readPersistedEvents;
82
+ private getMergedEvents;
83
+ private flushEvents;
84
+ private flushStats;
85
+ getDailyStats(date: string): DailyStats;
86
+ getEmpathyStats(range: 'today' | 'week' | 'session', sessionId?: string): EmpathyEventStats;
87
+ private aggregateSessionEmpathy;
88
+ rollbackEmpathyEvent(eventId: string, sessionId: string | undefined, reason: string, triggeredBy: 'user_command' | 'natural_language' | 'system'): number;
89
+ getLastEmpathyEventId(sessionId: string): string | null;
90
+ findLatestPainSignal(sessionId: string | undefined): PainSignalEventData | null;
91
+ dispose(): void;
92
+ }
93
+ export declare class EventLogService {
94
+ private static readonly instances;
95
+ static get(stateDir: string, logger?: PluginLogger): EventLog;
96
+ static flushAll(): void;
97
+ static disposeAll(): void;
98
+ }
@@ -0,0 +1,119 @@
1
+ /**
2
+ * Evolution Engine V2.0 - MVP
3
+ *
4
+ * 成长驱动的进化积分系统,替代惩罚驱动的 Trust Engine。
5
+ *
6
+ * 核心原则:
7
+ * 1. 起点0分,只能增加,不扣分
8
+ * 2. 失败记录教训,不扣分
9
+ * 3. 同类任务失败后首次成功 = 双倍奖励(1小时冷却)
10
+ * 4. 高等级做低级任务积分衰减
11
+ * 5. 原子写入防止并发损坏
12
+ */
13
+ import type { EvolutionScorecard, EvolutionStats, EvolutionConfig, TaskDifficulty, TierDefinition, GateDecision, ToolCallContext } from './evolution-types.js';
14
+ import { EvolutionTier } from './evolution-types.js';
15
+ export declare class EvolutionEngine {
16
+ private readonly scorecard;
17
+ private readonly workspaceDir;
18
+ private readonly stateDir;
19
+ private readonly config;
20
+ private readonly storagePath;
21
+ constructor(workspaceDir: string, config?: Partial<EvolutionConfig>);
22
+ /** 获取当前积分 */
23
+ getPoints(): number;
24
+ /** 获取可用积分 */
25
+ getAvailablePoints(): number;
26
+ /** 获取当前等级 */
27
+ getTier(): EvolutionTier;
28
+ /** 获取当前等级定义 */
29
+ getTierDefinition(): TierDefinition;
30
+ /** 获取完整积分卡 */
31
+ getScorecard(): EvolutionScorecard;
32
+ /** 获取统计信息 */
33
+ getStats(): EvolutionStats;
34
+ /** 获取状态摘要 */
35
+ getStatusSummary(): {
36
+ tier: EvolutionTier;
37
+ tierName: string;
38
+ totalPoints: number;
39
+ availablePoints: number;
40
+ permissions: import("@principles/core/runtime-v2").TierPermissions;
41
+ stats: EvolutionStats;
42
+ nextTier: {
43
+ tier: EvolutionTier;
44
+ name: string;
45
+ pointsNeeded: number;
46
+ } | null;
47
+ };
48
+ recordSuccess(toolName: string, options?: {
49
+ filePath?: string;
50
+ difficulty?: TaskDifficulty;
51
+ reason?: string;
52
+ sessionId?: string;
53
+ }): {
54
+ pointsAwarded: number;
55
+ isDoubleReward: boolean;
56
+ newTier?: EvolutionTier;
57
+ };
58
+ recordFailure(toolName: string, options?: {
59
+ filePath?: string;
60
+ difficulty?: TaskDifficulty;
61
+ reason?: string;
62
+ sessionId?: string;
63
+ }): {
64
+ pointsAwarded: number;
65
+ lessonRecorded: boolean;
66
+ };
67
+ /** 工具调用前检查 */
68
+ beforeToolCall(context: ToolCallContext): GateDecision;
69
+ private calculatePoints;
70
+ private getDifficultyPenalty;
71
+ private canReceiveDoubleReward;
72
+ private checkAndApplyPromotion;
73
+ private static inferDifficulty;
74
+ private static computeTaskHash;
75
+ private createEvent;
76
+ private addEvent;
77
+ private loadOrCreateScorecard;
78
+ private createNewScorecard;
79
+ /** 持久化评分卡(含锁保护) */
80
+ private saveScorecard;
81
+ /** Per-instance retry queue (P0 fix: was static, causing cross-instance race) */
82
+ private retryQueue;
83
+ private retryTimer;
84
+ /** 调度重试保存 */
85
+ private scheduleRetrySave;
86
+ /** 处理重试队列 */
87
+ private processRetryQueue;
88
+ /** 无锁快速保存(用于重试) */
89
+ private saveScorecardImmediate;
90
+ private generateId;
91
+ dispose(): void;
92
+ }
93
+ /** 获取指定 workspace 的引擎实例 */
94
+ export declare function getEvolutionEngine(workspaceDir: string): EvolutionEngine;
95
+ export declare function disposeEvolutionEngine(workspaceDir: string): void;
96
+ export declare function disposeAllEvolutionEngines(): void;
97
+ /** 记录成功(便捷函数) */
98
+ export declare function recordEvolutionSuccess(workspaceDir: string, toolName: string, options?: {
99
+ filePath?: string;
100
+ difficulty?: TaskDifficulty;
101
+ reason?: string;
102
+ sessionId?: string;
103
+ }): {
104
+ pointsAwarded: number;
105
+ isDoubleReward: boolean;
106
+ newTier?: EvolutionTier;
107
+ };
108
+ /** 记录失败(便捷函数) */
109
+ export declare function recordEvolutionFailure(workspaceDir: string, toolName: string, options?: {
110
+ filePath?: string;
111
+ difficulty?: TaskDifficulty;
112
+ reason?: string;
113
+ sessionId?: string;
114
+ }): {
115
+ pointsAwarded: number;
116
+ lessonRecorded: boolean;
117
+ };
118
+ /** Gate 检查(便捷函数) */
119
+ export declare function checkEvolutionGate(workspaceDir: string, context: ToolCallContext): GateDecision;