principles-disciple 1.139.0 → 1.141.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,170 +1,15 @@
1
1
  /**
2
- * Raw Observation Adapter — PRI-362
2
+ * Raw Observation Adapter — PRI-362 / PRI-446
3
3
  *
4
- * Unified source-kind resolution from RawObservation.
4
+ * The source-kind resolution logic and RawObservation builders have been
5
+ * migrated to principles-core (runtime-v2/evidence-triage/observation-resolver.ts).
5
6
  *
6
- * Replaces scattered resolveSourceKindFrom* functions with a single
7
- * field-driven adapter that maps observation fields to SourceKind.
8
- *
9
- * Field precedence (highest to lowest):
10
- * 1. isManualEntry → owner_reported
11
- * 2. isGateBlock → rulehost_block
12
- * 3. isSubagentError → subagent_error
13
- * 4. isRateLimit → rate_limit (if true)
14
- * 5. toolName === 'pain' / 'skill:pain' → agent_on_owner_request (with openclaw_context_bound) / owner_reported
15
- * 6. failureSource → tool_failure / dispatch_error
16
- * 7. isGfiTriggered → gfi_threshold
17
- * 8. detectionSource → llm_paralysis / semantic / empathy_inferred / unknown
18
- * 9. Fallback → unknown
7
+ * This file is now a thin re-export adapter. It preserves the original export
8
+ * names (resolveSourceKind, buildToolFailureObservation, buildLlmDetectionObservation,
9
+ * RawObservation) so all existing import sites and the source-string
10
+ * characterization tests keep working without changes.
19
11
  *
20
12
  * ERR checklist:
21
- * - ERR-001: Source kind resolved from runtime values, no `as` casts.
22
- * - ERR-002: Every path returns a valid SourceKind (fallback to 'unknown').
23
- * - EP-01: Runtime values validated before use.
24
- */
25
- /**
26
- * Resolve SourceKind from a unified RawObservation.
27
- *
28
- * This function replaces the scattered resolveSourceKindFrom* functions
29
- * and provides a single entry point for source-kind classification.
30
- *
31
- * Field precedence is explicitly defined in the function body to ensure
32
- * deterministic behavior and make the logic easy to understand and test.
33
- */
34
- export function resolveSourceKind(observation) {
35
- const { isManualEntry, isGateBlock, isSubagentError, isRateLimit, toolName, failureSource, isGfiTriggered, detectionSource, nonZeroExit, timedOut, toolNotFound, } = observation;
36
- // Priority 1: Manual entry (CLI, owner-reported)
37
- if (isManualEntry) {
38
- return 'owner_reported';
39
- }
40
- // Priority 2: Gate block
41
- if (isGateBlock) {
42
- return 'rulehost_block';
43
- }
44
- // Priority 3: Subagent error
45
- if (isSubagentError) {
46
- return 'subagent_error';
47
- }
48
- // Priority 4: Provider rate limit (explicit true/false)
49
- if (isRateLimit === true) {
50
- return 'rate_limit';
51
- }
52
- if (isRateLimit === false) {
53
- return 'provider_failure';
54
- }
55
- // Priority 5: Manual pain tool
56
- if (toolName === 'pain' || toolName === 'skill:pain') {
57
- // Match resolveSourceKindFromToolFailure behavior:
58
- // openclaw_context_bound → agent_on_owner_request
59
- // other provenance or undefined → owner_reported
60
- if (observation.provenance === 'openclaw_context_bound') {
61
- return 'agent_on_owner_request';
62
- }
63
- return 'owner_reported';
64
- }
65
- // Priority 6: GFI threshold (must check before failure source for LLM detection path)
66
- if (isGfiTriggered) {
67
- return 'gfi_threshold';
68
- }
69
- // Priority 7: Tool failure / dispatch error
70
- if (failureSource) {
71
- // Match resolveSourceKindFromToolFailure behavior:
72
- // dispatch_error → dispatch_error, anything else → tool_failure
73
- if (failureSource === 'dispatch_error') {
74
- return 'dispatch_error';
75
- }
76
- return 'tool_failure';
77
- }
78
- // Infer failureSource from tool failure indicators if not explicitly set
79
- if (toolNotFound) {
80
- return 'dispatch_error';
81
- }
82
- // Match classifyToolFailureSource behavior: unknown tool name → dispatch_error
83
- // BUT only if this looks like a tool failure context (has other tool fields)
84
- // Otherwise, this is likely a non-tool observation (e.g., LLM detection)
85
- const hasToolContext = toolName !== undefined || nonZeroExit || timedOut || toolNotFound;
86
- if (hasToolContext && (!toolName || toolName.trim() === '')) {
87
- return 'dispatch_error';
88
- }
89
- // Exit code-based detection: non-zero exit or timeout → tool_failure
90
- if (nonZeroExit || timedOut) {
91
- return 'tool_failure';
92
- }
93
- // Priority 8: LLM detection source
94
- if (detectionSource) {
95
- // Match resolveSourceKindFromLlmDetection behavior:
96
- if (detectionSource === 'llm_paralysis') {
97
- return 'llm_paralysis';
98
- }
99
- if (detectionSource.startsWith('llm_')) {
100
- return 'semantic';
101
- }
102
- if (detectionSource === 'user_empathy') {
103
- return 'empathy_inferred';
104
- }
105
- }
106
- // Fallback: unknown
107
- return 'unknown';
108
- }
109
- // ── Builder Functions ──────────────────────────────────────────────────────
110
- //
111
- // PRI-360 S1: These builders construct RawObservation from specific contexts,
112
- // centralizing source classification rules in the adapter layer.
113
- // Hooks should NOT hold source classification logic — use these builders.
114
- /**
115
- * Classify error message as dispatch_error vs tool_failure.
116
- *
117
- * This centralizes the regex-based classification that was previously
118
- * scattered in classifyToolFailureSource and after-tool-call-helpers.
119
- * Now hooks call this builder + resolveSourceKind instead of holding rules.
120
- */
121
- function classifyErrorForDispatch(error) {
122
- if (!error)
123
- return 'tool_failure';
124
- const msg = String(error);
125
- if (/\btool\s+(?:\S+\s+)?not\s+found\b/i.test(msg) || /\bunknown\s+tool\b/i.test(msg)) {
126
- return 'dispatch_error';
127
- }
128
- return 'tool_failure';
129
- }
130
- /**
131
- * Build a RawObservation for a tool failure context.
132
- *
133
- * This replaces classifyToolFailureSource and the inline classification
134
- * in after-tool-call-helpers. All tool error → dispatch/tool_failure
135
- * classification is centralized here.
136
- */
137
- export function buildToolFailureObservation(options) {
138
- const { toolName, error, provenance } = options;
139
- const nonZeroExit = typeof options.exitCode === 'number' && options.exitCode !== 0;
140
- // Classify dispatch vs tool_failure centrally
141
- let failureSource;
142
- if (!toolName || toolName.trim() === '') {
143
- // Empty/whitespace tool name → dispatch error
144
- failureSource = 'dispatch_error';
145
- }
146
- else {
147
- failureSource = classifyErrorForDispatch(error);
148
- }
149
- // If neither error nor non-zero exit, this is not a failure context
150
- if (!error && !nonZeroExit) {
151
- failureSource = undefined;
152
- }
153
- return {
154
- observedAt: new Date().toISOString(),
155
- toolName,
156
- failureSource,
157
- nonZeroExit,
158
- provenance,
159
- };
160
- }
161
- /**
162
- * Build a RawObservation for an LLM detection context.
13
+ * - ERR-011: re-export adapter, not a local re-definition of migrated logic.
163
14
  */
164
- export function buildLlmDetectionObservation(options) {
165
- return {
166
- observedAt: new Date().toISOString(),
167
- detectionSource: options.detectionSource,
168
- isGfiTriggered: options.isGfiTriggered,
169
- };
170
- }
15
+ export { resolveSourceKind, buildToolFailureObservation, buildLlmDetectionObservation, } from '@principles/core/runtime-v2';
@@ -1,62 +1,11 @@
1
1
  /**
2
- * Raw Observation Types — PRI-362
2
+ * Raw Observation Types — PRI-362 / PRI-446
3
3
  *
4
- * Source adapter layer that normalizes diverse hook contexts into a unified
5
- * observation model before mapping to SourceKind.
6
- *
7
- * This replaces scattered resolveSourceKindFrom* functions with a single
8
- * field-driven adapter.
4
+ * The RawObservation type has been migrated to principles-core
5
+ * (runtime-v2/evidence-triage/observation-resolver.ts). This file re-exports it
6
+ * so existing plugin import sites keep working unchanged.
9
7
  *
10
8
  * ERR checklist:
11
- * - ERR-001: No `as` casts; validate unknown payload field-by-field.
12
- * - ERR-002: Every decision carries reason + nextAction.
13
- * - EP-01: Source adapter validates before use.
14
- */
15
- /**
16
- * Raw observation from a source adapter.
17
- *
18
- * This is the input to resolveSourceKind. It contains all possible
19
- * context fields that different sources may provide. The adapter
20
- * reads only the fields it needs based on the observation source.
9
+ * - ERR-011: this is a re-export adapter, not a local re-definition.
21
10
  */
22
- export interface RawObservation {
23
- /** When the observation was made (ISO timestamp) */
24
- readonly observedAt: string;
25
- /** Workspace identifier */
26
- readonly workspaceId?: string;
27
- /** Session identifier */
28
- readonly sessionId?: string;
29
- /** Trace identifier for correlation */
30
- readonly traceId?: string;
31
- /** Tool name (for after_tool_call hook) */
32
- readonly toolName?: string;
33
- /** Failure source classification */
34
- readonly failureSource?: 'tool_failure' | 'dispatch_error';
35
- /** Whether the tool call exited with non-zero code */
36
- readonly nonZeroExit?: boolean;
37
- /** Whether the tool call timed out */
38
- readonly timedOut?: boolean;
39
- /** Whether the tool does not exist */
40
- readonly toolNotFound?: boolean;
41
- /** Detection source identifier */
42
- readonly detectionSource?: string;
43
- /** Whether GFI threshold was crossed */
44
- readonly isGfiTriggered?: boolean;
45
- /** Whether the failure was a rate limit (429) */
46
- readonly isRateLimit?: boolean;
47
- /** Whether this observation came from a gate block */
48
- readonly isGateBlock?: boolean;
49
- /** Whether this was a manual CLI entry */
50
- readonly isManualEntry?: boolean;
51
- /** Provenance: how trustworthy and context-bound is the observation */
52
- readonly provenance?: 'openclaw_context_bound' | 'owner_reported_no_host_trace' | 'automatic_hook';
53
- /** Whether this observation came from a subagent error */
54
- readonly isSubagentError?: boolean;
55
- /**
56
- * Raw payload from the source.
57
- *
58
- * This is always `unknown` (ERR-005). Source adapters validate only
59
- * enough to identify the source and capture bounded context.
60
- */
61
- readonly payload?: unknown;
62
- }
11
+ export type { RawObservation } from '@principles/core/runtime-v2';
@@ -1,15 +1,11 @@
1
1
  /**
2
- * Raw Observation Types — PRI-362
2
+ * Raw Observation Types — PRI-362 / PRI-446
3
3
  *
4
- * Source adapter layer that normalizes diverse hook contexts into a unified
5
- * observation model before mapping to SourceKind.
6
- *
7
- * This replaces scattered resolveSourceKindFrom* functions with a single
8
- * field-driven adapter.
4
+ * The RawObservation type has been migrated to principles-core
5
+ * (runtime-v2/evidence-triage/observation-resolver.ts). This file re-exports it
6
+ * so existing plugin import sites keep working unchanged.
9
7
  *
10
8
  * ERR checklist:
11
- * - ERR-001: No `as` casts; validate unknown payload field-by-field.
12
- * - ERR-002: Every decision carries reason + nextAction.
13
- * - EP-01: Source adapter validates before use.
9
+ * - ERR-011: this is a re-export adapter, not a local re-definition.
14
10
  */
15
11
  export {};
@@ -42,38 +42,18 @@ export { resolveSourceKind, buildToolFailureObservation, buildLlmDetectionObserv
42
42
  * - Falling back to existing behavior when the flag is off
43
43
  */
44
44
  export function evaluateEvidenceTriage(sourceKind, score, options) {
45
+ // PRI-446: the risky high-score and repeated-failure upgrade rules now live
46
+ // in core triage-policy.ts (single source of truth). The adapter passes the
47
+ // context flags straight through; core decides whether to upgrade.
45
48
  const input = {
46
49
  sourceKind,
47
50
  score,
48
51
  isUnsafeHighConfidence: options?.isUnsafeHighConfidence,
49
52
  provenance: options?.provenance,
53
+ isRisky: options?.isRisky,
54
+ consecutiveErrors: options?.consecutiveErrors,
50
55
  };
51
- let result = evaluateTriage(input);
52
- // PEAT-B1 upgrade logic: risky high-score overrides evidence_only
53
- // Matches PainDiagnosticGate.risky_high_score: isRisky && score >= 70 → admit
54
- if (result.decision === 'evidence_only' &&
55
- options?.isRisky === true &&
56
- score >= 70) {
57
- result = {
58
- ...result,
59
- decision: 'admit',
60
- reason: 'Risky high-score operation overrides evidence-only decision. Immediate diagnosis required.',
61
- nextAction: 'create_diagnostic_task',
62
- };
63
- }
64
- // PEAT-B1 upgrade logic: repeated failures override evidence_only
65
- // Threshold: 4 consecutive failures (matches PainDiagnosticGate.repeatedFailure)
66
- if (result.decision === 'evidence_only' &&
67
- options?.consecutiveErrors !== undefined &&
68
- options.consecutiveErrors >= 4) {
69
- result = {
70
- ...result,
71
- decision: 'admit',
72
- reason: 'Repeated failures override evidence-only decision. Pattern suggests systemic issue requiring diagnosis.',
73
- nextAction: 'create_diagnostic_task',
74
- };
75
- }
76
- return result;
56
+ return evaluateTriage(input);
77
57
  }
78
58
  // ── High-Confidence Unsafe Action Detection ──────────────────────────────────
79
59
  /**
@@ -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.139.0",
5
+ "version": "1.141.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.139.0",
3
+ "version": "1.141.0",
4
4
  "description": "Native OpenClaw plugin for Principles Disciple",
5
5
  "type": "module",
6
6
  "main": "./dist/bundle.js",
@@ -1,9 +0,0 @@
1
- import type { PluginHookSubagentEndedEvent, PluginHookSubagentContext, OpenClawPluginApi } from '../openclaw-sdk.js';
2
- type SubagentEndedHookContext = PluginHookSubagentContext & {
3
- api?: OpenClawPluginApi;
4
- workspaceDir?: string;
5
- sessionId?: string;
6
- agentId?: string;
7
- };
8
- export declare function handleSubagentEnded(event: PluginHookSubagentEndedEvent, ctx: SubagentEndedHookContext): Promise<void>;
9
- export {};
@@ -1,122 +0,0 @@
1
- import { WorkspaceContext } from '../core/workspace-context.js';
2
- import { extractAgentIdFromSessionKey } from '../utils/session-key.js';
3
- import { recordEvolutionSuccess } from '../core/evolution-engine.js';
4
- import { WorkflowStore } from '../service/subagent-workflow/workflow-store.js';
5
- /**
6
- * Factory to create the appropriate WorkflowManager by workflow_type string.
7
- * Used by the subagent_ended hook to dispatch lifecycle recovery to the right manager.
8
- */
9
- function createWorkflowManagerForType(workflowType) {
10
- switch (workflowType) {
11
- default:
12
- return null;
13
- }
14
- }
15
- const HELPER_WORKFLOW_SESSION_PREFIX = 'agent:main:subagent:workflow-';
16
- // Cleanup expired retry entries periodically
17
- function emitSubagentPainEvent(wctx, payload, logger) {
18
- try {
19
- wctx.evolutionReducer.emitSync({
20
- ts: new Date().toISOString(),
21
- type: 'pain_detected',
22
- data: {
23
- painId: `pain_${Date.now()}_${Math.random().toString(36).slice(2, 10)}`,
24
- painType: 'subagent_error',
25
- source: payload.source,
26
- reason: payload.reason,
27
- score: payload.score,
28
- sessionId: payload.sessionId,
29
- agentId: payload.agentId,
30
- },
31
- });
32
- }
33
- catch (e) {
34
- logger.warn(`[PD:Subagent] failed to emit evolution event: ${String(e)}`);
35
- }
36
- }
37
- export async function handleSubagentEnded(event, ctx) {
38
- const { outcome, targetSessionKey } = event;
39
- const { workspaceDir } = ctx;
40
- if (!workspaceDir)
41
- return;
42
- const wctx = WorkspaceContext.fromHookContext(ctx);
43
- const logger = ctx.api?.logger ?? console;
44
- // ── Helper Workflow Lifecycle Notification ──
45
- // When a helper workflow's subagent ends, notify the workflow manager
46
- // so that it can trigger fallback recovery (notifyWaitResult → finalizeOnce)
47
- if (targetSessionKey?.startsWith(HELPER_WORKFLOW_SESSION_PREFIX)) {
48
- try {
49
- const store = new WorkflowStore({ workspaceDir });
50
- const workflow = store.getWorkflowByChildSession(targetSessionKey);
51
- if (workflow && workflow.state !== 'completed' && workflow.state !== 'terminal_error' && workflow.state !== 'expired') {
52
- logger.info(`[PD:Subagent] Helper workflow lifecycle event: workflowId=${workflow.workflow_id}, workflowType=${workflow.workflow_type}, outcome=${outcome}`);
53
- const mappedOutcome = outcome === 'deleted' ? 'deleted' :
54
- outcome === 'killed' ? 'killed' :
55
- outcome === 'reset' ? 'reset' :
56
- outcome === 'error' ? 'error' :
57
- outcome === 'timeout' ? 'timeout' : 'ok';
58
- // Call notifyLifecycleEvent on the appropriate manager so it
59
- // triggers notifyWaitResult → finalizeOnce / terminal transition.
60
- const subagentRuntime = ctx.api?.runtime?.subagent;
61
- if (subagentRuntime) {
62
- const mgr = createWorkflowManagerForType(workflow.workflow_type);
63
- if (mgr) {
64
- await mgr.notifyLifecycleEvent(workflow.workflow_id, 'subagent_ended', { outcome: mappedOutcome });
65
- mgr.dispose();
66
- }
67
- else {
68
- logger.warn(`[PD:Subagent] Unknown workflow type ${workflow.workflow_type} — falling back to store-only event`);
69
- store.recordEvent(workflow.workflow_id, 'subagent_ended', workflow.state, workflow.state, `subagent ended with outcome: ${outcome}`, { outcome: mappedOutcome });
70
- }
71
- }
72
- else {
73
- logger.warn(`[PD:Subagent] Subagent runtime not available — cannot notify manager, falling back to store event`);
74
- store.recordEvent(workflow.workflow_id, 'subagent_ended', workflow.state, workflow.state, `subagent ended with outcome: ${outcome}`, { outcome: mappedOutcome });
75
- }
76
- store.dispose();
77
- return;
78
- }
79
- store.dispose();
80
- }
81
- catch (e) {
82
- logger.warn(`[PD:Subagent] Failed to notify helper workflow lifecycle: ${String(e)}`);
83
- }
84
- }
85
- const { config } = wctx;
86
- // ── Outcome-based EP and Pain Signal handling ──
87
- // OpenClaw v2026.3.23 fixes: timeout may be false positive (fast-finishing workers)
88
- // Only penalize actual errors, not timeout/killed/reset
89
- if (outcome === 'error') {
90
- // Only actual errors trigger penalty
91
- const scoreSettings = config.get('scores');
92
- const score = scoreSettings.subagent_error_penalty;
93
- const reason = `Subagent session ${targetSessionKey} ended with error`;
94
- // Emit pain via Runtime v2 chain (M8: no .pain_flag file)
95
- emitSubagentPainEvent(wctx, {
96
- source: `subagent_error`,
97
- reason,
98
- score,
99
- sessionId: ctx.sessionId,
100
- agentId: ctx.agentId || extractAgentIdFromSessionKey(targetSessionKey),
101
- }, logger);
102
- }
103
- if (outcome === 'timeout') {
104
- // OpenClaw v2026.3.23 fix: timeout may be false positive
105
- // Fast-finishing workers are no longer incorrectly reported as timed out
106
- // Do not penalize - the task may have actually succeeded
107
- logger.warn(`[PD:Subagent] Session ${targetSessionKey} timed out - not penalizing (OpenClaw fix applied)`);
108
- }
109
- if (outcome === 'killed' || outcome === 'reset') {
110
- // User-initiated termination or system reset - not an agent failure
111
- logger.info(`[PD:Subagent] Session ${targetSessionKey} ended with ${outcome} - no penalty (user/system action)`);
112
- }
113
- if (outcome === 'ok' || outcome === 'deleted') {
114
- recordEvolutionSuccess(workspaceDir, 'subagent', {
115
- sessionId: ctx.sessionId,
116
- reason: 'subagent_success',
117
- });
118
- }
119
- // ── End of subagent_ended handling ──
120
- // Note: Diagnostician runs via HEARTBEAT (main session LLM), not as a subagent.
121
- // Principle creation happens in evolution-worker.ts marker detection path.
122
- }