create-principles-disciple 1.124.2 → 1.125.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/core/dist/index.d.ts +3 -3
  2. package/core/dist/index.js +3 -3
  3. package/core/dist/runtime-v2/__tests__/pain-signal-observability.test.js +93 -0
  4. package/core/dist/runtime-v2/__tests__/pain-signal-observability.test.js.map +1 -1
  5. package/core/dist/runtime-v2/index.d.ts +2 -0
  6. package/core/dist/runtime-v2/index.d.ts.map +1 -1
  7. package/core/dist/runtime-v2/index.js.map +1 -1
  8. package/core/dist/runtime-v2/pain-signal-bridge.d.ts +8 -1
  9. package/core/dist/runtime-v2/pain-signal-bridge.d.ts.map +1 -1
  10. package/core/dist/runtime-v2/pain-signal-bridge.js.map +1 -1
  11. package/core/dist/runtime-v2/pain-signal-observability.d.ts.map +1 -1
  12. package/core/dist/runtime-v2/pain-signal-observability.js +25 -10
  13. package/core/dist/runtime-v2/pain-signal-observability.js.map +1 -1
  14. package/core/package.json +0 -1
  15. package/host-runtime/dist/governance-signal-admission.js +11 -5
  16. package/host-runtime/dist/index.d.ts +3 -0
  17. package/host-runtime/dist/index.js +1 -0
  18. package/host-runtime/dist/production-pain-evidence.d.ts +7 -0
  19. package/host-runtime/dist/production-pain-evidence.js +9 -4
  20. package/package.json +1 -1
  21. package/pd-cli/dist/commands/pain-list.d.ts +45 -0
  22. package/pd-cli/dist/commands/pain-list.d.ts.map +1 -0
  23. package/pd-cli/dist/commands/pain-list.js +165 -0
  24. package/pd-cli/dist/commands/pain-list.js.map +1 -0
  25. package/pd-cli/dist/index.js +11 -0
  26. package/pd-cli/dist/index.js.map +1 -1
  27. package/plugin/dist/bundle.js +27 -23
  28. package/plugin/dist/core/trajectory-types.d.ts +2 -0
  29. package/plugin/dist/rulehost-evidence.js +9 -7
  30. package/core/dist/adapters/__tests__/code-review-pain-adapter.test.d.ts +0 -2
  31. package/core/dist/adapters/__tests__/code-review-pain-adapter.test.d.ts.map +0 -1
  32. package/core/dist/adapters/__tests__/code-review-pain-adapter.test.js +0 -346
  33. package/core/dist/adapters/__tests__/code-review-pain-adapter.test.js.map +0 -1
  34. package/core/dist/adapters/__tests__/openclaw-pain-adapter.test.d.ts +0 -2
  35. package/core/dist/adapters/__tests__/openclaw-pain-adapter.test.d.ts.map +0 -1
  36. package/core/dist/adapters/__tests__/openclaw-pain-adapter.test.js +0 -290
  37. package/core/dist/adapters/__tests__/openclaw-pain-adapter.test.js.map +0 -1
  38. package/core/dist/adapters/__tests__/writing-pain-adapter.test.d.ts +0 -2
  39. package/core/dist/adapters/__tests__/writing-pain-adapter.test.d.ts.map +0 -1
  40. package/core/dist/adapters/__tests__/writing-pain-adapter.test.js +0 -239
  41. package/core/dist/adapters/__tests__/writing-pain-adapter.test.js.map +0 -1
  42. package/core/dist/adapters/code-review/code-review-pain-adapter.d.ts +0 -13
  43. package/core/dist/adapters/code-review/code-review-pain-adapter.d.ts.map +0 -1
  44. package/core/dist/adapters/code-review/code-review-pain-adapter.js +0 -139
  45. package/core/dist/adapters/code-review/code-review-pain-adapter.js.map +0 -1
  46. package/core/dist/adapters/code-review/index.d.ts +0 -6
  47. package/core/dist/adapters/code-review/index.d.ts.map +0 -1
  48. package/core/dist/adapters/code-review/index.js +0 -2
  49. package/core/dist/adapters/code-review/index.js.map +0 -1
  50. package/core/dist/adapters/code-review/review-event-types.d.ts +0 -54
  51. package/core/dist/adapters/code-review/review-event-types.d.ts.map +0 -1
  52. package/core/dist/adapters/code-review/review-event-types.js +0 -8
  53. package/core/dist/adapters/code-review/review-event-types.js.map +0 -1
  54. package/core/dist/adapters/coding/index.d.ts +0 -6
  55. package/core/dist/adapters/coding/index.d.ts.map +0 -1
  56. package/core/dist/adapters/coding/index.js +0 -5
  57. package/core/dist/adapters/coding/index.js.map +0 -1
  58. package/core/dist/adapters/coding/openclaw-event-types.d.ts +0 -26
  59. package/core/dist/adapters/coding/openclaw-event-types.d.ts.map +0 -1
  60. package/core/dist/adapters/coding/openclaw-event-types.js +0 -9
  61. package/core/dist/adapters/coding/openclaw-event-types.js.map +0 -1
  62. package/core/dist/adapters/coding/openclaw-pain-adapter.d.ts +0 -27
  63. package/core/dist/adapters/coding/openclaw-pain-adapter.d.ts.map +0 -1
  64. package/core/dist/adapters/coding/openclaw-pain-adapter.js +0 -102
  65. package/core/dist/adapters/coding/openclaw-pain-adapter.js.map +0 -1
  66. package/core/dist/adapters/writing/index.d.ts +0 -6
  67. package/core/dist/adapters/writing/index.d.ts.map +0 -1
  68. package/core/dist/adapters/writing/index.js +0 -5
  69. package/core/dist/adapters/writing/index.js.map +0 -1
  70. package/core/dist/adapters/writing/writing-pain-adapter.d.ts +0 -22
  71. package/core/dist/adapters/writing/writing-pain-adapter.d.ts.map +0 -1
  72. package/core/dist/adapters/writing/writing-pain-adapter.js +0 -62
  73. package/core/dist/adapters/writing/writing-pain-adapter.js.map +0 -1
  74. package/core/dist/adapters/writing/writing-types.d.ts +0 -34
  75. package/core/dist/adapters/writing/writing-types.d.ts.map +0 -1
  76. package/core/dist/adapters/writing/writing-types.js +0 -9
  77. package/core/dist/adapters/writing/writing-types.js.map +0 -1
  78. package/core/dist/pain-signal-adapter.d.ts +0 -37
  79. package/core/dist/pain-signal-adapter.d.ts.map +0 -1
  80. package/core/dist/pain-signal-adapter.js +0 -2
  81. package/core/dist/pain-signal-adapter.js.map +0 -1
  82. package/core/dist/pain-signal.d.ts +0 -16
  83. package/core/dist/pain-signal.d.ts.map +0 -1
  84. package/core/dist/pain-signal.js +0 -15
  85. package/core/dist/pain-signal.js.map +0 -1
  86. package/core/dist/runtime-v2/__tests__/pain-signal-unification.test.d.ts +0 -2
  87. package/core/dist/runtime-v2/__tests__/pain-signal-unification.test.d.ts.map +0 -1
  88. package/core/dist/runtime-v2/__tests__/pain-signal-unification.test.js +0 -150
  89. package/core/dist/runtime-v2/__tests__/pain-signal-unification.test.js.map +0 -1
@@ -1134,6 +1134,7 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
1134
1134
  text TEXT,
1135
1135
  canonical_pain_id TEXT,
1136
1136
  runtime_task_id TEXT,
1137
+ host_kind TEXT,
1137
1138
  created_at TEXT NOT NULL
1138
1139
  );
1139
1140
  CREATE TABLE IF NOT EXISTS gate_blocks (
@@ -1231,7 +1232,7 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
1231
1232
  metadata_json TEXT,
1232
1233
  created_at TEXT NOT NULL
1233
1234
  );
1234
- `);try{e.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(o){let a=o instanceof Error?o.message:String(o);if(!a.includes("duplicate column name")&&!a.includes("no column named"))throw o}for(let o of[{name:"canonical_pain_id",type:"TEXT"},{name:"runtime_task_id",type:"TEXT"}])try{e.exec(`ALTER TABLE pain_events ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}let r=[{table:"assistant_turns",name:"stop_reason",type:"TEXT"},{table:"assistant_turns",name:"thinking_blocks_count",type:"INTEGER"},{table:"tool_calls",name:"result_preview",type:"TEXT"}];for(let o of r)try{e.exec(`ALTER TABLE ${o.table} ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}e.exec(`
1235
+ `);try{e.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(o){let a=o instanceof Error?o.message:String(o);if(!a.includes("duplicate column name")&&!a.includes("no column named"))throw o}for(let o of[{name:"canonical_pain_id",type:"TEXT"},{name:"runtime_task_id",type:"TEXT"},{name:"host_kind",type:"TEXT"}])try{e.exec(`ALTER TABLE pain_events ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}let r=[{table:"assistant_turns",name:"stop_reason",type:"TEXT"},{table:"assistant_turns",name:"thinking_blocks_count",type:"INTEGER"},{table:"tool_calls",name:"result_preview",type:"TEXT"}];for(let o of r)try{e.exec(`ALTER TABLE ${o.table} ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}e.exec(`
1235
1236
  CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id
1236
1237
  ON pain_events(canonical_pain_id)
1237
1238
  WHERE canonical_pain_id IS NOT NULL
@@ -1257,16 +1258,17 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
1257
1258
  INSERT INTO sessions (session_id, started_at, updated_at)
1258
1259
  VALUES (?, ?, ?)
1259
1260
  ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
1260
- `).run(l,r,r);try{let f=c.prepare(`
1261
+ `).run(l,r,r);let f=[];try{let m=c.prepare(`
1261
1262
  INSERT INTO pain_events (
1262
1263
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
1263
- canonical_pain_id, runtime_task_id
1264
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1265
- `).run(l,n.source,n.score??80,Dc(n.reason??"",i),qUe(n.score??80),n.source==="manual"?"user_manual":"system_infer",1,Dc(n.reason??"",i),r,o??null,a??null);return Number(f.lastInsertRowid)}catch(f){if(o&&f instanceof Error&&f.message.includes("UNIQUE constraint failed")&&f.message.includes("canonical_pain_id")){c.prepare(`
1264
+ canonical_pain_id, runtime_task_id, host_kind
1265
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
1266
+ `).run(l,n.source,n.score??80,Dc(n.reason??"",i),qUe(n.score??80),n.source==="manual"?"user_manual":"system_infer",1,Dc(n.reason??"",i),r,o??null,a??null,n.hostKind??null);return{id:Number(m.lastInsertRowid),warnings:f}}catch(m){if(o&&m instanceof Error&&m.message.includes("UNIQUE constraint failed")&&m.message.includes("canonical_pain_id")){c.prepare(`
1266
1267
  UPDATE pain_events
1267
- SET runtime_task_id = COALESCE(?, runtime_task_id)
1268
+ SET runtime_task_id = COALESCE(?, runtime_task_id),
1269
+ host_kind = COALESCE(host_kind, ?)
1268
1270
  WHERE canonical_pain_id = ?
1269
- `).run(a??null,o);let m=c.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(o);return m&&typeof m=="object"&&Object.hasOwn(m,"id")&&typeof m.id=="number"?m.id:void 0}throw f}}finally{c.close()}}function Eq(e){let t=Vqt(),n=[],r=e.data.score??80,i=e.data.sessionId??"cli",o=zqt(t),a={warnings:n};try{let s=sx.join(e.stateDir,"logs",`events_${o}.jsonl`);jUe(s,{ts:t,date:o,type:"pain_signal",category:"detected",sessionId:i,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:r,source:e.data.source,reason:Dc(e.data.reason??"",e.workspaceDir),severity:qUe(r),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){n.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=sx.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Dc(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};jUe(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){n.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{a.trajectoryPainEventId=Qqt({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId})}catch(s){n.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function Zqt(e){if(e.errorCategory)return gA[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 eGt(e){if(e instanceof H&&e.category)return gA[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 Ny=class{opts;constructor(t){this.opts=t}async recordPain(t){let n=Date.now(),{painId:r}=t,i=t.taskId??cv(r),o={painId:r,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:i,traceId:t.traceId,provenance:t.provenance,hostKind:t.hostKind,evidence:t.evidence};try{if(this.opts.asyncMode){let p=await(await Tq({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(o),f=[];t.recordObservability!==!1&&(f=Eq({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:o,canonicalPainId:r,runtimeTaskId:p.taskId}).warnings);let m=Date.now()-n;return{status:"submitted",painId:r,taskId:p.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:f,latencyMs:m,message:`Diagnosis submitted. Use 'pd task show ${p.taskId}' to check progress.`}}let s=await(await Tq({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(o),c=[];t.recordObservability!==!1&&(c=Eq({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:o,canonicalPainId:r,runtimeTaskId:i}).warnings);let l=Date.now()-n;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:Zqt(s),latencyMs:l}}catch(a){let s=Date.now()-n;return{status:"failed",painId:r,taskId:i,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:eGt(a),latencyMs:s}}}};var Xte=[{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"}],nGt=Xte.map(e=>({pattern:e.pattern,description:e.description}));function Jte(e,t){let n=e.replace(/\\/g,"/");return n===t||n.endsWith("/"+t)}function Qte(e,t){if(e.length===0)return{migrated:e,changed:!1};let n=Xte.filter(f=>f.filenameSuffixes.some(m=>Jte(t,m)));if(n.length===0)return{migrated:e,changed:!1};let r=n.filter(f=>f.actionType==="remove-line"),i=n.filter(f=>f.actionType==="replace"),o=[],a=!1,s=e.split(`
1271
+ `).run(a??null,n.hostKind??null,o);let y=c.prepare("SELECT id, host_kind FROM pain_events WHERE canonical_pain_id = ?").get(o);if(y&&typeof y=="object"&&Object.hasOwn(y,"id")&&typeof y.id=="number"){let _=Object.getOwnPropertyDescriptor(y,"host_kind")?.value;return n.hostKind&&typeof _=="string"&&_!==n.hostKind&&f.push(`host_kind_conflict:kept=${_},rejected=${n.hostKind}`),{id:y.id,warnings:f}}return{id:void 0,warnings:f}}throw m}}finally{c.close()}}function Eq(e){let t=Vqt(),n=[],r=e.data.score??80,i=e.data.sessionId??"cli",o=zqt(t),a={warnings:n};try{let s=sx.join(e.stateDir,"logs",`events_${o}.jsonl`);jUe(s,{ts:t,date:o,type:"pain_signal",category:"detected",sessionId:i,workspaceDir:e.workspaceDir,data:{eventId:e.data.painId,score:r,source:e.data.source,reason:Dc(e.data.reason??"",e.workspaceDir),severity:qUe(r),origin:e.data.source==="manual"?"user_manual":"system_infer"}}),a.eventLogPath=s}catch(s){n.push(`event log write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=sx.join(e.workspaceDir,"memory","evolution.jsonl"),c={painId:e.data.painId,painType:e.data.painType,source:e.data.source,reason:Dc(e.data.reason??"",e.workspaceDir),score:e.data.score,sessionId:e.data.sessionId,provenance:e.data.provenance,evidenceCount:e.data.evidence?.length??0};jUe(s,{ts:t,type:"pain_detected",data:c}),a.evolutionStreamPath=s}catch(s){n.push(`evolution stream write failed: ${s instanceof Error?s.message:String(s)}`)}try{let s=Qqt({stateDir:e.stateDir,data:e.data,timestamp:t,workspaceDir:e.workspaceDir,canonicalPainId:e.canonicalPainId,runtimeTaskId:e.runtimeTaskId});a.trajectoryPainEventId=s.id,n.push(...s.warnings)}catch(s){n.push(`trajectory pain_events write failed: ${s instanceof Error?s.message:String(s)}`)}return a}function Zqt(e){if(e.errorCategory)return gA[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 eGt(e){if(e instanceof H&&e.category)return gA[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 Ny=class{opts;constructor(t){this.opts=t}async recordPain(t){let n=Date.now(),{painId:r}=t,i=t.taskId??cv(r),o={painId:r,painType:t.painType,source:t.source,reason:t.reason,score:t.score,sessionId:t.sessionId,agentId:t.agentId,taskId:i,traceId:t.traceId,provenance:t.provenance,hostKind:t.hostKind,evidence:t.evidence};try{if(this.opts.asyncMode){let p=await(await Tq({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(o),f=[];t.recordObservability!==!1&&(f=Eq({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:o,canonicalPainId:r,runtimeTaskId:p.taskId}).warnings);let m=Date.now()-n;return{status:"submitted",painId:r,taskId:p.taskId,candidateIds:[],ledgerEntryIds:[],observabilityWarnings:f,latencyMs:m,message:`Diagnosis submitted. Use 'pd task show ${p.taskId}' to check progress.`}}let s=await(await Tq({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(o),c=[];t.recordObservability!==!1&&(c=Eq({workspaceDir:this.opts.workspaceDir,stateDir:this.opts.stateDir,data:o,canonicalPainId:r,runtimeTaskId:i}).warnings);let l=Date.now()-n;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:Zqt(s),latencyMs:l}}catch(a){let s=Date.now()-n;return{status:"failed",painId:r,taskId:i,candidateIds:[],ledgerEntryIds:[],message:a instanceof Error?a.message:String(a),observabilityWarnings:[],failureCategory:eGt(a),latencyMs:s}}}};var Xte=[{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"}],nGt=Xte.map(e=>({pattern:e.pattern,description:e.description}));function Jte(e,t){let n=e.replace(/\\/g,"/");return n===t||n.endsWith("/"+t)}function Qte(e,t){if(e.length===0)return{migrated:e,changed:!1};let n=Xte.filter(f=>f.filenameSuffixes.some(m=>Jte(t,m)));if(n.length===0)return{migrated:e,changed:!1};let r=n.filter(f=>f.actionType==="remove-line"),i=n.filter(f=>f.actionType==="replace"),o=[],a=!1,s=e.split(`
1270
1272
  `),c=[];for(let f of s){let m=!1;for(let y of r)if(y.pattern.test(f)){m=!0,o.includes(y.description)||o.push(y.description),Jte(t,"MEMORY.md")&&(a=!0);break}m||c.push(f)}let l=c.join(`
1271
1273
  `);for(let f of i){let m=f.replacement??"",y=l,_=f.pattern.flags.includes("g")?f.pattern.flags:f.pattern.flags+"g",b=new RegExp(f.pattern.source,_);l=l.replace(b,m),l!==y&&!o.includes(f.description)&&o.push(f.description)}if(a){let f="[Historical: confirm-first gate was removed in PRI-286. This section is preserved for reference only.]";l.endsWith(`
1272
1274
  `)||(l=l+`
@@ -1905,12 +1907,12 @@ try {
1905
1907
  `).all(dK+1);if(!Array.isArray(b))So(i,"activation_query_invalid","inspect state.db schema and integrity");else{if(b.length>dK)return{decision:"allow",source:n.source,warnings:[bc(`active_rule_limit_exceeded: maximum ${dK}`,"deactivate excess active RuleHost rules and retry")],metadata:{evaluatedLiveRules:0}};{for(let K of b){if(!Mh(K)||typeof K.content_bytes!="number"||!Number.isSafeInteger(K.content_bytes)||K.content_bytes<0)return{decision:"allow",source:n.source,warnings:[bc("artifact_content_size_invalid","inspect state.db artifact content integrity")],metadata:{evaluatedLiveRules:0}};if(K.content_bytes>kD){let ce=typeof K.activation_id=="string"?K.activation_id:"unknown";return{decision:"allow",source:n.source,warnings:[bc(`artifact_content_budget_exceeded: activation=${ce} bytes=${K.content_bytes} maximum=${kD}`,"reduce the active artifact envelope and reactivate the rule")],metadata:{evaluatedLiveRules:0}}}}let U=new Map;for(let K of b){if(!Mh(K)||typeof K.target_ref!="string"||K.target_ref.length===0){So(i,"activation_row_invalid","deactivate and recreate the malformed activation");continue}let ce=typeof K.activation_id=="string"?K.activation_id:"unknown";if(K.enforcement==="safety_isolated"){So(i,`activation_safety_isolated: ${ce}`,"recover the activation to shadow after reviewing safety evidence");continue}if(K.enforcement!=="eligible"){So(i,`activation_control_state_invalid: ${ce}`,"repair the activation control state before RuleCode enforcement");continue}let ie=U.get(K.target_ref)??[];ie.push(K),U.set(K.target_ref,ie)}for(let[K,ce]of U){if(ce.length!==1){So(i,`duplicate_active_activation: ${K}`,"deactivate all but one activation for this target_ref");continue}let[ie]=ce;if(!ie||ie.action!=="code_tool_hook_live_activate")continue;let Se=ie.activation_id,Ge=ie.artifact_id,Ie=ie.content_bytes;if(typeof Se!="string"||typeof Ge!="string"||typeof Ie!="number"){So(i,"activation_required_fields_invalid","deactivate and recreate the activation");continue}let he=m.getDb().prepare(`
1906
1908
  SELECT content_json, length(CAST(content_json AS BLOB)) AS content_bytes
1907
1909
  FROM pi_artifacts WHERE artifact_id = ?
1908
- `).get(Ge);if(!Mh(he)||typeof he.content_json!="string"||typeof he.content_bytes!="number"||!Number.isSafeInteger(he.content_bytes)){So(i,`activation_artifact_invalid: ${Se}`,"inspect state.db artifact content integrity");continue}let ke=he.content_json,pe=Buffer.byteLength(ke,"utf8");if(he.content_bytes>kD||pe>kD)return{decision:"allow",source:n.source,warnings:[bc(`artifact_content_budget_exceeded: activation=${Se} bytes=${Math.max(he.content_bytes,pe)} maximum=${kD}`,"reduce the active artifact envelope and reactivate the rule")],metadata:{evaluatedLiveRules:0}};if(he.content_bytes!==Ie||pe!==he.content_bytes)return{decision:"allow",source:n.source,warnings:[bc(`artifact_content_size_changed: activation=${Se}`,"retry after the active artifact update completes")],metadata:{evaluatedLiveRules:0}};try{let Ne=JSON.parse(ke);if(!Mh(Ne)||typeof Ne.implementationCode!="string"||Ne.implementationCode.length===0){So(i,`activation_artifact_invalid: ${Se}`,"regenerate the rule artifact with implementationCode");continue}let st=Buffer.byteLength(Ne.implementationCode,"utf8");if(st>qae)return{decision:"allow",source:n.source,warnings:[bc(`rule_source_budget_exceeded: activation=${Se} bytes=${st}`,`reduce each RuleCode source below ${qae} bytes`)],metadata:{evaluatedLiveRules:0}};if(Object.hasOwn(Ne,"requiresContextVersion")){if(Ne.requiresContextVersion!==2){So(i,`unsupported_context_version: ${String(Ne.requiresContextVersion)}`,"regenerate the rule artifact for context version 2");continue}if(!l){So(i,"rule_context_v2_unavailable","enable and wire the host rule context provider");continue}}let bt=typeof Ne.ruleId=="string"?Ne.ruleId:typeof ie.source_rule_id=="string"?ie.source_rule_id:Ge,it=typeof Ne.principleId=="string"?Ne.principleId:typeof ie.source_principle_id=="string"?ie.source_principle_id:bt,xe=c8e(Ne.implementationCode);if(xe.length>0){So(i,`legacy_rule_contract_dependency: ${xe.join(", ")} (activation=${Se})`,"migrate the RuleCode off the retired contract symbols or deactivate the activation, then re-approve a migrated rule");continue}let pt={name:Se,version:"1",ruleId:bt,coversCondition:"all"};y.push({implId:Se,ruleId:bt,principleId:it,meta:_nn(Ne.meta)?Ne.meta:pt,source:Ne.implementationCode})}catch(Ne){So(i,`implementation_unhealthy: ${Ne instanceof Error?Ne.message:String(Ne)}`,"fix the RuleCode and reactivate the rule")}}}}let I={action:c,workspace:{isRiskPath:!1},session:{sessionId:n.context.sessionId,currentGfi:u.currentGfi},evolution:{epTier:u.epTier},derived:{estimatedLineChanges:tk({toolName:o.toolName,params:o.params}),bashRisk:u.bashRisk},...l?{context:l}:{}},E=y.reduce((U,K)=>U+Buffer.byteLength(K.source,"utf8"),0);if(E>Gae)return{decision:"allow",source:n.source,warnings:[bc(`rule_source_budget_exceeded: batchBytes=${E}`,`reduce total active RuleCode below ${Gae} bytes`)],metadata:{evaluatedLiveRules:0}};let R=y.map(U=>({source:U.source,filename:`activation-${U.implId}`})),A=Bae(r);if(A<=0)return{decision:"allow",source:n.source,warnings:[bc("gate_deadline_exceeded","reduce active RuleCode count or source size and retry")],metadata:{evaluatedLiveRules:0}};let P=t.evaluateBatch(R,I,A);if(!P.ok||!P.results)return{decision:"allow",source:n.source,warnings:[bc(`${P.reason??"rule_batch_failed"}: ${P.detail??"unknown failure"}`,"inspect active RuleCode resource use and repair or deactivate the unhealthy rule")],metadata:{evaluatedLiveRules:0}};let O=P.results.find(U=>!U.ok&&U.error?.includes("timed out"));if(O)return{decision:"allow",source:n.source,warnings:[bc(`rule_batch_timeout: ${O.error??"unknown child timeout"}`,"fix or deactivate the unhealthy RuleCode and retry")],metadata:{evaluatedLiveRules:0}};let $=[];for(let U=0;U<y.length;U+=1){let K=y[U],ce=P.results[U];if(!K||!ce){So(i,"rule_batch_result_missing","inspect the RuleCode runtime result contract");continue}if(!ce.ok){So(i,`implementation_unhealthy: ${ce.error??"unknown child error"}`,"fix the RuleCode and reactivate the rule");continue}let ie=c_(ce.result);if(!xnn(ce.result)){So(i,`invalid RuleHostResult: ${ie.errors.join("; ")}`,"fix the RuleCode result and reactivate the rule");continue}let Se=ce.result.matched?{...ce.result,ruleId:K.ruleId,principleId:K.principleId}:ce.result;$.push({...K,evaluate:()=>Se})}let M=WL($,I,{warn(U){So(i,U,"inspect the unhealthy activation and RuleCode output")}});return M?.decision==="block"?M.reason.trim().length===0?(So(i,"deny_reason_missing","fix the RuleCode to return a non-empty block reason"),{decision:"allow",source:n.source,warnings:i,metadata:{evaluatedLiveRules:$.length}}):{decision:"deny",reason:M.reason,source:n.source,...i.length?{warnings:i}:{},metadata:{evaluatedLiveRules:$.length,ruleId:M.ruleId,principleId:M.principleId}}:{decision:"allow",source:n.source,...i.length?{warnings:i}:{},metadata:{evaluatedLiveRules:$.length,ruleDecision:M?.decision??"allow"}}}catch(_){return So(i,`activation_read_failed: ${_ instanceof Error?_.message:String(_)}`,"inspect state.db schema and integrity"),{decision:"allow",source:n.source,warnings:i,metadata:{evaluatedLiveRules:0}}}finally{m.close()}}}import{createHash as Hae}from"node:crypto";import bnn from"node:fs";import m_ from"node:path";import Inn from"better-sqlite3";var wnn=new Set(["write","edit","apply_patch","write_file","edit_file","replace"]);var Kae=500,f8e=900*1e3,pK=new Map;function fK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function co(e,t){if(!(!fK(e)||!Object.hasOwn(e,t)))return Object.getOwnPropertyDescriptor(e,t)?.value}function Tnn(e){let t="context"in e?e.context:e,n=t.toolOutput,r=co(n,"result")??n,i=co(n,"error"),o=co(r,"exitCode"),a=co(co(r,"details"),"exitCode"),s=typeof o=="number"?o:typeof a=="number"?a:0,c=i==null||i===""?void 0:String(i),l=co(n,"durationMs");return{failure:c!==void 0||s!==0,exitCode:s,...c?{error:c.slice(0,Kae)}:{},...typeof l=="number"&&Number.isFinite(l)&&l>=0?{durationMs:l}:{},params:t.toolInput??{},result:r}}function m8e(e){return Array.isArray(e)&&e.length<=8&&e.every(t=>fK(t)&&typeof co(t,"sourceRef")=="string"&&String(co(t,"sourceRef")).trim().length>0&&String(co(t,"sourceRef")).length<=300&&typeof co(t,"note")=="string"&&String(co(t,"note")).length<=200)}function Enn(e){if(e===void 0)return{};if(!fK(e))return null;let t=co(e,"painScore"),n=co(e,"isRisky"),r=co(e,"consecutiveErrors"),i=co(e,"evidence"),o=co(e,"eventId"),a=co(e,"relativePath"),s=co(e,"agentId"),c=co(e,"errorHash");if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0||t>100)||n!==void 0&&typeof n!="boolean"||r!==void 0&&(typeof r!="number"||!Number.isInteger(r)||r<0))return null;for(let l of["eventId","relativePath","agentId","errorHash"]){let u=co(e,l);if(u!==void 0&&(typeof u!="string"||u.trim().length===0||u.length>500))return null}return i!==void 0&&!m8e(i)?null:{...typeof o=="string"?{eventId:o}:{},...typeof t=="number"?{painScore:t}:{},...typeof n=="boolean"?{isRisky:n}:{},...typeof r=="number"?{consecutiveErrors:r}:{},...typeof a=="string"?{relativePath:a}:{},...typeof s=="string"?{agentId:s}:{},...typeof c=="string"?{errorHash:c}:{},...m8e(i)?{evidence:i}:{}}}function uk(e,t=new WeakSet){return e===null||typeof e!="object"?JSON.stringify(typeof e=="string"?e.slice(0,2e3):typeof e=="number"||typeof e=="boolean"?e:String(e)):t.has(e)?'"[circular]"':(t.add(e),Array.isArray(e)?`[${e.slice(0,50).map(r=>uk(r,t)).join(",")}]`:`{${Object.keys(e).sort().slice(0,50).map(r=>`${JSON.stringify(r)}:${uk(co(e,r),t)}`).join(",")}}`)}function Snn(e){try{let t=uk(e);return t.length>Kae?`${t.slice(0,Kae-3)}...`:t}catch{return"[result_preview_unavailable]"}}function knn(e){let{outcome:t,sanitizedParams:n,canonicalEventId:r}=e,i=uk({workspaceDir:m_.resolve(e.workspaceDir),sessionId:e.sessionId,turnId:e.turnId??null,toolName:e.toolName,source:e.source,suppliedEventId:r??null,params:n,result:Fp(t.result,0,e.workspaceDir),error:t.error??null,exitCode:t.exitCode,failure:t.failure}),o=Hae("sha256").update(i).digest("hex");return{eventId:`host_${o}`,painId:`pain_host_${o}`}}function Vae(e){let t=uk({workspaceDir:m_.resolve(e.workspaceDir),sessionId:e.sessionId,occurrenceId:e.occurrenceId,source:"user_correction",text:e.text}),n=Hae("sha256").update(t).digest("hex");return{eventId:`host_${n}`,painId:`pain_host_${n}`}}var Ann={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",gfi_before:"REAL",gfi_after:"REAL",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",created_at:"TEXT"}};function zx(e,t){return fK(e)&&Object.hasOwn(e,t)?Object.getOwnPropertyDescriptor(e,t)?.value:void 0}function Rnn(e){let t=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?").get("idx_pain_events_canonical_pain_id"),n=zx(t,"sql");if(typeof n!="string"||n.length===0||n.length>2e3)return!1;let r=n.replace(/["'`]/g,"").replace(/\[|\]/g,"").replace(/\s+/g," ").trim().replace(/;$/,"").toUpperCase(),i=r.indexOf(" WHERE ");return i>=0&&r.slice(i+7)==="CANONICAL_PAIN_ID IS NOT NULL"}function h8e(e){for(let[i,o]of Object.entries(Ann)){let a=e.prepare(`PRAGMA table_info(${i})`).all(),s=new Map;for(let c of a){let l=zx(c,"name"),u=zx(c,"type");if(typeof l!="string"||typeof u!="string")return!1;s.set(l,u.toUpperCase())}for(let[c,l]of Object.entries(o))if(s.get(c)!==l)return!1}let n=e.prepare("PRAGMA index_list(pain_events)").all().find(i=>zx(i,"name")==="idx_pain_events_canonical_pain_id");if(zx(n,"unique")!==1||zx(n,"partial")!==1||!Rnn(e))return!1;let r=e.prepare("PRAGMA index_info(idx_pain_events_canonical_pain_id)").all();return r.length!==1||zx(r[0],"name")!=="canonical_pain_id"?!1:(e.prepare("SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?"),e.prepare("SELECT 1 FROM pain_events WHERE canonical_pain_id = ?"),e.prepare("INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at"),e.prepare("INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),e.prepare("INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),!0)}function g8e(e={}){return async t=>{let n=m_.join(t.context.workspaceDir,".state","trajectory.db");if(!bnn.existsSync(n))return{decision:"observe",source:t.source,warnings:["trajectory_db_not_found"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"initialize the selected PD workspace before retrying the hook"}};let r;try{if(r=e.painDatabaseFactory?e.painDatabaseFactory(n):new Inn(n),r.pragma("busy_timeout = 5000"),!h8e(r))return r.close(),r=void 0,{decision:"observe",source:t.source,warnings:["trajectory_schema_invalid"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"run the supported PD workspace migration"}}}catch(Se){try{r?.close()}catch{}return{decision:"observe",source:t.source,warnings:[`trajectory_database_unavailable:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"inspect or repair the selected PD trajectory database"}}}let i=[],o;try{o=Enn(await e.painEnrichmentProvider?.(t))}catch(Se){i.push(`pain_enrichment_failed:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`),o=null}if(!o){try{r.close()}catch{}return{decision:"observe",source:t.source,warnings:i.length>0?i:["pain_enrichment_invalid"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"inspect host pain enrichment input"}}}let a=Tnn(t),s=MA(a.params,t.context.workspaceDir),c=t.context.toolName??"",l=Dh({toolName:c,error:a.error,exitCode:a.exitCode}),u=nu({observedAt:new Date().toISOString(),workspaceId:t.context.workspaceDir,sessionId:t.context.sessionId,toolName:c,failureSource:l.failureSource,toolNotFound:l.toolNotFound,nonZeroExit:a.exitCode!==0}),p=o.relativePath??String(co(a.params,"file_path")??co(a.params,"path")??"unknown").slice(0,500),f=o.isRisky??(m_.isAbsolute(p)&&!m_.resolve(p).startsWith(`${m_.resolve(t.context.workspaceDir)}${m_.sep}`)),m=o.painScore??Math.min(100,(a.exitCode!==0?70:0)+(f?20:0)),y=o.errorHash??Hae("sha256").update(a.error??String(a.exitCode)).digest("hex"),_=`${m_.resolve(t.context.workspaceDir)}:${t.context.sessionId}:${l.failureSource}:${y}`,b=pK.get(_),I=b!==void 0&&Date.now()-b<f8e,E=jx({sourceKind:u,score:m,consecutiveErrors:o.consecutiveErrors,isRisky:f}),R=ru({triageResult:E,isOwnerManual:!1,isCooldownActive:I,isValid:!0,score:m,sessionId:t.context.sessionId}),A=a.failure&&wnn.has(c)&&R.shouldCreateDiagnosticTask,{eventId:P,painId:O}=knn({workspaceDir:t.context.workspaceDir,sessionId:t.context.sessionId,...t.context.turnId!==void 0?{turnId:t.context.turnId}:{},...c!==void 0?{toolName:c}:{},source:t.source,...o.eventId?{canonicalEventId:o.eventId}:{},outcome:a,sanitizedParams:s}),$=new Date().toISOString(),M=uk(s),U=Snn({eventId:P,result:Fp(a.result,0,t.context.workspaceDir)}),K=!1,ce=!1;try{if(r.transaction(()=>{if(r.prepare("SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?").get(t.context.sessionId,c,M,a.failure?"failure":"success",a.exitCode,a.error??null,U)){K=!0,ce=r.prepare("SELECT 1 FROM pain_events WHERE canonical_pain_id = ?").get(O)!==void 0;return}if(r.prepare("INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at").run(t.context.sessionId,$,$),r.prepare("INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(t.context.sessionId,c,a.failure?"failure":"success",a.durationMs??null,a.exitCode,a.error?a.error.split(/[\s:]/,1)[0]:null,a.error??null,null,null,M,U,$),A){let Se=`tool=${c}; error=${a.error??`exit=${a.exitCode}`}; path=${p}`;r.prepare("INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(t.context.sessionId,l.failureSource??"tool_failure",m,Se,m>=70?"severe":m>=40?"moderate":"mild","system_infer",null,o.evidence?.map(Ge=>`${Ge.sourceRef}: ${Ge.note}`).join(`
1909
- `)??null,O,null,$)}})(),A&&!K){let Se=Date.now();for(let[Ge,Ie]of pK)Se-Ie>=f8e&&pK.delete(Ge);pK.set(_,Se)}}catch(Se){return{decision:"observe",source:t.source,warnings:[`trajectory_write_failed:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`],metadata:{outcome:a.failure?"failure":"success",admitted:!1,duplicate:!1,nextAction:"inspect the workspace trajectory database and retry"}}}finally{try{r.close()}catch{}}let ie=A||ce;return{decision:"observe",source:t.source,metadata:{eventId:P,painId:ie?O:null,outcome:a.failure?"failure":"success",admitted:ie,duplicate:K,sourceKind:u,failureSource:l.failureSource??null,triggerOutcome:R.outcome,triggerReason:R.reason,painScore:m,isRisky:f,relativePath:p,agentId:o.agentId??null,evidence:o.evidence??[]}}}}import sWi from"better-sqlite3";var lWi=10080*60*1e3;var uWi=10080*60*1e3;import y8e from"node:fs";import mK from"node:path";import vWi from"better-sqlite3";var _8e=70,v8e=5,TWi=3600*1e3;var hK="correction_keywords.json",zae=.7,x8e=[["\u8FD9\u662F\u9519\u7684",.9],["\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",.9],["\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",.9]],b8e=[["\u641E\u4EC0\u4E48",.5]];function Cnn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.term!="string"||t.term.length===0||typeof t.weight!="number"||!Number.isFinite(t.weight)?!1:t.source==="seed"||t.source==="llm"||t.source==="user"}function Pnn(e){return e==="llm"?"llm_learned":e==="user"?"owner_promoted":"seed"}function Onn(e,t){return e==="llm"?"ambiguous":t>=zae?"high":"ambiguous"}function Lnn(e){if(typeof e!="object"||e===null)return null;let t=e.keywords;if(!Array.isArray(t))return null;let n={},r=0;for(let i of t){if(!Cnn(i))continue;let o=i.term.trim().toLowerCase();if(!o||Object.hasOwn(n,o))continue;let a=Math.max(0,Math.min(1,i.weight));n[o]={term:o,category:"correction",weight:a,precision:Onn(i.source,a),source:Pnn(i.source)},i.source==="llm"&&(r+=1)}return{terms:n,learnedCount:r}}function AD(){let e={};for(let[t,n]of x8e)e[t]={term:t,category:"correction",weight:n,precision:"high",source:"seed"};for(let[t,n]of b8e)e[t]={term:t,category:"empathy",weight:n,precision:"ambiguous",source:"seed"};for(let t of XS)Object.hasOwn(e,t.term)||(e[t.term]={term:t.term,category:"correction",weight:t.weight,precision:t.weight>=zae?"high":"ambiguous",source:"seed"});return{version:2,terms:e}}function I8e(e){let t=mK.resolve(e.workspaceDir,".state"),n=mK.join(t,hK);if(!n.startsWith(t+mK.sep)||mK.basename(n)!==hK)return e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`resolved store path escapes the workspace state directory; refusing to load (path=${n.slice(0,120)})`),{resolve:()=>AD(),stats:()=>({totalTerms:0,learnedTerms:0,lastReloadedAt:null})};let r=null,i=null,o=0,a=null,s=()=>{let c;try{c=JSON.parse(y8e.readFileSync(n,"utf-8"))}catch{e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`cannot read ${hK}; using seed-only store (first run before the optimizer writes is normal)`),r=AD(),o=0,a=new Date().toISOString();return}let l=Lnn(c);if(!l){e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`${hK} malformed (keywords[] missing/invalid); using seed-only store`),r=AD(),o=0,a=new Date().toISOString();return}let u=AD();for(let[p,f]of Object.entries(l.terms))u.terms[p]=f;r=u,{learnedCount:o}=l,a=new Date().toISOString(),e.logger?.debug?.(`[PD:Signal] keyword store reloaded: ${Object.keys(u.terms).length} terms (${o} learned)`)};return{resolve(){let c=null;try{({mtimeMs:c}=y8e.statSync(n))}catch{}return(!r||c!==i)&&(s(),i=c),r??AD()},stats(){return{totalTerms:r?Object.keys(r.terms).length:0,learnedTerms:o,lastReloadedAt:a}}}}function Dnn(e){if(e.decision==="activated")return{decision:e.decision,activationId:e.activationId};if(e.decision==="already_activated")return{decision:e.decision,reason:"idempotent_redispatch"};if(e.decision==="queued_for_approval")return{decision:e.decision,reason:e.approvalId};let t="reason"in e&&typeof e.reason=="string"?e.reason:e.decision;return{decision:e.decision,reason:t}}function Nnn(e){let t=oi(e);if(!t.ok)return()=>!1;let n=Zr(t.effective);return r=>po(n,r)}async function Mnn(e,t,n){let r=new Or(e);try{let i=new Tm(r),o={getArtifactById:async f=>{let m=await i.getArtifactById(f);return m?{artifactId:m.artifactId,artifactKind:m.artifactKind,sourceTaskId:m.sourceTaskId,sourcePrincipleId:m.sourcePrincipleId,sourceRuleId:m.sourceRuleId,lineageArtifactIds:m.lineageArtifactIds,validationStatus:m.validationStatus,contentJson:m.contentJson,createdAt:m.createdAt,updatedAt:m.updatedAt}:null}},a=new Hf(r),s=new HS(r),c=Nnn(e),u=await new px(o,a,{writers:[new lx,new mx({gateDeps:VS(),featureFlagProbe:c}),new ux],approvalQueueStore:s}).dispatch({artifactId:t.artifactId,channel:t.channel,rolloutDecision:"auto_activate",actor:{kind:"system",source:"rollout_reviewer"},now:new Date().toISOString(),confirm:!0,confidence:t.confidence}),p=Dnn(u);return n?.info?.(`[PD:Consumer] rollout dispatch: artifact=${t.artifactId} channel=${t.channel} \u2192 ${p.decision}${p.activationId?` (${p.activationId})`:""}${p.reason?` reason=${p.reason}`:""}`),p}finally{try{r.close()}catch{}}}function w8e(e,t,n){return{isRepairLoopEnabled:()=>{let r=oi(e);if(!r.ok)return!1;let i=Zr(r.effective);return po(i,"evaluator_artificer_repair_loop")},seedArtificerRepairTask:async r=>{let i=`artificer-repair-${r.repairPayload.sourceEvaluatorTaskId}-r${r.repairPayload.repairIteration}`;return await t.getTask(i)?(n?.info?.(`[PD:Consumer] repair task ${i} already exists; reusing (idempotent seed)`),i):(await t.createTask({taskId:i,taskKind:"artificer",status:"pending",attemptCount:0,maxAttempts:3,diagnosticJson:Ui({dependencyTaskIds:[...r.inheritedDependencyTaskIds],channel:r.inheritedChannel,timeoutMs:r.inheritedTimeoutMs,inputArtifactRefs:[...r.inheritedInputArtifactRefs],outputArtifactRefs:[],repairPayload:r.repairPayload})}),n?.info?.(`[PD:Consumer] seeded artificer repair task ${i} (iteration ${r.repairPayload.repairIteration})`),i)}}}function T8e(e,t,n){return{dispatchActivation:r=>Mnn(e,r,n),reopenRevisionTarget:async r=>{let i=await t.reopenTaskForRevision(r.targetTaskId,{revisionFeedback:r.revisionFeedback,reason:`rollout_revision_iteration_${r.revisionIteration}`,revisionCauseId:`rollout-${r.sourceRolloutTaskId}-r${r.revisionIteration}`});return i.ok?{ok:!0,reason:i.reason,reopenedTaskId:r.targetTaskId}:{ok:!1,reason:i.reason}}}}import{createHash as qnn}from"node:crypto";import{appendFileSync as $nn,mkdirSync as Fnn}from"node:fs";import{dirname as Unn,join as Wnn}from"node:path";var jnn=new Set(["evaluator_adversarial_replay_skipped","evaluator_adversarial_replay","evaluator_rule_assembled","evaluator_rule_assembly_failed"]),gK=class extends uv{upstream;sinkFilePath;onPersistFailure;constructor(t,n,r){super(),this.upstream=t,this.onPersistFailure=r,this.sinkFilePath=Wnn(n,".pd","telemetry","critical-events.jsonl")}emitTelemetry(t){return jnn.has(t.eventType)&&this.persist(t),this.upstream.emitTelemetry(t)}persist(t){try{Fnn(Unn(this.sinkFilePath),{recursive:!0}),$nn(this.sinkFilePath,`${JSON.stringify(t)}
1910
+ `).get(Ge);if(!Mh(he)||typeof he.content_json!="string"||typeof he.content_bytes!="number"||!Number.isSafeInteger(he.content_bytes)){So(i,`activation_artifact_invalid: ${Se}`,"inspect state.db artifact content integrity");continue}let ke=he.content_json,pe=Buffer.byteLength(ke,"utf8");if(he.content_bytes>kD||pe>kD)return{decision:"allow",source:n.source,warnings:[bc(`artifact_content_budget_exceeded: activation=${Se} bytes=${Math.max(he.content_bytes,pe)} maximum=${kD}`,"reduce the active artifact envelope and reactivate the rule")],metadata:{evaluatedLiveRules:0}};if(he.content_bytes!==Ie||pe!==he.content_bytes)return{decision:"allow",source:n.source,warnings:[bc(`artifact_content_size_changed: activation=${Se}`,"retry after the active artifact update completes")],metadata:{evaluatedLiveRules:0}};try{let Ne=JSON.parse(ke);if(!Mh(Ne)||typeof Ne.implementationCode!="string"||Ne.implementationCode.length===0){So(i,`activation_artifact_invalid: ${Se}`,"regenerate the rule artifact with implementationCode");continue}let st=Buffer.byteLength(Ne.implementationCode,"utf8");if(st>qae)return{decision:"allow",source:n.source,warnings:[bc(`rule_source_budget_exceeded: activation=${Se} bytes=${st}`,`reduce each RuleCode source below ${qae} bytes`)],metadata:{evaluatedLiveRules:0}};if(Object.hasOwn(Ne,"requiresContextVersion")){if(Ne.requiresContextVersion!==2){So(i,`unsupported_context_version: ${String(Ne.requiresContextVersion)}`,"regenerate the rule artifact for context version 2");continue}if(!l){So(i,"rule_context_v2_unavailable","enable and wire the host rule context provider");continue}}let bt=typeof Ne.ruleId=="string"?Ne.ruleId:typeof ie.source_rule_id=="string"?ie.source_rule_id:Ge,it=typeof Ne.principleId=="string"?Ne.principleId:typeof ie.source_principle_id=="string"?ie.source_principle_id:bt,xe=c8e(Ne.implementationCode);if(xe.length>0){So(i,`legacy_rule_contract_dependency: ${xe.join(", ")} (activation=${Se})`,"migrate the RuleCode off the retired contract symbols or deactivate the activation, then re-approve a migrated rule");continue}let pt={name:Se,version:"1",ruleId:bt,coversCondition:"all"};y.push({implId:Se,ruleId:bt,principleId:it,meta:_nn(Ne.meta)?Ne.meta:pt,source:Ne.implementationCode})}catch(Ne){So(i,`implementation_unhealthy: ${Ne instanceof Error?Ne.message:String(Ne)}`,"fix the RuleCode and reactivate the rule")}}}}let I={action:c,workspace:{isRiskPath:!1},session:{sessionId:n.context.sessionId,currentGfi:u.currentGfi},evolution:{epTier:u.epTier},derived:{estimatedLineChanges:tk({toolName:o.toolName,params:o.params}),bashRisk:u.bashRisk},...l?{context:l}:{}},E=y.reduce((U,K)=>U+Buffer.byteLength(K.source,"utf8"),0);if(E>Gae)return{decision:"allow",source:n.source,warnings:[bc(`rule_source_budget_exceeded: batchBytes=${E}`,`reduce total active RuleCode below ${Gae} bytes`)],metadata:{evaluatedLiveRules:0}};let R=y.map(U=>({source:U.source,filename:`activation-${U.implId}`})),A=Bae(r);if(A<=0)return{decision:"allow",source:n.source,warnings:[bc("gate_deadline_exceeded","reduce active RuleCode count or source size and retry")],metadata:{evaluatedLiveRules:0}};let P=t.evaluateBatch(R,I,A);if(!P.ok||!P.results)return{decision:"allow",source:n.source,warnings:[bc(`${P.reason??"rule_batch_failed"}: ${P.detail??"unknown failure"}`,"inspect active RuleCode resource use and repair or deactivate the unhealthy rule")],metadata:{evaluatedLiveRules:0}};let O=P.results.find(U=>!U.ok&&U.error?.includes("timed out"));if(O)return{decision:"allow",source:n.source,warnings:[bc(`rule_batch_timeout: ${O.error??"unknown child timeout"}`,"fix or deactivate the unhealthy RuleCode and retry")],metadata:{evaluatedLiveRules:0}};let $=[];for(let U=0;U<y.length;U+=1){let K=y[U],ce=P.results[U];if(!K||!ce){So(i,"rule_batch_result_missing","inspect the RuleCode runtime result contract");continue}if(!ce.ok){So(i,`implementation_unhealthy: ${ce.error??"unknown child error"}`,"fix the RuleCode and reactivate the rule");continue}let ie=c_(ce.result);if(!xnn(ce.result)){So(i,`invalid RuleHostResult: ${ie.errors.join("; ")}`,"fix the RuleCode result and reactivate the rule");continue}let Se=ce.result.matched?{...ce.result,ruleId:K.ruleId,principleId:K.principleId}:ce.result;$.push({...K,evaluate:()=>Se})}let M=WL($,I,{warn(U){So(i,U,"inspect the unhealthy activation and RuleCode output")}});return M?.decision==="block"?M.reason.trim().length===0?(So(i,"deny_reason_missing","fix the RuleCode to return a non-empty block reason"),{decision:"allow",source:n.source,warnings:i,metadata:{evaluatedLiveRules:$.length}}):{decision:"deny",reason:M.reason,source:n.source,...i.length?{warnings:i}:{},metadata:{evaluatedLiveRules:$.length,ruleId:M.ruleId,principleId:M.principleId}}:{decision:"allow",source:n.source,...i.length?{warnings:i}:{},metadata:{evaluatedLiveRules:$.length,ruleDecision:M?.decision??"allow"}}}catch(_){return So(i,`activation_read_failed: ${_ instanceof Error?_.message:String(_)}`,"inspect state.db schema and integrity"),{decision:"allow",source:n.source,warnings:i,metadata:{evaluatedLiveRules:0}}}finally{m.close()}}}import{createHash as Hae}from"node:crypto";import bnn from"node:fs";import m_ from"node:path";import Inn from"better-sqlite3";var wnn=new Set(["write","edit","apply_patch","write_file","edit_file","replace"]);var Kae=500,f8e=900*1e3,pK=new Map;function fK(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function co(e,t){if(!(!fK(e)||!Object.hasOwn(e,t)))return Object.getOwnPropertyDescriptor(e,t)?.value}function Tnn(e){let t="context"in e?e.context:e,n=t.toolOutput,r=co(n,"result")??n,i=co(n,"error"),o=co(r,"exitCode"),a=co(co(r,"details"),"exitCode"),s=typeof o=="number"?o:typeof a=="number"?a:0,c=i==null||i===""?void 0:String(i),l=co(n,"durationMs");return{failure:c!==void 0||s!==0,exitCode:s,...c?{error:c.slice(0,Kae)}:{},...typeof l=="number"&&Number.isFinite(l)&&l>=0?{durationMs:l}:{},params:t.toolInput??{},result:r}}function m8e(e){return Array.isArray(e)&&e.length<=8&&e.every(t=>fK(t)&&typeof co(t,"sourceRef")=="string"&&String(co(t,"sourceRef")).trim().length>0&&String(co(t,"sourceRef")).length<=300&&typeof co(t,"note")=="string"&&String(co(t,"note")).length<=200)}function Enn(e){if(e===void 0)return{};if(!fK(e))return null;let t=co(e,"painScore"),n=co(e,"isRisky"),r=co(e,"consecutiveErrors"),i=co(e,"evidence"),o=co(e,"eventId"),a=co(e,"relativePath"),s=co(e,"agentId"),c=co(e,"errorHash");if(t!==void 0&&(typeof t!="number"||!Number.isFinite(t)||t<0||t>100)||n!==void 0&&typeof n!="boolean"||r!==void 0&&(typeof r!="number"||!Number.isInteger(r)||r<0))return null;for(let l of["eventId","relativePath","agentId","errorHash"]){let u=co(e,l);if(u!==void 0&&(typeof u!="string"||u.trim().length===0||u.length>500))return null}return i!==void 0&&!m8e(i)?null:{...typeof o=="string"?{eventId:o}:{},...typeof t=="number"?{painScore:t}:{},...typeof n=="boolean"?{isRisky:n}:{},...typeof r=="number"?{consecutiveErrors:r}:{},...typeof a=="string"?{relativePath:a}:{},...typeof s=="string"?{agentId:s}:{},...typeof c=="string"?{errorHash:c}:{},...m8e(i)?{evidence:i}:{}}}function uk(e,t=new WeakSet){return e===null||typeof e!="object"?JSON.stringify(typeof e=="string"?e.slice(0,2e3):typeof e=="number"||typeof e=="boolean"?e:String(e)):t.has(e)?'"[circular]"':(t.add(e),Array.isArray(e)?`[${e.slice(0,50).map(r=>uk(r,t)).join(",")}]`:`{${Object.keys(e).sort().slice(0,50).map(r=>`${JSON.stringify(r)}:${uk(co(e,r),t)}`).join(",")}}`)}function Snn(e){try{let t=uk(e);return t.length>Kae?`${t.slice(0,Kae-3)}...`:t}catch{return"[result_preview_unavailable]"}}function knn(e){let{outcome:t,sanitizedParams:n,canonicalEventId:r}=e,i=uk({workspaceDir:m_.resolve(e.workspaceDir),sessionId:e.sessionId,turnId:e.turnId??null,toolName:e.toolName,source:e.source,suppliedEventId:r??null,params:n,result:Fp(t.result,0,e.workspaceDir),error:t.error??null,exitCode:t.exitCode,failure:t.failure}),o=Hae("sha256").update(i).digest("hex");return{eventId:`host_${o}`,painId:`pain_host_${o}`}}function Vae(e){let t=uk({workspaceDir:m_.resolve(e.workspaceDir),sessionId:e.sessionId,occurrenceId:e.occurrenceId,source:"user_correction",text:e.text}),n=Hae("sha256").update(t).digest("hex");return{eventId:`host_${n}`,painId:`pain_host_${n}`}}var Ann={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",gfi_before:"REAL",gfi_after:"REAL",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",host_kind:"TEXT",created_at:"TEXT"}};function zx(e,t){return fK(e)&&Object.hasOwn(e,t)?Object.getOwnPropertyDescriptor(e,t)?.value:void 0}function Rnn(e){let t=e.prepare("SELECT sql FROM sqlite_master WHERE type = 'index' AND name = ?").get("idx_pain_events_canonical_pain_id"),n=zx(t,"sql");if(typeof n!="string"||n.length===0||n.length>2e3)return!1;let r=n.replace(/["'`]/g,"").replace(/\[|\]/g,"").replace(/\s+/g," ").trim().replace(/;$/,"").toUpperCase(),i=r.indexOf(" WHERE ");return i>=0&&r.slice(i+7)==="CANONICAL_PAIN_ID IS NOT NULL"}function h8e(e){for(let[i,o]of Object.entries(Ann)){let a=e.prepare(`PRAGMA table_info(${i})`).all(),s=new Map;for(let c of a){let l=zx(c,"name"),u=zx(c,"type");if(typeof l!="string"||typeof u!="string")return!1;s.set(l,u.toUpperCase())}for(let[c,l]of Object.entries(o))if(s.get(c)!==l)return!1}let n=e.prepare("PRAGMA index_list(pain_events)").all().find(i=>zx(i,"name")==="idx_pain_events_canonical_pain_id");if(zx(n,"unique")!==1||zx(n,"partial")!==1||!Rnn(e))return!1;let r=e.prepare("PRAGMA index_info(idx_pain_events_canonical_pain_id)").all();return r.length!==1||zx(r[0],"name")!=="canonical_pain_id"?!1:(e.prepare("SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?"),e.prepare("SELECT 1 FROM pain_events WHERE canonical_pain_id = ?"),e.prepare("INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at"),e.prepare("INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),e.prepare("INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, host_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"),!0)}function g8e(e={}){return async t=>{let n=m_.join(t.context.workspaceDir,".state","trajectory.db");if(!bnn.existsSync(n))return{decision:"observe",source:t.source,warnings:["trajectory_db_not_found"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"initialize the selected PD workspace before retrying the hook"}};let r;try{if(r=e.painDatabaseFactory?e.painDatabaseFactory(n):new Inn(n),r.pragma("busy_timeout = 5000"),!h8e(r))return r.close(),r=void 0,{decision:"observe",source:t.source,warnings:["trajectory_schema_invalid"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"run the supported PD workspace migration"}}}catch(Se){try{r?.close()}catch{}return{decision:"observe",source:t.source,warnings:[`trajectory_database_unavailable:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"inspect or repair the selected PD trajectory database"}}}let i=[],o;try{o=Enn(await e.painEnrichmentProvider?.(t))}catch(Se){i.push(`pain_enrichment_failed:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`),o=null}if(!o){try{r.close()}catch{}return{decision:"observe",source:t.source,warnings:i.length>0?i:["pain_enrichment_invalid"],metadata:{outcome:"unavailable",admitted:!1,duplicate:!1,nextAction:"inspect host pain enrichment input"}}}let a=Tnn(t),s=MA(a.params,t.context.workspaceDir),c=t.context.toolName??"",l=Dh({toolName:c,error:a.error,exitCode:a.exitCode}),u=nu({observedAt:new Date().toISOString(),workspaceId:t.context.workspaceDir,sessionId:t.context.sessionId,toolName:c,failureSource:l.failureSource,toolNotFound:l.toolNotFound,nonZeroExit:a.exitCode!==0}),p=o.relativePath??String(co(a.params,"file_path")??co(a.params,"path")??"unknown").slice(0,500),f=o.isRisky??(m_.isAbsolute(p)&&!m_.resolve(p).startsWith(`${m_.resolve(t.context.workspaceDir)}${m_.sep}`)),m=o.painScore??Math.min(100,(a.exitCode!==0?70:0)+(f?20:0)),y=o.errorHash??Hae("sha256").update(a.error??String(a.exitCode)).digest("hex"),_=`${m_.resolve(t.context.workspaceDir)}:${t.context.sessionId}:${l.failureSource}:${y}`,b=pK.get(_),I=b!==void 0&&Date.now()-b<f8e,E=jx({sourceKind:u,score:m,consecutiveErrors:o.consecutiveErrors,isRisky:f}),R=ru({triageResult:E,isOwnerManual:!1,isCooldownActive:I,isValid:!0,score:m,sessionId:t.context.sessionId}),A=a.failure&&wnn.has(c)&&R.shouldCreateDiagnosticTask,{eventId:P,painId:O}=knn({workspaceDir:t.context.workspaceDir,sessionId:t.context.sessionId,...t.context.turnId!==void 0?{turnId:t.context.turnId}:{},...c!==void 0?{toolName:c}:{},source:t.source,...o.eventId?{canonicalEventId:o.eventId}:{},outcome:a,sanitizedParams:s}),$=new Date().toISOString(),M=uk(s),U=Snn({eventId:P,result:Fp(a.result,0,t.context.workspaceDir)}),K=!1,ce=!1;try{if(r.transaction(()=>{if(r.prepare("SELECT 1 FROM tool_calls WHERE session_id = ? AND tool_name = ? AND params_json = ? AND outcome = ? AND exit_code IS ? AND error_message IS ? AND result_preview IS ?").get(t.context.sessionId,c,M,a.failure?"failure":"success",a.exitCode,a.error??null,U)){K=!0,ce=r.prepare("SELECT 1 FROM pain_events WHERE canonical_pain_id = ?").get(O)!==void 0;return}if(r.prepare("INSERT INTO sessions (session_id, started_at, updated_at) VALUES (?, ?, ?) ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at").run(t.context.sessionId,$,$),r.prepare("INSERT INTO tool_calls (session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message, gfi_before, gfi_after, params_json, result_preview, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(t.context.sessionId,c,a.failure?"failure":"success",a.durationMs??null,a.exitCode,a.error?a.error.split(/[\s:]/,1)[0]:null,a.error??null,null,null,M,U,$),A){let Se=`tool=${c}; error=${a.error??`exit=${a.exitCode}`}; path=${p}`;r.prepare("INSERT INTO pain_events (session_id, source, score, reason, severity, origin, confidence, text, canonical_pain_id, runtime_task_id, host_kind, created_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(t.context.sessionId,l.failureSource??"tool_failure",m,Se,m>=70?"severe":m>=40?"moderate":"mild","system_infer",null,o.evidence?.map(Ge=>`${Ge.sourceRef}: ${Ge.note}`).join(`
1911
+ `)??null,O,null,e.hostKind??null,$)}})(),A&&!K){let Se=Date.now();for(let[Ge,Ie]of pK)Se-Ie>=f8e&&pK.delete(Ge);pK.set(_,Se)}}catch(Se){return{decision:"observe",source:t.source,warnings:[`trajectory_write_failed:${Se instanceof Error?Se.message.slice(0,200):String(Se).slice(0,200)}`],metadata:{outcome:a.failure?"failure":"success",admitted:!1,duplicate:!1,nextAction:"inspect the workspace trajectory database and retry"}}}finally{try{r.close()}catch{}}let ie=A||ce;return{decision:"observe",source:t.source,metadata:{eventId:P,painId:ie?O:null,outcome:a.failure?"failure":"success",admitted:ie,duplicate:K,sourceKind:u,failureSource:l.failureSource??null,triggerOutcome:R.outcome,triggerReason:R.reason,painScore:m,isRisky:f,relativePath:p,agentId:o.agentId??null,evidence:o.evidence??[]}}}}import sWi from"better-sqlite3";var lWi=10080*60*1e3;var uWi=10080*60*1e3;import y8e from"node:fs";import mK from"node:path";import vWi from"better-sqlite3";var _8e=70,v8e=5,TWi=3600*1e3;var hK="correction_keywords.json",zae=.7,x8e=[["\u8FD9\u662F\u9519\u7684",.9],["\u4E0D\u8981\u81EA\u4F5C\u4E3B\u5F20",.9],["\u4E0D\u5E94\u8BE5\u8FD9\u4E48\u505A",.9]],b8e=[["\u641E\u4EC0\u4E48",.5]];function Cnn(e){if(typeof e!="object"||e===null)return!1;let t=e;return typeof t.term!="string"||t.term.length===0||typeof t.weight!="number"||!Number.isFinite(t.weight)?!1:t.source==="seed"||t.source==="llm"||t.source==="user"}function Pnn(e){return e==="llm"?"llm_learned":e==="user"?"owner_promoted":"seed"}function Onn(e,t){return e==="llm"?"ambiguous":t>=zae?"high":"ambiguous"}function Lnn(e){if(typeof e!="object"||e===null)return null;let t=e.keywords;if(!Array.isArray(t))return null;let n={},r=0;for(let i of t){if(!Cnn(i))continue;let o=i.term.trim().toLowerCase();if(!o||Object.hasOwn(n,o))continue;let a=Math.max(0,Math.min(1,i.weight));n[o]={term:o,category:"correction",weight:a,precision:Onn(i.source,a),source:Pnn(i.source)},i.source==="llm"&&(r+=1)}return{terms:n,learnedCount:r}}function AD(){let e={};for(let[t,n]of x8e)e[t]={term:t,category:"correction",weight:n,precision:"high",source:"seed"};for(let[t,n]of b8e)e[t]={term:t,category:"empathy",weight:n,precision:"ambiguous",source:"seed"};for(let t of XS)Object.hasOwn(e,t.term)||(e[t.term]={term:t.term,category:"correction",weight:t.weight,precision:t.weight>=zae?"high":"ambiguous",source:"seed"});return{version:2,terms:e}}function I8e(e){let t=mK.resolve(e.workspaceDir,".state"),n=mK.join(t,hK);if(!n.startsWith(t+mK.sep)||mK.basename(n)!==hK)return e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`resolved store path escapes the workspace state directory; refusing to load (path=${n.slice(0,120)})`),{resolve:()=>AD(),stats:()=>({totalTerms:0,learnedTerms:0,lastReloadedAt:null})};let r=null,i=null,o=0,a=null,s=()=>{let c;try{c=JSON.parse(y8e.readFileSync(n,"utf-8"))}catch{e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`cannot read ${hK}; using seed-only store (first run before the optimizer writes is normal)`),r=AD(),o=0,a=new Date().toISOString();return}let l=Lnn(c);if(!l){e.onDegradation?.("SIGNAL_KEYWORD_STORE_INVALID",`${hK} malformed (keywords[] missing/invalid); using seed-only store`),r=AD(),o=0,a=new Date().toISOString();return}let u=AD();for(let[p,f]of Object.entries(l.terms))u.terms[p]=f;r=u,{learnedCount:o}=l,a=new Date().toISOString(),e.logger?.debug?.(`[PD:Signal] keyword store reloaded: ${Object.keys(u.terms).length} terms (${o} learned)`)};return{resolve(){let c=null;try{({mtimeMs:c}=y8e.statSync(n))}catch{}return(!r||c!==i)&&(s(),i=c),r??AD()},stats(){return{totalTerms:r?Object.keys(r.terms).length:0,learnedTerms:o,lastReloadedAt:a}}}}function Dnn(e){if(e.decision==="activated")return{decision:e.decision,activationId:e.activationId};if(e.decision==="already_activated")return{decision:e.decision,reason:"idempotent_redispatch"};if(e.decision==="queued_for_approval")return{decision:e.decision,reason:e.approvalId};let t="reason"in e&&typeof e.reason=="string"?e.reason:e.decision;return{decision:e.decision,reason:t}}function Nnn(e){let t=oi(e);if(!t.ok)return()=>!1;let n=Zr(t.effective);return r=>po(n,r)}async function Mnn(e,t,n){let r=new Or(e);try{let i=new Tm(r),o={getArtifactById:async f=>{let m=await i.getArtifactById(f);return m?{artifactId:m.artifactId,artifactKind:m.artifactKind,sourceTaskId:m.sourceTaskId,sourcePrincipleId:m.sourcePrincipleId,sourceRuleId:m.sourceRuleId,lineageArtifactIds:m.lineageArtifactIds,validationStatus:m.validationStatus,contentJson:m.contentJson,createdAt:m.createdAt,updatedAt:m.updatedAt}:null}},a=new Hf(r),s=new HS(r),c=Nnn(e),u=await new px(o,a,{writers:[new lx,new mx({gateDeps:VS(),featureFlagProbe:c}),new ux],approvalQueueStore:s}).dispatch({artifactId:t.artifactId,channel:t.channel,rolloutDecision:"auto_activate",actor:{kind:"system",source:"rollout_reviewer"},now:new Date().toISOString(),confirm:!0,confidence:t.confidence}),p=Dnn(u);return n?.info?.(`[PD:Consumer] rollout dispatch: artifact=${t.artifactId} channel=${t.channel} \u2192 ${p.decision}${p.activationId?` (${p.activationId})`:""}${p.reason?` reason=${p.reason}`:""}`),p}finally{try{r.close()}catch{}}}function w8e(e,t,n){return{isRepairLoopEnabled:()=>{let r=oi(e);if(!r.ok)return!1;let i=Zr(r.effective);return po(i,"evaluator_artificer_repair_loop")},seedArtificerRepairTask:async r=>{let i=`artificer-repair-${r.repairPayload.sourceEvaluatorTaskId}-r${r.repairPayload.repairIteration}`;return await t.getTask(i)?(n?.info?.(`[PD:Consumer] repair task ${i} already exists; reusing (idempotent seed)`),i):(await t.createTask({taskId:i,taskKind:"artificer",status:"pending",attemptCount:0,maxAttempts:3,diagnosticJson:Ui({dependencyTaskIds:[...r.inheritedDependencyTaskIds],channel:r.inheritedChannel,timeoutMs:r.inheritedTimeoutMs,inputArtifactRefs:[...r.inheritedInputArtifactRefs],outputArtifactRefs:[],repairPayload:r.repairPayload})}),n?.info?.(`[PD:Consumer] seeded artificer repair task ${i} (iteration ${r.repairPayload.repairIteration})`),i)}}}function T8e(e,t,n){return{dispatchActivation:r=>Mnn(e,r,n),reopenRevisionTarget:async r=>{let i=await t.reopenTaskForRevision(r.targetTaskId,{revisionFeedback:r.revisionFeedback,reason:`rollout_revision_iteration_${r.revisionIteration}`,revisionCauseId:`rollout-${r.sourceRolloutTaskId}-r${r.revisionIteration}`});return i.ok?{ok:!0,reason:i.reason,reopenedTaskId:r.targetTaskId}:{ok:!1,reason:i.reason}}}}import{createHash as qnn}from"node:crypto";import{appendFileSync as $nn,mkdirSync as Fnn}from"node:fs";import{dirname as Unn,join as Wnn}from"node:path";var jnn=new Set(["evaluator_adversarial_replay_skipped","evaluator_adversarial_replay","evaluator_rule_assembled","evaluator_rule_assembly_failed"]),gK=class extends uv{upstream;sinkFilePath;onPersistFailure;constructor(t,n,r){super(),this.upstream=t,this.onPersistFailure=r,this.sinkFilePath=Wnn(n,".pd","telemetry","critical-events.jsonl")}emitTelemetry(t){return jnn.has(t.eventType)&&this.persist(t),this.upstream.emitTelemetry(t)}persist(t){try{Fnn(Unn(this.sinkFilePath),{recursive:!0}),$nn(this.sinkFilePath,`${JSON.stringify(t)}
1910
1912
  `,"utf8")}catch(n){this.onPersistFailure(JSON.stringify({eventType:t.eventType,sinkFilePath:this.sinkFilePath,error:n instanceof Error?n.message:String(n)}))}}};var Yae="internalization_auto_consumer";function yK(e){return qnn("sha256").update(e).digest("hex")}function Gnn(e){return`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`}function Bnn(e){return e==="lease_conflict"?"Retry later or check for concurrent worker processes.":e==="timeout"?"Check model provider service status/latency, or increase timeout settings in workflows.yaml.":e==="cancelled"?"Re-enqueue or restart the task if it was cancelled by mistake.":e==="output_invalid"?"Verify if model outputs conform to expected schema and adjust prompt or validation templates if needed.":e==="input_invalid"?"Check predecessor task outputs and database integrity for malformed input references.":e==="max_attempts_exceeded"?"Investigate persistent failures, correct the root issue, and clear last_error or reset attempt count.":"Run: pd runtime internalization run-once --runner dreamer --runtime config --json to isolate the failure."}async function Knn(e,t){let{logger:n,emitEvent:r,logLabel:i}=t;try{let o=await e.runRecoverySweep();(o.recovered>0||o.errors.length>0)&&(r("INTERNALIZATION_CONSUMER_RECOVERED",JSON.stringify({recovered:o.recovered,failed:o.errors.length,errors:o.errors})),n.info(`[PD:${i}] Recovery sweep: recovered=${o.recovered} failed=${o.errors.length}`))}catch(o){r("INTERNALIZATION_CONSUMER_RECOVER_FAILED",String(o)),n.warn(`[PD:${i}] Recovery sweep failed: ${String(o)}`)}}var Hnn=5;async function Vnn(e,t,n){let{logger:r,emitEvent:i,logLabel:o}=n;try{let a=new Or(e);try{let s=new RA(a),c=s.get(CA),l=await t.reconcileSucceededTransitions({limit:Hnn,cursor:c?{updatedAt:c.lastUpdatedAt,taskId:c.lastTaskId}:void 0,logger:{info:p=>r.info(p)}});l.wrappedAround?s.clear(CA):s.set(CA,l.nextCursor);let u=l.outcomes.filter(p=>p.decision.startsWith("reconcile_error"));(l.recovered>0||u.length>0)&&(i("INTERNALIZATION_CONSUMER_RECONCILED",JSON.stringify({scanned:l.scanned,recovered:l.recovered,alreadyMaterialized:l.alreadyMaterialized,blocked:l.blocked,wrappedAround:l.wrappedAround,recoveries:l.outcomes.filter(p=>p.decision==="successor_created"||p.decision.includes("reopened")),errors:u})),r.info(`[PD:${o}] Reconciliation: recovered=${l.recovered} errors=${u.length} wrapped=${l.wrappedAround}`))}finally{try{a.close()}catch{}}}catch(a){i("INTERNALIZATION_CONSUMER_RECONCILE_FAILED",String(a)),r.warn(`[PD:${o}] Succeeded-transition reconciliation failed: ${String(a)}`)}}async function E8e(e,t){let{logger:n,emitEvent:r,logLabel:i,owner:o}=t,{hostToolCatalog:a}=t,s=t.envGetter??(m=>process.env[m]),c=null,l=dr(e,Yae,{info:m=>n.info(m),warn:m=>n.warn(m)});if(!l.enabled){let m=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:Gnn(e),flagSource:l.source});return r("INTERNALIZATION_CONSUMER_SKIP",m),n.info(`[PD:${i}] Cycle skipped: auto-consumer disabled. Source: ${l.source}`),{ran:!1,skipReason:"internalization_auto_consumer_disabled"}}let u=oi(e);if(!u.ok){let m=JSON.stringify({reason:"config_malformed",nextAction:u.errors[0]?.nextAction??"Fix .pd/config.yaml and retry",errors:u.errors.map(y=>y.reason)});return r("INTERNALIZATION_CONSUMER_SKIP",m),n.warn(`[PD:${i}] Config malformed, skipping cycle.`),{ran:!1,skipReason:"config_malformed"}}let p=wq(u.effective,m=>s(m));if(Iq(p)){let m=JSON.stringify({reason:"runtime_config_error",message:p.message,nextAction:p.nextAction});return r("INTERNALIZATION_CONSUMER_SKIP",m),n.warn(`[PD:${i}] Runtime config error: ${p.message}`),{ran:!1,skipReason:"runtime_config_error"}}let f=null;try{f=await tD({workspaceDir:e,readonly:!1});let{stateManager:m}=f,{runtimeKind:y}=p;c=new KL({stateManager:m},{owner:o,runtimeKind:y,dryRun:!0});let _=new nD(m);_.setPolicy({enabledChannels:new Set(["prompt","code_tool_hook","defer_archive"]),actionableTaskKinds:new Set(b3)});let b=await _.getSnapshot();b.readyTasks.length>5&&n.warn(`[PD:${i}] Backlog detected: ${b.readyTasks.length} tasks ready. Processing only one task.`);let E=dr(e,"internalization_full_chain").enabled?Qoe:I3,R=Zoe({autoConsumerEnabled:!0,readyTaskCount:b.readyTasks.length,runnerKinds:E});if(!R.shouldConsume)return r("INTERNALIZATION_CONSUMER_SKIP",JSON.stringify({reason:R.reason,readyTaskCount:b.readyTasks.length})),{ran:!1,skipReason:R.reason};let A=null,P="no_ready_tasks",O;for(let ke of R.runnerKinds){let pe=await c.wakeOnce(ke);if(pe.decision==="would_lease"){A=pe;break}P=pe.decision,O=pe.decision==="no_ready_tasks"?pe.reason:void 0}if(!A){let ke={decision:P};return O&&(ke.reason=O),r("INTERNALIZATION_CONSUMER_SKIP",JSON.stringify(ke)),n.info(`[PD:${i}] No task to consume: ${P}`),{ran:!1,skipReason:P}}let $;if(y==="pi-ai")if(dr(e,"l2_dreamer").enabled&&A.taskKind==="dreamer"){let pe=`${e}/.state`,Ne=Joe(Bn(pe),{logger:{warn:st=>n.warn(st)}});$=new $L({provider:p.provider??"openai",model:p.model??"gpt-4o",apiKeyEnv:p.apiKeyEnv??"OPENAI_API_KEY",baseUrl:p.baseUrl,workspace:e,totalBudgetMs:p.timeoutMs},{artifactReader:{getArtifactById:async st=>{let bt=await m.piArtifactStore.getArtifactById(st);return bt?{artifactId:bt.artifactId,artifactKind:String(bt.artifactKind),sourceTaskId:bt.sourceTaskId,contentJson:bt.contentJson,createdAt:bt.createdAt}:null},listBySourceTaskId:async st=>(await m.piArtifactStore.listBySourceTaskId(st)).map(it=>({artifactId:it.artifactId,artifactKind:String(it.artifactKind),sourceTaskId:it.sourceTaskId,contentJson:it.contentJson,createdAt:it.createdAt}))},principleReader:Ne})}else $=new Xl({provider:p.provider??"openai",model:p.model??"gpt-4o",apiKeyEnv:p.apiKeyEnv??"OPENAI_API_KEY",maxRetries:p.maxRetries,maxTokens:p.maxTokens,timeoutMs:p.timeoutMs,baseUrl:p.baseUrl,workspace:e});else if(y==="openclaw-cli")$=new km({runtimeMode:p.openclawMode??"default",workspaceDir:e});else throw new Error(`Unsupported runtime kind resolved for auto-consumer: ${y}`);let{taskId:M}=A,{taskKind:U}=A,K={owner:o,runtimeKind:y,effectiveConfig:u.effective},ce=new gK(Kr,e,ke=>{r("WORKSPACE_TELEMETRY_PERSIST_FAILED",ke)}),ie;switch(U){case"dreamer":ie=new HL({stateManager:m,runtimeAdapter:$,eventEmitter:Kr,artifactStore:m.piArtifactStore,validator:new lR,contentHashFn:yK},K);break;case"philosopher":ie=new VL({stateManager:m,runtimeAdapter:$,eventEmitter:Kr,artifactStore:m.piArtifactStore,validator:new uR,contentHashFn:yK},K);break;case"scribe":ie=new zL({stateManager:m,runtimeAdapter:$,eventEmitter:Kr,artifactStore:m.piArtifactStore,validator:new dR,contentHashFn:yK},K);break;case"artificer":ie=new YL({stateManager:m,runtimeAdapter:$,eventEmitter:Kr,artifactStore:m.piArtifactStore,validator:new fR,contentHashFn:yK},K);break;case"evaluator":ie=new XL({stateManager:m,runtimeAdapter:$,eventEmitter:ce,artifactStore:m.piArtifactStore,validator:new mR,...w8e(e,m,n)},{...K,gateDeps:VS(),...a?{hostToolCatalog:{readOnlyTools:[...a.readOnlyTools],writeTools:[...a.writeTools]}}:{}});break;case"rollout_reviewer":ie=new eD({stateManager:m,runtimeAdapter:$,eventEmitter:Kr,artifactStore:m.piArtifactStore,validator:new hR,...T8e(e,c,n)},K);break;default:return r("INTERNALIZATION_CONSUMER_SKIP",JSON.stringify({decision:"no_runner_for_kind",taskKind:U})),n.warn(`[PD:${i}] No consumer runner for task kind '${U}'; skipping. Advance manually: pd runtime internalization run-once --runner ${U}`),{ran:!1,skipReason:"no_runner_for_kind",taskKind:U}}n.info(`[PD:${i}] Running ${U} task: ${M}`),r("INTERNALIZATION_CONSUMER_RUN",JSON.stringify({taskId:M,taskKind:U}));let Se;try{Se=await ie.run(M)}catch(ke){n.error(`[PD:${i}] Runner crashed for task ${M}: ${String(ke)}`);try{let pe=await m.getTask(M),Ne=`Unhandled runner exception: ${ke instanceof Error?ke.message:String(ke)}`;pe&&m.getRetryPolicy().shouldRetry(pe)?(await m.markTaskRetryWait(M,"execution_failed",Ne),n.info(`[PD:${i}] Marked task ${M} as retry_wait.`)):(await m.markTaskFailed(M,"execution_failed",Ne),n.info(`[PD:${i}] Marked task ${M} as failed.`))}catch(pe){n.error(`[PD:${i}] Failed to update state for crashed task ${M}: ${String(pe)}`)}throw ke}if(Se.status==="succeeded"){let ke=null;try{ke=await c.commitNextTaskProposal(M)}catch(pe){r("INTERNALIZATION_CONSUMER_COMMIT_FAILED",JSON.stringify({taskId:M,error:String(pe).slice(0,300)})),n.warn(`[PD:${i}] Task ${M} succeeded but successor proposal failed: ${String(pe).slice(0,200)}`)}return r("INTERNALIZATION_CONSUMER_SUCCESS",JSON.stringify({taskId:M,status:Se.status,...ke?{successorDecision:ke.decision}:{successorDecision:"commit_failed"}})),n.info(`[PD:${i}] Task ${M} succeeded. Successor: ${ke?ke.decision:"commit_failed"}`),{ran:!0,taskId:M,taskKind:U,runStatus:"succeeded"}}let{errorCategory:Ge}=Se,{failureReason:Ie}=Se,he=Bnn(Ge);return r("INTERNALIZATION_CONSUMER_TASK_FAILED",JSON.stringify({taskId:M,status:Se.status,errorCategory:Ge,failureReason:Ie,nextAction:he})),n.warn(`[PD:${i}] Task ${M} status: ${Se.status}. Category: ${Ge}. Reason: ${Ie}. Next Action: ${he}`),{ran:!0,taskId:M,taskKind:U,runStatus:Se.status==="retried"?"retried":"failed"}}catch(m){return r("INTERNALIZATION_CONSUMER_ERROR",String(m)),n.error(`[PD:${i}] Cycle error: ${String(m)}`),{ran:!1,skipReason:"cycle_error"}}finally{f&&await Knn(f.stateManager,t),c&&await Vnn(e,c,t),f&&await f.close().catch(()=>{})}}import RD from"node:fs";import Jae from"node:path";var znn="product-telemetry.json",Yx="2",S8e="1",k8e=200,Ynn=30;function Xae(){return{consent:"unset",consentVersion:ug,schemaVersion:Yx}}function Jx(e){return Jae.join(Jae.resolve(e),".pd",znn)}function A8e(e){return e==="unset"||e==="granted"||e==="denied"}function dk(e){return e===void 0?!0:typeof e!="string"||e.length===0||e.length>40?!1:!Number.isNaN(Date.parse(e))}function P8e(e){return e===void 0?!0:yA(e)}function O8e(e){return e===void 0||typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=99}function L8e(e){return e===void 0||typeof e=="string"&&e.length>0&&e.length<=40}function R8e(e){return typeof e=="string"&&/^[0-9a-f]{4,32}$/.test(e)}function Jnn(e,t){let n=[];for(let r of Object.keys(e))["lastAttemptedAt","lastSucceededAt","lastFailureCode","nextRetryAt","dailyAttemptCount","attemptBucketDate"].includes(r)||n.push(`${t}: unknown field '${r}'`);return(!dk(e.lastAttemptedAt)||!dk(e.lastSucceededAt)||!dk(e.nextRetryAt))&&n.push(`${t}: timestamps must be parseable ISO-8601 strings (\u226440 chars) when present`),O8e(e.dailyAttemptCount)||n.push(`${t}: dailyAttemptCount must be an integer 0\u201399 when present`),P8e(e.attemptBucketDate)||n.push(`${t}: attemptBucketDate must be a valid YYYY-MM-DD UTC date when present`),L8e(e.lastFailureCode)||n.push(`${t}: lastFailureCode must be a short non-empty string when present`),n}function C8e(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function $h(e){let t=Jx(e),n;try{n=RD.readFileSync(t,"utf8")}catch(p){let f=typeof p=="object"&&p!==null&&Object.hasOwn(p,"code")?p.code:void 0,m=typeof f=="string"?f:void 0;return m==="ENOENT"?{ok:!0,state:Xae(),existed:!1}:{ok:!1,reason:`product_telemetry_state_unreadable: ${m??String(p)}`,nextAction:`Check permissions on ${t}`}}let r;try{r=JSON.parse(n)}catch{return{ok:!1,reason:"product_telemetry_state_malformed_json",nextAction:`Fix or delete ${t} (delete = consent returns to unset)`}}if(typeof r!="object"||r===null||Array.isArray(r))return{ok:!1,reason:"product_telemetry_state_malformed_shape",nextAction:`Fix or delete ${t} (delete = consent returns to unset)`};let i=r,{schemaVersion:o}=i,a=o===S8e,s=o===Yx;if(!a&&!s)return{ok:!1,reason:`product_telemetry_state_malformed: schemaVersion must be '${Yx}' or legacy '${S8e}'`,nextAction:`Fix or delete ${t} (delete = consent returns to unset)`};let c=a?["consent","consentVersion","telemetrySecret","lastAttemptedAt","lastSucceededAt","lastFailureCode","nextRetryAt","dailyAttemptCount","attemptBucketDate","schemaVersion"]:["consent","consentVersion","telemetrySecret","workspaceExports","schemaVersion"],l=[];for(let p of Object.keys(i))c.includes(p)||l.push(`unknown field '${p}'`);if(A8e(i.consent)||l.push("consent must be unset|granted|denied"),(typeof i.consentVersion!="string"||i.consentVersion.length===0||i.consentVersion.length>8)&&l.push("consentVersion must be a short non-empty string"),!Od(i.telemetrySecret)&&i.telemetrySecret!==void 0&&l.push("telemetrySecret must be 64 hex chars when present"),!a){if(i.workspaceExports!==void 0)if(typeof i.workspaceExports!="object"||i.workspaceExports===null||Array.isArray(i.workspaceExports))l.push("workspaceExports must be an object");else{let p=i.workspaceExports,f=Object.keys(p);f.length>k8e&&l.push(`workspaceExports must track at most ${k8e} workspaces`);for(let m of f){if(!R8e(m)){l.push(`workspaceExports key '${m}' must be 4\u201332 hex chars`);continue}let y=p[m];if(typeof y!="object"||y===null||Array.isArray(y)){l.push(`workspaceExports['${m}'] must be an object`);continue}l.push(...Jnn(y,`workspaceExports['${m}']`))}}}if(l.length>0)return{ok:!1,reason:`product_telemetry_state_malformed: ${l.join("; ")}`,nextAction:`Fix or delete ${t} (delete = consent returns to unset)`};let u={consent:A8e(i.consent)?i.consent:"unset",consentVersion:typeof i.consentVersion=="string"?i.consentVersion:ug,...Od(i.telemetrySecret)?{telemetrySecret:i.telemetrySecret}:{},...s&&C8e(i.workspaceExports)?{workspaceExports:Object.fromEntries(Object.entries(i.workspaceExports).filter(([p,f])=>R8e(p)&&C8e(f)).map(([p,f])=>{let m=f;return[p,{...dk(m.lastAttemptedAt)&&m.lastAttemptedAt!==void 0?{lastAttemptedAt:m.lastAttemptedAt}:{},...dk(m.lastSucceededAt)&&m.lastSucceededAt!==void 0?{lastSucceededAt:m.lastSucceededAt}:{},...dk(m.nextRetryAt)&&m.nextRetryAt!==void 0?{nextRetryAt:m.nextRetryAt}:{},...L8e(m.lastFailureCode)&&m.lastFailureCode!==void 0?{lastFailureCode:m.lastFailureCode}:{},...O8e(m.dailyAttemptCount)&&m.dailyAttemptCount!==void 0?{dailyAttemptCount:m.dailyAttemptCount}:{},...P8e(m.attemptBucketDate)&&m.attemptBucketDate!==void 0?{attemptBucketDate:m.attemptBucketDate}:{}}]}))}:{},schemaVersion:Yx};return u.workspaceExports!==void 0&&Object.keys(u.workspaceExports).length===0&&delete u.workspaceExports,{ok:!0,state:u,existed:!0}}function D8e(e,t){let n=e.workspaceExports;if(n===void 0)return e;let r=t-Ynn*24*60*60*1e3,i={};for(let[a,s]of Object.entries(n)){let c=[s.lastAttemptedAt,s.lastSucceededAt].filter(u=>u!==void 0).map(u=>Date.parse(u)),l=c.length>0?Math.max(...c):Number.NEGATIVE_INFINITY;Number.isNaN(l)||l<r||(i[a]=s)}let o={...e};return Object.keys(i).length>0?o.workspaceExports=i:delete o.workspaceExports,o}function CD(e,t){let n=Jx(e),r=Jae.dirname(n),i=`${n}.tmp-${process.pid}-${Date.now()}`;try{return RD.mkdirSync(r,{recursive:!0}),RD.writeFileSync(i,`${JSON.stringify(t,null,2)}
1911
1913
  `,{encoding:"utf8",mode:384}),RD.renameSync(i,n),{ok:!0}}catch(o){let a=o instanceof Error?o.message:String(o);try{RD.rmSync(i,{force:!0})}catch{}return{ok:!1,reason:`product_telemetry_state_write_failed: ${a}`,nextAction:`Check permissions on ${r}`}}}function N8e(e){return{consent:"granted",consentVersion:ug,telemetrySecret:Od(e.telemetrySecret)?e.telemetrySecret:R1(),...e.workspaceExports!==void 0?{workspaceExports:e.workspaceExports}:{},schemaVersion:Yx}}function M8e(){return{consent:"denied",consentVersion:ug,schemaVersion:Yx}}function $8e(e){return{consent:e.consent,consentVersion:ug,...e.consent==="granted"?{telemetrySecret:R1()}:{},schemaVersion:Yx}}import F8e from"node:fs";import _K from"node:path";function Xnn(e){return e==="1"||e==="true"}function U8e(e){return e!==void 0&&e!==""&&e!=="false"&&e!=="0"}function Qnn(e){let t=_K.resolve(e);for(let n=0;n<8;n+=1){let r=F8e.existsSync(_K.join(t,"packages","principles-core")),i=F8e.existsSync(_K.join(t,"packages","host-runtime"));if(r&&i)return!0;let o=_K.dirname(t);if(o===t)break;t=o}return!1}function W8e(e){let t=[];return Xnn(e.env.killSwitch)&&t.push("env_kill_switch"),U8e(e.env.ci)&&t.push("ci_environment"),U8e(e.env.vitest)&&t.push("vitest_environment"),e.env.e2eMode==="1"&&t.push("e2e_mode"),(e.workspaceEnvironment==="test"||e.workspaceEnvironment==="demo"||e.workspaceEnvironment==="development")&&t.push("workspace_environment"),e.installMode==="missing"&&t.push("install_layout_missing"),Qnn(e.moduleDir)&&t.push("repo_checkout"),{suppressed:t.length>0,reasons:t}}var Qae="https://principles-website.pages.dev/api/product-telemetry/snapshot";function Znn(e,t){return fetch.call(globalThis,e,t)}async function j8e(e){let t=e.endpoint??Qae,n=e.timeoutMs??8e3,r=e.fetchFn??Znn,i=JSON.stringify(e.snapshot);if(Buffer.byteLength(i,"utf8")>4096)return{ok:!1,code:"invalid_response",retryable:!1};let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(t,{method:"POST",headers:{"content-type":"application/json"},body:i,signal:o.signal}),{status:c}=s;return c>=200&&c<300?{ok:!0,status:c}:c===400?{ok:!1,code:"http_400",retryable:!1}:c===429?{ok:!1,code:"http_429",retryable:!0}:c>=500?{ok:!1,code:"http_5xx",retryable:!0}:{ok:!1,code:"http_unexpected_status",retryable:!1}}catch(s){return s instanceof Error&&s.name==="AbortError"?{ok:!1,code:"timeout",retryable:!0}:{ok:!1,code:"network_error",retryable:!0}}finally{clearTimeout(a)}}function q8e(e){return e?360*60*1e3:3600*1e3}import vK from"node:fs";import PD from"node:path";import ern from"better-sqlite3";var trn="principle_receipt_ledger";function nrn(e,t){return e===!0||t===!0?!0:e===!1&&t===!1?!1:null}function G8e(e,t,n){let{notes:r,unavailableNote:i}=n,o={};try{if(!vK.existsSync(e)){for(let s of Object.keys(t))o[s]=!1;return o}}catch{for(let s of Object.keys(t))o[s]=null;return r.push(i),o}let a;try{a=new ern(e,{readonly:!0})}catch(s){let c=s instanceof Error?s.message.split(`
1912
1914
  `)[0]:String(s);for(let l of Object.keys(t))o[l]=null;return r.push(`${i}: ${c}`),o}try{for(let[s,c]of Object.entries(t))try{o[s]=a.prepare(c).pluck().get()===1}catch(l){let u=l instanceof Error?l.message.split(`
1913
- `)[0]:String(l);o[s]=null,r.push(`${i}: ${u}`)}}finally{a.close()}return o}function Zae(e){let t=[],n={initialized:!1,painObserved:!1,principleObserved:!1,activationObserved:!1,presenceReceiptObserved:!1,effectReceiptObserved:!1,initializationFailed:!1},r=PD.resolve(e),i=PD.join(r,".pd","state.db"),o=vK.existsSync(i),a=G8e(i,{schemaTableExists:"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_version')",schemaVersionPopulated:"SELECT EXISTS(SELECT 1 FROM schema_version)",principleCandidates:"SELECT EXISTS(SELECT 1 FROM principle_candidates)",activations:"SELECT EXISTS(SELECT 1 FROM activations)",presenceReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='presence')",effectReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='effect')"},{notes:t,unavailableNote:"state_db_unreadable"});o||t.push("state_db_missing");let s=a.schemaTableExists??null,c=a.schemaVersionPopulated??null;n.initialized=s===null?null:s===!1?!1:c??null,n.initializationFailed=o?n.initialized===null?null:!n.initialized:!1,n.principleObserved=a.principleCandidates??null,n.activationObserved=a.activations??null,dr(r,trn).enabled?(n.presenceReceiptObserved=a.presenceReceipts??null,n.effectReceiptObserved=a.effectReceipts??null):(n.presenceReceiptObserved=null,n.effectReceiptObserved=null,t.push("receipt_collection_disabled"));let u=G8e(PD.join(r,".state","trajectory.db"),{painEvents:"SELECT EXISTS(SELECT 1 FROM pain_events)"},{notes:t,unavailableNote:"trajectory_db_unreadable"});n.painObserved=u.painEvents??null;let p=!1,f=PD.join(r,".state"),m=PD.join(f,"principle_training_state.json");if((()=>{try{return vK.existsSync(m)}catch{return!1}})())if(!(()=>{try{return JSON.parse(vK.readFileSync(m,"utf8")),!0}catch{return!1}})())p=null,t.push("principle_ledger_malformed");else try{let I=Bn(f)?.tree?.principles;p=I!==null&&typeof I=="object"&&Object.keys(I).length>0}catch{p=null,t.push("principle_ledger_malformed")}return n.principleObserved=nrn(n.principleObserved,p),{facts:n,notes:t}}import dl from"node:fs";import lrn from"node:os";import OD from"node:path";import{fileURLToPath as urn}from"node:url";import*as wa from"node:path";var B8e=1;var rrn=["codex","openclaw"];function irn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function orn(e){return typeof e=="string"&&rrn.includes(e)}function arn(e){if(e===void 0)return{workspaces:[]};if(!Array.isArray(e))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let t=[];for(let n of e){if(typeof n!="string"||n.length===0||!wa.isAbsolute(n))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let r=wa.resolve(n);t.includes(r)||t.push(r)}return{workspaces:t}}function ese(e){if(!irn(e))return{error:"install_manifest_malformed: expected an object"};if(e.layoutVersion!==B8e)return{error:`install_manifest_unsupported_version: ${String(e.layoutVersion)}`};if(e.mode!=="canonical"&&e.mode!=="legacy")return{error:"install_manifest_malformed: mode must be canonical or legacy"};if(!Array.isArray(e.hosts)||e.hosts.length===0||!e.hosts.every(orn))return{error:"install_manifest_malformed: hosts must contain codex and/or openclaw"};let t=[...new Set(e.hosts)],n=arn(e.workspaces);return n.error?{error:n.error}:{manifest:{layoutVersion:B8e,mode:e.mode,hosts:t,workspaces:n.workspaces}}}function tse(e){let t=wa.resolve(e),n=wa.join(t,".pd"),r=wa.join(n,"runtime"),i=wa.join(t,".openclaw");return{homeDir:t,pdDir:n,manifest:wa.join(n,"install.json"),runtimeDir:r,pluginDir:wa.join(r,"plugin"),installLayoutDir:wa.join(r,"install-layout"),coreDir:wa.join(r,"core"),hostRuntimeDir:wa.join(r,"host-runtime"),pdCliDir:wa.join(r,"pd-cli"),consoleDir:wa.join(r,"console"),binDir:wa.join(r,"bin"),codexDir:wa.join(n,"codex"),openClawDir:i,openClawExtensionDir:wa.join(i,"extensions","principles-disciple")}}function K8e(e){let t=tse(e.homeDir),n=ese(e.manifest);return n.manifest&&n.manifest.mode==="canonical"&&e.canonicalRuntimeExists?{mode:"canonical",paths:t,manifest:n.manifest}:e.legacyExtensionExists?{mode:"legacy",paths:t,...n.manifest?{manifest:n.manifest}:{},reason:n.error??"install_layout_legacy_fallback",nextAction:"Run the installer update to migrate the shared runtime to ~/.pd/runtime."}:{mode:"missing",paths:t,reason:n.error??"install_runtime_missing",nextAction:"Run npx create-principles-disciple to install or repair PD."}}import srn from"node:fs";import H8e from"node:path";function crn(e){let t=H8e.resolve(e);try{t=srn.realpathSync(t)}catch{}let n=t.split(H8e.sep).join("/");return process.platform==="win32"&&(n=n.toLowerCase()),n.length>1&&n.endsWith("/")&&(n=n.slice(0,-1)),n}function xK(e,t){return v6(e,crn(t))}function V8e(e,t){return`${e}.export-lock.${t}`}var z8e="anonymous_product_telemetry",Y8e="PD_TELEMETRY_DISABLED",drn="Preview only. Nothing was sent.",prn=5,frn=300*1e3,mrn=5*1e3,J8e=3*1e3,hrn=15,grn=e=>new Promise(t=>setTimeout(t,e));function yrn(e,t){let n=V8e(e,t),r=()=>{try{let i=dl.openSync(n,"wx");try{dl.writeSync(i,`${process.pid} ${new Date().toISOString()}`)}finally{dl.closeSync(i)}return!0}catch{return!1}};if(r())return{acquired:!0,lockPath:n};try{let i=dl.statSync(n);if(Date.now()-i.mtimeMs>frn&&(dl.rmSync(n,{force:!0}),r()))return{acquired:!0,lockPath:n}}catch{}return{acquired:!1}}function X8e(e){try{dl.rmSync(e,{force:!0})}catch{}}async function _rn(e){let t=`${e}.state-lock`,n=Date.now()+J8e,r=()=>{try{let i=dl.openSync(t,"wx");try{dl.writeSync(i,`${process.pid} ${new Date().toISOString()}`)}finally{dl.closeSync(i)}return!0}catch{return!1}};for(;;){if(r())return{acquired:!0,lockPath:t};try{let i=dl.statSync(t);if(Date.now()-i.mtimeMs>mrn&&(dl.rmSync(t,{force:!0}),r()))return{acquired:!0,lockPath:t}}catch{}if(Date.now()>=n)return{acquired:!1};await grn(hrn)}}async function vrn(e){let t=Jx(e.homeDir),n=await _rn(t);if(!n.acquired)return"skipped_contention";try{let r=$h(e.homeDir);if(!r.ok)return"skipped_unreadable";if(r.state.consent!=="granted"||r.state.telemetrySecret!==e.secret)return"skipped_identity_changed";let i=D8e(r.state,e.timestamp),o={...i,workspaceExports:{...i.workspaceExports??{},[e.scopeKey]:e.nextEntry}};return CD(e.homeDir,o).ok?"written":"skipped_unreadable"}finally{X8e(n.lockPath)}}var xrn=OD.dirname(urn(import.meta.url));function nse(e){try{return JSON.parse(dl.readFileSync(e,"utf8"))}catch{return}}function rse(e){let t=tse(e),r=ese(nse(t.manifest)).manifest,i=dl.existsSync(t.hostRuntimeDir),o=dl.existsSync(t.openClawExtensionDir),a=K8e({homeDir:e,manifest:r,canonicalRuntimeExists:i,legacyExtensionExists:o}),s="other";r&&r.hosts.length===1&&(r.hosts[0]==="codex"||r.hosts[0]==="openclaw")?[s]=r.hosts:o&&(s="openclaw");let c=nse(OD.join(t.pluginDir,"package.json"))??nse(OD.join(t.openClawExtensionDir,"package.json")),l=c!==null&&typeof c=="object"&&!Array.isArray(c)?c.version:void 0,u=typeof l=="string"?l.slice(0,32):"unknown";return{installMode:a.mode,hostKind:s,pdVersion:u}}function brn(e){return e?oi(e).effective.config.workspace?.environment??"unknown":"unknown"}function Q8e(e={}){let t=()=>OD.resolve(e.homeDir??lrn.homedir()),n=()=>e.env??process.env,r=()=>OD.resolve(e.moduleDir??xrn),i=()=>(e.now??Date.now)(),o=e.logger??{};function a(l){return W8e({env:{killSwitch:n()[Y8e],ci:n().CI,vitest:n().VITEST,e2eMode:n().PD_E2E_MODE},workspaceEnvironment:brn(l),installMode:rse(t()).installMode,moduleDir:r()})}function s(l,u){let p=null,f=null;if(u){let _=dr(u,z8e);p=_.enabled,f=_.source}let m=a(u),y=[];return p===null?y.push("feature_flag_unresolved"):p!==!0&&y.push("feature_flag_disabled"),l.consent!=="granted"&&y.push(`consent_${l.consent}`),y.push(...m.reasons),{flagEnabled:p,flagSource:f,consent:l.consent,environmentSuppressed:m.suppressed,suppressionReasons:m.reasons,canExport:y.length===0,blockers:y}}function c(l){if(!l.canExport)return l.suppressionReasons.includes("env_kill_switch")?`Unset ${Y8e} to allow telemetry export.`:l.flagEnabled===!1?`Set features.${z8e}.enabled: true in the workspace .pd/config.yaml.`:l.consent!=="granted"?"Run: pd telemetry enable --confirm":l.environmentSuppressed?`Telemetry is suppressed in this environment (${l.suppressionReasons.join(", ")}). This is expected for CI/test/dev environments.`:"Resolve the blockers listed above."}return{getStatus(l){let u=$h(t());if(!u.ok)return u;let p=s(u.state,l),f,m=u.state.telemetrySecret;if(l!==void 0&&Od(m)){let _=xK(m,l);f=u.state.workspaceExports?.[_]}return{ok:!0,view:{...p,consentVersion:u.state.consentVersion,hasSecret:Od(u.state.telemetrySecret),...f?.lastAttemptedAt!==void 0?{lastAttemptedAt:f.lastAttemptedAt}:{},...f?.lastSucceededAt!==void 0?{lastSucceededAt:f.lastSucceededAt}:{},...f?.lastFailureCode!==void 0?{lastFailureCode:f.lastFailureCode}:{},...f?.nextRetryAt!==void 0?{nextRetryAt:f.nextRetryAt}:{},endpoint:e.endpoint??Qae,...c(p)!==void 0?{nextAction:c(p)}:{}}}},preview(l){let u=$h(t()),p=u.ok?u.state:Xae(),f=s(p,l),m=i(),y=aI(m),_=!Od(p.telemetrySecret),b=p.telemetrySecret??"0".repeat(64),I=xK(b,l),E=rse(t()),{facts:R,notes:A}=Zae(l),P=L1({dailyTelemetryId:C1(b,I,y),bucketDate:y,pdVersion:E.pdVersion,hostKind:E.hostKind,milestones:{initialized:R.initialized,painObserved:R.painObserved,principleObserved:R.principleObserved,activationObserved:R.activationObserved,presenceReceiptObserved:R.presenceReceiptObserved,effectReceiptObserved:R.effectReceiptObserved},reliability:{initializationFailed:R.initializationFailed}}),O=[...A];return _&&O.push("payload shape is exact; dailyTelemetryId is provisional and will change after pd telemetry enable"),u.ok||O.push(`control state unreadable (${u.reason}) \u2014 showing defaults`),{banner:drn,snapshot:P,gates:f,notes:O,secretEphemeral:_}},enable(){let l=$h(t());if(!l.ok)return l;let u=N8e(l.state),p=CD(t(),u);return p.ok?(o.info?.(`[PD:Telemetry] Consent granted (control state: ${Jx(t())}).`),{ok:!0,consent:"granted"}):p},disable(){let l=$h(t());if(!l.ok)return l;let u=CD(t(),M8e());return u.ok?(o.info?.("[PD:Telemetry] Consent denied; local telemetry secret and export status deleted. Future export requests: 0."),{ok:!0,consent:"denied"}):u},reset(){let l=$h(t());if(!l.ok)return l;let u=$8e(l.state),p=CD(t(),u);return p.ok?(o.info?.("[PD:Telemetry] Telemetry identity reset; previous daily IDs are unlinkable going forward."),{ok:!0,consent:u.consent}):p},async maybeExportDaily(l){let u=$h(t());if(!u.ok)return o.warn?.(`[PD:Telemetry] Export skipped: ${u.reason}`),{attempted:!1,skipReason:"control_state_unreadable"};let{state:p}=u,f=s(p,l);if(!f.flagEnabled)return{attempted:!1,skipReason:"feature_flag_disabled"};if(p.consent!=="granted")return{attempted:!1,skipReason:`consent_${p.consent}`};if(f.environmentSuppressed)return o.info?.(`[PD:Telemetry] Export suppressed (${f.suppressionReasons.join(", ")}).`),{attempted:!1,skipReason:`environment_suppressed:${f.suppressionReasons.join("+")}`};if(!Od(p.telemetrySecret))return o.warn?.("[PD:Telemetry] Export skipped: telemetry secret missing/invalid. Run: pd telemetry enable --confirm"),{attempted:!1,skipReason:"secret_missing"};let m=p.telemetrySecret,y=i(),_=aI(y),b=xK(m,l),I=p.workspaceExports?.[b];if(I?.lastSucceededAt!==void 0&&aI(Date.parse(I.lastSucceededAt))===_)return{attempted:!1,skipReason:"already_succeeded_today"};if(I?.nextRetryAt!==void 0&&y<Date.parse(I.nextRetryAt))return{attempted:!1,skipReason:"retry_backoff"};let E=I?.attemptBucketDate===_?I?.dailyAttemptCount??0:0;if(E>=prn)return{attempted:!1,skipReason:"daily_attempt_cap"};let R=yrn(Jx(t()),b);if(!R.acquired||R.lockPath===void 0)return o.info?.("[PD:Telemetry] Export skipped: another export is in flight for this workspace (lock busy)."),{attempted:!1,skipReason:"export_lock_busy"};try{let A=$h(t()),P=A.ok?A.state.telemetrySecret:void 0,O=A.ok&&P===m?A.state:p;if(Od(O.telemetrySecret)){let Ie=O.workspaceExports?.[b];if(Ie?.lastSucceededAt!==void 0&&aI(Date.parse(Ie.lastSucceededAt))===_)return{attempted:!1,skipReason:"already_succeeded_today"}}let $=rse(t()),{facts:M}=Zae(l),U=L1({dailyTelemetryId:C1(m,b,_),bucketDate:_,pdVersion:$.pdVersion,hostKind:$.hostKind,milestones:{initialized:M.initialized,painObserved:M.painObserved,principleObserved:M.principleObserved,activationObserved:M.activationObserved,presenceReceiptObserved:M.presenceReceiptObserved,effectReceiptObserved:M.effectReceiptObserved},reliability:{initializationFailed:M.initializationFailed}}),K=await j8e({snapshot:U,...e.endpoint!==void 0?{endpoint:e.endpoint}:{},...e.fetchFn!==void 0?{fetchFn:e.fetchFn}:{}}),ce=O.workspaceExports?.[b],ie=ce?.lastAttemptedAt!==void 0&&y-Date.parse(ce.lastAttemptedAt)<1440*60*1e3,Se=K.ok?{lastAttemptedAt:new Date(y).toISOString(),lastSucceededAt:new Date(y).toISOString()}:{lastAttemptedAt:new Date(y).toISOString(),lastFailureCode:K.code,nextRetryAt:new Date(y+q8e(ie)).toISOString(),dailyAttemptCount:E+1,attemptBucketDate:_},Ge=await vrn({homeDir:t(),secret:m,scopeKey:b,timestamp:y,nextEntry:Se});return Ge==="skipped_contention"?o.warn?.(`[PD:Telemetry] Export ${K.ok?"succeeded":`failed (${K.code})`} but control state update was skipped after ${J8e/1e3}s of state-lock contention \u2014 this workspace may re-attempt today.`):Ge==="skipped_unreadable"?o.warn?.(`[PD:Telemetry] Export ${K.ok?"succeeded":`failed (${K.code})`} but control state could not be read/updated \u2014 ${Jx(t())}`):Ge==="skipped_identity_changed"&&o.info?.("[PD:Telemetry] Export finished after a consent/secret change; stale export bookkeeping was NOT written back."),K.ok?(o.info?.("[PD:Telemetry] Daily anonymous product telemetry snapshot exported."),{attempted:!0,ok:!0,httpStatus:K.status}):(o.warn?.(`[PD:Telemetry] Export failed (${K.code}); next retry after ${Se.nextRetryAt}. PD behavior is unaffected.`),{attempted:!0,ok:!1,failureCode:K.code})}finally{X8e(R.lockPath)}}}}function Z8e(e,t,n){setTimeout(()=>{e.maybeExportDaily(t).catch(i=>{let o=i instanceof Error?i.message:String(i);n?.warn?.(`[PD:Telemetry] Unexpected export error (PD unaffected): ${o}`)})},0).unref?.()}var bK=["before_prompt_build","before_tool_call","after_tool_call"],pk=class extends Error{reason;nextAction;constructor(t,n){super(`${t}: ${n}`),this.reason=t,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function Irn(e,t){switch(e.kind){case"before_prompt_build":return t.beforePromptBuild;case"before_tool_call":return t.beforeToolCall;case"after_tool_call":return t.afterToolCall;default:throw new pk("unsupported_host_event",`Only ${bK.join(", ")} are supported by the MVP host runtime`)}}function Xx(e){return typeof e=="string"&&e.trim().length>0}function t7e(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function wrn(e){return!Xx(e.context.workspaceDir)||!t7e(e.context.workspaceDir)||!Xx(e.context.sessionId)||!Xx(e.source)?!1:e.kind==="before_tool_call"||e.kind==="after_tool_call"?Xx(e.context.toolName):!0}function e7e(e){return e===void 0||Xx(e)}function Trn(e,t){if(t.warnings!==void 0&&(!Array.isArray(t.warnings)||!t.warnings.every(Xx))||t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null||Array.isArray(t.metadata))||!Xx(t.source)||!e7e(t.reason)||!e7e(t.additionalContext))return!1;let n=t.reason!==void 0,r=t.modifiedInput!==void 0,i=t.additionalContext!==void 0;switch(e.kind){case"before_prompt_build":return(t.decision==="allow"||t.decision==="modify")&&!n&&!r;case"before_tool_call":return t.decision==="observe"?!1:t.decision==="deny"?n&&!r&&!i:n?!1:!r||t.decision==="modify";case"after_tool_call":return t.decision==="observe"&&!n&&!r&&!i;default:return!1}}function Ern(e){return{async dispatch(t){if(!V3(t)||!wrn(t))throw new pk("invalid_host_event","Decode and validate the host event before dispatch");let n=await Irn(t,e)(t);if(!z3(n)||!Trn(t,n))throw new pk("invalid_handler_result",`Handler for ${t.kind} must return a valid HostEventResult`);if(n.source!==t.source)throw new pk("lineage_mismatch",`Handler result source must match event source ${t.source}`);return n},async health(t){return t.trim().length===0?{ok:!1,workspaceDir:t,routes:bK,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:t7e(t)?{ok:!0,workspaceDir:t,routes:bK}:{ok:!1,workspaceDir:t,routes:bK,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function n7e(e={}){let t=p8e({...e.ruleContextProvider?{ruleContextProvider:e.ruleContextProvider}:{},...e.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:e.ruleInputEnrichmentProvider}:{},...e.ruleImplementationRuntime?{implementationRuntime:e.ruleImplementationRuntime}:{}});return Ern({afterToolCall:e.afterToolCall??g8e({...e.painEnrichmentProvider?{painEnrichmentProvider:e.painEnrichmentProvider}:{},...e.painDatabaseFactory?{painDatabaseFactory:e.painDatabaseFactory}:{}}),beforeToolCall:e.beforeToolCall??t,async beforePromptBuild(n){let r=await s8e({workspaceDir:n.context.workspaceDir,excludePrincipleIds:e.promptExcludePrincipleIds?.(n)});return e.beforePromptBuild?e.beforePromptBuild(n,r):{decision:r.additionalContext.length>0?"modify":"allow",source:n.source,...r.additionalContext.length>0?{additionalContext:r.additionalContext}:{}}}})}function Fh(e){return{source:e.source}}function Qx(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,baseUrl:null}}function Srn(e){return Qs.some(t=>t===e)}function LD(e,t,n,r){let i=oi(e);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...Fh(i),...Qx(),reason:`Config validation failed: ${i.errors.map(f=>f.reason).join("; ")}`,nextAction:i.errors[0]?.nextAction??"Fix .pd/config.yaml and retry",configErrors:i.errors};let o=i.effective.config;if(!o.features[t]?.enabled)return{enabled:!1,readiness:"disabled",...Fh(i),...Qx(),reason:`${t} is disabled in .pd/config.yaml`,nextAction:`Set features.${t}.enabled=true in .pd/config.yaml to enable`};if(!Srn(n))return{enabled:!1,readiness:"needs_setup",...Fh(i),...Qx(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${Qs.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...Fh(i),...Qx(),reason:`${t} feature flag is enabled but internalAgents.agents.${n}.enabled is false`,nextAction:`Set internalAgents.agents.${n}.enabled=true in .pd/config.yaml, or disable features.${t}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,l=o.runtimeProfiles[c];if(!l)return{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,reason:`Runtime profile '${c}' not found in .pd/config.yaml`,nextAction:`Add runtime profile '${c}' to .pd/config.yaml runtimeProfiles`};if(l.type!=="pi-ai")return{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,runtimeProfileType:l.type,provider:l.provider??null,model:l.model??null,reason:`OpenClaw profile '${c}' is not supported for observer runtime. Observers require a pi-ai profile with an API key.`,nextAction:`Configure a pi-ai runtime profile for ${n} in .pd/config.yaml (e.g., add a pi-ai profile with provider, model, and apiKeyEnv)`};let u=l.apiKeyEnv??null;return u?Object.hasOwn(process.env,u)&&!!process.env[u]?{enabled:!0,readiness:"not_ready",...Fh(i),runtimeProfileId:c,runtimeProfileType:l.type,apiKeyEnv:u,apiKeyPresent:!0,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`pi-ai profile configured with apiKeyEnv='${u}' (key present); runtime availability unknown`,nextAction:"Run pd runtime probe to verify end-to-end connectivity"}:{enabled:!0,readiness:"needs_setup",...Fh(i),runtimeProfileId:c,runtimeProfileType:l.type,apiKeyEnv:u,apiKeyPresent:!1,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`Environment variable '${u}' is not set or empty`,nextAction:`Set the environment variable '${u}' with a valid API key`}:{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,runtimeProfileType:l.type,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`pi-ai profile '${c}' missing apiKeyEnv`,nextAction:`Add apiKeyEnv to runtime profile '${c}' in .pd/config.yaml`}}function r7e(e,t){let n=Q8e({...t!==void 0?{logger:t}:{}});Z8e(n,e,t)}import{existsSync as p7e,readFileSync as Orn,writeFileSync as Lrn,renameSync as Drn}from"fs";import{homedir as Nrn}from"os";import*as f7e from"path";import*as lo from"fs";import*as o7e from"path";var ise=class extends Error{filePath;lockPath;constructor(t,n,r){super(t),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},a7e={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function s7e(e){try{return process.kill(e,0),!0}catch{return!1}}function i7e(e,t){try{let n=o7e.dirname(e);lo.existsSync(n)||lo.mkdirSync(n,{recursive:!0});let r=lo.constants.O_WRONLY|lo.constants.O_CREAT|lo.constants.O_EXCL,i=lo.openSync(e,r);return lo.writeSync(i,String(t)),lo.fsyncSync(i),lo.closeSync(i),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function DD(e){try{let t=lo.readFileSync(e,"utf8"),n=parseInt(t.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function krn(e,t){try{DD(e)===t&&lo.unlinkSync(e)}catch{}}function Arn(e,t){try{let n=lo.statSync(e),r=DD(e),i=Date.now()-n.mtimeMs>t,o=r===null||!s7e(r);if(i||o)try{return lo.unlinkSync(e),!0}catch{return!1}return!1}catch{return!1}}function c7e(e,t,n){let r=Math.min(t*Math.pow(2,e),n),i=r*.2*Math.random();return Math.floor(r+i)}function Rrn(e){return new Promise(t=>setTimeout(t,e))}function Crn(e){let t=Date.now()+e;for(;Date.now()<t;);}function l7e(e,t){let n=DD(t),r=n!==null?s7e(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new ise(`Failed to acquire lock for ${e}. Lock holder: ${r}.`,e,t)}function u7e(e,t,n){let r=e+t.lockSuffix;return i7e(r,n)&&DD(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(Arn(r,t.lockStaleMs),i7e(r,n)&&DD(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function Prn(e,t={}){let n={...a7e,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=u7e(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=c7e(i,n.baseRetryDelayMs,n.maxRetryDelayMs);Crn(a)}}throw l7e(e,e+n.lockSuffix)}async function ose(e,t={}){let n={...a7e,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=u7e(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=c7e(i,n.baseRetryDelayMs,n.maxRetryDelayMs);await Rrn(a)}}throw l7e(e,e+n.lockSuffix)}function IK(e){krn(e.lockPath,e.pid)}function Va(e,t,n={}){let r=Prn(e,n);try{return t()}finally{IK(r)}}async function wK(e,t,n={}){let r=await ose(e,n);try{return await t()}finally{IK(r)}}function TK(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.plugins;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n.entries;if(!(!r||typeof r!="object"||Array.isArray(r)))return r[t]}var Mrn="allowConversationAccess",ase="openclaw config set plugins.entries.principles-disciple.hooks.allowConversationAccess true --strict-json";function MD(e){if(e==null||typeof e!="object"||Array.isArray(e))return{authorized:!1,reason:"pluginConfig is missing or invalid \u2014 conversation hooks cannot be registered",nextAction:ase};let t=e;return typeof t.hooks!="object"||t.hooks===null||Array.isArray(t.hooks)?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ase}:t.hooks[Mrn]!==!0?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ase}:{authorized:!0}}var d7e="principles-disciple";function $rn(){return f7e.join(Nrn(),".openclaw","openclaw.json")}function ND(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Frn(e){if(!p7e(e))return null;try{let t=Orn(e,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(t);return ND(n)?n:null}catch{return null}}function Urn(e,t){let n=e+".tmp."+Date.now();Lrn(n,JSON.stringify(t,null,2),"utf8"),Drn(n,e)}function EK(){let e=$rn();return p7e(e)?Va(e,()=>{let t=Frn(e);if(!t)return!1;ND(t.plugins)||(t.plugins={});let n=t.plugins;ND(n.entries)||(n.entries={});let r=n.entries,i=r[d7e],o=ND(i)?i:{enabled:!0};ND(o.hooks)||(o.hooks={});let a=o.hooks;return a.allowConversationAccess===!0?!1:(a.allowConversationAccess=!0,r[d7e]=o,Urn(e,t),!0)}):!1}function sse(e){return e.toLowerCase().startsWith("zh")?"zh":"en"}var Wrn={"pd-init":{zh:"\u521D\u59CB\u5316\u5DE5\u4F5C\u533A\uFF08\u751F\u6210 PRINCIPLES.md\u3001THINKING_OS.md \u7B49\uFF09",en:"Initialize workspace (generate PRINCIPLES.md, THINKING_OS.md, etc.)"},"pd-bootstrap":{zh:"\u626B\u63CF\u73AF\u5883\u5DE5\u5177\u5E76\u5EFA\u8BAE\u5347\u7EA7",en:"Scan environment tools and suggest upgrades"},"pd-research":{zh:"\u7814\u7A76\u5DE5\u5177\u5347\u7EA7\u65B9\u6848",en:"Research tool upgrade solutions"},"pd-help":{zh:"\u663E\u793A\u6240\u6709\u547D\u4EE4\u548C\u4F7F\u7528\u6307\u5357",en:"Show all commands and usage guide"},"pd-status":{zh:"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001\uFF08GFI\u3001Pain \u8BCD\u5178\uFF09",en:"View system status (GFI, Pain dictionary)"},"pd-context":{zh:"\u63A7\u5236\u4E0A\u4E0B\u6587\u6CE8\u5165 [status|thinking|reflection|focus|preset] - \u8F93\u5165 /pd-context help \u67E5\u770B\u8BE6\u60C5",en:"Control context injection [status|thinking|reflection|focus|preset] - Type /pd-context help for details"},"pd-focus":{zh:"\u7BA1\u7406 CURRENT_FOCUS.md [status|history|compress|rollback] - \u67E5\u770B/\u538B\u7F29/\u56DE\u6EDA\u7126\u70B9\u6587\u4EF6",en:"Manage CURRENT_FOCUS.md [status|history|compress|rollback] - View/compress/rollback focus file"},"pd-evolution-status":{zh:"\u67E5\u770B evolution \u95ED\u73AF\u72B6\u6001\uFF08candidate/probation/active\uFF09",en:"Show evolution loop status (candidate/probation/active)"},"pd-principle-rollback":{zh:"\u56DE\u6EDA\u539F\u5219\u5E76\u52A0\u5165\u9ED1\u540D\u5355 <principle-id> [reason]",en:"Rollback principle and blacklist pattern <principle-id> [reason]"},"pd-rollback":{zh:"\u56DE\u6EDA\u60C5\u7EEA\u4E8B\u4EF6\u60E9\u7F5A <event-id>|last",en:"Rollback empathy event penalty <event-id>|last"},"pd-export":{zh:"\u5BFC\u51FA\u6570\u636E [analytics|corrections --redacted]",en:"Export data [analytics|corrections --redacted]"},"pd-samples":{zh:"\u67E5\u770B\u6216\u5BA1\u6838\u7EA0\u9519\u6837\u672C [review approve|reject <sample-id> [note]]",en:"List or review correction samples [review approve|reject <sample-id> [note]]"},"pd-pain":{zh:"\u4ECE OpenClaw \u4F1A\u8BDD\u62A5\u544A pain\uFF08context-bound provenance\uFF09",en:"Report pain from OpenClaw session (context-bound provenance)"},"pd-workflow-debug":{zh:"\u8C03\u8BD5 workflow \u72B6\u6001\u4E0E\u4E8B\u4EF6 [workflowId]",en:"Debug workflow state and events [workflowId]"},"pd-promote-impl":{zh:"\u63D0\u5347\u5019\u9009\u5B9E\u73B0\u5230 active [list|show <id>|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Promote candidate implementation to active [list|show <id>|<id>] (semi-deprecated)"},"pd-disable-impl":{zh:'\u7981\u7528 active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Disable active implementation [list|<id> --reason "..."] (semi-deprecated)'},"pd-archive-impl":{zh:"\u6C38\u4E45\u5F52\u6863\u5B9E\u73B0 [list|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Archive implementation permanently [list|<id>] (semi-deprecated)"},"pd-rollback-impl":{zh:'\u56DE\u6EDA\u5230\u4E0A\u4E00\u4E2A active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Rollback to previous active implementation [list|<id> --reason "..."] (semi-deprecated)'}};function Ta(e,t){let n=sse(t),r=Wrn[e];return r&&(r[n]||r.en)||e}import*as Zx from"path";var Rr=(...e)=>Zx.posix.join(...e);function jrn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function qrn(e,t){return jrn(e)?Zx.win32.join(e,t):e.startsWith("/")?Zx.posix.join(e,t):Zx.join(e,t)}var zn={IDENTITY:".principles",MODELS:Rr(".principles","models"),STATE:".state",MEMORY:"memory",OKR:Rr("memory","okr"),LOGS:Rr("memory","logs"),SESSIONS:Rr(".state","sessions"),PAIN_SAMPLES:Rr("memory","pain"),LOCKS:Rr("memory",".locks"),IMPL_CODE_DIR:Rr(".state","principles","implementations")},SK={PROFILE:Rr(zn.IDENTITY,"PROFILE.json"),PRINCIPLES:Rr(zn.IDENTITY,"PRINCIPLES.md"),THINKING_OS:Rr(zn.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:Rr(zn.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:zn.MODELS,STATE_DIR:zn.STATE,EVOLUTION_QUEUE:Rr(zn.STATE,"evolution_queue.json"),EVOLUTION_DIRECTIVE:Rr(zn.STATE,"evolution_directive.json"),WORKBOARD:Rr(zn.STATE,"WORKBOARD.json"),AGENT_SCORECARD:Rr(zn.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:Rr(zn.STATE,".pain_flag"),SYSTEM_CAPABILITIES:Rr(zn.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:Rr(zn.STATE,"pain_settings.json"),PAIN_CANDIDATES:Rr(zn.STATE,"pain_candidates.json"),TRAJECTORY_DB:Rr(zn.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:Rr(zn.STATE,"blobs"),EXPORTS_DIR:Rr(zn.STATE,"exports"),SESSION_DIR:zn.SESSIONS,DICTIONARY:Rr(zn.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:Rr(zn.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:Rr(zn.STATE,"workflows.yaml"),IMPL_CODE_DIR:zn.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:Rr(zn.LOGS,"SYSTEM.log"),REFLECTION_LOG:Rr(zn.MEMORY,"reflection-log.md"),USER_CONTEXT:Rr(zn.MEMORY,"USER_CONTEXT.md"),OKR_DIR:zn.OKR,CURRENT_FOCUS:Rr(zn.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:Rr(zn.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:Rr(zn.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:Rr(zn.LOCKS,"evolution")};function Pi(e,t){return qrn(e,SK[t])}import*as Ic from"path";import*as CK from"os";import*as h_ from"fs";var Grn={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},$D=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="PdError",this.category=Grn[r]??"execution_failed"}code;category},kK=class extends $D{constructor(t,n,r){super(`[PD:Lock] ${n}: queue lock unavailable for ${t}`,"LOCK_UNAVAILABLE",r),this.name="LockUnavailableError"}},AK=class extends $D{constructor(t,n){super(`[PD:Path] Unknown path key: ${t}`,"PATH_RESOLUTION_ERROR",n),this.name="PathResolutionError"}};var FD=class extends $D{constructor(t,n){super(`[PD:Sample] Correction sample not found: ${t}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};import*as au from"path";import*as fk from"fs";var m7e=3,Brn=50;function Pt(e,t){let n=e+".tmp";fk.writeFileSync(n,t,"utf8");let r;for(let i=0;i<m7e;i++)try{fk.renameSync(n,e);return}catch(o){r=o;let a=o.code;if(a==="EPERM"||a==="EBUSY"||a==="EACCES"){if(i<m7e-1){let s=Brn*Math.pow(2,i),c=Date.now()+s,l=!1;for(;Date.now()<c;)if(!l&&Date.now()>=c-10){try{Ke("fs").accessSync?.(n)}catch{}l=!0}}continue}break}try{fk.unlinkSync(n)}catch{}throw r}function g7e(e,t){if(!e)return"";let n=t.includes("\\")||t.length>=2&&t[1]===":",r=e.includes("\\")||e.length>=2&&e[1]===":",i=e;n!==r&&r&&(i=`/mnt/${e.charAt(0).toLowerCase()}${e.slice(2).replace(/\\/g,"/")}`);let o=i.startsWith("/")&&!r,a=!n,s;if(n){let c=au.resolve(t);if(o)s=i;else{let l=au.isAbsolute(i)?i:au.join(c,i);s=au.relative(c,l)}}else if(a&&o){let c=t.replace(/\\/g,"/");s=au.posix.relative(c,i)}else{let c=t.replace(/\\/g,"/"),l=au.isAbsolute(i)?i:au.posix.join(c,i.replace(/\\/g,"/"));s=au.posix.relative(c,l)}return s=s.replace(/\\/g,"/"),s.startsWith("../")?i:s}function h7e(e){let t=e.replace(/\\/g,"/");return t.endsWith("/")&&(t=t.slice(0,-1)),t}function RK(e,t){if(!e||!t||t.length===0)return!1;let n=h7e(e);for(let r of t){let i=h7e(r);if(n.startsWith(i)&&(n===i||n.charAt(i.length)==="/"))return!0}return!1}function Oi(e){return e==null?"":Array.isArray(e)?e.join(" "):e}var Krn=".openclaw/workspace";var cse="principles-disciple.json",Hrn=[Ic.join(process.cwd(),cse),Ic.join(CK.homedir(),".openclaw",cse),Ic.join(CK.homedir(),".principles",cse)];function Vrn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function zrn(e){return e.startsWith("/")}function mk(e){return Vrn(e)?Ic.win32:zrn(e)?Ic.posix:Ic}function Yrn(){for(let e of Hrn)if(h_.existsSync(e))return e;return null}function y7e(){let e=Yrn();if(!e)return null;try{let t=h_.readFileSync(e,"utf8"),n=JSON.parse(t);return console.log(`[PD:PathResolver] Loaded config from: ${e}`),n}catch(t){return console.warn(`[PD:PathResolver] Failed to load config from ${e}: ${String(t)}`),null}}var od=class e{static extensionRoot=null;workspaceDir=null;stateDir=null;logger;normalizeWorkspace;initialized=!1;static setExtensionRoot(t){if(!t||!t.trim())return;let n=t.trim(),r=mk(n);e.extensionRoot=r.normalize(n)}static getExtensionRoot(){return e.extensionRoot}constructor(t={}){if(this.logger=t.logger,this.normalizeWorkspace=t.normalizeWorkspace??!0,t.workspaceDir){let n=t.workspaceDir,r=this.normalizeWorkspace?this.normalizePath(n):n;n!==r&&this.log("info",`Workspace path normalized: ${n} -> ${r}`),this.workspaceDir=r,this.initialized=!0}}log(t,n){let i=`[PD:PathResolver] ${n}`;switch(process.env.DEBUG==="true"&&this.logger?.debug?.(i),t){case"debug":this.logger?.debug?.(i);break;case"info":this.logger?.info?.(i);break;case"warn":this.logger?.warn?.(i);break;case"error":this.logger?.error?.(i);break}}detectWorkspaceDir(){let t=process.env.PD_WORKSPACE_DIR;if(t&&t.trim())return this.log("info",`Using workspace from PD_WORKSPACE_DIR: ${t}`),t.trim();let n=process.env.OPENCLAW_WORKSPACE;if(n&&n.trim())return this.log("info",`Using workspace from OPENCLAW_WORKSPACE: ${n}`),n.trim();let r=y7e();if(r?.workspace)return this.log("info",`Using workspace from config file: ${r.workspace}`),r.workspace;let i=CK.homedir(),o=Ic.join(i,Krn);return this.log("info",`Using default workspace: ${o}`),o}normalizePath(t){let n=mk(t),r=n===Ic?Ic.resolve(t):n.normalize(t);if(this.normalizeWorkspace){let i=["/memory","/docs","\\memory","\\docs"];for(let o of i)if(r.endsWith(o)){let a=n.dirname(r);this.log("warn",`Detected subdirectory suffix '${o}' in path. Normalized to parent: ${a}`),r=a;break}}return r}normalizeWorkspacePath(t){return this.normalizePath(t)}getWorkspaceDir(){if(this.initialized&&this.workspaceDir)return this.workspaceDir;let t=this.detectWorkspaceDir();if(this.normalizeWorkspace){let n=t;t=this.normalizePath(t),n!==t&&this.log("info",`Workspace path normalized: ${n} -> ${t}`)}return this.workspaceDir=t,this.initialized=!0,this.log("debug",`Final workspace directory: ${this.workspaceDir}`),this.workspaceDir}getStateDir(){if(this.stateDir)return this.stateDir;let t=process.env.PD_STATE_DIR;if(t&&t.trim())return this.stateDir=t.trim(),this.log("info",`Using state directory from PD_STATE_DIR: ${this.stateDir}`),this.stateDir;if(this.initialized&&this.workspaceDir){let o=mk(this.workspaceDir);return this.stateDir=o.join(this.workspaceDir,".state"),this.log("debug",`Using workspace-based state directory: ${this.stateDir}`),this.stateDir}let n=y7e();if(n?.state)return this.stateDir=n.state,this.log("info",`Using state directory from config file: ${this.stateDir}`),this.stateDir;let r=this.getWorkspaceDir(),i=mk(r);return this.stateDir=i.join(r,".state"),this.log("debug",`Computed state directory: ${this.stateDir}`),this.stateDir}resolve(t){let n=this.getWorkspaceDir(),r=this.getStateDir(),i=mk(n),o=e.extensionRoot||Ic.resolve(process.cwd(),"packages","openclaw-plugin"),a=mk(o),s=i.join(n,"memory"),c=a.join(o,"src"),l=a.join(o,"dist"),u=h_.existsSync(c)?a.join(c,"service","evolution-worker.ts"):a.join(l,"service","evolution-worker.js"),f={PROFILE:i.join(n,".principles","PROFILE.json"),PRINCIPLES:i.join(n,".principles","PRINCIPLES.md"),THINKING_OS:i.join(n,".principles","THINKING_OS.md"),DECISION_POLICY:i.join(n,".principles","DECISION_POLICY.json"),MODELS_DIR:i.join(n,".principles","models"),AGENT_SCORECARD:i.join(r,"AGENT_SCORECARD.json"),PAIN_FLAG:i.join(r,".pain_flag"),EVOLUTION_QUEUE:i.join(r,"evolution_queue.json"),EVOLUTION_DIRECTIVE:i.join(r,"evolution_directive.json"),WORKBOARD:i.join(r,"WORKBOARD.json"),SYSTEM_CAPABILITIES:i.join(r,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:i.join(r,"pain_settings.json"),PAIN_CANDIDATES:i.join(r,"pain_candidates.json"),DICTIONARY:i.join(r,"pain_dictionary.json"),STATE_DIR:r,EXTENSION_ROOT:o,EXTENSION_SRC:c,EXTENSION_DIST:l,EVOLUTION_WORKER:u,LOGS:i.join(s,"logs"),SYSTEM_LOG:i.join(s,"logs","SYSTEM.log"),REFLECTION_LOG:i.join(s,"reflection-log.md"),USER_CONTEXT:i.join(s,"USER_CONTEXT.md"),OKR_DIR:i.join(s,"okr"),CURRENT_FOCUS:i.join(s,"okr","CURRENT_FOCUS.md"),WEEK_STATE:i.join(s,"okr","WEEK_STATE.json"),EVOLUTION_STREAM:i.join(s,"evolution.jsonl"),EVOLUTION_LOCK:i.join(s,".locks","evolution"),PRINCIPLE_BLACKLIST:i.join(r,"principle_blacklist.json"),MEMORY:s}[t];if(!f)throw this.log("warn",`Unknown path key: ${t}`),new AK(t);return this.log("debug",`Resolved path for '${t}': ${f}`),f}ensureStateDir(){let t=this.getStateDir();h_.existsSync(t)||(this.log("info",`Creating state directory: ${t}`),h_.mkdirSync(t,{recursive:!0}))}static createFromHookContext(t){let n=new e;if(t?.workspaceDir){let r=String(t.workspaceDir);n.normalizeWorkspace&&(r=n.normalizePath(r)),n.workspaceDir=r,n.initialized=!0,n.log("info",`Created from hook context with workspace: ${r}`)}return t?.stateDir&&(n.stateDir=String(t.stateDir)),n}};function _7e(e,t){if(!e)return;let n=e.runtime.agent;if(n?.resolveAgentWorkspaceDir)try{return n.resolveAgentWorkspaceDir(e.config,t??"main")}catch{}let r=e.config?.workspaceDir;if(r&&r.trim())return r.trim();try{return new od().getWorkspaceDir()}catch{return}}import*as v7e from"os";import*as x7e from"path";function Ea(e){if(!e)return"workspaceDir is undefined/null";if(/^[A-Za-z]:\\?$/.test(e))return`workspaceDir is a drive root: "${e}"`;let t=x7e.resolve(e),n=v7e.homedir();if(t===n)return`workspaceDir equals home directory (${n}), likely missing context field`;if(t==="/"||t==="")return`workspaceDir is root or empty: "${t}"`;if(/^[A-Za-z]:\\?$/.test(t))return`workspaceDir is a drive root: "${t}"`;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[{pattern:new RegExp(`^${r}[\\\\/]?$`),desc:"is home directory"}];for(let{pattern:o,desc:a}of i)if(o.test(t))return`workspaceDir ${a}: "${t}"`;return null}import*as eb from"fs";import*as OK from"path";var b7e={language:"zh",diagnostician:{context:{time_window_minutes:5,max_message_length:500,max_summary_length:3e3}},thresholds:{pain_trigger:40,cognitive_paralysis_input:4e3,stuck_loops_trigger:4,semantic_min_score:.7,promotion_count_threshold:3,promotion_similarity_threshold:.8},scores:{paralysis:45,default_confusion:30,default_loop:40,tool_failure_friction:15,exit_code_penalty:50,spiral_penalty:30,missing_test_command_penalty:20,subagent_error_penalty:60,subagent_timeout_penalty:50},severity_thresholds:{high:70,medium:40,low:20},intervals:{worker_poll_ms:900*1e3,initial_delay_ms:5e3,task_timeout_ms:3600*1e3},empathy_engine:{enabled:!0,dedupe_window_ms:6e4,penalties:{mild:10,moderate:25,severe:40},rate_limit:{max_per_turn:40,max_per_hour:120},model_calibration:{}},gfi_gate:{enabled:!0,thresholds:{low_risk_block:70,high_risk_block:40,large_change_block:50},large_change_lines:50,ep_tier_multipliers:{1:.5,2:.75,3:1,4:1.5,5:2},bash_safe_patterns:["^(ls|dir|pwd|which|where|echo|env|cat|type|head|tail|less|more)\\b","^git\\s+(status|log|diff|branch|show|remote)\\b","^npm\\s+(run|test|build|start)\\b","^make\\s*$","^make\\s+(-j\\d+|--jobs\\s*\\d+)$","^(gradle|mvn)\\s+(clean|build|test|compile)\\b"],bash_dangerous_patterns:["rm\\s+(-[a-z]*r[a-z]*f|-rf)","del\\s+/s","rmdir\\s+/s","git\\s+(push\\s+.*--force|reset\\s+--hard|clean\\s+-fd)","npm\\s+publish","pip\\s+upload","docker\\s+push","(curl|wget).*\\|\\s*(ba)?sh"]},compression:{line_threshold:100,size_threshold_kb:15,interval_hours:24,keep_completed_tasks:3,max_working_memory_artifacts:10}},PK=class{settings={...b7e};filePath;constructor(t){this.filePath=OK.join(t,"pain_settings.json")}load(){if(eb.existsSync(this.filePath))try{let t=JSON.parse(eb.readFileSync(this.filePath,"utf8"));this.settings=this.deepMerge(b7e,t),this.validate(this.settings)}catch{console.error("[PD] Failed to parse pain_settings.json, using defaults.")}else console.log(`[PD:Config] Settings not found at ${this.filePath}, creating with defaults`),this.save()}save(){try{let t=OK.dirname(this.filePath);eb.existsSync(t)||eb.mkdirSync(t,{recursive:!0}),Pt(this.filePath,JSON.stringify(this.settings,null,2)),console.log(`[PD:Config] Settings saved to ${this.filePath}`)}catch(t){console.error(`[PD:Config] Failed to save settings: ${String(t)}`)}}deepMerge(t,n){let r={...t};return n&&typeof n=="object"&&Object.keys(n).forEach(i=>{n[i]!==void 0&&(n[i]&&typeof n[i]=="object"&&!Array.isArray(n[i])?i in t?r[i]=this.deepMerge(t[i],n[i]):Object.assign(r,{[i]:n[i]}):Object.assign(r,{[i]:n[i]}))}),r}validate(t){t.intervals.worker_poll_ms<1e3&&(t.intervals.worker_poll_ms=900*1e3)}get(t){let n=t.split("."),r=this.settings;for(let i of n){if(r===void 0||r[i]===void 0)return;r=r[i]}return r}getAll(){return this.settings}};var UD=null,I7e=null,LK={get(e){return(!UD||I7e!==e)&&(UD=new PK(e),UD.load(),I7e=e),UD},reset(){UD=null}};import*as ms from"fs";import*as WD from"path";var w7e=7,lse=class{logsDir;statsFile;logger;statsCache=new Map;eventBuffer=[];maxBufferSize=20;flushIntervalMs=3e4;flushTimer;currentEventsFile;currentDate;constructor(t,n){let r=$p(t);this.logsDir=WD.join(r,"logs"),ms.existsSync(this.logsDir)||ms.mkdirSync(this.logsDir,{recursive:!0}),this.statsFile=WD.join(this.logsDir,"daily-stats.json"),this.logger=n,this.loadStats(),this.startFlushTimer()}getEventsFile(t){return WD.join(this.logsDir,`events_${t}.jsonl`)}getTodayStr(){return new Date().toISOString().split("T")[0]??""}ensureEventsFile(){let t=this.getTodayStr();return(this.currentDate!==t||!this.currentEventsFile)&&(this.currentDate=t,this.currentEventsFile=this.getEventsFile(t),this.cleanupOldEventFiles(t)),this.currentEventsFile}cleanupOldEventFiles(t){if(!(w7e<=0))try{let n=Date.now()-w7e*24*60*60*1e3,r=ms.readdirSync(this.logsDir);for(let i of r){if(!i.startsWith("events_")||!i.endsWith(".jsonl"))continue;let o=WD.join(this.logsDir,i);ms.statSync(o).mtimeMs<n&&ms.unlinkSync(o)}}catch(n){this.logger?.debug?.(`[PD] Event file cleanup failed (non-blocking): ${String(n)}`)}}recordToolCall(t,n){let r=n.error||n.exitCode!==void 0&&n.exitCode!==0?"failure":"success";this.record("tool_call",r,t,n)}recordPainSignal(t,n){this.record("pain_signal","detected",t,n)}recordRulePromotion(t){this.record("rule_promotion","promoted",void 0,t)}recordGovernanceAction(t,n){this.record("governance_action","approved",void 0,t),n?.flushImmediately&&this.flushEvents()}recordHookExecution(t,n){let r=t.error?"failure":"success";this.record("hook_execution",r,void 0,t),n?.flushImmediately&&this.flushEvents()}recordGateBlock(t,n){this.record("gate_block","blocked",t,n)}recordGateBypass(t,n){this.record("gate_bypass","bypassed",t,n)}recordEvolutionTask(t){this.record("evolution_task","enqueued",void 0,t)}recordEvolutionTaskCompleted(t){this.record("evolution_task","completed",void 0,t)}recordEmpathyRollback(t,n){this.record("empathy_rollback","rolled_back",t,n)}recordError(t,n,r){this.record("error","failure",t,{message:n,...r})}recordWarn(t,n,r){this.record("warn","failure",t,{message:n,...r})}recordDiagnosisTask(t){this.record("diagnosis_task","written",void 0,t)}recordHeartbeatDiagnosis(t){this.record("heartbeat_diagnosis","injected",void 0,t)}recordDiagnosticianReport(t){let n={success:"completed",missing_json:"failure",incomplete_fields:"failure"};this.record("diagnostician_report",n[t.category],void 0,t)}recordPrincipleCandidate(t){this.record("principle_candidate","created",void 0,t)}recordRuleEnforced(t){this.record("rule_enforced","matched",void 0,t)}recordRuleHostEvaluated(t){this.record("rulehost_evaluated","evaluated",void 0,t)}recordRuleHostBlocked(t){this.record("rulehost_blocked","blocked",void 0,t)}recordRuleHostRequireApproval(t){this.record("rulehost_requireApproval","requireApproval",void 0,t)}recordRuleHostAutoCorrectProposed(t){this.record("rulehost_auto_correct_proposed","auto_correct",void 0,t)}recordRuleHostAutoCorrectApplied(t){this.record("rulehost_auto_correct_applied","auto_correct",void 0,t)}recordRuntimeV2ActivationsInjected(t){this.record("runtime_v2_prompt_activations_injected","injected",t.sessionId,t)}recordRuleHostUnhealthy(t){this.record("rulehost_unhealthy","failure",void 0,t)}recordRuleHostSkipped(t){this.record("rulehost_skipped","failure",void 0,t)}redactEventData(t,n){try{if(!new Set(["tool_call","rulehost_evaluated","rulehost_blocked","rulehost_requireApproval","rulehost_auto_correct_proposed","rulehost_auto_correct_applied","rulehost_skipped","rule_enforced","hook_execution","gate_block","gate_bypass"]).has(t))return n;let i={};for(let[o,a]of Object.entries(n))if(typeof a=="string")i[o]=Sm(a);else if(Array.isArray(a))i[o]=a.map(s=>{if(typeof s=="string")return Sm(s);if(typeof s=="object"&&s!==null){let c={};for(let[l,u]of Object.entries(s))c[l]=typeof u=="string"?Sm(u):u;return c}return s});else if(typeof a=="object"&&a!==null){let s={};for(let[c,l]of Object.entries(a))typeof l=="string"?s[c]=Sm(l):s[c]=l;i[o]=s}else i[o]=a;return i}catch(r){return{redactionFailure:!0,redactionStatus:"failed","redaction.status":"failed",redactionReason:(r instanceof Error?r.message.slice(0,200):String(r).slice(0,200))||"unknown error",redactionDataDropped:!0,originalType:t,originalSessionId:n.sessionId??null}}}record(t,n,r,i){let o=new Date,a=this.formatDate(o),s=this.redactEventData(t,i),c={ts:o.toISOString(),date:a,type:t,category:n,sessionId:r,data:s};this.eventBuffer.push(c),this.updateStats(c),this.eventBuffer.length>=this.maxBufferSize&&this.flushEvents()}formatDate(t){return t.toISOString().split("T")[0]??""}loadStats(){if(ms.existsSync(this.statsFile))try{let t=JSON.parse(ms.readFileSync(this.statsFile,"utf-8"));for(let n in t)this.statsCache.set(n,t[n])}catch(t){this.logger&&this.logger.error(`[PD] Failed to load daily-stats.json: ${String(t)}`)}}updateStats(t){let n=this.statsCache.get(t.date);if(n||(n=lI(t.date),this.statsCache.set(t.date,n)),t.type==="tool_call"){n.tools.total++,t.category==="success"?n.tools.success++:n.tools.failure++;let r=t.data,i=r.gfiAfter??r.gfi;i!==void 0&&(n.gfi.samples++,n.gfi.total+=i,n.gfi.peak=Math.max(n.gfi.peak,i))}else if(t.type==="pain_signal"){let r=t.data;if(r.source==="user_empathy"){if(r.deduped)n.empathy.dedupedCount++;else{n.empathy.totalEvents++,n.empathy.totalPenaltyScore+=r.score||0,r.severity&&(n.empathy.bySeverity[r.severity]++,n.empathy.scoreBySeverity[r.severity]+=r.score||0),r.detection_mode&&n.empathy.byDetectionMode[r.detection_mode]++,r.origin&&n.empathy.byOrigin[r.origin]++;let o=r.confidence??1;o>=.8?n.empathy.confidenceDistribution.high++:o>=.5?n.empathy.confidenceDistribution.medium++:n.empathy.confidenceDistribution.low++}let i=n.empathy.totalEvents+n.empathy.dedupedCount;n.empathy.dedupeHitRate=i>0?n.empathy.dedupedCount/i:0}}else if(t.type==="hook_execution"){let r=t.data;if(n.hooks.total++,t.category==="success"?n.hooks.success++:n.hooks.failure++,r.hook){n.hooks.byType[r.hook]||(n.hooks.byType[r.hook]={total:0,success:0,failure:0});let i=n.hooks.byType[r.hook];i&&(i.total++,t.category==="success"?i.success++:i.failure++)}}else if(t.type==="empathy_rollback"){let r=t.data;n.empathy.rollbackCount++,n.empathy.rolledBackScore+=r.originalScore||0}else if(t.type==="rule_promotion")n.evolution.rulesPromoted++;else if(t.type==="evolution_task")t.category==="completed"?n.evolution.tasksCompleted++:t.category==="enqueued"&&n.evolution.tasksEnqueued++;else if(t.type==="diagnosis_task")n.evolution.diagnosisTasksWritten++;else if(t.type==="heartbeat_diagnosis")n.evolution.heartbeatsInjected++;else if(t.type==="diagnostician_report"){let r=t.data;if(Object.prototype.hasOwnProperty.call(r,"category")){let i=r.category;typeof i=="string"&&(i==="success"||i==="missing_json"||i==="incomplete_fields")&&n.evolution.diagnosticianReportsWritten++,typeof i=="string"&&i==="missing_json"&&n.evolution.reportsMissingJson++,typeof i=="string"&&i==="incomplete_fields"&&n.evolution.reportsIncompleteFields++}else Object.prototype.hasOwnProperty.call(r,"success")&&n.evolution.diagnosticianReportsWritten++}else t.type==="principle_candidate"?n.evolution.principleCandidatesCreated++:t.type==="rule_enforced"?n.evolution.rulesEnforced++:t.type==="rulehost_evaluated"?n.evolution.rulehostEvaluated++:t.type==="rulehost_blocked"?n.evolution.rulehostBlocked++:t.type==="rulehost_requireApproval"?n.evolution.rulehostRequireApproval++:t.type==="rulehost_auto_correct_proposed"?n.evolution.rulehostAutoCorrectProposed++:t.type==="rulehost_auto_correct_applied"&&n.evolution.rulehostAutoCorrectApplied++}startFlushTimer(){this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer.unref()}flush(){this.flushEvents(),this.flushStats()}getBufferedEvents(){return this.eventBuffer.map(t=>({...t,data:{...t.data}}))}getEventDedupKey(t){let n=typeof t.data?.eventId=="string"?String(t.data.eventId):null;if(n)return`${t.type}:${t.sessionId??"none"}:${n}`;let r=t.data??{};return[t.ts??"no-ts",t.type??"no-type",t.category??"no-category",t.sessionId??"no-session",typeof r.source=="string"?r.source:"no-source",typeof r.toolName=="string"?r.toolName:"no-tool",typeof r.reason=="string"?r.reason:"no-reason"].join("::")}readPersistedEvents(){let t=this.ensureEventsFile();if(!ms.existsSync(t))return[];try{return ms.readFileSync(t,"utf-8").trim().split(`
1915
+ `)[0]:String(l);o[s]=null,r.push(`${i}: ${u}`)}}finally{a.close()}return o}function Zae(e){let t=[],n={initialized:!1,painObserved:!1,principleObserved:!1,activationObserved:!1,presenceReceiptObserved:!1,effectReceiptObserved:!1,initializationFailed:!1},r=PD.resolve(e),i=PD.join(r,".pd","state.db"),o=vK.existsSync(i),a=G8e(i,{schemaTableExists:"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_version')",schemaVersionPopulated:"SELECT EXISTS(SELECT 1 FROM schema_version)",principleCandidates:"SELECT EXISTS(SELECT 1 FROM principle_candidates)",activations:"SELECT EXISTS(SELECT 1 FROM activations)",presenceReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='presence')",effectReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='effect')"},{notes:t,unavailableNote:"state_db_unreadable"});o||t.push("state_db_missing");let s=a.schemaTableExists??null,c=a.schemaVersionPopulated??null;n.initialized=s===null?null:s===!1?!1:c??null,n.initializationFailed=o?n.initialized===null?null:!n.initialized:!1,n.principleObserved=a.principleCandidates??null,n.activationObserved=a.activations??null,dr(r,trn).enabled?(n.presenceReceiptObserved=a.presenceReceipts??null,n.effectReceiptObserved=a.effectReceipts??null):(n.presenceReceiptObserved=null,n.effectReceiptObserved=null,t.push("receipt_collection_disabled"));let u=G8e(PD.join(r,".state","trajectory.db"),{painEvents:"SELECT EXISTS(SELECT 1 FROM pain_events)"},{notes:t,unavailableNote:"trajectory_db_unreadable"});n.painObserved=u.painEvents??null;let p=!1,f=PD.join(r,".state"),m=PD.join(f,"principle_training_state.json");if((()=>{try{return vK.existsSync(m)}catch{return!1}})())if(!(()=>{try{return JSON.parse(vK.readFileSync(m,"utf8")),!0}catch{return!1}})())p=null,t.push("principle_ledger_malformed");else try{let I=Bn(f)?.tree?.principles;p=I!==null&&typeof I=="object"&&Object.keys(I).length>0}catch{p=null,t.push("principle_ledger_malformed")}return n.principleObserved=nrn(n.principleObserved,p),{facts:n,notes:t}}import dl from"node:fs";import lrn from"node:os";import OD from"node:path";import{fileURLToPath as urn}from"node:url";import*as wa from"node:path";var B8e=1;var rrn=["codex","openclaw"];function irn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function orn(e){return typeof e=="string"&&rrn.includes(e)}function arn(e){if(e===void 0)return{workspaces:[]};if(!Array.isArray(e))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let t=[];for(let n of e){if(typeof n!="string"||n.length===0||!wa.isAbsolute(n))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let r=wa.resolve(n);t.includes(r)||t.push(r)}return{workspaces:t}}function ese(e){if(!irn(e))return{error:"install_manifest_malformed: expected an object"};if(e.layoutVersion!==B8e)return{error:`install_manifest_unsupported_version: ${String(e.layoutVersion)}`};if(e.mode!=="canonical"&&e.mode!=="legacy")return{error:"install_manifest_malformed: mode must be canonical or legacy"};if(!Array.isArray(e.hosts)||e.hosts.length===0||!e.hosts.every(orn))return{error:"install_manifest_malformed: hosts must contain codex and/or openclaw"};let t=[...new Set(e.hosts)],n=arn(e.workspaces);return n.error?{error:n.error}:{manifest:{layoutVersion:B8e,mode:e.mode,hosts:t,workspaces:n.workspaces}}}function tse(e){let t=wa.resolve(e),n=wa.join(t,".pd"),r=wa.join(n,"runtime"),i=wa.join(t,".openclaw");return{homeDir:t,pdDir:n,manifest:wa.join(n,"install.json"),runtimeDir:r,pluginDir:wa.join(r,"plugin"),installLayoutDir:wa.join(r,"install-layout"),coreDir:wa.join(r,"core"),hostRuntimeDir:wa.join(r,"host-runtime"),pdCliDir:wa.join(r,"pd-cli"),consoleDir:wa.join(r,"console"),binDir:wa.join(r,"bin"),codexDir:wa.join(n,"codex"),openClawDir:i,openClawExtensionDir:wa.join(i,"extensions","principles-disciple")}}function K8e(e){let t=tse(e.homeDir),n=ese(e.manifest);return n.manifest&&n.manifest.mode==="canonical"&&e.canonicalRuntimeExists?{mode:"canonical",paths:t,manifest:n.manifest}:e.legacyExtensionExists?{mode:"legacy",paths:t,...n.manifest?{manifest:n.manifest}:{},reason:n.error??"install_layout_legacy_fallback",nextAction:"Run the installer update to migrate the shared runtime to ~/.pd/runtime."}:{mode:"missing",paths:t,reason:n.error??"install_runtime_missing",nextAction:"Run npx create-principles-disciple to install or repair PD."}}import srn from"node:fs";import H8e from"node:path";function crn(e){let t=H8e.resolve(e);try{t=srn.realpathSync(t)}catch{}let n=t.split(H8e.sep).join("/");return process.platform==="win32"&&(n=n.toLowerCase()),n.length>1&&n.endsWith("/")&&(n=n.slice(0,-1)),n}function xK(e,t){return v6(e,crn(t))}function V8e(e,t){return`${e}.export-lock.${t}`}var z8e="anonymous_product_telemetry",Y8e="PD_TELEMETRY_DISABLED",drn="Preview only. Nothing was sent.",prn=5,frn=300*1e3,mrn=5*1e3,J8e=3*1e3,hrn=15,grn=e=>new Promise(t=>setTimeout(t,e));function yrn(e,t){let n=V8e(e,t),r=()=>{try{let i=dl.openSync(n,"wx");try{dl.writeSync(i,`${process.pid} ${new Date().toISOString()}`)}finally{dl.closeSync(i)}return!0}catch{return!1}};if(r())return{acquired:!0,lockPath:n};try{let i=dl.statSync(n);if(Date.now()-i.mtimeMs>frn&&(dl.rmSync(n,{force:!0}),r()))return{acquired:!0,lockPath:n}}catch{}return{acquired:!1}}function X8e(e){try{dl.rmSync(e,{force:!0})}catch{}}async function _rn(e){let t=`${e}.state-lock`,n=Date.now()+J8e,r=()=>{try{let i=dl.openSync(t,"wx");try{dl.writeSync(i,`${process.pid} ${new Date().toISOString()}`)}finally{dl.closeSync(i)}return!0}catch{return!1}};for(;;){if(r())return{acquired:!0,lockPath:t};try{let i=dl.statSync(t);if(Date.now()-i.mtimeMs>mrn&&(dl.rmSync(t,{force:!0}),r()))return{acquired:!0,lockPath:t}}catch{}if(Date.now()>=n)return{acquired:!1};await grn(hrn)}}async function vrn(e){let t=Jx(e.homeDir),n=await _rn(t);if(!n.acquired)return"skipped_contention";try{let r=$h(e.homeDir);if(!r.ok)return"skipped_unreadable";if(r.state.consent!=="granted"||r.state.telemetrySecret!==e.secret)return"skipped_identity_changed";let i=D8e(r.state,e.timestamp),o={...i,workspaceExports:{...i.workspaceExports??{},[e.scopeKey]:e.nextEntry}};return CD(e.homeDir,o).ok?"written":"skipped_unreadable"}finally{X8e(n.lockPath)}}var xrn=OD.dirname(urn(import.meta.url));function nse(e){try{return JSON.parse(dl.readFileSync(e,"utf8"))}catch{return}}function rse(e){let t=tse(e),r=ese(nse(t.manifest)).manifest,i=dl.existsSync(t.hostRuntimeDir),o=dl.existsSync(t.openClawExtensionDir),a=K8e({homeDir:e,manifest:r,canonicalRuntimeExists:i,legacyExtensionExists:o}),s="other";r&&r.hosts.length===1&&(r.hosts[0]==="codex"||r.hosts[0]==="openclaw")?[s]=r.hosts:o&&(s="openclaw");let c=nse(OD.join(t.pluginDir,"package.json"))??nse(OD.join(t.openClawExtensionDir,"package.json")),l=c!==null&&typeof c=="object"&&!Array.isArray(c)?c.version:void 0,u=typeof l=="string"?l.slice(0,32):"unknown";return{installMode:a.mode,hostKind:s,pdVersion:u}}function brn(e){return e?oi(e).effective.config.workspace?.environment??"unknown":"unknown"}function Q8e(e={}){let t=()=>OD.resolve(e.homeDir??lrn.homedir()),n=()=>e.env??process.env,r=()=>OD.resolve(e.moduleDir??xrn),i=()=>(e.now??Date.now)(),o=e.logger??{};function a(l){return W8e({env:{killSwitch:n()[Y8e],ci:n().CI,vitest:n().VITEST,e2eMode:n().PD_E2E_MODE},workspaceEnvironment:brn(l),installMode:rse(t()).installMode,moduleDir:r()})}function s(l,u){let p=null,f=null;if(u){let _=dr(u,z8e);p=_.enabled,f=_.source}let m=a(u),y=[];return p===null?y.push("feature_flag_unresolved"):p!==!0&&y.push("feature_flag_disabled"),l.consent!=="granted"&&y.push(`consent_${l.consent}`),y.push(...m.reasons),{flagEnabled:p,flagSource:f,consent:l.consent,environmentSuppressed:m.suppressed,suppressionReasons:m.reasons,canExport:y.length===0,blockers:y}}function c(l){if(!l.canExport)return l.suppressionReasons.includes("env_kill_switch")?`Unset ${Y8e} to allow telemetry export.`:l.flagEnabled===!1?`Set features.${z8e}.enabled: true in the workspace .pd/config.yaml.`:l.consent!=="granted"?"Run: pd telemetry enable --confirm":l.environmentSuppressed?`Telemetry is suppressed in this environment (${l.suppressionReasons.join(", ")}). This is expected for CI/test/dev environments.`:"Resolve the blockers listed above."}return{getStatus(l){let u=$h(t());if(!u.ok)return u;let p=s(u.state,l),f,m=u.state.telemetrySecret;if(l!==void 0&&Od(m)){let _=xK(m,l);f=u.state.workspaceExports?.[_]}return{ok:!0,view:{...p,consentVersion:u.state.consentVersion,hasSecret:Od(u.state.telemetrySecret),...f?.lastAttemptedAt!==void 0?{lastAttemptedAt:f.lastAttemptedAt}:{},...f?.lastSucceededAt!==void 0?{lastSucceededAt:f.lastSucceededAt}:{},...f?.lastFailureCode!==void 0?{lastFailureCode:f.lastFailureCode}:{},...f?.nextRetryAt!==void 0?{nextRetryAt:f.nextRetryAt}:{},endpoint:e.endpoint??Qae,...c(p)!==void 0?{nextAction:c(p)}:{}}}},preview(l){let u=$h(t()),p=u.ok?u.state:Xae(),f=s(p,l),m=i(),y=aI(m),_=!Od(p.telemetrySecret),b=p.telemetrySecret??"0".repeat(64),I=xK(b,l),E=rse(t()),{facts:R,notes:A}=Zae(l),P=L1({dailyTelemetryId:C1(b,I,y),bucketDate:y,pdVersion:E.pdVersion,hostKind:E.hostKind,milestones:{initialized:R.initialized,painObserved:R.painObserved,principleObserved:R.principleObserved,activationObserved:R.activationObserved,presenceReceiptObserved:R.presenceReceiptObserved,effectReceiptObserved:R.effectReceiptObserved},reliability:{initializationFailed:R.initializationFailed}}),O=[...A];return _&&O.push("payload shape is exact; dailyTelemetryId is provisional and will change after pd telemetry enable"),u.ok||O.push(`control state unreadable (${u.reason}) \u2014 showing defaults`),{banner:drn,snapshot:P,gates:f,notes:O,secretEphemeral:_}},enable(){let l=$h(t());if(!l.ok)return l;let u=N8e(l.state),p=CD(t(),u);return p.ok?(o.info?.(`[PD:Telemetry] Consent granted (control state: ${Jx(t())}).`),{ok:!0,consent:"granted"}):p},disable(){let l=$h(t());if(!l.ok)return l;let u=CD(t(),M8e());return u.ok?(o.info?.("[PD:Telemetry] Consent denied; local telemetry secret and export status deleted. Future export requests: 0."),{ok:!0,consent:"denied"}):u},reset(){let l=$h(t());if(!l.ok)return l;let u=$8e(l.state),p=CD(t(),u);return p.ok?(o.info?.("[PD:Telemetry] Telemetry identity reset; previous daily IDs are unlinkable going forward."),{ok:!0,consent:u.consent}):p},async maybeExportDaily(l){let u=$h(t());if(!u.ok)return o.warn?.(`[PD:Telemetry] Export skipped: ${u.reason}`),{attempted:!1,skipReason:"control_state_unreadable"};let{state:p}=u,f=s(p,l);if(!f.flagEnabled)return{attempted:!1,skipReason:"feature_flag_disabled"};if(p.consent!=="granted")return{attempted:!1,skipReason:`consent_${p.consent}`};if(f.environmentSuppressed)return o.info?.(`[PD:Telemetry] Export suppressed (${f.suppressionReasons.join(", ")}).`),{attempted:!1,skipReason:`environment_suppressed:${f.suppressionReasons.join("+")}`};if(!Od(p.telemetrySecret))return o.warn?.("[PD:Telemetry] Export skipped: telemetry secret missing/invalid. Run: pd telemetry enable --confirm"),{attempted:!1,skipReason:"secret_missing"};let m=p.telemetrySecret,y=i(),_=aI(y),b=xK(m,l),I=p.workspaceExports?.[b];if(I?.lastSucceededAt!==void 0&&aI(Date.parse(I.lastSucceededAt))===_)return{attempted:!1,skipReason:"already_succeeded_today"};if(I?.nextRetryAt!==void 0&&y<Date.parse(I.nextRetryAt))return{attempted:!1,skipReason:"retry_backoff"};let E=I?.attemptBucketDate===_?I?.dailyAttemptCount??0:0;if(E>=prn)return{attempted:!1,skipReason:"daily_attempt_cap"};let R=yrn(Jx(t()),b);if(!R.acquired||R.lockPath===void 0)return o.info?.("[PD:Telemetry] Export skipped: another export is in flight for this workspace (lock busy)."),{attempted:!1,skipReason:"export_lock_busy"};try{let A=$h(t()),P=A.ok?A.state.telemetrySecret:void 0,O=A.ok&&P===m?A.state:p;if(Od(O.telemetrySecret)){let Ie=O.workspaceExports?.[b];if(Ie?.lastSucceededAt!==void 0&&aI(Date.parse(Ie.lastSucceededAt))===_)return{attempted:!1,skipReason:"already_succeeded_today"}}let $=rse(t()),{facts:M}=Zae(l),U=L1({dailyTelemetryId:C1(m,b,_),bucketDate:_,pdVersion:$.pdVersion,hostKind:$.hostKind,milestones:{initialized:M.initialized,painObserved:M.painObserved,principleObserved:M.principleObserved,activationObserved:M.activationObserved,presenceReceiptObserved:M.presenceReceiptObserved,effectReceiptObserved:M.effectReceiptObserved},reliability:{initializationFailed:M.initializationFailed}}),K=await j8e({snapshot:U,...e.endpoint!==void 0?{endpoint:e.endpoint}:{},...e.fetchFn!==void 0?{fetchFn:e.fetchFn}:{}}),ce=O.workspaceExports?.[b],ie=ce?.lastAttemptedAt!==void 0&&y-Date.parse(ce.lastAttemptedAt)<1440*60*1e3,Se=K.ok?{lastAttemptedAt:new Date(y).toISOString(),lastSucceededAt:new Date(y).toISOString()}:{lastAttemptedAt:new Date(y).toISOString(),lastFailureCode:K.code,nextRetryAt:new Date(y+q8e(ie)).toISOString(),dailyAttemptCount:E+1,attemptBucketDate:_},Ge=await vrn({homeDir:t(),secret:m,scopeKey:b,timestamp:y,nextEntry:Se});return Ge==="skipped_contention"?o.warn?.(`[PD:Telemetry] Export ${K.ok?"succeeded":`failed (${K.code})`} but control state update was skipped after ${J8e/1e3}s of state-lock contention \u2014 this workspace may re-attempt today.`):Ge==="skipped_unreadable"?o.warn?.(`[PD:Telemetry] Export ${K.ok?"succeeded":`failed (${K.code})`} but control state could not be read/updated \u2014 ${Jx(t())}`):Ge==="skipped_identity_changed"&&o.info?.("[PD:Telemetry] Export finished after a consent/secret change; stale export bookkeeping was NOT written back."),K.ok?(o.info?.("[PD:Telemetry] Daily anonymous product telemetry snapshot exported."),{attempted:!0,ok:!0,httpStatus:K.status}):(o.warn?.(`[PD:Telemetry] Export failed (${K.code}); next retry after ${Se.nextRetryAt}. PD behavior is unaffected.`),{attempted:!0,ok:!1,failureCode:K.code})}finally{X8e(R.lockPath)}}}}function Z8e(e,t,n){setTimeout(()=>{e.maybeExportDaily(t).catch(i=>{let o=i instanceof Error?i.message:String(i);n?.warn?.(`[PD:Telemetry] Unexpected export error (PD unaffected): ${o}`)})},0).unref?.()}var bK=["before_prompt_build","before_tool_call","after_tool_call"],pk=class extends Error{reason;nextAction;constructor(t,n){super(`${t}: ${n}`),this.reason=t,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function Irn(e,t){switch(e.kind){case"before_prompt_build":return t.beforePromptBuild;case"before_tool_call":return t.beforeToolCall;case"after_tool_call":return t.afterToolCall;default:throw new pk("unsupported_host_event",`Only ${bK.join(", ")} are supported by the MVP host runtime`)}}function Xx(e){return typeof e=="string"&&e.trim().length>0}function t7e(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function wrn(e){return!Xx(e.context.workspaceDir)||!t7e(e.context.workspaceDir)||!Xx(e.context.sessionId)||!Xx(e.source)?!1:e.kind==="before_tool_call"||e.kind==="after_tool_call"?Xx(e.context.toolName):!0}function e7e(e){return e===void 0||Xx(e)}function Trn(e,t){if(t.warnings!==void 0&&(!Array.isArray(t.warnings)||!t.warnings.every(Xx))||t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null||Array.isArray(t.metadata))||!Xx(t.source)||!e7e(t.reason)||!e7e(t.additionalContext))return!1;let n=t.reason!==void 0,r=t.modifiedInput!==void 0,i=t.additionalContext!==void 0;switch(e.kind){case"before_prompt_build":return(t.decision==="allow"||t.decision==="modify")&&!n&&!r;case"before_tool_call":return t.decision==="observe"?!1:t.decision==="deny"?n&&!r&&!i:n?!1:!r||t.decision==="modify";case"after_tool_call":return t.decision==="observe"&&!n&&!r&&!i;default:return!1}}function Ern(e){return{async dispatch(t){if(!V3(t)||!wrn(t))throw new pk("invalid_host_event","Decode and validate the host event before dispatch");let n=await Irn(t,e)(t);if(!z3(n)||!Trn(t,n))throw new pk("invalid_handler_result",`Handler for ${t.kind} must return a valid HostEventResult`);if(n.source!==t.source)throw new pk("lineage_mismatch",`Handler result source must match event source ${t.source}`);return n},async health(t){return t.trim().length===0?{ok:!1,workspaceDir:t,routes:bK,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:t7e(t)?{ok:!0,workspaceDir:t,routes:bK}:{ok:!1,workspaceDir:t,routes:bK,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function n7e(e={}){let t=p8e({...e.ruleContextProvider?{ruleContextProvider:e.ruleContextProvider}:{},...e.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:e.ruleInputEnrichmentProvider}:{},...e.ruleImplementationRuntime?{implementationRuntime:e.ruleImplementationRuntime}:{}});return Ern({afterToolCall:e.afterToolCall??g8e({...e.painEnrichmentProvider?{painEnrichmentProvider:e.painEnrichmentProvider}:{},...e.painDatabaseFactory?{painDatabaseFactory:e.painDatabaseFactory}:{},...e.hostKind?{hostKind:e.hostKind}:{}}),beforeToolCall:e.beforeToolCall??t,async beforePromptBuild(n){let r=await s8e({workspaceDir:n.context.workspaceDir,excludePrincipleIds:e.promptExcludePrincipleIds?.(n)});return e.beforePromptBuild?e.beforePromptBuild(n,r):{decision:r.additionalContext.length>0?"modify":"allow",source:n.source,...r.additionalContext.length>0?{additionalContext:r.additionalContext}:{}}}})}function Fh(e){return{source:e.source}}function Qx(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,baseUrl:null}}function Srn(e){return Qs.some(t=>t===e)}function LD(e,t,n,r){let i=oi(e);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...Fh(i),...Qx(),reason:`Config validation failed: ${i.errors.map(f=>f.reason).join("; ")}`,nextAction:i.errors[0]?.nextAction??"Fix .pd/config.yaml and retry",configErrors:i.errors};let o=i.effective.config;if(!o.features[t]?.enabled)return{enabled:!1,readiness:"disabled",...Fh(i),...Qx(),reason:`${t} is disabled in .pd/config.yaml`,nextAction:`Set features.${t}.enabled=true in .pd/config.yaml to enable`};if(!Srn(n))return{enabled:!1,readiness:"needs_setup",...Fh(i),...Qx(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${Qs.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...Fh(i),...Qx(),reason:`${t} feature flag is enabled but internalAgents.agents.${n}.enabled is false`,nextAction:`Set internalAgents.agents.${n}.enabled=true in .pd/config.yaml, or disable features.${t}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,l=o.runtimeProfiles[c];if(!l)return{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,reason:`Runtime profile '${c}' not found in .pd/config.yaml`,nextAction:`Add runtime profile '${c}' to .pd/config.yaml runtimeProfiles`};if(l.type!=="pi-ai")return{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,runtimeProfileType:l.type,provider:l.provider??null,model:l.model??null,reason:`OpenClaw profile '${c}' is not supported for observer runtime. Observers require a pi-ai profile with an API key.`,nextAction:`Configure a pi-ai runtime profile for ${n} in .pd/config.yaml (e.g., add a pi-ai profile with provider, model, and apiKeyEnv)`};let u=l.apiKeyEnv??null;return u?Object.hasOwn(process.env,u)&&!!process.env[u]?{enabled:!0,readiness:"not_ready",...Fh(i),runtimeProfileId:c,runtimeProfileType:l.type,apiKeyEnv:u,apiKeyPresent:!0,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`pi-ai profile configured with apiKeyEnv='${u}' (key present); runtime availability unknown`,nextAction:"Run pd runtime probe to verify end-to-end connectivity"}:{enabled:!0,readiness:"needs_setup",...Fh(i),runtimeProfileId:c,runtimeProfileType:l.type,apiKeyEnv:u,apiKeyPresent:!1,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`Environment variable '${u}' is not set or empty`,nextAction:`Set the environment variable '${u}' with a valid API key`}:{enabled:!0,readiness:"needs_setup",...Fh(i),...Qx(),runtimeProfileId:c,runtimeProfileType:l.type,provider:l.provider??null,model:l.model??null,timeoutMs:l.timeoutMs??null,baseUrl:l.baseUrl??null,reason:`pi-ai profile '${c}' missing apiKeyEnv`,nextAction:`Add apiKeyEnv to runtime profile '${c}' in .pd/config.yaml`}}function r7e(e,t){let n=Q8e({...t!==void 0?{logger:t}:{}});Z8e(n,e,t)}import{existsSync as p7e,readFileSync as Orn,writeFileSync as Lrn,renameSync as Drn}from"fs";import{homedir as Nrn}from"os";import*as f7e from"path";import*as lo from"fs";import*as o7e from"path";var ise=class extends Error{filePath;lockPath;constructor(t,n,r){super(t),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},a7e={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function s7e(e){try{return process.kill(e,0),!0}catch{return!1}}function i7e(e,t){try{let n=o7e.dirname(e);lo.existsSync(n)||lo.mkdirSync(n,{recursive:!0});let r=lo.constants.O_WRONLY|lo.constants.O_CREAT|lo.constants.O_EXCL,i=lo.openSync(e,r);return lo.writeSync(i,String(t)),lo.fsyncSync(i),lo.closeSync(i),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function DD(e){try{let t=lo.readFileSync(e,"utf8"),n=parseInt(t.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function krn(e,t){try{DD(e)===t&&lo.unlinkSync(e)}catch{}}function Arn(e,t){try{let n=lo.statSync(e),r=DD(e),i=Date.now()-n.mtimeMs>t,o=r===null||!s7e(r);if(i||o)try{return lo.unlinkSync(e),!0}catch{return!1}return!1}catch{return!1}}function c7e(e,t,n){let r=Math.min(t*Math.pow(2,e),n),i=r*.2*Math.random();return Math.floor(r+i)}function Rrn(e){return new Promise(t=>setTimeout(t,e))}function Crn(e){let t=Date.now()+e;for(;Date.now()<t;);}function l7e(e,t){let n=DD(t),r=n!==null?s7e(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new ise(`Failed to acquire lock for ${e}. Lock holder: ${r}.`,e,t)}function u7e(e,t,n){let r=e+t.lockSuffix;return i7e(r,n)&&DD(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(Arn(r,t.lockStaleMs),i7e(r,n)&&DD(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function Prn(e,t={}){let n={...a7e,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=u7e(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=c7e(i,n.baseRetryDelayMs,n.maxRetryDelayMs);Crn(a)}}throw l7e(e,e+n.lockSuffix)}async function ose(e,t={}){let n={...a7e,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=u7e(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=c7e(i,n.baseRetryDelayMs,n.maxRetryDelayMs);await Rrn(a)}}throw l7e(e,e+n.lockSuffix)}function IK(e){krn(e.lockPath,e.pid)}function Va(e,t,n={}){let r=Prn(e,n);try{return t()}finally{IK(r)}}async function wK(e,t,n={}){let r=await ose(e,n);try{return await t()}finally{IK(r)}}function TK(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.plugins;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n.entries;if(!(!r||typeof r!="object"||Array.isArray(r)))return r[t]}var Mrn="allowConversationAccess",ase="openclaw config set plugins.entries.principles-disciple.hooks.allowConversationAccess true --strict-json";function MD(e){if(e==null||typeof e!="object"||Array.isArray(e))return{authorized:!1,reason:"pluginConfig is missing or invalid \u2014 conversation hooks cannot be registered",nextAction:ase};let t=e;return typeof t.hooks!="object"||t.hooks===null||Array.isArray(t.hooks)?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ase}:t.hooks[Mrn]!==!0?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ase}:{authorized:!0}}var d7e="principles-disciple";function $rn(){return f7e.join(Nrn(),".openclaw","openclaw.json")}function ND(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Frn(e){if(!p7e(e))return null;try{let t=Orn(e,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(t);return ND(n)?n:null}catch{return null}}function Urn(e,t){let n=e+".tmp."+Date.now();Lrn(n,JSON.stringify(t,null,2),"utf8"),Drn(n,e)}function EK(){let e=$rn();return p7e(e)?Va(e,()=>{let t=Frn(e);if(!t)return!1;ND(t.plugins)||(t.plugins={});let n=t.plugins;ND(n.entries)||(n.entries={});let r=n.entries,i=r[d7e],o=ND(i)?i:{enabled:!0};ND(o.hooks)||(o.hooks={});let a=o.hooks;return a.allowConversationAccess===!0?!1:(a.allowConversationAccess=!0,r[d7e]=o,Urn(e,t),!0)}):!1}function sse(e){return e.toLowerCase().startsWith("zh")?"zh":"en"}var Wrn={"pd-init":{zh:"\u521D\u59CB\u5316\u5DE5\u4F5C\u533A\uFF08\u751F\u6210 PRINCIPLES.md\u3001THINKING_OS.md \u7B49\uFF09",en:"Initialize workspace (generate PRINCIPLES.md, THINKING_OS.md, etc.)"},"pd-bootstrap":{zh:"\u626B\u63CF\u73AF\u5883\u5DE5\u5177\u5E76\u5EFA\u8BAE\u5347\u7EA7",en:"Scan environment tools and suggest upgrades"},"pd-research":{zh:"\u7814\u7A76\u5DE5\u5177\u5347\u7EA7\u65B9\u6848",en:"Research tool upgrade solutions"},"pd-help":{zh:"\u663E\u793A\u6240\u6709\u547D\u4EE4\u548C\u4F7F\u7528\u6307\u5357",en:"Show all commands and usage guide"},"pd-status":{zh:"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001\uFF08GFI\u3001Pain \u8BCD\u5178\uFF09",en:"View system status (GFI, Pain dictionary)"},"pd-context":{zh:"\u63A7\u5236\u4E0A\u4E0B\u6587\u6CE8\u5165 [status|thinking|reflection|focus|preset] - \u8F93\u5165 /pd-context help \u67E5\u770B\u8BE6\u60C5",en:"Control context injection [status|thinking|reflection|focus|preset] - Type /pd-context help for details"},"pd-focus":{zh:"\u7BA1\u7406 CURRENT_FOCUS.md [status|history|compress|rollback] - \u67E5\u770B/\u538B\u7F29/\u56DE\u6EDA\u7126\u70B9\u6587\u4EF6",en:"Manage CURRENT_FOCUS.md [status|history|compress|rollback] - View/compress/rollback focus file"},"pd-evolution-status":{zh:"\u67E5\u770B evolution \u95ED\u73AF\u72B6\u6001\uFF08candidate/probation/active\uFF09",en:"Show evolution loop status (candidate/probation/active)"},"pd-principle-rollback":{zh:"\u56DE\u6EDA\u539F\u5219\u5E76\u52A0\u5165\u9ED1\u540D\u5355 <principle-id> [reason]",en:"Rollback principle and blacklist pattern <principle-id> [reason]"},"pd-rollback":{zh:"\u56DE\u6EDA\u60C5\u7EEA\u4E8B\u4EF6\u60E9\u7F5A <event-id>|last",en:"Rollback empathy event penalty <event-id>|last"},"pd-export":{zh:"\u5BFC\u51FA\u6570\u636E [analytics|corrections --redacted]",en:"Export data [analytics|corrections --redacted]"},"pd-samples":{zh:"\u67E5\u770B\u6216\u5BA1\u6838\u7EA0\u9519\u6837\u672C [review approve|reject <sample-id> [note]]",en:"List or review correction samples [review approve|reject <sample-id> [note]]"},"pd-pain":{zh:"\u4ECE OpenClaw \u4F1A\u8BDD\u62A5\u544A pain\uFF08context-bound provenance\uFF09",en:"Report pain from OpenClaw session (context-bound provenance)"},"pd-workflow-debug":{zh:"\u8C03\u8BD5 workflow \u72B6\u6001\u4E0E\u4E8B\u4EF6 [workflowId]",en:"Debug workflow state and events [workflowId]"},"pd-promote-impl":{zh:"\u63D0\u5347\u5019\u9009\u5B9E\u73B0\u5230 active [list|show <id>|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Promote candidate implementation to active [list|show <id>|<id>] (semi-deprecated)"},"pd-disable-impl":{zh:'\u7981\u7528 active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Disable active implementation [list|<id> --reason "..."] (semi-deprecated)'},"pd-archive-impl":{zh:"\u6C38\u4E45\u5F52\u6863\u5B9E\u73B0 [list|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Archive implementation permanently [list|<id>] (semi-deprecated)"},"pd-rollback-impl":{zh:'\u56DE\u6EDA\u5230\u4E0A\u4E00\u4E2A active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Rollback to previous active implementation [list|<id> --reason "..."] (semi-deprecated)'}};function Ta(e,t){let n=sse(t),r=Wrn[e];return r&&(r[n]||r.en)||e}import*as Zx from"path";var Rr=(...e)=>Zx.posix.join(...e);function jrn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function qrn(e,t){return jrn(e)?Zx.win32.join(e,t):e.startsWith("/")?Zx.posix.join(e,t):Zx.join(e,t)}var zn={IDENTITY:".principles",MODELS:Rr(".principles","models"),STATE:".state",MEMORY:"memory",OKR:Rr("memory","okr"),LOGS:Rr("memory","logs"),SESSIONS:Rr(".state","sessions"),PAIN_SAMPLES:Rr("memory","pain"),LOCKS:Rr("memory",".locks"),IMPL_CODE_DIR:Rr(".state","principles","implementations")},SK={PROFILE:Rr(zn.IDENTITY,"PROFILE.json"),PRINCIPLES:Rr(zn.IDENTITY,"PRINCIPLES.md"),THINKING_OS:Rr(zn.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:Rr(zn.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:zn.MODELS,STATE_DIR:zn.STATE,EVOLUTION_QUEUE:Rr(zn.STATE,"evolution_queue.json"),EVOLUTION_DIRECTIVE:Rr(zn.STATE,"evolution_directive.json"),WORKBOARD:Rr(zn.STATE,"WORKBOARD.json"),AGENT_SCORECARD:Rr(zn.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:Rr(zn.STATE,".pain_flag"),SYSTEM_CAPABILITIES:Rr(zn.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:Rr(zn.STATE,"pain_settings.json"),PAIN_CANDIDATES:Rr(zn.STATE,"pain_candidates.json"),TRAJECTORY_DB:Rr(zn.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:Rr(zn.STATE,"blobs"),EXPORTS_DIR:Rr(zn.STATE,"exports"),SESSION_DIR:zn.SESSIONS,DICTIONARY:Rr(zn.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:Rr(zn.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:Rr(zn.STATE,"workflows.yaml"),IMPL_CODE_DIR:zn.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:Rr(zn.LOGS,"SYSTEM.log"),REFLECTION_LOG:Rr(zn.MEMORY,"reflection-log.md"),USER_CONTEXT:Rr(zn.MEMORY,"USER_CONTEXT.md"),OKR_DIR:zn.OKR,CURRENT_FOCUS:Rr(zn.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:Rr(zn.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:Rr(zn.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:Rr(zn.LOCKS,"evolution")};function Pi(e,t){return qrn(e,SK[t])}import*as Ic from"path";import*as CK from"os";import*as h_ from"fs";var Grn={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},$D=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="PdError",this.category=Grn[r]??"execution_failed"}code;category},kK=class extends $D{constructor(t,n,r){super(`[PD:Lock] ${n}: queue lock unavailable for ${t}`,"LOCK_UNAVAILABLE",r),this.name="LockUnavailableError"}},AK=class extends $D{constructor(t,n){super(`[PD:Path] Unknown path key: ${t}`,"PATH_RESOLUTION_ERROR",n),this.name="PathResolutionError"}};var FD=class extends $D{constructor(t,n){super(`[PD:Sample] Correction sample not found: ${t}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};import*as au from"path";import*as fk from"fs";var m7e=3,Brn=50;function Pt(e,t){let n=e+".tmp";fk.writeFileSync(n,t,"utf8");let r;for(let i=0;i<m7e;i++)try{fk.renameSync(n,e);return}catch(o){r=o;let a=o.code;if(a==="EPERM"||a==="EBUSY"||a==="EACCES"){if(i<m7e-1){let s=Brn*Math.pow(2,i),c=Date.now()+s,l=!1;for(;Date.now()<c;)if(!l&&Date.now()>=c-10){try{Ke("fs").accessSync?.(n)}catch{}l=!0}}continue}break}try{fk.unlinkSync(n)}catch{}throw r}function g7e(e,t){if(!e)return"";let n=t.includes("\\")||t.length>=2&&t[1]===":",r=e.includes("\\")||e.length>=2&&e[1]===":",i=e;n!==r&&r&&(i=`/mnt/${e.charAt(0).toLowerCase()}${e.slice(2).replace(/\\/g,"/")}`);let o=i.startsWith("/")&&!r,a=!n,s;if(n){let c=au.resolve(t);if(o)s=i;else{let l=au.isAbsolute(i)?i:au.join(c,i);s=au.relative(c,l)}}else if(a&&o){let c=t.replace(/\\/g,"/");s=au.posix.relative(c,i)}else{let c=t.replace(/\\/g,"/"),l=au.isAbsolute(i)?i:au.posix.join(c,i.replace(/\\/g,"/"));s=au.posix.relative(c,l)}return s=s.replace(/\\/g,"/"),s.startsWith("../")?i:s}function h7e(e){let t=e.replace(/\\/g,"/");return t.endsWith("/")&&(t=t.slice(0,-1)),t}function RK(e,t){if(!e||!t||t.length===0)return!1;let n=h7e(e);for(let r of t){let i=h7e(r);if(n.startsWith(i)&&(n===i||n.charAt(i.length)==="/"))return!0}return!1}function Oi(e){return e==null?"":Array.isArray(e)?e.join(" "):e}var Krn=".openclaw/workspace";var cse="principles-disciple.json",Hrn=[Ic.join(process.cwd(),cse),Ic.join(CK.homedir(),".openclaw",cse),Ic.join(CK.homedir(),".principles",cse)];function Vrn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function zrn(e){return e.startsWith("/")}function mk(e){return Vrn(e)?Ic.win32:zrn(e)?Ic.posix:Ic}function Yrn(){for(let e of Hrn)if(h_.existsSync(e))return e;return null}function y7e(){let e=Yrn();if(!e)return null;try{let t=h_.readFileSync(e,"utf8"),n=JSON.parse(t);return console.log(`[PD:PathResolver] Loaded config from: ${e}`),n}catch(t){return console.warn(`[PD:PathResolver] Failed to load config from ${e}: ${String(t)}`),null}}var od=class e{static extensionRoot=null;workspaceDir=null;stateDir=null;logger;normalizeWorkspace;initialized=!1;static setExtensionRoot(t){if(!t||!t.trim())return;let n=t.trim(),r=mk(n);e.extensionRoot=r.normalize(n)}static getExtensionRoot(){return e.extensionRoot}constructor(t={}){if(this.logger=t.logger,this.normalizeWorkspace=t.normalizeWorkspace??!0,t.workspaceDir){let n=t.workspaceDir,r=this.normalizeWorkspace?this.normalizePath(n):n;n!==r&&this.log("info",`Workspace path normalized: ${n} -> ${r}`),this.workspaceDir=r,this.initialized=!0}}log(t,n){let i=`[PD:PathResolver] ${n}`;switch(process.env.DEBUG==="true"&&this.logger?.debug?.(i),t){case"debug":this.logger?.debug?.(i);break;case"info":this.logger?.info?.(i);break;case"warn":this.logger?.warn?.(i);break;case"error":this.logger?.error?.(i);break}}detectWorkspaceDir(){let t=process.env.PD_WORKSPACE_DIR;if(t&&t.trim())return this.log("info",`Using workspace from PD_WORKSPACE_DIR: ${t}`),t.trim();let n=process.env.OPENCLAW_WORKSPACE;if(n&&n.trim())return this.log("info",`Using workspace from OPENCLAW_WORKSPACE: ${n}`),n.trim();let r=y7e();if(r?.workspace)return this.log("info",`Using workspace from config file: ${r.workspace}`),r.workspace;let i=CK.homedir(),o=Ic.join(i,Krn);return this.log("info",`Using default workspace: ${o}`),o}normalizePath(t){let n=mk(t),r=n===Ic?Ic.resolve(t):n.normalize(t);if(this.normalizeWorkspace){let i=["/memory","/docs","\\memory","\\docs"];for(let o of i)if(r.endsWith(o)){let a=n.dirname(r);this.log("warn",`Detected subdirectory suffix '${o}' in path. Normalized to parent: ${a}`),r=a;break}}return r}normalizeWorkspacePath(t){return this.normalizePath(t)}getWorkspaceDir(){if(this.initialized&&this.workspaceDir)return this.workspaceDir;let t=this.detectWorkspaceDir();if(this.normalizeWorkspace){let n=t;t=this.normalizePath(t),n!==t&&this.log("info",`Workspace path normalized: ${n} -> ${t}`)}return this.workspaceDir=t,this.initialized=!0,this.log("debug",`Final workspace directory: ${this.workspaceDir}`),this.workspaceDir}getStateDir(){if(this.stateDir)return this.stateDir;let t=process.env.PD_STATE_DIR;if(t&&t.trim())return this.stateDir=t.trim(),this.log("info",`Using state directory from PD_STATE_DIR: ${this.stateDir}`),this.stateDir;if(this.initialized&&this.workspaceDir){let o=mk(this.workspaceDir);return this.stateDir=o.join(this.workspaceDir,".state"),this.log("debug",`Using workspace-based state directory: ${this.stateDir}`),this.stateDir}let n=y7e();if(n?.state)return this.stateDir=n.state,this.log("info",`Using state directory from config file: ${this.stateDir}`),this.stateDir;let r=this.getWorkspaceDir(),i=mk(r);return this.stateDir=i.join(r,".state"),this.log("debug",`Computed state directory: ${this.stateDir}`),this.stateDir}resolve(t){let n=this.getWorkspaceDir(),r=this.getStateDir(),i=mk(n),o=e.extensionRoot||Ic.resolve(process.cwd(),"packages","openclaw-plugin"),a=mk(o),s=i.join(n,"memory"),c=a.join(o,"src"),l=a.join(o,"dist"),u=h_.existsSync(c)?a.join(c,"service","evolution-worker.ts"):a.join(l,"service","evolution-worker.js"),f={PROFILE:i.join(n,".principles","PROFILE.json"),PRINCIPLES:i.join(n,".principles","PRINCIPLES.md"),THINKING_OS:i.join(n,".principles","THINKING_OS.md"),DECISION_POLICY:i.join(n,".principles","DECISION_POLICY.json"),MODELS_DIR:i.join(n,".principles","models"),AGENT_SCORECARD:i.join(r,"AGENT_SCORECARD.json"),PAIN_FLAG:i.join(r,".pain_flag"),EVOLUTION_QUEUE:i.join(r,"evolution_queue.json"),EVOLUTION_DIRECTIVE:i.join(r,"evolution_directive.json"),WORKBOARD:i.join(r,"WORKBOARD.json"),SYSTEM_CAPABILITIES:i.join(r,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:i.join(r,"pain_settings.json"),PAIN_CANDIDATES:i.join(r,"pain_candidates.json"),DICTIONARY:i.join(r,"pain_dictionary.json"),STATE_DIR:r,EXTENSION_ROOT:o,EXTENSION_SRC:c,EXTENSION_DIST:l,EVOLUTION_WORKER:u,LOGS:i.join(s,"logs"),SYSTEM_LOG:i.join(s,"logs","SYSTEM.log"),REFLECTION_LOG:i.join(s,"reflection-log.md"),USER_CONTEXT:i.join(s,"USER_CONTEXT.md"),OKR_DIR:i.join(s,"okr"),CURRENT_FOCUS:i.join(s,"okr","CURRENT_FOCUS.md"),WEEK_STATE:i.join(s,"okr","WEEK_STATE.json"),EVOLUTION_STREAM:i.join(s,"evolution.jsonl"),EVOLUTION_LOCK:i.join(s,".locks","evolution"),PRINCIPLE_BLACKLIST:i.join(r,"principle_blacklist.json"),MEMORY:s}[t];if(!f)throw this.log("warn",`Unknown path key: ${t}`),new AK(t);return this.log("debug",`Resolved path for '${t}': ${f}`),f}ensureStateDir(){let t=this.getStateDir();h_.existsSync(t)||(this.log("info",`Creating state directory: ${t}`),h_.mkdirSync(t,{recursive:!0}))}static createFromHookContext(t){let n=new e;if(t?.workspaceDir){let r=String(t.workspaceDir);n.normalizeWorkspace&&(r=n.normalizePath(r)),n.workspaceDir=r,n.initialized=!0,n.log("info",`Created from hook context with workspace: ${r}`)}return t?.stateDir&&(n.stateDir=String(t.stateDir)),n}};function _7e(e,t){if(!e)return;let n=e.runtime.agent;if(n?.resolveAgentWorkspaceDir)try{return n.resolveAgentWorkspaceDir(e.config,t??"main")}catch{}let r=e.config?.workspaceDir;if(r&&r.trim())return r.trim();try{return new od().getWorkspaceDir()}catch{return}}import*as v7e from"os";import*as x7e from"path";function Ea(e){if(!e)return"workspaceDir is undefined/null";if(/^[A-Za-z]:\\?$/.test(e))return`workspaceDir is a drive root: "${e}"`;let t=x7e.resolve(e),n=v7e.homedir();if(t===n)return`workspaceDir equals home directory (${n}), likely missing context field`;if(t==="/"||t==="")return`workspaceDir is root or empty: "${t}"`;if(/^[A-Za-z]:\\?$/.test(t))return`workspaceDir is a drive root: "${t}"`;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[{pattern:new RegExp(`^${r}[\\\\/]?$`),desc:"is home directory"}];for(let{pattern:o,desc:a}of i)if(o.test(t))return`workspaceDir ${a}: "${t}"`;return null}import*as eb from"fs";import*as OK from"path";var b7e={language:"zh",diagnostician:{context:{time_window_minutes:5,max_message_length:500,max_summary_length:3e3}},thresholds:{pain_trigger:40,cognitive_paralysis_input:4e3,stuck_loops_trigger:4,semantic_min_score:.7,promotion_count_threshold:3,promotion_similarity_threshold:.8},scores:{paralysis:45,default_confusion:30,default_loop:40,tool_failure_friction:15,exit_code_penalty:50,spiral_penalty:30,missing_test_command_penalty:20,subagent_error_penalty:60,subagent_timeout_penalty:50},severity_thresholds:{high:70,medium:40,low:20},intervals:{worker_poll_ms:900*1e3,initial_delay_ms:5e3,task_timeout_ms:3600*1e3},empathy_engine:{enabled:!0,dedupe_window_ms:6e4,penalties:{mild:10,moderate:25,severe:40},rate_limit:{max_per_turn:40,max_per_hour:120},model_calibration:{}},gfi_gate:{enabled:!0,thresholds:{low_risk_block:70,high_risk_block:40,large_change_block:50},large_change_lines:50,ep_tier_multipliers:{1:.5,2:.75,3:1,4:1.5,5:2},bash_safe_patterns:["^(ls|dir|pwd|which|where|echo|env|cat|type|head|tail|less|more)\\b","^git\\s+(status|log|diff|branch|show|remote)\\b","^npm\\s+(run|test|build|start)\\b","^make\\s*$","^make\\s+(-j\\d+|--jobs\\s*\\d+)$","^(gradle|mvn)\\s+(clean|build|test|compile)\\b"],bash_dangerous_patterns:["rm\\s+(-[a-z]*r[a-z]*f|-rf)","del\\s+/s","rmdir\\s+/s","git\\s+(push\\s+.*--force|reset\\s+--hard|clean\\s+-fd)","npm\\s+publish","pip\\s+upload","docker\\s+push","(curl|wget).*\\|\\s*(ba)?sh"]},compression:{line_threshold:100,size_threshold_kb:15,interval_hours:24,keep_completed_tasks:3,max_working_memory_artifacts:10}},PK=class{settings={...b7e};filePath;constructor(t){this.filePath=OK.join(t,"pain_settings.json")}load(){if(eb.existsSync(this.filePath))try{let t=JSON.parse(eb.readFileSync(this.filePath,"utf8"));this.settings=this.deepMerge(b7e,t),this.validate(this.settings)}catch{console.error("[PD] Failed to parse pain_settings.json, using defaults.")}else console.log(`[PD:Config] Settings not found at ${this.filePath}, creating with defaults`),this.save()}save(){try{let t=OK.dirname(this.filePath);eb.existsSync(t)||eb.mkdirSync(t,{recursive:!0}),Pt(this.filePath,JSON.stringify(this.settings,null,2)),console.log(`[PD:Config] Settings saved to ${this.filePath}`)}catch(t){console.error(`[PD:Config] Failed to save settings: ${String(t)}`)}}deepMerge(t,n){let r={...t};return n&&typeof n=="object"&&Object.keys(n).forEach(i=>{n[i]!==void 0&&(n[i]&&typeof n[i]=="object"&&!Array.isArray(n[i])?i in t?r[i]=this.deepMerge(t[i],n[i]):Object.assign(r,{[i]:n[i]}):Object.assign(r,{[i]:n[i]}))}),r}validate(t){t.intervals.worker_poll_ms<1e3&&(t.intervals.worker_poll_ms=900*1e3)}get(t){let n=t.split("."),r=this.settings;for(let i of n){if(r===void 0||r[i]===void 0)return;r=r[i]}return r}getAll(){return this.settings}};var UD=null,I7e=null,LK={get(e){return(!UD||I7e!==e)&&(UD=new PK(e),UD.load(),I7e=e),UD},reset(){UD=null}};import*as ms from"fs";import*as WD from"path";var w7e=7,lse=class{logsDir;statsFile;logger;statsCache=new Map;eventBuffer=[];maxBufferSize=20;flushIntervalMs=3e4;flushTimer;currentEventsFile;currentDate;constructor(t,n){let r=$p(t);this.logsDir=WD.join(r,"logs"),ms.existsSync(this.logsDir)||ms.mkdirSync(this.logsDir,{recursive:!0}),this.statsFile=WD.join(this.logsDir,"daily-stats.json"),this.logger=n,this.loadStats(),this.startFlushTimer()}getEventsFile(t){return WD.join(this.logsDir,`events_${t}.jsonl`)}getTodayStr(){return new Date().toISOString().split("T")[0]??""}ensureEventsFile(){let t=this.getTodayStr();return(this.currentDate!==t||!this.currentEventsFile)&&(this.currentDate=t,this.currentEventsFile=this.getEventsFile(t),this.cleanupOldEventFiles(t)),this.currentEventsFile}cleanupOldEventFiles(t){if(!(w7e<=0))try{let n=Date.now()-w7e*24*60*60*1e3,r=ms.readdirSync(this.logsDir);for(let i of r){if(!i.startsWith("events_")||!i.endsWith(".jsonl"))continue;let o=WD.join(this.logsDir,i);ms.statSync(o).mtimeMs<n&&ms.unlinkSync(o)}}catch(n){this.logger?.debug?.(`[PD] Event file cleanup failed (non-blocking): ${String(n)}`)}}recordToolCall(t,n){let r=n.error||n.exitCode!==void 0&&n.exitCode!==0?"failure":"success";this.record("tool_call",r,t,n)}recordPainSignal(t,n){this.record("pain_signal","detected",t,n)}recordRulePromotion(t){this.record("rule_promotion","promoted",void 0,t)}recordGovernanceAction(t,n){this.record("governance_action","approved",void 0,t),n?.flushImmediately&&this.flushEvents()}recordHookExecution(t,n){let r=t.error?"failure":"success";this.record("hook_execution",r,void 0,t),n?.flushImmediately&&this.flushEvents()}recordGateBlock(t,n){this.record("gate_block","blocked",t,n)}recordGateBypass(t,n){this.record("gate_bypass","bypassed",t,n)}recordEvolutionTask(t){this.record("evolution_task","enqueued",void 0,t)}recordEvolutionTaskCompleted(t){this.record("evolution_task","completed",void 0,t)}recordEmpathyRollback(t,n){this.record("empathy_rollback","rolled_back",t,n)}recordError(t,n,r){this.record("error","failure",t,{message:n,...r})}recordWarn(t,n,r){this.record("warn","failure",t,{message:n,...r})}recordDiagnosisTask(t){this.record("diagnosis_task","written",void 0,t)}recordHeartbeatDiagnosis(t){this.record("heartbeat_diagnosis","injected",void 0,t)}recordDiagnosticianReport(t){let n={success:"completed",missing_json:"failure",incomplete_fields:"failure"};this.record("diagnostician_report",n[t.category],void 0,t)}recordPrincipleCandidate(t){this.record("principle_candidate","created",void 0,t)}recordRuleEnforced(t){this.record("rule_enforced","matched",void 0,t)}recordRuleHostEvaluated(t){this.record("rulehost_evaluated","evaluated",void 0,t)}recordRuleHostBlocked(t){this.record("rulehost_blocked","blocked",void 0,t)}recordRuleHostRequireApproval(t){this.record("rulehost_requireApproval","requireApproval",void 0,t)}recordRuleHostAutoCorrectProposed(t){this.record("rulehost_auto_correct_proposed","auto_correct",void 0,t)}recordRuleHostAutoCorrectApplied(t){this.record("rulehost_auto_correct_applied","auto_correct",void 0,t)}recordRuntimeV2ActivationsInjected(t){this.record("runtime_v2_prompt_activations_injected","injected",t.sessionId,t)}recordRuleHostUnhealthy(t){this.record("rulehost_unhealthy","failure",void 0,t)}recordRuleHostSkipped(t){this.record("rulehost_skipped","failure",void 0,t)}redactEventData(t,n){try{if(!new Set(["tool_call","rulehost_evaluated","rulehost_blocked","rulehost_requireApproval","rulehost_auto_correct_proposed","rulehost_auto_correct_applied","rulehost_skipped","rule_enforced","hook_execution","gate_block","gate_bypass"]).has(t))return n;let i={};for(let[o,a]of Object.entries(n))if(typeof a=="string")i[o]=Sm(a);else if(Array.isArray(a))i[o]=a.map(s=>{if(typeof s=="string")return Sm(s);if(typeof s=="object"&&s!==null){let c={};for(let[l,u]of Object.entries(s))c[l]=typeof u=="string"?Sm(u):u;return c}return s});else if(typeof a=="object"&&a!==null){let s={};for(let[c,l]of Object.entries(a))typeof l=="string"?s[c]=Sm(l):s[c]=l;i[o]=s}else i[o]=a;return i}catch(r){return{redactionFailure:!0,redactionStatus:"failed","redaction.status":"failed",redactionReason:(r instanceof Error?r.message.slice(0,200):String(r).slice(0,200))||"unknown error",redactionDataDropped:!0,originalType:t,originalSessionId:n.sessionId??null}}}record(t,n,r,i){let o=new Date,a=this.formatDate(o),s=this.redactEventData(t,i),c={ts:o.toISOString(),date:a,type:t,category:n,sessionId:r,data:s};this.eventBuffer.push(c),this.updateStats(c),this.eventBuffer.length>=this.maxBufferSize&&this.flushEvents()}formatDate(t){return t.toISOString().split("T")[0]??""}loadStats(){if(ms.existsSync(this.statsFile))try{let t=JSON.parse(ms.readFileSync(this.statsFile,"utf-8"));for(let n in t)this.statsCache.set(n,t[n])}catch(t){this.logger&&this.logger.error(`[PD] Failed to load daily-stats.json: ${String(t)}`)}}updateStats(t){let n=this.statsCache.get(t.date);if(n||(n=lI(t.date),this.statsCache.set(t.date,n)),t.type==="tool_call"){n.tools.total++,t.category==="success"?n.tools.success++:n.tools.failure++;let r=t.data,i=r.gfiAfter??r.gfi;i!==void 0&&(n.gfi.samples++,n.gfi.total+=i,n.gfi.peak=Math.max(n.gfi.peak,i))}else if(t.type==="pain_signal"){let r=t.data;if(r.source==="user_empathy"){if(r.deduped)n.empathy.dedupedCount++;else{n.empathy.totalEvents++,n.empathy.totalPenaltyScore+=r.score||0,r.severity&&(n.empathy.bySeverity[r.severity]++,n.empathy.scoreBySeverity[r.severity]+=r.score||0),r.detection_mode&&n.empathy.byDetectionMode[r.detection_mode]++,r.origin&&n.empathy.byOrigin[r.origin]++;let o=r.confidence??1;o>=.8?n.empathy.confidenceDistribution.high++:o>=.5?n.empathy.confidenceDistribution.medium++:n.empathy.confidenceDistribution.low++}let i=n.empathy.totalEvents+n.empathy.dedupedCount;n.empathy.dedupeHitRate=i>0?n.empathy.dedupedCount/i:0}}else if(t.type==="hook_execution"){let r=t.data;if(n.hooks.total++,t.category==="success"?n.hooks.success++:n.hooks.failure++,r.hook){n.hooks.byType[r.hook]||(n.hooks.byType[r.hook]={total:0,success:0,failure:0});let i=n.hooks.byType[r.hook];i&&(i.total++,t.category==="success"?i.success++:i.failure++)}}else if(t.type==="empathy_rollback"){let r=t.data;n.empathy.rollbackCount++,n.empathy.rolledBackScore+=r.originalScore||0}else if(t.type==="rule_promotion")n.evolution.rulesPromoted++;else if(t.type==="evolution_task")t.category==="completed"?n.evolution.tasksCompleted++:t.category==="enqueued"&&n.evolution.tasksEnqueued++;else if(t.type==="diagnosis_task")n.evolution.diagnosisTasksWritten++;else if(t.type==="heartbeat_diagnosis")n.evolution.heartbeatsInjected++;else if(t.type==="diagnostician_report"){let r=t.data;if(Object.prototype.hasOwnProperty.call(r,"category")){let i=r.category;typeof i=="string"&&(i==="success"||i==="missing_json"||i==="incomplete_fields")&&n.evolution.diagnosticianReportsWritten++,typeof i=="string"&&i==="missing_json"&&n.evolution.reportsMissingJson++,typeof i=="string"&&i==="incomplete_fields"&&n.evolution.reportsIncompleteFields++}else Object.prototype.hasOwnProperty.call(r,"success")&&n.evolution.diagnosticianReportsWritten++}else t.type==="principle_candidate"?n.evolution.principleCandidatesCreated++:t.type==="rule_enforced"?n.evolution.rulesEnforced++:t.type==="rulehost_evaluated"?n.evolution.rulehostEvaluated++:t.type==="rulehost_blocked"?n.evolution.rulehostBlocked++:t.type==="rulehost_requireApproval"?n.evolution.rulehostRequireApproval++:t.type==="rulehost_auto_correct_proposed"?n.evolution.rulehostAutoCorrectProposed++:t.type==="rulehost_auto_correct_applied"&&n.evolution.rulehostAutoCorrectApplied++}startFlushTimer(){this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer.unref()}flush(){this.flushEvents(),this.flushStats()}getBufferedEvents(){return this.eventBuffer.map(t=>({...t,data:{...t.data}}))}getEventDedupKey(t){let n=typeof t.data?.eventId=="string"?String(t.data.eventId):null;if(n)return`${t.type}:${t.sessionId??"none"}:${n}`;let r=t.data??{};return[t.ts??"no-ts",t.type??"no-type",t.category??"no-category",t.sessionId??"no-session",typeof r.source=="string"?r.source:"no-source",typeof r.toolName=="string"?r.toolName:"no-tool",typeof r.reason=="string"?r.reason:"no-reason"].join("::")}readPersistedEvents(){let t=this.ensureEventsFile();if(!ms.existsSync(t))return[];try{return ms.readFileSync(t,"utf-8").trim().split(`
1914
1916
  `).filter(r=>r.trim().length>0).map(r=>{try{return JSON.parse(r)}catch(i){return this.logger?.warn?.(`[PD] Corrupted event line skipped: ${String(i).slice(0,100)}`),null}}).filter(r=>r!==null)}catch(n){return this.logger&&this.logger.error(`[PD] Failed to read events file: ${String(n)}`),[]}}getMergedEvents(){let t=new Map;for(let n of[...this.readPersistedEvents(),...this.getBufferedEvents()])t.set(this.getEventDedupKey(n),n);return[...t.values()].sort((n,r)=>n.ts.localeCompare(r.ts))}flushEvents(){if(this.eventBuffer.length===0)return;let t=this.ensureEventsFile(),n=this.eventBuffer.map(r=>JSON.stringify(r)).join(`
1915
1917
  `)+`
1916
1918
  `;try{ms.appendFileSync(t,n,"utf-8"),this.eventBuffer=[]}catch(r){this.logger&&this.logger.error(`[PD] Failed to flush events: ${String(r)}`)}}flushStats(){if(this.statsCache.size===0)return;let t={};this.statsCache.forEach((n,r)=>{t[r]=n});try{Pt(this.statsFile,JSON.stringify(t,null,2))}catch(n){this.logger&&this.logger.error(`[PD] Failed to flush daily-stats.json: ${String(n)}`)}}getDailyStats(t){let n=this.statsCache.get(t);return n||(n=lI(t),this.statsCache.set(t,n)),n}getEmpathyStats(t,n){let r=new Date,i=this.formatDate(r),o={totalEvents:0,dedupedCount:0,dedupeHitRate:0,totalPenaltyScore:0,rolledBackScore:0,rollbackCount:0,bySeverity:{mild:0,moderate:0,severe:0},scoreBySeverity:{mild:0,moderate:0,severe:0},byDetectionMode:{structured:0,legacy_tag:0},byOrigin:{assistant_self_report:0,user_manual:0,system_infer:0},confidenceDistribution:{high:0,medium:0,low:0},dailyTrend:[]};if(t==="session"&&n)this.aggregateSessionEmpathy(n,o);else if(t==="week")for(let s=0;s<7;s++){let c=new Date(r);c.setDate(c.getDate()-s);let l=this.formatDate(c),u=this.getDailyStats(l);o.totalEvents+=u.empathy.totalEvents,o.dedupedCount+=u.empathy.dedupedCount,o.totalPenaltyScore+=u.empathy.totalPenaltyScore,o.rolledBackScore+=u.empathy.rolledBackScore,o.rollbackCount+=u.empathy.rollbackCount;for(let p of["mild","moderate","severe"])o.bySeverity[p]+=u.empathy.bySeverity[p],o.scoreBySeverity[p]+=u.empathy.scoreBySeverity[p];o.byDetectionMode.structured+=u.empathy.byDetectionMode.structured,o.byDetectionMode.legacy_tag+=u.empathy.byDetectionMode.legacy_tag;for(let p of["assistant_self_report","user_manual","system_infer"])o.byOrigin[p]+=u.empathy.byOrigin[p];o.confidenceDistribution.high+=u.empathy.confidenceDistribution.high,o.confidenceDistribution.medium+=u.empathy.confidenceDistribution.medium,o.confidenceDistribution.low+=u.empathy.confidenceDistribution.low,(u.empathy.totalEvents>0||u.empathy.dedupedCount>0)&&o.dailyTrend.push({date:l,count:u.empathy.totalEvents,score:u.empathy.totalPenaltyScore})}else{let s=this.getDailyStats(i);Object.assign(o,s.empathy),(s.empathy.totalEvents>0||s.empathy.dedupedCount>0)&&(o.dailyTrend=[{date:i,count:s.empathy.totalEvents,score:s.empathy.totalPenaltyScore}])}let a=o.totalEvents+o.dedupedCount;return o.dedupeHitRate=a>0?o.dedupedCount/a:0,o}aggregateSessionEmpathy(t,n){for(let r of this.getMergedEvents())if(r.sessionId===t&&r.type==="pain_signal"){let i=r.data;if(i.source==="user_empathy")if(i.deduped)n.dedupedCount++;else{n.totalEvents++,n.totalPenaltyScore+=i.score||0,i.severity&&(n.bySeverity[i.severity]++,n.scoreBySeverity[i.severity]+=i.score||0),i.detection_mode&&n.byDetectionMode[i.detection_mode]++,i.origin&&n.byOrigin[i.origin]++;let o=i.confidence??1;o>=.8?n.confidenceDistribution.high++:o>=.5?n.confidenceDistribution.medium++:n.confidenceDistribution.low++}}else if(r.sessionId===t&&r.type==="empathy_rollback"){let i=r.data;n.rollbackCount++,n.rolledBackScore+=i.originalScore||0}}rollbackEmpathyEvent(t,n,r,i){let o=this.getMergedEvents(),a=null;for(let c of o)if(c.type==="pain_signal"){let l=c.data;if(l.eventId===t&&l.source==="user_empathy"){a={entry:c,data:l};break}}if(!a||a.data.deduped)return 0;let s=a.data.score||0;return this.recordEmpathyRollback(n,{eventId:t,originalScore:s,originalSessionId:a.entry.sessionId,reason:r,triggeredBy:i}),s}getLastEmpathyEventId(t){let n=this.getMergedEvents();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i&&i.sessionId===t&&i.type==="pain_signal"){let o=i.data;if(o.source==="user_empathy"&&!o.deduped)return o.eventId||null}}return null}findLatestPainSignal(t){let n=this.getMergedEvents();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i&&i.sessionId===t&&i.type==="pain_signal")return i.data}return null}dispose(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flush()}},hs=class{static instances=new Map;static get(t,n){let r=this.instances.get(t);return r||(r=new lse(t,n),this.instances.set(t,r)),r}static flushAll(){for(let t of this.instances.values())t.flush()}static disposeAll(){for(let t of this.instances.values())t.dispose();this.instances.clear()}};import*as S7e from"fs";import*as use from"path";import*as tb from"fs";import*as T7e from"path";var DK=class{filePath;defaultFactory;constructor(t,n){this.filePath=t,this.defaultFactory=n}load(){try{if(!tb.existsSync(this.filePath))return this.defaultFactory();let t=tb.readFileSync(this.filePath,"utf8");return t?JSON.parse(t):this.defaultFactory()}catch{return console.warn(`[JsonFileStore] File corrupt or unreadable, using defaults: ${this.filePath}`),this.defaultFactory()}}save(t){let n=T7e.dirname(this.filePath);tb.existsSync(n)||tb.mkdirSync(n,{recursive:!0}),Pt(this.filePath,JSON.stringify(t,null,2))}mutate(t){let n=this.load(),r=t(n);return this.save(n),r}};var Jrn=["[EVOLUTION_ACK]","HEARTBEAT_OK","HEARTBEAT_CHECK"];function jD(e){let t=e.trim();return t?Jrn.some(n=>t===n||t.startsWith(`${n} `)||t.includes(n)):!1}var E7e={P_CONFUSION_ZH:{type:"regex",pattern:"\u6211(\u4F3C\u4E4E|\u597D\u50CF)(\u4E0D\u786E\u5B9A|\u4E0D\u592A\u786E\u5B9A|\u4E0D\u6E05\u695A|\u56F0\u60D1)",severity:35,hits:0,status:"active"},P_CONFUSION_EN:{type:"regex",pattern:"i am (not sure|unsure|confused|uncertain|struggling to)",severity:35,hits:0,status:"active"},P_LOOP_ZH:{type:"regex",pattern:"\u4F3C\u4E4E(\u9677\u5165\u4E86?\u5FAA\u73AF|\u56DE\u5230\u4E86?\u539F\u70B9|\u539F\u5730\u6253\u8F6C)",severity:45,hits:0,status:"active"},P_LOOP_EN:{type:"exact_match",phrases:["going in circles","back to square one","looping"],severity:45,hits:0,status:"active"}},NK=class{constructor(t){this.stateDir=t;let n=use.join(t,"pain_dictionary.json");this.store=new DK(n,()=>({rules:{...E7e}}))}stateDir;data={rules:{}};store;compiledRegex=new Map;load(){let t=use.join(this.stateDir,"pain_dictionary.json"),n=S7e.existsSync(t),r=this.store.load();r.rules&&Object.keys(r.rules).length>0?this.data=r:(this.data={rules:{...E7e}},n?console.warn("[PD:Dictionary] Dictionary corrupt or empty, preserving file and using defaults"):(console.log("[PD:Dictionary] Dictionary not found, creating with default rules"),this.flush())),this.compile()}compile(){this.compiledRegex.clear();for(let[t,n]of Object.entries(this.data.rules))n.type==="regex"&&n.pattern&&this.compiledRegex.set(t,new RegExp(n.pattern,"i"))}getRule(t){return this.data.rules[t]}getAllRules(){return this.data.rules}addRule(t,n){this.data.rules[t]={...n,hits:this.data.rules[t]?.hits||0},n.type==="regex"&&n.pattern&&this.compiledRegex.set(t,new RegExp(n.pattern,"i"))}match(t){if(jD(t))return;let n;for(let[r,i]of Object.entries(this.data.rules)){if(i.status!=="active")continue;let o=!1;if(i.type==="regex"){let a=this.compiledRegex.get(r);a&&(a.lastIndex=0,a.test(t)&&(o=!0))}else if(i.type==="exact_match"&&i.phrases){let a=t.toLowerCase();i.phrases.some(s=>a.includes(s.toLowerCase()))&&(o=!0)}o&&(i.hits++,(!n||i.severity>n.severity)&&(n={ruleId:r,severity:i.severity}))}return n}flush(){this.store.save(this.data)}getStats(){let t=0;for(let n of Object.values(this.data.rules))t+=n.hits||0;return{totalRules:Object.keys(this.data.rules).length,totalHits:t}}};var qD=null,k7e=null,MK={get(e){return(!qD||k7e!==e)&&(qD=new NK(e),qD.load(),k7e=e),qD},reset(){qD=null}};import*as Sp from"fs";import*as FK from"path";var $K=class{statsFile;currentStats;logger;constructor(t,n){if(this.statsFile=FK.join(t,"hygiene-stats.json"),this.logger=n,!Sp.existsSync(t))try{Sp.mkdirSync(t,{recursive:!0})}catch(r){this.logger?.error(`[PD] Failed to create state directory ${t}: ${String(r)}`)}this.currentStats=this.loadStats()}loadStats(){let t=new Date().toISOString().split("T")[0]??"";if(Sp.existsSync(this.statsFile))try{let n=Sp.readFileSync(this.statsFile,"utf-8");if(n.trim()){let r=JSON.parse(n);if(r[t])return r[t]}}catch(n){this.logger?.error(`[PD] Failed to load/parse hygiene-stats.json: ${String(n)}`);try{let r=`${this.statsFile}.bak`;Sp.renameSync(this.statsFile,r),this.logger?.warn(`[PD] Corrupted hygiene stats backed up to ${r}`)}catch{}}return ov(t)}saveStats(){let t={},n=new Date().toISOString().split("T")[0]??"";if(this.currentStats.date!==n&&(this.currentStats=ov(n)),Sp.existsSync(this.statsFile))try{let r=Sp.readFileSync(this.statsFile,"utf-8");r.trim()&&(t=JSON.parse(r))}catch(r){this.logger?.error(`[PD] Failed to parse hygiene-stats.json for saving: ${String(r)}`)}t[this.currentStats.date]=this.currentStats;try{Pt(this.statsFile,JSON.stringify(t,null,2))}catch(r){this.logger?.error(`[PD] Failed to write hygiene-stats.json: ${String(r)}`)}}recordPersistence(t){this.currentStats.persistenceCount++,this.currentStats.lastPersistenceTime=t.ts,this.currentStats.totalCharsPersisted+=t.contentLength;let n=FK.basename(t.path);this.currentStats.persistenceByFile[n]=(this.currentStats.persistenceByFile[n]||0)+1,this.saveStats(),this.logger?.info(`[PD] Hygiene: Persisted state to ${n} (${t.contentLength} chars)`)}recordGrooming(){this.currentStats.groomingExecutedCount++,this.currentStats.lastGroomingTime=new Date().toISOString(),this.saveStats(),this.logger?.info("[PD] Hygiene: Workspace grooming executed.")}getStats(){let t=new Date().toISOString().split("T")[0]??"";return this.currentStats.date!==t&&(this.currentStats=ov(t)),this.currentStats}};import*as za from"fs";import*as ob from"path";import*as su from"fs";import*as ad from"path";var UK=new Map,dse=new Map,A7e=7;function Xrn(e,t){let n=t.toISOString().slice(0,10),r=ad.dirname(Pi(e,"SYSTEM_LOG")),i=ad.basename(SK.SYSTEM_LOG,".log");return ad.join(r,`${i}_${n}.log`)}function Qrn(){return new Date().toISOString().slice(0,10)}function Zrn(e){if(!(A7e<=0))try{let t=ad.dirname(Pi(e,"SYSTEM_LOG")),r=`${ad.basename(SK.SYSTEM_LOG,".log")}_`;if(!su.existsSync(t))return;let i=Date.now()-A7e*24*60*60*1e3,o=su.readdirSync(t);for(let a of o){if(!a.startsWith(r)||!a.endsWith(".log"))continue;let s=ad.join(t,a);su.statSync(s).mtimeMs<i&&su.unlinkSync(s)}}catch{}}var R7e=new Map,$e={log(e,t,n){if(!e)return;let r=$p(e);try{let i=ad.resolve(r),o=Qrn();dse.get(i)!==o&&(dse.set(i,o),UK.delete(i),R7e.get(i)!==o&&(R7e.set(i,o),Zrn(r)));let a=UK.get(i);if(!a){a=Xrn(r,new Date),UK.set(i,a);let l=ad.dirname(a);su.existsSync(l)||su.mkdirSync(l,{recursive:!0})}let c=`[${new Date().toISOString()}] [${t.padEnd(15)}] ${n}
@@ -1980,6 +1982,7 @@ try {
1980
1982
  text TEXT,
1981
1983
  canonical_pain_id TEXT,
1982
1984
  runtime_task_id TEXT,
1985
+ host_kind TEXT,
1983
1986
  created_at TEXT NOT NULL
1984
1987
  );
1985
1988
  CREATE TABLE IF NOT EXISTS gate_blocks (
@@ -2077,7 +2080,7 @@ try {
2077
2080
  metadata_json TEXT,
2078
2081
  created_at TEXT NOT NULL
2079
2082
  );
2080
- `);try{e.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(o){let a=o instanceof Error?o.message:String(o);if(!a.includes("duplicate column name")&&!a.includes("no column named"))throw o}for(let o of[{name:"canonical_pain_id",type:"TEXT"},{name:"runtime_task_id",type:"TEXT"}])try{e.exec(`ALTER TABLE pain_events ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}let r=[{table:"assistant_turns",name:"stop_reason",type:"TEXT"},{table:"assistant_turns",name:"thinking_blocks_count",type:"INTEGER"},{table:"tool_calls",name:"result_preview",type:"TEXT"}];for(let o of r)try{e.exec(`ALTER TABLE ${o.table} ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}e.exec(`
2083
+ `);try{e.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(o){let a=o instanceof Error?o.message:String(o);if(!a.includes("duplicate column name")&&!a.includes("no column named"))throw o}for(let o of[{name:"canonical_pain_id",type:"TEXT"},{name:"runtime_task_id",type:"TEXT"},{name:"host_kind",type:"TEXT"}])try{e.exec(`ALTER TABLE pain_events ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}let r=[{table:"assistant_turns",name:"stop_reason",type:"TEXT"},{table:"assistant_turns",name:"thinking_blocks_count",type:"INTEGER"},{table:"tool_calls",name:"result_preview",type:"TEXT"}];for(let o of r)try{e.exec(`ALTER TABLE ${o.table} ADD COLUMN ${o.name} ${o.type}`)}catch(a){let s=a instanceof Error?a.message:String(a);if(!s.includes("duplicate column name")&&!s.includes("no column named"))throw a}e.exec(`
2081
2084
  CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id
2082
2085
  ON pain_events(canonical_pain_id)
2083
2086
  WHERE canonical_pain_id IS NOT NULL
@@ -2132,13 +2135,14 @@ try {
2132
2135
  `).run(t.sessionId,t.toolName,t.outcome,t.durationMs??null,t.exitCode??null,t.errorType??null,t.errorMessage??null,t.gfiBefore??null,t.gfiAfter??null,nb(t.paramsJson),t.resultPreview??null,n);return Number(i.lastInsertRowid)});return t.outcome==="success"&&this.maybeCreateCorrectionSample(t.sessionId),r}recordPainEvent(t){this.recordSession({sessionId:t.sessionId,startedAt:t.createdAt});let n=-1;return this.withWrite(()=>{try{let r=this.db.prepare(`
2133
2136
  INSERT INTO pain_events (
2134
2137
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
2135
- canonical_pain_id, runtime_task_id
2136
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2137
- `).run(t.sessionId,t.source,t.score,t.reason??null,t.severity??null,t.origin??null,t.confidence??null,t.text??null,t.createdAt??ca(),t.canonicalPainId??null,t.runtimeTaskId??null);n=Number(r.lastInsertRowid)}catch(r){if(t.canonicalPainId&&r instanceof Error&&r.message.includes("UNIQUE constraint failed")&&r.message.includes("canonical_pain_id")){this.db.prepare(`
2138
+ canonical_pain_id, runtime_task_id, host_kind
2139
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
2140
+ `).run(t.sessionId,t.source,t.score,t.reason??null,t.severity??null,t.origin??null,t.confidence??null,t.text??null,t.createdAt??ca(),t.canonicalPainId??null,t.runtimeTaskId??null,t.hostKind??null);n=Number(r.lastInsertRowid)}catch(r){if(t.canonicalPainId&&r instanceof Error&&r.message.includes("UNIQUE constraint failed")&&r.message.includes("canonical_pain_id")){this.db.prepare(`
2138
2141
  UPDATE pain_events
2139
- SET runtime_task_id = COALESCE(?, runtime_task_id)
2142
+ SET runtime_task_id = COALESCE(?, runtime_task_id),
2143
+ host_kind = COALESCE(host_kind, ?)
2140
2144
  WHERE canonical_pain_id = ?
2141
- `).run(t.runtimeTaskId??null,t.canonicalPainId);let i=this.db.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(t.canonicalPainId);i&&typeof i=="object"&&Object.hasOwn(i,"id")&&typeof i.id=="number"?n=i.id:n=-1}else throw r}}),n}recordGateBlock(t){this.withWrite(()=>{this.db.prepare(`
2145
+ `).run(t.runtimeTaskId??null,t.hostKind??null,t.canonicalPainId);let i=this.db.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(t.canonicalPainId);i&&typeof i=="object"&&Object.hasOwn(i,"id")&&typeof i.id=="number"?n=i.id:n=-1}else throw r}}),n}recordGateBlock(t){this.withWrite(()=>{this.db.prepare(`
2142
2146
  INSERT INTO gate_blocks (session_id, tool_name, file_path, reason, created_at)
2143
2147
  VALUES (?, ?, ?, ?, ?)
2144
2148
  `).run(t.sessionId??null,t.toolName,t.filePath??null,t.reason,t.createdAt??ca())})}recordTrustChange(t){this.withWrite(()=>{this.db.prepare(`
@@ -2278,7 +2282,7 @@ try {
2278
2282
  review_status, export_mode, created_at, updated_at
2279
2283
  FROM correction_samples
2280
2284
  WHERE sample_id = ?
2281
- `).get(t);if(!a)throw new FD(`${t} (after update)`);return n==="rejected"&&this.recordCorrectionRejectedPain({session_id:a.session_id,quality_score:a.quality_score,diff_excerpt:a.diff_excerpt,principle_ids_json:a.principle_ids_json,created_at:a.created_at}),{sampleId:String(a.sample_id),sessionId:String(a.session_id),badAssistantTurnId:Number(a.bad_assistant_turn_id),userCorrectionTurnId:Number(a.user_correction_turn_id),recoveryToolSpanJson:String(a.recovery_tool_span_json),diffExcerpt:String(a.diff_excerpt??""),principleIdsJson:String(a.principle_ids_json??"[]"),qualityScore:Number(a.quality_score),reviewStatus:a.review_status,exportMode:a.export_mode,createdAt:String(a.created_at),updatedAt:String(a.updated_at)}}recordCorrectionRejectedPain(t){let n=String(t.session_id),r=Number(t.quality_score),i=String(t.diff_excerpt??""),o=String(t.principle_ids_json??"[]"),a=Math.max(0,Math.min(100,Math.round(Number(r)||0))),s=`Correction rejected (quality ${r.toFixed(2)}). Principles: ${o}${i?` \u2014 ${i.slice(0,120)}`:""}`;try{this.recordPainEvent({sessionId:n,source:"correction_rejected",score:a,reason:s,severity:a>=70?"severe":a>=40?"moderate":"mild",origin:"system_infer",text:i||void 0,createdAt:String(t.created_at)})}catch(c){console.warn(`[Trajectory] Failed to record correction_rejected pain event: ${String(c)}`)}}exportCorrections(t){let n=this.db.prepare(`
2285
+ `).get(t);if(!a)throw new FD(`${t} (after update)`);return n==="rejected"&&this.recordCorrectionRejectedPain({session_id:a.session_id,quality_score:a.quality_score,diff_excerpt:a.diff_excerpt,principle_ids_json:a.principle_ids_json,created_at:a.created_at}),{sampleId:String(a.sample_id),sessionId:String(a.session_id),badAssistantTurnId:Number(a.bad_assistant_turn_id),userCorrectionTurnId:Number(a.user_correction_turn_id),recoveryToolSpanJson:String(a.recovery_tool_span_json),diffExcerpt:String(a.diff_excerpt??""),principleIdsJson:String(a.principle_ids_json??"[]"),qualityScore:Number(a.quality_score),reviewStatus:a.review_status,exportMode:a.export_mode,createdAt:String(a.created_at),updatedAt:String(a.updated_at)}}recordCorrectionRejectedPain(t){let n=String(t.session_id),r=Number(t.quality_score),i=String(t.diff_excerpt??""),o=String(t.principle_ids_json??"[]"),a=Math.max(0,Math.min(100,Math.round(Number(r)||0))),s=`Correction rejected (quality ${r.toFixed(2)}). Principles: ${o}${i?` \u2014 ${i.slice(0,120)}`:""}`;try{this.recordPainEvent({sessionId:n,source:"correction_rejected",score:a,reason:s,severity:a>=70?"severe":a>=40?"moderate":"mild",origin:"system_infer",text:i||void 0,createdAt:String(t.created_at),hostKind:"openclaw"})}catch(c){console.warn(`[Trajectory] Failed to record correction_rejected pain event: ${String(c)}`)}}exportCorrections(t){let n=this.db.prepare(`
2282
2286
  SELECT cs.sample_id, cs.session_id, cs.recovery_tool_span_json, cs.diff_excerpt, cs.quality_score,
2283
2287
  at.raw_text AS assistant_raw_text, at.blob_ref AS assistant_blob_ref, at.sanitized_text,
2284
2288
  ut.raw_text AS user_raw_text, ut.blob_ref AS user_blob_ref, ut.correction_cue
@@ -2511,7 +2515,7 @@ ${r.join(`
2511
2515
  `).replace(/\n{3,}/g,`
2512
2516
 
2513
2517
  `).trim()}function Qf(e,t){let n=[];if(!e.trajectory||t==="unknown")return n.push({sourceRef:"owner_message:unavailable",note:`trajectory_unavailable: ${e.trajectory?"unknown_session":"no_trajectory_db"}`}),n.slice(0,wm);try{let i=[...e.trajectory.listUserTurnsForSession(t)??[]].reverse().find(o=>o.correctionDetected);if(i){let o=kk((i.rawExcerpt??"").slice(0,lv));n.push({sourceRef:`owner_message:${i.createdAt}`,note:o})}}catch(r){n.push({sourceRef:"owner_message:unavailable",note:`trajectory_user_turns_unavailable: ${String(r).slice(0,100)}`})}try{let i=(e.trajectory.listAssistantTurns(t)??[]).slice(-3);for(let o of i){if(n.length>=wm)break;let a=kk((o.sanitizedText??"").slice(0,lv)),s=o.stopReason==="length"?" [TRUNCATED: output cut off by length limit]":"";n.push({sourceRef:`agent_turn:${o.createdAt}`,note:a+s})}}catch(r){n.length<wm&&n.push({sourceRef:"agent_turn:unavailable",note:`trajectory_assistant_turns_unavailable: ${String(r).slice(0,100)}`})}try{let i=(e.trajectory.listToolCallsForSession(t)??[]).filter(o=>o.outcome==="failure").slice(-3);for(let o of i){if(n.length>=wm)break;let a=o.resultPreview?` | ${o.resultPreview.slice(0,200)}`:"",s=`Tool ${o.toolName} failed: ${o.errorType??"unknown"} (exitCode: ${o.exitCode??"N/A"})${a}`;n.push({sourceRef:`tool_call_failure:${o.createdAt}`,note:kk(s.slice(0,lv))})}}catch(r){n.length===0&&n.push({sourceRef:"tool_call_failure:unavailable",note:`trajectory_tool_calls_unavailable: ${String(r).slice(0,100)}`})}return n.length===0&&n.push({sourceRef:"trajectory:empty",note:"trajectory_available_but_empty: no user correction or assistant turns found"}),n.slice(0,wm)}var Ak=500;function MYe(e){if(e==null)return null;try{if(typeof e=="string")return e.length>Ak?`${e.slice(0,Ak-3)}...`:e;if(typeof e=="object"&&!Array.isArray(e)){let t=e;if(Array.isArray(t.content)){let r=[];for(let i of t.content)if(i&&typeof i=="object"&&!Array.isArray(i)){let o=i;o.type==="text"&&typeof o.text=="string"&&r.push(o.text)}if(r.length>0){let i=r.join(`
2514
- `);return i.length>Ak?`${i.slice(0,Ak-3)}...`:i}}let n=JSON.stringify(t,(r,i)=>{if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.keys(i);if(o.length>10){let a={};for(let s of o.slice(0,10))a[s]=i[s];return a.__truncated__=!0,a}}return i},2);if(n&&n!=="{}")return n.length>Ak?`${n.slice(0,Ak-3)}...`:n}return null}catch{return"[result_preview_extraction_failed]"}}function Fse(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,n=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,r=t?.exitCode,i=n?.exitCode,o=typeof r=="number"?r:typeof i=="number"?i:0,a=!!e.error||o!==0,s=Dh({toolName:e.toolName,error:e.error,exitCode:o}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:o,failureSource:c}}function Use(e,t,n,r){let i=e.params,o=i&&typeof i=="object"&&!Array.isArray(i)?i:{},a=o.file_path||o.path||o.file,s=typeof a=="string"?g7e(a,n):"unknown",c=RK(s,r.risk_paths),l;if(e.error)l=String(e.error);else if(typeof e.result=="string")l=e.result;else try{l=JSON.stringify(e.result)}catch{l=`[unserializable result: ${typeof e.result}]`}let u=bYe(l),p=Tk(u),f=RYe(1,!1,!1,c?20:0,n);return{params:{filePath:a,content:o.content,text:o.text,newString:o.new_string,query:o.query,input:o.input,arguments:o.arguments},relPath:s,isRisk:c,errorType:fon(e.error||l),errorHash:p,errorText:l,painScore:f,traceId:I_()}}function Wse(e,t,n,r,i,o,a,s,c={}){let l=a.get("scores.tool_failure_friction")||30,u=bk(e,l,r.errorHash,o,{source:n.failureSource});return DYe(o,t.toolName,{filePath:r.relPath,reason:r.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:r.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:r.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:n.exitCode,gfiBefore:i,gfiAfter:u.currentGfi}),c.recordTrajectory!==!1&&s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:n.exitCode,errorType:r.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:i,gfiAfter:u.currentGfi,paramsJson:$se(t.params,o),resultPreview:MYe(t.result)}),u}function jse(e,t,n,r,i,o,a,s={}){let c=Gs(e),l=c?.gfiBySource?.tool_failure||0,u=c?.gfiBySource?.dispatch_error||0,p=c||sd(e,o);return l>0&&(p=sd(e,o,{source:"tool_failure",amount:l*.5})),u>0&&(p=sd(e,o,{source:"dispatch_error",amount:u*.5})),LYe(o,t.toolName,{sessionId:e,reason:"tool_success"}),s.recordTrajectory!==!1&&a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:n.exitCode,gfiBefore:i,gfiAfter:p.currentGfi,paramsJson:$se(t.params,o),resultPreview:MYe(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:r.params.filePath,gfi:p.currentGfi,gfiBefore:i,gfiAfter:p.currentGfi}),p}function qse(e,t,n){let r=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",i=/(?:^|\/)memory\//.test(r)||r.endsWith("/MEMORY.md")||r==="MEMORY.md",o=r==="PLAN.md"||r.endsWith("/PLAN.md");(i||o)&&n.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:i?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&n.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function pon(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function JD(e,t,n,r,i){let o=z7e(e,n);for(let a of o){let s=r.evolutionReducer.getPrincipleById(a);s&&pon(s,t)&&r.evolutionReducer.recordProbationFeedback(a,i)}VD(e,n)}var NYe=["write","edit","apply_patch","write_file","edit_file","replace"];function $Ye(e,t,n,r,i,o,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...NYe,...YD]:NYe).includes(e.toolName)||!n.isFailure)return n.isFailure&&$e.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:n.failureSource,sessionId:o,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=${n.isFailure}`};let u=n.failureSource??"tool_failure",p=w_(u,o,r?.lastErrorHash),f={observedAt:new Date().toISOString(),workspaceId:a,sessionId:o,toolName:e.toolName,failureSource:n.failureSource,toolNotFound:n.failureSource==="dispatch_error",nonZeroExit:n.exitCode!==0},m=nu(f),y=(r??i)?.consecutiveErrors,_=c?Math.max(4,y??0):y,b=E_(m,t.painScore,{consecutiveErrors:_,isRisky:t.isRisk}),I=ru({triageResult:b,isOwnerManual:!1,isCooldownActive:p,isValid:!0,score:t.painScore,sessionId:o});return $e.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:I.outcome,sourceKind:I.sourceKind,reason:I.reason,nextAction:I.nextAction,triageDecision:I.triageDecision,tool:e.toolName,path:t.relPath})),I.shouldCreateDiagnosticTask?(T_(u,o,r?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:I.reason,detail:`outcome=${I.outcome}, sourceKind=${I.sourceKind}, nextAction=${I.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:I.reason,detail:`outcome=${I.outcome}, sourceKind=${I.sourceKind}, nextAction=${I.nextAction}`}}function FYe(e,t,n,r,i,o,a,s,c){if(!i.admitted)return;let l=r.failureSource??"tool_failure",u=`pain_${Date.now()}_${n.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:o,source:l,score:n.painScore,reason:`Tool ${t.toolName} failed on ${n.relPath}`,severity:n.painScore>=70?"severe":n.painScore>=40?"moderate":"mild",origin:"system_infer",text:u4(n.params.text??n.params.content,s)||void 0,canonicalPainId:u});try{CYe(s,{reason:`Tool ${t.toolName} failed on ${n.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:l,score:String(n.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(f=>({id:f.id,trigger:f.trigger,valueMetrics:f.valueMetrics})),(f,m)=>{let y=e.evolutionReducer.getPrincipleById(f);if(y){y.valueMetrics=m;try{e.principleTreeLedger.updatePrincipleValueMetrics(f,{principleId:f,painPreventedCount:m.painPreventedCount,lastPainPreventedAt:m.lastPainPreventedAt,calculatedAt:m.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(_){$e.log(s,"METRICS_UPDATE_SKIP",String(_))}}})}catch(f){$e.log(s,"PRINCIPLE_TRACK_SKIP",String(f))}e.eventLog.recordPainSignal(o,{score:n.painScore,source:l,reason:`Tool ${t.toolName} failed on ${n.relPath}`,isRisky:n.isRisk}),zD(s,e.trajectory).logPainDetected({traceId:n.traceId,source:l,reason:`Tool ${t.toolName} failed on ${n.relPath}`,score:n.painScore,toolName:t.toolName,filePath:n.relPath,sessionId:o}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:l,source:t.toolName,reason:`Tool ${t.toolName} failed on ${n.relPath}; diagnosticGate=${i.reason}`,score:n.painScore,sessionId:o,traceId:n.traceId,agentId:a,provenance:"automatic_hook",evidence:Qf(e,o)}},{recordObservability:!1})}function fon(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"}var UYe=new Set,WYe=3e4;function mon(e,t){try{$e.log(e,"PAIN_CONTINUATION_FAILED",JSON.stringify({reason:t.slice(0,200),nextAction:"inspect the admitted pain and retry diagnosis from the persisted canonical pain ID"}))}catch{}}function hon(e,t){let n=!1,r,o=new Promise(a=>{let s=c=>{n||(n=!0,r!==void 0&&clearTimeout(r),c&&mon(e,c),a())};t.then(()=>s(),c=>s(c instanceof Error?c.message:String(c))),r=setTimeout(()=>s(`pain_continuation_timeout:${WYe}ms`),WYe)}).finally(()=>{r!==void 0&&clearTimeout(r),UYe.delete(o)});UYe.add(o)}function gon(e){let t=new Eh({stateDir:e.stateDir}),n=oi(e.workspaceDir),r={listUserTurnsForSession:i=>e.trajectory.listUserTurnsForSession(i),listAssistantTurns:i=>e.trajectory.listAssistantTurns(i)};return new Ny({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:n.effective,getEnvVar:i=>process.env[i],intentDocReader:n4(e.workspaceDir,wk(e.workspaceDir)),trajectoryTurnReader:r})}async function Bs(e,t,n){try{e.evolutionReducer.emitSync(t)}catch(r){$e.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(r)}`)}if(t.type==="pain_detected"){let r=t.data;try{let i=gon(e);(r.source==="manual"||r.source==="pain"||r.source==="skill:pain")&&$e.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:r.painId,score:r.score}));let a=n?.recordObservability??!0,s=await i.recordPain({painId:r.painId,painType:r.painType,source:r.source,reason:r.reason,score:r.score,sessionId:r.sessionId,agentId:r.agentId,taskId:r.taskId,traceId:r.traceId,provenance:r.provenance,hostKind:r.hostKind,evidence:r.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?$e.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"&&$e.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(i){$e.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(i)}`);let o=i instanceof Error?i.message:String(i),a=!1;try{let s=new Or({workspaceDir:e.workspaceDir});try{let l=new fD(s).insertDeadLetter({painId:r.painId,painData:r});l.ok?a=!0:$e.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",l.error)}finally{s.close()}}catch(s){$e.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}$e.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:r.painId,painType:r.painType,source:r.source,score:r.score,deadLetterInserted:a,error:o,nextAction:`Run 'pd pain retry --pain-id ${r.painId}' to replay this pain signal`}))}}}function yon(e){return`pain_${Date.now()}_${Tk(e).slice(0,8)}`}function Gse(e,t,n){let r;try{r=EYe(t,n,"after_tool_call")}catch(_){$e.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(_).slice(0,200)}));return}let i=rt.fromHookContextExplicit({...t,workspaceDir:r}),{config:o}=i,a=t.sessionId||"unknown",s=t.sessionId?Gs(t.sessionId):void 0,c=s?.currentGfi??0,l=i.resolve("PROFILE"),u=b_({});if(Rk.existsSync(l))try{let _=Rk.readFileSync(l,"utf8");_.length>1024*1024?$e.log(r,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):u=b_(JSON.parse(_))}catch(_){$e.log(r,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(_)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){_on(e,t,i,r,a);return}let p=Fse(e),f=Use(e,p,r,u),m;p.isFailure?(m=Wse(a,e,p,f,c,r,o,i),JD(a,e.toolName,r,i,!1)):(jse(a,e,p,f,c,r,i),JD(a,e.toolName,r,i,!0),qse(e,f,i));let y=$Ye(e,f,p,m,s,a,r,o);y.stage!=="not_applicable"&&FYe(i,e,f,p,y,a,t.agentId,r,Bs)}function jYe(e,t){let n=rt.fromHookContextExplicit(t),r=t.sessionId||"unknown",i=t.sessionId?Gs(t.sessionId):void 0,o=i?.currentGfi??0,a=n.resolve("PROFILE"),s=b_({});if(Rk.existsSync(a))try{let f=Rk.readFileSync(a,"utf8");f.length<=1024*1024?s=b_(JSON.parse(f)):$e.log(t.workspaceDir,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping")}catch(f){$e.log(t.workspaceDir,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(f)}`)}let c=Fse(e),l=Use(e,c,t.workspaceDir,s),u=Object.hasOwn(e,"toolUseId")?e.toolUseId:Object.hasOwn(e,"toolCallId")?e.toolCallId:void 0,p;return c.isFailure?(p=Wse(r,e,c,l,o,t.workspaceDir,n.config,n,{recordTrajectory:!1}),JD(r,e.toolName,t.workspaceDir,n,!1)):(jse(r,e,c,l,o,t.workspaceDir,n,{recordTrajectory:!1}),JD(r,e.toolName,t.workspaceDir,n,!0),qse(e,l,n)),{...typeof u=="string"&&u.trim().length>0?{eventId:`openclaw:${u}`}:{},painScore:l.painScore,isRisky:l.isRisk,consecutiveErrors:(p??i)?.consecutiveErrors??0,relativePath:l.relPath,errorHash:l.errorHash,agentId:t.agentId,evidence:Qf(n,r)}}function XD(e,t){let n=Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"&&n.trim().length>0?n:null}function qYe(e,t,n){let r=n.metadata;if(!r||r.admitted!==!0||r.duplicate===!0)return;let i=XD(r,"painId"),o=XD(r,"failureSource"),a=XD(r,"relativePath"),s=XD(r,"triggerReason"),c=r.painScore;if(!i||!o||!a||!s||typeof c!="number"||!Number.isFinite(c)){$e.log(t.workspaceDir,"SHARED_PAIN_RESULT_INVALID",JSON.stringify({reason:"shared_pain_metadata_invalid",nextAction:"inspect host-runtime after-tool result metadata"}));return}let l=rt.fromHookContextExplicit(t),u=t.sessionId||"unknown",p=XD(r,"eventId")??I_(),f=`Tool ${e.toolName} failed on ${a}`;l.eventLog.recordPainSignal(u,{score:c,source:o,reason:f,isRisky:r.isRisky===!0}),zD(t.workspaceDir,l.trajectory).logPainDetected({traceId:p,source:o,reason:f,score:c,toolName:e.toolName,filePath:a,sessionId:u});let m=r.evidence,y=Array.isArray(m)?m.filter(_=>typeof _=="object"&&_!==null&&!Array.isArray(_)&&typeof Object.getOwnPropertyDescriptor(_,"sourceRef")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(_,"note")?.value=="string").slice(0,8):[];hon(t.workspaceDir,Bs(l,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:i,painType:"tool_failure",source:e.toolName,reason:`${f}; diagnosticGate=${s}`,score:c,sessionId:u,traceId:p,agentId:t.agentId,provenance:"automatic_hook",evidence:y}},{recordObservability:!1}))}function _on(e,t,n,r,i){let o=e.params,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=a.input||a.arguments||"Manual intervention",c=I_();bk(i,100,"manual_pain",r,{source:"manual_pain"}),$e.log(r,"MANUAL_PAIN",`User manually triggered pain: ${s}`),n.eventLog.recordPainSignal(i,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let l=yon(i);n.trajectory?.recordPainEvent?.({sessionId:i,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:l}),zD(r,n.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:i});let p=dr(r,"painEvidenceAdmission"),f=dr(r,"painEvidenceAdmissionDefault");if(p.enabled&&f.enabled){let y=uD({sessionId:i}),_=nu(y),b=E_(_,100),I=w_(_,i,"manual_pain"),E=ru({triageResult:b,isOwnerManual:!0,isCooldownActive:I,isValid:!0,score:100,sessionId:i});oi(r).effective&&$e.log(r,"TRIGGER_DECISION",JSON.stringify({outcome:E.outcome,sourceKind:E.sourceKind,reason:E.reason,nextAction:E.nextAction,isOwnerManual:!0,sessionId:i,score:100})),E.shouldCreateDiagnosticTask?(T_(_,i,"manual_pain"),Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:i,traceId:c,agentId:t.agentId,provenance:i&&i!=="unknown"?"host_context_bound":"owner_reported_no_host_trace",hostKind:"openclaw",evidence:Qf(n,i)}},{recordObservability:!1})):$e.log(r,"MANUAL_PAIN_SKIPPED",E.reason)}else{let y=Gs(i),_=Ek({source:"manual",score:100,currentGfi:y?.currentGfi??0,sessionId:i});if(!_.shouldDiagnose){$e.log(r,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${_.detail}`);let b;try{b=JSON.stringify({reason:_.reason,detail:_.detail,source:"manual",sessionId:i,gfi:0,score:100})}catch(E){$e.log(r,"PAYLOAD_SERIALIZE_FAILED",String(E)),b=JSON.stringify({reason:_.reason,detail:"(log serialization failed)"})}$e.log(r,"PAIN_GATE_REJECTED",b),oi(r).effective&&$e.log(r,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${_.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:i,score:100}));return}Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:i,traceId:c,agentId:t.agentId,provenance:i&&i!=="unknown"?"host_context_bound":"owner_reported_no_host_trace",hostKind:"openclaw",evidence:Qf(n,i)}},{recordObservability:!1})}}var von={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:_8e,strongRateLimitPerHour:v8e};function Bse(e){return e==="user"||e==="api"||e===void 0}function xon(){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 bon=3600*1e3,d4=class{wctx;storeProvider;config;llmClassifier;rateLimit=new Map;constructor(t,n={}){this.wctx=t,this.storeProvider=n.keywordStoreProvider??(n.keywordStore?()=>n.keywordStore:()=>xon()),this.config=n.config??von,this.llmClassifier=n.llmClassifier??null}detectSync(t,n,r,i){if(!Bse(r))return;let o=new Date().toISOString(),a=this.storeProvider(),s=mD(t,n,a,this.config,o),c={sessionId:n,turnIndex:i?.turnIndex??Date.now(),rawText:t,correctionDetected:s.isSignal&&s.strength==="STRONG",correctionCue:s.matchedTerms.length>0?s.matchedTerms.join(", "):null,referencesAssistantTurnId:i?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(c)}catch(l){$e.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(l)}`)}if(s.isSignal&&s.strength==="STRONG"&&s.matchedPrecision==="high"){this.routeStrong(s,n,t,this.resolveOccurrenceId(n,t,i));return}if(s.needsLlmConfirmation){let l={output:s,sessionId:n,text:t,occurrenceId:this.resolveOccurrenceId(n,t,i),traceId:I_(),storeSnapshot:a};this.detectAsyncAndRoute(l)}}async detectAsyncAndRoute(t){let n;if(this.llmClassifier&&this.config.enableLlmStage){let r=null;try{r=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(o){$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(o)}`)}let i=new Date().toISOString();r?n=hD(r,t.text,t.sessionId,this.config,i):($e.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),n=hD({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,i))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(i=>t.storeSnapshot.terms[i]?.category==="empathy")){$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let i={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(i,t.sessionId);return}$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}n.isSignal&&n.strength==="STRONG"?this.routeStrong(n,t.sessionId,t.text,t.occurrenceId):n.isSignal&&n.strength==="WEAK"&&this.routeWeak(n,t.sessionId)}resolveOccurrenceId(t,n,r){return r?.turnIndex!==void 0?String(r.turnIndex):($e.log(this.wctx.workspaceDir,"SIGNAL_OCCURRENCE_ID_LEGACY","turnIndex not provided; correction occurrence identity degraded to content hash"),"legacy:"+GYe("sha256").update(t+":"+n).digest("hex").slice(0,16))}routeStrong(t,n,r,i){if(!this.tryConsumeRateLimit(n)){$e.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"),{painId:a}=Vae({workspaceDir:this.wctx.workspaceDir,sessionId:n,occurrenceId:i,text:r});Bs(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:a,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:n,agentId:"main",traceId:I_(),provenance:"host_context_bound",hostKind:"openclaw",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(s=>{$e.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(s)}`)})}routeWeak(t,n){try{let r=GYe("sha256").update(`${t.evidence.detectedAt}:${n}`).digest("hex").slice(0,32);bk(n,20,r,this.wctx.workspaceDir,{source:"user_empathy"})}catch(r){$e.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(r)}`)}}tryConsumeRateLimit(t){let n=this.config.strongRateLimitPerHour,r=Date.now(),i=this.rateLimit.get(t);return(!i||r-i.windowStart>=bon)&&(i={count:0,windowStart:r},this.rateLimit.set(t,i)),i.count>=n?!1:(i.count+=1,!0)}};function BYe(e,t){try{let n=LD(e.workspaceDir,"signal_collector","signalCollector",t);if(!n.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${n.reason}`),null;if(n.readiness!=="not_ready"&&n.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${n.readiness}): ${n.reason}. ${n.nextAction}`),null;if(!n.provider||!n.model||!n.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let r=new Xl({provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,timeoutMs:n.timeoutMs??3e4,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return async(o,a)=>{let s=B3(o);try{let c=await r.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:n.timeoutMs??3e4,outputSchemaRef:"signal-classification-output-v1"}),l=await r.pollRun(c.runId),u=Date.now()+(n.timeoutMs??3e4);for(;l.status==="running"&&Date.now()<u;)await new Promise(m=>setTimeout(m,500)),l=await r.pollRun(c.runId);if(l.status!=="succeeded")return $e.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:l.status})),null;let p=await r.fetchOutput(c.runId),f=K3(p?.payload);return f.path==="structured"&&f.value?f.value:(f.path==="legacy_string"||f.path==="legacy_envelope")&&f.value?($e.log(e.workspaceDir,"SIGNAL_LLM_LEGACY_STRING_PAYLOAD",`adapter payload path=${f.path} (no outputSchemaRef support); parsed via legacy path`),f.value):($e.log(e.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`unusable classifier payload path=${f.path}: ${bp(p?.payload)}`),null)}catch(c){return $e.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(n){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(n)}`),null}}function KYe(e,t){return I8e({workspaceDir:e.workspaceDir,onDegradation:(n,r)=>$e.log(e.workspaceDir,n,r),...t?{logger:t}:{}})}function Hse(e,t,n){let r=t.getActivePrinciples(),i=t.getProbationPrinciples(),o=new Set;try{o=Soe(e)}catch(u){let p=`[PD:Pruning] Failed to read review log \u2014 all principles injected: ${u instanceof Error?u.message:String(u)}`;n?.info?n.info(p):console.error(p)}let a=yD(r.filter(u=>!o.has(u.id)),X3),s=yD(i.filter(u=>!o.has(u.id)),1e3);(a.wasTruncated||s.wasTruncated)&&n?.info?.(`[PD:Prompt] Principles truncated: active=${a.selected.length}/${r.length} (${a.totalChars}c), probation=${s.selected.length}/${i.length} (${s.totalChars}c)`);let c=a.selected,l=s.selected;return{active:c,probation:l,content:c.length>0||l.length>0?_Ye(c,l):"",selectedIds:new Set([...c,...l].map(u=>u.id)),wasTruncated:a.wasTruncated||s.wasTruncated}}var Ion=6e4,HYe=new Map,won=256,Kse=new Map;function Ton(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function Eon(e){if(typeof e!="object"||e===null)return;let t=Ton(e,"code");return typeof t=="string"?t:void 0}function Son(e){let t=HYe.get(e);return t||(t=new Map,HYe.set(e,t)),t}function zYe(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function kon(e,t,n){let r=e.trajectory?.listUserTurnsForSession?.(t)??[];return r.length>0?r.reduce((i,o)=>Math.max(i,o.turnIndex),0)+1:n.filter(i=>zYe(i,"user")).length+1}function Aon(e,t,n){let r=Kse.get(e);r||(r=new Set,Kse.set(e,r));let i=`${t}\0${n}`;if(r.has(i))return!1;if(r.add(i),r.size>won){let o=r.values().next().value;typeof o=="string"&&r.delete(o)}return!0}function Ron(e,t,n){return Kse.get(e)?.has(`${t}\0${n}`)??!1}function Con(e,t){let n=Son(t),r=Date.now(),i=n.get(e);try{let a=ub.statSync(e).mtimeMs;if(i&&r-i.loadedAt<Ion&&i.mtime===a)return i.content;let s=ub.readFileSync(e,"utf8");return n.set(e,{content:s,mtime:a,loadedAt:r}),s}catch(o){return n.delete(e),Eon(o)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(o)}`),""}}var VYe=new Map;function Pon(e,t){let n=VYe.get(e.workspaceDir);if(!n){let r=BYe(e,t),i=KYe(e,t);n=new d4(e,{llmClassifier:r,keywordStoreProvider:()=>i.resolve()}),VYe.set(e.workspaceDir,n)}return n}function db(e){return{...oi(e).effective.resolvedContextInjection}}function Oon(e,t){try{let n=oi(e);if(!n.ok){let i=n.errors.map(o=>`${o.path||"(root)"}: ${o.reason}`).join("; ");t?.warn?.(`[PD:Prompt] .pd/config.yaml malformed (${i}). Core axioms fall back to default language ${hg}. nextAction: ${n.errors[0]?.nextAction??"Fix .pd/config.yaml and retry"}`)}let r=KA(n.effective.config.principles?.outputLanguage);return r.degradationWarning&&t?.warn?.(`[PD:Prompt] ${r.degradationWarning}`),r}catch(n){return t?.warn?.(`[PD:Prompt] Core axiom language resolution failed (${String(n)}); falling back to default language ${hg}. nextAction: Check that .pd/config.yaml is readable YAML`),{outputLanguage:hg}}}async function Vse(e,t,n,r){let{workspaceDir:i}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!i}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!i){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let a=rt.fromHookContext(t),{runId:s,sessionKey:c,trigger:l,sessionId:u}=t,p=Bse(l),f=t.api;u&&a.trajectory?.recordSession?.({sessionId:u});let m=null;if(u&&p&&e.messages.some(it=>zYe(it,"assistant"))){let it=a.trajectory?.listAssistantTurns?.(u)??[];m=it[it.length-1]?.id??null}let y=db(a.workspaceDir),_=Y3(l,u),b=u?Gs(u):void 0,I,E="",R="";l==="user"&&u&&b&&b.currentGfi>=100&&sd(u,i),I=hYe();let A=gYe(),{message:P,isAgentToAgent:O}=mYe(e.prompt,u),$=!1;if(p&&u&&f&&!O&&($=!0),P&&u&&p&&!O&&(s&&Ron(a.workspaceDir,c??u,s)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${s}, sessionId=${u.substring(0,20)}`):(s||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${u.substring(0,20)}`),Pon(a,o).detectSync(P,u,l??"api",{referencesAssistantTurnId:m,turnIndex:kon(a,u,e.messages)}),s&&Aon(a.workspaceDir,c??u,s))),l==="heartbeat"||l==="cron"){if(u){let xe=X7e(u);if(xe>=1){let pt=J7e(u,xe);pt&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${xe}min elapsed, GFI now ${pt.currentGfi.toFixed(1)}`)}}let it=a.resolve("HEARTBEAT");if(ub.existsSync(it))try{let xe=ub.readFileSync(it,"utf8");E+=yYe(xe)}catch(xe){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(xe)}`)}}let M="";try{M=HA(Oon(i,o).outputLanguage,"foundational")}catch(it){o?.warn?.(`[PD:Prompt] Failed to load core principles from registry: ${String(it)}`)}let U="";if(y.thinkingOs){let it=a.resolve("THINKING_OS");try{let xe=Con(it,a.workspaceDir);xe&&(U=xe.trim())}catch(xe){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(xe)}`)}}let K="",ce="";if(!_&&y.projectFocus!=="off"){let it=a.resolve("CURRENT_FOCUS"),xe=od.getExtensionRoot(),{content:pt,recovered:kn,validationErrors:Mn}=iYe(it,xe||"",o);if(kn&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Mn.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Mn.join(", ")}`),pt.trim())try{let{stateDir:tn}=a,zt=rYe(it,i,tn);zt.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${zt.oldLines} \u2192 ${zt.newLines} lines. Milestones archived: ${zt.milestonesArchived}`):zt.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${zt.reason}`);let F=zt.newContent?.trim()||pt.trim();if(F){let q=vD(F);if(q&&(ce=xD(q)),y.projectFocus==="summary")K=rk(F,30);else{let B=await eYe(it,3);if(B.length>0){let le=B.map((Q,re)=>`
2518
+ `);return i.length>Ak?`${i.slice(0,Ak-3)}...`:i}}let n=JSON.stringify(t,(r,i)=>{if(typeof i=="object"&&i!==null&&!Array.isArray(i)){let o=Object.keys(i);if(o.length>10){let a={};for(let s of o.slice(0,10))a[s]=i[s];return a.__truncated__=!0,a}}return i},2);if(n&&n!=="{}")return n.length>Ak?`${n.slice(0,Ak-3)}...`:n}return null}catch{return"[result_preview_extraction_failed]"}}function Fse(e){let t=e.result&&typeof e.result=="object"&&!Array.isArray(e.result)?e.result:null,n=t&&t.details&&typeof t.details=="object"&&!Array.isArray(t.details)?t.details:null,r=t?.exitCode,i=n?.exitCode,o=typeof r=="number"?r:typeof i=="number"?i:0,a=!!e.error||o!==0,s=Dh({toolName:e.toolName,error:e.error,exitCode:o}),c=a?s.failureSource:void 0;return{isFailure:a,exitCode:o,failureSource:c}}function Use(e,t,n,r){let i=e.params,o=i&&typeof i=="object"&&!Array.isArray(i)?i:{},a=o.file_path||o.path||o.file,s=typeof a=="string"?g7e(a,n):"unknown",c=RK(s,r.risk_paths),l;if(e.error)l=String(e.error);else if(typeof e.result=="string")l=e.result;else try{l=JSON.stringify(e.result)}catch{l=`[unserializable result: ${typeof e.result}]`}let u=bYe(l),p=Tk(u),f=RYe(1,!1,!1,c?20:0,n);return{params:{filePath:a,content:o.content,text:o.text,newString:o.new_string,query:o.query,input:o.input,arguments:o.arguments},relPath:s,isRisk:c,errorType:fon(e.error||l),errorHash:p,errorText:l,painScore:f,traceId:I_()}}function Wse(e,t,n,r,i,o,a,s,c={}){let l=a.get("scores.tool_failure_friction")||30,u=bk(e,l,r.errorHash,o,{source:n.failureSource});return DYe(o,t.toolName,{filePath:r.relPath,reason:r.isRisk?"risky":"tool",sessionId:e}),s.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:r.params.filePath,error:t.error?String(t.error).substring(0,200):void 0,errorType:r.errorType,gfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,exitCode:n.exitCode,gfiBefore:i,gfiAfter:u.currentGfi}),c.recordTrajectory!==!1&&s.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"failure",durationMs:t.durationMs,exitCode:n.exitCode,errorType:r.errorType,errorMessage:t.error?String(t.error):void 0,gfiBefore:i,gfiAfter:u.currentGfi,paramsJson:$se(t.params,o),resultPreview:MYe(t.result)}),u}function jse(e,t,n,r,i,o,a,s={}){let c=Gs(e),l=c?.gfiBySource?.tool_failure||0,u=c?.gfiBySource?.dispatch_error||0,p=c||sd(e,o);return l>0&&(p=sd(e,o,{source:"tool_failure",amount:l*.5})),u>0&&(p=sd(e,o,{source:"dispatch_error",amount:u*.5})),LYe(o,t.toolName,{sessionId:e,reason:"tool_success"}),s.recordTrajectory!==!1&&a.trajectory?.recordToolCall?.({sessionId:e,toolName:t.toolName,outcome:"success",durationMs:t.durationMs,exitCode:n.exitCode,gfiBefore:i,gfiAfter:p.currentGfi,paramsJson:$se(t.params,o),resultPreview:MYe(t.result)}),a.eventLog.recordToolCall(e,{toolName:t.toolName,filePath:r.params.filePath,gfi:p.currentGfi,gfiBefore:i,gfiAfter:p.currentGfi}),p}function qse(e,t,n){let r=typeof t.params.filePath=="string"?t.params.filePath.replace(/\\/g,"/"):"",i=/(?:^|\/)memory\//.test(r)||r.endsWith("/MEMORY.md")||r==="MEMORY.md",o=r==="PLAN.md"||r.endsWith("/PLAN.md");(i||o)&&n.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:t.params.filePath??"unknown",type:i?"memory":"plan",contentLength:t.params.content?.length??t.params.newString?.length??0}),e.toolName==="memory_store"&&n.hygiene.recordPersistence({ts:new Date().toISOString(),tool:e.toolName,path:"DATABASE",type:"memory",contentLength:t.params.text?.length??0})}function pon(e,t){return e.contextTags.includes(t)||e.trigger.includes(t)}function JD(e,t,n,r,i){let o=z7e(e,n);for(let a of o){let s=r.evolutionReducer.getPrincipleById(a);s&&pon(s,t)&&r.evolutionReducer.recordProbationFeedback(a,i)}VD(e,n)}var NYe=["write","edit","apply_patch","write_file","edit_file","replace"];function $Ye(e,t,n,r,i,o,a,s){let c=process.env.PD_E2E_MODE==="1";if(!(c?[...NYe,...YD]:NYe).includes(e.toolName)||!n.isFailure)return n.isFailure&&$e.log(a,"PAIN_ADMISSION_SKIPPED",JSON.stringify({hook:"after_tool_call",reason:"not_a_write_tool_failure",tool:e.toolName,failureSource:n.failureSource,sessionId:o,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=${n.isFailure}`};let u=n.failureSource??"tool_failure",p=w_(u,o,r?.lastErrorHash),f={observedAt:new Date().toISOString(),workspaceId:a,sessionId:o,toolName:e.toolName,failureSource:n.failureSource,toolNotFound:n.failureSource==="dispatch_error",nonZeroExit:n.exitCode!==0},m=nu(f),y=(r??i)?.consecutiveErrors,_=c?Math.max(4,y??0):y,b=E_(m,t.painScore,{consecutiveErrors:_,isRisky:t.isRisk}),I=ru({triageResult:b,isOwnerManual:!1,isCooldownActive:p,isValid:!0,score:t.painScore,sessionId:o});return $e.log(a,"TRIGGER_DECISION",JSON.stringify({outcome:I.outcome,sourceKind:I.sourceKind,reason:I.reason,nextAction:I.nextAction,triageDecision:I.triageDecision,tool:e.toolName,path:t.relPath})),I.shouldCreateDiagnosticTask?(T_(u,o,r?.lastErrorHash),{admitted:!0,stage:"trigger_admitted",reason:I.reason,detail:`outcome=${I.outcome}, sourceKind=${I.sourceKind}, nextAction=${I.nextAction}`}):{admitted:!1,stage:"trigger_rejected",reason:I.reason,detail:`outcome=${I.outcome}, sourceKind=${I.sourceKind}, nextAction=${I.nextAction}`}}function FYe(e,t,n,r,i,o,a,s,c){if(!i.admitted)return;let l=r.failureSource??"tool_failure",u=`pain_${Date.now()}_${n.errorHash.slice(0,8)}`;e.trajectory?.recordPainEvent({sessionId:o,source:l,score:n.painScore,reason:`Tool ${t.toolName} failed on ${n.relPath}`,severity:n.painScore>=70?"severe":n.painScore>=40?"moderate":"mild",origin:"system_infer",text:u4(n.params.text??n.params.content,s)||void 0,canonicalPainId:u,hostKind:"openclaw"});try{CYe(s,{reason:`Tool ${t.toolName} failed on ${n.relPath}. Error: ${t.error??"Non-zero exit code"}`,source:l,score:String(n.painScore)},()=>e.evolutionReducer.getActivePrinciples().map(f=>({id:f.id,trigger:f.trigger,valueMetrics:f.valueMetrics})),(f,m)=>{let y=e.evolutionReducer.getPrincipleById(f);if(y){y.valueMetrics=m;try{e.principleTreeLedger.updatePrincipleValueMetrics(f,{principleId:f,painPreventedCount:m.painPreventedCount,lastPainPreventedAt:m.lastPainPreventedAt,calculatedAt:m.calculatedAt,avgPainSeverityPrevented:0,totalOpportunities:0,adheredCount:0,violatedCount:0,implementationCost:0,benefitScore:0})}catch(_){$e.log(s,"METRICS_UPDATE_SKIP",String(_))}}})}catch(f){$e.log(s,"PRINCIPLE_TRACK_SKIP",String(f))}e.eventLog.recordPainSignal(o,{score:n.painScore,source:l,reason:`Tool ${t.toolName} failed on ${n.relPath}`,isRisky:n.isRisk}),zD(s,e.trajectory).logPainDetected({traceId:n.traceId,source:l,reason:`Tool ${t.toolName} failed on ${n.relPath}`,score:n.painScore,toolName:t.toolName,filePath:n.relPath,sessionId:o}),c(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:u,painType:l,source:t.toolName,reason:`Tool ${t.toolName} failed on ${n.relPath}; diagnosticGate=${i.reason}`,score:n.painScore,sessionId:o,traceId:n.traceId,agentId:a,provenance:"automatic_hook",hostKind:"openclaw",evidence:Qf(e,o)}},{recordObservability:!1})}function fon(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"}var UYe=new Set,WYe=3e4;function mon(e,t){try{$e.log(e,"PAIN_CONTINUATION_FAILED",JSON.stringify({reason:t.slice(0,200),nextAction:"inspect the admitted pain and retry diagnosis from the persisted canonical pain ID"}))}catch{}}function hon(e,t){let n=!1,r,o=new Promise(a=>{let s=c=>{n||(n=!0,r!==void 0&&clearTimeout(r),c&&mon(e,c),a())};t.then(()=>s(),c=>s(c instanceof Error?c.message:String(c))),r=setTimeout(()=>s(`pain_continuation_timeout:${WYe}ms`),WYe)}).finally(()=>{r!==void 0&&clearTimeout(r),UYe.delete(o)});UYe.add(o)}function gon(e){let t=new Eh({stateDir:e.stateDir}),n=oi(e.workspaceDir),r={listUserTurnsForSession:i=>e.trajectory.listUserTurnsForSession(i),listAssistantTurns:i=>e.trajectory.listAssistantTurns(i)};return new Ny({workspaceDir:e.workspaceDir,stateDir:e.stateDir,ledgerAdapter:t,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:n.effective,getEnvVar:i=>process.env[i],intentDocReader:n4(e.workspaceDir,wk(e.workspaceDir)),trajectoryTurnReader:r})}async function Bs(e,t,n){try{e.evolutionReducer.emitSync(t)}catch(r){$e.log(e.workspaceDir,"EVOLUTION_EMIT_WARN",`Failed to emit evolution event: ${String(r)}`)}if(t.type==="pain_detected"){let r=t.data;try{let i=gon(e);(r.source==="manual"||r.source==="pain"||r.source==="skill:pain")&&$e.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:r.painId,score:r.score}));let a=n?.recordObservability??!0,s=await i.recordPain({painId:r.painId,painType:r.painType,source:r.source,reason:r.reason,score:r.score,sessionId:r.sessionId,agentId:r.agentId,taskId:r.taskId,traceId:r.traceId,provenance:r.provenance,hostKind:r.hostKind,evidence:r.evidence,recordObservability:a});s.status==="failed"&&s.failureCategory?$e.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"&&$e.log(e.workspaceDir,"PAIN_SERVICE_SKIPPED",JSON.stringify({painId:s.painId,taskId:s.taskId,latencyMs:s.latencyMs,message:s.message}))}catch(i){$e.log(e.workspaceDir,"PAIN_SERVICE_ERROR",`recordPain threw: ${String(i)}`);let o=i instanceof Error?i.message:String(i),a=!1;try{let s=new Or({workspaceDir:e.workspaceDir});try{let l=new fD(s).insertDeadLetter({painId:r.painId,painData:r});l.ok?a=!0:$e.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",l.error)}finally{s.close()}}catch(s){$e.log(e.workspaceDir,"DEAD_LETTER_PERSIST_FAILED",String(s))}$e.log(e.workspaceDir,"PAIN_DEAD_LETTER",JSON.stringify({painId:r.painId,painType:r.painType,source:r.source,score:r.score,deadLetterInserted:a,error:o,nextAction:`Run 'pd pain retry --pain-id ${r.painId}' to replay this pain signal`}))}}}function yon(e){return`pain_${Date.now()}_${Tk(e).slice(0,8)}`}function Gse(e,t,n){let r;try{r=EYe(t,n,"after_tool_call")}catch(_){$e.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(_).slice(0,200)}));return}let i=rt.fromHookContextExplicit({...t,workspaceDir:r}),{config:o}=i,a=t.sessionId||"unknown",s=t.sessionId?Gs(t.sessionId):void 0,c=s?.currentGfi??0,l=i.resolve("PROFILE"),u=b_({});if(Rk.existsSync(l))try{let _=Rk.readFileSync(l,"utf8");_.length>1024*1024?$e.log(r,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping"):u=b_(JSON.parse(_))}catch(_){$e.log(r,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(_)}`)}if(e.toolName==="pain"||e.toolName==="skill:pain"){_on(e,t,i,r,a);return}let p=Fse(e),f=Use(e,p,r,u),m;p.isFailure?(m=Wse(a,e,p,f,c,r,o,i),JD(a,e.toolName,r,i,!1)):(jse(a,e,p,f,c,r,i),JD(a,e.toolName,r,i,!0),qse(e,f,i));let y=$Ye(e,f,p,m,s,a,r,o);y.stage!=="not_applicable"&&FYe(i,e,f,p,y,a,t.agentId,r,Bs)}function jYe(e,t){let n=rt.fromHookContextExplicit(t),r=t.sessionId||"unknown",i=t.sessionId?Gs(t.sessionId):void 0,o=i?.currentGfi??0,a=n.resolve("PROFILE"),s=b_({});if(Rk.existsSync(a))try{let f=Rk.readFileSync(a,"utf8");f.length<=1024*1024?s=b_(JSON.parse(f)):$e.log(t.workspaceDir,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping")}catch(f){$e.log(t.workspaceDir,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(f)}`)}let c=Fse(e),l=Use(e,c,t.workspaceDir,s),u=Object.hasOwn(e,"toolUseId")?e.toolUseId:Object.hasOwn(e,"toolCallId")?e.toolCallId:void 0,p;return c.isFailure?(p=Wse(r,e,c,l,o,t.workspaceDir,n.config,n,{recordTrajectory:!1}),JD(r,e.toolName,t.workspaceDir,n,!1)):(jse(r,e,c,l,o,t.workspaceDir,n,{recordTrajectory:!1}),JD(r,e.toolName,t.workspaceDir,n,!0),qse(e,l,n)),{...typeof u=="string"&&u.trim().length>0?{eventId:`openclaw:${u}`}:{},painScore:l.painScore,isRisky:l.isRisk,consecutiveErrors:(p??i)?.consecutiveErrors??0,relativePath:l.relPath,errorHash:l.errorHash,agentId:t.agentId,evidence:Qf(n,r)}}function XD(e,t){let n=Object.hasOwn(e,t)?e[t]:void 0;return typeof n=="string"&&n.trim().length>0?n:null}function qYe(e,t,n){let r=n.metadata;if(!r||r.admitted!==!0||r.duplicate===!0)return;let i=XD(r,"painId"),o=XD(r,"failureSource"),a=XD(r,"relativePath"),s=XD(r,"triggerReason"),c=r.painScore;if(!i||!o||!a||!s||typeof c!="number"||!Number.isFinite(c)){$e.log(t.workspaceDir,"SHARED_PAIN_RESULT_INVALID",JSON.stringify({reason:"shared_pain_metadata_invalid",nextAction:"inspect host-runtime after-tool result metadata"}));return}let l=rt.fromHookContextExplicit(t),u=t.sessionId||"unknown",p=XD(r,"eventId")??I_(),f=`Tool ${e.toolName} failed on ${a}`;l.eventLog.recordPainSignal(u,{score:c,source:o,reason:f,isRisky:r.isRisky===!0}),zD(t.workspaceDir,l.trajectory).logPainDetected({traceId:p,source:o,reason:f,score:c,toolName:e.toolName,filePath:a,sessionId:u});let m=r.evidence,y=Array.isArray(m)?m.filter(_=>typeof _=="object"&&_!==null&&!Array.isArray(_)&&typeof Object.getOwnPropertyDescriptor(_,"sourceRef")?.value=="string"&&typeof Object.getOwnPropertyDescriptor(_,"note")?.value=="string").slice(0,8):[];hon(t.workspaceDir,Bs(l,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:i,painType:"tool_failure",source:e.toolName,reason:`${f}; diagnosticGate=${s}`,score:c,sessionId:u,traceId:p,agentId:t.agentId,provenance:"automatic_hook",hostKind:"openclaw",evidence:y}},{recordObservability:!1}))}function _on(e,t,n,r,i){let o=e.params,a=o&&typeof o=="object"&&!Array.isArray(o)?o:{},s=a.input||a.arguments||"Manual intervention",c=I_();bk(i,100,"manual_pain",r,{source:"manual_pain"}),$e.log(r,"MANUAL_PAIN",`User manually triggered pain: ${s}`),n.eventLog.recordPainSignal(i,{score:100,source:"manual",reason:`User intervention: ${s}`,isRisky:!0});let l=yon(i);n.trajectory?.recordPainEvent?.({sessionId:i,source:"manual",score:100,reason:`User intervention: ${s}`,origin:"user_manual",text:s,canonicalPainId:l,hostKind:"openclaw"}),zD(r,n.trajectory).logPainDetected({traceId:c,source:"manual",reason:`User intervention: ${s}`,score:100,toolName:e.toolName,sessionId:i});let p=dr(r,"painEvidenceAdmission"),f=dr(r,"painEvidenceAdmissionDefault");if(p.enabled&&f.enabled){let y=uD({sessionId:i}),_=nu(y),b=E_(_,100),I=w_(_,i,"manual_pain"),E=ru({triageResult:b,isOwnerManual:!0,isCooldownActive:I,isValid:!0,score:100,sessionId:i});oi(r).effective&&$e.log(r,"TRIGGER_DECISION",JSON.stringify({outcome:E.outcome,sourceKind:E.sourceKind,reason:E.reason,nextAction:E.nextAction,isOwnerManual:!0,sessionId:i,score:100})),E.shouldCreateDiagnosticTask?(T_(_,i,"manual_pain"),Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:i,traceId:c,agentId:t.agentId,provenance:i&&i!=="unknown"?"host_context_bound":"owner_reported_no_host_trace",hostKind:"openclaw",evidence:Qf(n,i)}},{recordObservability:!1})):$e.log(r,"MANUAL_PAIN_SKIPPED",E.reason)}else{let y=Gs(i),_=Ek({source:"manual",score:100,currentGfi:y?.currentGfi??0,sessionId:i});if(!_.shouldDiagnose){$e.log(r,"MANUAL_PAIN_SKIPPED",`Manual pain within cooldown: ${_.detail}`);let b;try{b=JSON.stringify({reason:_.reason,detail:_.detail,source:"manual",sessionId:i,gfi:0,score:100})}catch(E){$e.log(r,"PAYLOAD_SERIALIZE_FAILED",String(E)),b=JSON.stringify({reason:_.reason,detail:"(log serialization failed)"})}$e.log(r,"PAIN_GATE_REJECTED",b),oi(r).effective&&$e.log(r,"TRIGGER_DECISION",JSON.stringify({outcome:"cooldown_skipped",sourceKind:"owner_reported",reason:`Manual pain within cooldown: ${_.detail}`,nextAction:"wait_for_cooldown_or_manual_retrigger",isOwnerManual:!0,sessionId:i,score:100}));return}Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:l,painType:"user_frustration",source:e.toolName,reason:`User intervention: ${s}`,score:100,sessionId:i,traceId:c,agentId:t.agentId,provenance:i&&i!=="unknown"?"host_context_bound":"owner_reported_no_host_trace",hostKind:"openclaw",evidence:Qf(n,i)}},{recordObservability:!1})}}var von={enableLlmStage:!0,llmTimeoutMs:3e4,promptTemplate:"",strongPainScore:_8e,strongRateLimitPerHour:v8e};function Bse(e){return e==="user"||e==="api"||e===void 0}function xon(){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 bon=3600*1e3,d4=class{wctx;storeProvider;config;llmClassifier;rateLimit=new Map;constructor(t,n={}){this.wctx=t,this.storeProvider=n.keywordStoreProvider??(n.keywordStore?()=>n.keywordStore:()=>xon()),this.config=n.config??von,this.llmClassifier=n.llmClassifier??null}detectSync(t,n,r,i){if(!Bse(r))return;let o=new Date().toISOString(),a=this.storeProvider(),s=mD(t,n,a,this.config,o),c={sessionId:n,turnIndex:i?.turnIndex??Date.now(),rawText:t,correctionDetected:s.isSignal&&s.strength==="STRONG",correctionCue:s.matchedTerms.length>0?s.matchedTerms.join(", "):null,referencesAssistantTurnId:i?.referencesAssistantTurnId??null};try{this.wctx.trajectory?.recordUserTurn?.(c)}catch(l){$e.log(this.wctx.workspaceDir,"SIGNAL_TRAJECTORY_FAIL",`recordUserTurn threw: ${String(l)}`)}if(s.isSignal&&s.strength==="STRONG"&&s.matchedPrecision==="high"){this.routeStrong(s,n,t,this.resolveOccurrenceId(n,t,i));return}if(s.needsLlmConfirmation){let l={output:s,sessionId:n,text:t,occurrenceId:this.resolveOccurrenceId(n,t,i),traceId:I_(),storeSnapshot:a};this.detectAsyncAndRoute(l)}}async detectAsyncAndRoute(t){let n;if(this.llmClassifier&&this.config.enableLlmStage){let r=null;try{r=await this.llmClassifier(t.text,this.config.promptTemplate)}catch(o){$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`LLM classifier threw: ${String(o)}`)}let i=new Date().toISOString();r?n=hD(r,t.text,t.sessionId,this.config,i):($e.log(this.wctx.workspaceDir,"SIGNAL_LLM_PARSE_FAIL","LLM returned invalid result, treating as none"),n=hD({is_feedback:!1,type:"none",confidence:1,reason:"LLM parse failed"},t.text,t.sessionId,this.config,i))}else{if(t.output.matchedPrecision==="ambiguous"&&t.output.matchedTerms.length>0&&t.output.matchedTerms.some(i=>t.storeSnapshot.terms[i]?.category==="empathy")){$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED_WEAK","LLM unavailable, routing empathy ambiguous as WEAK (GFI accumulation, no STRONG trigger)");let i={...t.output,isSignal:!0,type:"empathy",strength:"WEAK",detectionSource:"keyword",needsLlmConfirmation:!1};this.routeWeak(i,t.sessionId);return}$e.log(this.wctx.workspaceDir,"SIGNAL_LLM_DEGRADED","LLM unavailable, dropping candidate (no STRONG trigger)");return}n.isSignal&&n.strength==="STRONG"?this.routeStrong(n,t.sessionId,t.text,t.occurrenceId):n.isSignal&&n.strength==="WEAK"&&this.routeWeak(n,t.sessionId)}resolveOccurrenceId(t,n,r){return r?.turnIndex!==void 0?String(r.turnIndex):($e.log(this.wctx.workspaceDir,"SIGNAL_OCCURRENCE_ID_LEGACY","turnIndex not provided; correction occurrence identity degraded to content hash"),"legacy:"+GYe("sha256").update(t+":"+n).digest("hex").slice(0,16))}routeStrong(t,n,r,i){if(!this.tryConsumeRateLimit(n)){$e.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"),{painId:a}=Vae({workspaceDir:this.wctx.workspaceDir,sessionId:n,occurrenceId:i,text:r});Bs(this.wctx,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:a,painType:"user_frustration",source:"user_correction",reason:o,score:this.config.strongPainScore,sessionId:n,agentId:"main",traceId:I_(),provenance:"host_context_bound",hostKind:"openclaw",evidence:[{sourceRef:"signal_collector",note:t.evidence.excerpt}]}},{recordObservability:!0}).catch(s=>{$e.log(this.wctx.workspaceDir,"SIGNAL_EMIT_FAIL",`emitPainDetectedEvent failed: ${String(s)}`)})}routeWeak(t,n){try{let r=GYe("sha256").update(`${t.evidence.detectedAt}:${n}`).digest("hex").slice(0,32);bk(n,20,r,this.wctx.workspaceDir,{source:"user_empathy"})}catch(r){$e.log(this.wctx.workspaceDir,"SIGNAL_TRACK_FRICTION_FAIL",`trackFriction threw: ${String(r)}`)}}tryConsumeRateLimit(t){let n=this.config.strongRateLimitPerHour,r=Date.now(),i=this.rateLimit.get(t);return(!i||r-i.windowStart>=bon)&&(i={count:0,windowStart:r},this.rateLimit.set(t,i)),i.count>=n?!1:(i.count+=1,!0)}};function BYe(e,t){try{let n=LD(e.workspaceDir,"signal_collector","signalCollector",t);if(!n.enabled)return t?.debug?.(`[PD:Signal] LLM classifier disabled: ${n.reason}`),null;if(n.readiness!=="not_ready"&&n.readiness!=="ready")return t?.debug?.(`[PD:Signal] LLM classifier not ready (${n.readiness}): ${n.reason}. ${n.nextAction}`),null;if(!n.provider||!n.model||!n.apiKeyEnv)return t?.debug?.("[PD:Signal] LLM classifier missing provider/model/apiKeyEnv"),null;let r=new Xl({provider:n.provider,model:n.model,apiKeyEnv:n.apiKeyEnv,timeoutMs:n.timeoutMs??3e4,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return async(o,a)=>{let s=B3(o);try{let c=await r.startRun({agentSpec:{agentId:"signal-collector",schemaVersion:"1"},inputPayload:{prompt:s},contextItems:[],timeoutMs:n.timeoutMs??3e4,outputSchemaRef:"signal-classification-output-v1"}),l=await r.pollRun(c.runId),u=Date.now()+(n.timeoutMs??3e4);for(;l.status==="running"&&Date.now()<u;)await new Promise(m=>setTimeout(m,500)),l=await r.pollRun(c.runId);if(l.status!=="succeeded")return $e.log(e.workspaceDir,"SIGNAL_LLM_TIMEOUT",JSON.stringify({status:l.status})),null;let p=await r.fetchOutput(c.runId),f=K3(p?.payload);return f.path==="structured"&&f.value?f.value:(f.path==="legacy_string"||f.path==="legacy_envelope")&&f.value?($e.log(e.workspaceDir,"SIGNAL_LLM_LEGACY_STRING_PAYLOAD",`adapter payload path=${f.path} (no outputSchemaRef support); parsed via legacy path`),f.value):($e.log(e.workspaceDir,"SIGNAL_LLM_PARSE_FAIL",`unusable classifier payload path=${f.path}: ${bp(p?.payload)}`),null)}catch(c){return $e.log(e.workspaceDir,"SIGNAL_LLM_FAILED",String(c).slice(0,200)),null}}}catch(n){return t?.warn?.(`[PD:Signal] createSignalLlmClassifierFromConfig failed: ${String(n)}`),null}}function KYe(e,t){return I8e({workspaceDir:e.workspaceDir,onDegradation:(n,r)=>$e.log(e.workspaceDir,n,r),...t?{logger:t}:{}})}function Hse(e,t,n){let r=t.getActivePrinciples(),i=t.getProbationPrinciples(),o=new Set;try{o=Soe(e)}catch(u){let p=`[PD:Pruning] Failed to read review log \u2014 all principles injected: ${u instanceof Error?u.message:String(u)}`;n?.info?n.info(p):console.error(p)}let a=yD(r.filter(u=>!o.has(u.id)),X3),s=yD(i.filter(u=>!o.has(u.id)),1e3);(a.wasTruncated||s.wasTruncated)&&n?.info?.(`[PD:Prompt] Principles truncated: active=${a.selected.length}/${r.length} (${a.totalChars}c), probation=${s.selected.length}/${i.length} (${s.totalChars}c)`);let c=a.selected,l=s.selected;return{active:c,probation:l,content:c.length>0||l.length>0?_Ye(c,l):"",selectedIds:new Set([...c,...l].map(u=>u.id)),wasTruncated:a.wasTruncated||s.wasTruncated}}var Ion=6e4,HYe=new Map,won=256,Kse=new Map;function Ton(e,t){if(Object.hasOwn(e,t))return Object.getOwnPropertyDescriptor(e,t)?.value}function Eon(e){if(typeof e!="object"||e===null)return;let t=Ton(e,"code");return typeof t=="string"?t:void 0}function Son(e){let t=HYe.get(e);return t||(t=new Map,HYe.set(e,t)),t}function zYe(e,t){return typeof e!="object"||e===null||!Object.hasOwn(e,"role")?!1:Object.getOwnPropertyDescriptor(e,"role")?.value===t}function kon(e,t,n){let r=e.trajectory?.listUserTurnsForSession?.(t)??[];return r.length>0?r.reduce((i,o)=>Math.max(i,o.turnIndex),0)+1:n.filter(i=>zYe(i,"user")).length+1}function Aon(e,t,n){let r=Kse.get(e);r||(r=new Set,Kse.set(e,r));let i=`${t}\0${n}`;if(r.has(i))return!1;if(r.add(i),r.size>won){let o=r.values().next().value;typeof o=="string"&&r.delete(o)}return!0}function Ron(e,t,n){return Kse.get(e)?.has(`${t}\0${n}`)??!1}function Con(e,t){let n=Son(t),r=Date.now(),i=n.get(e);try{let a=ub.statSync(e).mtimeMs;if(i&&r-i.loadedAt<Ion&&i.mtime===a)return i.content;let s=ub.readFileSync(e,"utf8");return n.set(e,{content:s,mtime:a,loadedAt:r}),s}catch(o){return n.delete(e),Eon(o)!=="ENOENT"&&console.warn(`[PD:Prompt] cachedReadFile failed: path=${e}, workspace=${t}, error=${String(o)}`),""}}var VYe=new Map;function Pon(e,t){let n=VYe.get(e.workspaceDir);if(!n){let r=BYe(e,t),i=KYe(e,t);n=new d4(e,{llmClassifier:r,keywordStoreProvider:()=>i.resolve()}),VYe.set(e.workspaceDir,n)}return n}function db(e){return{...oi(e).effective.resolvedContextInjection}}function Oon(e,t){try{let n=oi(e);if(!n.ok){let i=n.errors.map(o=>`${o.path||"(root)"}: ${o.reason}`).join("; ");t?.warn?.(`[PD:Prompt] .pd/config.yaml malformed (${i}). Core axioms fall back to default language ${hg}. nextAction: ${n.errors[0]?.nextAction??"Fix .pd/config.yaml and retry"}`)}let r=KA(n.effective.config.principles?.outputLanguage);return r.degradationWarning&&t?.warn?.(`[PD:Prompt] ${r.degradationWarning}`),r}catch(n){return t?.warn?.(`[PD:Prompt] Core axiom language resolution failed (${String(n)}); falling back to default language ${hg}. nextAction: Check that .pd/config.yaml is readable YAML`),{outputLanguage:hg}}}async function Vse(e,t,n,r){let{workspaceDir:i}=t,o=t.api?.logger;if(o?.info?.(`[PD:Prompt] handleBeforePromptBuild called: workspaceDir=${!!i}, trigger=${t.trigger}, sessionId=${t.sessionId?.substring(0,20)}`),!i){o?.warn?.("[PD:Prompt] workspaceDir is missing \u2014 skipping PD context injection");return}let a=rt.fromHookContext(t),{runId:s,sessionKey:c,trigger:l,sessionId:u}=t,p=Bse(l),f=t.api;u&&a.trajectory?.recordSession?.({sessionId:u});let m=null;if(u&&p&&e.messages.some(it=>zYe(it,"assistant"))){let it=a.trajectory?.listAssistantTurns?.(u)??[];m=it[it.length-1]?.id??null}let y=db(a.workspaceDir),_=Y3(l,u),b=u?Gs(u):void 0,I,E="",R="";l==="user"&&u&&b&&b.currentGfi>=100&&sd(u,i),I=hYe();let A=gYe(),{message:P,isAgentToAgent:O}=mYe(e.prompt,u),$=!1;if(p&&u&&f&&!O&&($=!0),P&&u&&p&&!O&&(s&&Ron(a.workspaceDir,c??u,s)?o?.info?.(`[PD:Prompt] duplicate signal run skipped: runId=${s}, sessionId=${u.substring(0,20)}`):(s||o?.warn?.(`[PD:Prompt] runId missing; signal collection cannot be deduplicated: sessionId=${u.substring(0,20)}`),Pon(a,o).detectSync(P,u,l??"api",{referencesAssistantTurnId:m,turnIndex:kon(a,u,e.messages)}),s&&Aon(a.workspaceDir,c??u,s))),l==="heartbeat"||l==="cron"){if(u){let xe=X7e(u);if(xe>=1){let pt=J7e(u,xe);pt&&o?.info?.(`[PD:GFI] Heartbeat decay applied: ${xe}min elapsed, GFI now ${pt.currentGfi.toFixed(1)}`)}}let it=a.resolve("HEARTBEAT");if(ub.existsSync(it))try{let xe=ub.readFileSync(it,"utf8");E+=yYe(xe)}catch(xe){o?.error(`[PD:Prompt] Failed to read HEARTBEAT: ${String(xe)}`)}}let M="";try{M=HA(Oon(i,o).outputLanguage,"foundational")}catch(it){o?.warn?.(`[PD:Prompt] Failed to load core principles from registry: ${String(it)}`)}let U="";if(y.thinkingOs){let it=a.resolve("THINKING_OS");try{let xe=Con(it,a.workspaceDir);xe&&(U=xe.trim())}catch(xe){o?.error(`[PD:Prompt] Failed to read THINKING_OS: ${String(xe)}`)}}let K="",ce="";if(!_&&y.projectFocus!=="off"){let it=a.resolve("CURRENT_FOCUS"),xe=od.getExtensionRoot(),{content:pt,recovered:kn,validationErrors:Mn}=iYe(it,xe||"",o);if(kn&&o?.info?.("[PD:Prompt] CURRENT_FOCUS.md was recovered from template"),Mn.length>0&&o?.warn?.(`[PD:Prompt] CURRENT_FOCUS validation errors: ${Mn.join(", ")}`),pt.trim())try{let{stateDir:tn}=a,zt=rYe(it,i,tn);zt.compressed?o?.info?.(`[PD:Prompt] Auto-compressed CURRENT_FOCUS: ${zt.oldLines} \u2192 ${zt.newLines} lines. Milestones archived: ${zt.milestonesArchived}`):zt.reason==="Rate limited (24h interval)"&&o?.debug?.(`[PD:Prompt] Auto-compress skipped: ${zt.reason}`);let F=zt.newContent?.trim()||pt.trim();if(F){let q=vD(F);if(q&&(ce=xD(q)),y.projectFocus==="summary")K=rk(F,30);else{let B=await eYe(it,3);if(B.length>0){let le=B.map((Q,re)=>`
2515
2519
  ---
2516
2520
 
2517
2521
  **\u5386\u53F2\u7248\u672C v${B.length-re}**
@@ -2541,7 +2545,7 @@ ${Q}`).join("");K=`${F}${le}`}else K=F}}}catch(tn){o?.error(`[PD:Prompt] Failed
2541
2545
  WHERE p.source_principle_id = ? AND a.deactivated_at IS NULL
2542
2546
  ORDER BY a.activated_at DESC
2543
2547
  LIMIT 1
2544
- `).get(t);s=zse(l?.activated_at)}return{title:o,approvedAt:s,sourceSummary:i.painReasonSummary?.slice(0,60)}}catch{return}}function ZYe(e,t,n){let r;try{r=e.trajectory}catch(i){return n(`[PD_GATE] Trajectory gate block skipped (reasonCode=trajectory_getter_failed): ${String(i)}`),"skipped"}if(!r||typeof r.recordGateBlock!="function")return n("[PD_GATE] Trajectory gate block skipped: collector not mounted (reasonCode=trajectory_collector_unmounted); event-log row retained"),"skipped";try{return r.recordGateBlock(t),"written"}catch(i){return n(`[PD_GATE] Failed to record trajectory gate block (reasonCode=trajectory_write_failed): ${String(i)}`),"retryable"}}function Yse(e,t,n){let{filePath:r,reason:i,toolName:o,sessionId:a,blockSource:s}=t,c=p=>n.warn?.(p),l=p=>n.error?.(p);if(a)try{K7e(a)}catch(p){c(`[PD_GATE] Session GFI tracking skipped (reasonCode=gfi_track_failed): ${String(p)}`)}let u={sessionId:a??null,toolName:o,filePath:r,reason:i};try{e.eventLog.recordGateBlock(a,{toolName:o,filePath:r??"<unresolved>",reason:i,blockSource:s??"gate"})}catch(p){c(`[PD_GATE] Failed to record gate block event: ${String(p)}`)}ZYe(e,u,c)==="retryable"&&tJe(e,u,1,c,l)}function eJe(e,t,n){let{filePath:r,reason:i,toolName:o,sessionId:a,blockSource:s}=t,c=r??"<unresolved>",l=y=>n.warn?.(y),u=y=>n.error?.(y),p=s?`[${s}]`:"";if(u(`[PD_GATE]${p} BLOCKED: ${c}. Reason: ${i}`),Yse(e,t,n),a){let _=`gate_${Date.now()}_${Math.random().toString(36).slice(2,10)}`,b=dr(e.workspaceDir,"painEvidenceAdmission"),I=dr(e.workspaceDir,"painEvidenceAdmissionDefault"),E=b.enabled&&I.enabled,R=Gs(a);if(E){let A=e.resolve("PROFILE"),P=b_({});if(p4.existsSync(A))try{let M=p4.readFileSync(A,"utf8");M.length>1024*1024?(n.warn?.("[PD_GATE] PROFILE.json exceeds 1 MB, skipping"),$e.log(e.workspaceDir,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping \u2014 fallback to non-risky")):P=b_(JSON.parse(M))}catch(M){n.warn?.(`[PD_GATE] Failed to parse PROFILE.json: ${String(M)}`),$e.log(e.workspaceDir,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(M)} \u2014 fallback to non-risky`)}let O=RK(c,P.risk_paths),$=E_("rulehost_block",45,{isUnsafeHighConfidence:O,isRisky:O,consecutiveErrors:R?.consecutiveErrors});if($.decision!=="admit")n.info?.(`[PD_GATE] Triage ${$.decision}: ${$.reason}`);else{let M=`${o}:${c}:${i}`,U=w_("rulehost_block",a,M),K=ru({triageResult:$,isOwnerManual:!1,isCooldownActive:U,isValid:!0,score:45,sessionId:a});K.shouldCreateDiagnosticTask?(T_("rulehost_block",a,M),Bs(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:_,painType:"user_frustration",source:"gate_blocked",reason:`Gate blocked ${o} on ${c}: ${i}`,score:45,sessionId:a,agentId:"main"}}).catch(ce=>{l(`[PD_GATE] Failed to emit gate block pain event: ${String(ce)}`)})):n.info?.(`[PD_GATE] Gate B skipped: ${K.reason}`)}}else{let A=Ek({source:"gate_blocked",score:45,currentGfi:R?.currentGfi??0,consecutiveErrors:R?.consecutiveErrors??0,sessionId:a,errorHash:`${o}:${c}:${i}`,thresholds:{painTrigger:e.config.get("thresholds.pain_trigger")||40,highSeverity:e.config.get("severity_thresholds.high")||70}});A.shouldDiagnose?Bs(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:_,painType:"user_frustration",source:"gate_blocked",reason:`Gate blocked ${o} on ${c}: ${i}`,score:45,sessionId:a,agentId:"main"}}).catch(P=>{l(`[PD_GATE] Failed to emit gate block pain event: ${String(P)}`)}):n.info?.(`[PD_GATE] Gate block recorded without Runtime V2 diagnosis: ${A.detail}`)}}let f;if(dr(e.workspaceDir,"principle_receipt_block_copy",n).enabled&&t.blockSource==="rule-host"){let y=JYe(e.workspaceDir,t.ruleId,t.principleId);y?f=jon({filePath:c,reason:i,toolName:o,metadata:y}):(l("[PD_GATE] Receipt metadata unresolved \u2014 generic block copy used (rc-9)"),f=QYe({filePath:c,reason:i}))}else f=QYe({filePath:c,reason:i});return{block:!0,blockReason:f}}function jon({filePath:e,reason:t,toolName:n,metadata:r}){let i=r.approvedAt?`\u4F60 ${r.approvedAt} \u6279\u51C6`:"\u4F60\u6279\u51C6",o=r.sourceSummary?` \xB7 \u6765\u6E90\uFF1A${r.sourceSummary}`:"";return`\u26D4 [PD \u539F\u5219]\u300C${r.title}\u300D\u62E6\u622A\u4E86 ${n} ${e}
2548
+ `).get(t);s=zse(l?.activated_at)}return{title:o,approvedAt:s,sourceSummary:i.painReasonSummary?.slice(0,60)}}catch{return}}function ZYe(e,t,n){let r;try{r=e.trajectory}catch(i){return n(`[PD_GATE] Trajectory gate block skipped (reasonCode=trajectory_getter_failed): ${String(i)}`),"skipped"}if(!r||typeof r.recordGateBlock!="function")return n("[PD_GATE] Trajectory gate block skipped: collector not mounted (reasonCode=trajectory_collector_unmounted); event-log row retained"),"skipped";try{return r.recordGateBlock(t),"written"}catch(i){return n(`[PD_GATE] Failed to record trajectory gate block (reasonCode=trajectory_write_failed): ${String(i)}`),"retryable"}}function Yse(e,t,n){let{filePath:r,reason:i,toolName:o,sessionId:a,blockSource:s}=t,c=p=>n.warn?.(p),l=p=>n.error?.(p);if(a)try{K7e(a)}catch(p){c(`[PD_GATE] Session GFI tracking skipped (reasonCode=gfi_track_failed): ${String(p)}`)}let u={sessionId:a??null,toolName:o,filePath:r,reason:i};try{e.eventLog.recordGateBlock(a,{toolName:o,filePath:r??"<unresolved>",reason:i,blockSource:s??"gate"})}catch(p){c(`[PD_GATE] Failed to record gate block event: ${String(p)}`)}ZYe(e,u,c)==="retryable"&&tJe(e,u,1,c,l)}function eJe(e,t,n){let{filePath:r,reason:i,toolName:o,sessionId:a,blockSource:s}=t,c=r??"<unresolved>",l=y=>n.warn?.(y),u=y=>n.error?.(y),p=s?`[${s}]`:"";if(u(`[PD_GATE]${p} BLOCKED: ${c}. Reason: ${i}`),Yse(e,t,n),a){let _=`gate_${Date.now()}_${Math.random().toString(36).slice(2,10)}`,b=dr(e.workspaceDir,"painEvidenceAdmission"),I=dr(e.workspaceDir,"painEvidenceAdmissionDefault"),E=b.enabled&&I.enabled,R=Gs(a);if(E){let A=e.resolve("PROFILE"),P=b_({});if(p4.existsSync(A))try{let M=p4.readFileSync(A,"utf8");M.length>1024*1024?(n.warn?.("[PD_GATE] PROFILE.json exceeds 1 MB, skipping"),$e.log(e.workspaceDir,"PROFILE_PARSE_WARN","PROFILE.json exceeds 1 MB, skipping \u2014 fallback to non-risky")):P=b_(JSON.parse(M))}catch(M){n.warn?.(`[PD_GATE] Failed to parse PROFILE.json: ${String(M)}`),$e.log(e.workspaceDir,"PROFILE_PARSE_WARN",`Failed to parse PROFILE.json: ${String(M)} \u2014 fallback to non-risky`)}let O=RK(c,P.risk_paths),$=E_("rulehost_block",45,{isUnsafeHighConfidence:O,isRisky:O,consecutiveErrors:R?.consecutiveErrors});if($.decision!=="admit")n.info?.(`[PD_GATE] Triage ${$.decision}: ${$.reason}`);else{let M=`${o}:${c}:${i}`,U=w_("rulehost_block",a,M),K=ru({triageResult:$,isOwnerManual:!1,isCooldownActive:U,isValid:!0,score:45,sessionId:a});K.shouldCreateDiagnosticTask?(T_("rulehost_block",a,M),Bs(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:_,painType:"user_frustration",source:"gate_blocked",reason:`Gate blocked ${o} on ${c}: ${i}`,score:45,sessionId:a,agentId:"main",hostKind:"openclaw"}}).catch(ce=>{l(`[PD_GATE] Failed to emit gate block pain event: ${String(ce)}`)})):n.info?.(`[PD_GATE] Gate B skipped: ${K.reason}`)}}else{let A=Ek({source:"gate_blocked",score:45,currentGfi:R?.currentGfi??0,consecutiveErrors:R?.consecutiveErrors??0,sessionId:a,errorHash:`${o}:${c}:${i}`,thresholds:{painTrigger:e.config.get("thresholds.pain_trigger")||40,highSeverity:e.config.get("severity_thresholds.high")||70}});A.shouldDiagnose?Bs(e,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:_,painType:"user_frustration",source:"gate_blocked",reason:`Gate blocked ${o} on ${c}: ${i}`,score:45,sessionId:a,agentId:"main",hostKind:"openclaw"}}).catch(P=>{l(`[PD_GATE] Failed to emit gate block pain event: ${String(P)}`)}):n.info?.(`[PD_GATE] Gate block recorded without Runtime V2 diagnosis: ${A.detail}`)}}let f;if(dr(e.workspaceDir,"principle_receipt_block_copy",n).enabled&&t.blockSource==="rule-host"){let y=JYe(e.workspaceDir,t.ruleId,t.principleId);y?f=jon({filePath:c,reason:i,toolName:o,metadata:y}):(l("[PD_GATE] Receipt metadata unresolved \u2014 generic block copy used (rc-9)"),f=QYe({filePath:c,reason:i}))}else f=QYe({filePath:c,reason:i});return{block:!0,blockReason:f}}function jon({filePath:e,reason:t,toolName:n,metadata:r}){let i=r.approvedAt?`\u4F60 ${r.approvedAt} \u6279\u51C6`:"\u4F60\u6279\u51C6",o=r.sourceSummary?` \xB7 \u6765\u6E90\uFF1A${r.sourceSummary}`:"";return`\u26D4 [PD \u539F\u5219]\u300C${r.title}\u300D\u62E6\u622A\u4E86 ${n} ${e}
2545
2549
  ${i}${o}
2546
2550
  Reason: ${t}
2547
2551
 
@@ -2574,13 +2578,13 @@ and ask for explicit confirmation to proceed.
2574
2578
  `}),u+=`
2575
2579
  ### Review
2576
2580
  - Signals above are informational notes. Fatal-intercept signals were already emitted into the Runtime V2 pain chain. Review and act on them via pd-console: \`pd console open --workspace "<workspace>"\`.
2577
- `;try{let p=k_.dirname(c);Li.existsSync(p)||Li.mkdirSync(p,{recursive:!0}),Li.appendFileSync(c,u,"utf8"),n.some(m=>m.includes("[FATAL INTERCEPT]"))&&Bs(i,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`intercept_${Date.now()}`,painType:"tool_failure",source:"intercept_extraction",reason:"Hard intercept detected in session history compaction.",score:100,sessionId:t.sessionId||"unknown",agentId:t.agentId}})}catch(p){t.logger?.error?.(`[PD:Lifecycle] Failed to write pain signals: ${String(p)}`)}}}async function uJe(e,t){if(!t.workspaceDir)return;let n=rt.fromHookContext(t),[r]=new Date().toISOString().split("T"),i=k_.join(t.workspaceDir,zn.MEMORY,`${r}.md`),o=`
2581
+ `;try{let p=k_.dirname(c);Li.existsSync(p)||Li.mkdirSync(p,{recursive:!0}),Li.appendFileSync(c,u,"utf8"),n.some(m=>m.includes("[FATAL INTERCEPT]"))&&Bs(i,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:`intercept_${Date.now()}`,painType:"tool_failure",source:"intercept_extraction",reason:"Hard intercept detected in session history compaction.",score:100,sessionId:t.sessionId||"unknown",agentId:t.agentId,hostKind:"openclaw"}})}catch(p){t.logger?.error?.(`[PD:Lifecycle] Failed to write pain signals: ${String(p)}`)}}}async function uJe(e,t){if(!t.workspaceDir)return;let n=rt.fromHookContext(t),[r]=new Date().toISOString().split("T"),i=k_.join(t.workspaceDir,zn.MEMORY,`${r}.md`),o=`
2578
2582
  ## [${new Date().toISOString()}] Pre-Compaction Checkpoint
2579
2583
  - Compacting session with ${e.messageCount} messages.
2580
2584
  - Ensuring critical state is flushed to disk.
2581
2585
  `;try{let s=k_.dirname(i);Li.existsSync(s)||Li.mkdirSync(s,{recursive:!0}),Li.appendFileSync(i,o,"utf8")}catch(s){t.logger?.error?.(`[PD:Lifecycle] Failed to write pre-compaction checkpoint: ${String(s)}`)}let a=e.sessionFile;a&&(await zon(a,t),await Yon(a,t,n))}async function Yon(e,t,n){if(!Li.existsSync(e)){t.logger?.debug&&t.logger.debug(`[WorkingMemory] Session file not found: ${e}`);return}let r=[],i=0,o=1e3,a=Li.createReadStream(e),s=Qse.createInterface({input:a,crlfDelay:1/0});try{for await(let u of s){if(i>=o)break;if(u.trim()){i++;try{let p=JSON.parse(u);r.push(p)}catch{}}}}finally{try{s.close(),a.destroy()}catch{}}if(r.length===0){t.logger?.debug&&t.logger.debug("[WorkingMemory] No messages found in session file");return}let c=tYe(r,t.workspaceDir);if(c.artifacts.length===0&&c.activeProblems.length===0&&c.nextActions.length===0){t.logger?.debug&&t.logger.debug("[WorkingMemory] No working memory to preserve");return}let l=n.resolve("CURRENT_FOCUS");try{let u="";if(Li.existsSync(l)){u=Li.readFileSync(l,"utf-8");let m=`${l}.wm-backup`;Li.copyFileSync(l,m)}let p=ID(u,c),f=k_.dirname(l);Li.existsSync(f)||Li.mkdirSync(f,{recursive:!0}),Pt(l,p),t.logger?.info?.(`[WorkingMemory] Preserved ${c.artifacts.length} artifacts, ${c.activeProblems.length} problems, ${c.nextActions.length} next actions to CURRENT_FOCUS.md`)}catch(u){t.logger?.error?.(`[PD:Lifecycle] Failed to save working memory: ${String(u)}`);let p=`${l}.wm-backup`;if(Li.existsSync(p))try{Li.copyFileSync(p,l),t.logger?.warn?.("[WorkingMemory] Restored from backup after failure")}catch{}}}async function dJe(e,t){if(!t.workspaceDir)return;let[n]=new Date().toISOString().split("T"),r=k_.join(t.workspaceDir,zn.MEMORY,`${n}.md`),o=`- Post-Compaction Complete. Reduced active context to ${e.messageCount??0} messages.
2582
2586
  `;try{Li.appendFileSync(r,o,"utf8")}catch(a){t.logger?.error?.(`[PD:Lifecycle] Failed to write post-compaction checkpoint: ${String(a)}`)}}import{createHash as Jon}from"crypto";var f4=class{core;constructor(t){this.core=new ek({match:n=>t.match(n),hash:n=>Jon("sha256").update(n).digest("hex"),shouldIgnoreProtocol:jD})}detect(t){return this.core.detect(t)}updateCache(t,n){this.core.updateCache(t,n)}flushQueue(){return this.core.flushQueue()}};var m4=null,Zse=null,pJe={get(e){if(!m4||Zse!==e){let t=MK.get(e);m4=new f4(t),Zse=e}return m4},reset(){m4=null,Zse=null}};function fJe(e,t,n){return Math.max(t,Math.min(n,e))}function Xon(e){let t=Number(e);return Number.isFinite(t)?fJe(t,0,1):1}function Qon(e){return/^\s*\[EMOTIONAL_DAMAGE_DETECTED(?::(mild|moderate|severe))?\]\s*$/i.exec(e)}function Zon(e,t){let n=t.index??0,r=e.substring(Math.max(0,n-100),n).toLowerCase();if((r.match(/["'\u300c\u300d\u201c\u201d`]/g)||[]).length%2===1)return!0;let o=[/用户(说|让|要求|让我输出)/,/user\s+(said|asked|told|wants)\s+me\s+to\s+(output|write|say)/,/请(输出|包含|显示).*\[emotional/,/please\s+(output|include).*\[emotional/,/你让我输出/];for(let c of o)if(c.test(r))return!0;let a=[{pattern:/echo/,window:15},{pattern:/copy/,window:15},{pattern:/复述/,window:15}];for(let{pattern:c,window:l}of a){let u=e.substring(Math.max(0,n-l),n).toLowerCase();if(c.test(u))return!0}return(r.match(/```/g)||[]).length%2===1}function ean(e){if(!e||typeof e!="string")return{detected:!1,severity:"mild",confidence:1};let t=/<empathy\s+([^>]*)\/?>(?:<\/empathy>)?/i.exec(e);if(t?.[1]){let[,i]=t,o=/signal\s*=\s*"([^"]+)"/i.exec(i)?.[1]?.toLowerCase();if(o==="damage"||o==="pain"||o==="frustration"){let a=qx(/severity\s*=\s*"([^"]+)"/i.exec(i)?.[1]),s=Xon(/confidence\s*=\s*"([^"]+)"/i.exec(i)?.[1]),c=/reason\s*=\s*"([^"]+)"/i.exec(i)?.[1];return{detected:!0,severity:a,confidence:s,reason:c,mode:"structured"}}}let n=/"empathy"\s*:\s*\{[\s\S]*?\}/i.exec(e);if(n){let i=`{${n[0]}}`;try{let o=JSON.parse(i);if(o.empathy?.damageDetected===!0)return{detected:!0,severity:qx(o.empathy.severity),confidence:fJe(Number(o.empathy.confidence??1),0,1),reason:o.empathy.reason,mode:"structured"}}catch{}}let r=Qon(e);return r?Zon(e,r)?{detected:!1,severity:"mild",confidence:1}:{detected:!0,severity:qx(r[1]),confidence:1,mode:"legacy_tag"}:{detected:!1,severity:"mild",confidence:1}}function tan(e){if(!e||typeof e!="string")return!1;let t=e.trim();return!!(/^\{[\s\S]*"damageDetected"[\s\S]*\}$/.test(t)||/^<empathy\s+([^>]*)\/?>/i.test(t)||/^\s*\[EMOTIONAL_DAMAGE_DETECTED(?::(mild|moderate|severe))?\]\s*$/i.test(t))}function nan(e){if(!e||typeof e!="object"||Array.isArray(e))return{stopReason:null,thinkingBlocksCount:null};let t=e,n=typeof t.stopReason=="string"?t.stopReason:null,r=null;if(Array.isArray(t.content)){let i=0;for(let o of t.content)if(o&&typeof o=="object"&&!Array.isArray(o)){let a=o.type;(a==="thinking"||a==="redacted_thinking")&&i++}r=i}return{stopReason:n,thinkingBlocksCount:r}}function mJe(e,t){if(!t.workspaceDir||!t.sessionId)return;let n=rt.fromHookContext(t),{config:r}=n,{eventLog:i}=n,o=e.trigger??void 0,a=e.usage,s=t.sessionId??"unknown",c=t.workspaceDir,l=t.sessionKey??"unknown",u=B7e(s,a,r,c,l,o);if(!e.assistantTexts||e.assistantTexts.length===0)return;let p=e.assistantTexts.join(`
2583
- `);try{e4(c??"",p,t.sessionId,t.logger)}catch{}let f=ean(p),m=nan(e.lastAssistant),y=new Date().toISOString();try{n.trajectory?.recordAssistantTurn?.({sessionId:t.sessionId,runId:e.runId??"unknown",provider:e.provider??"unknown",model:e.model??"unknown",rawText:p,sanitizedText:kk(p),usageJson:e.usage||{},empathySignalJson:f,stopReason:m.stopReason,thinkingBlocksCount:m.thinkingBlocksCount,createdAt:y})}catch(ie){t.logger?.warn?.(`[PD:LLM] Failed to persist assistant turn to trajectory: ${String(ie)}`)}let _=tan(p)?"":p,I=pJe.get(n.stateDir).detect(_),E=I.detected&&I.severity||0,R=I.detected?I.ruleId?`llm_${I.ruleId.toLowerCase()}`:`llm_${I.source}`:"",A=I.detected?`Agent triggered pain detection (Source: ${I.source}${I.ruleId?`, Rule: ${I.ruleId}`:""})`:"";if(/^\s*\[EMPATHY_ROLLBACK_REQUEST\]\s*$/m.exec(p)){let ie=i.getLastEmpathyEventId(t.sessionId);if(ie){let Se=i.rollbackEmpathyEvent(ie,t.sessionId,"Natural language rollback request detected","natural_language");Se>0&&sd(t.sessionId,t.workspaceDir,{source:"user_empathy",amount:Se})}}let O=r.get("thresholds.stuck_loops_trigger")||3,$=r.get("thresholds.cognitive_paralysis_input")||4e3,M=r.get("scores.paralysis")||40;u.stuckLoops>=O&&u.totalInputTokens>$&&E<M&&(E=M,R="llm_paralysis",A=`Agent is stuck in low-output loops (${u.stuckLoops} consecutive turns with tiny output but huge context), indicating cognitive paralysis.`);let U=r.get("thresholds.pain_trigger")||30,K=Math.max(r.get("severity_thresholds.high")||70,U+30),ce=!1;if(u.currentGfi>=K&&E<U&&(E=Math.min(u.currentGfi,60),R="user_empathy",ce=!0,A=`Accumulated GFI (${u.currentGfi.toFixed(1)}) crossed highGfi threshold (${K}). Source: empathy keyword friction.`),E>=U){let ie=dr(t.workspaceDir,"painEvidenceAdmission"),Se=dr(t.workspaceDir,"painEvidenceAdmissionDefault"),Ge=ie.enabled&&Se.enabled;i.recordPainSignal(t.sessionId,{score:E,source:R,reason:A,isRisky:!1});let Ie=`llm_${Date.now()}`;if(n.trajectory?.recordPainEvent?.({sessionId:t.sessionId||"unknown",source:R,score:E,reason:A,origin:"system_infer",canonicalPainId:Ie}),Ge){let he={observedAt:new Date().toISOString(),workspaceId:t.workspaceDir,sessionId:t.sessionId,detectionSource:R,isGfiTriggered:ce},ke=nu(he),pe=E_(ke,E);if(pe.decision!=="admit")t.logger?.info?.(`[PD:LLM] Triage ${pe.decision}: ${pe.reason}`);else{let Ne=w_(ke,t.sessionId,R),st=ru({triageResult:pe,isOwnerManual:!1,isCooldownActive:Ne,isValid:!0,score:E,sessionId:t.sessionId});if(st.shouldCreateDiagnosticTask){T_(ke,t.sessionId,R);let bt=Qf(n,t.sessionId||"unknown");Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:Ie,painType:"user_frustration",source:R,reason:`${A}; trigger=${st.outcome}`,score:E,sessionId:t.sessionId||"unknown",agentId:t.agentId,provenance:"host_context_bound",hostKind:"openclaw",evidence:bt}},{recordObservability:!1})}else t.logger?.info?.(`[PD:LLM] Gate B skipped: ${st.reason}`)}}else{let he=Ek({source:R==="llm_paralysis"?"llm_paralysis":"semantic",score:E,currentGfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,sessionId:t.sessionId||"unknown",errorHash:R,thresholds:{painTrigger:U,highSeverity:r.get("severity_thresholds.high")||70,semanticPain:Math.max(U,60)}});if(he.shouldDiagnose){let ke=Qf(n,t.sessionId||"unknown");Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:Ie,painType:"user_frustration",source:R,reason:`${A}; diagnosticGate=${he.reason}`,score:E,sessionId:t.sessionId||"unknown",agentId:t.agentId,provenance:"host_context_bound",hostKind:"openclaw",evidence:ke}},{recordObservability:!1})}else t.logger?.info?.(`[PD:LLM] Pain signal recorded without Runtime V2 diagnosis: ${he.detail}`)}}}var ece=class{queue=[];processing=!1;enqueue(t){this.queue.push(t),this.processing||(this.processing=!0,queueMicrotask(()=>{this.processNext()}))}async processNext(){for(;this.queue.length>0;){let t=this.queue.shift();if(!t)break;try{await t()}catch(n){console.warn("[PD:trajectory-queue] uncaught task error:",n)}}this.processing=!1}},gJe=new ece;function ran(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.type==="text").map(t=>t.text).join(`
2587
+ `);try{e4(c??"",p,t.sessionId,t.logger)}catch{}let f=ean(p),m=nan(e.lastAssistant),y=new Date().toISOString();try{n.trajectory?.recordAssistantTurn?.({sessionId:t.sessionId,runId:e.runId??"unknown",provider:e.provider??"unknown",model:e.model??"unknown",rawText:p,sanitizedText:kk(p),usageJson:e.usage||{},empathySignalJson:f,stopReason:m.stopReason,thinkingBlocksCount:m.thinkingBlocksCount,createdAt:y})}catch(ie){t.logger?.warn?.(`[PD:LLM] Failed to persist assistant turn to trajectory: ${String(ie)}`)}let _=tan(p)?"":p,I=pJe.get(n.stateDir).detect(_),E=I.detected&&I.severity||0,R=I.detected?I.ruleId?`llm_${I.ruleId.toLowerCase()}`:`llm_${I.source}`:"",A=I.detected?`Agent triggered pain detection (Source: ${I.source}${I.ruleId?`, Rule: ${I.ruleId}`:""})`:"";if(/^\s*\[EMPATHY_ROLLBACK_REQUEST\]\s*$/m.exec(p)){let ie=i.getLastEmpathyEventId(t.sessionId);if(ie){let Se=i.rollbackEmpathyEvent(ie,t.sessionId,"Natural language rollback request detected","natural_language");Se>0&&sd(t.sessionId,t.workspaceDir,{source:"user_empathy",amount:Se})}}let O=r.get("thresholds.stuck_loops_trigger")||3,$=r.get("thresholds.cognitive_paralysis_input")||4e3,M=r.get("scores.paralysis")||40;u.stuckLoops>=O&&u.totalInputTokens>$&&E<M&&(E=M,R="llm_paralysis",A=`Agent is stuck in low-output loops (${u.stuckLoops} consecutive turns with tiny output but huge context), indicating cognitive paralysis.`);let U=r.get("thresholds.pain_trigger")||30,K=Math.max(r.get("severity_thresholds.high")||70,U+30),ce=!1;if(u.currentGfi>=K&&E<U&&(E=Math.min(u.currentGfi,60),R="user_empathy",ce=!0,A=`Accumulated GFI (${u.currentGfi.toFixed(1)}) crossed highGfi threshold (${K}). Source: empathy keyword friction.`),E>=U){let ie=dr(t.workspaceDir,"painEvidenceAdmission"),Se=dr(t.workspaceDir,"painEvidenceAdmissionDefault"),Ge=ie.enabled&&Se.enabled;i.recordPainSignal(t.sessionId,{score:E,source:R,reason:A,isRisky:!1});let Ie=`llm_${Date.now()}`;if(n.trajectory?.recordPainEvent?.({sessionId:t.sessionId||"unknown",source:R,score:E,reason:A,origin:"system_infer",canonicalPainId:Ie,hostKind:"openclaw"}),Ge){let he={observedAt:new Date().toISOString(),workspaceId:t.workspaceDir,sessionId:t.sessionId,detectionSource:R,isGfiTriggered:ce},ke=nu(he),pe=E_(ke,E);if(pe.decision!=="admit")t.logger?.info?.(`[PD:LLM] Triage ${pe.decision}: ${pe.reason}`);else{let Ne=w_(ke,t.sessionId,R),st=ru({triageResult:pe,isOwnerManual:!1,isCooldownActive:Ne,isValid:!0,score:E,sessionId:t.sessionId});if(st.shouldCreateDiagnosticTask){T_(ke,t.sessionId,R);let bt=Qf(n,t.sessionId||"unknown");Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:Ie,painType:"user_frustration",source:R,reason:`${A}; trigger=${st.outcome}`,score:E,sessionId:t.sessionId||"unknown",agentId:t.agentId,provenance:"host_context_bound",hostKind:"openclaw",evidence:bt}},{recordObservability:!1})}else t.logger?.info?.(`[PD:LLM] Gate B skipped: ${st.reason}`)}}else{let he=Ek({source:R==="llm_paralysis"?"llm_paralysis":"semantic",score:E,currentGfi:u.currentGfi,consecutiveErrors:u.consecutiveErrors,sessionId:t.sessionId||"unknown",errorHash:R,thresholds:{painTrigger:U,highSeverity:r.get("severity_thresholds.high")||70,semanticPain:Math.max(U,60)}});if(he.shouldDiagnose){let ke=Qf(n,t.sessionId||"unknown");Bs(n,{ts:new Date().toISOString(),type:"pain_detected",data:{painId:Ie,painType:"user_frustration",source:R,reason:`${A}; diagnosticGate=${he.reason}`,score:E,sessionId:t.sessionId||"unknown",agentId:t.agentId,provenance:"host_context_bound",hostKind:"openclaw",evidence:ke}},{recordObservability:!1})}else t.logger?.info?.(`[PD:LLM] Pain signal recorded without Runtime V2 diagnosis: ${he.detail}`)}}}var ece=class{queue=[];processing=!1;enqueue(t){this.queue.push(t),this.processing||(this.processing=!0,queueMicrotask(()=>{this.processNext()}))}async processNext(){for(;this.queue.length>0;){let t=this.queue.shift();if(!t)break;try{await t()}catch(n){console.warn("[PD:trajectory-queue] uncaught task error:",n)}}this.processing=!1}},gJe=new ece;function ran(e){return typeof e=="string"?e:Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.type==="text").map(t=>t.text).join(`
2584
2588
  `):""}function yJe(e,t){let{workspaceDir:n}=t;if(!n)return;let r=e.message;if(!r||!r.role||r.role!=="user"&&r.role!=="assistant")return;let i=MD(t.pluginConfig);if(i.authorized)return;let o=t.logger,a=ran(r.content),s=e.sessionKey??t.sessionId??"unknown",c=new Date().toISOString();if(r.role==="assistant"){try{e4(n,a,s,o)}catch{}gJe.enqueue(async()=>{try{let l=rt.fromHookContext({workspaceDir:n,logger:o}),u=u4(a.slice(0,1e3),n);l.trajectory?.recordAssistantTurn?.({sessionId:s,runId:"before_message_write_fallback",provider:"unknown",model:"unknown",rawText:a,sanitizedText:u,usageJson:{},empathySignalJson:{detected:!1,severity:"mild",confidence:1},createdAt:c})}catch(l){o?.warn?.(`[PD:before_message_write] SQLite fallback write failed: ${String(l)}`)}})}else r.role==="user"&&gJe.enqueue(async()=>{try{rt.fromHookContext({workspaceDir:n,logger:o}).trajectory?.recordUserTurn?.({sessionId:s,turnIndex:0,rawText:a.slice(0,1e3),correctionDetected:!1,createdAt:c})}catch(l){o?.warn?.(`[PD:before_message_write] SQLite user turn fallback failed: ${String(l)}`)}});$e.log(n,"CONVERSATION_HOOK_BLOCKED",JSON.stringify({reason:i.reason,nextAction:i.nextAction,hook:"llm_output",fallback:"before_message_write",role:r.role}))}function _Je(e){let t=Pr(e,"strategy"),n=rt.fromHookContext({workspaceDir:t,...e.config}),r=n.resolve("OKR_DIR").replace(t,"").replace(/^\/+/,""),i=n.resolve("CURRENT_FOCUS").replace(t,"").replace(/^\/+/,""),o=n.resolve("USER_CONTEXT").replace(t,"").replace(/^\/+/,"");return{text:`\u{1F3AF} **Strategy Initialization**
2585
2589
 
2586
2590
  The Agent will now conduct a deep interview to establish your project's vision and strategic OKRs.
@@ -2655,7 +2659,7 @@ Capabilities saved to \`.state/SYSTEM_CAPABILITIES.json\`.`}}catch(r){return{tex
2655
2659
  `,I+=`This is a fresh workspace with no pain signals yet \u2014 that's expected.
2656
2660
 
2657
2661
  `,I+=`**Next steps**:
2658
- `,I+="1. Let your agent work and run `/pd-pain <description>` when it makes a mistake\n",I+="2. Or run the demo: `pd demo first-principle`\n",I+='3. Configure LLM runtime profile: `pd console open --workspace "<path>"`\n\n',I+="Approved principles will appear here once activated."):I+="*\u{1F4A1} Hint: Use `/pd-status empathy` to view detailed empathy event statistics.*",{text:I}}}function lan(e,t,n,r){let i="today";if(t.includes("--week")||t.includes("-w")?i="week":t.includes("--session")||t.includes("-s")?i="session":(t.includes("--today")||t.includes("-t"))&&(i="today"),i==="session"&&!n)return{text:r?"\u274C \u65E0\u6CD5\u83B7\u53D6\u4F1A\u8BDD\u7EDF\u8BA1\uFF0C\u8BF7\u5728\u804A\u5929\u4F1A\u8BDD\u4E2D\u4F7F\u7528\u6B64\u547D\u4EE4\u3002":"\u274C Session not found. Use this command in a chat session."};let o=e.eventLog.getEmpathyStats(i,n),a=r?{today:"\u4ECA\u5929",week:"\u6700\u8FD1 7 \u5929",session:"\u5F53\u524D\u4F1A\u8BDD"}[i]:{today:"Today",week:"Last 7 Days",session:"Current Session"}[i],s=can(o,a,r);return i==="today"&&(s+=r?"\n\n*\u{1F4A1} \u4F7F\u7528 `/pd-status empathy --week` \u67E5\u770B\u5468\u7EDF\u8BA1\uFF0C`--session` \u67E5\u770B\u4F1A\u8BDD\u7EDF\u8BA1\u3002*":"\n\n*\u{1F4A1} Use `/pd-status empathy --week` for weekly stats, `--session` for session stats.*"),{text:s}}async function wJe(e){let t=Pr(e,"pain-report"),n=rt.fromHookContext({workspaceDir:t,...e.config}),i=(e.config?.language||"en")==="zh",{sessionId:o}=e,a=Oi(e.args).trim();if(!a)return{text:i?"\u274C \u8BF7\u63D0\u4F9B pain reason\u3002\u7528\u6CD5: `/pd-pain <\u63CF\u8FF0\u4F60\u9047\u5230\u7684\u95EE\u9898>`":"\u274C Please provide a pain reason. Usage: `/pd-pain <describe the issue you encountered>`"};if(!o||o==="unknown")return{text:i?"\u274C \u65E0\u6CD5\u83B7\u53D6\u5F53\u524D\u4F1A\u8BDD ID\u3002\u8BF7\u5728 OpenClaw \u5BF9\u8BDD\u4F1A\u8BDD\u4E2D\u4F7F\u7528\u6B64\u547D\u4EE4\u3002":"\u274C Session ID not available. Please use this command in an OpenClaw chat session."};let s=`manual_${Date.now()}_${Tk(o).slice(0,8)}`,c={painId:s,painType:"user_frustration",source:"manual",reason:a,score:90,sessionId:o,agentId:"openclaw-host",provenance:"host_context_bound",hostKind:"openclaw"};try{let l=new Eh({stateDir:n.stateDir}),u=oi(n.workspaceDir),f=await new Ny({workspaceDir:n.workspaceDir,stateDir:n.stateDir,ledgerAdapter:l,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:u.effective,getEnvVar:_=>process.env[_],intentDocReader:n4(n.workspaceDir,wk(n.workspaceDir))}).recordPain({painId:c.painId,painType:c.painType,source:c.source,reason:c.reason,score:c.score,sessionId:c.sessionId,agentId:c.agentId,provenance:c.provenance,recordObservability:!0});if(f.status==="succeeded")return n.evolutionReducer.emitSync({ts:new Date().toISOString(),type:"pain_detected",data:c}),{text:i?`\u2705 Pain \u5DF2\u8BB0\u5F55 (context-bound)
2662
+ `,I+="1. Let your agent work and run `/pd-pain <description>` when it makes a mistake\n",I+="2. Or run the demo: `pd demo first-principle`\n",I+='3. Configure LLM runtime profile: `pd console open --workspace "<path>"`\n\n',I+="Approved principles will appear here once activated."):I+="*\u{1F4A1} Hint: Use `/pd-status empathy` to view detailed empathy event statistics.*",{text:I}}}function lan(e,t,n,r){let i="today";if(t.includes("--week")||t.includes("-w")?i="week":t.includes("--session")||t.includes("-s")?i="session":(t.includes("--today")||t.includes("-t"))&&(i="today"),i==="session"&&!n)return{text:r?"\u274C \u65E0\u6CD5\u83B7\u53D6\u4F1A\u8BDD\u7EDF\u8BA1\uFF0C\u8BF7\u5728\u804A\u5929\u4F1A\u8BDD\u4E2D\u4F7F\u7528\u6B64\u547D\u4EE4\u3002":"\u274C Session not found. Use this command in a chat session."};let o=e.eventLog.getEmpathyStats(i,n),a=r?{today:"\u4ECA\u5929",week:"\u6700\u8FD1 7 \u5929",session:"\u5F53\u524D\u4F1A\u8BDD"}[i]:{today:"Today",week:"Last 7 Days",session:"Current Session"}[i],s=can(o,a,r);return i==="today"&&(s+=r?"\n\n*\u{1F4A1} \u4F7F\u7528 `/pd-status empathy --week` \u67E5\u770B\u5468\u7EDF\u8BA1\uFF0C`--session` \u67E5\u770B\u4F1A\u8BDD\u7EDF\u8BA1\u3002*":"\n\n*\u{1F4A1} Use `/pd-status empathy --week` for weekly stats, `--session` for session stats.*"),{text:s}}async function wJe(e){let t=Pr(e,"pain-report"),n=rt.fromHookContext({workspaceDir:t,...e.config}),i=(e.config?.language||"en")==="zh",{sessionId:o}=e,a=Oi(e.args).trim();if(!a)return{text:i?"\u274C \u8BF7\u63D0\u4F9B pain reason\u3002\u7528\u6CD5: `/pd-pain <\u63CF\u8FF0\u4F60\u9047\u5230\u7684\u95EE\u9898>`":"\u274C Please provide a pain reason. Usage: `/pd-pain <describe the issue you encountered>`"};if(!o||o==="unknown")return{text:i?"\u274C \u65E0\u6CD5\u83B7\u53D6\u5F53\u524D\u4F1A\u8BDD ID\u3002\u8BF7\u5728 OpenClaw \u5BF9\u8BDD\u4F1A\u8BDD\u4E2D\u4F7F\u7528\u6B64\u547D\u4EE4\u3002":"\u274C Session ID not available. Please use this command in an OpenClaw chat session."};let s=`manual_${Date.now()}_${Tk(o).slice(0,8)}`,c={painId:s,painType:"user_frustration",source:"manual",reason:a,score:90,sessionId:o,agentId:"openclaw-host",provenance:"host_context_bound",hostKind:"openclaw"};try{let l=new Eh({stateDir:n.stateDir}),u=oi(n.workspaceDir),f=await new Ny({workspaceDir:n.workspaceDir,stateDir:n.stateDir,ledgerAdapter:l,owner:"openclaw-plugin",autoIntakeEnabled:!0,effectiveConfig:u.effective,getEnvVar:_=>process.env[_],intentDocReader:n4(n.workspaceDir,wk(n.workspaceDir))}).recordPain({painId:c.painId,painType:c.painType,source:c.source,reason:c.reason,score:c.score,sessionId:c.sessionId,agentId:c.agentId,provenance:c.provenance,hostKind:c.hostKind,recordObservability:!0});if(f.status==="succeeded")return n.evolutionReducer.emitSync({ts:new Date().toISOString(),type:"pain_detected",data:c}),{text:i?`\u2705 Pain \u5DF2\u8BB0\u5F55 (context-bound)
2659
2663
 
2660
2664
  \u{1F4CB} **Pain ID**: ${s}
2661
2665
  \u{1F4DD} **Reason**: ${a}
@@ -3161,7 +3165,7 @@ ${a.join(`
3161
3165
  `);let i=JSON.parse(t.metadata_json||"{}"),o=Iln(i)?i:{},a=Tln(o,"workspaceDir"),s="--";if(Object.hasOwn(o,"taskInput")&&typeof o.taskInput=="string"){let u=o.taskInput;s=u.substring(0,100)+(u.length>100?"...":"")}let c=n.slice(-10),l=[`Workflow Debug: ${e}`,"============================","","Overview",`- Type: ${t.workflow_type}`,`- Transport: ${t.transport}`,`- State: ${wln(t.state)}`,`- Cleanup: ${t.cleanup_state}`,`- Created: ${Mce(t.created_at)}`,`- Last Observed: ${Mce(t.last_observed_at)}`,"","Sessions",`- Parent: ${t.parent_session_id}`,`- Child: ${t.child_session_key}`,`- Run ID: ${t.run_id??"--"}`,"","Metadata",`- Workspace: ${a}`,`- Task Input: ${s}`,"",`Recent Events (${c.length})`];if(c.length===0)l.push("- (no events)");else for(let u of c){let p=Mce(u.created_at),f=u.from_state?`${u.from_state} \u2192 ${u.to_state}`:`\u2192 ${u.to_state}`;l.push(`- [${p}] ${u.event_type}: ${f} (${u.reason})`)}return l.push(""),l.push(`Workspace: ${r}`),l.join(`
3162
3166
  `)}function KXe(e){let t=Pr(e,"workflow-debug"),n=Oi(e.args).trim(),[r]=n.split(/\s+/);if(!r)return{text:["Workflow Debug","============================","","Usage: /pd-workflow-debug <workflowId>","","Description:","- Display debug summary for a helper workflow","- Shows state, cleanup status, and recent events","","To find workflow IDs, check .state/subagent_workflows.db"].join(`
3163
3167
  `)};try{let i=new D_({workspaceDir:t}),o=i.getWorkflow(r),a=i.getEvents(r);return i.dispose(),{text:Eln(r,o,a,t)}}catch(i){return{text:[`Workflow Debug: ${r}`,"============================","",`\u274C Error: ${String(i)}`,"",`Workspace: ${t}`].join(`
3164
- `)}}}import*as N_ from"fs";import*as Kce from"path";import*as Yn from"fs";import*as eo from"path";import{fileURLToPath as YXe}from"url";function HXe(e){return Sln(e)}function VXe(e,t){WA(e,n=>{n[t.principleId]=t})}function Sln(e){return Bn(e).trainingStore}import*as sN from"fs";import*as P4 from"path";var kln="empathy_keywords.json";function zXe(e,t){let n=P4.join(e,kln),r=P4.dirname(n);sN.existsSync(r)||sN.mkdirSync(r,{recursive:!0}),t.lastUpdated=new Date().toISOString(),Pt(n,JSON.stringify(t,null,2))}var Aln={name:"Principles Disciple Agent",version:"1.0.0"},Rln="pd-core-guidance-v2",JXe=new Set(["AGENTS.md","TOOLS.md"]);function Cln(){return`pd-core-guidance-version: ${Rln}`}function Pln(e,t){return!JXe.has(e)||t.includes(Cln())?!1:!!(t.includes("pd_spawn_agent")||!t.includes("subagents")||!t.includes("sessions_spawn"))}function XXe(e,t,n="en"){try{let r=YXe(import.meta.url),i=eo.dirname(r),o=eo.resolve(i,"..","..","templates","workspace");Yn.existsSync(o)&&(e.logger.info(`[PD] Syncing workspace templates: ${t}...`),$ce(o,t,e));let a=eo.resolve(i,"..","..","templates","langs",n,"core");if(Yn.existsSync(a)||(a=eo.resolve(i,"..","..","templates","langs","zh","core")),Yn.existsSync(a)){e.logger.info(`[PD] Flattening ${n} core templates to workspace root...`);let p=Yn.readdirSync(a);for(let f of p){let m=eo.join(a,f),y=eo.join(t,f);if(!Yn.existsSync(y))Yn.copyFileSync(m,y),e.logger.info(`[PD] Initialized core file: ${f}`);else if(JXe.has(f)){let _=Yn.readFileSync(y,"utf8");Pln(f,_)&&e.logger.warn(`[PD] Outdated core guidance detected in ${f}. Review the latest template guidance for peer sessions, subagents, and sessions_spawn routing.`)}}}let s=eo.resolve(i,"..","..","templates","langs",n,"pain"),c=eo.join(t,zn.PAIN_SAMPLES);Yn.existsSync(s)&&(Yn.existsSync(c)||Yn.mkdirSync(c,{recursive:!0}),$ce(s,c,e));let l=eo.join(t,zn.IDENTITY),u=eo.join(l,"PROFILE.json");Yn.existsSync(u)||(Yn.existsSync(l)||Yn.mkdirSync(l,{recursive:!0}),Pt(u,JSON.stringify(Aln,null,2)),e.logger.info("[PD] Initialized PROFILE.json with identity metadata (contextInjection migrated to .pd/config.yaml)"))}catch(r){e.logger.error(`[PD] Failed to initialize workspace templates: ${String(r)}`)}}function $ce(e,t,n){let r=Yn.readdirSync(e);for(let i of r){let o=eo.join(e,i),a=i==="okr"?eo.join("memory","okr"):i,s=eo.join(t,a);if(Yn.statSync(o).isDirectory())Yn.existsSync(s)||Yn.mkdirSync(s,{recursive:!0}),$ce(o,s,n);else if(!Yn.existsSync(s)){let l=eo.dirname(s);Yn.existsSync(l)||Yn.mkdirSync(l,{recursive:!0}),Yn.copyFileSync(o,s),n.logger.info(`[PD] Copied: ${a}`)}}}var $k=jp.map(e=>({id:e.id,name:e.name,description:e.statement}));function QXe(e,t){try{let n=HXe(e);if(Object.keys(n).filter(a=>a!=="_tree").length>0)return!1;t.info(`[PD] Initializing core thinking models (${$k.length} principles) into training store`);for(let a of $k){let s={principleId:a.id,evaluability:"deterministic",applicableOpportunityCount:0,observedViolationCount:0,complianceRate:0,violationTrend:0,generatedSampleCount:0,approvedSampleCount:0,includedTrainRunIds:[],deployedCheckpointIds:[],internalizationStatus:"needs_training"};VXe(e,s);let c=new Date().toISOString(),l={id:a.id,version:1,text:a.description,coreAxiomId:a.id,triggerPattern:"",action:"",status:"active",priority:"P1",scope:"general",evaluability:"deterministic",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:c,updatedAt:c,suggestedRules:[]};dv(e,l)}let i=$k[0]?.id??"T-01",o=$k[$k.length-1]?.id??"T-10";return t.info(`[PD] Initialized ${$k.length} core thinking models: ${i} through ${o}`),!0}catch(n){return t.error(`[PD] Failed to initialize core principles: ${String(n)}`),!1}}function ZXe(e,t,n="en"){try{let r=YXe(import.meta.url),i=eo.dirname(r);Yn.existsSync(t)||Yn.mkdirSync(t,{recursive:!0});let o=["pain_settings.json"];for(let l of o){let u=eo.resolve(i,"..","..","templates",l),p=eo.join(t,l);!Yn.existsSync(p)&&Yn.existsSync(u)&&(Yn.copyFileSync(u,p),e.logger.info(`[PD] Initialized ${l} in stateDir: ${p}`))}let a=eo.resolve(i,"..","..","templates","langs",n,"pain_dictionary.json");Yn.existsSync(a)||(a=eo.resolve(i,"..","..","templates","langs","en","pain_dictionary.json"));let s=eo.join(t,"pain_dictionary.json");!Yn.existsSync(s)&&Yn.existsSync(a)&&(Yn.copyFileSync(a,s),e.logger.info(`[PD] Initialized pain dictionary in stateDir: ${s} (Lang: ${n})`));let c=eo.join(t,"empathy_keywords.json");if(!Yn.existsSync(c)){let u=nk(n==="zh"||n==="en"?n:"en");zXe(t,u),e.logger.info(`[PD] Initialized empathy keyword store in stateDir: ${c}`)}}catch(r){e.logger.error(`[PD] Failed to initialize state templates: ${String(r)}`)}}import*as r9e from"fs";var e9e="pain_diagnosis",t9e="medium";function n9e(e){return{id:e.id,taskKind:e.taskKind||e9e,priority:e.priority||t9e,source:e.source,traceId:e.traceId,task:e.task,score:e.score,reason:e.reason,timestamp:e.timestamp,enqueued_at:e.enqueued_at,started_at:e.started_at,completed_at:e.completed_at,assigned_session_key:e.assigned_session_key,trigger_text_preview:e.trigger_text_preview,status:e.status||"pending",resolution:e.resolution,session_id:e.session_id,agent_id:e.agent_id,retryCount:e.retryCount||0,maxRetries:e.maxRetries||3,lastError:e.lastError,resultRef:e.resultRef}}function Uce(e){return e&&typeof e=="object"&&!("taskKind"in e)}function O4(e){return e.map(t=>Uce(t)?n9e(t):t)}var Fce=["pain_diagnosis","sleep_reflection","model_eval","keyword_optimization"];function L4(e){let t=[];if(e===null||typeof e!="object"||Array.isArray(e))return["item is not an object"];let n=e;return(!n.id||typeof n.id!="string")&&t.push("missing/invalid id"),(!n.source||typeof n.source!="string")&&t.push("missing/invalid source"),typeof n.score!="number"&&t.push("missing/invalid score"),(!n.status||typeof n.status!="string")&&t.push("missing/invalid status"),!n.taskKind||typeof n.taskKind!="string"?t.push("missing/invalid taskKind"):Fce.includes(n.taskKind)||t.push(`invalid taskKind value '${n.taskKind}' (expected one of: ${Fce.join(", ")})`),typeof n.retryCount!="number"&&t.push("missing/invalid retryCount"),typeof n.maxRetries!="number"&&t.push("missing/invalid maxRetries"),t}var Wce=".lock",i9e=50,o9e=50,a9e=3e4;async function jce(e,t,n,r=Wce){try{return await s9e(e,t,r)}catch(i){throw new kK(e,n,{cause:i})}}async function s9e(e,t,n=Wce){try{let r=await ose(e,{lockSuffix:n,maxRetries:i9e,baseRetryDelayMs:o9e,lockStaleMs:a9e});return()=>IK(r)}catch(r){let i=t?.warn;throw i?.(`[PD:EvolutionWorker] Failed to acquire lock for ${e}: ${String(r)}`),r}}function qce(e){let t=[];try{t=JSON.parse(r9e.readFileSync(e,"utf8"))}catch(r){r.code==="ENOENT"?t=[]:(console.warn(`[queue-io] Failed to load evolution queue (recovering with empty): ${String(r)}`),t=[])}return O4(t).filter(r=>{let i=L4(r);return i.length>0?(console.warn(`[queue-io] Dropping malformed queue item: ${i.join(", ")} | id=${r?.id??"N/A"}`),!1):!0})}function D4(e,t){Pt(e,JSON.stringify(t,null,2))}function c9e(e){let t=String(e);return t.includes("Plugin runtime subagent methods are only available during a gateway request")||t.includes("cannot start workflow for boot session")||t.includes("subagent runtime unavailable")||t.includes("subagent is not available")||t.includes("NocturnalWorkflowManager")&&t.includes("subagent runtime unavailable")||t.includes("gateway is not running")||t.includes("process isolation")||t.includes("subagent")&&t.toLowerCase().includes("connection")&&(t.includes("refused")||t.includes("reset")||t.includes("econnrefused"))}async function l9e(e,t,n,r){let i=r?` (${r})`:"";if(typeof e.patchSessionEntry!="function"||typeof e.getSessionEntry!="function"){n?.warn?.(`[PD:Watchdog] Cannot clean up session ${t}${i}: host does not expose row-scoped session helpers. The stale entry will be swept by OpenClaw's session GC.`);return}if(!e.getSessionEntry({sessionKey:t})){n?.debug?.(`[PD:Watchdog] Session ${t} already absent${i}; nothing to clean.`);return}await e.patchSessionEntry({sessionKey:t,replaceEntry:!0,preserveActivity:!1,update:()=>null}),n?.info?.(`[PD:Watchdog] Cleaned up stale session via row-scoped API${i}: ${t}`)}async function u9e(e,t,n){let r=[],i=Date.now(),o=t?.runtime?.subagent,a=t?.runtime?.agent?.session;try{let s=new D_({workspaceDir:e.workspaceDir});try{let c=s.listWorkflows(),l=3e5*2,u=c.filter(y=>y.state==="active"&&i-y.created_at>l);if(u.length>0)for(let y of u){let _=Math.round((i-y.created_at)/6e4);r.push(`stale_active: ${y.workflow_id} (${y.workflow_type}, ${_}min old)`);let b=s.getEvents(y.workflow_id),I=b[b.length-1],E=I?I.reason:"unknown";if(c9e(E)){n?.debug?.(`[PD:Watchdog] Skipping stale active workflow ${y.workflow_id}: expected subagent error (${E})`);continue}if(s.updateWorkflowState(y.workflow_id,"terminal_error"),s.recordEvent(y.workflow_id,"watchdog_timeout","active","terminal_error",`Stale active > ${l/6e4}s`,{ageMs:i-y.created_at}),y.child_session_key)try{o?(await o.deleteSession({sessionKey:y.child_session_key,deleteTranscript:!0}),n?.info?.(`[PD:Watchdog] Cleaned up stale session: ${y.child_session_key}`)):a&&await l9e(a,y.child_session_key,n)}catch(R){let A=String(R);if(A.includes("gateway request")&&a)try{await l9e(a,y.child_session_key,n,"after gateway error")}catch(P){n?.warn?.(`[PD:Watchdog] Fallback cleanup also failed for ${y.child_session_key}: ${String(P)}`)}else n?.warn?.(`[PD:Watchdog] Failed to cleanup session ${y.child_session_key}: ${A}`)}}let p=c.filter(y=>(y.state==="terminal_error"||y.state==="expired")&&y.cleanup_state==="pending");p.length>0&&r.push(`uncleared_terminal: ${p.length} workflows (will be swept next cycle)`);let f={};for(let y of c)f[y.state]=(f[y.state]||0)+1;let m=Object.entries(f).map(([y,_])=>`${y}=${_}`).join(", ");r.length===0?n?.debug?.(`[PD:Watchdog] OK \u2014 ${c.length} workflows (${m})`):n?.info?.(`[PD:Watchdog] ${r.length} anomalies \u2014 ${c.length} workflows (${m})`)}finally{s.dispose()}}catch(s){return n?.warn?.(`[PD:Watchdog] Failed to scan workflows: ${String(s)}`),{anomalies:-1,details:[],scanError:String(s)}}return{anomalies:r.length,details:r}}var em=null;var Oln=1440*60*1e3;function Lln(e,t){let n=Date.now()-Oln,r={},i=e.filter(s=>{if(s.status!=="failed")return!1;let c=new Date(s.timestamp||s.enqueued_at||0).getTime();if(!Number.isFinite(c)||c>n)return!1;let l=s.lastError||s.resolution||"unknown";return r[l]=(r[l]||0)+1,!0});if(i.length===0)return{purged:0,remaining:e.length,byReason:r};let o=new Set(i.map(s=>s.id));for(let s=e.length-1;s>=0;s--){let c=e[s];c&&o.has(c.id)&&e.splice(s,1)}let a=Object.entries(r).map(([s,c])=>`${c}x ${s}`).join("; ");return t?.info?.(`[PD:EvolutionWorker] Purged ${i.length} stale failed tasks (>24h): ${a}`),{purged:i.length,remaining:e.length,byReason:r}}async function Dln(e,t,n){if(!e.stateDir)return;let r;try{r=Bn(e.stateDir)}catch(c){t?.warn?.(`[PD:EvolutionWorker] CompilationBackfill: failed to load ledger: ${String(c)}`);return}let i=Kce.join(e.stateDir,"COMPILATION_BACKFILL_DONE");if(!N_.existsSync(i)){let c=0;for(let[l,u]of Object.entries(r.tree.principles)){if(u.compilationRetryCount!==void 0||u.evaluability==="manual_only")continue;if(Object.values(r.tree.implementations).some(f=>f.lifecycleState==="active"&&r.tree.rules[f.ruleId]?.principleId===l))try{ns(e.stateDir,l,{compilationRetryCount:void 0})}catch(f){$e.log(e.workspaceDir,"BACKFILL_UPDATE_FAILED",`Failed to mark principle ${l} as done: ${String(f)}`);continue}else try{ns(e.stateDir,l,{compilationRetryCount:0}),c++}catch(f){$e.log(e.workspaceDir,"BACKFILL_UPDATE_FAILED",`Failed to queue principle ${l}: ${String(f)}`);continue}}c>0&&$e.log(e.workspaceDir,"COMPILE_BACKFILL_QUEUED",`Queued ${c} old principles for compilation`);try{Pt(i,new Date().toISOString())}catch(l){$e.log(e.workspaceDir,"BACKFILL_MARKER_WRITE_FAILED",`Failed to write backfill marker: ${String(l)}`)}}let a=Sa.get(e.workspaceDir),s=new ib(e.stateDir,a);r=Bn(e.stateDir);for(let[c,l]of Object.entries(r.tree.principles)){let u=l.compilationRetryCount;if(u!==void 0&&!(u>=5))try{let p=s.compileOne(c);if(p.success)Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:void 0,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_SUCCESS",`Principle ${c} compiled successfully (attempt ${u+1})`);else{let f=u+1;f>=5?(d9e({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,updates:{evaluability:"manual_only",compilationRetryCount:void 0},workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_EXHAUSTED",`Principle ${c} compilation exhausted after 5 attempts: ${p.reason??"unknown"}`)):(Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:f,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_FAILED",`Principle ${c} compile failed: ${p.reason??"unknown"} (attempt ${f}/5)`))}}catch(p){let f=u+1;f>=5?(d9e({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,updates:{evaluability:"manual_only",compilationRetryCount:void 0},workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_EXHAUSTED",`Principle ${c} compilation exhausted after 5 attempts: threw ${String(p)}`)):(Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:f,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_FAILED",`Principle ${c} compile threw: ${String(p)} (attempt ${f}/5)`))}}}function Bce(e){let{stateDir:t,workspaceDir:n,principleId:r,count:i,workerStatus:o}=e;try{ns(t,r,{compilationRetryCount:i})}catch(a){let s=a instanceof Error?a.message:String(a);$e.log(n,"WORKER_RETRY_UPDATE_FAILED",`Failed to update retry count for ${r}: ${s}`),o&&(o.errors.push({at:new Date().toISOString(),kind:"retry_count_update_failed",principleId:r,error:s}),N4(t,o))}}function d9e(e){let{stateDir:t,workspaceDir:n,principleId:r,updates:i,workerStatus:o}=e;try{ns(t,r,i)}catch(a){let s=a instanceof Error?a.message:String(a);$e.log(n,"WORKER_PRINCIPLE_UPDATE_FAILED",`Failed to update principle ${r}: ${s}`),o&&(o.errors.push({at:new Date().toISOString(),kind:"principle_update_failed",principleId:r,error:s}),N4(t,o))}}async function Nln(e,t,n,r){let i=e.resolve("EVOLUTION_QUEUE");if(!N_.existsSync(i)){t?.debug?.("[PD:EvolutionWorker] No evolution queue file \u2014 nothing to process");return}let o=await jce(i,t,"processEvolutionQueue"),a=!1;try{let s=[];try{s=JSON.parse(N_.readFileSync(i,"utf8"))}catch(f){let m=`${i}.corrupted.${Date.now()}`;try{N_.renameSync(i,m),t&&t.error(`[PD:EvolutionWorker] Evolution queue corrupted and backed up to ${m}. All pending tasks have been preserved in the backup file. Parse error: ${String(f)}`),$e.log(e.workspaceDir,"QUEUE_CORRUPTED",`Queue file backed up to ${m}. Error: ${String(f)}`)}catch(y){t&&t.error(`[PD:EvolutionWorker] Failed to backup corrupted queue: ${String(y)}`)}return}let c=O4(s),l=c.length;c=c.filter(f=>f.taskKind!=="pain_diagnosis"),c.length<l&&t?.info?.(`[PD:EvolutionWorker] Dropped ${l-c.length} legacy pain_diagnosis queue item(s); use PainSignalBridge/pd pain record`);let u=c.length;c=c.filter(f=>{let m=L4(f);return m.length>0?(t?.warn?.(`[PD:EvolutionWorker] Skipping malformed queue item: ${m.join(", ")} | ${JSON.stringify(f).slice(0,200)}`),$e.log(e.workspaceDir,"QUEUE_ITEM_MALFORMED",`Skipped: ${m.join(", ")} | id=${f.id||"N/A"}`),!1):!0}),c.length<u&&t?.info?.(`[PD:EvolutionWorker] Filtered ${u-c.length} malformed queue item(s)`),(s.some(Uce)||c.length<l||c.length<u)&&D4(i,c)}catch(s){t&&t.warn(`[PD:EvolutionWorker] Error processing evolution queue: ${String(s)}`)}finally{a||o()}}function N4(e,t){try{let n=Kce.join(e,"worker-status.json");Pt(n,JSON.stringify(t,null,2))}catch(n){}}async function p9e(e,t,n,r){let i={total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},o=[];try{let a=e.resolve("EVOLUTION_QUEUE");if(!N_.existsSync(a))return{queue:i,errors:o};let s=qce(a),c=Lln(s,t);c.purged>0&&D4(a,s),i.total=s.length,i.pending=s.filter(l=>l.status==="pending").length,i.in_progress=s.filter(l=>l.status==="in_progress").length,i.failed_this_cycle=s.filter(l=>l.status==="failed").length,i.completed_this_cycle=s.filter(l=>l.status==="completed").length,t.info(`[PD:EvolutionWorker] Queue snapshot: total=${i.total} pending=${i.pending} in_progress=${i.in_progress} completed=${i.completed_this_cycle} failed=${i.failed_this_cycle} purged=${c.purged}`),await Nln(e,t,n,r)}catch(a){let s=`processEvolutionQueue failed: ${String(a)}`;o.push(s),t.error(`[PD:EvolutionWorker] ${s}`)}return{queue:i,errors:o}}var M4={id:"principles-evolution-worker",api:null,_startedWorkspaces:new Set,start(e){let t=e?.workspaceDir,n=e?.logger||console,{api:r}=this;if(!t){n&&n.warn("[PD:EvolutionWorker] workspaceDir not found in service config. Evolution cycle disabled.");return}let i=M4._startedWorkspaces;if(i.has(t)){e?.logger?.info?.(`[PD:EvolutionWorker] Already started for ${t}, skipping`);return}i.add(t);let o=rt.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:EvolutionWorker] Starting with workspaceDir=${o.workspaceDir}, stateDir=${o.stateDir}`),q7e(o.stateDir);let{eventLog:a}=o,{config:s}=o,c=s.get("language")||"en";ZXe({logger:n},o.stateDir,c),QXe(o.stateDir,n);let l=5e3,u=s.get("intervals.worker_poll_ms")||900*1e3,p=0;async function f(){let m=Date.now();p++;let y=r?.runtime?.subagent;n?.info?.(`[PD:DEBUG:SubagentCheck:Heartbeat] api_exists=${!!r}, subagent_exists=${!!y}, subagent.run_exists=${!!y?.run}, heartbeatCounter=${p}`),y?.run&&n?.info?.("[PD:DEBUG:SubagentCheck:Heartbeat] run entrypoint is callable");let _={timestamp:new Date().toISOString(),cycle_start_ms:m,duration_ms:0,pain_flag:{exists:!1,score:null,source:null,enqueued:!1,skipped_reason:null},queue:{total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},errors:[]};try{Dln(o,n,_).catch(I=>{n?.error?.(`[PD:EvolutionWorker] CompilationBackfill threw: ${String(I)}`)}),n?.info?.(`[PD:EvolutionWorker] HEARTBEAT cycle=${new Date().toISOString()}`);let b=await p9e(o,n,a,r??void 0);_.queue=b.queue,b.errors&&_.errors.push(...b.errors);try{let I=r?.runtime?.subagent,E=new D_({workspaceDir:o.workspaceDir});try{let R=E.getExpiredWorkflows(3e5);for(let A of R){if(I&&A.child_session_key)try{await I.deleteSession({sessionKey:A.child_session_key,deleteTranscript:!0}),E.updateCleanupState(A.workflow_id,"completed"),n?.info?.(`[PD:EvolutionWorker] Cleaned up session ${A.child_session_key} for expired workflow ${A.workflow_id}`)}catch(P){let O=`Session cleanup failed for workflow ${A.workflow_id} (child_session=${A.child_session_key}): ${String(P)}`;E.updateCleanupState(A.workflow_id,"failed"),_.errors.push(O),n?.warn?.(`[PD:EvolutionWorker] ${O}`)}else if(A.child_session_key){let P=`Session cleanup unavailable for workflow ${A.workflow_id} (child_session=${A.child_session_key}): subagentRuntime not in gateway context`;E.updateCleanupState(A.workflow_id,"failed"),_.errors.push(P),n?.warn?.(`[PD:EvolutionWorker] ${P}`)}E.updateWorkflowState(A.workflow_id,"expired"),E.recordEvent(A.workflow_id,"swept",A.state,"expired","TTL expired",{}),n?.warn?.(`[PD:EvolutionWorker] Marked workflow ${A.workflow_id} as expired`)}}finally{E.dispose()}}catch(I){let E=`Failed to sweep expired workflows: ${String(I)}`;_.errors.push(E),n?.warn?.(`[PD:EvolutionWorker] ${E}`)}try{let I=await u9e(o,r,n);I.anomalies>0&&(n?.warn?.(`[PD:Watchdog] ${I.anomalies} anomalies: ${I.details.join("; ")}`),_.errors.push(...I.details))}catch(I){n?.warn?.(`[PD:Watchdog] Watchdog failed: ${String(I)}`)}o.dictionary.flush(),xse(),_.duration_ms=Date.now()-m,N4(o.stateDir,_)}catch(b){let I=`Error in worker interval: ${String(b)}`;n&&n.error(`[PD:EvolutionWorker] ${I}`),N4(o.stateDir,{timestamp:new Date().toISOString(),cycle_start_ms:m,duration_ms:Date.now()-m,pain_flag:{exists:!1,score:null,source:null,enqueued:!1,skipped_reason:null},queue:{total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},errors:[I]})}em=setTimeout(f,u),em.unref()}em=setTimeout(()=>{(async()=>{let m=await p9e(o,n,a,r??void 0);m.errors.length>0&&m.errors.forEach(y=>n?.error?.(`[PD:EvolutionWorker] Startup cycle error: ${y}`)),em=setTimeout(f,u),em.unref()})().catch(m=>{n&&n.error(`[PD:EvolutionWorker] Startup worker cycle failed: ${String(m)}`),em=setTimeout(f,u),em.unref()})},l),em.unref()},stop(e){e?.logger&&e.logger.info("[PD:EvolutionWorker] Stopping background service..."),em&&clearTimeout(em),xse()}};import*as Uk from"fs";import*as Vce from"path";var h9e="correction_keywords.json",f9e=.1,Mln=.9,xb=null;function $ln(){let e=new Date().toISOString();return{keywords:XS.map(n=>({...n,source:"seed",addedAt:e})),version:1,lastOptimizedAt:e}}function Fln(e){if(xb)return xb;let t=Vce.join(e,h9e);if(Uk.existsSync(t))try{let r=Uk.readFileSync(t,"utf-8");return xb=JSON.parse(r),xb}catch{}let n=$ln();return g9e(e,n),xb=n,xb}function g9e(e,t){let n=Vce.join(e,h9e);Uk.mkdirSync(e,{recursive:!0}),Pt(n,JSON.stringify(t,null,2)),xb=null}var Hce=null,m9e=null;var Fk=class e{store;stateDir;constructor(t){this.stateDir=t,this.store=Fln(t)}match(t){let n=t.trim().toLowerCase().replace(/[.,!?;:,。!?;:]/g,""),r=[],i=0;for(let u of this.store.keywords)if(n.includes(u.term.toLowerCase())){let p=u.truePositiveCount??0,f=u.falsePositiveCount??0,m=p+f>0?p/(p+f):1,y=u.weight*m;i+=y,r.push(u.term)}let o=Math.min(1,i),a=r.length>0,s=Math.min(1,r.length/3),c=Math.min(1,o/.8),l=Math.max(s,c);return{matched:a,matchedTerms:r.slice(0,5),score:o,confidence:l}}recordHits(t){for(let n of t){let r=this.store.keywords.findIndex(o=>o.term.toLowerCase()===n.toLowerCase());if(r<0)continue;let i=this.store.keywords[r];i&&(this.store.keywords[r]={...i,hitCount:(i.hitCount??0)+1,lastHitAt:new Date().toISOString()})}}recordTruePositive(t){let n=this.store.keywords.find(i=>i.term.toLowerCase()===t.toLowerCase());if(!n)return;n.truePositiveCount=(n.truePositiveCount??0)+1;let r=this.store.keywords.findIndex(i=>i.term.toLowerCase()===t.toLowerCase());r>=0&&(this.store.keywords[r]={...n}),this.flush()}recordFalsePositive(t){let n=this.store.keywords.find(i=>i.term.toLowerCase()===t.toLowerCase());if(!n)return;n.falsePositiveCount=(n.falsePositiveCount??0)+1,n.weight=Math.max(f9e,n.weight*.8),n.lastHitAt=new Date().toISOString();let r=this.store.keywords.findIndex(i=>i.term.toLowerCase()===t.toLowerCase());r>=0&&(this.store.keywords[r]={...n}),this.flush()}add(t){if(this.store.keywords.length>=L3)throw new Error("Correction keyword store limit reached (200 terms)");let n={...t,addedAt:new Date().toISOString()};this.store.keywords.push(n),this.flush()}updateWeight(t,n){let r=this.store.keywords.find(o=>o.term.toLowerCase()===t.toLowerCase());if(!r)throw new Error(`Keyword not found: ${t}`);r.weight=Math.max(f9e,Math.min(Mln,n));let i=this.store.keywords.findIndex(o=>o.term.toLowerCase()===t.toLowerCase());i>=0&&(this.store.keywords[i]={...r}),this.flush()}remove(t){let n=this.store.keywords.findIndex(r=>r.term.toLowerCase()===t.toLowerCase());if(n<0)throw new Error(`Keyword not found: ${t}`);this.store.keywords.splice(n,1),this.flush()}getStore(){return this.store}getLastOptimizedAt(){return this.store.lastOptimizedAt}flush(){g9e(this.stateDir,this.store)}static get(t){return(!Hce||m9e!==t)&&(Hce=new e(t),m9e=t),Hce}};var $4=class e{stateDir;workspaceDir;logger;constructor(t,n,r){this.stateDir=t,this.workspaceDir=n,this.logger=r}applyResult(t){let n=Fk.get(this.stateDir),r=t.updates??{};if(!t.updated||Object.keys(r).length===0){this.logger?.info?.("[KeywordOptimizationService] No updates to apply");return}for(let[i,o]of Object.entries(r))try{switch(o.action){case"add":{let a=i.trim().toLowerCase(),s=n.getStore().keywords.find(l=>l.term.toLowerCase()===a);if(s){this.logger?.info?.(`[KeywordOptimizationService] ADD skipped: "${i}" already exists as "${s.term}"`);break}let c=o.weight!==void 0?Math.max(.1,Math.min(.9,o.weight)):.5;n.add({term:a,weight:c,source:"llm"}),this.logger?.info?.(`[KeywordOptimizationService] ADD term="${a}" weight=${c}`);break}case"update":{o.weight!==void 0&&(n.updateWeight(i,o.weight),this.logger?.info?.(`[KeywordOptimizationService] UPDATE term="${i}" weight=${o.weight}`));break}case"remove":{n.remove(i),this.logger?.info?.(`[KeywordOptimizationService] REMOVE term="${i}"`);break}}}catch(a){this.logger?.warn?.(`[KeywordOptimizationService] ${o.action.toUpperCase()} failed for term="${i}": ${String(a)}`)}if(t.fpAnalysisStatus==="completed"&&t.fpTerms&&t.fpTerms.length>0){let o=[...new Set(t.fpTerms.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0))].slice(0,20);for(let a of o)try{n.recordFalsePositive(a),this.logger?.info?.(`[KeywordOptimizationService] FP recorded for term="${a}" (weight x0.8)`)}catch(s){this.logger?.warn?.(`[KeywordOptimizationService] recordFalsePositive failed for term="${a}": ${String(s)}`)}}}async buildTrajectoryHistory(t){let n=[],r=Sa.get(this.workspaceDir);for(let i of t.slice(0,10)){try{let o=r.listUserTurnsForSession(i);for(let a of o)if(a.correctionDetected&&n.push({sessionId:i,timestamp:a.createdAt??new Date().toISOString(),term:a.correctionCue??"unknown",userMessage:""}),n.length>=50)break}catch(o){this.logger?.warn?.(`[KeywordOptimizationService] Failed to read trajectory for session ${i}: ${String(o)}`)}if(n.length>=50)break}return n}static _instances=new Map;static get(t,n,r){let i=`${t}::${n}`;return e._instances.has(i)||e._instances.set(i,new e(t,n,r)),e._instances.get(i)}static reset(){e._instances.clear()}};var Bh=null,cN=!1,zce=new Set,Uln=900*1e3,Wln=1e4,jln=20,qln=5;function Gln(e,t){try{let n=LD(e.workspaceDir,"correction_observer","correctionObserver",t);if(!n.enabled)return n.readiness==="config_malformed"?t?.warn?.(`[PD:CorrectionObserver] Config malformed: ${n.reason}. ${n.nextAction}`):t?.debug?.(`[PD:CorrectionObserver] ${n.reason}`),null;if(n.readiness==="needs_setup")return t?.info?.(`[PD:CorrectionObserver] ${n.reason}. ${n.nextAction}`),null;if(n.runtimeProfileType==="pi-ai"){let r=new Xl({provider:n.provider??"anthropic",model:n.model??"anthropic/claude-3-5-sonnet",apiKeyEnv:n.apiKeyEnv??"ANTHROPIC_API_KEY",timeoutMs:n.timeoutMs??void 0,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return new gR({runtimeAdapter:r},{timeoutMs:n.timeoutMs??void 0})}return t?.info?.("[PD:CorrectionObserver] OpenClaw runtime profile not yet supported for correction observer. Skipping."),null}catch(n){return t?.warn?.(`[PD:CorrectionObserver] Failed to resolve CorrectionObserver: ${String(n)}`),null}}async function Bln(e,t){try{let n=Gln(e,t);if(!n){t?.debug?.("[PD:CorrectionObserver] Observer not resolved. Skipping cycle.");return}t?.info?.("[PD:CorrectionObserver] Observer resolved. Initiating periodic optimization...");let r=Sa.get(e.workspaceDir),o=r.listRecentSessions({limit:jln}).map(_=>_.sessionId);if(o.length===0){t?.info?.("[PD:CorrectionObserver] No recent sessions found. Skipping correction optimization.");return}let a=[];for(let _ of o.slice(0,qln))try{let b=r.listUserTurnsForSession(_);for(let I of b)I.rawExcerpt&&a.push(I.rawExcerpt)}catch(b){t?.warn?.(`[PD:CorrectionObserver] Failed to load user turns for session ${_}: ${String(b)}`)}let c=Fk.get(e.stateDir).getStore().keywords,l={totalKeywords:c.length,terms:c.map(_=>({term:_.term,weight:_.weight,hitCount:_.hitCount??0,truePositiveCount:_.truePositiveCount??0,falsePositiveCount:_.falsePositiveCount??0}))},u=$4.get(e.stateDir,e.workspaceDir,t),p=await u.buildTrajectoryHistory(o),f={parentSessionId:"correction-observer-service",workspaceDir:e.workspaceDir,keywordStoreSummary:l,recentMessages:a,trajectoryHistory:p},m=new aD;m.register({agentId:"correction-observer",mode:"realtime",runner:n}),t?.info?.(`[PD:CorrectionObserver] Dispatching with ${p.length} trajectory events, ${a.length} recent messages.`);let y=await m.dispatch("correction-observer",f);t?.info?.(`[PD:CorrectionObserver] Completed: updated=${y.updated}, summary="${y.summary}"`),y.updated&&u.applyResult(y)}catch(n){let r=`Correction observer cycle failed: ${String(n)}`;t?.warn?.(`[PD:CorrectionObserver] ${r}`),$e.log(e.workspaceDir,"CORRECTION_OBSERVER_CYCLE_FAILED",r)}}var Yce={id:"principles-correction-observer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n&&n.warn("[PD:CorrectionObserver] workspaceDir not found in service config. Correction observer disabled.");return}if(zce.has(t)){n&&n.info(`[PD:CorrectionObserver] Already started for workspace: ${t}. Skipping duplicate start.`);return}let r=LD(t,"correction_observer","correctionObserver",n);if(!r.enabled){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}if(r.readiness==="needs_setup"){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}zce.add(t),cN=!1;let i=rt.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:CorrectionObserver] Starting with workspaceDir=${i.workspaceDir}, stateDir=${i.stateDir}`);let o=Uln;async function a(){cN||(await Bln(i,n),!cN&&(Bh=setTimeout(a,o),Bh.unref()))}Bh=setTimeout(()=>{a().catch(s=>{n&&n.error(`[PD:CorrectionObserver] Startup cycle failed: ${String(s)}`),!cN&&(Bh=setTimeout(a,o),Bh.unref())})},Wln),Bh.unref()},stop(e){cN=!0,zce.clear(),Bh&&clearTimeout(Bh),Bh=null}};var Kln=12e4,Jce=3e4,Wk=new Map;function Hln(e){let t=Wk.get(e);return t||(t={stopped:!1,timeoutId:null},Wk.set(e,t)),t}function Vln(e){return`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`}async function zln(e,t){await E8e(e,{owner:"auto-consumer",logLabel:"AutoConsumer",logger:t,emitEvent:(n,r)=>$e.log(e,n,r),hostToolCatalog:{readOnlyTools:a4,writeTools:[...Sk,...Pse,...s4]}})}var Xce={id:"principles-internalization-auto-consumer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n.warn("[PD:AutoConsumer] No workspace directory, not starting.");return}let r=t,i=Hln(r);if(!i.stopped&&i.timeoutId!==null){n.info(`[PD:AutoConsumer] Already started for workspace: ${r}`);return}let o=dr(r,Yae,{info:l=>n.info(l),warn:l=>n.warn(l)});if(!o.enabled){let l=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:Vln(r),flagSource:o.source});$e.log(r,"INTERNALIZATION_CONSUMER_DISABLED",l),n.info(`[PD:AutoConsumer] NOT started for workspace: ${r}. Disabled (source: ${o.source}).`);return}i.stopped=!1;let a=Kln;function s(){i.stopped||(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())}async function c(){i.stopped||(await zln(r,n),s())}i.timeoutId=setTimeout(()=>{c().catch(l=>{n.error(`[PD:AutoConsumer] Startup cycle failed: ${String(l)}`),!i.stopped&&(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())})},Jce),i.timeoutId?.unref(),$e.log(r,"INTERNALIZATION_CONSUMER_STARTED",JSON.stringify({intervalMs:a,initialDelayMs:Jce})),n.info(`[PD:AutoConsumer] Started for workspace: ${r} (interval: ${a}ms, initial delay: ${Jce}ms)`)},stop(e){let t=e?.workspaceDir;if(t){let n=Wk.get(t);n&&(n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null),Wk.delete(t)}else{for(let[,n]of Wk)n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null;Wk.clear()}}};var y9e={id:"principles-disciple-trajectory",start(e){e.workspaceDir&&rt.fromHookContext(e).trajectory},stop(e){e.workspaceDir&&Sa.dispose(e.workspaceDir)}};import*as U4 from"fs";import*as T9e from"path";import*as E9e from"os";var _9e=[];import*as bb from"fs";import*as Qce from"path";var v9e="pd_tasks.json";function x9e(e){return Qce.join(e,".state",v9e)}function Yln(e){let t=Qce.join(e,".state");bb.existsSync(t)||bb.mkdirSync(t,{recursive:!0})}function b9e(e){let t=x9e(e);if(!bb.existsSync(t))return[];try{let n=bb.readFileSync(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch(n){return console.warn(`[PD:TaskStore] Failed to parse ${v9e}: ${String(n)}`),[]}}async function I9e(e,t){let n=x9e(e);Yln(e),await wK(n,async()=>{Pt(n,JSON.stringify(t,null,2))})}var F4=T9e.join(E9e.homedir(),".openclaw","cron","jobs.json");function Jln(e){if(!U4.existsSync(F4))return e?.info?.("[PD:Reconciler] cron/jobs.json not found, starting with empty store"),{version:1,jobs:[]};try{let t=U4.readFileSync(F4,"utf-8"),n=JSON.parse(t);return e?.info?.(`[PD:Reconciler] Loaded cron/jobs.json: ${n.jobs.length} jobs`),n}catch(t){return e?.warn?.(`[PD:Reconciler] Failed to parse cron/jobs.json: ${String(t)}`),{version:1,jobs:[]}}}async function Xln(e){await wK(F4,async()=>{Pt(F4,JSON.stringify(e,null,2))})}function Qln(e,t){let n=[],r=new Map;for(let i of t)r.set(i.name,i);for(let i of e){let o=r.get(i.name);if(!o)i.enabled&&n.push({type:"CREATE",task:i});else{let a=o.metadata?.pdVersion;i.enabled?!a||a!==i.version?n.push({type:"UPDATE",task:i,job:o}):n.push({type:"SKIP",task:i,job:o}):n.push({type:"DISABLE",task:i,job:o})}}for(let i of t){if(!i.name.startsWith("PD "))continue;e.find(a=>a.name===i.name)||n.push({type:"ORPHAN",job:i})}return n}function w9e(e,t,n,r){return r?.info?.(`[PD:Reconciler] Building cron job: ${e.name} (id=${e.id}, interval=${e.schedule.everyMs}ms)`),{id:`pd-${e.id}-${t}`,name:e.name,agentId:e.agentId||"main",description:e.description,enabled:e.enabled,schedule:{kind:"every",everyMs:e.schedule.everyMs},sessionTarget:"isolated",wakeMode:"now",payload:{kind:"agentTurn",message:Zln(e,n,r),lightContext:e.execution.lightContext??!0,timeoutSeconds:e.execution.timeoutSeconds??120,toolsAllow:e.execution.toolsAllow},delivery:{mode:e.delivery.mode},createdAtMs:t,updatedAtMs:t,state:{nextRunAtMs:t+e.schedule.everyMs},metadata:{pdVersion:e.version,pdTaskId:e.id}}}function Zln(e,t,n){return e.description}async function S9e(e,t){let n=t?.dryRun??!1,r=t?.logger??console,i=Date.now(),o={created:[],updated:[],skipped:[],orphaned:[],errors:[]},a=b9e(e),s=new Map(a.map(f=>[f.id,f])),c=_9e.map(f=>{let m=s.get(f.id);return m?{...f,meta:{...f.meta,...m.meta}}:{...f,meta:{createdAtMs:i}}}),l=await Jln(r),u=eun(c,l,r),p=Qln(u,l.jobs);for(let f of p)switch(f.type){case"CREATE":if(f.task){if(!n){let m=w9e(f.task,i,e,r);l.jobs.push(m),r.info?.(`[PD:Reconciler] Created job: ${f.task.name}`)}o.created.push(f.task.name)}break;case"UPDATE":if(f.task&&f.job){if(!n){let m=l.jobs.indexOf(f.job),y=w9e(f.task,i,e,r);y.id=f.job.id,y.state={...f.job.state,nextRunAtMs:void 0},l.jobs[m]=y,r.info?.(`[PD:Reconciler] Updated job: ${f.task.name}`)}o.updated.push(f.task.name)}break;case"DISABLE":if(f.job){if(!n){let m=l.jobs.indexOf(f.job);m>=0&&(l.jobs[m]={...f.job,enabled:!1,updatedAtMs:i})}r.warn?.(`[PD:Reconciler] Disabled job: ${f.job.name}`)}break;case"ORPHAN":f.job&&(r.warn?.(`[PD:Reconciler] Orphaned job (no declaration): ${f.job.name}`),o.orphaned.push(f.job.name));break;case"SKIP":f.task&&o.skipped.push(f.task.name);break}if(!n&&(o.created.length>0||o.updated.length>0)){await Xln(l),r.info?.(`[PD:Reconciler] Wrote cron/jobs.json: ${l.jobs.length} total jobs`);for(let f of l.jobs)f.name.startsWith("PD ")&&r.info?.(`[PD:Reconciler] PD job: name=${f.name}, enabled=${f.enabled}, schedule=${JSON.stringify(f.schedule)}, nextRun=${f.state.nextRunAtMs?new Date(f.state.nextRunAtMs).toISOString():"TBD"}`)}return!n&&c.length>0&&await I9e(e,c),o}function eun(e,t,n){let r=new Map(t.jobs.map(i=>[i.name,i]));return e.map(i=>{let o=r.get(i.name);if(!o)return i;let a=o.state.consecutiveErrors??0,s=o.state.lastError??"",c=s.includes("timed out")||s.includes("timeout");if(c&&a>0&&o.payload.kind==="agentTurn"){let u=o.payload.timeoutSeconds??120,p=Math.min(1800,u*2);p>u&&(o.payload.timeoutSeconds=p,o.state.consecutiveErrors=0,o.state.lastError=void 0,n.info?.(`[PD:Reconciler] Auto-increased timeout for '${i.name}': ${u}s \u2192 ${p}s (was ${a} consecutive timeouts)`))}let l=a>=3&&!c&&!i.meta?.autoDisabled;return a===0&&i.meta?.autoDisabled&&n.info?.(`[PD:Reconciler] Task '${i.id}' was previously auto-disabled but has 0 consecutive errors now`),l||i.meta||o.state.lastRunAtMs?{...i,meta:{...i.meta,...l?{autoDisabled:!0,autoDisabledAt:Date.now(),autoDisabledReason:`consecutiveErrors=${a}`}:{},...i.meta?{consecutiveFailCount:a}:{},...o.state.lastRunAtMs?{lastFailedAtMs:o.state.lastRunAtMs}:{}}}:i})}var k9e={id:"principles-disciple-task-manager",async start(e){let{workspaceDir:t}=e,n=e.logger??e.api?.logger;if(!t){n?.warn?.("[PD:TaskManager] No workspaceDir, skipping PD task reconciliation");return}n?.info?.("[PD:TaskManager] Starting PD task reconciliation...");try{let r=await S9e(t,{logger:n??console});n?.info?.(`[PD:TaskManager] Reconcile complete: +${r.created.length} ~${r.updated.length} =${r.skipped.length} orphan=${r.orphaned.length}`),r.created.length>0&&n?.info?.(`[PD:TaskManager] Created jobs: ${r.created.join(", ")}`),r.updated.length>0&&n?.info?.(`[PD:TaskManager] Updated jobs: ${r.updated.join(", ")}`),r.errors.length>0&&n?.warn?.(`[PD:TaskManager] Reconcile errors: ${r.errors.map(i=>i.message).join(", ")}`)}catch(r){n?.warn?.(`[PD:TaskManager] Reconcile failed: ${String(r)}`)}},stop(e){}};import*as ys from"fs";import*as ko from"path";function A9e(e,t){try{let n=ko.join(t,"docs"),r=ko.join(t,"memory",".state"),i=[{legacy:ko.join(n,"PRINCIPLES.md"),newKey:"PRINCIPLES"},{legacy:ko.join(n,"THINKING_OS.md"),newKey:"THINKING_OS"},{legacy:ko.join(n,"DECISION_POLICY.json"),newKey:"DECISION_POLICY"},{legacy:ko.join(n,"evolution_queue.json"),newKey:"EVOLUTION_QUEUE"},{legacy:ko.join(n,".pain_flag"),newKey:"PAIN_FLAG"},{legacy:ko.join(n,"SYSTEM_CAPABILITIES.json"),newKey:"SYSTEM_CAPABILITIES"},{legacy:ko.join(n,"SYSTEM.log"),newKey:"SYSTEM_LOG"},{legacy:ko.join(r,"pain_dictionary.json"),newKey:"DICTIONARY"},{legacy:ko.join(r,"pain_settings.json"),newKey:"PAIN_SETTINGS"},{legacy:ko.join(r,"pain_candidates.json"),newKey:"PAIN_CANDIDATES"},{legacy:ko.join(r,"evolution_directive.json"),newKey:"EVOLUTION_DIRECTIVE"},{legacy:ko.join(r,"sessions"),newKey:"SESSION_DIR"},{legacy:ko.join(r,"logs","events.jsonl"),newKey:"SYSTEM_LOG"}],o=0;for(let a of i)if(ys.existsSync(a.legacy)){let s=Pi(t,a.newKey),c=ko.dirname(s);if(ys.existsSync(c)||ys.mkdirSync(c,{recursive:!0}),ys.existsSync(s))e.logger?.warn?.(`[PD:Migration] Skipping ${ko.basename(a.legacy)}: already exists at destination.`);else try{ys.renameSync(a.legacy,s),e.logger.info(`[PD:Migration] Migrated ${ko.basename(a.legacy)} to ${s.replace(t,"")}`),o++}catch(l){e.logger.error(`[PD:Migration] Failed to rename ${a.legacy}: ${String(l)}`)}}if(o>0&&e.logger.info(`[PD:Migration] Successfully migrated ${o} files/folders to new architecture.`),ys.existsSync(r))try{let a=ys.readdirSync(r);if(a.length===0||a.length===1&&a[0]==="logs"){let s=ko.join(r,"logs");ys.existsSync(s)&&ys.readdirSync(s).length===0&&ys.rmdirSync(s),ys.readdirSync(r).length===0&&(ys.rmdirSync(r),e.logger.info("[PD:Migration] Cleaned up empty legacy state directory."))}}catch(a){e.logger.debug?.(`[PD:Migration] Failed to cleanup legacy state dir: ${String(a)}`)}}catch(n){e.logger.error(`[PD:Migration] Directory refactor migration failed: ${String(n)}`)}}import*as ld from"fs";import*as M_ from"path";var tun=["AGENTS.md","MEMORY.md"],nun=["THINKING_OS.md"],R9e=M_.join(".principles","skills"),run=".principles",C9e=".pre-pri286.bak";function iun(e){try{let t=ld.readFileSync(e,"utf-8");return typeof t!="string"?null:t}catch{return null}}function oun(e,t){let n=e+C9e;try{return ld.writeFileSync(n,t,"utf-8"),!0}catch{return!1}}function aun(e){let t=M_.join(e,R9e);if(!ld.existsSync(t))return{files:[]};try{let n=ld.readdirSync(t,{withFileTypes:!0}),r=[];for(let i of n)if(i.isDirectory()){let o=M_.join(t,i.name,"SKILL.md");ld.existsSync(o)&&r.push(o)}return{files:r}}catch(n){let r=n instanceof Error?n.message:String(n);return{files:[],error:{file:R9e,error:`Failed to enumerate skills directory: ${r}`}}}}function sun(e,t){let n=[];for(let i of tun)n.push(M_.join(e,i));for(let i of nun)n.push(M_.join(e,run,i));let r=aun(e);return r.error&&t.errors.push(r.error),n.push(...r.files),n}function P9e(e,t){let n={migratedFiles:[],skippedFiles:[],errors:[]},r=sun(t,n);for(let i of r){let o=M_.relative(t,i);if(!ld.existsSync(i))continue;let a=iun(i);if(a===null){n.errors.push({file:o,error:"Failed to read file content"});continue}if(!Zte(a,o)){n.skippedFiles.push(o);continue}let s=Qte(a,o);if(!s.changed){n.skippedFiles.push(o);continue}let c=s.migrated;if(!oun(i,a)){n.errors.push({file:o,error:"Failed to create backup file before migration"});continue}try{ld.writeFileSync(i,c,"utf-8"),n.migratedFiles.push(o),e.logger.info(`[PD:GuidanceMigration] Migrated ${o} (backup at ${o}${C9e})`)}catch(u){let p=u instanceof Error?u.message:String(u);n.errors.push({file:o,error:`Failed to write migrated content: ${p}`});try{ld.writeFileSync(i,a,"utf-8")}catch{e.logger.error(`[PD:GuidanceMigration] CRITICAL: Failed to restore original content for ${o} after write failure`)}}}return n.migratedFiles.length>0&&e.logger.info(`[PD:GuidanceMigration] Migration complete: ${n.migratedFiles.length} migrated, ${n.skippedFiles.length} skipped, ${n.errors.length} errors`),n}function cun(e,t,n){return{workspaceDir:e,sessionId:t??"openclaw:session-unavailable",toolName:n}}function O9e(e){let t=new WeakMap,n=new WeakMap;function r(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error(`OpenClaw ${s.kind} dispatch is missing its native payload token`);let c=Object.hasOwn(s.rawPayload,"nativeToken")?Reflect.get(s.rawPayload,"nativeToken"):s.rawPayload;if(typeof c!="object"||c===null)throw new Error(`OpenClaw ${s.kind} dispatch has an invalid native payload token`);let l=t.get(c);if(!l||l.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} dispatch has a mismatched native payload`);return l}function i(s,c,l,u){let p={decision:l,source:s.source,...u?{reason:u}:{}};return n.set(p,c),p}let o=n7e({ruleContextProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule context request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule context request has an invalid native token");let l=t.get(c);if(!l||l.kind!=="before_tool_call")throw new Error("OpenClaw rule context request has a mismatched native payload");return e.ruleContextProvider?.(l.event,l.context,s)},ruleInputEnrichmentProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule enrichment request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule enrichment request has an invalid native token");let l=t.get(c);if(!l||l.kind!=="before_tool_call")throw new Error("OpenClaw rule enrichment request has a mismatched native payload");return e.ruleInputEnrichmentProvider?.(l.event,l.context,s)},promptExcludePrincipleIds(s){let c=r(s);if(c.kind!=="before_prompt_build")throw new Error("OpenClaw prompt exclusion payload mismatch");return e.promptExcludePrincipleIds?.(c.event,c.context)??new Set},async beforePromptBuild(s,c){let l=r(s);if(l.kind!=="before_prompt_build")throw new Error("OpenClaw prompt payload mismatch");let u=await e.beforePromptBuild(l.event,l.context,c);return i(s,{kind:l.kind,value:u},u?"modify":"allow")},painEnrichmentProvider(s){let c=r(s);if(c.kind!=="after_tool_call")throw new Error("OpenClaw pain payload mismatch");return e.painEnrichmentProvider?.(c.event,c.context)}});async function a(s,c,l){let u={};t.set(u,s);let p={kind:s.kind,context:{...cun(c,l,s.kind==="before_prompt_build"?void 0:s.event.toolName),...s.kind==="after_tool_call"?{toolInput:s.event.params??{},toolOutput:{error:s.event.error,result:s.event.result,durationMs:s.event.durationMs}}:{}},rawPayload:s.kind==="before_tool_call"?{nativeToken:u,toolInput:{toolName:s.event.toolName,params:s.event.params??{}}}:{nativeToken:u},source:`openclaw:${s.kind}`},f=await o.dispatch(p),m=n.get(f);if(s.kind==="before_tool_call"&&!m){let y=e.onBeforeToolResult?.(s.event,s.context,f);return{kind:s.kind,value:f.decision==="deny"?{block:!0,blockReason:f.reason}:y}}if(s.kind==="after_tool_call"&&!m)return f.metadata?.outcome!=="unavailable"&&await e.onAfterToolResult?.(s.event,s.context,f),{kind:s.kind,value:void 0};if(!m||m.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} result mapping is missing`);return m}return{runtime:o,async dispatchBeforePromptBuild(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_prompt_build requires workspaceDir");let l=await a({kind:"before_prompt_build",event:s,context:c},c.workspaceDir,c.sessionId);if(l.kind!=="before_prompt_build")throw new Error("OpenClaw prompt result mismatch");return l.value},async dispatchBeforeToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_tool_call requires workspaceDir");let l=await a({kind:"before_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(l.kind!=="before_tool_call")throw new Error("OpenClaw gate result mismatch");return l.value},async dispatchAfterToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw after_tool_call requires workspaceDir");await a({kind:"after_tool_call",event:s,context:c},c.workspaceDir,c.sessionId)}}}var L9e=new Set;try{EK()}catch{}function Xzi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j4(e,t,n){return dr(e,t,n)}function lun(e,t){let n=j4(e,"evolution_worker",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"mvp_quiet_per_adr0014",nextAction:"set features.evolution_worker.enabled=true in .pd/config.yaml to enable",featureFlag:"evolution_worker",boundedContext:"legacy_evolution_worker",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function uun(e,t){let n=j4(e,"correction_observer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"correction_observer_disabled",nextAction:"set features.correction_observer.enabled=true in .pd/config.yaml to enable",featureFlag:"correction_observer",boundedContext:"correction_observer_service",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function dun(e,t){let n=j4(e,"internalization_auto_consumer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`,featureFlag:"internalization_auto_consumer",boundedContext:"internalization_auto_consumer",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function pun(e,t){let n=j4(e,"abstraction_layer_v1",t);return n.enabled?{enabled:!0,source:n.source,rollbackReason:null}:{enabled:!1,source:n.source,rollbackReason:JSON.stringify({reason:"abstraction_layer_v1_disabled",nextAction:"set features.abstraction_layer_v1.enabled=true in .pd/config.yaml for controlled shared-runtime parity validation",route:"openclaw_legacy",flagSource:n.source})}}var fun={name:"Principles Disciple",description:"Evolutionary programming agent framework with strategic guardrails and reflection loops.",register(e){e.logger.info(`Principles Disciple Plugin registered. (Path: ${e.rootDir??"(unknown)"})`),od.setExtensionRoot(e.rootDir??"."),setTimeout(()=>{let p=TYe({agentId:"main"},e,"startup.health_check"),f=Ea(p);f?(e.logger.error(`[PD:health] Tool hook workspaceDir is INVALID: "${p}" - ${f}`),e.logger.error("[PD:health] Tool hook events will be written to the WRONG .state directory!")):e.logger.info(`[PD:health] Tool hook workspaceDir OK: "${p}"`);let m=MD(TK(e.config,e.id));if(m.authorized)e.logger.info("[PD:health] conversation hooks (allowConversationAccess) OK");else{let y=!1;try{y=EK()}catch(_){e.logger.warn(`[PD:health] auto-fix for allowConversationAccess failed: ${String(_ instanceof Error?_.message:_)}`)}y?e.logger.info("[PD:health] allowConversationAccess auto-configured. Restart the gateway to activate conversation hooks."):e.logger.error(`[PD:health] conversation hooks (llm_output / trajectory) will be BLOCKED by OpenClaw.
3168
+ `)}}}import*as N_ from"fs";import*as Kce from"path";import*as Yn from"fs";import*as eo from"path";import{fileURLToPath as YXe}from"url";function HXe(e){return Sln(e)}function VXe(e,t){WA(e,n=>{n[t.principleId]=t})}function Sln(e){return Bn(e).trainingStore}import*as sN from"fs";import*as P4 from"path";var kln="empathy_keywords.json";function zXe(e,t){let n=P4.join(e,kln),r=P4.dirname(n);sN.existsSync(r)||sN.mkdirSync(r,{recursive:!0}),t.lastUpdated=new Date().toISOString(),Pt(n,JSON.stringify(t,null,2))}var Aln={name:"Principles Disciple Agent",version:"1.0.0"},Rln="pd-core-guidance-v2",JXe=new Set(["AGENTS.md","TOOLS.md"]);function Cln(){return`pd-core-guidance-version: ${Rln}`}function Pln(e,t){return!JXe.has(e)||t.includes(Cln())?!1:!!(t.includes("pd_spawn_agent")||!t.includes("subagents")||!t.includes("sessions_spawn"))}function XXe(e,t,n="en"){try{let r=YXe(import.meta.url),i=eo.dirname(r),o=eo.resolve(i,"..","..","templates","workspace");Yn.existsSync(o)&&(e.logger.info(`[PD] Syncing workspace templates: ${t}...`),$ce(o,t,e));let a=eo.resolve(i,"..","..","templates","langs",n,"core");if(Yn.existsSync(a)||(a=eo.resolve(i,"..","..","templates","langs","zh","core")),Yn.existsSync(a)){e.logger.info(`[PD] Flattening ${n} core templates to workspace root...`);let p=Yn.readdirSync(a);for(let f of p){let m=eo.join(a,f),y=eo.join(t,f);if(!Yn.existsSync(y))Yn.copyFileSync(m,y),e.logger.info(`[PD] Initialized core file: ${f}`);else if(JXe.has(f)){let _=Yn.readFileSync(y,"utf8");Pln(f,_)&&e.logger.warn(`[PD] Outdated core guidance detected in ${f}. Review the latest template guidance for peer sessions, subagents, and sessions_spawn routing.`)}}}let s=eo.resolve(i,"..","..","templates","langs",n,"pain"),c=eo.join(t,zn.PAIN_SAMPLES);Yn.existsSync(s)&&(Yn.existsSync(c)||Yn.mkdirSync(c,{recursive:!0}),$ce(s,c,e));let l=eo.join(t,zn.IDENTITY),u=eo.join(l,"PROFILE.json");Yn.existsSync(u)||(Yn.existsSync(l)||Yn.mkdirSync(l,{recursive:!0}),Pt(u,JSON.stringify(Aln,null,2)),e.logger.info("[PD] Initialized PROFILE.json with identity metadata (contextInjection migrated to .pd/config.yaml)"))}catch(r){e.logger.error(`[PD] Failed to initialize workspace templates: ${String(r)}`)}}function $ce(e,t,n){let r=Yn.readdirSync(e);for(let i of r){let o=eo.join(e,i),a=i==="okr"?eo.join("memory","okr"):i,s=eo.join(t,a);if(Yn.statSync(o).isDirectory())Yn.existsSync(s)||Yn.mkdirSync(s,{recursive:!0}),$ce(o,s,n);else if(!Yn.existsSync(s)){let l=eo.dirname(s);Yn.existsSync(l)||Yn.mkdirSync(l,{recursive:!0}),Yn.copyFileSync(o,s),n.logger.info(`[PD] Copied: ${a}`)}}}var $k=jp.map(e=>({id:e.id,name:e.name,description:e.statement}));function QXe(e,t){try{let n=HXe(e);if(Object.keys(n).filter(a=>a!=="_tree").length>0)return!1;t.info(`[PD] Initializing core thinking models (${$k.length} principles) into training store`);for(let a of $k){let s={principleId:a.id,evaluability:"deterministic",applicableOpportunityCount:0,observedViolationCount:0,complianceRate:0,violationTrend:0,generatedSampleCount:0,approvedSampleCount:0,includedTrainRunIds:[],deployedCheckpointIds:[],internalizationStatus:"needs_training"};VXe(e,s);let c=new Date().toISOString(),l={id:a.id,version:1,text:a.description,coreAxiomId:a.id,triggerPattern:"",action:"",status:"active",priority:"P1",scope:"general",evaluability:"deterministic",valueScore:0,adherenceRate:0,painPreventedCount:0,derivedFromPainIds:[],ruleIds:[],conflictsWithPrincipleIds:[],createdAt:c,updatedAt:c,suggestedRules:[]};dv(e,l)}let i=$k[0]?.id??"T-01",o=$k[$k.length-1]?.id??"T-10";return t.info(`[PD] Initialized ${$k.length} core thinking models: ${i} through ${o}`),!0}catch(n){return t.error(`[PD] Failed to initialize core principles: ${String(n)}`),!1}}function ZXe(e,t,n="en"){try{let r=YXe(import.meta.url),i=eo.dirname(r);Yn.existsSync(t)||Yn.mkdirSync(t,{recursive:!0});let o=["pain_settings.json"];for(let l of o){let u=eo.resolve(i,"..","..","templates",l),p=eo.join(t,l);!Yn.existsSync(p)&&Yn.existsSync(u)&&(Yn.copyFileSync(u,p),e.logger.info(`[PD] Initialized ${l} in stateDir: ${p}`))}let a=eo.resolve(i,"..","..","templates","langs",n,"pain_dictionary.json");Yn.existsSync(a)||(a=eo.resolve(i,"..","..","templates","langs","en","pain_dictionary.json"));let s=eo.join(t,"pain_dictionary.json");!Yn.existsSync(s)&&Yn.existsSync(a)&&(Yn.copyFileSync(a,s),e.logger.info(`[PD] Initialized pain dictionary in stateDir: ${s} (Lang: ${n})`));let c=eo.join(t,"empathy_keywords.json");if(!Yn.existsSync(c)){let u=nk(n==="zh"||n==="en"?n:"en");zXe(t,u),e.logger.info(`[PD] Initialized empathy keyword store in stateDir: ${c}`)}}catch(r){e.logger.error(`[PD] Failed to initialize state templates: ${String(r)}`)}}import*as r9e from"fs";var e9e="pain_diagnosis",t9e="medium";function n9e(e){return{id:e.id,taskKind:e.taskKind||e9e,priority:e.priority||t9e,source:e.source,traceId:e.traceId,task:e.task,score:e.score,reason:e.reason,timestamp:e.timestamp,enqueued_at:e.enqueued_at,started_at:e.started_at,completed_at:e.completed_at,assigned_session_key:e.assigned_session_key,trigger_text_preview:e.trigger_text_preview,status:e.status||"pending",resolution:e.resolution,session_id:e.session_id,agent_id:e.agent_id,retryCount:e.retryCount||0,maxRetries:e.maxRetries||3,lastError:e.lastError,resultRef:e.resultRef}}function Uce(e){return e&&typeof e=="object"&&!("taskKind"in e)}function O4(e){return e.map(t=>Uce(t)?n9e(t):t)}var Fce=["pain_diagnosis","sleep_reflection","model_eval","keyword_optimization"];function L4(e){let t=[];if(e===null||typeof e!="object"||Array.isArray(e))return["item is not an object"];let n=e;return(!n.id||typeof n.id!="string")&&t.push("missing/invalid id"),(!n.source||typeof n.source!="string")&&t.push("missing/invalid source"),typeof n.score!="number"&&t.push("missing/invalid score"),(!n.status||typeof n.status!="string")&&t.push("missing/invalid status"),!n.taskKind||typeof n.taskKind!="string"?t.push("missing/invalid taskKind"):Fce.includes(n.taskKind)||t.push(`invalid taskKind value '${n.taskKind}' (expected one of: ${Fce.join(", ")})`),typeof n.retryCount!="number"&&t.push("missing/invalid retryCount"),typeof n.maxRetries!="number"&&t.push("missing/invalid maxRetries"),t}var Wce=".lock",i9e=50,o9e=50,a9e=3e4;async function jce(e,t,n,r=Wce){try{return await s9e(e,t,r)}catch(i){throw new kK(e,n,{cause:i})}}async function s9e(e,t,n=Wce){try{let r=await ose(e,{lockSuffix:n,maxRetries:i9e,baseRetryDelayMs:o9e,lockStaleMs:a9e});return()=>IK(r)}catch(r){let i=t?.warn;throw i?.(`[PD:EvolutionWorker] Failed to acquire lock for ${e}: ${String(r)}`),r}}function qce(e){let t=[];try{t=JSON.parse(r9e.readFileSync(e,"utf8"))}catch(r){r.code==="ENOENT"?t=[]:(console.warn(`[queue-io] Failed to load evolution queue (recovering with empty): ${String(r)}`),t=[])}return O4(t).filter(r=>{let i=L4(r);return i.length>0?(console.warn(`[queue-io] Dropping malformed queue item: ${i.join(", ")} | id=${r?.id??"N/A"}`),!1):!0})}function D4(e,t){Pt(e,JSON.stringify(t,null,2))}function c9e(e){let t=String(e);return t.includes("Plugin runtime subagent methods are only available during a gateway request")||t.includes("cannot start workflow for boot session")||t.includes("subagent runtime unavailable")||t.includes("subagent is not available")||t.includes("NocturnalWorkflowManager")&&t.includes("subagent runtime unavailable")||t.includes("gateway is not running")||t.includes("process isolation")||t.includes("subagent")&&t.toLowerCase().includes("connection")&&(t.includes("refused")||t.includes("reset")||t.includes("econnrefused"))}async function l9e(e,t,n,r){let i=r?` (${r})`:"";if(typeof e.patchSessionEntry!="function"||typeof e.getSessionEntry!="function"){n?.warn?.(`[PD:Watchdog] Cannot clean up session ${t}${i}: host does not expose row-scoped session helpers. The stale entry will be swept by OpenClaw's session GC.`);return}if(!e.getSessionEntry({sessionKey:t})){n?.debug?.(`[PD:Watchdog] Session ${t} already absent${i}; nothing to clean.`);return}await e.patchSessionEntry({sessionKey:t,replaceEntry:!0,preserveActivity:!1,update:()=>null}),n?.info?.(`[PD:Watchdog] Cleaned up stale session via row-scoped API${i}: ${t}`)}async function u9e(e,t,n){let r=[],i=Date.now(),o=t?.runtime?.subagent,a=t?.runtime?.agent?.session;try{let s=new D_({workspaceDir:e.workspaceDir});try{let c=s.listWorkflows(),l=3e5*2,u=c.filter(y=>y.state==="active"&&i-y.created_at>l);if(u.length>0)for(let y of u){let _=Math.round((i-y.created_at)/6e4);r.push(`stale_active: ${y.workflow_id} (${y.workflow_type}, ${_}min old)`);let b=s.getEvents(y.workflow_id),I=b[b.length-1],E=I?I.reason:"unknown";if(c9e(E)){n?.debug?.(`[PD:Watchdog] Skipping stale active workflow ${y.workflow_id}: expected subagent error (${E})`);continue}if(s.updateWorkflowState(y.workflow_id,"terminal_error"),s.recordEvent(y.workflow_id,"watchdog_timeout","active","terminal_error",`Stale active > ${l/6e4}s`,{ageMs:i-y.created_at}),y.child_session_key)try{o?(await o.deleteSession({sessionKey:y.child_session_key,deleteTranscript:!0}),n?.info?.(`[PD:Watchdog] Cleaned up stale session: ${y.child_session_key}`)):a&&await l9e(a,y.child_session_key,n)}catch(R){let A=String(R);if(A.includes("gateway request")&&a)try{await l9e(a,y.child_session_key,n,"after gateway error")}catch(P){n?.warn?.(`[PD:Watchdog] Fallback cleanup also failed for ${y.child_session_key}: ${String(P)}`)}else n?.warn?.(`[PD:Watchdog] Failed to cleanup session ${y.child_session_key}: ${A}`)}}let p=c.filter(y=>(y.state==="terminal_error"||y.state==="expired")&&y.cleanup_state==="pending");p.length>0&&r.push(`uncleared_terminal: ${p.length} workflows (will be swept next cycle)`);let f={};for(let y of c)f[y.state]=(f[y.state]||0)+1;let m=Object.entries(f).map(([y,_])=>`${y}=${_}`).join(", ");r.length===0?n?.debug?.(`[PD:Watchdog] OK \u2014 ${c.length} workflows (${m})`):n?.info?.(`[PD:Watchdog] ${r.length} anomalies \u2014 ${c.length} workflows (${m})`)}finally{s.dispose()}}catch(s){return n?.warn?.(`[PD:Watchdog] Failed to scan workflows: ${String(s)}`),{anomalies:-1,details:[],scanError:String(s)}}return{anomalies:r.length,details:r}}var em=null;var Oln=1440*60*1e3;function Lln(e,t){let n=Date.now()-Oln,r={},i=e.filter(s=>{if(s.status!=="failed")return!1;let c=new Date(s.timestamp||s.enqueued_at||0).getTime();if(!Number.isFinite(c)||c>n)return!1;let l=s.lastError||s.resolution||"unknown";return r[l]=(r[l]||0)+1,!0});if(i.length===0)return{purged:0,remaining:e.length,byReason:r};let o=new Set(i.map(s=>s.id));for(let s=e.length-1;s>=0;s--){let c=e[s];c&&o.has(c.id)&&e.splice(s,1)}let a=Object.entries(r).map(([s,c])=>`${c}x ${s}`).join("; ");return t?.info?.(`[PD:EvolutionWorker] Purged ${i.length} stale failed tasks (>24h): ${a}`),{purged:i.length,remaining:e.length,byReason:r}}async function Dln(e,t,n){if(!e.stateDir)return;let r;try{r=Bn(e.stateDir)}catch(c){t?.warn?.(`[PD:EvolutionWorker] CompilationBackfill: failed to load ledger: ${String(c)}`);return}let i=Kce.join(e.stateDir,"COMPILATION_BACKFILL_DONE");if(!N_.existsSync(i)){let c=0;for(let[l,u]of Object.entries(r.tree.principles)){if(u.compilationRetryCount!==void 0||u.evaluability==="manual_only")continue;if(Object.values(r.tree.implementations).some(f=>f.lifecycleState==="active"&&r.tree.rules[f.ruleId]?.principleId===l))try{ns(e.stateDir,l,{compilationRetryCount:void 0})}catch(f){$e.log(e.workspaceDir,"BACKFILL_UPDATE_FAILED",`Failed to mark principle ${l} as done: ${String(f)}`);continue}else try{ns(e.stateDir,l,{compilationRetryCount:0}),c++}catch(f){$e.log(e.workspaceDir,"BACKFILL_UPDATE_FAILED",`Failed to queue principle ${l}: ${String(f)}`);continue}}c>0&&$e.log(e.workspaceDir,"COMPILE_BACKFILL_QUEUED",`Queued ${c} old principles for compilation`);try{Pt(i,new Date().toISOString())}catch(l){$e.log(e.workspaceDir,"BACKFILL_MARKER_WRITE_FAILED",`Failed to write backfill marker: ${String(l)}`)}}let a=Sa.get(e.workspaceDir),s=new ib(e.stateDir,a);r=Bn(e.stateDir);for(let[c,l]of Object.entries(r.tree.principles)){let u=l.compilationRetryCount;if(u!==void 0&&!(u>=5))try{let p=s.compileOne(c);if(p.success)Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:void 0,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_SUCCESS",`Principle ${c} compiled successfully (attempt ${u+1})`);else{let f=u+1;f>=5?(d9e({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,updates:{evaluability:"manual_only",compilationRetryCount:void 0},workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_EXHAUSTED",`Principle ${c} compilation exhausted after 5 attempts: ${p.reason??"unknown"}`)):(Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:f,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_FAILED",`Principle ${c} compile failed: ${p.reason??"unknown"} (attempt ${f}/5)`))}}catch(p){let f=u+1;f>=5?(d9e({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,updates:{evaluability:"manual_only",compilationRetryCount:void 0},workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_EXHAUSTED",`Principle ${c} compilation exhausted after 5 attempts: threw ${String(p)}`)):(Bce({stateDir:e.stateDir,workspaceDir:e.workspaceDir,principleId:c,count:f,workerStatus:n}),$e.log(e.workspaceDir,"COMPILE_FAILED",`Principle ${c} compile threw: ${String(p)} (attempt ${f}/5)`))}}}function Bce(e){let{stateDir:t,workspaceDir:n,principleId:r,count:i,workerStatus:o}=e;try{ns(t,r,{compilationRetryCount:i})}catch(a){let s=a instanceof Error?a.message:String(a);$e.log(n,"WORKER_RETRY_UPDATE_FAILED",`Failed to update retry count for ${r}: ${s}`),o&&(o.errors.push({at:new Date().toISOString(),kind:"retry_count_update_failed",principleId:r,error:s}),N4(t,o))}}function d9e(e){let{stateDir:t,workspaceDir:n,principleId:r,updates:i,workerStatus:o}=e;try{ns(t,r,i)}catch(a){let s=a instanceof Error?a.message:String(a);$e.log(n,"WORKER_PRINCIPLE_UPDATE_FAILED",`Failed to update principle ${r}: ${s}`),o&&(o.errors.push({at:new Date().toISOString(),kind:"principle_update_failed",principleId:r,error:s}),N4(t,o))}}async function Nln(e,t,n,r){let i=e.resolve("EVOLUTION_QUEUE");if(!N_.existsSync(i)){t?.debug?.("[PD:EvolutionWorker] No evolution queue file \u2014 nothing to process");return}let o=await jce(i,t,"processEvolutionQueue"),a=!1;try{let s=[];try{s=JSON.parse(N_.readFileSync(i,"utf8"))}catch(f){let m=`${i}.corrupted.${Date.now()}`;try{N_.renameSync(i,m),t&&t.error(`[PD:EvolutionWorker] Evolution queue corrupted and backed up to ${m}. All pending tasks have been preserved in the backup file. Parse error: ${String(f)}`),$e.log(e.workspaceDir,"QUEUE_CORRUPTED",`Queue file backed up to ${m}. Error: ${String(f)}`)}catch(y){t&&t.error(`[PD:EvolutionWorker] Failed to backup corrupted queue: ${String(y)}`)}return}let c=O4(s),l=c.length;c=c.filter(f=>f.taskKind!=="pain_diagnosis"),c.length<l&&t?.info?.(`[PD:EvolutionWorker] Dropped ${l-c.length} legacy pain_diagnosis queue item(s); use PainSignalBridge/pd pain record`);let u=c.length;c=c.filter(f=>{let m=L4(f);return m.length>0?(t?.warn?.(`[PD:EvolutionWorker] Skipping malformed queue item: ${m.join(", ")} | ${JSON.stringify(f).slice(0,200)}`),$e.log(e.workspaceDir,"QUEUE_ITEM_MALFORMED",`Skipped: ${m.join(", ")} | id=${f.id||"N/A"}`),!1):!0}),c.length<u&&t?.info?.(`[PD:EvolutionWorker] Filtered ${u-c.length} malformed queue item(s)`),(s.some(Uce)||c.length<l||c.length<u)&&D4(i,c)}catch(s){t&&t.warn(`[PD:EvolutionWorker] Error processing evolution queue: ${String(s)}`)}finally{a||o()}}function N4(e,t){try{let n=Kce.join(e,"worker-status.json");Pt(n,JSON.stringify(t,null,2))}catch(n){}}async function p9e(e,t,n,r){let i={total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},o=[];try{let a=e.resolve("EVOLUTION_QUEUE");if(!N_.existsSync(a))return{queue:i,errors:o};let s=qce(a),c=Lln(s,t);c.purged>0&&D4(a,s),i.total=s.length,i.pending=s.filter(l=>l.status==="pending").length,i.in_progress=s.filter(l=>l.status==="in_progress").length,i.failed_this_cycle=s.filter(l=>l.status==="failed").length,i.completed_this_cycle=s.filter(l=>l.status==="completed").length,t.info(`[PD:EvolutionWorker] Queue snapshot: total=${i.total} pending=${i.pending} in_progress=${i.in_progress} completed=${i.completed_this_cycle} failed=${i.failed_this_cycle} purged=${c.purged}`),await Nln(e,t,n,r)}catch(a){let s=`processEvolutionQueue failed: ${String(a)}`;o.push(s),t.error(`[PD:EvolutionWorker] ${s}`)}return{queue:i,errors:o}}var M4={id:"principles-evolution-worker",api:null,_startedWorkspaces:new Set,start(e){let t=e?.workspaceDir,n=e?.logger||console,{api:r}=this;if(!t){n&&n.warn("[PD:EvolutionWorker] workspaceDir not found in service config. Evolution cycle disabled.");return}let i=M4._startedWorkspaces;if(i.has(t)){e?.logger?.info?.(`[PD:EvolutionWorker] Already started for ${t}, skipping`);return}i.add(t);let o=rt.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:EvolutionWorker] Starting with workspaceDir=${o.workspaceDir}, stateDir=${o.stateDir}`),q7e(o.stateDir);let{eventLog:a}=o,{config:s}=o,c=s.get("language")||"en";ZXe({logger:n},o.stateDir,c),QXe(o.stateDir,n);let l=5e3,u=s.get("intervals.worker_poll_ms")||900*1e3,p=0;async function f(){let m=Date.now();p++;let y=r?.runtime?.subagent;n?.info?.(`[PD:DEBUG:SubagentCheck:Heartbeat] api_exists=${!!r}, subagent_exists=${!!y}, subagent.run_exists=${!!y?.run}, heartbeatCounter=${p}`),y?.run&&n?.info?.("[PD:DEBUG:SubagentCheck:Heartbeat] run entrypoint is callable");let _={timestamp:new Date().toISOString(),cycle_start_ms:m,duration_ms:0,pain_flag:{exists:!1,score:null,source:null,enqueued:!1,skipped_reason:null},queue:{total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},errors:[]};try{Dln(o,n,_).catch(I=>{n?.error?.(`[PD:EvolutionWorker] CompilationBackfill threw: ${String(I)}`)}),n?.info?.(`[PD:EvolutionWorker] HEARTBEAT cycle=${new Date().toISOString()}`);let b=await p9e(o,n,a,r??void 0);_.queue=b.queue,b.errors&&_.errors.push(...b.errors);try{let I=r?.runtime?.subagent,E=new D_({workspaceDir:o.workspaceDir});try{let R=E.getExpiredWorkflows(3e5);for(let A of R){if(I&&A.child_session_key)try{await I.deleteSession({sessionKey:A.child_session_key,deleteTranscript:!0}),E.updateCleanupState(A.workflow_id,"completed"),n?.info?.(`[PD:EvolutionWorker] Cleaned up session ${A.child_session_key} for expired workflow ${A.workflow_id}`)}catch(P){let O=`Session cleanup failed for workflow ${A.workflow_id} (child_session=${A.child_session_key}): ${String(P)}`;E.updateCleanupState(A.workflow_id,"failed"),_.errors.push(O),n?.warn?.(`[PD:EvolutionWorker] ${O}`)}else if(A.child_session_key){let P=`Session cleanup unavailable for workflow ${A.workflow_id} (child_session=${A.child_session_key}): subagentRuntime not in gateway context`;E.updateCleanupState(A.workflow_id,"failed"),_.errors.push(P),n?.warn?.(`[PD:EvolutionWorker] ${P}`)}E.updateWorkflowState(A.workflow_id,"expired"),E.recordEvent(A.workflow_id,"swept",A.state,"expired","TTL expired",{}),n?.warn?.(`[PD:EvolutionWorker] Marked workflow ${A.workflow_id} as expired`)}}finally{E.dispose()}}catch(I){let E=`Failed to sweep expired workflows: ${String(I)}`;_.errors.push(E),n?.warn?.(`[PD:EvolutionWorker] ${E}`)}try{let I=await u9e(o,r,n);I.anomalies>0&&(n?.warn?.(`[PD:Watchdog] ${I.anomalies} anomalies: ${I.details.join("; ")}`),_.errors.push(...I.details))}catch(I){n?.warn?.(`[PD:Watchdog] Watchdog failed: ${String(I)}`)}o.dictionary.flush(),xse(),_.duration_ms=Date.now()-m,N4(o.stateDir,_)}catch(b){let I=`Error in worker interval: ${String(b)}`;n&&n.error(`[PD:EvolutionWorker] ${I}`),N4(o.stateDir,{timestamp:new Date().toISOString(),cycle_start_ms:m,duration_ms:Date.now()-m,pain_flag:{exists:!1,score:null,source:null,enqueued:!1,skipped_reason:null},queue:{total:0,pending:0,in_progress:0,completed_this_cycle:0,failed_this_cycle:0},errors:[I]})}em=setTimeout(f,u),em.unref()}em=setTimeout(()=>{(async()=>{let m=await p9e(o,n,a,r??void 0);m.errors.length>0&&m.errors.forEach(y=>n?.error?.(`[PD:EvolutionWorker] Startup cycle error: ${y}`)),em=setTimeout(f,u),em.unref()})().catch(m=>{n&&n.error(`[PD:EvolutionWorker] Startup worker cycle failed: ${String(m)}`),em=setTimeout(f,u),em.unref()})},l),em.unref()},stop(e){e?.logger&&e.logger.info("[PD:EvolutionWorker] Stopping background service..."),em&&clearTimeout(em),xse()}};import*as Uk from"fs";import*as Vce from"path";var h9e="correction_keywords.json",f9e=.1,Mln=.9,xb=null;function $ln(){let e=new Date().toISOString();return{keywords:XS.map(n=>({...n,source:"seed",addedAt:e})),version:1,lastOptimizedAt:e}}function Fln(e){if(xb)return xb;let t=Vce.join(e,h9e);if(Uk.existsSync(t))try{let r=Uk.readFileSync(t,"utf-8");return xb=JSON.parse(r),xb}catch{}let n=$ln();return g9e(e,n),xb=n,xb}function g9e(e,t){let n=Vce.join(e,h9e);Uk.mkdirSync(e,{recursive:!0}),Pt(n,JSON.stringify(t,null,2)),xb=null}var Hce=null,m9e=null;var Fk=class e{store;stateDir;constructor(t){this.stateDir=t,this.store=Fln(t)}match(t){let n=t.trim().toLowerCase().replace(/[.,!?;:,。!?;:]/g,""),r=[],i=0;for(let u of this.store.keywords)if(n.includes(u.term.toLowerCase())){let p=u.truePositiveCount??0,f=u.falsePositiveCount??0,m=p+f>0?p/(p+f):1,y=u.weight*m;i+=y,r.push(u.term)}let o=Math.min(1,i),a=r.length>0,s=Math.min(1,r.length/3),c=Math.min(1,o/.8),l=Math.max(s,c);return{matched:a,matchedTerms:r.slice(0,5),score:o,confidence:l}}recordHits(t){for(let n of t){let r=this.store.keywords.findIndex(o=>o.term.toLowerCase()===n.toLowerCase());if(r<0)continue;let i=this.store.keywords[r];i&&(this.store.keywords[r]={...i,hitCount:(i.hitCount??0)+1,lastHitAt:new Date().toISOString()})}}recordTruePositive(t){let n=this.store.keywords.find(i=>i.term.toLowerCase()===t.toLowerCase());if(!n)return;n.truePositiveCount=(n.truePositiveCount??0)+1;let r=this.store.keywords.findIndex(i=>i.term.toLowerCase()===t.toLowerCase());r>=0&&(this.store.keywords[r]={...n}),this.flush()}recordFalsePositive(t){let n=this.store.keywords.find(i=>i.term.toLowerCase()===t.toLowerCase());if(!n)return;n.falsePositiveCount=(n.falsePositiveCount??0)+1,n.weight=Math.max(f9e,n.weight*.8),n.lastHitAt=new Date().toISOString();let r=this.store.keywords.findIndex(i=>i.term.toLowerCase()===t.toLowerCase());r>=0&&(this.store.keywords[r]={...n}),this.flush()}add(t){if(this.store.keywords.length>=L3)throw new Error("Correction keyword store limit reached (200 terms)");let n={...t,addedAt:new Date().toISOString()};this.store.keywords.push(n),this.flush()}updateWeight(t,n){let r=this.store.keywords.find(o=>o.term.toLowerCase()===t.toLowerCase());if(!r)throw new Error(`Keyword not found: ${t}`);r.weight=Math.max(f9e,Math.min(Mln,n));let i=this.store.keywords.findIndex(o=>o.term.toLowerCase()===t.toLowerCase());i>=0&&(this.store.keywords[i]={...r}),this.flush()}remove(t){let n=this.store.keywords.findIndex(r=>r.term.toLowerCase()===t.toLowerCase());if(n<0)throw new Error(`Keyword not found: ${t}`);this.store.keywords.splice(n,1),this.flush()}getStore(){return this.store}getLastOptimizedAt(){return this.store.lastOptimizedAt}flush(){g9e(this.stateDir,this.store)}static get(t){return(!Hce||m9e!==t)&&(Hce=new e(t),m9e=t),Hce}};var $4=class e{stateDir;workspaceDir;logger;constructor(t,n,r){this.stateDir=t,this.workspaceDir=n,this.logger=r}applyResult(t){let n=Fk.get(this.stateDir),r=t.updates??{};if(!t.updated||Object.keys(r).length===0){this.logger?.info?.("[KeywordOptimizationService] No updates to apply");return}for(let[i,o]of Object.entries(r))try{switch(o.action){case"add":{let a=i.trim().toLowerCase(),s=n.getStore().keywords.find(l=>l.term.toLowerCase()===a);if(s){this.logger?.info?.(`[KeywordOptimizationService] ADD skipped: "${i}" already exists as "${s.term}"`);break}let c=o.weight!==void 0?Math.max(.1,Math.min(.9,o.weight)):.5;n.add({term:a,weight:c,source:"llm"}),this.logger?.info?.(`[KeywordOptimizationService] ADD term="${a}" weight=${c}`);break}case"update":{o.weight!==void 0&&(n.updateWeight(i,o.weight),this.logger?.info?.(`[KeywordOptimizationService] UPDATE term="${i}" weight=${o.weight}`));break}case"remove":{n.remove(i),this.logger?.info?.(`[KeywordOptimizationService] REMOVE term="${i}"`);break}}}catch(a){this.logger?.warn?.(`[KeywordOptimizationService] ${o.action.toUpperCase()} failed for term="${i}": ${String(a)}`)}if(t.fpAnalysisStatus==="completed"&&t.fpTerms&&t.fpTerms.length>0){let o=[...new Set(t.fpTerms.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0))].slice(0,20);for(let a of o)try{n.recordFalsePositive(a),this.logger?.info?.(`[KeywordOptimizationService] FP recorded for term="${a}" (weight x0.8)`)}catch(s){this.logger?.warn?.(`[KeywordOptimizationService] recordFalsePositive failed for term="${a}": ${String(s)}`)}}}async buildTrajectoryHistory(t){let n=[],r=Sa.get(this.workspaceDir);for(let i of t.slice(0,10)){try{let o=r.listUserTurnsForSession(i);for(let a of o)if(a.correctionDetected&&n.push({sessionId:i,timestamp:a.createdAt??new Date().toISOString(),term:a.correctionCue??"unknown",userMessage:""}),n.length>=50)break}catch(o){this.logger?.warn?.(`[KeywordOptimizationService] Failed to read trajectory for session ${i}: ${String(o)}`)}if(n.length>=50)break}return n}static _instances=new Map;static get(t,n,r){let i=`${t}::${n}`;return e._instances.has(i)||e._instances.set(i,new e(t,n,r)),e._instances.get(i)}static reset(){e._instances.clear()}};var Bh=null,cN=!1,zce=new Set,Uln=900*1e3,Wln=1e4,jln=20,qln=5;function Gln(e,t){try{let n=LD(e.workspaceDir,"correction_observer","correctionObserver",t);if(!n.enabled)return n.readiness==="config_malformed"?t?.warn?.(`[PD:CorrectionObserver] Config malformed: ${n.reason}. ${n.nextAction}`):t?.debug?.(`[PD:CorrectionObserver] ${n.reason}`),null;if(n.readiness==="needs_setup")return t?.info?.(`[PD:CorrectionObserver] ${n.reason}. ${n.nextAction}`),null;if(n.runtimeProfileType==="pi-ai"){let r=new Xl({provider:n.provider??"anthropic",model:n.model??"anthropic/claude-3-5-sonnet",apiKeyEnv:n.apiKeyEnv??"ANTHROPIC_API_KEY",timeoutMs:n.timeoutMs??void 0,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return new gR({runtimeAdapter:r},{timeoutMs:n.timeoutMs??void 0})}return t?.info?.("[PD:CorrectionObserver] OpenClaw runtime profile not yet supported for correction observer. Skipping."),null}catch(n){return t?.warn?.(`[PD:CorrectionObserver] Failed to resolve CorrectionObserver: ${String(n)}`),null}}async function Bln(e,t){try{let n=Gln(e,t);if(!n){t?.debug?.("[PD:CorrectionObserver] Observer not resolved. Skipping cycle.");return}t?.info?.("[PD:CorrectionObserver] Observer resolved. Initiating periodic optimization...");let r=Sa.get(e.workspaceDir),o=r.listRecentSessions({limit:jln}).map(_=>_.sessionId);if(o.length===0){t?.info?.("[PD:CorrectionObserver] No recent sessions found. Skipping correction optimization.");return}let a=[];for(let _ of o.slice(0,qln))try{let b=r.listUserTurnsForSession(_);for(let I of b)I.rawExcerpt&&a.push(I.rawExcerpt)}catch(b){t?.warn?.(`[PD:CorrectionObserver] Failed to load user turns for session ${_}: ${String(b)}`)}let c=Fk.get(e.stateDir).getStore().keywords,l={totalKeywords:c.length,terms:c.map(_=>({term:_.term,weight:_.weight,hitCount:_.hitCount??0,truePositiveCount:_.truePositiveCount??0,falsePositiveCount:_.falsePositiveCount??0}))},u=$4.get(e.stateDir,e.workspaceDir,t),p=await u.buildTrajectoryHistory(o),f={parentSessionId:"correction-observer-service",workspaceDir:e.workspaceDir,keywordStoreSummary:l,recentMessages:a,trajectoryHistory:p},m=new aD;m.register({agentId:"correction-observer",mode:"realtime",runner:n}),t?.info?.(`[PD:CorrectionObserver] Dispatching with ${p.length} trajectory events, ${a.length} recent messages.`);let y=await m.dispatch("correction-observer",f);t?.info?.(`[PD:CorrectionObserver] Completed: updated=${y.updated}, summary="${y.summary}"`),y.updated&&u.applyResult(y)}catch(n){let r=`Correction observer cycle failed: ${String(n)}`;t?.warn?.(`[PD:CorrectionObserver] ${r}`),$e.log(e.workspaceDir,"CORRECTION_OBSERVER_CYCLE_FAILED",r)}}var Yce={id:"principles-correction-observer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n&&n.warn("[PD:CorrectionObserver] workspaceDir not found in service config. Correction observer disabled.");return}if(zce.has(t)){n&&n.info(`[PD:CorrectionObserver] Already started for workspace: ${t}. Skipping duplicate start.`);return}let r=LD(t,"correction_observer","correctionObserver",n);if(!r.enabled){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}if(r.readiness==="needs_setup"){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}zce.add(t),cN=!1;let i=rt.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:CorrectionObserver] Starting with workspaceDir=${i.workspaceDir}, stateDir=${i.stateDir}`);let o=Uln;async function a(){cN||(await Bln(i,n),!cN&&(Bh=setTimeout(a,o),Bh.unref()))}Bh=setTimeout(()=>{a().catch(s=>{n&&n.error(`[PD:CorrectionObserver] Startup cycle failed: ${String(s)}`),!cN&&(Bh=setTimeout(a,o),Bh.unref())})},Wln),Bh.unref()},stop(e){cN=!0,zce.clear(),Bh&&clearTimeout(Bh),Bh=null}};var Kln=12e4,Jce=3e4,Wk=new Map;function Hln(e){let t=Wk.get(e);return t||(t={stopped:!1,timeoutId:null},Wk.set(e,t)),t}function Vln(e){return`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`}async function zln(e,t){await E8e(e,{owner:"auto-consumer",logLabel:"AutoConsumer",logger:t,emitEvent:(n,r)=>$e.log(e,n,r),hostToolCatalog:{readOnlyTools:a4,writeTools:[...Sk,...Pse,...s4]}})}var Xce={id:"principles-internalization-auto-consumer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n.warn("[PD:AutoConsumer] No workspace directory, not starting.");return}let r=t,i=Hln(r);if(!i.stopped&&i.timeoutId!==null){n.info(`[PD:AutoConsumer] Already started for workspace: ${r}`);return}let o=dr(r,Yae,{info:l=>n.info(l),warn:l=>n.warn(l)});if(!o.enabled){let l=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:Vln(r),flagSource:o.source});$e.log(r,"INTERNALIZATION_CONSUMER_DISABLED",l),n.info(`[PD:AutoConsumer] NOT started for workspace: ${r}. Disabled (source: ${o.source}).`);return}i.stopped=!1;let a=Kln;function s(){i.stopped||(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())}async function c(){i.stopped||(await zln(r,n),s())}i.timeoutId=setTimeout(()=>{c().catch(l=>{n.error(`[PD:AutoConsumer] Startup cycle failed: ${String(l)}`),!i.stopped&&(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())})},Jce),i.timeoutId?.unref(),$e.log(r,"INTERNALIZATION_CONSUMER_STARTED",JSON.stringify({intervalMs:a,initialDelayMs:Jce})),n.info(`[PD:AutoConsumer] Started for workspace: ${r} (interval: ${a}ms, initial delay: ${Jce}ms)`)},stop(e){let t=e?.workspaceDir;if(t){let n=Wk.get(t);n&&(n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null),Wk.delete(t)}else{for(let[,n]of Wk)n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null;Wk.clear()}}};var y9e={id:"principles-disciple-trajectory",start(e){e.workspaceDir&&rt.fromHookContext(e).trajectory},stop(e){e.workspaceDir&&Sa.dispose(e.workspaceDir)}};import*as U4 from"fs";import*as T9e from"path";import*as E9e from"os";var _9e=[];import*as bb from"fs";import*as Qce from"path";var v9e="pd_tasks.json";function x9e(e){return Qce.join(e,".state",v9e)}function Yln(e){let t=Qce.join(e,".state");bb.existsSync(t)||bb.mkdirSync(t,{recursive:!0})}function b9e(e){let t=x9e(e);if(!bb.existsSync(t))return[];try{let n=bb.readFileSync(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch(n){return console.warn(`[PD:TaskStore] Failed to parse ${v9e}: ${String(n)}`),[]}}async function I9e(e,t){let n=x9e(e);Yln(e),await wK(n,async()=>{Pt(n,JSON.stringify(t,null,2))})}var F4=T9e.join(E9e.homedir(),".openclaw","cron","jobs.json");function Jln(e){if(!U4.existsSync(F4))return e?.info?.("[PD:Reconciler] cron/jobs.json not found, starting with empty store"),{version:1,jobs:[]};try{let t=U4.readFileSync(F4,"utf-8"),n=JSON.parse(t);return e?.info?.(`[PD:Reconciler] Loaded cron/jobs.json: ${n.jobs.length} jobs`),n}catch(t){return e?.warn?.(`[PD:Reconciler] Failed to parse cron/jobs.json: ${String(t)}`),{version:1,jobs:[]}}}async function Xln(e){await wK(F4,async()=>{Pt(F4,JSON.stringify(e,null,2))})}function Qln(e,t){let n=[],r=new Map;for(let i of t)r.set(i.name,i);for(let i of e){let o=r.get(i.name);if(!o)i.enabled&&n.push({type:"CREATE",task:i});else{let a=o.metadata?.pdVersion;i.enabled?!a||a!==i.version?n.push({type:"UPDATE",task:i,job:o}):n.push({type:"SKIP",task:i,job:o}):n.push({type:"DISABLE",task:i,job:o})}}for(let i of t){if(!i.name.startsWith("PD "))continue;e.find(a=>a.name===i.name)||n.push({type:"ORPHAN",job:i})}return n}function w9e(e,t,n,r){return r?.info?.(`[PD:Reconciler] Building cron job: ${e.name} (id=${e.id}, interval=${e.schedule.everyMs}ms)`),{id:`pd-${e.id}-${t}`,name:e.name,agentId:e.agentId||"main",description:e.description,enabled:e.enabled,schedule:{kind:"every",everyMs:e.schedule.everyMs},sessionTarget:"isolated",wakeMode:"now",payload:{kind:"agentTurn",message:Zln(e,n,r),lightContext:e.execution.lightContext??!0,timeoutSeconds:e.execution.timeoutSeconds??120,toolsAllow:e.execution.toolsAllow},delivery:{mode:e.delivery.mode},createdAtMs:t,updatedAtMs:t,state:{nextRunAtMs:t+e.schedule.everyMs},metadata:{pdVersion:e.version,pdTaskId:e.id}}}function Zln(e,t,n){return e.description}async function S9e(e,t){let n=t?.dryRun??!1,r=t?.logger??console,i=Date.now(),o={created:[],updated:[],skipped:[],orphaned:[],errors:[]},a=b9e(e),s=new Map(a.map(f=>[f.id,f])),c=_9e.map(f=>{let m=s.get(f.id);return m?{...f,meta:{...f.meta,...m.meta}}:{...f,meta:{createdAtMs:i}}}),l=await Jln(r),u=eun(c,l,r),p=Qln(u,l.jobs);for(let f of p)switch(f.type){case"CREATE":if(f.task){if(!n){let m=w9e(f.task,i,e,r);l.jobs.push(m),r.info?.(`[PD:Reconciler] Created job: ${f.task.name}`)}o.created.push(f.task.name)}break;case"UPDATE":if(f.task&&f.job){if(!n){let m=l.jobs.indexOf(f.job),y=w9e(f.task,i,e,r);y.id=f.job.id,y.state={...f.job.state,nextRunAtMs:void 0},l.jobs[m]=y,r.info?.(`[PD:Reconciler] Updated job: ${f.task.name}`)}o.updated.push(f.task.name)}break;case"DISABLE":if(f.job){if(!n){let m=l.jobs.indexOf(f.job);m>=0&&(l.jobs[m]={...f.job,enabled:!1,updatedAtMs:i})}r.warn?.(`[PD:Reconciler] Disabled job: ${f.job.name}`)}break;case"ORPHAN":f.job&&(r.warn?.(`[PD:Reconciler] Orphaned job (no declaration): ${f.job.name}`),o.orphaned.push(f.job.name));break;case"SKIP":f.task&&o.skipped.push(f.task.name);break}if(!n&&(o.created.length>0||o.updated.length>0)){await Xln(l),r.info?.(`[PD:Reconciler] Wrote cron/jobs.json: ${l.jobs.length} total jobs`);for(let f of l.jobs)f.name.startsWith("PD ")&&r.info?.(`[PD:Reconciler] PD job: name=${f.name}, enabled=${f.enabled}, schedule=${JSON.stringify(f.schedule)}, nextRun=${f.state.nextRunAtMs?new Date(f.state.nextRunAtMs).toISOString():"TBD"}`)}return!n&&c.length>0&&await I9e(e,c),o}function eun(e,t,n){let r=new Map(t.jobs.map(i=>[i.name,i]));return e.map(i=>{let o=r.get(i.name);if(!o)return i;let a=o.state.consecutiveErrors??0,s=o.state.lastError??"",c=s.includes("timed out")||s.includes("timeout");if(c&&a>0&&o.payload.kind==="agentTurn"){let u=o.payload.timeoutSeconds??120,p=Math.min(1800,u*2);p>u&&(o.payload.timeoutSeconds=p,o.state.consecutiveErrors=0,o.state.lastError=void 0,n.info?.(`[PD:Reconciler] Auto-increased timeout for '${i.name}': ${u}s \u2192 ${p}s (was ${a} consecutive timeouts)`))}let l=a>=3&&!c&&!i.meta?.autoDisabled;return a===0&&i.meta?.autoDisabled&&n.info?.(`[PD:Reconciler] Task '${i.id}' was previously auto-disabled but has 0 consecutive errors now`),l||i.meta||o.state.lastRunAtMs?{...i,meta:{...i.meta,...l?{autoDisabled:!0,autoDisabledAt:Date.now(),autoDisabledReason:`consecutiveErrors=${a}`}:{},...i.meta?{consecutiveFailCount:a}:{},...o.state.lastRunAtMs?{lastFailedAtMs:o.state.lastRunAtMs}:{}}}:i})}var k9e={id:"principles-disciple-task-manager",async start(e){let{workspaceDir:t}=e,n=e.logger??e.api?.logger;if(!t){n?.warn?.("[PD:TaskManager] No workspaceDir, skipping PD task reconciliation");return}n?.info?.("[PD:TaskManager] Starting PD task reconciliation...");try{let r=await S9e(t,{logger:n??console});n?.info?.(`[PD:TaskManager] Reconcile complete: +${r.created.length} ~${r.updated.length} =${r.skipped.length} orphan=${r.orphaned.length}`),r.created.length>0&&n?.info?.(`[PD:TaskManager] Created jobs: ${r.created.join(", ")}`),r.updated.length>0&&n?.info?.(`[PD:TaskManager] Updated jobs: ${r.updated.join(", ")}`),r.errors.length>0&&n?.warn?.(`[PD:TaskManager] Reconcile errors: ${r.errors.map(i=>i.message).join(", ")}`)}catch(r){n?.warn?.(`[PD:TaskManager] Reconcile failed: ${String(r)}`)}},stop(e){}};import*as ys from"fs";import*as ko from"path";function A9e(e,t){try{let n=ko.join(t,"docs"),r=ko.join(t,"memory",".state"),i=[{legacy:ko.join(n,"PRINCIPLES.md"),newKey:"PRINCIPLES"},{legacy:ko.join(n,"THINKING_OS.md"),newKey:"THINKING_OS"},{legacy:ko.join(n,"DECISION_POLICY.json"),newKey:"DECISION_POLICY"},{legacy:ko.join(n,"evolution_queue.json"),newKey:"EVOLUTION_QUEUE"},{legacy:ko.join(n,".pain_flag"),newKey:"PAIN_FLAG"},{legacy:ko.join(n,"SYSTEM_CAPABILITIES.json"),newKey:"SYSTEM_CAPABILITIES"},{legacy:ko.join(n,"SYSTEM.log"),newKey:"SYSTEM_LOG"},{legacy:ko.join(r,"pain_dictionary.json"),newKey:"DICTIONARY"},{legacy:ko.join(r,"pain_settings.json"),newKey:"PAIN_SETTINGS"},{legacy:ko.join(r,"pain_candidates.json"),newKey:"PAIN_CANDIDATES"},{legacy:ko.join(r,"evolution_directive.json"),newKey:"EVOLUTION_DIRECTIVE"},{legacy:ko.join(r,"sessions"),newKey:"SESSION_DIR"},{legacy:ko.join(r,"logs","events.jsonl"),newKey:"SYSTEM_LOG"}],o=0;for(let a of i)if(ys.existsSync(a.legacy)){let s=Pi(t,a.newKey),c=ko.dirname(s);if(ys.existsSync(c)||ys.mkdirSync(c,{recursive:!0}),ys.existsSync(s))e.logger?.warn?.(`[PD:Migration] Skipping ${ko.basename(a.legacy)}: already exists at destination.`);else try{ys.renameSync(a.legacy,s),e.logger.info(`[PD:Migration] Migrated ${ko.basename(a.legacy)} to ${s.replace(t,"")}`),o++}catch(l){e.logger.error(`[PD:Migration] Failed to rename ${a.legacy}: ${String(l)}`)}}if(o>0&&e.logger.info(`[PD:Migration] Successfully migrated ${o} files/folders to new architecture.`),ys.existsSync(r))try{let a=ys.readdirSync(r);if(a.length===0||a.length===1&&a[0]==="logs"){let s=ko.join(r,"logs");ys.existsSync(s)&&ys.readdirSync(s).length===0&&ys.rmdirSync(s),ys.readdirSync(r).length===0&&(ys.rmdirSync(r),e.logger.info("[PD:Migration] Cleaned up empty legacy state directory."))}}catch(a){e.logger.debug?.(`[PD:Migration] Failed to cleanup legacy state dir: ${String(a)}`)}}catch(n){e.logger.error(`[PD:Migration] Directory refactor migration failed: ${String(n)}`)}}import*as ld from"fs";import*as M_ from"path";var tun=["AGENTS.md","MEMORY.md"],nun=["THINKING_OS.md"],R9e=M_.join(".principles","skills"),run=".principles",C9e=".pre-pri286.bak";function iun(e){try{let t=ld.readFileSync(e,"utf-8");return typeof t!="string"?null:t}catch{return null}}function oun(e,t){let n=e+C9e;try{return ld.writeFileSync(n,t,"utf-8"),!0}catch{return!1}}function aun(e){let t=M_.join(e,R9e);if(!ld.existsSync(t))return{files:[]};try{let n=ld.readdirSync(t,{withFileTypes:!0}),r=[];for(let i of n)if(i.isDirectory()){let o=M_.join(t,i.name,"SKILL.md");ld.existsSync(o)&&r.push(o)}return{files:r}}catch(n){let r=n instanceof Error?n.message:String(n);return{files:[],error:{file:R9e,error:`Failed to enumerate skills directory: ${r}`}}}}function sun(e,t){let n=[];for(let i of tun)n.push(M_.join(e,i));for(let i of nun)n.push(M_.join(e,run,i));let r=aun(e);return r.error&&t.errors.push(r.error),n.push(...r.files),n}function P9e(e,t){let n={migratedFiles:[],skippedFiles:[],errors:[]},r=sun(t,n);for(let i of r){let o=M_.relative(t,i);if(!ld.existsSync(i))continue;let a=iun(i);if(a===null){n.errors.push({file:o,error:"Failed to read file content"});continue}if(!Zte(a,o)){n.skippedFiles.push(o);continue}let s=Qte(a,o);if(!s.changed){n.skippedFiles.push(o);continue}let c=s.migrated;if(!oun(i,a)){n.errors.push({file:o,error:"Failed to create backup file before migration"});continue}try{ld.writeFileSync(i,c,"utf-8"),n.migratedFiles.push(o),e.logger.info(`[PD:GuidanceMigration] Migrated ${o} (backup at ${o}${C9e})`)}catch(u){let p=u instanceof Error?u.message:String(u);n.errors.push({file:o,error:`Failed to write migrated content: ${p}`});try{ld.writeFileSync(i,a,"utf-8")}catch{e.logger.error(`[PD:GuidanceMigration] CRITICAL: Failed to restore original content for ${o} after write failure`)}}}return n.migratedFiles.length>0&&e.logger.info(`[PD:GuidanceMigration] Migration complete: ${n.migratedFiles.length} migrated, ${n.skippedFiles.length} skipped, ${n.errors.length} errors`),n}function cun(e,t,n){return{workspaceDir:e,sessionId:t??"openclaw:session-unavailable",toolName:n}}function O9e(e){let t=new WeakMap,n=new WeakMap;function r(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error(`OpenClaw ${s.kind} dispatch is missing its native payload token`);let c=Object.hasOwn(s.rawPayload,"nativeToken")?Reflect.get(s.rawPayload,"nativeToken"):s.rawPayload;if(typeof c!="object"||c===null)throw new Error(`OpenClaw ${s.kind} dispatch has an invalid native payload token`);let l=t.get(c);if(!l||l.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} dispatch has a mismatched native payload`);return l}function i(s,c,l,u){let p={decision:l,source:s.source,...u?{reason:u}:{}};return n.set(p,c),p}let o=n7e({ruleContextProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule context request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule context request has an invalid native token");let l=t.get(c);if(!l||l.kind!=="before_tool_call")throw new Error("OpenClaw rule context request has a mismatched native payload");return e.ruleContextProvider?.(l.event,l.context,s)},ruleInputEnrichmentProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule enrichment request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule enrichment request has an invalid native token");let l=t.get(c);if(!l||l.kind!=="before_tool_call")throw new Error("OpenClaw rule enrichment request has a mismatched native payload");return e.ruleInputEnrichmentProvider?.(l.event,l.context,s)},promptExcludePrincipleIds(s){let c=r(s);if(c.kind!=="before_prompt_build")throw new Error("OpenClaw prompt exclusion payload mismatch");return e.promptExcludePrincipleIds?.(c.event,c.context)??new Set},async beforePromptBuild(s,c){let l=r(s);if(l.kind!=="before_prompt_build")throw new Error("OpenClaw prompt payload mismatch");let u=await e.beforePromptBuild(l.event,l.context,c);return i(s,{kind:l.kind,value:u},u?"modify":"allow")},painEnrichmentProvider(s){let c=r(s);if(c.kind!=="after_tool_call")throw new Error("OpenClaw pain payload mismatch");return e.painEnrichmentProvider?.(c.event,c.context)},hostKind:"openclaw"});async function a(s,c,l){let u={};t.set(u,s);let p={kind:s.kind,context:{...cun(c,l,s.kind==="before_prompt_build"?void 0:s.event.toolName),...s.kind==="after_tool_call"?{toolInput:s.event.params??{},toolOutput:{error:s.event.error,result:s.event.result,durationMs:s.event.durationMs}}:{}},rawPayload:s.kind==="before_tool_call"?{nativeToken:u,toolInput:{toolName:s.event.toolName,params:s.event.params??{}}}:{nativeToken:u},source:`openclaw:${s.kind}`},f=await o.dispatch(p),m=n.get(f);if(s.kind==="before_tool_call"&&!m){let y=e.onBeforeToolResult?.(s.event,s.context,f);return{kind:s.kind,value:f.decision==="deny"?{block:!0,blockReason:f.reason}:y}}if(s.kind==="after_tool_call"&&!m)return f.metadata?.outcome!=="unavailable"&&await e.onAfterToolResult?.(s.event,s.context,f),{kind:s.kind,value:void 0};if(!m||m.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} result mapping is missing`);return m}return{runtime:o,async dispatchBeforePromptBuild(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_prompt_build requires workspaceDir");let l=await a({kind:"before_prompt_build",event:s,context:c},c.workspaceDir,c.sessionId);if(l.kind!=="before_prompt_build")throw new Error("OpenClaw prompt result mismatch");return l.value},async dispatchBeforeToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_tool_call requires workspaceDir");let l=await a({kind:"before_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(l.kind!=="before_tool_call")throw new Error("OpenClaw gate result mismatch");return l.value},async dispatchAfterToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw after_tool_call requires workspaceDir");await a({kind:"after_tool_call",event:s,context:c},c.workspaceDir,c.sessionId)}}}var L9e=new Set;try{EK()}catch{}function Xzi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function j4(e,t,n){return dr(e,t,n)}function lun(e,t){let n=j4(e,"evolution_worker",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"mvp_quiet_per_adr0014",nextAction:"set features.evolution_worker.enabled=true in .pd/config.yaml to enable",featureFlag:"evolution_worker",boundedContext:"legacy_evolution_worker",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function uun(e,t){let n=j4(e,"correction_observer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"correction_observer_disabled",nextAction:"set features.correction_observer.enabled=true in .pd/config.yaml to enable",featureFlag:"correction_observer",boundedContext:"correction_observer_service",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function dun(e,t){let n=j4(e,"internalization_auto_consumer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`,featureFlag:"internalization_auto_consumer",boundedContext:"internalization_auto_consumer",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function pun(e,t){let n=j4(e,"abstraction_layer_v1",t);return n.enabled?{enabled:!0,source:n.source,rollbackReason:null}:{enabled:!1,source:n.source,rollbackReason:JSON.stringify({reason:"abstraction_layer_v1_disabled",nextAction:"set features.abstraction_layer_v1.enabled=true in .pd/config.yaml for controlled shared-runtime parity validation",route:"openclaw_legacy",flagSource:n.source})}}var fun={name:"Principles Disciple",description:"Evolutionary programming agent framework with strategic guardrails and reflection loops.",register(e){e.logger.info(`Principles Disciple Plugin registered. (Path: ${e.rootDir??"(unknown)"})`),od.setExtensionRoot(e.rootDir??"."),setTimeout(()=>{let p=TYe({agentId:"main"},e,"startup.health_check"),f=Ea(p);f?(e.logger.error(`[PD:health] Tool hook workspaceDir is INVALID: "${p}" - ${f}`),e.logger.error("[PD:health] Tool hook events will be written to the WRONG .state directory!")):e.logger.info(`[PD:health] Tool hook workspaceDir OK: "${p}"`);let m=MD(TK(e.config,e.id));if(m.authorized)e.logger.info("[PD:health] conversation hooks (allowConversationAccess) OK");else{let y=!1;try{y=EK()}catch(_){e.logger.warn(`[PD:health] auto-fix for allowConversationAccess failed: ${String(_ instanceof Error?_.message:_)}`)}y?e.logger.info("[PD:health] allowConversationAccess auto-configured. Restart the gateway to activate conversation hooks."):e.logger.error(`[PD:health] conversation hooks (llm_output / trajectory) will be BLOCKED by OpenClaw.
3165
3169
  reason: ${m.reason}
3166
3170
  nextAction: ${m.nextAction}`)}},1e3).unref();let n=new Map,r=new Set,i=u=>{let p=n.get(u);return p||(p=pun(u,e.logger),n.set(u,p)),!p.enabled&&!r.has(u)&&(r.add(u),e.logger.info(`[PD:host-runtime] OpenClaw legacy route selected. ${p.rollbackReason}`)),p},o=Pq();if(!o.passed)for(let u of o.violations)e.logger.error(`[PD:surface-guard] VIOLATION: ${u}`);e.logger.info(`[PD:surface-guard] Core surfaces: ${o.enabledCoreSurfaces.join(", ")}`),e.logger.info(`[PD:surface-guard] Disabled non-core surfaces: ${o.disabledNonCoreSurfaces.length}`);for(let u of o.warnings)e.logger.warn(`[PD:surface-guard] ${u}`);let a=e.pluginConfig?.language||"zh",s=new WeakMap,c=O9e({promptExcludePrincipleIds:(u,p)=>{try{let f=rt.fromHookContext({...p,workspaceDir:p.workspaceDir}).evolutionReducer,m=Hse(p.workspaceDir??"",f,e.logger);return s.set(u,m),m.selectedIds}catch(f){return e.logger.info(`[PD:RuntimeV2] Legacy principle dedup unavailable; continuing with shared active principles: ${String(f)}`),new Set}},beforePromptBuild:async(u,p,f)=>{let m=s.get(u);return s.delete(u),Vse(u,{...p,api:e},f,m)},ruleContextProvider:(u,p,f)=>Xse(rt.fromHookContext({...p,workspaceDir:p.workspaceDir}),f.targetPath,p.sessionId,e.logger),ruleInputEnrichmentProvider:(u,p)=>sJe(u,p.workspaceDir??"",p.sessionId),onBeforeToolResult:(u,p,f)=>{if(!p.workspaceDir){e.logger.warn("[PD_GATE:RULE_HOST] shared result mapping skipped: workspaceDir missing; nextAction=inspect OpenClaw hook context");return}cJe(u,{...p,workspaceDir:p.workspaceDir,logger:e.logger},f);let m=f.metadata?.ruleDecision;if(m==="auto_correct"||m==="requireApproval")return Jse(u,{...p,workspaceDir:p.workspaceDir,pluginConfig:e.pluginConfig??{},logger:e.logger})},painEnrichmentProvider:(u,p)=>jYe(u,{...p,workspaceDir:p.workspaceDir??"",pluginConfig:e.pluginConfig??{}}),onAfterToolResult:(u,p,f)=>qYe(u,{...p,workspaceDir:p.workspaceDir??""},f)});e.on("before_prompt_build",dp("hook:before_prompt_build",e.logger,async(u,p)=>{let f=Xf(p,e,"before_prompt_build");if(!f.ok){e.logger.error(`[PD:before_prompt_build] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped \u2014 no mutation will occur. NextAction: ${f.nextAction}`);return}let m=f.workspaceDir;f.consistencyWarning&&e.logger.warn(`[PD:before_prompt_build] ${f.consistencyWarning}`);try{if(!L9e.has(m)){L9e.add(m),A9e(e,m),P9e(e,m),XXe(e,m,a),$e.log(m,"SYSTEM_BOOT",`Principles Disciple online. Language: ${a}`);let I=lun(m,e.logger);I.shouldStart?(M4.api=e,M4.start({config:e.config,workspaceDir:m,stateDir:W4.join(m,".state"),logger:e.logger}),e.logger.info(`[PD] EvolutionWorker started for workspace: ${m} (flag source: ${I.flagSource})`)):(e.logger.info(`[PD] EvolutionWorker NOT started for workspace: ${m}. ${I.disabledInfo}`),$e.log(m,"EVOLUTION_WORKER_DISABLED",I.disabledInfo??""));let E=uun(m,e.logger);E.shouldStart?(Yce.start({config:e.config,workspaceDir:m,stateDir:W4.join(m,".state"),logger:e.logger}),e.logger.info(`[PD] CorrectionObserver started for workspace: ${m} (flag source: ${E.flagSource})`)):(e.logger.info(`[PD] CorrectionObserver NOT started for workspace: ${m}. ${E.disabledInfo}`),$e.log(m,"CORRECTION_OBSERVER_DISABLED",E.disabledInfo??""));let R=dun(m,e.logger);R.shouldStart?(Xce.start({config:e.config,workspaceDir:m,stateDir:W4.join(m,".state"),logger:e.logger}),e.logger.info(`[PD] InternalizationAutoConsumer started for workspace: ${m} (flag source: ${R.flagSource})`)):(e.logger.info(`[PD] InternalizationAutoConsumer NOT started for workspace: ${m}. ${R.disabledInfo}`),$e.log(m,"INTERNALIZATION_CONSUMER_DISABLED",R.disabledInfo??"")),r7e(m,e.logger)}let y={...p,workspaceDir:m},b=i(m).enabled?await c.dispatchBeforePromptBuild(u,y):await Vse(u,{...y,api:e});return rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_prompt_build",sessionId:p.sessionId}),b}catch(y){rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_prompt_build",sessionId:p.sessionId,error:String(y)}),e.logger.error(`[PD] Error in before_prompt_build: ${String(y)}`)}})),e.on("before_tool_call",dp("hook:before_tool_call",e.logger,(u,p)=>{let f=Xf(p,e,"before_tool_call");if(!f.ok){e.logger.error(`[PD:before_tool_call] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped \u2014 security gate bypassed. NextAction: ${f.nextAction}`);return}let m=f.workspaceDir;f.consistencyWarning&&e.logger.warn(`[PD:before_tool_call] ${f.consistencyWarning}`);try{let y=e.pluginConfig??{},{logger:_}=e,b={...p,workspaceDir:m,pluginConfig:y,logger:_};if(!i(m).enabled){let E=Jse(u,b);return rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_tool_call"},{flushImmediately:!0}),E}return c.dispatchBeforeToolCall(u,b).then(E=>(rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_tool_call"},{flushImmediately:!0}),E)).catch(E=>{let R=E instanceof Error?E.message.slice(0,500):bp(E).slice(0,500);rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_tool_call",error:R},{flushImmediately:!0}),e.logger.error(`[PD] Error in before_tool_call: ${R}`)})}catch(y){rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"before_tool_call",error:String(y)},{flushImmediately:!0}),e.logger.error(`[PD] Error in before_tool_call: ${String(y)}`)}})),e.on("after_tool_call",dp("hook:after_tool_call",e.logger,(u,p)=>{let f=Xf(p,e,"after_tool_call");if(!f.ok){e.logger.error(`[PD:after_tool_call] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped \u2014 pain detection bypassed. NextAction: ${f.nextAction}`);return}let m=f.workspaceDir;f.consistencyWarning&&e.logger.warn(`[PD:after_tool_call] ${f.consistencyWarning}`);try{let y=e.pluginConfig??{},_={...p,workspaceDir:m,pluginConfig:y};if(!i(m).enabled){Gse(u,_,e),rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"after_tool_call"},{flushImmediately:!0});return}if(u.toolName==="pain"||u.toolName==="skill:pain"){Gse(u,_,e),rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"after_tool_call"},{flushImmediately:!0});return}return c.dispatchAfterToolCall(u,_).then(()=>{rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"after_tool_call"},{flushImmediately:!0})}).catch(I=>{let E=I instanceof Error?I.message.slice(0,500):bp(I).slice(0,500);rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"after_tool_call",error:E},{flushImmediately:!0}),e.logger.error(`[PD:EmpathyObserver] Error in after_tool_call: ${E}`)})}catch(y){rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"after_tool_call",error:String(y)},{flushImmediately:!0}),e.logger.error(`[PD:EmpathyObserver] Error in after_tool_call: ${String(y)}`)}}),{timeoutMs:1e4}),e.on("llm_output",dp("hook:llm_output",e.logger,(u,p)=>{let f=Xf(p,e,"llm_output");if(!f.ok){e.logger.error(`[PD:llm_output] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped \u2014 LLM analysis bypassed. NextAction: ${f.nextAction}`);return}let m=f.workspaceDir;f.consistencyWarning&&e.logger.warn(`[PD:llm_output] ${f.consistencyWarning}`);try{mJe(u,{...p,workspaceDir:m}),rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"llm_output",sessionId:p.sessionId})}catch(y){rt.fromHookContext({workspaceDir:m}).eventLog.recordHookExecution({hook:"llm_output",sessionId:p.sessionId,error:String(y)}),e.logger.error(`[PD] Error in llm_output: ${String(y)}`)}}),{timeoutMs:1e4}),e.on("before_reset",dp("hook:before_reset",e.logger,(u,p)=>{let f=Xf(p,e,"before_reset");if(!f.ok){e.logger.error(`[PD:before_reset] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped. NextAction: ${f.nextAction}`);return}return f.consistencyWarning&&e.logger.warn(`[PD:before_reset] ${f.consistencyWarning}`),lJe(u,{...p,workspaceDir:f.workspaceDir})})),e.on("before_compaction",dp("hook:before_compaction",e.logger,(u,p)=>{let f=Xf(p,e,"before_compaction");if(!f.ok){e.logger.error(`[PD:before_compaction] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped. NextAction: ${f.nextAction}`);return}return f.consistencyWarning&&e.logger.warn(`[PD:before_compaction] ${f.consistencyWarning}`),uJe(u,{...p,workspaceDir:f.workspaceDir})})),e.on("after_compaction",dp("hook:after_compaction",e.logger,(u,p)=>{let f=Xf(p,e,"after_compaction");if(!f.ok){e.logger.error(`[PD:after_compaction] workspaceDir resolution failed. reason=${f.reason} agentId=${p.agentId??"(missing)"} sessionId=${p.sessionId??"(missing)"}. Hook skipped. NextAction: ${f.nextAction}`);return}return f.consistencyWarning&&e.logger.warn(`[PD:after_compaction] ${f.consistencyWarning}`),dJe(u,{...p,workspaceDir:f.workspaceDir})})),e.on("before_message_write",dp("hook:before_message_write",e.logger,(u,p)=>{let f=Xf(p,e,"before_message_write");if(!f.ok){e.logger.warn(`[PD:before_message_write] workspaceDir resolution failed: ${f.reason}`);return}try{yJe(u,{...p,workspaceDir:f.workspaceDir,pluginConfig:TK(e.config,e.id)})}catch(m){e.logger.warn(`[PD:before_message_write] error: ${String(m)}`)}}));try{let u=cx("service:correction-observer",Yce,e.logger);u&&e.registerService(u);let p=cx("service:trajectory",y9e,e.logger);p&&e.registerService(p);let f=cx("service:pd-task",k9e,e.logger);f&&e.registerService(f);let m=cx("service:internalization-auto-consumer",Xce,e.logger);m&&e.registerService(m)}catch(u){e.logger.error(`[PD] Failed to register services: ${String(u)}`)}let l=(u,p,f,m,y)=>{let _={name:u,description:f,handler:m,...y?.acceptsArgs?{acceptsArgs:!0}:{}};e.registerCommand(_),p&&e.registerCommand({..._,name:p,description:`${f} (alias of /${u})`})};l("pd-init","pdi",Ta("pd-init",a),u=>_Je(u)),l("pd-bootstrap","pdb",Ta("pd-bootstrap",a),u=>xJe(u)),l("pd-research","pdr",Ta("pd-research",a),u=>bJe(u)),l("pd-help","pdh",Ta("pd-help",a),()=>a==="zh"?{text:`
3167
3171
  \u{1F4D6} **Principles Disciple \u547D\u4EE4\u5927\u5168**