principles-disciple 1.197.4 → 1.197.5
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/dist/bundle.js +1 -1
- package/dist/openclaw.plugin.json +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +1 -1
package/dist/bundle.js
CHANGED
|
@@ -878,7 +878,7 @@ CONSTRAINTS:
|
|
|
878
878
|
contains no evidence at all.
|
|
879
879
|
${s}${c}`}var Kz=class{adapter;schema;constructor(t={}){this.adapter=t.adapter??new ed,this.schema=t.schema??ql}buildRootCauseInstruction(t={}){return hGt({adapter:t.adapter??this.adapter,schema:t.schema??this.schema,outputLanguage:t.outputLanguage,coreGrounding:t.coreGrounding,intentGrounding:t.intentGrounding})}buildPrompt(t,r={}){let n=r.limits??pOe,{outputLanguage:o,coreGrounding:i,intentGrounding:a,intentDoc:s}=r,c=[],u=t.conversationWindow,l=u.slice(0,n.maxConversationEntries);u.length>n.maxConversationEntries&&c.push(`conversationWindow truncated from ${u.length} to ${n.maxConversationEntries} entries`);let d=l.map(_=>_.text&&_.text.length>n.maxEntryTextChars?{..._,text:_.text.slice(0,n.maxEntryTextChars)+"...[truncated]"}:_),p={...t,conversationWindow:d},m=this.buildRootCauseInstruction({outputLanguage:o,coreGrounding:i,intentGrounding:a}),f={taskId:t.taskId,contextHash:t.contextHash,diagnosisTarget:t.diagnosisTarget,conversationWindow:d,sourceRefs:t.sourceRefs,context:p,diagnosticInstruction:m,...c.length>0?{truncationWarnings:c}:{},...a&&s?{intentDoc:s}:{}},g=JSON.stringify(f);if(g.length>n.maxMessageChars){let _=g.length-n.maxMessageChars,b=m,v=Math.max(200,b.length-_-100),R=b.slice(0,v)+`
|
|
880
880
|
|
|
881
|
-
[OUTPUT FORMAT section is REQUIRED; other sections may be summarized if needed]`;f.diagnosticInstruction=R,f.truncationWarnings=[...c,`diagnosticInstruction truncated due to size (${g.length} > ${n.maxMessageChars})`],g=JSON.stringify(f)}return{message:g,promptInput:f}}};gc();var Zg=["core","quiet","gone","legacy_retire"],BT=["openclaw","pi-ai"],_u=["diagnostician","dreamer","philosopher","scribe","artificer","evaluator","rolloutReviewer","correctionObserver","empathyObserver","signalCollector"],Fv=["simple","advanced"],Jz=["low","medium","high"],Hz=["realtime","async"],KT=["smoke","unit","full"],k1=["full","summary","off"],Qa=new Set(["__proto__","constructor","prototype"]);var Vz=[{id:"prompt",category:"core",enabled:!0,since:"2026-05-24",description:"Prompt injection for principle application"},{id:"code_tool_hook",category:"core",enabled:!0,since:"2026-05-24",description:"Code tool hook for rule host enforcement"},{id:"defer_archive",category:"core",enabled:!0,since:"2026-05-24",description:"Defer/archive activation writer"},{id:"correction_observer",category:"quiet",enabled:!0,since:"2026-06-02",description:"Independent correction observer service for keyword self-correction (MVP-Core per ADR-0014 amendment, PRI-293; quiet flag to allow runtime disable)"},{id:"signal_collector",category:"quiet",enabled:!1,since:"2026-06-30",description:"Unified signal collection host (correction + empathy upstream merge). NOTE: keyword detection (high-precision phrases) runs regardless of this flag; this flag only gates the LLM deep-judgment path (ambiguous terms / missed keywords). Quiet flag: dogfood-only until validated."},{id:"internalization_auto_consumer",category:"quiet",enabled:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381; quiet flag, default on, disableable via config)"},{id:"story_a_approval_completion",category:"quiet",enabled:!0,since:"2026-06-18",description:"Story A approval-completion orchestrator (PRI-408) \u2014 formal service replacing demo direct-writer activation; quiet flag, default on, disableable via config"},{id:"feedback_channel",category:"quiet",enabled:!0,since:"2026-06-01",description:"MVP seed feedback channel \u2014 privacy-preserving report drafts"},{id:"gfi",category:"quiet",enabled:!1,since:"2026-05-24",description:"Global Friction Index session scoring"},{id:"evolution_worker",category:"quiet",enabled:!1,since:"2026-06-01",description:"Legacy evolution worker heartbeat (MVP-Quiet per ADR-0014 \xA72.5)"},{id:"empathy_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking (MVP-Quiet)"},{id:"painEvidenceAdmission",category:"quiet",enabled:!0,since:"2026-06-06",description:"Pre-diagnosis evidence triage for pain signals (PEAT-B1). PRI-454: default-on, Gate B is primary gate."},{id:"pain_evidence_admission",category:"quiet",enabled:!0,since:"2026-06-15",description:"Snake-case alias for painEvidenceAdmission \u2014 same functionality, matches config.yaml key convention. PRI-454: default-on."},{id:"painEvidenceAdmissionDefault",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Global kill switch for Gate B migration. When ON (default), Gate B (TriggerController) owns admission. When OFF (rollback), Gate A (PainDiagnosticGate) is re-activated."},{id:"pain_evidence_admission_default",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Snake-case alias for painEvidenceAdmissionDefault \u2014 global kill switch, matches config.yaml key convention"},{id:"diagnostician_async_cli",category:"quiet",enabled:!1,since:"2026-06-11",description:"Async pain-record CLI \u2014 submit and return immediately, diagnosis runs in background. Default: false until orchestrator exists."},{id:"diagnostician_core_grounding",category:"quiet",enabled:!0,since:"2026-06-11",description:"Core principle grounding in diagnostician prompt (Arm 2)"},{id:"internalization_core_grounding",category:"quiet",enabled:!0,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders (dreamer, philosopher, scribe)"},{id:"diagnostician_split_pipeline",category:"quiet",enabled:!0,since:"2026-06-11",description:"3-stage split diagnostician pipeline (RootCause\u2192Distiller\u2192Router)"},{id:"diagnostician_llm_degradation",category:"quiet",enabled:!1,since:"2026-07-03",description:"Diagnostician LLM rate-limit graceful degradation \u2014 on persistent rate-limit, emit diag_llm_rate_limit_degraded telemetry + rate_limit errorCategory instead of max_attempts_exceeded (ADR-0019). Default off; flag-off = hard fail (legacy behavior)."},{id:"l2_dreamer",category:"quiet",enabled:!1,since:"2026-06-16",description:"L2 multi-turn agent loop for the dreamer runner (PRI-419) \u2014 read-only tools + submit_output, scoped to dreamer only"},{id:"code_rule_capability",category:"core",enabled:!0,since:"2026-06-18",description:"Code-rule capability (atomic: ArtificerL2 + Evaluator) for RuleHost pipeline \u2014 MVP-Core, default ON (PRI-435)"},{id:"intent_engineering",category:"quiet",enabled:!1,since:"2026-06-25",description:"INTENT.md-grounded constructive friction and Stage-A intent tension diagnosis (PRI-465). Default off; flag-off = no INTENT read, no prompt injection, no intentTension."},{id:"rulecode_context_v2",category:"quiet",enabled:!1,since:"2026-06-27",description:"RuleContext v2 \u2014 rule-code context vision (PRI-479). Foundation flag; default off, v1 rule behavior unchanged. See docs/superpowers/specs/2026-06-27-rulecode-context-vision-design.md"},{id:"failed_tasks_observability",category:"quiet",enabled:!0,since:"2026-07-04",description:"Failed tasks observability \u2014 list/view failed pipeline tasks"},{id:"evaluator_artificer_repair_loop",category:"quiet",enabled:!1,since:"2026-07-04",description:"PRI-509: Evaluator\u2192Artificer repair loop \u2014 auto-seed artificer repair task on needs_revision. Default off; flag-off = current behavior (no repair task seeded)."},{id:"nocturnal",category:"gone",enabled:!1,since:"2026-05-24",description:"Nocturnal trinity pipeline (retired)"},{id:"idle_trigger",category:"gone",enabled:!1,since:"2026-05-24",description:"Idle trigger for background processing (retired)"},{id:"new_user_onboarding",category:"core",enabled:!0,since:"2026-07-01",description:"New user onboarding wizard \u2014 first-visit redirect to /welcome + demo story-a trigger endpoint. Maintainer-approved MVP-Core (2026-07-01): default-on; emergency disable via .pd/config.yaml: new_user_onboarding: { enabled: false }."}];var n0={};for(let e of Vz)n0[e.id]={category:e.category,enabled:e.enabled};var dOe="pd.default",mOe={type:"pi-ai",provider:"",model:"",apiKeyEnv:""},gGt="openclaw.default",yGt={type:"openclaw",source:"default"},r0=dOe,Xz=mOe,_Gt={diagnostician:!0,dreamer:!0,philosopher:!1,scribe:!0,artificer:!0,evaluator:!1,rolloutReviewer:!1,correctionObserver:!1,empathyObserver:!1,signalCollector:!1};function T1(){let e={};for(let t of _u)e[t]={enabled:_Gt[t],runtimeProfile:r0};return{defaultRuntime:r0,agents:e}}var I1={diagnostics:{mode:"simple"}},Zu={thinkingOs:!1,projectFocus:"off",evolutionContext:{enabled:!0,maxMessages:4,maxCharsPerMessage:200}};function Yz(){return{version:1,features:{...n0},runtimeProfiles:{[dOe]:{...mOe},[gGt]:{...yGt}},internalAgents:T1(),ui:{...I1},principles:{outputLanguage:void 0},contextInjection:void 0}}var hQ=["prompt","code_tool_hook","defer_archive"];function Kc(e){let{config:t}=e,r=[],n={};for(let[i,a]of Object.entries(n0))n[i]={id:i,category:a.category,enabled:a.enabled};for(let[i,a]of Object.entries(t.features))if(!Qa.has(i)&&a)if(Object.hasOwn(n,i)){let s=n[i];if(!s)continue;if(s.category==="gone"&&a.enabled){r.push(`feature '${i}': gone flag cannot be re-enabled`);continue}if(s.category==="core"&&!a.enabled){r.push(`feature '${i}': core flag explicitly disabled via config (emergency disable)`),n[i]={id:i,category:s.category,enabled:!1};continue}n[i]={id:i,category:a.category,enabled:a.enabled}}else{if(!Zg.includes(a.category)){r.push(`feature '${i}': invalid category '${a.category}', ignored`);continue}n[i]={id:i,category:a.category,enabled:a.enabled},r.push(`feature '${i}': unknown flag accepted`)}let o=[];for(let i of hQ){let a=n[i];a&&a.enabled&&o.push(i)}return{flags:n,enabledChannels:o,warnings:r}}function td(e,t){return Object.hasOwn(e.flags,t)?e.flags[t]?.enabled??!1:!1}var Zz="<redacted-path>",oh="[REDACTED]";var xGt=/(?:[A-Za-z]:[\\/](?:[^\\\s/:*?"<>|]+[\\/])+[^\\\s/:*?"<>|]*)/g,bGt=/(?<![a-zA-Z0-9_.])[\\/](?:usr|home|Users|var|opt|etc|tmp|root|run|mnt|media|srv|boot|dev|proc|sys)(?:[\\/][^\\\s/:*?"<>|]+)+/g;function ih(e){return typeof e!="string"?e:e.replace(xGt,Zz).replace(bGt,Zz)}var vGt=/\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}\b/g,SGt=/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/g,wGt=/\blin_api_[A-Za-z0-9_-]{16,}\b/g,kGt=/(Authorization\s*:\s*)(["'])?([A-Za-z]+\s+)?([^\s"';,]+)/gi,TGt=/(\$env:\s*[A-Z_][A-Z0-9_]{2,}\s*=\s*")([^"]*)(")/gi,IGt=/\b(api[_-]?key|token|secret|password|auth(?:_?token)?)\s*[:=]\s*['"]?([^\s'",}{]+)['"]?/gi,EGt=/\bBearer\s+[A-Za-z0-9._\-+/=]{8,}\b/g;function ah(e){return typeof e!="string"?e:e.replace(vGt,oh).replace(SGt,oh).replace(wGt,oh).replace(kGt,"$1$2$3[REDACTED]").replace(TGt,"$1[REDACTED]$3").replace(EGt,oh).replace(IGt,(t,r)=>`${r}=${oh}`)}var RGt=/\b([A-Z_][A-Z0-9_]{2,})\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s,;}{]+))/g;function sh(e){return typeof e!="string"?e:e.replace(RGt,(t,r)=>`${r}=${oh}`)}function Qg(e){if(typeof e!="string")return e;let t=ih(e);return t=ah(t),t=sh(t),t}var CGt=new Set(["password","passwd","secret","token","api","apikey","authorization","auth","credential","credentials","private","key"]);function AGt(e){return e.toLowerCase().split(/[_\-.]/g).filter(t=>t.length>0)}function fOe(e){let t=AGt(e);if(t.length===0)return!1;for(let r of t)if(CGt.has(r))return!0;return!1}var OGt=6,hOe=100,gQ=2e3;function Qz(e,t){if(e===null)return{ok:!0,value:null,notes:[]};if(e===void 0)return{ok:!0,value:void 0,notes:[]};let r=typeof e;if(r==="string"){let o=e,i=o;return o=ih(o),o=ah(o),o=sh(o),o!==i&&t.notes.push("string value redacted (path/token/env)"),o.length>gQ&&(o=o.slice(0,gQ)+"\u2026",t.notes.push(`string truncated to ${gQ} chars`)),{ok:!0,value:o,notes:t.notes}}if(r==="bigint")return{ok:!0,value:`<bigint:${e.toString()}>`,notes:[]};if(r!=="object")return{ok:!0,value:e,notes:[]};if(t.depth>=OGt)return{ok:!0,value:"<deep>",notes:[]};let n=e;if(t.seen.has(n))return t.notes.push("circular reference detected"),{ok:!0,value:"<circular>",notes:[]};t.seen.add(n);try{if(Array.isArray(e)){let s=[];for(let c=0;c<e.length;c++){let u=Qz(e[c],{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!u.ok)return u;s.push(u.value)}return{ok:!0,value:s,notes:[]}}let o=e,i={},a=Object.keys(o).slice(0,hOe);for(let s of a){if(fOe(s)){i[s]=oh,t.notes.push(`field "${s}" redacted`);continue}let c=o[s];if(c!==null&&typeof c=="object"&&t.seen.has(c)){t.notes.push(`circular reference detected at "${s}"`),i[s]="<circular>";continue}let u=Qz(c,{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!u.ok)return u;i[s]=u.value}return{ok:!0,value:i,notes:[]}}finally{t.seen.delete(n)}}function PGt(e){let t=[],r=[],n={seen:new WeakSet,depth:0,notes:t};n.seen.add(e);for(let o=0;o<e.length;o++){let i=e[o];if(i!==null&&typeof i=="object"&&n.seen.has(i)){t.push("circular reference detected in array"),r.push("<circular>");continue}let a=Qz(i,n);if(!a.ok)return a;r.push(a.value)}return{ok:!0,value:r,notes:t}}function NGt(e){let t=e,r=[],n={seen:new WeakSet,depth:0,notes:r};n.seen.add(e);let o={},i=Object.keys(t).slice(0,hOe);for(let a of i){if(fOe(a)){o[a]=oh,r.push(`field "${a}" redacted`);continue}let s=t[a];if(s!==null&&typeof s=="object"&&n.seen.has(s)){r.push(`circular reference detected at "${a}"`),o[a]="<circular>";continue}let c=Qz(s,n);if(!c.ok)return c;o[a]=c.value}return{ok:!0,value:o,notes:r}}function E1(e){if(e===null)return{ok:!1,error:"redactSensitiveFields: null is not a redactable object",nextAction:"pass a JSON object or array; null carries no fields to redact"};if(e===void 0)return{ok:!1,error:"redactSensitiveFields: undefined is not a redactable object",nextAction:"pass a JSON object or array; undefined carries no fields to redact"};let t=typeof e;return t!=="object"?{ok:!1,error:`redactSensitiveFields: top-level value must be an object or array (got ${t})`,nextAction:"pass a JSON object or array; for primitive values use redactTokenLikeValues / redactEnvLikeValues / redactAbsolutePaths"}:Array.isArray(e)?PGt(e):NGt(e)}var yQ={pollIntervalMs:5e3,timeoutMs:3e5,defaultMaxAttempts:3,agentId:"peer-runner",coreGrounding:!0};function $Gt(e,t){return{pollIntervalMs:e.pollIntervalMs??yQ.pollIntervalMs,timeoutMs:e.timeoutMs??yQ.timeoutMs,defaultMaxAttempts:e.defaultMaxAttempts??yQ.defaultMaxAttempts,owner:e.owner,runtimeKind:e.runtimeKind,agentId:e.agentId??t,outputLanguage:e.outputLanguage,coreGrounding:e.coreGrounding??!0}}function MGt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LGt(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!MGt(t)||!Object.hasOwn(t,"sourcePainId"))return null;let{sourcePainId:r}=t;return typeof r!="string"||r.length===0?null:r}var ws=class{stateManager;runtimeAdapter;eventEmitter;artifactStore;resolvedOptions;config;pendingAgentDraftStore;phase=xc.Idle;constructor(t,r,n){this.stateManager=t.stateManager,this.runtimeAdapter=t.runtimeAdapter,this.eventEmitter=t.eventEmitter,this.artifactStore=t.artifactStore,this.pendingAgentDraftStore=t.pendingAgentDraftStore,this.config=n,this.resolvedOptions=$Gt(r,n.defaultAgentId)}get currentPhase(){return this.phase}getRuntimeKind(){return typeof this.runtimeAdapter.kind=="function"?this.runtimeAdapter.kind():this.resolvedOptions.runtimeKind}emitSuccessTelemetry(t,r,n){}checkLineageIntegrity(t,r,n){}postFetchTransform(t,r,n){typeof r=="object"&&r!==null&&!Array.isArray(r)&&Reflect.set(r,"generatedAt",new Date().toISOString())}async run(t){this.phase=xc.Idle;let r=this.getRuntimeKind(),n;try{n=await this.stateManager.acquireLease({taskId:t,owner:this.resolvedOptions.owner,runtimeKind:r})}catch(o){return await this.handleLeaseOrPhaseError(t,o)}if(n.taskKind!==this.config.expectedTaskKind)return this.emitEvent("wrong_task_kind",t,{expectedKind:this.config.expectedTaskKind,actualKind:n.taskKind}),await this.stateManager.markTaskFailed(t,"input_invalid"),{status:"failed",taskId:t,errorCategory:"input_invalid",failureReason:`Task kind must be '${this.config.expectedTaskKind}', got '${n.taskKind}'`,attemptCount:n.attemptCount};this.emitEvent("task_leased",t,{taskKind:this.config.expectedTaskKind,attemptCount:n.attemptCount});try{let o=await this.resolveStoreRunId(t);this.phase=xc.BuildingContext;let i=await this.buildContext(t);this.emitEvent("context_built",t,{contextHash:i.contextHash}),this.phase=xc.Invoking;let a=await this.invokeRuntime(t,i);this.emitEvent("run_started",t,{runtimeKind:r}),this.phase=xc.Polling;let s=await this.pollUntilTerminal(a);if(s.status!=="succeeded")return await this.handleRuntimeFailure(t,n,s);this.phase=xc.FetchingOutput;let c=await this.fetchAndParseOutput(a.runId,t);this.postFetchTransform(t,c,i),this.phase=xc.Validating;let u=await this.validateOutput(c,t,i);if(!u.valid)return await this.handleValidationError({taskId:t,task:n,errors:u.errors,errorCategory:u.errorCategory});let l=c;this.emitEvent("output_validated",t,{}),this.checkLineageIntegrity(t,l,i),this.emitSuccessTelemetry(t,l,i);let d=await this.succeedTask(t,o,l,n,i.contextHash,i);return d.status==="succeeded"&&(this.phase=xc.Completed),d}catch(o){return await this.handlePostLeaseError(t,n,o)}}emitEvent(t,r,n){this.eventEmitter.emitTelemetry({eventType:`${this.config.runnerName}_${t}`,traceId:r,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:n})}async pollUntilTerminal(t){let r=Date.now()+this.resolvedOptions.timeoutMs,n=["succeeded","failed","timed_out","cancelled"];for(;Date.now()<r;){let a=await this.runtimeAdapter.pollRun(t.runId);if(n.includes(a.status))return a;await this.sleep(this.resolvedOptions.pollIntervalMs)}try{let a=await this.runtimeAdapter.pollRun(t.runId);if(n.includes(a.status))return a}catch{}let o=!1;try{await this.runtimeAdapter.cancelRun(t.runId)}catch(a){o=!0,this.emitEvent("cancel_run_failed",t.runId,{runId:t.runId,errorMessage:a instanceof Error?a.message:String(a)})}let i=o?" (cancelRun also failed)":"";throw new Je("timeout",`Run ${t.runId} timed out after ${this.resolvedOptions.timeoutMs}ms${i}`)}async fetchAndParseOutput(t,r){let n;try{n=await this.runtimeAdapter.fetchOutput(t)}catch(i){throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"fetchOutput",errorMessage:i instanceof Error?i.message:String(i)}),i}if(!n||!n.payload)throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"payload_missing",errorMessage:`No output available for run ${t}`}),new Je("output_invalid",`No output available for run ${t}`);let{payload:o}=n;if(typeof o!="object"||o===null)throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"payload_not_object",errorMessage:`Output payload is not an object for run ${t}`}),new Je("output_invalid",`Output payload is not an object for run ${t}`);return o}async resolveLineageArtifactIds(t){let{hydratePITaskRecord:r}=await Promise.resolve().then(()=>(yc(),LAe)),n=await this.stateManager.getTask(t);if(!n)return{ids:[],hasRejected:!1};let i=r(n)?.dependencyTaskIds??[];if(i.length===0)return{ids:[],hasRejected:!1};let a=[],s=!1,c=await Promise.allSettled(i.map(u=>this.artifactStore.listBySourceTaskId(u)));for(let u of c)if(u.status==="fulfilled")for(let l of u.value)a.push(l.artifactId);else s=!0;return{ids:a,hasRejected:s}}async resolveStoreRunId(t){let{runs:r,degradedRuns:n}=await this.stateManager.getValidRunsByTaskTolerant(t);n.length>0&&this.eventEmitter.emitTelemetry({eventType:"degradation_triggered",traceId:t,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:{component:"BasePeerRunner",runnerName:this.config.runnerName,trigger:"malformed_historical_run_rows",degradedCount:n.length,runIds:n.map(i=>i.runId),errors:n.map(i=>i.error),nextAction:"Quarantine malformed run rows: pd runtime internalization integrity-repair --confirm"}});let o=r[r.length-1];if(!o)throw new Je("execution_failed",`No valid run records found for task ${t} after lease acquisition. If historical runs are malformed, quarantine them first: pd runtime internalization integrity-repair --confirm`);return o.runId}static hashContextRefs(t){if(t.length===0)return"empty";let r=t.join("|"),n=0;for(let o=0;o<r.length;o++)n=Math.imul(31,n)+r.charCodeAt(o)|0;return`ctx-${Math.abs(n).toString(16)}`}async handleLeaseOrPhaseError(t,r){let n=this.classifyError(r);if(n.category==="lease_conflict")return this.emitEvent("run_failed",t,{errorCategory:"lease_conflict",errorMessage:n.message}),{status:"failed",taskId:t,errorCategory:"lease_conflict",failureReason:n.message,attemptCount:1};this.emitEvent("run_failed",t,{errorCategory:n.category,errorMessage:n.message});let o={taskId:t,taskKind:this.config.expectedTaskKind,status:"leased",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),attemptCount:1,maxAttempts:this.resolvedOptions.defaultMaxAttempts};return this.retryOrFail({taskId:t,task:o,errorCategory:n.category,failureReason:n.message})}async handlePostLeaseError(t,r,n){let o=this.classifyError(n);return this.emitEvent("run_failed",t,{errorCategory:o.category,errorMessage:o.message}),this.retryOrFail({taskId:t,task:r,errorCategory:o.category,failureReason:o.message})}async handleRuntimeFailure(t,r,n){let o=this.mapRunStatusToErrorCategory(n.status,n.reason);return this.emitEvent("run_failed",t,{runStatus:n.status,errorCategory:o}),this.retryOrFail({taskId:t,task:r,errorCategory:o,failureReason:n.reason?`Runtime execution ended with status: ${n.status}. Reason: ${n.reason}`:`Runtime execution ended with status: ${n.status}`})}async handleValidationError(t){let r=t.errorCategory??"output_invalid";return this.emitEvent("output_invalid",t.taskId,{errorCount:t.errors.length,errorCategory:r}),this.retryOrFail({taskId:t.taskId,task:t.task,errorCategory:r,failureReason:`Validation failed: ${t.errors.join("; ")}`})}async retryOrFail(t){if(this.permanentErrorCategories.has(t.errorCategory)){try{await this.stateManager.markTaskFailed(t.taskId,t.errorCategory,t.failureReason)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount,failureReason:t.failureReason}),this.phase=xc.Failed,this.injectAgentDraftOnPermanentFailure(t),{status:"failed",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}if(t.errorCategory==="rate_limit"&&this.isDegradationEnabled()){try{await this.stateManager.markTaskFailed(t.taskId,"rate_limit",`LLM rate limit degraded: ${t.failureReason}`)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("diag_llm_rate_limit_degraded",t.taskId,{errorCategory:"rate_limit",attemptCount:t.task.attemptCount,failureReason:t.failureReason,nextAction:"Retry diagnosis manually with `pd pain retry` when rate limit clears, or enable fallback provider."}),this.phase=xc.Failed,{status:"failed",taskId:t.taskId,errorCategory:"rate_limit",failureReason:`LLM rate limit degraded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}if(this.stateManager.getRetryPolicy().shouldRetry(t.task)){try{await this.stateManager.markTaskRetryWait(t.taskId,t.errorCategory,t.failureReason)}catch(n){return this.emitEvent("mark_retry_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_retried",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount}),this.phase=xc.RetryWaiting,{status:"retried",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}try{await this.stateManager.markTaskFailed(t.taskId,"max_attempts_exceeded",`Max attempts exceeded: ${t.failureReason}`)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:"max_attempts_exceeded",attemptCount:t.task.attemptCount,failureReason:`Max attempts exceeded: ${t.failureReason}`}),this.phase=xc.Failed,{status:"failed",taskId:t.taskId,errorCategory:"max_attempts_exceeded",failureReason:`Max attempts exceeded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}classifyError(t){return t instanceof Je?{category:t.category,message:t.message}:t instanceof Error?{category:"execution_failed",message:t.message}:{category:"execution_failed",message:String(t)}}mapRunStatusToErrorCategory(t,r){switch(t){case"failed":return"execution_failed";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return"execution_failed"}}sleep(t){return new Promise(r=>setTimeout(r,t))}isDegradationEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let r=Kc(t);return td(r,"diagnostician_llm_degradation")}injectAgentDraftOnPermanentFailure(t){if(!this.pendingAgentDraftStore)return;let{taskKind:r}=t.task,{errorCategory:n}=t,o=t.failureReason,i=sh(ih(ah(o))),a={summary:`${r} failed with category=${n} at ${new Date().toISOString()}`,observedFailure:i},s=LGt(t.task.diagnosticJson);try{let c=this.pendingAgentDraftStore.insertPendingDraft({taskId:t.taskId,painId:s??void 0,agentDraft:a});if(!c.ok){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,errorMessage:c.error,nextAction:"Inspect pending_agent_drafts table integrity; draft will be retried on next permanent failure of the same taskId (idempotent UPDATE)."});return}this.emitEvent("agent_draft_inserted",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,draftId:c.id,painIdLinked:s!==null})}catch(c){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,errorMessage:c instanceof Error?c.message:String(c),nextAction:"PendingAgentDraftStore.insertPendingDraft threw unexpectedly; inspect the store implementation."})}}};var R1=class extends ws{validator;contextAssembler;effectiveConfig;intentDocReader;constructor(t,r){super(t,r,{runnerName:"diag_rootcause",expectedTaskKind:"diag_rootcause",defaultAgentId:"main",resultRefPrefix:"diag-rootcause",effectiveConfig:r.effectiveConfig}),this.validator=t.validator,this.contextAssembler=t.contextAssembler,this.effectiveConfig=r.effectiveConfig,this.intentDocReader=t.intentDocReader}get permanentErrorCategories(){return new Set(["storage_unavailable","workspace_invalid","capability_missing","cancelled","input_invalid"])}async buildContext(t){let r=await this.stateManager.getTask(t);if(!r)throw new Je("input_invalid",`Task ${t} not found`);let n=r.inputRef||t,o=await this.contextAssembler.assemble(n),a=Ji(r)?.dependencyTaskIds??[],s=[...o.sourceRefs];if(a.length>0){let u=await Promise.allSettled(a.map(l=>this.stateManager.getTask(l)));for(let l=0;l<u.length;l++){let d=u[l],p=a[l];if(!(!d||p===void 0)&&d.status==="fulfilled"&&d.value){d.value.resultRef&&s.push(d.value.resultRef);let m=d.value?Ji(d.value):null;m?.outputArtifactRefs&&s.push(...m.outputArtifactRefs.map(f=>f.ref))}}}return{contextHash:ws.hashContextRefs(s),contextRefs:s,painPayload:o}}async invokeRuntime(t,r){let n=!1,o=!1;if(this.effectiveConfig){let c=Kc(this.effectiveConfig);n=td(c,"diagnostician_core_grounding"),o=td(c,"intent_engineering")}let i;if(o&&!this.intentDocReader)o=!1;else if(o&&this.intentDocReader){let c=this.intentDocReader.readIntentDoc();c.ok&&c.doc?i={raw:c.doc.raw,contentHash:c.doc.contentHash,path:c.doc.path}:(this.emitEvent("intent_doc_read_failed",t,{reason:c.reason??"unknown",nextAction:c.nextAction??"Check INTENT.md configuration.",flagEnabled:c.flagEnabled,found:c.found}),o=!1)}let a=new Kz,{message:s}=a.buildPrompt(r.painPayload,{outputLanguage:this.resolvedOptions.outputLanguage,coreGrounding:n,intentGrounding:o,intentDoc:i});return this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:s,contextItems:[],outputSchemaRef:"diag-rootcause-output-v1",timeoutMs:this.resolvedOptions.timeoutMs})}async validateOutput(t,r,n){let o=await this.validator.validate(t,r);return{valid:o.valid,errors:o.errors,errorCategory:o.errorCategory}}async succeedTask(t,r,n,o,i,a){try{await this.stateManager.updateRunOutput(r,JSON.stringify(n))}catch(p){throw this.emitEvent("update_output_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)}),p}let s=[],c=!1;try{let p=await this.resolveLineageArtifactIds(t);s=p.ids,c=p.hasRejected}catch(p){this.emitEvent("lineage_resolve_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)})}c&&this.emitEvent("lineage_partial",t,{runId:r,resolvedCount:s.length,warning:"Some dependency artifact queries were rejected; lineage may be incomplete"});let u=`pi-art-${t}-${r}`,l=new Date().toISOString();try{await this.artifactStore.upsertArtifact({artifactId:u,artifactKind:"principle",sourceTaskId:t,lineageArtifactIds:s,validationStatus:"pending",contentJson:JSON.stringify(n),createdAt:l,updatedAt:l})}catch(p){return this.emitEvent("artifact_write_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)}),this.retryOrFail({taskId:t,task:o,errorCategory:"artifact_commit_failed",failureReason:`PIArtifact write failed: ${p instanceof Error?p.message:String(p)}`})}let d=`${this.config.resultRefPrefix}://${r}`;try{await this.stateManager.markTaskSucceeded(t,d)}catch(p){throw this.emitEvent("mark_succeeded_failed",t,{taskId:t,runId:r,errorMessage:p instanceof Error?p.message:String(p)}),p}return this.emitEvent("task_succeeded",t,{attemptCount:o.attemptCount,resultRef:d,rootCauseCategory:n.rootCauseCategory,causalChainDepth:n.causalChain.length}),{status:"succeeded",taskId:t,runId:r,artifactId:u,resultRef:d,contextHash:i,output:n,attemptCount:o.attemptCount}}postFetchTransform(t,r){jl(r,"taskId",t)}emitSuccessTelemetry(t,r,n){this.emitEvent("rootcause_completed",t,{rootCauseCategory:r.rootCauseCategory,causalChainDepth:r.causalChain.length})}};yc();var DGt=h.Union([h.Literal("general"),h.Literal("domain"),h.Literal("scenario")]),ch=h.Object({valid:h.Boolean(),taskId:h.String({minLength:1}),sourceRootCauseArtifactId:h.String({minLength:1,description:"Lineage consistency check \u2014 must match the artifact ID from Stage A"}),abstractedPrinciple:h.String({minLength:1,maxLength:200,description:"Highly abstracted, cross-scenario principle (\u2264200 chars)"}),rationale:h.String({minLength:1,description:"Why this principle addresses the root cause"}),groundedOnCorePrincipleIds:h.Array(h.String({minLength:1}),{description:"Subset of T-01..T-10. Validated against registry \u2014 fabricated IDs cause validation failure."}),scope:DGt,confidence:h.Number({minimum:0,maximum:1}),ambiguityNotes:h.Optional(h.Array(h.String()))}),C1=class{async validate(t,r){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if((typeof o.taskId!="string"||o.taskId!==r)&&n.push(`taskId mismatch: expected ${r}, got ${String(o.taskId)}`),!Ar.Check(ch,t)){let a=[...Ar.Errors(ch,t)].map(s=>`${s.path}: ${s.message}`);n.push(...a)}if(Array.isArray(o.groundedOnCorePrincipleIds))for(let i of o.groundedOnCorePrincipleIds)typeof i=="string"&&!GT(i)&&n.push(`Fabricated axiom ID ${i} not in core principle registry`);return n.length>0?{valid:!1,errors:n,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};function UGt(e={}){let t=e.adapter??new ed,r=e.schema??ch,{outputLanguage:n,coreGrounding:o}=e,i=t.generateExample(r),a=t.generateConstraints(r),s=t0(n);return`You are a principle distiller. Your job is to abstract a specific root cause into a general, cross-scenario principle.
|
|
881
|
+
[OUTPUT FORMAT section is REQUIRED; other sections may be summarized if needed]`;f.diagnosticInstruction=R,f.truncationWarnings=[...c,`diagnosticInstruction truncated due to size (${g.length} > ${n.maxMessageChars})`],g=JSON.stringify(f)}return{message:g,promptInput:f}}};gc();var Zg=["core","quiet","gone","legacy_retire"],BT=["openclaw","pi-ai"],_u=["diagnostician","dreamer","philosopher","scribe","artificer","evaluator","rolloutReviewer","correctionObserver","empathyObserver","signalCollector"],Fv=["simple","advanced"],Jz=["low","medium","high"],Hz=["realtime","async"],KT=["smoke","unit","full"],k1=["full","summary","off"],Qa=new Set(["__proto__","constructor","prototype"]);var Vz=[{id:"prompt",category:"core",enabled:!0,since:"2026-05-24",description:"Prompt injection for principle application"},{id:"code_tool_hook",category:"core",enabled:!0,since:"2026-05-24",description:"Code tool hook for rule host enforcement"},{id:"defer_archive",category:"core",enabled:!0,since:"2026-05-24",description:"Defer/archive activation writer"},{id:"correction_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Optional LLM optimization service for correction keywords; synchronous correction detection remains active independently"},{id:"signal_collector",category:"quiet",enabled:!1,since:"2026-06-30",description:"Unified signal collection host (correction + empathy upstream merge). NOTE: keyword detection (high-precision phrases) runs regardless of this flag; this flag only gates the LLM deep-judgment path (ambiguous terms / missed keywords). Quiet flag: dogfood-only until validated."},{id:"internalization_auto_consumer",category:"quiet",enabled:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381; quiet flag, default on, disableable via config)"},{id:"story_a_approval_completion",category:"quiet",enabled:!0,since:"2026-06-18",description:"Story A approval-completion orchestrator (PRI-408) \u2014 formal service replacing demo direct-writer activation; quiet flag, default on, disableable via config"},{id:"feedback_channel",category:"quiet",enabled:!0,since:"2026-06-01",description:"MVP seed feedback channel \u2014 privacy-preserving report drafts"},{id:"gfi",category:"quiet",enabled:!1,since:"2026-05-24",description:"Global Friction Index session scoring"},{id:"evolution_worker",category:"quiet",enabled:!1,since:"2026-06-01",description:"Legacy evolution worker heartbeat (MVP-Quiet per ADR-0014 \xA72.5)"},{id:"empathy_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking (MVP-Quiet)"},{id:"painEvidenceAdmission",category:"quiet",enabled:!0,since:"2026-06-06",description:"Pre-diagnosis evidence triage for pain signals (PEAT-B1). PRI-454: default-on, Gate B is primary gate."},{id:"pain_evidence_admission",category:"quiet",enabled:!0,since:"2026-06-15",description:"Snake-case alias for painEvidenceAdmission \u2014 same functionality, matches config.yaml key convention. PRI-454: default-on."},{id:"painEvidenceAdmissionDefault",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Global kill switch for Gate B migration. When ON (default), Gate B (TriggerController) owns admission. When OFF (rollback), Gate A (PainDiagnosticGate) is re-activated."},{id:"pain_evidence_admission_default",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Snake-case alias for painEvidenceAdmissionDefault \u2014 global kill switch, matches config.yaml key convention"},{id:"diagnostician_async_cli",category:"quiet",enabled:!1,since:"2026-06-11",description:"Async pain-record CLI \u2014 submit and return immediately, diagnosis runs in background. Default: false until orchestrator exists."},{id:"diagnostician_core_grounding",category:"quiet",enabled:!0,since:"2026-06-11",description:"Core principle grounding in diagnostician prompt (Arm 2)"},{id:"internalization_core_grounding",category:"quiet",enabled:!0,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders (dreamer, philosopher, scribe)"},{id:"diagnostician_split_pipeline",category:"quiet",enabled:!0,since:"2026-06-11",description:"3-stage split diagnostician pipeline (RootCause\u2192Distiller\u2192Router)"},{id:"diagnostician_llm_degradation",category:"quiet",enabled:!1,since:"2026-07-03",description:"Diagnostician LLM rate-limit graceful degradation \u2014 on persistent rate-limit, emit diag_llm_rate_limit_degraded telemetry + rate_limit errorCategory instead of max_attempts_exceeded (ADR-0019). Default off; flag-off = hard fail (legacy behavior)."},{id:"l2_dreamer",category:"quiet",enabled:!1,since:"2026-06-16",description:"L2 multi-turn agent loop for the dreamer runner (PRI-419) \u2014 read-only tools + submit_output, scoped to dreamer only"},{id:"code_rule_capability",category:"core",enabled:!0,since:"2026-06-18",description:"Code-rule capability (atomic: ArtificerL2 + Evaluator) for RuleHost pipeline \u2014 MVP-Core, default ON (PRI-435)"},{id:"intent_engineering",category:"quiet",enabled:!1,since:"2026-06-25",description:"INTENT.md-grounded constructive friction and Stage-A intent tension diagnosis (PRI-465). Default off; flag-off = no INTENT read, no prompt injection, no intentTension."},{id:"rulecode_context_v2",category:"quiet",enabled:!1,since:"2026-06-27",description:"RuleContext v2 \u2014 rule-code context vision (PRI-479). Foundation flag; default off, v1 rule behavior unchanged. See docs/superpowers/specs/2026-06-27-rulecode-context-vision-design.md"},{id:"failed_tasks_observability",category:"quiet",enabled:!0,since:"2026-07-04",description:"Failed tasks observability \u2014 list/view failed pipeline tasks"},{id:"evaluator_artificer_repair_loop",category:"quiet",enabled:!1,since:"2026-07-04",description:"PRI-509: Evaluator\u2192Artificer repair loop \u2014 auto-seed artificer repair task on needs_revision. Default off; flag-off = current behavior (no repair task seeded)."},{id:"nocturnal",category:"gone",enabled:!1,since:"2026-05-24",description:"Nocturnal trinity pipeline (retired)"},{id:"idle_trigger",category:"gone",enabled:!1,since:"2026-05-24",description:"Idle trigger for background processing (retired)"},{id:"new_user_onboarding",category:"core",enabled:!0,since:"2026-07-01",description:"New user onboarding wizard \u2014 first-visit redirect to /welcome + demo story-a trigger endpoint. Maintainer-approved MVP-Core (2026-07-01): default-on; emergency disable via .pd/config.yaml: new_user_onboarding: { enabled: false }."}];var n0={};for(let e of Vz)n0[e.id]={category:e.category,enabled:e.enabled};var gGt="pd.default",yGt={type:"pi-ai",provider:"",model:"",apiKeyEnv:""},dOe="openclaw.default",mOe={type:"openclaw",source:"default"},r0=dOe,Xz=mOe,_Gt={diagnostician:!0,dreamer:!0,philosopher:!1,scribe:!0,artificer:!0,evaluator:!1,rolloutReviewer:!1,correctionObserver:!1,empathyObserver:!1,signalCollector:!1};function T1(){let e={};for(let t of _u)e[t]={enabled:_Gt[t],runtimeProfile:r0};return{defaultRuntime:r0,agents:e}}var I1={diagnostics:{mode:"simple"}},Zu={thinkingOs:!1,projectFocus:"off",evolutionContext:{enabled:!0,maxMessages:4,maxCharsPerMessage:200}};function Yz(){return{version:1,features:{...n0},runtimeProfiles:{[gGt]:{...yGt},[dOe]:{...mOe}},internalAgents:T1(),ui:{...I1},principles:{outputLanguage:void 0},contextInjection:void 0}}var hQ=["prompt","code_tool_hook","defer_archive"];function Kc(e){let{config:t}=e,r=[],n={};for(let[i,a]of Object.entries(n0))n[i]={id:i,category:a.category,enabled:a.enabled};for(let[i,a]of Object.entries(t.features))if(!Qa.has(i)&&a)if(Object.hasOwn(n,i)){let s=n[i];if(!s)continue;if(s.category==="gone"&&a.enabled){r.push(`feature '${i}': gone flag cannot be re-enabled`);continue}if(s.category==="core"&&!a.enabled){r.push(`feature '${i}': core flag explicitly disabled via config (emergency disable)`),n[i]={id:i,category:s.category,enabled:!1};continue}n[i]={id:i,category:a.category,enabled:a.enabled}}else{if(!Zg.includes(a.category)){r.push(`feature '${i}': invalid category '${a.category}', ignored`);continue}n[i]={id:i,category:a.category,enabled:a.enabled},r.push(`feature '${i}': unknown flag accepted`)}let o=[];for(let i of hQ){let a=n[i];a&&a.enabled&&o.push(i)}return{flags:n,enabledChannels:o,warnings:r}}function td(e,t){return Object.hasOwn(e.flags,t)?e.flags[t]?.enabled??!1:!1}var Zz="<redacted-path>",oh="[REDACTED]";var xGt=/(?:[A-Za-z]:[\\/](?:[^\\\s/:*?"<>|]+[\\/])+[^\\\s/:*?"<>|]*)/g,bGt=/(?<![a-zA-Z0-9_.])[\\/](?:usr|home|Users|var|opt|etc|tmp|root|run|mnt|media|srv|boot|dev|proc|sys)(?:[\\/][^\\\s/:*?"<>|]+)+/g;function ih(e){return typeof e!="string"?e:e.replace(xGt,Zz).replace(bGt,Zz)}var vGt=/\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}\b/g,SGt=/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/g,wGt=/\blin_api_[A-Za-z0-9_-]{16,}\b/g,kGt=/(Authorization\s*:\s*)(["'])?([A-Za-z]+\s+)?([^\s"';,]+)/gi,TGt=/(\$env:\s*[A-Z_][A-Z0-9_]{2,}\s*=\s*")([^"]*)(")/gi,IGt=/\b(api[_-]?key|token|secret|password|auth(?:_?token)?)\s*[:=]\s*['"]?([^\s'",}{]+)['"]?/gi,EGt=/\bBearer\s+[A-Za-z0-9._\-+/=]{8,}\b/g;function ah(e){return typeof e!="string"?e:e.replace(vGt,oh).replace(SGt,oh).replace(wGt,oh).replace(kGt,"$1$2$3[REDACTED]").replace(TGt,"$1[REDACTED]$3").replace(EGt,oh).replace(IGt,(t,r)=>`${r}=${oh}`)}var RGt=/\b([A-Z_][A-Z0-9_]{2,})\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s,;}{]+))/g;function sh(e){return typeof e!="string"?e:e.replace(RGt,(t,r)=>`${r}=${oh}`)}function Qg(e){if(typeof e!="string")return e;let t=ih(e);return t=ah(t),t=sh(t),t}var CGt=new Set(["password","passwd","secret","token","api","apikey","authorization","auth","credential","credentials","private","key"]);function AGt(e){return e.toLowerCase().split(/[_\-.]/g).filter(t=>t.length>0)}function fOe(e){let t=AGt(e);if(t.length===0)return!1;for(let r of t)if(CGt.has(r))return!0;return!1}var OGt=6,hOe=100,gQ=2e3;function Qz(e,t){if(e===null)return{ok:!0,value:null,notes:[]};if(e===void 0)return{ok:!0,value:void 0,notes:[]};let r=typeof e;if(r==="string"){let o=e,i=o;return o=ih(o),o=ah(o),o=sh(o),o!==i&&t.notes.push("string value redacted (path/token/env)"),o.length>gQ&&(o=o.slice(0,gQ)+"\u2026",t.notes.push(`string truncated to ${gQ} chars`)),{ok:!0,value:o,notes:t.notes}}if(r==="bigint")return{ok:!0,value:`<bigint:${e.toString()}>`,notes:[]};if(r!=="object")return{ok:!0,value:e,notes:[]};if(t.depth>=OGt)return{ok:!0,value:"<deep>",notes:[]};let n=e;if(t.seen.has(n))return t.notes.push("circular reference detected"),{ok:!0,value:"<circular>",notes:[]};t.seen.add(n);try{if(Array.isArray(e)){let s=[];for(let c=0;c<e.length;c++){let u=Qz(e[c],{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!u.ok)return u;s.push(u.value)}return{ok:!0,value:s,notes:[]}}let o=e,i={},a=Object.keys(o).slice(0,hOe);for(let s of a){if(fOe(s)){i[s]=oh,t.notes.push(`field "${s}" redacted`);continue}let c=o[s];if(c!==null&&typeof c=="object"&&t.seen.has(c)){t.notes.push(`circular reference detected at "${s}"`),i[s]="<circular>";continue}let u=Qz(c,{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!u.ok)return u;i[s]=u.value}return{ok:!0,value:i,notes:[]}}finally{t.seen.delete(n)}}function PGt(e){let t=[],r=[],n={seen:new WeakSet,depth:0,notes:t};n.seen.add(e);for(let o=0;o<e.length;o++){let i=e[o];if(i!==null&&typeof i=="object"&&n.seen.has(i)){t.push("circular reference detected in array"),r.push("<circular>");continue}let a=Qz(i,n);if(!a.ok)return a;r.push(a.value)}return{ok:!0,value:r,notes:t}}function NGt(e){let t=e,r=[],n={seen:new WeakSet,depth:0,notes:r};n.seen.add(e);let o={},i=Object.keys(t).slice(0,hOe);for(let a of i){if(fOe(a)){o[a]=oh,r.push(`field "${a}" redacted`);continue}let s=t[a];if(s!==null&&typeof s=="object"&&n.seen.has(s)){r.push(`circular reference detected at "${a}"`),o[a]="<circular>";continue}let c=Qz(s,n);if(!c.ok)return c;o[a]=c.value}return{ok:!0,value:o,notes:r}}function E1(e){if(e===null)return{ok:!1,error:"redactSensitiveFields: null is not a redactable object",nextAction:"pass a JSON object or array; null carries no fields to redact"};if(e===void 0)return{ok:!1,error:"redactSensitiveFields: undefined is not a redactable object",nextAction:"pass a JSON object or array; undefined carries no fields to redact"};let t=typeof e;return t!=="object"?{ok:!1,error:`redactSensitiveFields: top-level value must be an object or array (got ${t})`,nextAction:"pass a JSON object or array; for primitive values use redactTokenLikeValues / redactEnvLikeValues / redactAbsolutePaths"}:Array.isArray(e)?PGt(e):NGt(e)}var yQ={pollIntervalMs:5e3,timeoutMs:3e5,defaultMaxAttempts:3,agentId:"peer-runner",coreGrounding:!0};function $Gt(e,t){return{pollIntervalMs:e.pollIntervalMs??yQ.pollIntervalMs,timeoutMs:e.timeoutMs??yQ.timeoutMs,defaultMaxAttempts:e.defaultMaxAttempts??yQ.defaultMaxAttempts,owner:e.owner,runtimeKind:e.runtimeKind,agentId:e.agentId??t,outputLanguage:e.outputLanguage,coreGrounding:e.coreGrounding??!0}}function MGt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function LGt(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!MGt(t)||!Object.hasOwn(t,"sourcePainId"))return null;let{sourcePainId:r}=t;return typeof r!="string"||r.length===0?null:r}var ws=class{stateManager;runtimeAdapter;eventEmitter;artifactStore;resolvedOptions;config;pendingAgentDraftStore;phase=xc.Idle;constructor(t,r,n){this.stateManager=t.stateManager,this.runtimeAdapter=t.runtimeAdapter,this.eventEmitter=t.eventEmitter,this.artifactStore=t.artifactStore,this.pendingAgentDraftStore=t.pendingAgentDraftStore,this.config=n,this.resolvedOptions=$Gt(r,n.defaultAgentId)}get currentPhase(){return this.phase}getRuntimeKind(){return typeof this.runtimeAdapter.kind=="function"?this.runtimeAdapter.kind():this.resolvedOptions.runtimeKind}emitSuccessTelemetry(t,r,n){}checkLineageIntegrity(t,r,n){}postFetchTransform(t,r,n){typeof r=="object"&&r!==null&&!Array.isArray(r)&&Reflect.set(r,"generatedAt",new Date().toISOString())}async run(t){this.phase=xc.Idle;let r=this.getRuntimeKind(),n;try{n=await this.stateManager.acquireLease({taskId:t,owner:this.resolvedOptions.owner,runtimeKind:r})}catch(o){return await this.handleLeaseOrPhaseError(t,o)}if(n.taskKind!==this.config.expectedTaskKind)return this.emitEvent("wrong_task_kind",t,{expectedKind:this.config.expectedTaskKind,actualKind:n.taskKind}),await this.stateManager.markTaskFailed(t,"input_invalid"),{status:"failed",taskId:t,errorCategory:"input_invalid",failureReason:`Task kind must be '${this.config.expectedTaskKind}', got '${n.taskKind}'`,attemptCount:n.attemptCount};this.emitEvent("task_leased",t,{taskKind:this.config.expectedTaskKind,attemptCount:n.attemptCount});try{let o=await this.resolveStoreRunId(t);this.phase=xc.BuildingContext;let i=await this.buildContext(t);this.emitEvent("context_built",t,{contextHash:i.contextHash}),this.phase=xc.Invoking;let a=await this.invokeRuntime(t,i);this.emitEvent("run_started",t,{runtimeKind:r}),this.phase=xc.Polling;let s=await this.pollUntilTerminal(a);if(s.status!=="succeeded")return await this.handleRuntimeFailure(t,n,s);this.phase=xc.FetchingOutput;let c=await this.fetchAndParseOutput(a.runId,t);this.postFetchTransform(t,c,i),this.phase=xc.Validating;let u=await this.validateOutput(c,t,i);if(!u.valid)return await this.handleValidationError({taskId:t,task:n,errors:u.errors,errorCategory:u.errorCategory});let l=c;this.emitEvent("output_validated",t,{}),this.checkLineageIntegrity(t,l,i),this.emitSuccessTelemetry(t,l,i);let d=await this.succeedTask(t,o,l,n,i.contextHash,i);return d.status==="succeeded"&&(this.phase=xc.Completed),d}catch(o){return await this.handlePostLeaseError(t,n,o)}}emitEvent(t,r,n){this.eventEmitter.emitTelemetry({eventType:`${this.config.runnerName}_${t}`,traceId:r,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:n})}async pollUntilTerminal(t){let r=Date.now()+this.resolvedOptions.timeoutMs,n=["succeeded","failed","timed_out","cancelled"];for(;Date.now()<r;){let a=await this.runtimeAdapter.pollRun(t.runId);if(n.includes(a.status))return a;await this.sleep(this.resolvedOptions.pollIntervalMs)}try{let a=await this.runtimeAdapter.pollRun(t.runId);if(n.includes(a.status))return a}catch{}let o=!1;try{await this.runtimeAdapter.cancelRun(t.runId)}catch(a){o=!0,this.emitEvent("cancel_run_failed",t.runId,{runId:t.runId,errorMessage:a instanceof Error?a.message:String(a)})}let i=o?" (cancelRun also failed)":"";throw new Je("timeout",`Run ${t.runId} timed out after ${this.resolvedOptions.timeoutMs}ms${i}`)}async fetchAndParseOutput(t,r){let n;try{n=await this.runtimeAdapter.fetchOutput(t)}catch(i){throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"fetchOutput",errorMessage:i instanceof Error?i.message:String(i)}),i}if(!n||!n.payload)throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"payload_missing",errorMessage:`No output available for run ${t}`}),new Je("output_invalid",`No output available for run ${t}`);let{payload:o}=n;if(typeof o!="object"||o===null)throw this.emitEvent("output_extraction_failed",r,{runId:t,stage:"payload_not_object",errorMessage:`Output payload is not an object for run ${t}`}),new Je("output_invalid",`Output payload is not an object for run ${t}`);return o}async resolveLineageArtifactIds(t){let{hydratePITaskRecord:r}=await Promise.resolve().then(()=>(yc(),LAe)),n=await this.stateManager.getTask(t);if(!n)return{ids:[],hasRejected:!1};let i=r(n)?.dependencyTaskIds??[];if(i.length===0)return{ids:[],hasRejected:!1};let a=[],s=!1,c=await Promise.allSettled(i.map(u=>this.artifactStore.listBySourceTaskId(u)));for(let u of c)if(u.status==="fulfilled")for(let l of u.value)a.push(l.artifactId);else s=!0;return{ids:a,hasRejected:s}}async resolveStoreRunId(t){let{runs:r,degradedRuns:n}=await this.stateManager.getValidRunsByTaskTolerant(t);n.length>0&&this.eventEmitter.emitTelemetry({eventType:"degradation_triggered",traceId:t,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:{component:"BasePeerRunner",runnerName:this.config.runnerName,trigger:"malformed_historical_run_rows",degradedCount:n.length,runIds:n.map(i=>i.runId),errors:n.map(i=>i.error),nextAction:"Quarantine malformed run rows: pd runtime internalization integrity-repair --confirm"}});let o=r[r.length-1];if(!o)throw new Je("execution_failed",`No valid run records found for task ${t} after lease acquisition. If historical runs are malformed, quarantine them first: pd runtime internalization integrity-repair --confirm`);return o.runId}static hashContextRefs(t){if(t.length===0)return"empty";let r=t.join("|"),n=0;for(let o=0;o<r.length;o++)n=Math.imul(31,n)+r.charCodeAt(o)|0;return`ctx-${Math.abs(n).toString(16)}`}async handleLeaseOrPhaseError(t,r){let n=this.classifyError(r);if(n.category==="lease_conflict")return this.emitEvent("run_failed",t,{errorCategory:"lease_conflict",errorMessage:n.message}),{status:"failed",taskId:t,errorCategory:"lease_conflict",failureReason:n.message,attemptCount:1};this.emitEvent("run_failed",t,{errorCategory:n.category,errorMessage:n.message});let o={taskId:t,taskKind:this.config.expectedTaskKind,status:"leased",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),attemptCount:1,maxAttempts:this.resolvedOptions.defaultMaxAttempts};return this.retryOrFail({taskId:t,task:o,errorCategory:n.category,failureReason:n.message})}async handlePostLeaseError(t,r,n){let o=this.classifyError(n);return this.emitEvent("run_failed",t,{errorCategory:o.category,errorMessage:o.message}),this.retryOrFail({taskId:t,task:r,errorCategory:o.category,failureReason:o.message})}async handleRuntimeFailure(t,r,n){let o=this.mapRunStatusToErrorCategory(n.status,n.reason);return this.emitEvent("run_failed",t,{runStatus:n.status,errorCategory:o}),this.retryOrFail({taskId:t,task:r,errorCategory:o,failureReason:n.reason?`Runtime execution ended with status: ${n.status}. Reason: ${n.reason}`:`Runtime execution ended with status: ${n.status}`})}async handleValidationError(t){let r=t.errorCategory??"output_invalid";return this.emitEvent("output_invalid",t.taskId,{errorCount:t.errors.length,errorCategory:r}),this.retryOrFail({taskId:t.taskId,task:t.task,errorCategory:r,failureReason:`Validation failed: ${t.errors.join("; ")}`})}async retryOrFail(t){if(this.permanentErrorCategories.has(t.errorCategory)){try{await this.stateManager.markTaskFailed(t.taskId,t.errorCategory,t.failureReason)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount,failureReason:t.failureReason}),this.phase=xc.Failed,this.injectAgentDraftOnPermanentFailure(t),{status:"failed",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}if(t.errorCategory==="rate_limit"&&this.isDegradationEnabled()){try{await this.stateManager.markTaskFailed(t.taskId,"rate_limit",`LLM rate limit degraded: ${t.failureReason}`)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("diag_llm_rate_limit_degraded",t.taskId,{errorCategory:"rate_limit",attemptCount:t.task.attemptCount,failureReason:t.failureReason,nextAction:"Retry diagnosis manually with `pd pain retry` when rate limit clears, or enable fallback provider."}),this.phase=xc.Failed,{status:"failed",taskId:t.taskId,errorCategory:"rate_limit",failureReason:`LLM rate limit degraded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}if(this.stateManager.getRetryPolicy().shouldRetry(t.task)){try{await this.stateManager.markTaskRetryWait(t.taskId,t.errorCategory,t.failureReason)}catch(n){return this.emitEvent("mark_retry_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_retried",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount}),this.phase=xc.RetryWaiting,{status:"retried",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}try{await this.stateManager.markTaskFailed(t.taskId,"max_attempts_exceeded",`Max attempts exceeded: ${t.failureReason}`)}catch(n){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:n instanceof Error?n.message:String(n)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:"max_attempts_exceeded",attemptCount:t.task.attemptCount,failureReason:`Max attempts exceeded: ${t.failureReason}`}),this.phase=xc.Failed,{status:"failed",taskId:t.taskId,errorCategory:"max_attempts_exceeded",failureReason:`Max attempts exceeded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}classifyError(t){return t instanceof Je?{category:t.category,message:t.message}:t instanceof Error?{category:"execution_failed",message:t.message}:{category:"execution_failed",message:String(t)}}mapRunStatusToErrorCategory(t,r){switch(t){case"failed":return"execution_failed";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return"execution_failed"}}sleep(t){return new Promise(r=>setTimeout(r,t))}isDegradationEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let r=Kc(t);return td(r,"diagnostician_llm_degradation")}injectAgentDraftOnPermanentFailure(t){if(!this.pendingAgentDraftStore)return;let{taskKind:r}=t.task,{errorCategory:n}=t,o=t.failureReason,i=sh(ih(ah(o))),a={summary:`${r} failed with category=${n} at ${new Date().toISOString()}`,observedFailure:i},s=LGt(t.task.diagnosticJson);try{let c=this.pendingAgentDraftStore.insertPendingDraft({taskId:t.taskId,painId:s??void 0,agentDraft:a});if(!c.ok){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,errorMessage:c.error,nextAction:"Inspect pending_agent_drafts table integrity; draft will be retried on next permanent failure of the same taskId (idempotent UPDATE)."});return}this.emitEvent("agent_draft_inserted",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,draftId:c.id,painIdLinked:s!==null})}catch(c){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:n,attemptCount:t.task.attemptCount,errorMessage:c instanceof Error?c.message:String(c),nextAction:"PendingAgentDraftStore.insertPendingDraft threw unexpectedly; inspect the store implementation."})}}};var R1=class extends ws{validator;contextAssembler;effectiveConfig;intentDocReader;constructor(t,r){super(t,r,{runnerName:"diag_rootcause",expectedTaskKind:"diag_rootcause",defaultAgentId:"main",resultRefPrefix:"diag-rootcause",effectiveConfig:r.effectiveConfig}),this.validator=t.validator,this.contextAssembler=t.contextAssembler,this.effectiveConfig=r.effectiveConfig,this.intentDocReader=t.intentDocReader}get permanentErrorCategories(){return new Set(["storage_unavailable","workspace_invalid","capability_missing","cancelled","input_invalid"])}async buildContext(t){let r=await this.stateManager.getTask(t);if(!r)throw new Je("input_invalid",`Task ${t} not found`);let n=r.inputRef||t,o=await this.contextAssembler.assemble(n),a=Ji(r)?.dependencyTaskIds??[],s=[...o.sourceRefs];if(a.length>0){let u=await Promise.allSettled(a.map(l=>this.stateManager.getTask(l)));for(let l=0;l<u.length;l++){let d=u[l],p=a[l];if(!(!d||p===void 0)&&d.status==="fulfilled"&&d.value){d.value.resultRef&&s.push(d.value.resultRef);let m=d.value?Ji(d.value):null;m?.outputArtifactRefs&&s.push(...m.outputArtifactRefs.map(f=>f.ref))}}}return{contextHash:ws.hashContextRefs(s),contextRefs:s,painPayload:o}}async invokeRuntime(t,r){let n=!1,o=!1;if(this.effectiveConfig){let c=Kc(this.effectiveConfig);n=td(c,"diagnostician_core_grounding"),o=td(c,"intent_engineering")}let i;if(o&&!this.intentDocReader)o=!1;else if(o&&this.intentDocReader){let c=this.intentDocReader.readIntentDoc();c.ok&&c.doc?i={raw:c.doc.raw,contentHash:c.doc.contentHash,path:c.doc.path}:(this.emitEvent("intent_doc_read_failed",t,{reason:c.reason??"unknown",nextAction:c.nextAction??"Check INTENT.md configuration.",flagEnabled:c.flagEnabled,found:c.found}),o=!1)}let a=new Kz,{message:s}=a.buildPrompt(r.painPayload,{outputLanguage:this.resolvedOptions.outputLanguage,coreGrounding:n,intentGrounding:o,intentDoc:i});return this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:s,contextItems:[],outputSchemaRef:"diag-rootcause-output-v1",timeoutMs:this.resolvedOptions.timeoutMs})}async validateOutput(t,r,n){let o=await this.validator.validate(t,r);return{valid:o.valid,errors:o.errors,errorCategory:o.errorCategory}}async succeedTask(t,r,n,o,i,a){try{await this.stateManager.updateRunOutput(r,JSON.stringify(n))}catch(p){throw this.emitEvent("update_output_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)}),p}let s=[],c=!1;try{let p=await this.resolveLineageArtifactIds(t);s=p.ids,c=p.hasRejected}catch(p){this.emitEvent("lineage_resolve_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)})}c&&this.emitEvent("lineage_partial",t,{runId:r,resolvedCount:s.length,warning:"Some dependency artifact queries were rejected; lineage may be incomplete"});let u=`pi-art-${t}-${r}`,l=new Date().toISOString();try{await this.artifactStore.upsertArtifact({artifactId:u,artifactKind:"principle",sourceTaskId:t,lineageArtifactIds:s,validationStatus:"pending",contentJson:JSON.stringify(n),createdAt:l,updatedAt:l})}catch(p){return this.emitEvent("artifact_write_failed",t,{runId:r,errorMessage:p instanceof Error?p.message:String(p)}),this.retryOrFail({taskId:t,task:o,errorCategory:"artifact_commit_failed",failureReason:`PIArtifact write failed: ${p instanceof Error?p.message:String(p)}`})}let d=`${this.config.resultRefPrefix}://${r}`;try{await this.stateManager.markTaskSucceeded(t,d)}catch(p){throw this.emitEvent("mark_succeeded_failed",t,{taskId:t,runId:r,errorMessage:p instanceof Error?p.message:String(p)}),p}return this.emitEvent("task_succeeded",t,{attemptCount:o.attemptCount,resultRef:d,rootCauseCategory:n.rootCauseCategory,causalChainDepth:n.causalChain.length}),{status:"succeeded",taskId:t,runId:r,artifactId:u,resultRef:d,contextHash:i,output:n,attemptCount:o.attemptCount}}postFetchTransform(t,r){jl(r,"taskId",t)}emitSuccessTelemetry(t,r,n){this.emitEvent("rootcause_completed",t,{rootCauseCategory:r.rootCauseCategory,causalChainDepth:r.causalChain.length})}};yc();var DGt=h.Union([h.Literal("general"),h.Literal("domain"),h.Literal("scenario")]),ch=h.Object({valid:h.Boolean(),taskId:h.String({minLength:1}),sourceRootCauseArtifactId:h.String({minLength:1,description:"Lineage consistency check \u2014 must match the artifact ID from Stage A"}),abstractedPrinciple:h.String({minLength:1,maxLength:200,description:"Highly abstracted, cross-scenario principle (\u2264200 chars)"}),rationale:h.String({minLength:1,description:"Why this principle addresses the root cause"}),groundedOnCorePrincipleIds:h.Array(h.String({minLength:1}),{description:"Subset of T-01..T-10. Validated against registry \u2014 fabricated IDs cause validation failure."}),scope:DGt,confidence:h.Number({minimum:0,maximum:1}),ambiguityNotes:h.Optional(h.Array(h.String()))}),C1=class{async validate(t,r){let n=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if((typeof o.taskId!="string"||o.taskId!==r)&&n.push(`taskId mismatch: expected ${r}, got ${String(o.taskId)}`),!Ar.Check(ch,t)){let a=[...Ar.Errors(ch,t)].map(s=>`${s.path}: ${s.message}`);n.push(...a)}if(Array.isArray(o.groundedOnCorePrincipleIds))for(let i of o.groundedOnCorePrincipleIds)typeof i=="string"&&!GT(i)&&n.push(`Fabricated axiom ID ${i} not in core principle registry`);return n.length>0?{valid:!1,errors:n,errorCategory:"output_invalid"}:{valid:!0,errors:[]}}};function UGt(e={}){let t=e.adapter??new ed,r=e.schema??ch,{outputLanguage:n,coreGrounding:o}=e,i=t.generateExample(r),a=t.generateConstraints(r),s=t0(n);return`You are a principle distiller. Your job is to abstract a specific root cause into a general, cross-scenario principle.
|
|
882
882
|
|
|
883
883
|
INPUT:
|
|
884
884
|
You will receive the Stage A root cause output as structured data. This contains:
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
|
-
"version": "1.197.
|
|
5
|
+
"version": "1.197.5",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onCapabilities": [
|
|
8
8
|
"hook"
|
package/openclaw.plugin.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
|
-
"version": "1.197.
|
|
5
|
+
"version": "1.197.5",
|
|
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.197.
|
|
3
|
+
"version": "1.197.5",
|
|
4
4
|
"description": "Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles. Stop correcting the same AI behavior across sessions.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|