principles-disciple 1.197.11 → 1.197.12

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 CHANGED
@@ -1053,7 +1053,7 @@ ${a}${s}`}buildPrompt(t,r={}){let{outputLanguage:o}=r,n=this.buildRouterInstruct
1053
1053
  apiKeyEnv: ANTHROPIC_AUTH_TOKEN
1054
1054
  baseUrl: https://token-plan-cn.xiaomimimo.com/v1
1055
1055
 
1056
- If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-cli`)}}function cQ(e,t){let r=oQ(e,"diagnostician");if(!r.ok)return{ok:!1,reason:r.readiness,message:r.reason,nextAction:r.nextAction};let o=nQ(r.profile,t);if(o.readiness!=="ready")return{ok:!1,reason:o.readiness,message:o.reason??`Agent runtime profile '${r.profileId}' is not ready`,nextAction:o.nextAction??"Check .pd/config.yaml runtime profile configuration"};let n=iQ(r.profile,"");if(n.runtimeKind==="pi-ai")return{runtimeKind:"pi-ai",provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,baseUrl:n.baseUrl,timeoutMs:n.timeoutMs??mk,maxRetries:n.maxRetries,agentId:"main",...n.systemPrompt?{systemPrompt:n.systemPrompt}:{}};let i={runtimeKind:"openclaw-cli",timeoutMs:mk,agentId:"main"};return n.openclawMode!=="default"&&(i.openclawMode=n.openclawMode),i}var zMt=new Map,aQ=class{async run(t){return{status:"failed",taskId:t,errorCategory:"capability_missing",failureReason:"Diagnostician pipeline is disabled by feature flag (diagnostician_split_pipeline=false)",attemptCount:1}}};async function uQ(e){let t;if(e.effectiveConfig){let v=e.getEnvVar??(E=>process.env[E]);t=cQ(e.effectiveConfig,v)}else t=UMt(e.stateDir);if(sQ(t))throw new Error(`[PainSignalRuntimeFactory] Config resolution failed: ${t.reason}. ${t.message}. nextAction: ${t.nextAction}`);FMt(t);let r=!0;if(e.effectiveConfig){let v=mp(e.effectiveConfig),E=Fm(v,"diagnostician_split_pipeline"),L=Fm(v,"diagnostician_async_cli");if(E&&!L){let H=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_split_pipeline")??!1,B=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_async_cli")??!1;if(H||B)throw new wt("input_invalid","diagnostician_split_pipeline requires diagnostician_async_cli=on (3 serial LLM calls would block the sync CLI 540s+)")}r=E}let o=`${e.workspaceDir}:${t.runtimeKind}:${t.openclawMode??""}:${r?"split":"disabled"}`,n=zMt.get(o);if(n)return n;let i=new Rx({workspaceDir:e.workspaceDir});await i.initialize();let a=new Tl(e.workspaceDir),s=new DC(a),c=new Y2(a),u=new MC(a),l=new LC(i.taskStore,u),m=new UC(i.taskStore,s,i.runStore,{sourceTraceLocator:l}),p=t.runtimeKind==="pi-ai"?new nm({provider:String(t.provider),model:String(t.model),apiKeyEnv:String(t.apiKeyEnv),maxRetries:t.maxRetries,timeoutMs:t.timeoutMs,baseUrl:t.baseUrl,workspace:e.workspaceDir,...t.systemPrompt?{systemPrompt:t.systemPrompt}:{}}):new Cx({runtimeMode:t.openclawMode??"default",workspaceDir:e.workspaceDir}),h=Cle(e.effectiveConfig?.config.principles?.outputLanguage),f=h.outputLanguage;h.degradationWarning&&ks.emitTelemetry({eventType:"degradation_triggered",traceId:`output-language-config-${Date.now()}`,timestamp:new Date().toISOString(),sessionId:"",payload:{component:"PainSignalRuntimeFactory",reason:"invalid_output_language_config",warning:h.degradationWarning,fallbackValue:h.outputLanguage}});let g;if(r){let v=new l$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new U2,contextAssembler:m,intentDocReader:e.intentDocReader},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),E=new m$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new d$},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),L=new f$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,committer:c},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f});g=new o$({rootCauseRunner:v,distillerRunner:E,routerRunner:L,stateManager:i,committer:c,perStageTimeoutMs:t.timeoutMs??mk})}else g=new aQ;let y=new W2({stateManager:i,ledgerAdapter:e.ledgerAdapter}),T=new X2({stateManager:i,runner:g,intakeService:y,ledgerAdapter:e.ledgerAdapter,autoIntakeEnabled:e.autoIntakeEnabled??!0,workspaceDir:e.workspaceDir});return zMt.set(o,T),T}var qMt=["deterministic","weak_heuristic","manual_only"];function zlo(e){return e.startsWith("candidate://")?e.slice(12):e}function Ulo(e,t){if(!qMt.includes(e.evaluability))throw new Error(`Invalid evaluability value: ${e.evaluability}. Must be one of: ${qMt.join(", ")}`);return{id:e.id,version:1,text:e.text,triggerPattern:e.triggerPattern??"",action:e.action??"",status:"candidate",evaluability:e.evaluability,priority:"P1",scope:"general",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[t],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:e.createdAt,updatedAt:e.createdAt}}var oT=class{#e;#t=new Map;constructor(t){this.#e=t.stateDir}writeProbationEntry(t){let r=zlo(t.sourceRef),o=this.#t.get(r);if(o)return o;let n=Ulo(t,r);return hR(this.#e,n),this.#t.set(r,t),t}existsForCandidate(t){let r=this.#t.get(t);if(r)return r;let o=xi(this.#e),n=Object.values(o.tree.principles).find(i=>i.derivedFromPainIds.includes(t));return n?{id:n.id,title:"",status:"probation",sourceRef:`candidate://${t}`,artifactRef:"",taskRef:"",text:n.text,triggerPattern:n.triggerPattern,action:n.action,evaluability:"weak_heuristic",createdAt:n.createdAt}:null}activatePrinciple(t){try{return $u(this.#e,t,{status:"active",updatedAt:new Date().toISOString()}),{ok:!0}}catch(r){return{ok:!1,reason:`ledger_activate_failed: ${r instanceof Error?r.message:String(r)}`}}}};import Blo from"better-sqlite3";import*as L5 from"fs";import*as fk from"path";function Klo(){return new Date().toISOString()}function Hlo(e){return e.slice(0,10)}function jMt(e){return e>=70?"severe":e>=40?"moderate":"mild"}function WMt(e,t){L5.mkdirSync(fk.dirname(e),{recursive:!0}),L5.appendFileSync(e,`${JSON.stringify(t)}
1056
+ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-cli`)}}function cQ(e,t){let r=oQ(e,"diagnostician");if(!r.ok)return{ok:!1,reason:r.readiness,message:r.reason,nextAction:r.nextAction};let o=nQ(r.profile,t);if(o.readiness!=="ready")return{ok:!1,reason:o.readiness,message:o.reason??`Agent runtime profile '${r.profileId}' is not ready`,nextAction:o.nextAction??"Check .pd/config.yaml runtime profile configuration"};let n=iQ(r.profile,"");if(n.runtimeKind==="pi-ai")return{runtimeKind:"pi-ai",provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,baseUrl:n.baseUrl,timeoutMs:n.timeoutMs??mk,maxRetries:n.maxRetries,agentId:"main",...n.systemPrompt?{systemPrompt:n.systemPrompt}:{}};let i={runtimeKind:"openclaw-cli",timeoutMs:mk,agentId:"main"};return n.openclawMode!=="default"&&(i.openclawMode=n.openclawMode),i}var zMt=new Map,aQ=class{async run(t){return{status:"failed",taskId:t,errorCategory:"capability_missing",failureReason:"Diagnostician pipeline is disabled by feature flag (diagnostician_split_pipeline=false)",attemptCount:1}}};async function uQ(e){let t;if(e.effectiveConfig){let v=e.getEnvVar??(E=>process.env[E]);t=cQ(e.effectiveConfig,v)}else t=UMt(e.stateDir);if(sQ(t))throw new Error(`[PainSignalRuntimeFactory] Config resolution failed: ${t.reason}. ${t.message}. nextAction: ${t.nextAction}`);FMt(t);let r=!0;if(e.effectiveConfig){let v=mp(e.effectiveConfig),E=Fm(v,"diagnostician_split_pipeline"),L=Fm(v,"diagnostician_async_cli");if(E&&!L){let H=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_split_pipeline")??!1,B=e.effectiveConfig.featuresChangedFromDefault?.includes("diagnostician_async_cli")??!1;if(H||B)throw new wt("input_invalid","diagnostician_split_pipeline requires diagnostician_async_cli=on (3 serial LLM calls would block the sync CLI 540s+)")}r=E}let o=`${e.workspaceDir}:${t.runtimeKind}:${t.openclawMode??""}:${r?"split":"disabled"}`,n=zMt.get(o);if(n)return n;let i=new Rx({workspaceDir:e.workspaceDir});await i.initialize();let a=new Tl(e.workspaceDir),s=new DC(a),c=new Y2(a),u=new MC(a),l=new LC(i.taskStore,u),m=new UC(i.taskStore,s,i.runStore,{sourceTraceLocator:l,trajectoryTurnReader:e.trajectoryTurnReader}),p=t.runtimeKind==="pi-ai"?new nm({provider:String(t.provider),model:String(t.model),apiKeyEnv:String(t.apiKeyEnv),maxRetries:t.maxRetries,timeoutMs:t.timeoutMs,baseUrl:t.baseUrl,workspace:e.workspaceDir,...t.systemPrompt?{systemPrompt:t.systemPrompt}:{}}):new Cx({runtimeMode:t.openclawMode??"default",workspaceDir:e.workspaceDir}),h=Cle(e.effectiveConfig?.config.principles?.outputLanguage),f=h.outputLanguage;h.degradationWarning&&ks.emitTelemetry({eventType:"degradation_triggered",traceId:`output-language-config-${Date.now()}`,timestamp:new Date().toISOString(),sessionId:"",payload:{component:"PainSignalRuntimeFactory",reason:"invalid_output_language_config",warning:h.degradationWarning,fallbackValue:h.outputLanguage}});let g;if(r){let v=new l$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new U2,contextAssembler:m,intentDocReader:e.intentDocReader},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),E=new m$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,validator:new d$},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f,effectiveConfig:e.effectiveConfig}),L=new f$({stateManager:i,runtimeAdapter:p,eventEmitter:ks,artifactStore:i.piArtifactStore,committer:c},{owner:e.owner??"pain-signal-bridge",runtimeKind:t.runtimeKind,outputLanguage:f});g=new o$({rootCauseRunner:v,distillerRunner:E,routerRunner:L,stateManager:i,committer:c,perStageTimeoutMs:t.timeoutMs??mk})}else g=new aQ;let y=new W2({stateManager:i,ledgerAdapter:e.ledgerAdapter}),T=new X2({stateManager:i,runner:g,intakeService:y,ledgerAdapter:e.ledgerAdapter,autoIntakeEnabled:e.autoIntakeEnabled??!0,workspaceDir:e.workspaceDir});return zMt.set(o,T),T}var qMt=["deterministic","weak_heuristic","manual_only"];function zlo(e){return e.startsWith("candidate://")?e.slice(12):e}function Ulo(e,t){if(!qMt.includes(e.evaluability))throw new Error(`Invalid evaluability value: ${e.evaluability}. Must be one of: ${qMt.join(", ")}`);return{id:e.id,version:1,text:e.text,triggerPattern:e.triggerPattern??"",action:e.action??"",status:"candidate",evaluability:e.evaluability,priority:"P1",scope:"general",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[t],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:e.createdAt,updatedAt:e.createdAt}}var oT=class{#e;#t=new Map;constructor(t){this.#e=t.stateDir}writeProbationEntry(t){let r=zlo(t.sourceRef),o=this.#t.get(r);if(o)return o;let n=Ulo(t,r);return hR(this.#e,n),this.#t.set(r,t),t}existsForCandidate(t){let r=this.#t.get(t);if(r)return r;let o=xi(this.#e),n=Object.values(o.tree.principles).find(i=>i.derivedFromPainIds.includes(t));return n?{id:n.id,title:"",status:"probation",sourceRef:`candidate://${t}`,artifactRef:"",taskRef:"",text:n.text,triggerPattern:n.triggerPattern,action:n.action,evaluability:"weak_heuristic",createdAt:n.createdAt}:null}activatePrinciple(t){try{return $u(this.#e,t,{status:"active",updatedAt:new Date().toISOString()}),{ok:!0}}catch(r){return{ok:!1,reason:`ledger_activate_failed: ${r instanceof Error?r.message:String(r)}`}}}};import Blo from"better-sqlite3";import*as L5 from"fs";import*as fk from"path";function Klo(){return new Date().toISOString()}function Hlo(e){return e.slice(0,10)}function jMt(e){return e>=70?"severe":e>=40?"moderate":"mild"}function WMt(e,t){L5.mkdirSync(fk.dirname(e),{recursive:!0}),L5.appendFileSync(e,`${JSON.stringify(t)}
1057
1057
  `,"utf8")}function Xlo(e){return e.prepare("PRAGMA table_info(sessions)").all().map(r=>r.name)}function Ylo(e){return Object.hasOwn(e,"name")}function Qlo(e){let t=[],r=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","exports_audit","evolution_tasks","evolution_events"];e.exec(`
1058
1058
  CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL);
1059
1059
  CREATE TABLE IF NOT EXISTS ingest_checkpoint (
@@ -1253,7 +1253,7 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
1253
1253
  UPDATE pain_events
1254
1254
  SET runtime_task_id = COALESCE(?, runtime_task_id)
1255
1255
  WHERE canonical_pain_id = ?
1256
- `).run(a??null,i);let h=c.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(i);return h&&typeof h=="object"&&Object.hasOwn(h,"id")&&typeof h.id=="number"?h.id:void 0}throw p}}finally{c.close()}}function pQ(e){let t=Klo(),r=[],o=e.data.score??80,n=e.data.sessionId??"cli",i=Hlo(t),a={warnings:r};try{let s=fk.join(e.stateDir,"logs",`events_${i}.jsonl`);WMt(s,{ts:t,date:i,type:"pain_signal",category:"detected",sessionId:n,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:o,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),severity:jMt(o),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){r.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=fk.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};WMt(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){r.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{a.trajectoryPainEventId=Zlo({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId})}catch(s){r.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function edo(e){if(e.errorCategory)return M2[e.errorCategory]??"runtime_unavailable";if(e.status==="failed"){if(e.candidateIds.length===0)return"candidate_missing";if(e.ledgerEntryIds.length===0)return"ledger_write_failed"}}function tdo(e){if(e instanceof wt&&e.category)return M2[e.category]??"runtime_unavailable";let t=e instanceof Error?e.message:String(e);return/api[_\s]?key|not found in env|missing required/i.test(t)?"config_missing":/timeout|timed[_\s]?out/i.test(t)?"runtime_timeout":/output.*invalid|validation.*fail/i.test(t)?"output_invalid":"runtime_unavailable"}var hk=class{opts;constructor(t){this.opts=t}async recordPain(t){let r=Date.now(),{painId:o}=t,n=t.taskId??H2(o),i={painId:o,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:n,traceId:t.traceId,provenance:t.provenance,evidence:t.evidence};try{if(this.opts.asyncMode){let m=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:!1,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader})).submitPainSignal(i),p=[];t.recordObservability!==!1&&(p=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:m.taskId}).warnings);let h=Date.now()-r;return{status:"submitted",painId:o,taskId:m.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:p,latencyMs:h,message:`Diagnosis submitted. Use 'pd task show ${m.taskId}' to check progress.`}}let s=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:this.opts.autoIntakeEnabled,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader})).onPainDetected(i),c=[];t.recordObservability!==!1&&(c=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:n}).warnings);let u=Date.now()-r;return{status:s.status,painId:s.painId,taskId:s.taskId,runId:s.runId,artifactId:s.artifactId,candidateIds:s.candidateIds,ledgerEntryIds:s.ledgerEntryIds,admissionResults:s.admissionResults,message:s.message,observabilityWarnings:c,failureCategory:edo(s),latencyMs:u}}catch(a){let s=Date.now()-r;return{status:"failed",painId:o,taskId:n,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:tdo(a),latencyMs:s}}}};var kOe=[{pattern:/Physical interception|physical blocking|物理拦截/i,description:"Remove Physical interception / physical blocking / \u7269\u7406\u62E6\u622A references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/Single source of truth.*PLAN/i,description:"Remove Single source of truth PLAN references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/PLAN\.md` \(status: READY\)|PLAN\.md`(状态:READY)/,description:"Remove PLAN.md status: READY references (AGENTS.md, THINKING_OS.md)",filenameSuffixes:["AGENTS.md","THINKING_OS.md"],actionType:"remove-line"},{pattern:/project physical plan|项目物理计划/i,description:"Remove project physical plan / \u9879\u76EE\u7269\u7406\u8BA1\u5212 references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/L2 delegation.*(PLAN|gate|blocking)|L2 委派.*(PLAN|gate|拦截)/i,description:"Remove L2 delegation / L2 \u59D4\u6D3E tied to PLAN.md gate enforcement (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/ or `PLAN\.md`/,description:'Replace "or PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (en)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/或 `PLAN\.md`/,description:'Replace "\u6216 PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (zh)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/PLAN\.md mechanism protects|PLAN\.md 机制保护/,description:"Remove PLAN.md mechanism protects / PLAN.md \u673A\u5236\u4FDD\u62A4 lines (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/STATUS: READY|STATUS:READY/,description:"Remove STATUS: READY references (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/Ensure `PLAN\.md` contains `## Target Files` heading|确保 `PLAN\.md` 包含 `## Target Files` 标题/,description:"Remove PLAN.md Target Files heading checks (admin/SKILL.md)",filenameSuffixes:["admin/SKILL.md"],actionType:"remove-line"},{pattern:/,\s*`PLAN\.md`\s*/,description:"Remove PLAN.md from list as trailing item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/`PLAN\.md`\s*,\s*/,description:"Remove PLAN.md from list as leading item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/Check `PLAN\.md` or early conversation/,description:"Replace Check PLAN.md or early conversation (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Check early conversation context"},{pattern:/Update `PLAN\.md`/,description:"Replace Update PLAN.md with Update memory/.scratchpad.md (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Update `memory/.scratchpad.md`"},{pattern:/检查 `PLAN\.md` 或早期对话/,description:"Replace Check PLAN.md or early conversation (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u68C0\u67E5\u65E9\u671F\u5BF9\u8BDD\u4E0A\u4E0B\u6587"},{pattern:/更新 `PLAN\.md`/,description:"Replace Update PLAN.md (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u66F4\u65B0 `memory/.scratchpad.md`"},{pattern:/, `PLAN\.md`, and /,description:"Remove PLAN.md from task descriptions (en, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:" and "},{pattern:/、`PLAN\.md` 和/,description:"Remove PLAN.md from task descriptions (zh, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:"\u548C"}],odo=kOe.map(e=>({pattern:e.pattern,description:e.description}));function wOe(e,t){let r=e.replace(/\\/g,"/");return r===t||r.endsWith("/"+t)}function IOe(e,t){if(e.length===0)return{migrated:e,changed:!1};let r=kOe.filter(p=>p.filenameSuffixes.some(h=>wOe(t,h)));if(r.length===0)return{migrated:e,changed:!1};let o=r.filter(p=>p.actionType==="remove-line"),n=r.filter(p=>p.actionType==="replace"),i=[],a=!1,s=e.split(`
1256
+ `).run(a??null,i);let h=c.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(i);return h&&typeof h=="object"&&Object.hasOwn(h,"id")&&typeof h.id=="number"?h.id:void 0}throw p}}finally{c.close()}}function pQ(e){let t=Klo(),r=[],o=e.data.score??80,n=e.data.sessionId??"cli",i=Hlo(t),a={warnings:r};try{let s=fk.join(e.stateDir,"logs",`events_${i}.jsonl`);WMt(s,{ts:t,date:i,type:"pain_signal",category:"detected",sessionId:n,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:o,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),severity:jMt(o),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){r.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=fk.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Lm(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};WMt(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){r.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{a.trajectoryPainEventId=Zlo({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId})}catch(s){r.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function edo(e){if(e.errorCategory)return M2[e.errorCategory]??"runtime_unavailable";if(e.status==="failed"){if(e.candidateIds.length===0)return"candidate_missing";if(e.ledgerEntryIds.length===0)return"ledger_write_failed"}}function tdo(e){if(e instanceof wt&&e.category)return M2[e.category]??"runtime_unavailable";let t=e instanceof Error?e.message:String(e);return/api[_\s]?key|not found in env|missing required/i.test(t)?"config_missing":/timeout|timed[_\s]?out/i.test(t)?"runtime_timeout":/output.*invalid|validation.*fail/i.test(t)?"output_invalid":"runtime_unavailable"}var hk=class{opts;constructor(t){this.opts=t}async recordPain(t){let r=Date.now(),{painId:o}=t,n=t.taskId??H2(o),i={painId:o,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:n,traceId:t.traceId,provenance:t.provenance,evidence:t.evidence};try{if(this.opts.asyncMode){let m=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:!1,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader,trajectoryTurnReader:this.opts.trajectoryTurnReader})).submitPainSignal(i),p=[];t.recordObservability!==!1&&(p=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:m.taskId}).warnings);let h=Date.now()-r;return{status:"submitted",painId:o,taskId:m.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:p,latencyMs:h,message:`Diagnosis submitted. Use 'pd task show ${m.taskId}' to check progress.`}}let s=await(await uQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,ledgerAdapter:this.opts.ledgerAdapter,owner:this.opts.owner,autoIntakeEnabled:this.opts.autoIntakeEnabled,effectiveConfig:this.opts.effectiveConfig,getEnvVar:this.opts.getEnvVar,intentDocReader:this.opts.intentDocReader,trajectoryTurnReader:this.opts.trajectoryTurnReader})).onPainDetected(i),c=[];t.recordObservability!==!1&&(c=pQ({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:i,canonicalPainId:o,runtimeTaskId:n}).warnings);let u=Date.now()-r;return{status:s.status,painId:s.painId,taskId:s.taskId,runId:s.runId,artifactId:s.artifactId,candidateIds:s.candidateIds,ledgerEntryIds:s.ledgerEntryIds,admissionResults:s.admissionResults,message:s.message,observabilityWarnings:c,failureCategory:edo(s),latencyMs:u}}catch(a){let s=Date.now()-r;return{status:"failed",painId:o,taskId:n,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:tdo(a),latencyMs:s}}}};var kOe=[{pattern:/Physical interception|physical blocking|物理拦截/i,description:"Remove Physical interception / physical blocking / \u7269\u7406\u62E6\u622A references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/Single source of truth.*PLAN/i,description:"Remove Single source of truth PLAN references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/PLAN\.md` \(status: READY\)|PLAN\.md`(状态:READY)/,description:"Remove PLAN.md status: READY references (AGENTS.md, THINKING_OS.md)",filenameSuffixes:["AGENTS.md","THINKING_OS.md"],actionType:"remove-line"},{pattern:/project physical plan|项目物理计划/i,description:"Remove project physical plan / \u9879\u76EE\u7269\u7406\u8BA1\u5212 references (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/L2 delegation.*(PLAN|gate|blocking)|L2 委派.*(PLAN|gate|拦截)/i,description:"Remove L2 delegation / L2 \u59D4\u6D3E tied to PLAN.md gate enforcement (AGENTS.md)",filenameSuffixes:["AGENTS.md"],actionType:"remove-line"},{pattern:/ or `PLAN\.md`/,description:'Replace "or PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (en)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/或 `PLAN\.md`/,description:'Replace "\u6216 PLAN.md" in T-02 PHYSICAL_MEMORY_PERSISTENCE (zh)',filenameSuffixes:["THINKING_OS.md"],actionType:"replace",replacement:""},{pattern:/PLAN\.md mechanism protects|PLAN\.md 机制保护/,description:"Remove PLAN.md mechanism protects / PLAN.md \u673A\u5236\u4FDD\u62A4 lines (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/STATUS: READY|STATUS:READY/,description:"Remove STATUS: READY references (MEMORY.md)",filenameSuffixes:["MEMORY.md"],actionType:"remove-line"},{pattern:/Ensure `PLAN\.md` contains `## Target Files` heading|确保 `PLAN\.md` 包含 `## Target Files` 标题/,description:"Remove PLAN.md Target Files heading checks (admin/SKILL.md)",filenameSuffixes:["admin/SKILL.md"],actionType:"remove-line"},{pattern:/,\s*`PLAN\.md`\s*/,description:"Remove PLAN.md from list as trailing item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/`PLAN\.md`\s*,\s*/,description:"Remove PLAN.md from list as leading item (admin/SKILL.md, pd-grooming/SKILL.md)",filenameSuffixes:["admin/SKILL.md","pd-grooming/SKILL.md"],actionType:"replace",replacement:""},{pattern:/Check `PLAN\.md` or early conversation/,description:"Replace Check PLAN.md or early conversation (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Check early conversation context"},{pattern:/Update `PLAN\.md`/,description:"Replace Update PLAN.md with Update memory/.scratchpad.md (en, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"Update `memory/.scratchpad.md`"},{pattern:/检查 `PLAN\.md` 或早期对话/,description:"Replace Check PLAN.md or early conversation (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u68C0\u67E5\u65E9\u671F\u5BF9\u8BDD\u4E0A\u4E0B\u6587"},{pattern:/更新 `PLAN\.md`/,description:"Replace Update PLAN.md (zh, reflection/SKILL.md)",filenameSuffixes:["reflection/SKILL.md"],actionType:"replace",replacement:"\u66F4\u65B0 `memory/.scratchpad.md`"},{pattern:/, `PLAN\.md`, and /,description:"Remove PLAN.md from task descriptions (en, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:" and "},{pattern:/、`PLAN\.md` 和/,description:"Remove PLAN.md from task descriptions (zh, report/SKILL.md)",filenameSuffixes:["report/SKILL.md"],actionType:"replace",replacement:"\u548C"}],odo=kOe.map(e=>({pattern:e.pattern,description:e.description}));function wOe(e,t){let r=e.replace(/\\/g,"/");return r===t||r.endsWith("/"+t)}function IOe(e,t){if(e.length===0)return{migrated:e,changed:!1};let r=kOe.filter(p=>p.filenameSuffixes.some(h=>wOe(t,h)));if(r.length===0)return{migrated:e,changed:!1};let o=r.filter(p=>p.actionType==="remove-line"),n=r.filter(p=>p.actionType==="replace"),i=[],a=!1,s=e.split(`
1257
1257
  `),c=[];for(let p of s){let h=!1;for(let f of o)if(f.pattern.test(p)){h=!0,i.includes(f.description)||i.push(f.description),wOe(t,"MEMORY.md")&&(a=!0);break}h||c.push(p)}let u=c.join(`
1258
1258
  `);for(let p of n){let h=p.replacement??"",f=u,g=p.pattern.flags.includes("g")?p.pattern.flags:p.pattern.flags+"g",y=new RegExp(p.pattern.source,g);u=u.replace(y,h),u!==f&&!i.includes(p.description)&&i.push(p.description)}if(a){let p="[Historical: confirm-first gate was removed in PRI-286. This section is preserved for reference only.]";u.endsWith(`
1259
1259
  `)||(u=u+`
@@ -2054,7 +2054,7 @@ ${o.join(`
2054
2054
  `).replace(/\n{3,}/g,`
2055
2055
 
2056
2056
  `).trim()}function lb(e,t){let r=[];if(!e.trajectory||t==="unknown")return r.push({sourceRef:"owner_message:unavailable",note:`trajectory_unavailable: ${e.trajectory?"unknown_session":"no_trajectory_db"}`}),r.slice(0,Ex);try{let n=[...e.trajectory.listUserTurnsForSession(t)??[]].reverse().find(i=>i.correctionDetected);if(n){let i=GD((n.rawExcerpt??"").slice(0,fR));r.push({sourceRef:`owner_message:${n.createdAt}`,note:i})}}catch(o){r.push({sourceRef:"owner_message:unavailable",note:`trajectory_user_turns_unavailable: ${String(o).slice(0,100)}`})}try{let n=(e.trajectory.listAssistantTurns(t)??[]).slice(-3);for(let i of n){if(r.length>=Ex)break;let a=GD((i.sanitizedText??"").slice(0,fR)),s=i.stopReason==="length"?" [TRUNCATED: output cut off by length limit]":"";r.push({sourceRef:`agent_turn:${i.createdAt}`,note:a+s})}}catch(o){r.length<Ex&&r.push({sourceRef:"agent_turn:unavailable",note:`trajectory_assistant_turns_unavailable: ${String(o).slice(0,100)}`})}try{let n=(e.trajectory.listToolCallsForSession(t)??[]).filter(i=>i.outcome==="failure").slice(-3);for(let i of n){if(r.length>=Ex)break;let a=i.resultPreview?` | ${i.resultPreview.slice(0,200)}`:"",s=`Tool ${i.toolName} failed: ${i.errorType??"unknown"} (exitCode: ${i.exitCode??"N/A"})${a}`;r.push({sourceRef:`tool_call_failure:${i.createdAt}`,note:GD(s.slice(0,fR))})}}catch(o){r.length===0&&r.push({sourceRef:"tool_call_failure:unavailable",note:`trajectory_tool_calls_unavailable: ${String(o).slice(0,100)}`})}return r.length===0&&r.push({sourceRef:"trajectory:empty",note:"trajectory_available_but_empty: no user correction or assistant turns found"}),r.slice(0,Ex)}var JD=500;function Rxr(e){if(e==null)return null;try{if(typeof e=="string")return e.length>JD?`${e.slice(0,JD-3)}...`:e;if(typeof e=="object"&&!Array.isArray(e)){let t=e;if(Array.isArray(t.content)){let o=[];for(let n of t.content)if(n&&typeof n=="object"&&!Array.isArray(n)){let i=n;i.type==="text"&&typeof i.text=="string"&&o.push(i.text)}if(o.length>0){let n=o.join(`
2057
- `);return n.length>JD?`${n.slice(0,JD-3)}...`:n}}let r=JSON.stringify(t,(o,n)=>{if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let i=Object.keys(n);if(i.length>10){let a={};for(let s of i.slice(0,10))a[s]=n[s];return a.__truncated__=!0,a}}return n},2);if(r&&r!=="{}")return r.length>JD?`${r.slice(0,JD-3)}...`:r}return null}catch{return"[result_preview_extraction_failed]"}}function wxr(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,r=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,o=t?.exitCode,n=r?.exitCode,i=typeof o=="number"?o:typeof n=="number"?n:0,a=!!e.error||i!==0,s=ED({toolName:e.toolName,error:e.error,exitCode:i}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:i,failureSource:c}}function kxr(e,t,r,o){let n=e.params,i=n&&typeof n=="object"&&!Array.isArray(n)?n:{},a=i.file_path||i.path||i.file,s=typeof a=="string"?ryr(a,r):"unknown",c=gse(s,o.risk_paths),u;if(e.error)u=String(e.error);else if(typeof e.result=="string")u=e.result;else try{u=JSON.stringify(e.result)}catch{u=`[unserializable result: ${typeof e.result}]`}let l=sxr(u),m=WD(l),p=hxr(1,!1,!1,c?20:0,r);return{params:{filePath:a,content:i.content,text:i.text,newString:i.new_string,query:i.query,input:i.input,arguments:i.arguments},relPath:s,isRisk:c,errorType:mTn(e.error||u),errorHash:m,errorText:u,painScore:p,traceId:PI()}}function Ixr(e,t,r,o,n,i,a,s){let c=a.get("scores.tool_failure_friction")||30,u=LD(e,c,o.errorHash,i,{source:r.failureSource});return Txr(i,t.toolName,{filePath:o.relPath,reason:o.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:o.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:r.exitCode,gfiBefore:n,gfiAfter:u.currentGfi}),s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:r.exitCode,errorType:o.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:n,gfiAfter:u.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),u}function Cxr(e,t,r,o,n,i,a){let s=Sm(e),c=s?.gfiBySource?.tool_failure||0,u=s?.gfiBySource?.dispatch_error||0,l=s||xh(e,i);return c>0&&(l=xh(e,i,{source:"tool_failure",amount:c*.5})),u>0&&(l=xh(e,i,{source:"dispatch_error",amount:u*.5})),vxr(i,t.toolName,{sessionId:e,reason:"tool_success"}),a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:r.exitCode,gfiBefore:n,gfiAfter:l.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,gfi:l.currentGfi,gfiBefore:n,gfiAfter:l.currentGfi}),l}function Axr(e,t,r){let o=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",n=/(?:^|\/)memory\//.test(o)||o.endsWith("/MEMORY.md")||o==="MEMORY.md",i=o==="PLAN.md"||o.endsWith("/PLAN.md");(n||i)&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:n?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function dTn(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function aqe(e,t,r,o,n){let i=Nyr(e,r);for(let a of i){let s=o.evolutionReducer.getPrincipleById(a);s&&dTn(s,t)&&o.evolutionReducer.recordProbationFeedback(a,n)}rj(e,r)}var Exr=["write","edit","apply_patch","write_file","edit_file","replace"];function Oxr(e,t,r,o,n,i,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...Exr,...lj]:Exr).includes(e.toolName)||!r.isFailure)return r.isFailure&&pr.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:r.failureSource,sessionId:i,nextAction:"No pain task created; failure is outside write-tool admission scope. Retry or investigate if unexpected."})),{admitted:!1,stage:"not_applicable",reason:"not_a_write_tool_failure",detail:`tool=${e.toolName}, isFailure=${r.isFailure}`};let l=r.failureSource??"tool_failure",m=IE(l,i,o?.lastErrorHash),p={observedAt:new Date().toISOString(),workspaceId:a,sessionId:i,toolName:e.toolName,failureSource:r.failureSource,toolNotFound:r.failureSource==="dispatch_error",nonZeroExit:r.exitCode!==0},h=Ky(p),f=(o??n)?.consecutiveErrors,g=c?Math.max(4,f??0):f,y=AE(h,t.painScore,{consecutiveErrors:g,isRisky:t.isRisk}),T=Hy({triageResult:y,isOwnerManual:!1,isCooldownActive:m,isValid:!0,score:t.painScore,sessionId:i});return pr.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:T.outcome,sourceKind:T.sourceKind,reason:T.reason,nextAction:T.nextAction,triageDecision:T.triageDecision,tool:e.toolName,path:t.relPath})),T.shouldCreateDiagnosticTask?(CE(l,i,o?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}}function Pxr(e,t,r,o,n,i,a,s,c){if(!n.admitted)return;let u=o.failureSource??"tool_failure",l=`pain_${Date.now()}_${r.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:i,source:u,score:r.painScore,reason:`Tool ${t.toolName} failed on ${r.relPath}`,severity:r.painScore>=70?"severe":r.painScore>=40?"moderate":"mild",origin:"system_infer",text:Yse(r.params.text??r.params.content,s)||void 0,canonicalPainId:l});try{gxr(s,{reason:`Tool ${t.toolName} failed on ${r.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:u,score:String(r.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(p=>({id:p.id,trigger:p.trigger,valueMetrics:p.valueMetrics})),(p,h)=>{let f=e.evolutionReducer.getPrincipleById(p);if(f){f.valueMetrics=h;try{e.principleTreeLedger.updatePrincipleValueMetrics(p,{principleId:p,painPreventedCount:h.painPreventedCount,lastPainPreventedAt:h.lastPainPreventedAt,calculatedAt:h.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(g){pr.log(s,"METRICS_UPDATE_SKIP",String(g))}}})}catch(p){pr.log(s,"PRINCIPLE_TRACK_SKIP",String(p))}e.eventLog.recordPainSignal(i,{score:r.painScore,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,isRisky:r.isRisk}),Jse(s,e.trajectory).logPainDetected({traceId:r.traceId,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,score:r.painScore,toolName:t.toolName,filePath:r.relPath,sessionId:i}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:u,source:t.toolName,reason:`Tool ${t.toolName} failed on ${r.relPath}; diagnosticGate=${n.reason}`,score:r.painScore,sessionId:i,traceId:r.traceId,agentId:a,provenance:"automatic_hook",evidence:lb(e,i)}},{recordObservability:!1})}function mTn(e){if(!e)return"Unknown";let t=String(e);return t.includes("EACCES")||t.includes("permission denied")?"EACCES":t.includes("ENOENT")||t.includes("no such file")?"ENOENT":t.includes("EISDIR")?"EISDIR":t.includes("ENOSPC")?"ENOSPC":t.includes("SyntaxError")?"SyntaxError":t.includes("TypeError")?"TypeError":t.includes("ReferenceError")?"ReferenceError":t.includes("timeout")||t.includes("ETIMEDOUT")?"Timeout":t.includes("network")||t.includes("ECONNREFUSED")?"Network":"Other"}function fTn(e){let t=new oT({stateDir:e.stateDir}),r=Pp(e.workspaceDir);return new hk({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:r.effective,getEnvVar:o=>process.env[o],intentDocReader:Gse(e.workspaceDir,FD(e.workspaceDir))})}async function ll(e,t,r){try{e.evolutionReducer.emitSync(t)}catch(o){pr.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(o)}`)}if(t.type==="pain_detected"){let o=t.data;try{let n=fTn(e);(o.source==="manual"||o.source==="pain"||o.source==="skill:pain")&&pr.log(e.workspaceDir,"TRIGGER_DECISION",JSON.stringify({outcome:"manual_owner_admitted",sourceKind:"owner_reported",reason:"Owner explicit manual pain. Bypasses triage and cooldown.",nextAction:"create_diagnostic_task",painId:o.painId,score:o.score}));let a=r?.recordObservability??!0,s=await n.recordPain({painId:o.painId,painType:o.painType,source:o.source,reason:o.reason,score:o.score,sessionId:o.sessionId,agentId:o.agentId,taskId:o.taskId,traceId:o.traceId,provenance:o.provenance,evidence:o.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?pr.log(e.workspaceDir,"PAIN_SERVICE_FAILED",JSON.stringify({painId:s.painId,taskId:s.taskId,failureCategory:s.failureCategory,latencyMs:s.latencyMs,message:s.message})):s.status==="skipped"&&pr.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(n){pr.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(n)}`);let i=n instanceof Error?n.message:String(n),a=!1;try{let s=new Tl({workspaceDir:e.workspaceDir});try{let u=new D4(s).insertDeadLetter({painId:o.painId,painData:o});u.ok?a=!0:pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",u.error)}finally{s.close()}}catch(s){pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}pr.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:o.painId,painType:o.painType,source:o.source,score:o.score,deadLetterInserted:a,error:i,nextAction:`Run 'pd pain retry --pain-id ${o.painId}' to replay this pain signal`}))}}}function hTn(e){return`pain_${Date.now()}_${WD(e).slice(0,8)}`}function Nxr(e,t,r){let o;try{o=lxr(t,r,"after_tool_call")}catch(g){pr.log(t.workspaceDir??"unknown","WORKSPACE_RESOLUTION_FAILED",JSON.stringify({hook:"after_tool_call",sessionId:t.sessionId??"unknown",toolName:e.toolName,reason:"workspace_resolution_failed",nextAction:"check_plugin_config_workspace_resolution",error:String(g).slice(0,200)}));return}let n=no.fromHookContextExplicit({...t,workspaceDir:o}),{config:i}=n,a=t.sessionId||"unknown",s=t.sessionId?Sm(t.sessionId):void 0,c=s?.currentGfi??0,u=n.resolve("PROFILE"),l=qD({});if(Qse.existsSync(u))try{let g=Qse.readFileSync(u,"utf8");g.length>1024*1024?pr.log(o,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):l=qD(JSON.parse(g))}catch(g){pr.log(o,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(g)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){gTn(e,t,n,o,a);return}let m=wxr(e),p=kxr(e,m,o,l),h;m.isFailure?(h=Ixr(a,e,m,p,c,o,i,n),aqe(a,e.toolName,o,n,!1)):(Cxr(a,e,m,p,c,o,n),aqe(a,e.toolName,o,n,!0),Axr(e,p,n));let f=Oxr(e,p,m,h,s,a,o,i);f.stage!=="not_applicable"&&Pxr(n,e,p,m,f,a,t.agentId,o,ll)}function gTn(e,t,r,o,n){let i=e.params,a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},s=a.input||a.arguments||"Manual intervention",c=PI();LD(n,100,"manual_pain",o,{source:"manual_pain"}),pr.log(o,"MANUAL_PAIN",`User manually triggered pain: ${s}`),r.eventLog.recordPainSignal(n,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let u=hTn(n);r.trajectory?.recordPainEvent?.({sessionId:n,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:u}),Jse(o,r.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:n});let m=ru(o,"painEvidenceAdmission"),p=ru(o,"painEvidenceAdmissionDefault");if(m.enabled&&p.enabled){let f=N4({sessionId:n}),g=Ky(f),y=AE(g,100),T=IE(g,n,"manual_pain"),v=Hy({triageResult:y,isOwnerManual:!0,isCooldownActive:T,isValid:!0,score:100,sessionId:n});Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:v.outcome,sourceKind:v.sourceKind,reason:v.reason,nextAction:v.nextAction,isOwnerManual:!0,sessionId:n,score:100})),v.shouldCreateDiagnosticTask?(CE(g,n,"manual_pain"),ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})):pr.log(o,"MANUAL_PAIN_SKIPPED",v.reason)}else{let f=Sm(n),g=jD({source:"manual",score:100,currentGfi:f?.currentGfi??0,sessionId:n});if(!g.shouldDiagnose){pr.log(o,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${g.detail}`);let y;try{y=JSON.stringify({reason:g.reason,detail:g.detail,source:"manual",sessionId:n,gfi:0,score:100})}catch(v){pr.log(o,"PAYLOAD_SERIALIZE_FAILED",String(v)),y=JSON.stringify({reason:g.reason,detail:"(log serialization failed)"})}pr.log(o,"PAIN_GATE_REJECTED",y),Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${g.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:n,score:100}));return}ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})}}var yTn={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:70,strongRateLimitPerHour:5};function sqe(e){return e==="user"||e==="api"||e===void 0}function xTn(){return{version:1,terms:{\u8FD9\u662F\u9519\u7684:{term:"\u8FD9\u662F\u9519\u7684",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20:{term:"\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A:{term:"\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5BF9:{term:"\u4E0D\u5BF9",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u9519\u4E86:{term:"\u9519\u4E86",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u641E\u4EC0\u4E48:{term:"\u641E\u4EC0\u4E48",category:"empathy",weight:.5,precision:"ambiguous",source:"seed"}}}}var bTn=3600*1e3,Zse=class{wctx;store;config;llmClassifier;rateLimit=new Map;constructor(t,r={}){this.wctx=t,this.store=r.keywordStore??xTn(),this.config=r.config??yTn,this.llmClassifier=r.llmClassifier??null}detectSync(t,r,o,n){if(!sqe(o))return;let i=new Date().toISOString(),a=sse(t,r,this.store,this.config,i),s={sessionId:r,turnIndex:n?.turnIndex??Date.now(),rawText:t,correctionDetected:a.isSignal&&a.strength==="STRONG",correctionCue:a.matchedTerms.length>0?a.matchedTerms.join(", "):null,referencesAssistantTurnId:n?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(s)}catch(c){pr.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(c)}`)}if(a.isSignal&&a.strength==="STRONG"&&a.matchedPrecision==="high"){this.routeStrong(a,r);return}if(a.needsLlmConfirmation){let c={output:a,sessionId:r,text:t,traceId:PI()};this.detectAsyncAndRoute(c)}}async detectAsyncAndRoute(t){let r;if(this.llmClassifier&&this.config.enableLlmStage){let o=null;try{o=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(i){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(i)}`)}let n=new Date().toISOString();o?r=F4(o,t.text,t.sessionId,this.config,n):(pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),r=F4({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,n))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(n=>this.store.terms[n]?.category==="empathy")){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let n={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(n,t.sessionId);return}pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}r.isSignal&&r.strength==="STRONG"?this.routeStrong(r,t.sessionId):r.isSignal&&r.strength==="WEAK"&&this.routeWeak(r,t.sessionId)}routeStrong(t,r){if(!this.tryConsumeRateLimit(r)){pr.log(this.wctx.workspaceDir,"SIGNAL_STRONG_RATE_LIMITED","STRONG signal suppressed by rate limit");return}let o=t.llmReason||(t.matchedTerms.length>0?`User correction detected: ${t.matchedTerms.join(", ")}`:"User correction detected");ll(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`correction_${PI()}`,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:r,agentId:"main",provenance:"openclaw_context_bound",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(n=>{pr.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(n)}`)})}routeWeak(t,r){try{let o=_Tn("sha256").update(`${t.evidence.detectedAt}:${r}`).digest("hex").slice(0,32);LD(r,20,o,this.wctx.workspaceDir,{source:"user_empathy"})}catch(o){pr.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(o)}`)}}tryConsumeRateLimit(t){let r=this.config.strongRateLimitPerHour,o=Date.now(),n=this.rateLimit.get(t);return(!n||o-n.windowStart>=bTn)&&(n={count:0,windowStart:o},this.rateLimit.set(t,n)),n.count>=r?!1:(n.count+=1,!0)}};function Mxr(e,t){try{let r=W4(e.workspaceDir,"signal_collector","signalCollector",t);if(!r.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${r.reason}`),null;if(r.readiness!=="not_ready"&&r.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${r.readiness}): ${r.reason}. ${r.nextAction}`),null;if(!r.provider||!r.model||!r.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let o=new nm({provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,timeoutMs:r.timeoutMs??3e4,baseUrl:r.baseUrl??void 0,workspace:e.workspaceDir});return async(i,a)=>{let s=nse(i);try{let c=await o.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:r.timeoutMs??3e4}),u=await o.pollRun(c.runId),l=Date.now()+(r.timeoutMs??3e4);for(;u.status==="running"&&Date.now()<l;)await new Promise(g=>setTimeout(g,500)),u=await o.pollRun(c.runId);if(u.status!=="succeeded")return pr.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:u.status})),null;let p=(await o.fetchOutput(c.runId))?.payload,h="";if(typeof p=="string")h=p;else if(typeof p=="object"&&p!==null&&Object.hasOwn(p,"output")){let g=p.output;typeof g=="string"&&(h=g)}let f=ise(h);return f.valid?f.value:null}catch(c){return pr.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(r){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(r)}`),null}}var STn=6e4,Lxr=new Map,vTn=256,cqe=new Map;function TTn(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function ETn(e){if(typeof e!="object"||e===null)return;let t=TTn(e,"code");return typeof t=="string"?t:void 0}function RTn(e){let t=Lxr.get(e);return t||(t=new Map,Lxr.set(e,t)),t}function $xr(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function wTn(e,t,r){let o=e.trajectory?.listUserTurnsForSession?.(t)??[];return o.length>0?o.reduce((n,i)=>Math.max(n,i.turnIndex),0)+1:r.filter(n=>$xr(n,"user")).length+1}function kTn(e,t,r){let o=cqe.get(e);o||(o=new Set,cqe.set(e,o));let n=`${t}\0${r}`;if(o.has(n))return!1;if(o.add(n),o.size>vTn){let i=o.values().next().value;typeof i=="string"&&o.delete(i)}return!0}function ITn(e,t,r){return cqe.get(e)?.has(`${t}\0${r}`)??!1}function CTn(e,t){let r=RTn(t),o=Date.now(),n=r.get(e);try{let a=NI.statSync(e).mtimeMs;if(n&&o-n.loadedAt<STn&&n.mtime===a)return n.content;let s=NI.readFileSync(e,"utf8");return r.set(e,{content:s,mtime:a,loadedAt:o}),s}catch(i){return r.delete(e),ETn(i)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(i)}`),""}}var Dxr=new Map;function ATn(e,t){let r=Dxr.get(e.workspaceDir);if(!r){let o=Mxr(e,t);r=new Zse(e,{llmClassifier:o}),Dxr.set(e.workspaceDir,r)}return r}function MI(e){return{...Pp(e).effective.resolvedContextInjection}}async function zxr(e,t){let{workspaceDir:r}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!r}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!r){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let n=no.fromHookContext(t),{runId:i,sessionKey:a,trigger:s,sessionId:c}=t,u=sqe(s),l=t.api;c&&n.trajectory?.recordSession?.({sessionId:c});let m=null;if(c&&u&&e.messages.some($t=>$xr($t,"assistant"))){let $t=n.trajectory?.listAssistantTurns?.(c)??[];m=$t[$t.length-1]?.id??null}let p=MI(n.workspaceDir),h=Dse(s,c),f=c?Sm(c):void 0,g,y="",T="";s==="user"&&c&&f&&f.currentGfi>=100&&xh(c,r),g=exr();let v=txr(),{message:E,isAgentToAgent:L}=Zyr(e.prompt,c),H=!1;if(u&&c&&l&&!L&&(H=!0),E&&c&&u&&!L&&(i&&ITn(n.workspaceDir,a??c,i)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${i}, sessionId=${c.substring(0,20)}`):(i||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${c.substring(0,20)}`),ATn(n,o).detectSync(E,c,s??"api",{referencesAssistantTurnId:m,turnIndex:wTn(n,c,e.messages)}),i&&kTn(n.workspaceDir,a??c,i))),s==="heartbeat"||s==="cron"){if(c){let fr=Dyr(c);if(fr>=1){let Ot=Lyr(c,fr);Ot&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${fr}min elapsed, GFI now ${Ot.currentGfi.toFixed(1)}`)}}let $t=n.resolve("HEARTBEAT");if(NI.existsSync($t))try{let fr=NI.readFileSync($t,"utf8");y+=rxr(fr)}catch(fr){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(fr)}`)}}let B="";try{let $t=n.evolutionReducer.getActivePrinciples();$t.length>0&&(B=oxr($t))}catch($t){o?.warn?.(`[PD:Prompt] Failed to load core principles from reducer: ${String($t)}`)}let Te="";if(p.thinkingOs){let $t=n.resolve("THINKING_OS");try{let fr=CTn($t,n.workspaceDir);fr&&(Te=fr.trim())}catch(fr){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(fr)}`)}}let Ce="",ye="";if(!h&&p.projectFocus!=="off"){let $t=n.resolve("CURRENT_FOCUS"),fr=_h.getExtensionRoot(),{content:Ot,recovered:vr,validationErrors:Zr}=Xyr($t,fr||"",o);if(vr&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Zr.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Zr.join(", ")}`),Ot.trim())try{let{stateDir:Di}=n,aa=Hyr($t,r,Di);aa.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${aa.oldLines} \u2192 ${aa.newLines} lines. Milestones archived: ${aa.milestonesArchived}`):aa.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${aa.reason}`);let mr=aa.newContent?.trim()||Ot.trim();if(mr){let Eo=ij(mr);if(Eo&&(ye=aj(Eo)),p.projectFocus==="summary")Ce=$D(mr,30);else{let fn=await Vyr($t,3);if(fn.length>0){let au=fn.map((ai,Ji)=>`
2057
+ `);return n.length>JD?`${n.slice(0,JD-3)}...`:n}}let r=JSON.stringify(t,(o,n)=>{if(typeof n=="object"&&n!==null&&!Array.isArray(n)){let i=Object.keys(n);if(i.length>10){let a={};for(let s of i.slice(0,10))a[s]=n[s];return a.__truncated__=!0,a}}return n},2);if(r&&r!=="{}")return r.length>JD?`${r.slice(0,JD-3)}...`:r}return null}catch{return"[result_preview_extraction_failed]"}}function wxr(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,r=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,o=t?.exitCode,n=r?.exitCode,i=typeof o=="number"?o:typeof n=="number"?n:0,a=!!e.error||i!==0,s=ED({toolName:e.toolName,error:e.error,exitCode:i}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:i,failureSource:c}}function kxr(e,t,r,o){let n=e.params,i=n&&typeof n=="object"&&!Array.isArray(n)?n:{},a=i.file_path||i.path||i.file,s=typeof a=="string"?ryr(a,r):"unknown",c=gse(s,o.risk_paths),u;if(e.error)u=String(e.error);else if(typeof e.result=="string")u=e.result;else try{u=JSON.stringify(e.result)}catch{u=`[unserializable result: ${typeof e.result}]`}let l=sxr(u),m=WD(l),p=hxr(1,!1,!1,c?20:0,r);return{params:{filePath:a,content:i.content,text:i.text,newString:i.new_string,query:i.query,input:i.input,arguments:i.arguments},relPath:s,isRisk:c,errorType:mTn(e.error||u),errorHash:m,errorText:u,painScore:p,traceId:PI()}}function Ixr(e,t,r,o,n,i,a,s){let c=a.get("scores.tool_failure_friction")||30,u=LD(e,c,o.errorHash,i,{source:r.failureSource});return Txr(i,t.toolName,{filePath:o.relPath,reason:o.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:o.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:r.exitCode,gfiBefore:n,gfiAfter:u.currentGfi}),s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:r.exitCode,errorType:o.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:n,gfiAfter:u.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),u}function Cxr(e,t,r,o,n,i,a){let s=Sm(e),c=s?.gfiBySource?.tool_failure||0,u=s?.gfiBySource?.dispatch_error||0,l=s||xh(e,i);return c>0&&(l=xh(e,i,{source:"tool_failure",amount:c*.5})),u>0&&(l=xh(e,i,{source:"dispatch_error",amount:u*.5})),vxr(i,t.toolName,{sessionId:e,reason:"tool_success"}),a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:r.exitCode,gfiBefore:n,gfiAfter:l.currentGfi,paramsJson:iqe(t.params,i),resultPreview:Rxr(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:o.params.filePath,gfi:l.currentGfi,gfiBefore:n,gfiAfter:l.currentGfi}),l}function Axr(e,t,r){let o=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",n=/(?:^|\/)memory\//.test(o)||o.endsWith("/MEMORY.md")||o==="MEMORY.md",i=o==="PLAN.md"||o.endsWith("/PLAN.md");(n||i)&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:n?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&r.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function dTn(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function aqe(e,t,r,o,n){let i=Nyr(e,r);for(let a of i){let s=o.evolutionReducer.getPrincipleById(a);s&&dTn(s,t)&&o.evolutionReducer.recordProbationFeedback(a,n)}rj(e,r)}var Exr=["write","edit","apply_patch","write_file","edit_file","replace"];function Oxr(e,t,r,o,n,i,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...Exr,...lj]:Exr).includes(e.toolName)||!r.isFailure)return r.isFailure&&pr.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:r.failureSource,sessionId:i,nextAction:"No pain task created; failure is outside write-tool admission scope. Retry or investigate if unexpected."})),{admitted:!1,stage:"not_applicable",reason:"not_a_write_tool_failure",detail:`tool=${e.toolName}, isFailure=${r.isFailure}`};let l=r.failureSource??"tool_failure",m=IE(l,i,o?.lastErrorHash),p={observedAt:new Date().toISOString(),workspaceId:a,sessionId:i,toolName:e.toolName,failureSource:r.failureSource,toolNotFound:r.failureSource==="dispatch_error",nonZeroExit:r.exitCode!==0},h=Ky(p),f=(o??n)?.consecutiveErrors,g=c?Math.max(4,f??0):f,y=AE(h,t.painScore,{consecutiveErrors:g,isRisky:t.isRisk}),T=Hy({triageResult:y,isOwnerManual:!1,isCooldownActive:m,isValid:!0,score:t.painScore,sessionId:i});return pr.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:T.outcome,sourceKind:T.sourceKind,reason:T.reason,nextAction:T.nextAction,triageDecision:T.triageDecision,tool:e.toolName,path:t.relPath})),T.shouldCreateDiagnosticTask?(CE(l,i,o?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:T.reason,detail:`outcome=${T.outcome}, sourceKind=${T.sourceKind}, nextAction=${T.nextAction}`}}function Pxr(e,t,r,o,n,i,a,s,c){if(!n.admitted)return;let u=o.failureSource??"tool_failure",l=`pain_${Date.now()}_${r.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:i,source:u,score:r.painScore,reason:`Tool ${t.toolName} failed on ${r.relPath}`,severity:r.painScore>=70?"severe":r.painScore>=40?"moderate":"mild",origin:"system_infer",text:Yse(r.params.text??r.params.content,s)||void 0,canonicalPainId:l});try{gxr(s,{reason:`Tool ${t.toolName} failed on ${r.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:u,score:String(r.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(p=>({id:p.id,trigger:p.trigger,valueMetrics:p.valueMetrics})),(p,h)=>{let f=e.evolutionReducer.getPrincipleById(p);if(f){f.valueMetrics=h;try{e.principleTreeLedger.updatePrincipleValueMetrics(p,{principleId:p,painPreventedCount:h.painPreventedCount,lastPainPreventedAt:h.lastPainPreventedAt,calculatedAt:h.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(g){pr.log(s,"METRICS_UPDATE_SKIP",String(g))}}})}catch(p){pr.log(s,"PRINCIPLE_TRACK_SKIP",String(p))}e.eventLog.recordPainSignal(i,{score:r.painScore,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,isRisky:r.isRisk}),Jse(s,e.trajectory).logPainDetected({traceId:r.traceId,source:u,reason:`Tool ${t.toolName} failed on ${r.relPath}`,score:r.painScore,toolName:t.toolName,filePath:r.relPath,sessionId:i}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:u,source:t.toolName,reason:`Tool ${t.toolName} failed on ${r.relPath}; diagnosticGate=${n.reason}`,score:r.painScore,sessionId:i,traceId:r.traceId,agentId:a,provenance:"automatic_hook",evidence:lb(e,i)}},{recordObservability:!1})}function mTn(e){if(!e)return"Unknown";let t=String(e);return t.includes("EACCES")||t.includes("permission denied")?"EACCES":t.includes("ENOENT")||t.includes("no such file")?"ENOENT":t.includes("EISDIR")?"EISDIR":t.includes("ENOSPC")?"ENOSPC":t.includes("SyntaxError")?"SyntaxError":t.includes("TypeError")?"TypeError":t.includes("ReferenceError")?"ReferenceError":t.includes("timeout")||t.includes("ETIMEDOUT")?"Timeout":t.includes("network")||t.includes("ECONNREFUSED")?"Network":"Other"}function fTn(e){let t=new oT({stateDir:e.stateDir}),r=Pp(e.workspaceDir),o={listUserTurnsForSession:n=>e.trajectory.listUserTurnsForSession(n),listAssistantTurns:n=>e.trajectory.listAssistantTurns(n)};return new hk({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:r.effective,getEnvVar:n=>process.env[n],intentDocReader:Gse(e.workspaceDir,FD(e.workspaceDir)),trajectoryTurnReader:o})}async function ll(e,t,r){try{e.evolutionReducer.emitSync(t)}catch(o){pr.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(o)}`)}if(t.type==="pain_detected"){let o=t.data;try{let n=fTn(e);(o.source==="manual"||o.source==="pain"||o.source==="skill:pain")&&pr.log(e.workspaceDir,"TRIGGER_DECISION",JSON.stringify({outcome:"manual_owner_admitted",sourceKind:"owner_reported",reason:"Owner explicit manual pain. Bypasses triage and cooldown.",nextAction:"create_diagnostic_task",painId:o.painId,score:o.score}));let a=r?.recordObservability??!0,s=await n.recordPain({painId:o.painId,painType:o.painType,source:o.source,reason:o.reason,score:o.score,sessionId:o.sessionId,agentId:o.agentId,taskId:o.taskId,traceId:o.traceId,provenance:o.provenance,evidence:o.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?pr.log(e.workspaceDir,"PAIN_SERVICE_FAILED",JSON.stringify({painId:s.painId,taskId:s.taskId,failureCategory:s.failureCategory,latencyMs:s.latencyMs,message:s.message})):s.status==="skipped"&&pr.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(n){pr.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(n)}`);let i=n instanceof Error?n.message:String(n),a=!1;try{let s=new Tl({workspaceDir:e.workspaceDir});try{let u=new D4(s).insertDeadLetter({painId:o.painId,painData:o});u.ok?a=!0:pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",u.error)}finally{s.close()}}catch(s){pr.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}pr.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:o.painId,painType:o.painType,source:o.source,score:o.score,deadLetterInserted:a,error:i,nextAction:`Run 'pd pain retry --pain-id ${o.painId}' to replay this pain signal`}))}}}function hTn(e){return`pain_${Date.now()}_${WD(e).slice(0,8)}`}function Nxr(e,t,r){let o;try{o=lxr(t,r,"after_tool_call")}catch(g){pr.log(t.workspaceDir??"unknown","WORKSPACE_RESOLUTION_FAILED",JSON.stringify({hook:"after_tool_call",sessionId:t.sessionId??"unknown",toolName:e.toolName,reason:"workspace_resolution_failed",nextAction:"check_plugin_config_workspace_resolution",error:String(g).slice(0,200)}));return}let n=no.fromHookContextExplicit({...t,workspaceDir:o}),{config:i}=n,a=t.sessionId||"unknown",s=t.sessionId?Sm(t.sessionId):void 0,c=s?.currentGfi??0,u=n.resolve("PROFILE"),l=qD({});if(Qse.existsSync(u))try{let g=Qse.readFileSync(u,"utf8");g.length>1024*1024?pr.log(o,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):l=qD(JSON.parse(g))}catch(g){pr.log(o,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(g)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){gTn(e,t,n,o,a);return}let m=wxr(e),p=kxr(e,m,o,l),h;m.isFailure?(h=Ixr(a,e,m,p,c,o,i,n),aqe(a,e.toolName,o,n,!1)):(Cxr(a,e,m,p,c,o,n),aqe(a,e.toolName,o,n,!0),Axr(e,p,n));let f=Oxr(e,p,m,h,s,a,o,i);f.stage!=="not_applicable"&&Pxr(n,e,p,m,f,a,t.agentId,o,ll)}function gTn(e,t,r,o,n){let i=e.params,a=i&&typeof i=="object"&&!Array.isArray(i)?i:{},s=a.input||a.arguments||"Manual intervention",c=PI();LD(n,100,"manual_pain",o,{source:"manual_pain"}),pr.log(o,"MANUAL_PAIN",`User manually triggered pain: ${s}`),r.eventLog.recordPainSignal(n,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let u=hTn(n);r.trajectory?.recordPainEvent?.({sessionId:n,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:u}),Jse(o,r.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:n});let m=ru(o,"painEvidenceAdmission"),p=ru(o,"painEvidenceAdmissionDefault");if(m.enabled&&p.enabled){let f=N4({sessionId:n}),g=Ky(f),y=AE(g,100),T=IE(g,n,"manual_pain"),v=Hy({triageResult:y,isOwnerManual:!0,isCooldownActive:T,isValid:!0,score:100,sessionId:n});Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:v.outcome,sourceKind:v.sourceKind,reason:v.reason,nextAction:v.nextAction,isOwnerManual:!0,sessionId:n,score:100})),v.shouldCreateDiagnosticTask?(CE(g,n,"manual_pain"),ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})):pr.log(o,"MANUAL_PAIN_SKIPPED",v.reason)}else{let f=Sm(n),g=jD({source:"manual",score:100,currentGfi:f?.currentGfi??0,sessionId:n});if(!g.shouldDiagnose){pr.log(o,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${g.detail}`);let y;try{y=JSON.stringify({reason:g.reason,detail:g.detail,source:"manual",sessionId:n,gfi:0,score:100})}catch(v){pr.log(o,"PAYLOAD_SERIALIZE_FAILED",String(v)),y=JSON.stringify({reason:g.reason,detail:"(log serialization failed)"})}pr.log(o,"PAIN_GATE_REJECTED",y),Pp(o).effective&&pr.log(o,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${g.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:n,score:100}));return}ll(r,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:n,traceId:c,agentId:t.agentId,provenance:n&&n!=="unknown"?"openclaw_context_bound":"owner_reported_no_host_trace",evidence:lb(r,n)}},{recordObservability:!1})}}var yTn={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:70,strongRateLimitPerHour:5};function sqe(e){return e==="user"||e==="api"||e===void 0}function xTn(){return{version:1,terms:{\u8FD9\u662F\u9519\u7684:{term:"\u8FD9\u662F\u9519\u7684",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20:{term:"\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A:{term:"\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",category:"correction",weight:.9,precision:"high",source:"seed"},\u4E0D\u5BF9:{term:"\u4E0D\u5BF9",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u9519\u4E86:{term:"\u9519\u4E86",category:"correction",weight:.5,precision:"ambiguous",source:"seed"},\u641E\u4EC0\u4E48:{term:"\u641E\u4EC0\u4E48",category:"empathy",weight:.5,precision:"ambiguous",source:"seed"}}}}var bTn=3600*1e3,Zse=class{wctx;store;config;llmClassifier;rateLimit=new Map;constructor(t,r={}){this.wctx=t,this.store=r.keywordStore??xTn(),this.config=r.config??yTn,this.llmClassifier=r.llmClassifier??null}detectSync(t,r,o,n){if(!sqe(o))return;let i=new Date().toISOString(),a=sse(t,r,this.store,this.config,i),s={sessionId:r,turnIndex:n?.turnIndex??Date.now(),rawText:t,correctionDetected:a.isSignal&&a.strength==="STRONG",correctionCue:a.matchedTerms.length>0?a.matchedTerms.join(", "):null,referencesAssistantTurnId:n?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(s)}catch(c){pr.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(c)}`)}if(a.isSignal&&a.strength==="STRONG"&&a.matchedPrecision==="high"){this.routeStrong(a,r);return}if(a.needsLlmConfirmation){let c={output:a,sessionId:r,text:t,traceId:PI()};this.detectAsyncAndRoute(c)}}async detectAsyncAndRoute(t){let r;if(this.llmClassifier&&this.config.enableLlmStage){let o=null;try{o=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(i){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(i)}`)}let n=new Date().toISOString();o?r=F4(o,t.text,t.sessionId,this.config,n):(pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),r=F4({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,n))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(n=>this.store.terms[n]?.category==="empathy")){pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let n={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(n,t.sessionId);return}pr.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}r.isSignal&&r.strength==="STRONG"?this.routeStrong(r,t.sessionId):r.isSignal&&r.strength==="WEAK"&&this.routeWeak(r,t.sessionId)}routeStrong(t,r){if(!this.tryConsumeRateLimit(r)){pr.log(this.wctx.workspaceDir,"SIGNAL_STRONG_RATE_LIMITED","STRONG signal suppressed by rate limit");return}let o=t.llmReason||(t.matchedTerms.length>0?`User correction detected: ${t.matchedTerms.join(", ")}`:"User correction detected");ll(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`correction_${PI()}`,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:r,agentId:"main",provenance:"openclaw_context_bound",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(n=>{pr.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(n)}`)})}routeWeak(t,r){try{let o=_Tn("sha256").update(`${t.evidence.detectedAt}:${r}`).digest("hex").slice(0,32);LD(r,20,o,this.wctx.workspaceDir,{source:"user_empathy"})}catch(o){pr.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(o)}`)}}tryConsumeRateLimit(t){let r=this.config.strongRateLimitPerHour,o=Date.now(),n=this.rateLimit.get(t);return(!n||o-n.windowStart>=bTn)&&(n={count:0,windowStart:o},this.rateLimit.set(t,n)),n.count>=r?!1:(n.count+=1,!0)}};function Mxr(e,t){try{let r=W4(e.workspaceDir,"signal_collector","signalCollector",t);if(!r.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${r.reason}`),null;if(r.readiness!=="not_ready"&&r.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${r.readiness}): ${r.reason}. ${r.nextAction}`),null;if(!r.provider||!r.model||!r.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let o=new nm({provider:r.provider,model:r.model,apiKeyEnv:r.apiKeyEnv,timeoutMs:r.timeoutMs??3e4,baseUrl:r.baseUrl??void 0,workspace:e.workspaceDir});return async(i,a)=>{let s=nse(i);try{let c=await o.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:r.timeoutMs??3e4}),u=await o.pollRun(c.runId),l=Date.now()+(r.timeoutMs??3e4);for(;u.status==="running"&&Date.now()<l;)await new Promise(g=>setTimeout(g,500)),u=await o.pollRun(c.runId);if(u.status!=="succeeded")return pr.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:u.status})),null;let p=(await o.fetchOutput(c.runId))?.payload,h="";if(typeof p=="string")h=p;else if(typeof p=="object"&&p!==null&&Object.hasOwn(p,"output")){let g=p.output;typeof g=="string"&&(h=g)}let f=ise(h);return f.valid?f.value:null}catch(c){return pr.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(r){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(r)}`),null}}var STn=6e4,Lxr=new Map,vTn=256,cqe=new Map;function TTn(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function ETn(e){if(typeof e!="object"||e===null)return;let t=TTn(e,"code");return typeof t=="string"?t:void 0}function RTn(e){let t=Lxr.get(e);return t||(t=new Map,Lxr.set(e,t)),t}function $xr(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function wTn(e,t,r){let o=e.trajectory?.listUserTurnsForSession?.(t)??[];return o.length>0?o.reduce((n,i)=>Math.max(n,i.turnIndex),0)+1:r.filter(n=>$xr(n,"user")).length+1}function kTn(e,t,r){let o=cqe.get(e);o||(o=new Set,cqe.set(e,o));let n=`${t}\0${r}`;if(o.has(n))return!1;if(o.add(n),o.size>vTn){let i=o.values().next().value;typeof i=="string"&&o.delete(i)}return!0}function ITn(e,t,r){return cqe.get(e)?.has(`${t}\0${r}`)??!1}function CTn(e,t){let r=RTn(t),o=Date.now(),n=r.get(e);try{let a=NI.statSync(e).mtimeMs;if(n&&o-n.loadedAt<STn&&n.mtime===a)return n.content;let s=NI.readFileSync(e,"utf8");return r.set(e,{content:s,mtime:a,loadedAt:o}),s}catch(i){return r.delete(e),ETn(i)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(i)}`),""}}var Dxr=new Map;function ATn(e,t){let r=Dxr.get(e.workspaceDir);if(!r){let o=Mxr(e,t);r=new Zse(e,{llmClassifier:o}),Dxr.set(e.workspaceDir,r)}return r}function MI(e){return{...Pp(e).effective.resolvedContextInjection}}async function zxr(e,t){let{workspaceDir:r}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!r}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!r){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let n=no.fromHookContext(t),{runId:i,sessionKey:a,trigger:s,sessionId:c}=t,u=sqe(s),l=t.api;c&&n.trajectory?.recordSession?.({sessionId:c});let m=null;if(c&&u&&e.messages.some($t=>$xr($t,"assistant"))){let $t=n.trajectory?.listAssistantTurns?.(c)??[];m=$t[$t.length-1]?.id??null}let p=MI(n.workspaceDir),h=Dse(s,c),f=c?Sm(c):void 0,g,y="",T="";s==="user"&&c&&f&&f.currentGfi>=100&&xh(c,r),g=exr();let v=txr(),{message:E,isAgentToAgent:L}=Zyr(e.prompt,c),H=!1;if(u&&c&&l&&!L&&(H=!0),E&&c&&u&&!L&&(i&&ITn(n.workspaceDir,a??c,i)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${i}, sessionId=${c.substring(0,20)}`):(i||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${c.substring(0,20)}`),ATn(n,o).detectSync(E,c,s??"api",{referencesAssistantTurnId:m,turnIndex:wTn(n,c,e.messages)}),i&&kTn(n.workspaceDir,a??c,i))),s==="heartbeat"||s==="cron"){if(c){let fr=Dyr(c);if(fr>=1){let Ot=Lyr(c,fr);Ot&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${fr}min elapsed, GFI now ${Ot.currentGfi.toFixed(1)}`)}}let $t=n.resolve("HEARTBEAT");if(NI.existsSync($t))try{let fr=NI.readFileSync($t,"utf8");y+=rxr(fr)}catch(fr){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(fr)}`)}}let B="";try{let $t=n.evolutionReducer.getActivePrinciples();$t.length>0&&(B=oxr($t))}catch($t){o?.warn?.(`[PD:Prompt] Failed to load core principles from reducer: ${String($t)}`)}let Te="";if(p.thinkingOs){let $t=n.resolve("THINKING_OS");try{let fr=CTn($t,n.workspaceDir);fr&&(Te=fr.trim())}catch(fr){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(fr)}`)}}let Ce="",ye="";if(!h&&p.projectFocus!=="off"){let $t=n.resolve("CURRENT_FOCUS"),fr=_h.getExtensionRoot(),{content:Ot,recovered:vr,validationErrors:Zr}=Xyr($t,fr||"",o);if(vr&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Zr.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Zr.join(", ")}`),Ot.trim())try{let{stateDir:Di}=n,aa=Hyr($t,r,Di);aa.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${aa.oldLines} \u2192 ${aa.newLines} lines. Milestones archived: ${aa.milestonesArchived}`):aa.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${aa.reason}`);let mr=aa.newContent?.trim()||Ot.trim();if(mr){let Eo=ij(mr);if(Eo&&(ye=aj(Eo)),p.projectFocus==="summary")Ce=$D(mr,30);else{let fn=await Vyr($t,3);if(fn.length>0){let au=fn.map((ai,Ji)=>`
2058
2058
  ---
2059
2059
 
2060
2060
  **\u5386\u53F2\u7248\u672C v${fn.length-Ji}**
@@ -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.11",
5
+ "version": "1.197.12",
6
6
  "activation": {
7
7
  "onCapabilities": [
8
8
  "hook"
@@ -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.11",
5
+ "version": "1.197.12",
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.11",
3
+ "version": "1.197.12",
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",