principles-disciple 1.236.0 → 1.236.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1051,7 +1051,7 @@ CONSTRAINTS:
1051
1051
  - evidence: list all evidence items that support your analysis. If sourceRefs or diagnosisTarget.evidence
1052
1052
  were provided in the input, you MUST reference them here. Only leave empty if the input genuinely
1053
1053
  contains no evidence at all.
1054
- ${c}${l}`}var N2=class{adapter;schema;constructor(t={}){this.adapter=t.adapter??new Cd,this.schema=t.schema??hu}buildRootCauseInstruction(t={}){return PDt({adapter:t.adapter??this.adapter,schema:t.schema??this.schema,outputLanguage:t.outputLanguage,coreGrounding:t.coreGrounding,intentGrounding:t.intentGrounding,evidenceFirstAttribution:t.evidenceFirstAttribution})}buildPrompt(t,n={}){let r=n.limits??mCe,{outputLanguage:i,coreGrounding:o,intentGrounding:s,intentDoc:a,evidenceFirstAttribution:c}=n,l=[],u=t.conversationWindow,d=u.slice(0,r.maxConversationEntries);u.length>r.maxConversationEntries&&l.push(`conversationWindow truncated from ${u.length} to ${r.maxConversationEntries} entries`);let p=d.map(x=>x.text&&x.text.length>r.maxEntryTextChars?{...x,text:x.text.slice(0,r.maxEntryTextChars)+"...[truncated]"}:x),m={...t,conversationWindow:p},g=this.buildRootCauseInstruction({outputLanguage:i,coreGrounding:o,intentGrounding:s,evidenceFirstAttribution:c}),A={taskId:t.taskId,contextHash:t.contextHash,diagnosisTarget:t.diagnosisTarget,conversationWindow:p,sourceRefs:t.sourceRefs,context:m,...l.length>0?{truncationWarnings:l}:{},...s&&a?{intentDoc:a}:{}},_=JSON.stringify(A);if(_.length>r.maxMessageChars){let x=[...p],v=0,k=T=>(A.conversationWindow=x,A.context={...m,conversationWindow:x},A.truncationWarnings=[...l,T>0?`payload truncated due to size (dropped ${T} conversationWindow entries; limit ${r.maxMessageChars} chars)`:`payload exceeds maxMessageChars (${_.length} > ${r.maxMessageChars} chars); no conversationWindow entries left to drop`],JSON.stringify(A));do x.length>0&&(x=x.slice(0,-1),v+=1),_=k(v);while(x.length>0&&_.length>r.maxMessageChars)}return{message:_,promptInput:A,systemPrompt:g}}};ka();var C_=["core","quiet","gone","legacy_retire"],VO=["owner","system"],Ob=["openclaw","pi-ai"],Rc=["diagnostician","dreamer","philosopher","scribe","artificer","evaluator","rolloutReviewer","correctionObserver","empathyObserver","signalCollector"],S_=["simple","advanced"],YO=["production","development","demo","test"],P2=["low","medium","high"],L2=["realtime","async"],Nb=["smoke","unit","full"],zO=["full","summary","off"],ys=new Set(["__proto__","constructor","prototype"]);var B9=new Set(["__proto__","constructor","prototype"]),Pb={pain_evidence_admission:"painEvidenceAdmission",pain_evidence_admission_default:"painEvidenceAdmissionDefault"};function hCe(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"enabled")){let{enabled:t}=e;if(typeof t=="boolean")return t}}function M2(e){let t={},n=[];for(let r of Object.keys(e))B9.has(r)&&n.push(`flag '${r}': dangerous key rejected`);for(let r of Object.keys(e))B9.has(r)||Object.hasOwn(Pb,r)||(t[r]=e[r]);for(let r of Object.keys(e)){if(B9.has(r))continue;let i=Object.hasOwn(Pb,r)?Pb[r]:void 0;i!==void 0&&!Object.hasOwn(e,i)&&(t[i]=e[r])}for(let[r,i]of Object.entries(Pb))if(Object.hasOwn(e,r)&&Object.hasOwn(e,i)){let o=hCe(e[r]),s=hCe(e[i]);o!==s&&n.push(`feature '${i}': conflicting values for canonical ID and alias '${r}' \u2014 canonical value used (enabled=${String(s)})`)}return{normalized:t,warnings:n}}var B2=[{id:"prompt",category:"core",enabled:!0,since:"2026-05-24",description:"Prompt injection for principle application"},{id:"code_tool_hook",category:"core",enabled:!0,since:"2026-05-24",description:"Code tool hook for rule host enforcement"},{id:"rulecode_safety_controls",category:"core",enabled:!0,since:"2026-08-21",description:"Durable RuleCode safety isolation authority. Default ON; emergency enforcement shutdown remains the code_tool_hook core flag."},{id:"rulecode_owner_live_decision",category:"core",enabled:!0,since:"2026-08-21",description:"Owner-reviewed RuleCode shadow-to-live decision authority. Default ON after the readiness, authenticated Console, CLI, audit, and rollback rollout gates passed; flag-off refuses promotion."},{id:"defer_archive",category:"core",enabled:!0,since:"2026-05-24",description:"Defer/archive activation writer"},{id:"correction_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Optional LLM optimization service for correction keywords; synchronous correction detection remains active independently"},{id:"signal_collector",category:"quiet",enabled:!1,since:"2026-06-30",description:"Unified signal collection host (correction + empathy upstream merge). NOTE: keyword detection (high-precision phrases) runs regardless of this flag; this flag only gates the LLM deep-judgment path (ambiguous terms / missed keywords). Quiet flag: dogfood-only until validated."},{id:"internalization_auto_consumer",category:"quiet",enabled:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381; quiet flag, default on, disableable via config)"},{id:"internalization_full_chain",category:"core",enabled:!0,since:"2026-08-12",description:"PRI-419 amendment: auto-consumer advances dreamer\u2192\u2026\u2192evaluator\u2192rollout_reviewer (full chain) so artifacts reach validated and the approval queue is populated unattended. The human gate is the approval queue (Console), not the rollout_reviewer CLI trigger. Default ON; flag-off = dreamer-only."},{id:"story_a_approval_completion",category:"quiet",enabled:!0,since:"2026-06-18",description:"Story A approval-completion orchestrator (PRI-408) \u2014 formal service replacing demo direct-writer activation; quiet flag, default on, disableable via config"},{id:"feedback_channel",category:"quiet",enabled:!0,since:"2026-06-01",description:"MVP seed feedback channel \u2014 privacy-preserving report drafts. PRI-543: flag scope extended to also cover the feedback SUBMIT ladder (ingest relay / gh CLI / mailto / export-file channels + submit endpoints). Flag-off = submit endpoints 403 + submit UI hidden; config `feedback:` segment and channel parameters still available."},{id:"release_manager_shadow",category:"quiet",enabled:!0,since:"2026-08-25",description:"ReleaseManager governance for the update surface \u2014 signed-metadata checks with legacy comparison; graduated default-on 2026-09-07 (Owner decision). Rollback = set enabled:false."},{id:"release_manager_write_authority",category:"quiet",enabled:!0,since:"2026-09-06",description:"PRI-698 Phase 1 \u2014 ReleaseManager.apply() serves Console /apply-full (installer + journal deployment); graduated default-on 2026-09-07 (Owner decision) with pre-transaction legacy fallback; flag-off = legacy console updater with explicit release_manager_write_disabled fallback reason"},{id:"gfi",category:"quiet",enabled:!1,since:"2026-05-24",description:"Global Friction Index session scoring"},{id:"evolution_worker",category:"quiet",enabled:!1,since:"2026-06-01",description:"Legacy evolution worker heartbeat (MVP-Quiet per ADR-0014 \xA72.5)"},{id:"empathy_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking (MVP-Quiet)"},{id:"painEvidenceAdmission",category:"quiet",enabled:!0,since:"2026-06-06",description:"Pre-diagnosis evidence triage for pain signals (PEAT-B1). PRI-454: default-on, Gate B is primary gate."},{id:"painEvidenceAdmissionDefault",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Global kill switch for Gate B migration. When ON (default), Gate B (TriggerController) owns admission. When OFF (rollback), Gate A (PainDiagnosticGate) is re-activated."},{id:"diagnostician_async_cli",category:"quiet",enabled:!1,since:"2026-06-11",description:"Async pain-record CLI \u2014 submit and return immediately, diagnosis runs in background. Default: false until orchestrator exists."},{id:"diagnostician_core_grounding",category:"quiet",enabled:!0,since:"2026-06-11",description:"Core principle grounding in diagnostician prompt (Arm 2)"},{id:"internalization_core_grounding",category:"quiet",enabled:!0,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders (dreamer, philosopher, scribe)"},{id:"diagnostician_split_pipeline",category:"quiet",enabled:!0,since:"2026-06-11",description:"3-stage split diagnostician pipeline (RootCause\u2192Distiller\u2192Router)"},{id:"diagnostician_llm_degradation",category:"quiet",enabled:!0,since:"2026-07-03",description:"Diagnostician LLM rate-limit graceful degradation \u2014 on persistent rate-limit, emit diag_llm_rate_limit_degraded telemetry + rate_limit errorCategory instead of max_attempts_exceeded (ADR-0019). Default ON (graduated PRI-571, 2026-08-24); flag-off = hard fail (legacy behavior)."},{id:"l2_dreamer",category:"quiet",enabled:!1,since:"2026-06-16",description:"L2 multi-turn agent loop for the dreamer runner (PRI-419) \u2014 read-only tools + submit_output, scoped to dreamer only"},{id:"code_rule_capability",category:"core",enabled:!0,since:"2026-06-18",description:"Code-rule capability (atomic: ArtificerL2 + Evaluator) for RuleHost pipeline \u2014 MVP-Core, default ON (PRI-435)"},{id:"intent_engineering",category:"quiet",enabled:!1,since:"2026-06-25",description:"INTENT.md-grounded constructive friction and Stage-A intent tension diagnosis (PRI-465). Default off; flag-off = no INTENT read, no prompt injection, no intentTension."},{id:"rulecode_context_v2",category:"quiet",enabled:!1,since:"2026-06-27",description:"RuleContext v2 \u2014 rule-code context vision (PRI-479). Foundation flag; default off, v1 rule behavior unchanged. See docs/superpowers/specs/2026-06-27-rulecode-context-vision-design.md"},{id:"failed_tasks_observability",category:"quiet",enabled:!0,since:"2026-07-04",description:"Failed tasks observability \u2014 list/view failed pipeline tasks"},{id:"evaluator_artificer_repair_loop",category:"quiet",enabled:!0,since:"2026-07-04",description:"PRI-509/P0-D: Evaluator\u2192Artificer repair loop \u2014 auto-seed artificer repair on needs_revision (2-round cap \u2192 needs_human_review). Default ON (INV-02 liveness); production-wired in auto-consumer since 2026-08-18."},{id:"artificer_output_retry",category:"quiet",enabled:!0,since:"2026-08-20",description:"Issue 2/PRI-621: retry Artificer `output_invalid` (malformed LLM output, e.g. missed submit_rulecode) via the base retry policy (max 3 attempts) instead of permanent failure. Graduated default-on 2026-08-29 \u2014 aligns artificer with every other peer runner; flag-off reverts output_invalid to permanent (legacy)."},{id:"artifact_summary_redundancy",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 0 \u2014 writer-side ArtifactSummary + predecessorSummary envelope on all 8 SummaryRunnerKind stages. Default off; flag-off = current contentJson shape unchanged."},{id:"context_manifest_budget",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 1 \u2014 manifest + budget-driven context injection with information-floor fallback. Default off; flag-off = existing buildContext assembly unchanged."},{id:"progressive_evaluator",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 2 \u2014 two-stage evaluation with flagged criteria + painCoverage/compressionFidelity output fields. Default off; flag-off = single-stage evaluation unchanged."},{id:"host.codex",category:"core",enabled:!0,since:"2026-08-11",description:"ADR-0020: Codex CLI host adapter. Default ON (flipped 2026-08-12 after PRI-282 E2E). Flag-off = pd-hook.js outputs {} + exit 0 + SystemLogger records skip (rc-9). Disable via .pd/config.yaml: host.codex: { enabled: false }."},{id:"abstraction_layer_v1",category:"quiet",enabled:!1,since:"2026-08-13",description:"PRI-523 shared host-runtime cutover for OpenClaw. Default OFF preserves the legacy route; enable only for controlled parity validation."},{id:"principle_receipt_block_copy",category:"quiet",enabled:!0,since:"2026-08-15",description:"Principle Receipt P0 \u2014 enriched RuleHost block copy with principle attribution (title/approval date/source summary, PRI-530). Default ON (graduated PRI-571, 2026-08-24); flag-off = generic block template unchanged."},{id:"principle_receipt_ledger",category:"quiet",enabled:!0,since:"2026-08-15",description:"Principle Receipt ledger \u2014 durable principle_applications history (effect/presence two-level semantics, PRI-531). Default ON (graduated PRI-571, 2026-08-24); flag-off = no ledger writes."},{id:"principle_receipt_self_report",category:"quiet",enabled:!1,since:"2026-08-16",description:"Principle Receipt P1-a \u2014 agent self-report \u{1F4CC} line (injection instruction + capture, PRI-532). Default off; flag-off = directive template unchanged, no capture."},{id:"principle_governance_projection_v2",category:"quiet",enabled:!0,since:"2026-08-20",description:"Read-only per-principle Owner governance projection (PRI-549). Default ON (graduated PRI-571, 2026-08-24); flag-off preserves the pre-projection Principle Detail experience."},{id:"failed_task_recovery_console",category:"quiet",enabled:!0,since:"2026-08-23",description:"Governance Recovery Actions v1 \u2014 Owner-triggered recovery of failed / needs_human_review tasks from Console (failed\u2192pending via RecoverySweepService; needs_human_review\u2192pending via owner authority reset). Default on (2026-08-24 owner decision); flag-off = Console read-only."},{id:"pain_diagnosis_persistence",category:"quiet",enabled:!1,since:"2026-08-23",description:"Persist diagnostician root-cause attribution to pain_diagnoses (state.db, keyed by canonical pain_id) + Evidence First attribution rules in the Stage A prompt. Default off; flag-off = no writes, prompt byte-identical."},{id:"governance_experience_v1",category:"quiet",enabled:!0,since:"2026-08-24",description:"Governance Experience Snapshot v1.5.1 \u2014 read-only workspace governance experience (batch projection + GET /api/v1/governance/experience + Console Focus integration). Default on (graduated 2026-08-29); flag-off via config = endpoint 403 (no DB access) and legacy Focus behavior preserved."},{id:"anonymous_product_telemetry",category:"quiet",enabled:!1,since:"2026-08-26",description:"Anonymous Product Telemetry v1 \u2014 opt-in daily boolean-milestone snapshot (initialized/pain/principle/activation/receipt presence+effect), daily unlinkable IDs, zero content collection. Default off; export also requires explicit consent (pd telemetry enable) + production eligibility."},{id:"codex_conversation_ingestion",category:"quiet",enabled:!1,since:"2026-08-29",description:"Codex Governance Closure Slice A \u2014 bounded governance-observation ingestion from the authenticated Codex Stop-hook transcript (visible user/assistant/tool facts only, \u226432 turns/\u22647 days operational window, promotion substrate). Default off; flag-off = zero transcript reads, no observation writes, existing Codex behavior unchanged."},{id:"nocturnal",category:"gone",enabled:!1,since:"2026-05-24",description:"Nocturnal trinity pipeline (retired)"},{id:"idle_trigger",category:"gone",enabled:!1,since:"2026-05-24",description:"Idle trigger for background processing (retired)"},{id:"new_user_onboarding",category:"core",enabled:!0,since:"2026-07-01",description:"New user onboarding wizard \u2014 first-visit redirect to /welcome + demo story-a trigger endpoint. Maintainer-approved MVP-Core (2026-07-01): default-on; emergency disable via .pd/config.yaml: new_user_onboarding: { enabled: false }."}];var ly={};for(let e of B2)ly[e.id]={category:e.category,enabled:e.enabled};var LDt="pd.default",MDt={type:"pi-ai",provider:"",model:"",apiKeyEnv:""},gCe="openclaw.default",ACe={type:"openclaw",source:"default"},cy=gCe,F2=ACe,BDt={diagnostician:!0,dreamer:!0,philosopher:!1,scribe:!0,artificer:!0,evaluator:!1,rolloutReviewer:!1,correctionObserver:!1,empathyObserver:!1,signalCollector:!1};function JO(){let e={};for(let t of Rc)e[t]={enabled:BDt[t],runtimeProfile:cy};return{defaultRuntime:cy,agents:e}}var XO={diagnostics:{mode:"simple"}},yl={thinkingOs:!1,projectFocus:"off",evolutionContext:{enabled:!0,maxMessages:4,maxCharsPerMessage:200}};function U2(){return{version:1,features:{...ly},runtimeProfiles:{[LDt]:{...MDt},[gCe]:{...ACe}},internalAgents:JO(),ui:{...XO},principles:{outputLanguage:void 0},contextInjection:void 0}}var F9=["prompt","code_tool_hook","defer_archive"];function li(e){let{config:t}=e,n=[],r={};for(let[o,s]of Object.entries(ly))r[o]={id:o,category:s.category,enabled:s.enabled};for(let[o,s]of Object.entries(t.features))if(!ys.has(o)&&s)if(Object.hasOwn(r,o)){let a=r[o];if(!a)continue;if(a.category==="gone"&&s.enabled){n.push(`feature '${o}': gone flag cannot be re-enabled`);continue}if(a.category==="core"&&!s.enabled){n.push(`feature '${o}': core flag explicitly disabled via config (emergency disable)`),r[o]={id:o,category:a.category,enabled:!1,...s.source?{source:s.source}:{}};continue}r[o]={id:o,category:s.category,enabled:s.enabled,...s.source?{source:s.source}:{}}}else n.push(`feature '${o}': unknown flag ignored (not a registered capability)`);let i=[];for(let o of F9){let s=r[o];s&&s.enabled&&i.push(o)}return{flags:r,enabledChannels:i,warnings:n}}function Is(e,t){return Object.hasOwn(e.flags,t)?e.flags[t]?.enabled??!1:!1}var Q2="<redacted-path>",am="[REDACTED]";var FDt=/(?:[A-Za-z]:[\\/](?:[^\\\s/:*?"<>|]+[\\/])+[^\\\s/:*?"<>|]*)/g,UDt=/(?<![a-zA-Z0-9_.])[\\/](?:usr|home|Users|var|opt|etc|tmp|root|run|mnt|media|srv|boot|dev|proc|sys)(?:[\\/][^\\\s/:*?"<>|]+)+/g;function cm(e){return typeof e!="string"?e:e.replace(FDt,Q2).replace(UDt,Q2)}var QDt=/\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}\b/g,$Dt=/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/g,WDt=/\blin_api_[A-Za-z0-9_-]{16,}\b/g,GDt=/(Authorization\s*:\s*)(["'])?([A-Za-z]+\s+)?([^\s"';,]+)/gi,qDt=/(\$env:\s*[A-Z_][A-Z0-9_]{2,}\s*=\s*")([^"]*)(")/gi,HDt=/\b(api[_-]?key|token|secret|password|auth(?:_?token)?)\s*[:=]\s*['"]?([^\s'",}{]+)['"]?/gi,jDt=/\bBearer\s+[A-Za-z0-9._\-+/=]{8,}\b/g;function lm(e){return typeof e!="string"?e:e.replace(QDt,am).replace($Dt,am).replace(WDt,am).replace(GDt,"$1$2$3[REDACTED]").replace(qDt,"$1[REDACTED]$3").replace(jDt,am).replace(HDt,(t,n)=>`${n}=${am}`)}var KDt=/\b([A-Z_][A-Z0-9_]{2,})\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s,;}{]+))/g;function um(e){return typeof e!="string"?e:e.replace(KDt,(t,n)=>`${n}=${am}`)}function tg(e){if(typeof e!="string")return e;let t=cm(e);return t=lm(t),t=um(t),t}var VDt=new Set(["password","passwd","secret","token","api","apikey","authorization","auth","credential","credentials","private","key"]);function YDt(e){return e.toLowerCase().split(/[_\-.]/g).filter(t=>t.length>0)}function yCe(e){let t=YDt(e);if(t.length===0)return!1;for(let n of t)if(VDt.has(n))return!0;return!1}var zDt=6,ICe=100,U9=2e3;function $2(e,t){if(e===null)return{ok:!0,value:null,notes:[]};if(e===void 0)return{ok:!0,value:void 0,notes:[]};let n=typeof e;if(n==="string"){let i=e,o=i;return i=cm(i),i=lm(i),i=um(i),i!==o&&t.notes.push("string value redacted (path/token/env)"),i.length>U9&&(i=i.slice(0,U9)+"\u2026",t.notes.push(`string truncated to ${U9} chars`)),{ok:!0,value:i,notes:t.notes}}if(n==="bigint")return{ok:!0,value:`<bigint:${e.toString()}>`,notes:[]};if(n!=="object")return{ok:!0,value:e,notes:[]};if(t.depth>=zDt)return{ok:!0,value:"<deep>",notes:[]};let r=e;if(t.seen.has(r))return t.notes.push("circular reference detected"),{ok:!0,value:"<circular>",notes:[]};t.seen.add(r);try{if(Array.isArray(e)){let a=[];for(let c=0;c<e.length;c++){let l=$2(e[c],{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!l.ok)return l;a.push(l.value)}return{ok:!0,value:a,notes:[]}}let i=e,o={},s=Object.keys(i).slice(0,ICe);for(let a of s){if(yCe(a)){o[a]=am,t.notes.push(`field "${a}" redacted`);continue}let c=i[a];if(c!==null&&typeof c=="object"&&t.seen.has(c)){t.notes.push(`circular reference detected at "${a}"`),o[a]="<circular>";continue}let l=$2(c,{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!l.ok)return l;o[a]=l.value}return{ok:!0,value:o,notes:[]}}finally{t.seen.delete(r)}}function JDt(e){let t=[],n=[],r={seen:new WeakSet,depth:0,notes:t};r.seen.add(e);for(let i=0;i<e.length;i++){let o=e[i];if(o!==null&&typeof o=="object"&&r.seen.has(o)){t.push("circular reference detected in array"),n.push("<circular>");continue}let s=$2(o,r);if(!s.ok)return s;n.push(s.value)}return{ok:!0,value:n,notes:t}}function XDt(e){let t=e,n=[],r={seen:new WeakSet,depth:0,notes:n};r.seen.add(e);let i={},o=Object.keys(t).slice(0,ICe);for(let s of o){if(yCe(s)){i[s]=am,n.push(`field "${s}" redacted`);continue}let a=t[s];if(a!==null&&typeof a=="object"&&r.seen.has(a)){n.push(`circular reference detected at "${s}"`),i[s]="<circular>";continue}let c=$2(a,r);if(!c.ok)return c;i[s]=c.value}return{ok:!0,value:i,notes:n}}function ZO(e){if(e===null)return{ok:!1,error:"redactSensitiveFields: null is not a redactable object",nextAction:"pass a JSON object or array; null carries no fields to redact"};if(e===void 0)return{ok:!1,error:"redactSensitiveFields: undefined is not a redactable object",nextAction:"pass a JSON object or array; undefined carries no fields to redact"};let t=typeof e;return t!=="object"?{ok:!1,error:`redactSensitiveFields: top-level value must be an object or array (got ${t})`,nextAction:"pass a JSON object or array; for primitive values use redactTokenLikeValues / redactEnvLikeValues / redactAbsolutePaths"}:Array.isArray(e)?JDt(e):XDt(e)}var ECe="\u2026[canonical-json-truncated]";function eN(e,t=new WeakSet){if(e===null)return"null";let n=typeof e;if(n==="string")return JSON.stringify(e);if(n==="number")return Number.isFinite(e)?String(e):"null";if(n==="boolean")return String(e);if(n==="bigint")return JSON.stringify(`${String(e)}n`);if(n==="undefined"||n==="function"||n==="symbol")return"null";if(Array.isArray(e)){if(t.has(e))return'"[Circular]"';t.add(e);let r=e.map(i=>eN(i,t));return t.delete(e),`[${r.join(",")}]`}if(e instanceof Date)return JSON.stringify(Number.isNaN(e.getTime())?null:e.toISOString());if(e instanceof Map){if(t.has(e))return'"[Circular]"';t.add(e);let i=[...e.entries()].map(([o,s])=>[String(o),s]).sort(([o],[s])=>o<s?-1:o>s?1:0).map(([o,s])=>`${JSON.stringify(o)}:${eN(s,t)}`).join(",");return t.delete(e),`{${i}}`}if(e instanceof Set){if(t.has(e))return'"[Circular]"';t.add(e);let r=[...e.values()].map(i=>eN(i,t));return t.delete(e),`[${r.join(",")}]`}if(n==="object"){let r=e;if(t.has(r))return'"[Circular]"';t.add(r);let i=Object.keys(r).sort((s,a)=>s<a?-1:s>a?1:0),o=[];for(let s of i){let a=eN(r[s],t),c=r[s],l=typeof c;c===void 0||l==="function"||l==="symbol"||o.push(`${JSON.stringify(s)}:${a}`)}return t.delete(r),`{${o.join(",")}}`}return'"[Unserializable]"'}function ZDt(e){let t=eN(e);if(t.length<=262144)return{text:t,truncated:!1};let n=262144-ECe.length;return{text:`${t.slice(0,Math.max(0,n))}${ECe}`,truncated:!0}}function Q9(e,t){return t(ZDt(e).text)}var uy=["diag_rootcause","diag_distiller","diag_router","dreamer","philosopher","scribe","artificer","evaluator"],q2=1,$9=200,eOt=600;function T_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tOt(e){return uy.includes(e)}function so(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n!="string"||n.trim()===""?null:n}function Lb(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return T_(n)?n:null}function Mb(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return Array.isArray(n)?n:null}function W2(e,t){let n=Mb(e,t);if(n===null)return null;let r=n.filter(i=>typeof i=="string"&&i.trim()!=="");return r.length===0?null:r.join(" / ")}function nOt(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?String(n):null}function rOt(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="boolean"?String(n):null}function G2(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function tN(e){let n=/^[\s\S]*?[。;;.]/.exec(e)?.[0]??e;return G2(n.trim(),$9)}function W9(e){let t=e.filter(n=>n!==null&&n.trim()!=="");return t.length===0?null:G2(t.join("; "),$9)}function iOt(e){let t=so(e,"rootCause");return{headlineSource:t===null?null:tN(t),resolved:{rootSymptom:so(e,"summary"),category:so(e,"rootCauseCategory"),severity:null,rootCause:t}}}function oOt(e){let t=so(e,"abstractedPrinciple");return{headlineSource:t===null?null:tN(t),resolved:{rootCause:so(e,"rationale"),affectedComponents:null,category:so(e,"scope"),severity:null}}}function sOt(e){let t=so(e,"summary"),r=(Mb(e,"violatedPrinciples")??[]).map(s=>so(s,"principleId")).filter(s=>s!==null),i=Mb(e,"recommendations")??[],o=i.length>0?so(i[0],"kind"):null;return{headlineSource:W9([t,o]),resolved:{rootCause:so(e,"rootCause"),affectedComponents:r.length>0?r.join(" / "):null,rootSymptom:t,category:o,severity:null}}}function aOt(e){let t=Mb(e,"candidates")??[],n=t.length>0?t[0]:null,r=so(n,"betterDecision");return{headlineSource:r===null?null:tN(r),resolved:{badDecision:so(n,"badDecision"),betterDecision:r,rationale:so(n,"rationale"),riskLevel:so(n,"riskLevel"),strategicPerspective:so(n,"strategicPerspective")}}}function cOt(e){let t=Lb(e,"principleCandidate"),n=so(t,"title");return{headlineSource:n,resolved:{thesis:so(e,"thesis"),principleTitle:n,principleScope:so(t,"scope"),principleConfidence:nOt(t,"confidence")}}}function lOt(e){let t=Lb(e,"principleDraft"),n=so(t,"statement"),r=Lb(e,"intentContract");return{headlineSource:n===null?null:tN(n),resolved:{principleText:n,scope:W2(t,"applicability"),exceptions:W2(t,"antiPatterns"),intentOwner:so(r,"ownerIntent"),intentForbidden:so(r,"forbiddenBehavior"),intentValidation:so(r,"validationExpectation")}}}function uOt(e){let t=W2(e,"affectedTools"),n=so(e,"implementationSummary"),r=Mb(e,"affectedTools")?.length??null;return{headlineSource:W9([r!==null?`${r} affected tools`:null,n===null?null:tN(n)]),resolved:{changedFiles:t,apiSurface:n,risks:W2(e,"risks")}}}function dOt(e){let t=Lb(e,"evaluation"),n=so(t,"decision"),r=Mb(t,"concerns"),i=r===null?null:String(r.length),o=Lb(e,"codeReview"),s=Lb(o,"intentConsistency");return{headlineSource:W9([n===null?null:`verdict=${n}`,i===null?null:`concerns=${i}`]),resolved:{verdict:n,concernCount:i,intentConsistency:rOt(s,"aligned")}}}var pOt={diag_rootcause:iOt,diag_distiller:oOt,diag_router:sOt,dreamer:aOt,philosopher:cOt,scribe:lOt,artificer:uOt,evaluator:dOt};function Bb(e,t){if(!tOt(e))return{ok:!1,reason:"unsupported_runner_kind",detail:`Unsupported SummaryRunnerKind: ${String(e)}`};if(!T_(t))return{ok:!1,reason:"output_not_object",detail:`validatedOutput for runnerKind "${e}" is not a non-null object`};let n=pOt[e],{headlineSource:r,resolved:i}=n(t),o={},s=[];for(let[a,c]of Object.entries(i))c!==null?o[a]=G2(c,eOt):s.push(a);return r===null&&Object.keys(o).length===0?{ok:!1,reason:"no_derivable_field",detail:`No derivable headline or field for runnerKind "${e}" from the given output`}:{ok:!0,value:{schemaVersion:q2,runnerKind:e,headline:r===null?"":G2(r,$9),fields:o,derivedFrom:"structured_output",omittedFields:s}}}function fOt(e){if(e===null||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"summary"))return null;let{summary:t}=e;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;if(!Object.hasOwn(n,"schemaVersion")||n.schemaVersion!==q2||!Object.hasOwn(n,"runnerKind")||typeof n.runnerKind!="string"||!uy.includes(n.runnerKind)||!Object.hasOwn(n,"headline")||typeof n.headline!="string"||!Object.hasOwn(n,"fields")||n.fields===null||typeof n.fields!="object"||Array.isArray(n.fields))return null;let r=n.fields;return!Object.values(r).every(i=>typeof i=="string")||!Object.hasOwn(n,"derivedFrom")||n.derivedFrom!=="structured_output"||!Object.hasOwn(n,"omittedFields")||!Array.isArray(n.omittedFields)||!n.omittedFields.every(i=>typeof i=="string")?null:{schemaVersion:q2,runnerKind:n.runnerKind,headline:n.headline,fields:r,derivedFrom:"structured_output",omittedFields:n.omittedFields}}function _Ce(e,t,n,r,i){let o=Bb(e,t);if(!o.ok)return i({type:"artifact_summary_skipped",runnerKind:e,reason:o.reason}),{};let s={summary:o.value};if(n===null)return i({type:"artifact_summary_predecessor_absent",runnerKind:e,reason:"no_predecessor_in_context"}),s;let a=fOt(n.contentJson);if(a===null){let c=Bb(n.runnerKind,n.contentJson);if(!c.ok)return i({type:"artifact_summary_predecessor_skipped",runnerKind:e,reason:c.reason}),s;a=c.value}return{...s,predecessorSummary:{artifactId:n.artifactId,runnerKind:n.runnerKind,contentHash:Q9(n.contentJson,r),summary:a}}}var nN={betterDecision:"required",rationale:"required",riskLevel:"required",badDecision:"optional",strategicPerspective:"excluded"},jrr=Object.entries(nN).filter(([,e])=>e==="required").map(([e])=>e),xCe=["badDecision","betterDecision","rationale","riskLevel","strategicPerspective"];function mOt(e){if(Object.hasOwn(nN,e))return nN[e]}function vCe(e){return mOt(e)==="required"}var Fb=1;function wCe(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}var Yrr=xCe.filter(e=>nN[e]!=="excluded");function bCe(e,t){let n=t.priority.indexOf(e);if(n>=0)return n;let r=wCe([...t.tier0,...t.tier1,...t.tier2]).indexOf(e),i=r>=0?r:0;return t.priority.length+i}function k_(e){return wCe([...e.tier0,...e.tier1,...e.tier2])}function hOt(e){return Math.ceil(e.length/4)}var gOt=600,AOt=8,CCe="\u2026[budget-truncated]";function SCe(e,t,n){let r=k_(e),i=[],o=[];for(let l of r){if(!t.has(l)){o.push(l);continue}let u=wo(t.get(l),gOt);i.push({path:l,text:u,tokens:hOt(u),rank:bCe(l,e)})}i.sort((l,u)=>l.rank-u.rank||(l.path<u.path?-1:l.path>u.path?1:0));let s={},a=[],c=e.budgetTokens;for(let l of i)if(l.tokens<=c)s[l.path]=l.text,c-=l.tokens;else if(c>AOt){let u=Math.max(0,c*4-CCe.length),d=l.text.slice(0,u)+CCe;s[l.path]=d;let p={fieldPath:l.path,reason:"partially_truncated",remainingBudgetTokens:c,keptChars:d.length,droppedChars:l.text.length-d.length};a.push(p),n({type:"context_truncated",runnerKind:e.runnerKind,manifestId:e.manifestId,fieldPath:l.path,reason:p.reason,remainingBudgetTokens:c}),c=0}else{let u={fieldPath:l.path,reason:"budget_exceeded",remainingBudgetTokens:c,keptChars:0,droppedChars:l.text.length};a.push(u),n({type:"context_truncated",runnerKind:e.runnerKind,manifestId:e.manifestId,fieldPath:l.path,reason:u.reason,remainingBudgetTokens:c})}return{manifestId:e.manifestId,fields:s,truncated:a,absent:o,usedTokens:e.budgetTokens-c,budgetTokens:e.budgetTokens}}var yOt=.5;function TCe(e,t,n){let r=SCe(e,t,u=>n(u)),o=k_(e).length,s=r.absent.length,a=o>0?s/o:1,c=()=>({type:"manifest_resolution_insufficient",runnerKind:e.runnerKind,manifestId:e.manifestId,absentCount:s,declaredCount:o,absentRatio:a,fallback:"full_predecessor_injection"});return Object.keys(r.fields).length===0?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"empty_allocation",absentRatio:a}):e.tier1.length>0&&e.tier1.every(u=>r.absent.includes(u))?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"tier1_all_absent",absentRatio:a}):a>yOt?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"absent_ratio_exceeded",absentRatio:a}):{kind:"focused",allocated:r,fellBack:!1}}function rN(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kCe(e,t){if(!rN(e)||!Object.hasOwn(e,"summary"))return;let{summary:n}=e;if(!rN(n))return;if(t==="headline")return Object.hasOwn(n,"headline")?n.headline:void 0;let r=Object.hasOwn(n,"fields")?n.fields:void 0;if(rN(r)&&Object.hasOwn(r,t))return r[t];if(Object.hasOwn(n,t))return n[t]}function IOt(e,t){if(!rN(e)||!Object.hasOwn(e,"predecessorSummary"))return;let{predecessorSummary:n}=e;if(!(!rN(n)||!Object.hasOwn(n,"summary")))return kCe(n,t)}function G9(e,t){let n=e.indexOf("summary."),r=e.indexOf("predecessorSummary."),i=e.indexOf("raw.");if(!(i>=0&&(n<0||i<n)&&(r<0||i<r))){if(r>=0&&(n<0||r<n)){let o=e.slice(r+19);return IOt(t,o)}if(n>=0){let o=e.slice(n+8);return kCe(t,o)}}}function q9(e,t){let n=new Map;for(let r of e){let i=G9(r,t);i!==void 0&&n.set(r,i)}return n}var EOt=6,H2="pi-art-",_Ot="-run_";function xOt(e){if(!e.startsWith(H2))return null;let t=e.lastIndexOf(_Ot);if(t<=H2.length)return null;let n=e.slice(H2.length,t);if(n==="")return null;let r=e.slice(t+1+4),i=`${n}_`;if(!r.startsWith(i))return null;let o=r.slice(i.length);return/^(0|[1-9][0-9]*)$/.test(o)?n:null}function H9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vOt(e){if(!H9(e)||!Object.hasOwn(e,"summary"))return;let{summary:t}=e;if(H9(t)&&Object.hasOwn(t,"schemaVersion")&&t.schemaVersion===1&&Object.hasOwn(t,"runnerKind")&&typeof t.runnerKind=="string"&&uy.includes(t.runnerKind)&&Object.hasOwn(t,"headline")&&typeof t.headline=="string"&&Object.hasOwn(t,"fields")&&H9(t.fields)&&Object.values(t.fields).every(n=>typeof n=="string")&&Object.hasOwn(t,"derivedFrom")&&t.derivedFrom==="structured_output"&&Object.hasOwn(t,"omittedFields")&&Array.isArray(t.omittedFields)&&t.omittedFields.every(n=>typeof n=="string"))return{schemaVersion:1,runnerKind:t.runnerKind,headline:t.headline,fields:t.fields,derivedFrom:"structured_output",omittedFields:t.omittedFields}}var iN=class{artifacts;tasks;maxDepth;emit;cache=new Map;taskCache=new Map;constructor(t){this.artifacts=t.artifacts,this.tasks=t.tasks,this.maxDepth=t.maxDepth??EOt,this.emit=t.emit??(()=>{})}async resolve(t){return this.resolveChain(t,new Set)}async findAncestorByTaskKind(t,n){let r=await this.resolve(t);return r.ok?{ok:!0,node:r.value.nodes.find(o=>o.taskKind===n)??null,notes:r.value.notes}:{ok:!1,error:r.error}}async resolveChain(t,n){let r=[],i=[],o=new Set,s=[t],a=0;for(;s.length>0;){if(a>=this.maxDepth){let[l]=s;i.push({code:"depth_limit_reached",artifactId:l??t,detail:`maxDepth (${this.maxDepth}) reached; remaining ${s.length} ancestor(s) not traversed`}),this.emit({type:"lineage_partial",artifactId:l??t,noteCode:"depth_limit_reached",detail:`maxDepth ${this.maxDepth}`});break}let c=s.length;for(let l=0;l<c;l++){let u=s.shift();if(u===void 0)break;if(n.has(u)){i.push({code:"cycle_detected",artifactId:u,detail:`artifact ${u} already on the resolution path`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"cycle_detected",detail:"cycle detected"});continue}n.add(u);let d=await this.getArtifactCached(u);if(!d.ok)return d;let p=d.value;if(p===null){let T=await this.tryReboundInstance(u);if(!T.ok)return T;if(p=T.value,p===null){i.push({code:"ancestor_pruned",artifactId:u,detail:T.ambiguousCandidates!==void 0?`ancestor artifact ${u} not rebound: ambiguous current artifacts for source task (${T.ambiguousCandidates} same-family candidates) \u2014 refusing to pick by array order`:`ancestor artifact ${u} not found (pruned)`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"ancestor_pruned",detail:"artifact not found"});continue}}if(o.has(p.artifactId))continue;o.add(p.artifactId);let m;try{m=JSON.parse(p.contentJson)}catch{let T={kind:"content_json_unparseable",artifactId:u,detail:`contentJson of ${u} is not valid JSON`};return this.emit({type:"lineage_data_corrupt",artifactId:u,detail:T.detail,errorKind:"content_json_unparseable"}),{ok:!1,error:T}}if(typeof p.sourceTaskId!="string"||p.sourceTaskId===""){let T={kind:"artifact_shape_invalid",artifactId:u,detail:`artifact ${u} missing required sourceTaskId`};return this.emit({type:"lineage_data_corrupt",artifactId:u,detail:T.detail,errorKind:"artifact_shape_invalid"}),{ok:!1,error:T}}let g=await this.getTaskCached(p.sourceTaskId);if(!g.ok)return g;let A=g.value,_,x;A===null?(_="unknown",x="unknown",i.push({code:"task_missing",artifactId:u,detail:`task ${p.sourceTaskId} not found; cannot determine stage via two-hop`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"task_missing",detail:`task ${p.sourceTaskId} missing`})):({taskKind:_}=A,x=uy.includes(_)?_:"unknown");let v={artifactId:p.artifactId,taskId:p.sourceTaskId,taskKind:_,runnerKind:x,contentJson:m,summary:vOt(m)};r.push(v);let k=Array.isArray(p.lineageArtifactIds)?p.lineageArtifactIds:[];k.length===0&&r.length;for(let T of k)typeof T=="string"&&T!==""&&s.push(T)}a++}return{ok:!0,value:{nodes:r,complete:i.length===0,notes:i}}}async tryReboundInstance(t){let n=xOt(t);if(n===null)return{ok:!0,value:null};try{let r=await this.artifacts.listBySourceTaskId(n),i=`${H2}${n}-run_`,o=r.filter(a=>a.artifactId.startsWith(i));if(o.length!==1)return{ok:!0,value:null,...o.length>1?{ambiguousCandidates:o.length}:{}};let[s]=o;return s===void 0?{ok:!0,value:null}:(this.cache.set(t,s),this.emit({type:"lineage_edge_rebound",staleArtifactId:t,resolvedArtifactId:s.artifactId,taskId:n}),{ok:!0,value:s})}catch(r){let i={kind:"store_failure",detail:r instanceof Error?r.message:String(r)};return this.emit({type:"lineage_store_failure",detail:i.detail}),{ok:!1,error:i}}}async getArtifactCached(t){if(this.cache.has(t))return{ok:!0,value:this.cache.get(t)??null};try{let n=await this.artifacts.getArtifactById(t);return this.cache.set(t,n),{ok:!0,value:n}}catch(n){let r={kind:"store_failure",detail:n instanceof Error?n.message:String(n)};return this.emit({type:"lineage_store_failure",detail:r.detail}),{ok:!1,error:r}}}async getTaskCached(t){if(this.taskCache.has(t))return{ok:!0,value:this.taskCache.get(t)??null};try{let n=await this.tasks.getTaskById(t);return this.taskCache.set(t,n),{ok:!0,value:n}}catch(n){let r={kind:"store_failure",detail:n instanceof Error?n.message:String(n)};return this.emit({type:"lineage_store_failure",detail:r.detail}),{ok:!1,error:r}}}};function Ub(e){let t=e.split(".");if(t.length<3)return null;let[n,r]=t,i=t.slice(2);return n===void 0||n===""||r!=="raw"&&r!=="summary"&&r!=="predecessorSummary"||i.length===0||i.some(o=>o==="")?null:{namespace:n,layer:r,rest:i}}var j9=new Set(["__proto__","constructor","prototype"]);function RCe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var wOt=/^(0|[1-9][0-9]*)$/;function bOt(e,t){let n=t;for(let r of e){if(j9.has(r))return;if(Array.isArray(n)){if(!wOt.test(r)||!Object.hasOwn(n,r))return;n=n[Number(r)];continue}if(!RCe(n)||!Object.hasOwn(n,r))return;n=n[r]}return n}var COt={diagnostician:["diagnostician","diag_router"]},SOt={diagnostician:"diag_router"};function TOt(e,t,n){let r=G9(e,n);if(r!==void 0)return r;if(!RCe(n))return;let i=SOt[t]??(uy.includes(t)?t:void 0);if(i===void 0)return;let o=Bb(i,n);if(!o.ok)return;let s=Ub(e);if(s===null)return;let[a]=s.rest;if(!(a===void 0||j9.has(a))){if(a==="headline")return o.value.headline;if(Object.hasOwn(o.value.fields,a))return o.value.fields[a]}}function DCe(e){let t=[];for(let n of e)n.taskKind==="unknown"||n.taskKind===""||t.push({stage:n.taskKind,contentJson:n.contentJson});return t}function OCe(e,t){let n=new Set(t),r=[],i=[];for(let o of e){let s=Ub(o);if(s!==null&&s.layer==="raw"&&n.has(s.namespace)){i.push(o);continue}r.push(o)}return{ancestry:r,related:i}}function NCe(e,t){let n=new Map;for(let r of e){let i=Ub(r);if(i===null||i.layer==="predecessorSummary")continue;let o=[i.namespace,...COt[i.namespace]??[]],s=t.find(c=>o.includes(c.stage));if(s===void 0)continue;let a=i.layer==="raw"?bOt(i.rest,s.contentJson):TOt(r,s.stage,s.contentJson);a!==void 0&&n.set(r,a)}return n}function PCe(e,t){let n=new Map;for(let r of e){let i=Ub(r);if(i===null||i.rest.length!==1||i.layer==="predecessorSummary")continue;let o=t.find(l=>l.namespace===i.namespace);if(o===void 0)continue;let s=i.layer==="raw"?o.raw:o.summary;if(s===void 0)continue;let[a]=i.rest;if(a===void 0||j9.has(a)||!Object.hasOwn(s,a))continue;let c=s[a];c!==void 0&&n.set(r,c)}return n}function LCe(e,t){let n=new Map(e);for(let r of t)for(let[i,o]of r)n.has(i)||n.set(i,o);return n}function MCe(e){let t=new Set(e.absent),n=new Set(e.truncated.map(r=>r.fieldPath));return e.required.filter(r=>t.has(r)||n.has(r))}var K9={pollIntervalMs:5e3,timeoutMs:3e5,defaultMaxAttempts:3,agentId:"peer-runner",coreGrounding:!0};function kOt(e,t){return{pollIntervalMs:e.pollIntervalMs??K9.pollIntervalMs,timeoutMs:e.timeoutMs??K9.timeoutMs,defaultMaxAttempts:e.defaultMaxAttempts??K9.defaultMaxAttempts,owner:e.owner,runtimeKind:e.runtimeKind,agentId:e.agentId??t,outputLanguage:e.outputLanguage,coreGrounding:e.coreGrounding??!0}}function ROt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DOt(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!ROt(t)||!Object.hasOwn(t,"sourcePainId"))return null;let{sourcePainId:n}=t;return typeof n!="string"||n.length===0?null:n}var Ai=class{stateManager;runtimeAdapter;eventEmitter;artifactStore;resolvedOptions;config;pendingAgentDraftStore;contentHashFn;phase=Hn.Idle;currentLeasedAttempt;constructor(t,n,r){this.stateManager=t.stateManager,this.runtimeAdapter=t.runtimeAdapter,this.eventEmitter=t.eventEmitter,this.artifactStore=t.artifactStore,this.pendingAgentDraftStore=t.pendingAgentDraftStore,this.contentHashFn=t.contentHashFn,this.config=r,this.resolvedOptions=kOt(n,r.defaultAgentId)}get currentPhase(){return this.phase}getRuntimeKind(){return typeof this.runtimeAdapter.kind=="function"?this.runtimeAdapter.kind():this.resolvedOptions.runtimeKind}async maybeResumePendingIntent(t,n){return null}emitSuccessTelemetry(t,n,r){}checkLineageIntegrity(t,n,r){}postFetchTransform(t,n,r){typeof n=="object"&&n!==null&&!Array.isArray(n)&&Reflect.set(n,"generatedAt",new Date().toISOString())}async run(t){this.phase=Hn.Idle;let n=this.getRuntimeKind(),r;try{r=await this.stateManager.acquireLease({taskId:t,owner:this.resolvedOptions.owner,runtimeKind:n})}catch(o){return await this.handleLeaseOrPhaseError(t,o)}if(r.taskKind!==this.config.expectedTaskKind)return this.emitEvent("wrong_task_kind",t,{expectedKind:this.config.expectedTaskKind,actualKind:r.taskKind}),await this.stateManager.markTaskFailed(t,"input_invalid"),{status:"failed",taskId:t,errorCategory:"input_invalid",failureReason:`Task kind must be '${this.config.expectedTaskKind}', got '${r.taskKind}'`,attemptCount:r.attemptCount};this.emitEvent("task_leased",t,{taskKind:this.config.expectedTaskKind,attemptCount:r.attemptCount});let i=await this.maybeResumePendingIntent(t,r);if(i)return this.phase=Hn.Completed,i;try{let o=await this.resolveStoreRunId(t);this.phase=Hn.BuildingContext,this.currentLeasedAttempt=r.attemptCount;let s=await this.buildContext(t);this.emitEvent("context_built",t,{contextHash:s.contextHash}),this.phase=Hn.Invoking;let a=await this.invokeRuntime(t,s);this.emitEvent("run_started",t,{runtimeKind:n}),this.phase=Hn.Polling;let c=await this.pollUntilTerminal(a);if(c.status!=="succeeded")return await this.handleRuntimeFailure(t,r,c);this.phase=Hn.FetchingOutput;let l=await this.fetchAndParseOutput(a.runId,t);this.postFetchTransform(t,l,s),this.phase=Hn.Validating;let u=await this.validateOutput(l,t,s);if(!u.valid)return await this.handleValidationError({taskId:t,task:r,errors:u.errors,errorCategory:u.errorCategory});let d=l;this.emitEvent("output_validated",t,{}),this.checkLineageIntegrity(t,d,s),this.emitSuccessTelemetry(t,d,s);let p=await this.succeedTask(t,o,d,r,s.contextHash,s);return p.status==="succeeded"&&(this.phase=Hn.Completed),p}catch(o){return await this.handlePostLeaseError(t,r,o)}}emitEvent(t,n,r){this.eventEmitter.emitTelemetry({eventType:`${this.config.runnerName}_${t}`,traceId:n,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:r})}async pollUntilTerminal(t){let n=Date.now()+this.resolvedOptions.timeoutMs,r=["succeeded","failed","timed_out","cancelled"];for(;Date.now()<n;){let s=await this.runtimeAdapter.pollRun(t.runId);if(r.includes(s.status))return s;await this.sleep(this.resolvedOptions.pollIntervalMs)}try{let s=await this.runtimeAdapter.pollRun(t.runId);if(r.includes(s.status))return s}catch{}let i=!1;try{await this.runtimeAdapter.cancelRun(t.runId)}catch(s){i=!0,this.emitEvent("cancel_run_failed",t.runId,{runId:t.runId,errorMessage:s instanceof Error?s.message:String(s)})}let o=i?" (cancelRun also failed)":"";throw new Y("timeout",`Run ${t.runId} timed out after ${this.resolvedOptions.timeoutMs}ms${o}`)}async fetchAndParseOutput(t,n){let r;try{r=await this.runtimeAdapter.fetchOutput(t)}catch(o){throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"fetchOutput",errorMessage:o instanceof Error?o.message:String(o)}),o}if(!r||!r.payload)throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"payload_missing",errorMessage:`No output available for run ${t}`}),new Y("output_invalid",`No output available for run ${t}`);let{payload:i}=r;if(typeof i!="object"||i===null)throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"payload_not_object",errorMessage:`Output payload is not an object for run ${t}`}),new Y("output_invalid",`Output payload is not an object for run ${t}`);return i}async resolveLineageArtifactIds(t){let{hydratePITaskRecord:n}=await Promise.resolve().then(()=>(Po(),Nbe)),r=await this.stateManager.getTask(t);if(!r)return{ids:[],hasRejected:!1};let o=n(r)?.dependencyTaskIds??[];if(o.length===0)return{ids:[],hasRejected:!1};let s=[],a=!1,c=await Promise.allSettled(o.map(l=>this.artifactStore.listBySourceTaskId(l)));for(let l of c)if(l.status==="fulfilled")for(let u of l.value)s.push(u.artifactId);else a=!0;return{ids:s,hasRejected:a}}async resolveStoreRunId(t){let{runs:n,degradedRuns:r}=await this.stateManager.getValidRunsByTaskTolerant(t);r.length>0&&this.eventEmitter.emitTelemetry({eventType:"degradation_triggered",traceId:t,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:{component:"BasePeerRunner",runnerName:this.config.runnerName,trigger:"malformed_historical_run_rows",degradedCount:r.length,runIds:r.map(o=>o.runId),errors:r.map(o=>o.error),nextAction:"Quarantine malformed run rows: pd runtime internalization integrity-repair --confirm"}});let i=n[n.length-1];if(!i)throw new Y("execution_failed",`No valid run records found for task ${t} after lease acquisition. If historical runs are malformed, quarantine them first: pd runtime internalization integrity-repair --confirm`);return i.runId}static hashContextRefs(t){if(t.length===0)return"empty";let n=t.join("|"),r=0;for(let i=0;i<n.length;i++)r=Math.imul(31,r)+n.charCodeAt(i)|0;return`ctx-${Math.abs(r).toString(16)}`}async handleLeaseOrPhaseError(t,n){let r=this.classifyError(n);if(r.category==="lease_conflict")return this.emitEvent("run_failed",t,{errorCategory:"lease_conflict",errorMessage:r.message}),{status:"failed",taskId:t,errorCategory:"lease_conflict",failureReason:r.message,attemptCount:1};this.emitEvent("run_failed",t,{errorCategory:r.category,errorMessage:r.message});let i={taskId:t,taskKind:this.config.expectedTaskKind,status:"leased",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),attemptCount:1,maxAttempts:this.resolvedOptions.defaultMaxAttempts};return r.details&&Object.keys(r.details).length>0&&await this.persistOutputFailureDetails(t,void 0,{errorCategory:r.category,errorMessage:r.message,...r.details}),this.retryOrFail({taskId:t,task:i,errorCategory:r.category,failureReason:r.message})}async handlePostLeaseError(t,n,r){let i=this.classifyError(r);return this.emitEvent("run_failed",t,{errorCategory:i.category,errorMessage:i.message}),i.details&&Object.keys(i.details).length>0&&await this.persistOutputFailureDetails(t,n.diagnosticJson,{errorCategory:i.category,errorMessage:i.message,...i.details}),this.retryOrFail({taskId:t,task:n,errorCategory:i.category,failureReason:i.message})}async handleRuntimeFailure(t,n,r){let i=this.mapRunStatusToErrorCategory(r.status,r.reason);return this.emitEvent("run_failed",t,{runStatus:r.status,errorCategory:i}),this.retryOrFail({taskId:t,task:n,errorCategory:i,failureReason:r.reason?`Runtime execution ended with status: ${r.status}. Reason: ${r.reason}`:`Runtime execution ended with status: ${r.status}`})}async handleValidationError(t){let n=t.errorCategory??"output_invalid";return this.emitEvent("output_invalid",t.taskId,{errorCount:t.errors.length,errorCategory:n}),await this.persistOutputFailureDetails(t.taskId,t.task.diagnosticJson,{errorCategory:n,validatorErrors:[...t.errors],errorCount:t.errors.length},{lastValidatorErrors:{recordedAt:new Date().toISOString(),errorCategory:n,errors:[...t.errors],sourceAttemptCount:t.task.attemptCount}}),this.retryOrFail({taskId:t.taskId,task:t.task,errorCategory:n,failureReason:`Validation failed: ${t.errors.join("; ")}`})}async retryOrFail(t){if(this.permanentErrorCategories.has(t.errorCategory)){try{await this.stateManager.markTaskFailed(t.taskId,t.errorCategory,t.failureReason)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount,failureReason:t.failureReason}),this.phase=Hn.Failed,this.injectAgentDraftOnPermanentFailure(t),{status:"failed",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}if(t.errorCategory==="rate_limit"&&this.isDegradationEnabled()){try{await this.stateManager.markTaskFailed(t.taskId,"rate_limit",`LLM rate limit degraded: ${t.failureReason}`)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("diag_llm_rate_limit_degraded",t.taskId,{errorCategory:"rate_limit",attemptCount:t.task.attemptCount,failureReason:t.failureReason,nextAction:"Retry diagnosis manually with `pd pain retry` when rate limit clears, or enable fallback provider."}),this.phase=Hn.Failed,{status:"failed",taskId:t.taskId,errorCategory:"rate_limit",failureReason:`LLM rate limit degraded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}if(this.stateManager.getRetryPolicy().shouldRetry(t.task)){try{await this.stateManager.markTaskRetryWait(t.taskId,t.errorCategory,t.failureReason)}catch(r){return this.emitEvent("mark_retry_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_retried",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount}),this.phase=Hn.RetryWaiting,{status:"retried",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}try{await this.stateManager.markTaskFailed(t.taskId,"max_attempts_exceeded",`Max attempts exceeded: ${t.failureReason}`)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:"max_attempts_exceeded",attemptCount:t.task.attemptCount,failureReason:`Max attempts exceeded: ${t.failureReason}`}),this.phase=Hn.Failed,{status:"failed",taskId:t.taskId,errorCategory:"max_attempts_exceeded",failureReason:`Max attempts exceeded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}classifyError(t){return t instanceof Y?{category:t.category,message:t.message,details:t.details}:t instanceof Error?{category:"execution_failed",message:t.message}:{category:"execution_failed",message:String(t)}}async persistOutputFailureDetails(t,n,r,i){try{let o={};if(n){let s=JSON.parse(n);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(o=s)}o.output_failure_details={recordedAt:new Date().toISOString(),...r},i!==void 0&&Object.assign(o,i),await this.stateManager.updateTask(t,{diagnosticJson:JSON.stringify(o)})}catch(o){this.emitEvent("mark_failed_error",t,{errorCategory:"storage_unavailable",errorMessage:`persistOutputFailureDetails failed: ${o instanceof Error?o.message:String(o)}`})}}mapRunStatusToErrorCategory(t,n){switch(t){case"failed":return"execution_failed";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return"execution_failed"}}sleep(t){return new Promise(n=>setTimeout(n,t))}isDegradationEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"diagnostician_llm_degradation")}isArtifactSummaryEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"artifact_summary_redundancy")}buildArtifactContentJson(t,n,r,i){if(!this.isArtifactSummaryEnabled())return JSON.stringify(r);try{let o=this.contentHashFn,s=o?i:null;!o&&i!==null&&this.emitEvent("artifact_summary_predecessor_skipped",t,{runnerKind:n,reason:"content_hash_fn_not_injected",nextAction:"Inject contentHashFn into PeerRunnerDeps (plugin/CLI layer) to enable predecessorSummary."});let a=_Ce(n,r,s,o??(u=>u),u=>{this.emitEvent(u.type,t,{runnerKind:u.runnerKind,reason:u.reason})});if(a.summary===void 0||r===null||typeof r!="object"||Array.isArray(r))return JSON.stringify(r);let c=r,l=Object.hasOwn(c,"summary");return l&&this.emitEvent("artifact_summary_skipped",t,{runnerKind:n,reason:"output_summary_key_collision",nextAction:"Runner output already declares a top-level `summary` field; the Layer 0 envelope summary key is skipped to avoid overwriting it. predecessorSummary is still attached."}),JSON.stringify({...c,...l?{}:{summary:a.summary},...a.predecessorSummary!==void 0?{predecessorSummary:a.predecessorSummary}:{}})}catch(o){return this.emitEvent("artifact_summary_skipped",t,{runnerKind:n,reason:"unexpected_error",errorMessage:o instanceof Error?o.message:String(o)}),JSON.stringify(r)}}isContextManifestBudgetEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"context_manifest_budget")}isProgressiveEvaluatorEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"progressive_evaluator")}async runSingleEvaluation(t,n,r){let i=this.getRuntimeKind(),o=await this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:n,contextItems:[],outputSchemaRef:this.config.resultRefPrefix.includes("evaluator")?"evaluator-output-v1":`${this.config.expectedTaskKind}-output-v1`,timeoutMs:this.resolvedOptions.timeoutMs,systemPrompt:r});this.emitEvent("run_started",t,{runtimeKind:i,stage:"progressive_evaluation"});let s=await this.pollUntilTerminal(o);if(s.status!=="succeeded")throw new Y(s.status==="timed_out"?"timeout":"execution_failed",`Progressive evaluation run ${o.runId} ended with status ${s.status}`);return this.fetchAndParseOutput(o.runId,t)}resolveContextInjection(t,n,r){if(!this.isContextManifestBudgetEnabled())return{mode:"disabled"};let i=k_(n),o=q9(i,r);return this.runResolveInjection({taskId:t,manifest:n,available:o,requiredPaths:[]})}async resolveContextInjectionAsync(t){let{taskId:n,manifest:r}=t;if(!this.isContextManifestBudgetEnabled())return{mode:"disabled"};let i=k_(r),o=t.requiredPaths??[],s=q9(i,t.predecessorContentJson),a=[],c=(t.relatedSources??[]).map(g=>g.namespace),{ancestry:l}=OCe(r.tier2,c),u=new Set(c),d=[...r.tier0,...r.tier1].filter(g=>{let A=Ub(g);return A!==null&&A.layer==="summary"&&!u.has(A.namespace)}),p=[...l,...d];if(p.length>0&&t.startArtifactId!==void 0){let A=await new iN({artifacts:this.artifactStore,tasks:{getTaskById:async _=>{let x=await this.stateManager.getTask(_);return x===null?null:{taskId:_,taskKind:x.taskKind}}}}).resolve(t.startArtifactId);if(A.ok)a.push(NCe(p,DCe(A.value.nodes)));else if(this.emitEvent("context_lineage_unavailable",n,{runnerKind:r.runnerKind,manifestId:r.manifestId,errorKind:A.error.kind,detail:A.error.detail,fallback:"full_predecessor_injection",nextAction:"verify_durable_artifact_ancestry_before_tier2_resolution"}),o.length>0)return{mode:"fallback",reason:"lineage_unavailable",unresolvedRequired:[...o]}}t.relatedSources!==void 0&&t.relatedSources.length>0&&a.push(PCe(i,t.relatedSources));let m=LCe(s,a);return this.runResolveInjection({taskId:n,manifest:r,available:m,requiredPaths:o})}runResolveInjection(t){let{taskId:n,manifest:r,available:i,requiredPaths:o}=t,a=TCe(r,i,l=>{l.type==="manifest_resolution_insufficient"?this.emitEvent("manifest_resolution_insufficient",n,{runnerKind:l.runnerKind,manifestId:l.manifestId,absentCount:l.absentCount,declaredCount:l.declaredCount,absentRatio:l.absentRatio,fallback:l.fallback}):this.emitEvent("context_truncated",n,{runnerKind:l.runnerKind,manifestId:l.manifestId,fieldPath:l.fieldPath,reason:l.reason,remainingBudgetTokens:l.remainingBudgetTokens})}),c=MCe({required:o,absent:a.allocated.absent,truncated:a.allocated.truncated});return c.length>0?(this.emitEvent("required_context_evidence_unresolved",n,{runnerKind:r.runnerKind,manifestId:r.manifestId,requiredPaths:c,fallback:"full_predecessor_injection",nextAction:"verify_durable_ancestry_or_related_reference_availability"}),{mode:"fallback",reason:"required_evidence_unresolved",unresolvedRequired:c}):a.kind==="focused"?{mode:"focused",fields:a.allocated.fields}:{mode:"fallback",reason:a.reason,unresolvedRequired:[]}}injectAgentDraftOnPermanentFailure(t){if(!this.pendingAgentDraftStore)return;let{taskKind:n}=t.task,{errorCategory:r}=t,i=t.failureReason,o=um(cm(lm(i))),s={summary:`${n} failed with category=${r} at ${new Date().toISOString()}`,observedFailure:o},a=DOt(t.task.diagnosticJson);try{let c=this.pendingAgentDraftStore.insertPendingDraft({taskId:t.taskId,painId:a??void 0,agentDraft:s});if(!c.ok){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,errorMessage:c.error,nextAction:"Inspect pending_agent_drafts table integrity; draft will be retried on next permanent failure of the same taskId (idempotent UPDATE)."});return}this.emitEvent("agent_draft_inserted",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,draftId:c.id,painIdLinked:a!==null})}catch(c){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,errorMessage:c instanceof Error?c.message:String(c),nextAction:"PendingAgentDraftStore.insertPendingDraft threw unexpectedly; inspect the store implementation."})}}};var oN=class extends Ai{validator;contextAssembler;effectiveConfig;intentDocReader;constructor(t,n){super(t,n,{runnerName:"diag_rootcause",expectedTaskKind:"diag_rootcause",defaultAgentId:"main",resultRefPrefix:"diag-rootcause",effectiveConfig:n.effectiveConfig}),this.validator=t.validator,this.contextAssembler=t.contextAssembler,this.effectiveConfig=n.effectiveConfig,this.intentDocReader=t.intentDocReader}get permanentErrorCategories(){return new Set(["storage_unavailable","workspace_invalid","capability_missing","cancelled","input_invalid"])}async buildContext(t){let n=await this.stateManager.getTask(t);if(!n)throw new Y("input_invalid",`Task ${t} not found`);let r=n.inputRef||t,i=await this.contextAssembler.assemble(r),s=ht(n)?.dependencyTaskIds??[],a=[...i.sourceRefs];if(s.length>0){let l=await Promise.allSettled(s.map(u=>this.stateManager.getTask(u)));for(let u=0;u<l.length;u++){let d=l[u],p=s[u];if(!(!d||p===void 0)&&d.status==="fulfilled"&&d.value){d.value.resultRef&&a.push(d.value.resultRef);let m=d.value?ht(d.value):null;m?.outputArtifactRefs&&a.push(...m.outputArtifactRefs.map(g=>g.ref))}}}return{contextHash:Ai.hashContextRefs(a),contextRefs:a,painPayload:i}}async invokeRuntime(t,n){let r=!1,i=!1,o=!1;if(this.effectiveConfig){let u=li(this.effectiveConfig);r=Is(u,"diagnostician_core_grounding"),i=Is(u,"intent_engineering"),o=Is(u,"pain_diagnosis_persistence")}let s;if(i&&!this.intentDocReader)i=!1;else if(i&&this.intentDocReader){let u=this.intentDocReader.readIntentDoc();u.ok&&u.doc?s={raw:u.doc.raw,contentHash:u.doc.contentHash,path:u.doc.path}:(this.emitEvent("intent_doc_read_failed",t,{reason:u.reason??"unknown",nextAction:u.nextAction??"Check INTENT.md configuration.",flagEnabled:u.flagEnabled,found:u.found}),i=!1)}let a=new N2,{message:c,systemPrompt:l}=a.buildPrompt(n.painPayload,{outputLanguage:this.resolvedOptions.outputLanguage,coreGrounding:r,intentGrounding:i,intentDoc:s,evidenceFirstAttribution:o});return this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:c,contextItems:[],outputSchemaRef:"diag-rootcause-output-v1",timeoutMs:this.resolvedOptions.timeoutMs,systemPrompt:l})}async validateOutput(t,n,r){let i=await this.validator.validate(t,n);return{valid:i.valid,errors:i.errors,errorCategory:i.errorCategory,warnings:i.warnings}}async succeedTask(t,n,r,i,o,s){try{await this.stateManager.updateRunOutput(n,JSON.stringify(r))}catch(p){throw this.emitEvent("update_output_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)}),p}let a=[],c=!1;try{let p=await this.resolveLineageArtifactIds(t);a=p.ids,c=p.hasRejected}catch(p){this.emitEvent("lineage_resolve_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)})}c&&this.emitEvent("lineage_partial",t,{runId:n,resolvedCount:a.length,warning:"Some dependency artifact queries were rejected; lineage may be incomplete"});let l=`pi-art-${t}-${n}`,u=new Date().toISOString();try{await this.artifactStore.upsertArtifact({artifactId:l,artifactKind:"principle",sourceTaskId:t,lineageArtifactIds:a,validationStatus:"pending",contentJson:this.buildArtifactContentJson(t,"diag_rootcause",r,null),createdAt:u,updatedAt:u})}catch(p){return this.emitEvent("artifact_write_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)}),this.retryOrFail({taskId:t,task:i,errorCategory:"artifact_commit_failed",failureReason:`PIArtifact write failed: ${p instanceof Error?p.message:String(p)}`})}let d=`${this.config.resultRefPrefix}://${n}`;try{await this.stateManager.markTaskSucceeded(t,d)}catch(p){throw this.emitEvent("mark_succeeded_failed",t,{taskId:t,runId:n,errorMessage:p instanceof Error?p.message:String(p)}),p}return this.emitEvent("task_succeeded",t,{attemptCount:i.attemptCount,resultRef:d,rootCauseCategory:r.rootCauseCategory,causalChainDepth:r.causalChain.length}),{status:"succeeded",taskId:t,runId:n,artifactId:l,resultRef:d,contextHash:o,output:r,attemptCount:i.attemptCount}}postFetchTransform(t,n){y_(n,"taskId",t)}emitSuccessTelemetry(t,n,r){this.emitEvent("rootcause_completed",t,{rootCauseCategory:n.rootCauseCategory,causalChainDepth:n.causalChain.length})}};Po();var OOt=f.Union([f.Literal("general"),f.Literal("domain"),f.Literal("scenario")]),dm=f.Object({valid:f.Boolean(),taskId:f.String({minLength:1}),sourceRootCauseArtifactId:f.String({minLength:1,description:"Lineage consistency check \u2014 must match the artifact ID from Stage A"}),abstractedPrinciple:f.String({minLength:1,maxLength:200,description:"Highly abstracted, cross-scenario principle (\u2264200 chars)"}),rationale:f.String({minLength:1,description:"Why this principle addresses the root cause"}),groundedOnCorePrincipleIds:f.Array(f.String({minLength:1}),{description:"Subset of T-01..T-10. Validated against registry \u2014 fabricated IDs cause validation failure."}),scope:OOt,confidence:f.Number({minimum:0,maximum:1}),ambiguityNotes:f.Optional(f.Array(f.String()))}),sN=class{async validate(t,n){let r=[],i=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if(typeof o.taskId!="string"||o.taskId!==n){let s=["diag_rootcause-","diag_distiller-","diag_router-"],a=u=>{for(let d of s)if(u.startsWith(d))return u.slice(d.length);return u},c=a(n),l=typeof o.taskId=="string"?a(o.taskId):"";if(l!==""&&l===c){let u=o.taskId;o.taskId=n,i.push(`taskId re-injected: LLM output "${u}", corrected to "${n}" (ERR-008)`)}else r.push(`taskId mismatch: expected ${n}, got ${String(o.taskId)}`)}if(!Ct.Check(dm,t)){let a=[...Ct.Errors(dm,t)].map(c=>`${c.path}: ${c.message}`);r.push(...a)}if(Array.isArray(o.groundedOnCorePrincipleIds))for(let s of o.groundedOnCorePrincipleIds)typeof s=="string"&&!Db(s)&&r.push(`Fabricated axiom ID ${s} not in core principle registry`);return r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[],warnings:i}}};function NOt(e={}){let t=e.adapter??new Cd,n=e.schema??dm,{outputLanguage:r,coreGrounding:i}=e,o=t.generateExample(n),s=t.generateConstraints(n),a=Ws(r);return`You are a principle distiller. Your job is to abstract a specific root cause into a general, cross-scenario principle.
1054
+ ${c}${l}`}var N2=class{adapter;schema;constructor(t={}){this.adapter=t.adapter??new Cd,this.schema=t.schema??hu}buildRootCauseInstruction(t={}){return PDt({adapter:t.adapter??this.adapter,schema:t.schema??this.schema,outputLanguage:t.outputLanguage,coreGrounding:t.coreGrounding,intentGrounding:t.intentGrounding,evidenceFirstAttribution:t.evidenceFirstAttribution})}buildPrompt(t,n={}){let r=n.limits??mCe,{outputLanguage:i,coreGrounding:o,intentGrounding:s,intentDoc:a,evidenceFirstAttribution:c}=n,l=[],u=t.conversationWindow,d=u.slice(0,r.maxConversationEntries);u.length>r.maxConversationEntries&&l.push(`conversationWindow truncated from ${u.length} to ${r.maxConversationEntries} entries`);let p=d.map(x=>x.text&&x.text.length>r.maxEntryTextChars?{...x,text:x.text.slice(0,r.maxEntryTextChars)+"...[truncated]"}:x),m={...t,conversationWindow:p},g=this.buildRootCauseInstruction({outputLanguage:i,coreGrounding:o,intentGrounding:s,evidenceFirstAttribution:c}),A={taskId:t.taskId,contextHash:t.contextHash,diagnosisTarget:t.diagnosisTarget,conversationWindow:p,sourceRefs:t.sourceRefs,context:m,...l.length>0?{truncationWarnings:l}:{},...s&&a?{intentDoc:a}:{}},_=JSON.stringify(A);if(_.length>r.maxMessageChars){let x=[...p],v=0,k=T=>(A.conversationWindow=x,A.context={...m,conversationWindow:x},A.truncationWarnings=[...l,T>0?`payload truncated due to size (dropped ${T} conversationWindow entries; limit ${r.maxMessageChars} chars)`:`payload exceeds maxMessageChars (${_.length} > ${r.maxMessageChars} chars); no conversationWindow entries left to drop`],JSON.stringify(A));do x.length>0&&(x=x.slice(0,-1),v+=1),_=k(v);while(x.length>0&&_.length>r.maxMessageChars)}return{message:_,promptInput:A,systemPrompt:g}}};ka();var C_=["core","quiet","gone","legacy_retire"],VO=["owner","system"],Ob=["openclaw","pi-ai"],Rc=["diagnostician","dreamer","philosopher","scribe","artificer","evaluator","rolloutReviewer","correctionObserver","empathyObserver","signalCollector"],S_=["simple","advanced"],YO=["production","development","demo","test"],P2=["low","medium","high"],L2=["realtime","async"],Nb=["smoke","unit","full"],zO=["full","summary","off"],ys=new Set(["__proto__","constructor","prototype"]);var B9=new Set(["__proto__","constructor","prototype"]),Pb={pain_evidence_admission:"painEvidenceAdmission",pain_evidence_admission_default:"painEvidenceAdmissionDefault"};function hCe(e){if(e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.hasOwn(e,"enabled")){let{enabled:t}=e;if(typeof t=="boolean")return t}}function M2(e){let t={},n=[];for(let r of Object.keys(e))B9.has(r)&&n.push(`flag '${r}': dangerous key rejected`);for(let r of Object.keys(e))B9.has(r)||Object.hasOwn(Pb,r)||(t[r]=e[r]);for(let r of Object.keys(e)){if(B9.has(r))continue;let i=Object.hasOwn(Pb,r)?Pb[r]:void 0;i!==void 0&&!Object.hasOwn(e,i)&&(t[i]=e[r])}for(let[r,i]of Object.entries(Pb))if(Object.hasOwn(e,r)&&Object.hasOwn(e,i)){let o=hCe(e[r]),s=hCe(e[i]);o!==s&&n.push(`feature '${i}': conflicting values for canonical ID and alias '${r}' \u2014 canonical value used (enabled=${String(s)})`)}return{normalized:t,warnings:n}}var B2=[{id:"prompt",category:"core",enabled:!0,since:"2026-05-24",description:"Prompt injection for principle application"},{id:"code_tool_hook",category:"core",enabled:!0,since:"2026-05-24",description:"Code tool hook for rule host enforcement"},{id:"rulecode_safety_controls",category:"core",enabled:!0,since:"2026-08-21",description:"Durable RuleCode safety isolation authority. Default ON; emergency enforcement shutdown remains the code_tool_hook core flag."},{id:"rulecode_owner_live_decision",category:"core",enabled:!0,since:"2026-08-21",description:"Owner-reviewed RuleCode shadow-to-live decision authority. Default ON after the readiness, authenticated Console, CLI, audit, and rollback rollout gates passed; flag-off refuses promotion."},{id:"defer_archive",category:"core",enabled:!0,since:"2026-05-24",description:"Defer/archive activation writer"},{id:"correction_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Optional LLM optimization service for correction keywords; synchronous correction detection remains active independently"},{id:"signal_collector",category:"quiet",enabled:!1,since:"2026-06-30",description:"Unified signal collection host (correction + empathy upstream merge). NOTE: keyword detection (high-precision phrases) runs regardless of this flag; this flag only gates the LLM deep-judgment path (ambiguous terms / missed keywords). Quiet flag: dogfood-only until validated."},{id:"internalization_auto_consumer",category:"quiet",enabled:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381; quiet flag, default on, disableable via config)"},{id:"internalization_full_chain",category:"core",enabled:!0,since:"2026-08-12",description:"PRI-419 amendment: auto-consumer advances dreamer\u2192\u2026\u2192evaluator\u2192rollout_reviewer (full chain) so artifacts reach validated and the approval queue is populated unattended. The human gate is the approval queue (Console), not the rollout_reviewer CLI trigger. Default ON; flag-off = dreamer-only."},{id:"story_a_approval_completion",category:"quiet",enabled:!0,since:"2026-06-18",description:"Story A approval-completion orchestrator (PRI-408) \u2014 formal service replacing demo direct-writer activation; quiet flag, default on, disableable via config"},{id:"feedback_channel",category:"quiet",enabled:!0,since:"2026-06-01",description:"MVP seed feedback channel \u2014 privacy-preserving report drafts. PRI-543: flag scope extended to also cover the feedback SUBMIT ladder (ingest relay / gh CLI / mailto / export-file channels + submit endpoints). Flag-off = submit endpoints 403 + submit UI hidden; config `feedback:` segment and channel parameters still available."},{id:"release_manager_shadow",category:"quiet",enabled:!0,since:"2026-08-25",description:"ReleaseManager governance for the update surface \u2014 signed-metadata checks with legacy comparison; graduated default-on 2026-09-07 (Owner decision). Rollback = set enabled:false."},{id:"release_manager_write_authority",category:"quiet",enabled:!0,since:"2026-09-06",description:"PRI-698 Phase 1 \u2014 ReleaseManager.apply() serves Console /apply-full (installer + journal deployment); graduated default-on 2026-09-07 (Owner decision) with pre-transaction legacy fallback; flag-off = legacy console updater with explicit release_manager_write_disabled fallback reason"},{id:"gfi",category:"quiet",enabled:!1,since:"2026-05-24",description:"Global Friction Index session scoring"},{id:"evolution_worker",category:"gone",enabled:!1,since:"2026-06-01",description:"Legacy evolution worker heartbeat (worker deleted in PRI-737; flag locked off, retired 2026-09-12 PRI-752)"},{id:"empathy_observer",category:"quiet",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking (MVP-Quiet)"},{id:"painEvidenceAdmission",category:"quiet",enabled:!0,since:"2026-06-06",description:"Pre-diagnosis evidence triage for pain signals (PEAT-B1). PRI-454: default-on, Gate B is primary gate."},{id:"painEvidenceAdmissionDefault",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: Global kill switch for Gate B migration. When ON (default), Gate B (TriggerController) owns admission. When OFF (rollback), Gate A (PainDiagnosticGate) is re-activated."},{id:"diagnostician_async_cli",category:"quiet",enabled:!1,since:"2026-06-11",description:"Async pain-record CLI \u2014 submit and return immediately, diagnosis runs in background. Default: false until orchestrator exists."},{id:"diagnostician_core_grounding",category:"quiet",enabled:!0,since:"2026-06-11",description:"Core principle grounding in diagnostician prompt (Arm 2)"},{id:"internalization_core_grounding",category:"quiet",enabled:!0,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders (dreamer, philosopher, scribe)"},{id:"diagnostician_split_pipeline",category:"quiet",enabled:!0,since:"2026-06-11",description:"3-stage split diagnostician pipeline (RootCause\u2192Distiller\u2192Router)"},{id:"diagnostician_llm_degradation",category:"quiet",enabled:!0,since:"2026-07-03",description:"Diagnostician LLM rate-limit graceful degradation \u2014 on persistent rate-limit, emit diag_llm_rate_limit_degraded telemetry + rate_limit errorCategory instead of max_attempts_exceeded (ADR-0019). Default ON (graduated PRI-571, 2026-08-24); flag-off = hard fail (legacy behavior)."},{id:"l2_dreamer",category:"quiet",enabled:!1,since:"2026-06-16",description:"L2 multi-turn agent loop for the dreamer runner (PRI-419) \u2014 read-only tools + submit_output, scoped to dreamer only"},{id:"code_rule_capability",category:"core",enabled:!0,since:"2026-06-18",description:"Code-rule capability (atomic: ArtificerL2 + Evaluator) for RuleHost pipeline \u2014 MVP-Core, default ON (PRI-435)"},{id:"intent_engineering",category:"quiet",enabled:!1,since:"2026-06-25",description:"INTENT.md-grounded constructive friction and Stage-A intent tension diagnosis (PRI-465). Default off; flag-off = no INTENT read, no prompt injection, no intentTension."},{id:"rulecode_context_v2",category:"quiet",enabled:!1,since:"2026-06-27",description:"RuleContext v2 \u2014 rule-code context vision (PRI-479). Foundation flag; default off, v1 rule behavior unchanged. See docs/superpowers/specs/2026-06-27-rulecode-context-vision-design.md"},{id:"failed_tasks_observability",category:"quiet",enabled:!0,since:"2026-07-04",description:"Failed tasks observability \u2014 list/view failed pipeline tasks"},{id:"evaluator_artificer_repair_loop",category:"quiet",enabled:!0,since:"2026-07-04",description:"PRI-509/P0-D: Evaluator\u2192Artificer repair loop \u2014 auto-seed artificer repair on needs_revision (2-round cap \u2192 needs_human_review). Default ON (INV-02 liveness); production-wired in auto-consumer since 2026-08-18."},{id:"artificer_output_retry",category:"quiet",enabled:!0,since:"2026-08-20",description:"Issue 2/PRI-621: retry Artificer `output_invalid` (malformed LLM output, e.g. missed submit_rulecode) via the base retry policy (max 3 attempts) instead of permanent failure. Graduated default-on 2026-08-29 \u2014 aligns artificer with every other peer runner; flag-off reverts output_invalid to permanent (legacy)."},{id:"artifact_summary_redundancy",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 0 \u2014 writer-side ArtifactSummary + predecessorSummary envelope on all 8 SummaryRunnerKind stages. Default off; flag-off = current contentJson shape unchanged."},{id:"context_manifest_budget",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 1 \u2014 manifest + budget-driven context injection with information-floor fallback. Default off; flag-off = existing buildContext assembly unchanged."},{id:"progressive_evaluator",category:"quiet",enabled:!1,since:"2026-07-26",description:"Internalization progressive disclosure Layer 2 \u2014 two-stage evaluation with flagged criteria + painCoverage/compressionFidelity output fields. Default off; flag-off = single-stage evaluation unchanged."},{id:"host.codex",category:"core",enabled:!0,since:"2026-08-11",description:"ADR-0020: Codex CLI host adapter. Default ON (flipped 2026-08-12 after PRI-282 E2E). Flag-off = pd-hook.js outputs {} + exit 0 + SystemLogger records skip (rc-9). Disable via .pd/config.yaml: host.codex: { enabled: false }."},{id:"abstraction_layer_v1",category:"quiet",enabled:!1,since:"2026-08-13",description:"PRI-523 shared host-runtime cutover for OpenClaw. Default OFF preserves the legacy route; enable only for controlled parity validation."},{id:"principle_receipt_block_copy",category:"quiet",enabled:!0,since:"2026-08-15",description:"Principle Receipt P0 \u2014 enriched RuleHost block copy with principle attribution (title/approval date/source summary, PRI-530). Default ON (graduated PRI-571, 2026-08-24); flag-off = generic block template unchanged."},{id:"principle_receipt_ledger",category:"quiet",enabled:!0,since:"2026-08-15",description:"Principle Receipt ledger \u2014 durable principle_applications history (effect/presence two-level semantics, PRI-531). Default ON (graduated PRI-571, 2026-08-24); flag-off = no ledger writes."},{id:"principle_receipt_self_report",category:"quiet",enabled:!1,since:"2026-08-16",description:"Principle Receipt P1-a \u2014 agent self-report \u{1F4CC} line (injection instruction + capture, PRI-532). Default off; flag-off = directive template unchanged, no capture."},{id:"principle_governance_projection_v2",category:"quiet",enabled:!0,since:"2026-08-20",description:"Read-only per-principle Owner governance projection (PRI-549). Default ON (graduated PRI-571, 2026-08-24); flag-off preserves the pre-projection Principle Detail experience."},{id:"failed_task_recovery_console",category:"quiet",enabled:!0,since:"2026-08-23",description:"Governance Recovery Actions v1 \u2014 Owner-triggered recovery of failed / needs_human_review tasks from Console (failed\u2192pending via RecoverySweepService; needs_human_review\u2192pending via owner authority reset). Default on (2026-08-24 owner decision); flag-off = Console read-only."},{id:"pain_diagnosis_persistence",category:"quiet",enabled:!1,since:"2026-08-23",description:"Persist diagnostician root-cause attribution to pain_diagnoses (state.db, keyed by canonical pain_id) + Evidence First attribution rules in the Stage A prompt. Default off; flag-off = no writes, prompt byte-identical."},{id:"governance_experience_v1",category:"quiet",enabled:!0,since:"2026-08-24",description:"Governance Experience Snapshot v1.5.1 \u2014 read-only workspace governance experience (batch projection + GET /api/v1/governance/experience + Console Focus integration). Default on (graduated 2026-08-29); flag-off via config = endpoint 403 (no DB access) and legacy Focus behavior preserved."},{id:"anonymous_product_telemetry",category:"quiet",enabled:!1,since:"2026-08-26",description:"Anonymous Product Telemetry v1 \u2014 opt-in daily boolean-milestone snapshot (initialized/pain/principle/activation/receipt presence+effect), daily unlinkable IDs, zero content collection. Default off; export also requires explicit consent (pd telemetry enable) + production eligibility."},{id:"codex_conversation_ingestion",category:"quiet",enabled:!1,since:"2026-08-29",description:"Codex Governance Closure Slice A \u2014 bounded governance-observation ingestion from the authenticated Codex Stop-hook transcript (visible user/assistant/tool facts only, \u226432 turns/\u22647 days operational window, promotion substrate). Default off; flag-off = zero transcript reads, no observation writes, existing Codex behavior unchanged."},{id:"nocturnal",category:"gone",enabled:!1,since:"2026-05-24",description:"Nocturnal trinity pipeline (retired)"},{id:"idle_trigger",category:"gone",enabled:!1,since:"2026-05-24",description:"Idle trigger for background processing (retired)"},{id:"new_user_onboarding",category:"core",enabled:!0,since:"2026-07-01",description:"New user onboarding wizard \u2014 first-visit redirect to /welcome + demo story-a trigger endpoint. Maintainer-approved MVP-Core (2026-07-01): default-on; emergency disable via .pd/config.yaml: new_user_onboarding: { enabled: false }."}];var ly={};for(let e of B2)ly[e.id]={category:e.category,enabled:e.enabled};var LDt="pd.default",MDt={type:"pi-ai",provider:"",model:"",apiKeyEnv:""},gCe="openclaw.default",ACe={type:"openclaw",source:"default"},cy=gCe,F2=ACe,BDt={diagnostician:!0,dreamer:!0,philosopher:!1,scribe:!0,artificer:!0,evaluator:!1,rolloutReviewer:!1,correctionObserver:!1,empathyObserver:!1,signalCollector:!1};function JO(){let e={};for(let t of Rc)e[t]={enabled:BDt[t],runtimeProfile:cy};return{defaultRuntime:cy,agents:e}}var XO={diagnostics:{mode:"simple"}},yl={thinkingOs:!1,projectFocus:"off",evolutionContext:{enabled:!0,maxMessages:4,maxCharsPerMessage:200}};function U2(){return{version:1,features:{...ly},runtimeProfiles:{[LDt]:{...MDt},[gCe]:{...ACe}},internalAgents:JO(),ui:{...XO},principles:{outputLanguage:void 0},contextInjection:void 0}}var F9=["prompt","code_tool_hook","defer_archive"];function li(e){let{config:t}=e,n=[],r={};for(let[o,s]of Object.entries(ly))r[o]={id:o,category:s.category,enabled:s.enabled};for(let[o,s]of Object.entries(t.features))if(!ys.has(o)&&s)if(Object.hasOwn(r,o)){let a=r[o];if(!a)continue;if(a.category==="gone"){s.enabled&&n.push(`feature '${o}': gone flag cannot be re-enabled`);continue}if(a.category==="core"&&!s.enabled){n.push(`feature '${o}': core flag explicitly disabled via config (emergency disable)`),r[o]={id:o,category:a.category,enabled:!1,...s.source?{source:s.source}:{}};continue}r[o]={id:o,category:s.category,enabled:s.enabled,...s.source?{source:s.source}:{}}}else n.push(`feature '${o}': unknown flag ignored (not a registered capability)`);let i=[];for(let o of F9){let s=r[o];s&&s.enabled&&i.push(o)}return{flags:r,enabledChannels:i,warnings:n}}function Is(e,t){return Object.hasOwn(e.flags,t)?e.flags[t]?.enabled??!1:!1}var Q2="<redacted-path>",am="[REDACTED]";var FDt=/(?:[A-Za-z]:[\\/](?:[^\\\s/:*?"<>|]+[\\/])+[^\\\s/:*?"<>|]*)/g,UDt=/(?<![a-zA-Z0-9_.])[\\/](?:usr|home|Users|var|opt|etc|tmp|root|run|mnt|media|srv|boot|dev|proc|sys)(?:[\\/][^\\\s/:*?"<>|]+)+/g;function cm(e){return typeof e!="string"?e:e.replace(FDt,Q2).replace(UDt,Q2)}var QDt=/\bsk-(?:ant-)?[A-Za-z0-9_-]{16,}\b/g,$Dt=/\bgh[pousr]_[A-Za-z0-9_]{16,}\b/g,WDt=/\blin_api_[A-Za-z0-9_-]{16,}\b/g,GDt=/(Authorization\s*:\s*)(["'])?([A-Za-z]+\s+)?([^\s"';,]+)/gi,qDt=/(\$env:\s*[A-Z_][A-Z0-9_]{2,}\s*=\s*")([^"]*)(")/gi,HDt=/\b(api[_-]?key|token|secret|password|auth(?:_?token)?)\s*[:=]\s*['"]?([^\s'",}{]+)['"]?/gi,jDt=/\bBearer\s+[A-Za-z0-9._\-+/=]{8,}\b/g;function lm(e){return typeof e!="string"?e:e.replace(QDt,am).replace($Dt,am).replace(WDt,am).replace(GDt,"$1$2$3[REDACTED]").replace(qDt,"$1[REDACTED]$3").replace(jDt,am).replace(HDt,(t,n)=>`${n}=${am}`)}var KDt=/\b([A-Z_][A-Z0-9_]{2,})\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s,;}{]+))/g;function um(e){return typeof e!="string"?e:e.replace(KDt,(t,n)=>`${n}=${am}`)}function tg(e){if(typeof e!="string")return e;let t=cm(e);return t=lm(t),t=um(t),t}var VDt=new Set(["password","passwd","secret","token","api","apikey","authorization","auth","credential","credentials","private","key"]);function YDt(e){return e.toLowerCase().split(/[_\-.]/g).filter(t=>t.length>0)}function yCe(e){let t=YDt(e);if(t.length===0)return!1;for(let n of t)if(VDt.has(n))return!0;return!1}var zDt=6,ICe=100,U9=2e3;function $2(e,t){if(e===null)return{ok:!0,value:null,notes:[]};if(e===void 0)return{ok:!0,value:void 0,notes:[]};let n=typeof e;if(n==="string"){let i=e,o=i;return i=cm(i),i=lm(i),i=um(i),i!==o&&t.notes.push("string value redacted (path/token/env)"),i.length>U9&&(i=i.slice(0,U9)+"\u2026",t.notes.push(`string truncated to ${U9} chars`)),{ok:!0,value:i,notes:t.notes}}if(n==="bigint")return{ok:!0,value:`<bigint:${e.toString()}>`,notes:[]};if(n!=="object")return{ok:!0,value:e,notes:[]};if(t.depth>=zDt)return{ok:!0,value:"<deep>",notes:[]};let r=e;if(t.seen.has(r))return t.notes.push("circular reference detected"),{ok:!0,value:"<circular>",notes:[]};t.seen.add(r);try{if(Array.isArray(e)){let a=[];for(let c=0;c<e.length;c++){let l=$2(e[c],{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!l.ok)return l;a.push(l.value)}return{ok:!0,value:a,notes:[]}}let i=e,o={},s=Object.keys(i).slice(0,ICe);for(let a of s){if(yCe(a)){o[a]=am,t.notes.push(`field "${a}" redacted`);continue}let c=i[a];if(c!==null&&typeof c=="object"&&t.seen.has(c)){t.notes.push(`circular reference detected at "${a}"`),o[a]="<circular>";continue}let l=$2(c,{seen:t.seen,depth:t.depth+1,notes:t.notes});if(!l.ok)return l;o[a]=l.value}return{ok:!0,value:o,notes:[]}}finally{t.seen.delete(r)}}function JDt(e){let t=[],n=[],r={seen:new WeakSet,depth:0,notes:t};r.seen.add(e);for(let i=0;i<e.length;i++){let o=e[i];if(o!==null&&typeof o=="object"&&r.seen.has(o)){t.push("circular reference detected in array"),n.push("<circular>");continue}let s=$2(o,r);if(!s.ok)return s;n.push(s.value)}return{ok:!0,value:n,notes:t}}function XDt(e){let t=e,n=[],r={seen:new WeakSet,depth:0,notes:n};r.seen.add(e);let i={},o=Object.keys(t).slice(0,ICe);for(let s of o){if(yCe(s)){i[s]=am,n.push(`field "${s}" redacted`);continue}let a=t[s];if(a!==null&&typeof a=="object"&&r.seen.has(a)){n.push(`circular reference detected at "${s}"`),i[s]="<circular>";continue}let c=$2(a,r);if(!c.ok)return c;i[s]=c.value}return{ok:!0,value:i,notes:n}}function ZO(e){if(e===null)return{ok:!1,error:"redactSensitiveFields: null is not a redactable object",nextAction:"pass a JSON object or array; null carries no fields to redact"};if(e===void 0)return{ok:!1,error:"redactSensitiveFields: undefined is not a redactable object",nextAction:"pass a JSON object or array; undefined carries no fields to redact"};let t=typeof e;return t!=="object"?{ok:!1,error:`redactSensitiveFields: top-level value must be an object or array (got ${t})`,nextAction:"pass a JSON object or array; for primitive values use redactTokenLikeValues / redactEnvLikeValues / redactAbsolutePaths"}:Array.isArray(e)?JDt(e):XDt(e)}var ECe="\u2026[canonical-json-truncated]";function eN(e,t=new WeakSet){if(e===null)return"null";let n=typeof e;if(n==="string")return JSON.stringify(e);if(n==="number")return Number.isFinite(e)?String(e):"null";if(n==="boolean")return String(e);if(n==="bigint")return JSON.stringify(`${String(e)}n`);if(n==="undefined"||n==="function"||n==="symbol")return"null";if(Array.isArray(e)){if(t.has(e))return'"[Circular]"';t.add(e);let r=e.map(i=>eN(i,t));return t.delete(e),`[${r.join(",")}]`}if(e instanceof Date)return JSON.stringify(Number.isNaN(e.getTime())?null:e.toISOString());if(e instanceof Map){if(t.has(e))return'"[Circular]"';t.add(e);let i=[...e.entries()].map(([o,s])=>[String(o),s]).sort(([o],[s])=>o<s?-1:o>s?1:0).map(([o,s])=>`${JSON.stringify(o)}:${eN(s,t)}`).join(",");return t.delete(e),`{${i}}`}if(e instanceof Set){if(t.has(e))return'"[Circular]"';t.add(e);let r=[...e.values()].map(i=>eN(i,t));return t.delete(e),`[${r.join(",")}]`}if(n==="object"){let r=e;if(t.has(r))return'"[Circular]"';t.add(r);let i=Object.keys(r).sort((s,a)=>s<a?-1:s>a?1:0),o=[];for(let s of i){let a=eN(r[s],t),c=r[s],l=typeof c;c===void 0||l==="function"||l==="symbol"||o.push(`${JSON.stringify(s)}:${a}`)}return t.delete(r),`{${o.join(",")}}`}return'"[Unserializable]"'}function ZDt(e){let t=eN(e);if(t.length<=262144)return{text:t,truncated:!1};let n=262144-ECe.length;return{text:`${t.slice(0,Math.max(0,n))}${ECe}`,truncated:!0}}function Q9(e,t){return t(ZDt(e).text)}var uy=["diag_rootcause","diag_distiller","diag_router","dreamer","philosopher","scribe","artificer","evaluator"],q2=1,$9=200,eOt=600;function T_(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function tOt(e){return uy.includes(e)}function so(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n!="string"||n.trim()===""?null:n}function Lb(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return T_(n)?n:null}function Mb(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return Array.isArray(n)?n:null}function W2(e,t){let n=Mb(e,t);if(n===null)return null;let r=n.filter(i=>typeof i=="string"&&i.trim()!=="");return r.length===0?null:r.join(" / ")}function nOt(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="number"&&Number.isFinite(n)?String(n):null}function rOt(e,t){if(!T_(e)||!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="boolean"?String(n):null}function G2(e,t){return e.length<=t?e:`${e.slice(0,t-1)}\u2026`}function tN(e){let n=/^[\s\S]*?[。;;.]/.exec(e)?.[0]??e;return G2(n.trim(),$9)}function W9(e){let t=e.filter(n=>n!==null&&n.trim()!=="");return t.length===0?null:G2(t.join("; "),$9)}function iOt(e){let t=so(e,"rootCause");return{headlineSource:t===null?null:tN(t),resolved:{rootSymptom:so(e,"summary"),category:so(e,"rootCauseCategory"),severity:null,rootCause:t}}}function oOt(e){let t=so(e,"abstractedPrinciple");return{headlineSource:t===null?null:tN(t),resolved:{rootCause:so(e,"rationale"),affectedComponents:null,category:so(e,"scope"),severity:null}}}function sOt(e){let t=so(e,"summary"),r=(Mb(e,"violatedPrinciples")??[]).map(s=>so(s,"principleId")).filter(s=>s!==null),i=Mb(e,"recommendations")??[],o=i.length>0?so(i[0],"kind"):null;return{headlineSource:W9([t,o]),resolved:{rootCause:so(e,"rootCause"),affectedComponents:r.length>0?r.join(" / "):null,rootSymptom:t,category:o,severity:null}}}function aOt(e){let t=Mb(e,"candidates")??[],n=t.length>0?t[0]:null,r=so(n,"betterDecision");return{headlineSource:r===null?null:tN(r),resolved:{badDecision:so(n,"badDecision"),betterDecision:r,rationale:so(n,"rationale"),riskLevel:so(n,"riskLevel"),strategicPerspective:so(n,"strategicPerspective")}}}function cOt(e){let t=Lb(e,"principleCandidate"),n=so(t,"title");return{headlineSource:n,resolved:{thesis:so(e,"thesis"),principleTitle:n,principleScope:so(t,"scope"),principleConfidence:nOt(t,"confidence")}}}function lOt(e){let t=Lb(e,"principleDraft"),n=so(t,"statement"),r=Lb(e,"intentContract");return{headlineSource:n===null?null:tN(n),resolved:{principleText:n,scope:W2(t,"applicability"),exceptions:W2(t,"antiPatterns"),intentOwner:so(r,"ownerIntent"),intentForbidden:so(r,"forbiddenBehavior"),intentValidation:so(r,"validationExpectation")}}}function uOt(e){let t=W2(e,"affectedTools"),n=so(e,"implementationSummary"),r=Mb(e,"affectedTools")?.length??null;return{headlineSource:W9([r!==null?`${r} affected tools`:null,n===null?null:tN(n)]),resolved:{changedFiles:t,apiSurface:n,risks:W2(e,"risks")}}}function dOt(e){let t=Lb(e,"evaluation"),n=so(t,"decision"),r=Mb(t,"concerns"),i=r===null?null:String(r.length),o=Lb(e,"codeReview"),s=Lb(o,"intentConsistency");return{headlineSource:W9([n===null?null:`verdict=${n}`,i===null?null:`concerns=${i}`]),resolved:{verdict:n,concernCount:i,intentConsistency:rOt(s,"aligned")}}}var pOt={diag_rootcause:iOt,diag_distiller:oOt,diag_router:sOt,dreamer:aOt,philosopher:cOt,scribe:lOt,artificer:uOt,evaluator:dOt};function Bb(e,t){if(!tOt(e))return{ok:!1,reason:"unsupported_runner_kind",detail:`Unsupported SummaryRunnerKind: ${String(e)}`};if(!T_(t))return{ok:!1,reason:"output_not_object",detail:`validatedOutput for runnerKind "${e}" is not a non-null object`};let n=pOt[e],{headlineSource:r,resolved:i}=n(t),o={},s=[];for(let[a,c]of Object.entries(i))c!==null?o[a]=G2(c,eOt):s.push(a);return r===null&&Object.keys(o).length===0?{ok:!1,reason:"no_derivable_field",detail:`No derivable headline or field for runnerKind "${e}" from the given output`}:{ok:!0,value:{schemaVersion:q2,runnerKind:e,headline:r===null?"":G2(r,$9),fields:o,derivedFrom:"structured_output",omittedFields:s}}}function fOt(e){if(e===null||typeof e!="object"||Array.isArray(e)||!Object.hasOwn(e,"summary"))return null;let{summary:t}=e;if(t===null||typeof t!="object"||Array.isArray(t))return null;let n=t;if(!Object.hasOwn(n,"schemaVersion")||n.schemaVersion!==q2||!Object.hasOwn(n,"runnerKind")||typeof n.runnerKind!="string"||!uy.includes(n.runnerKind)||!Object.hasOwn(n,"headline")||typeof n.headline!="string"||!Object.hasOwn(n,"fields")||n.fields===null||typeof n.fields!="object"||Array.isArray(n.fields))return null;let r=n.fields;return!Object.values(r).every(i=>typeof i=="string")||!Object.hasOwn(n,"derivedFrom")||n.derivedFrom!=="structured_output"||!Object.hasOwn(n,"omittedFields")||!Array.isArray(n.omittedFields)||!n.omittedFields.every(i=>typeof i=="string")?null:{schemaVersion:q2,runnerKind:n.runnerKind,headline:n.headline,fields:r,derivedFrom:"structured_output",omittedFields:n.omittedFields}}function _Ce(e,t,n,r,i){let o=Bb(e,t);if(!o.ok)return i({type:"artifact_summary_skipped",runnerKind:e,reason:o.reason}),{};let s={summary:o.value};if(n===null)return i({type:"artifact_summary_predecessor_absent",runnerKind:e,reason:"no_predecessor_in_context"}),s;let a=fOt(n.contentJson);if(a===null){let c=Bb(n.runnerKind,n.contentJson);if(!c.ok)return i({type:"artifact_summary_predecessor_skipped",runnerKind:e,reason:c.reason}),s;a=c.value}return{...s,predecessorSummary:{artifactId:n.artifactId,runnerKind:n.runnerKind,contentHash:Q9(n.contentJson,r),summary:a}}}var nN={betterDecision:"required",rationale:"required",riskLevel:"required",badDecision:"optional",strategicPerspective:"excluded"},jrr=Object.entries(nN).filter(([,e])=>e==="required").map(([e])=>e),xCe=["badDecision","betterDecision","rationale","riskLevel","strategicPerspective"];function mOt(e){if(Object.hasOwn(nN,e))return nN[e]}function vCe(e){return mOt(e)==="required"}var Fb=1;function wCe(e){let t=new Set,n=[];for(let r of e)t.has(r)||(t.add(r),n.push(r));return n}var Yrr=xCe.filter(e=>nN[e]!=="excluded");function bCe(e,t){let n=t.priority.indexOf(e);if(n>=0)return n;let r=wCe([...t.tier0,...t.tier1,...t.tier2]).indexOf(e),i=r>=0?r:0;return t.priority.length+i}function k_(e){return wCe([...e.tier0,...e.tier1,...e.tier2])}function hOt(e){return Math.ceil(e.length/4)}var gOt=600,AOt=8,CCe="\u2026[budget-truncated]";function SCe(e,t,n){let r=k_(e),i=[],o=[];for(let l of r){if(!t.has(l)){o.push(l);continue}let u=wo(t.get(l),gOt);i.push({path:l,text:u,tokens:hOt(u),rank:bCe(l,e)})}i.sort((l,u)=>l.rank-u.rank||(l.path<u.path?-1:l.path>u.path?1:0));let s={},a=[],c=e.budgetTokens;for(let l of i)if(l.tokens<=c)s[l.path]=l.text,c-=l.tokens;else if(c>AOt){let u=Math.max(0,c*4-CCe.length),d=l.text.slice(0,u)+CCe;s[l.path]=d;let p={fieldPath:l.path,reason:"partially_truncated",remainingBudgetTokens:c,keptChars:d.length,droppedChars:l.text.length-d.length};a.push(p),n({type:"context_truncated",runnerKind:e.runnerKind,manifestId:e.manifestId,fieldPath:l.path,reason:p.reason,remainingBudgetTokens:c}),c=0}else{let u={fieldPath:l.path,reason:"budget_exceeded",remainingBudgetTokens:c,keptChars:0,droppedChars:l.text.length};a.push(u),n({type:"context_truncated",runnerKind:e.runnerKind,manifestId:e.manifestId,fieldPath:l.path,reason:u.reason,remainingBudgetTokens:c})}return{manifestId:e.manifestId,fields:s,truncated:a,absent:o,usedTokens:e.budgetTokens-c,budgetTokens:e.budgetTokens}}var yOt=.5;function TCe(e,t,n){let r=SCe(e,t,u=>n(u)),o=k_(e).length,s=r.absent.length,a=o>0?s/o:1,c=()=>({type:"manifest_resolution_insufficient",runnerKind:e.runnerKind,manifestId:e.manifestId,absentCount:s,declaredCount:o,absentRatio:a,fallback:"full_predecessor_injection"});return Object.keys(r.fields).length===0?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"empty_allocation",absentRatio:a}):e.tier1.length>0&&e.tier1.every(u=>r.absent.includes(u))?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"tier1_all_absent",absentRatio:a}):a>yOt?(n(c()),{kind:"fallback",allocated:r,fellBack:!0,reason:"absent_ratio_exceeded",absentRatio:a}):{kind:"focused",allocated:r,fellBack:!1}}function rN(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function kCe(e,t){if(!rN(e)||!Object.hasOwn(e,"summary"))return;let{summary:n}=e;if(!rN(n))return;if(t==="headline")return Object.hasOwn(n,"headline")?n.headline:void 0;let r=Object.hasOwn(n,"fields")?n.fields:void 0;if(rN(r)&&Object.hasOwn(r,t))return r[t];if(Object.hasOwn(n,t))return n[t]}function IOt(e,t){if(!rN(e)||!Object.hasOwn(e,"predecessorSummary"))return;let{predecessorSummary:n}=e;if(!(!rN(n)||!Object.hasOwn(n,"summary")))return kCe(n,t)}function G9(e,t){let n=e.indexOf("summary."),r=e.indexOf("predecessorSummary."),i=e.indexOf("raw.");if(!(i>=0&&(n<0||i<n)&&(r<0||i<r))){if(r>=0&&(n<0||r<n)){let o=e.slice(r+19);return IOt(t,o)}if(n>=0){let o=e.slice(n+8);return kCe(t,o)}}}function q9(e,t){let n=new Map;for(let r of e){let i=G9(r,t);i!==void 0&&n.set(r,i)}return n}var EOt=6,H2="pi-art-",_Ot="-run_";function xOt(e){if(!e.startsWith(H2))return null;let t=e.lastIndexOf(_Ot);if(t<=H2.length)return null;let n=e.slice(H2.length,t);if(n==="")return null;let r=e.slice(t+1+4),i=`${n}_`;if(!r.startsWith(i))return null;let o=r.slice(i.length);return/^(0|[1-9][0-9]*)$/.test(o)?n:null}function H9(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function vOt(e){if(!H9(e)||!Object.hasOwn(e,"summary"))return;let{summary:t}=e;if(H9(t)&&Object.hasOwn(t,"schemaVersion")&&t.schemaVersion===1&&Object.hasOwn(t,"runnerKind")&&typeof t.runnerKind=="string"&&uy.includes(t.runnerKind)&&Object.hasOwn(t,"headline")&&typeof t.headline=="string"&&Object.hasOwn(t,"fields")&&H9(t.fields)&&Object.values(t.fields).every(n=>typeof n=="string")&&Object.hasOwn(t,"derivedFrom")&&t.derivedFrom==="structured_output"&&Object.hasOwn(t,"omittedFields")&&Array.isArray(t.omittedFields)&&t.omittedFields.every(n=>typeof n=="string"))return{schemaVersion:1,runnerKind:t.runnerKind,headline:t.headline,fields:t.fields,derivedFrom:"structured_output",omittedFields:t.omittedFields}}var iN=class{artifacts;tasks;maxDepth;emit;cache=new Map;taskCache=new Map;constructor(t){this.artifacts=t.artifacts,this.tasks=t.tasks,this.maxDepth=t.maxDepth??EOt,this.emit=t.emit??(()=>{})}async resolve(t){return this.resolveChain(t,new Set)}async findAncestorByTaskKind(t,n){let r=await this.resolve(t);return r.ok?{ok:!0,node:r.value.nodes.find(o=>o.taskKind===n)??null,notes:r.value.notes}:{ok:!1,error:r.error}}async resolveChain(t,n){let r=[],i=[],o=new Set,s=[t],a=0;for(;s.length>0;){if(a>=this.maxDepth){let[l]=s;i.push({code:"depth_limit_reached",artifactId:l??t,detail:`maxDepth (${this.maxDepth}) reached; remaining ${s.length} ancestor(s) not traversed`}),this.emit({type:"lineage_partial",artifactId:l??t,noteCode:"depth_limit_reached",detail:`maxDepth ${this.maxDepth}`});break}let c=s.length;for(let l=0;l<c;l++){let u=s.shift();if(u===void 0)break;if(n.has(u)){i.push({code:"cycle_detected",artifactId:u,detail:`artifact ${u} already on the resolution path`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"cycle_detected",detail:"cycle detected"});continue}n.add(u);let d=await this.getArtifactCached(u);if(!d.ok)return d;let p=d.value;if(p===null){let T=await this.tryReboundInstance(u);if(!T.ok)return T;if(p=T.value,p===null){i.push({code:"ancestor_pruned",artifactId:u,detail:T.ambiguousCandidates!==void 0?`ancestor artifact ${u} not rebound: ambiguous current artifacts for source task (${T.ambiguousCandidates} same-family candidates) \u2014 refusing to pick by array order`:`ancestor artifact ${u} not found (pruned)`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"ancestor_pruned",detail:"artifact not found"});continue}}if(o.has(p.artifactId))continue;o.add(p.artifactId);let m;try{m=JSON.parse(p.contentJson)}catch{let T={kind:"content_json_unparseable",artifactId:u,detail:`contentJson of ${u} is not valid JSON`};return this.emit({type:"lineage_data_corrupt",artifactId:u,detail:T.detail,errorKind:"content_json_unparseable"}),{ok:!1,error:T}}if(typeof p.sourceTaskId!="string"||p.sourceTaskId===""){let T={kind:"artifact_shape_invalid",artifactId:u,detail:`artifact ${u} missing required sourceTaskId`};return this.emit({type:"lineage_data_corrupt",artifactId:u,detail:T.detail,errorKind:"artifact_shape_invalid"}),{ok:!1,error:T}}let g=await this.getTaskCached(p.sourceTaskId);if(!g.ok)return g;let A=g.value,_,x;A===null?(_="unknown",x="unknown",i.push({code:"task_missing",artifactId:u,detail:`task ${p.sourceTaskId} not found; cannot determine stage via two-hop`}),this.emit({type:"lineage_partial",artifactId:u,noteCode:"task_missing",detail:`task ${p.sourceTaskId} missing`})):({taskKind:_}=A,x=uy.includes(_)?_:"unknown");let v={artifactId:p.artifactId,taskId:p.sourceTaskId,taskKind:_,runnerKind:x,contentJson:m,summary:vOt(m)};r.push(v);let k=Array.isArray(p.lineageArtifactIds)?p.lineageArtifactIds:[];k.length===0&&r.length;for(let T of k)typeof T=="string"&&T!==""&&s.push(T)}a++}return{ok:!0,value:{nodes:r,complete:i.length===0,notes:i}}}async tryReboundInstance(t){let n=xOt(t);if(n===null)return{ok:!0,value:null};try{let r=await this.artifacts.listBySourceTaskId(n),i=`${H2}${n}-run_`,o=r.filter(a=>a.artifactId.startsWith(i));if(o.length!==1)return{ok:!0,value:null,...o.length>1?{ambiguousCandidates:o.length}:{}};let[s]=o;return s===void 0?{ok:!0,value:null}:(this.cache.set(t,s),this.emit({type:"lineage_edge_rebound",staleArtifactId:t,resolvedArtifactId:s.artifactId,taskId:n}),{ok:!0,value:s})}catch(r){let i={kind:"store_failure",detail:r instanceof Error?r.message:String(r)};return this.emit({type:"lineage_store_failure",detail:i.detail}),{ok:!1,error:i}}}async getArtifactCached(t){if(this.cache.has(t))return{ok:!0,value:this.cache.get(t)??null};try{let n=await this.artifacts.getArtifactById(t);return this.cache.set(t,n),{ok:!0,value:n}}catch(n){let r={kind:"store_failure",detail:n instanceof Error?n.message:String(n)};return this.emit({type:"lineage_store_failure",detail:r.detail}),{ok:!1,error:r}}}async getTaskCached(t){if(this.taskCache.has(t))return{ok:!0,value:this.taskCache.get(t)??null};try{let n=await this.tasks.getTaskById(t);return this.taskCache.set(t,n),{ok:!0,value:n}}catch(n){let r={kind:"store_failure",detail:n instanceof Error?n.message:String(n)};return this.emit({type:"lineage_store_failure",detail:r.detail}),{ok:!1,error:r}}}};function Ub(e){let t=e.split(".");if(t.length<3)return null;let[n,r]=t,i=t.slice(2);return n===void 0||n===""||r!=="raw"&&r!=="summary"&&r!=="predecessorSummary"||i.length===0||i.some(o=>o==="")?null:{namespace:n,layer:r,rest:i}}var j9=new Set(["__proto__","constructor","prototype"]);function RCe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}var wOt=/^(0|[1-9][0-9]*)$/;function bOt(e,t){let n=t;for(let r of e){if(j9.has(r))return;if(Array.isArray(n)){if(!wOt.test(r)||!Object.hasOwn(n,r))return;n=n[Number(r)];continue}if(!RCe(n)||!Object.hasOwn(n,r))return;n=n[r]}return n}var COt={diagnostician:["diagnostician","diag_router"]},SOt={diagnostician:"diag_router"};function TOt(e,t,n){let r=G9(e,n);if(r!==void 0)return r;if(!RCe(n))return;let i=SOt[t]??(uy.includes(t)?t:void 0);if(i===void 0)return;let o=Bb(i,n);if(!o.ok)return;let s=Ub(e);if(s===null)return;let[a]=s.rest;if(!(a===void 0||j9.has(a))){if(a==="headline")return o.value.headline;if(Object.hasOwn(o.value.fields,a))return o.value.fields[a]}}function DCe(e){let t=[];for(let n of e)n.taskKind==="unknown"||n.taskKind===""||t.push({stage:n.taskKind,contentJson:n.contentJson});return t}function OCe(e,t){let n=new Set(t),r=[],i=[];for(let o of e){let s=Ub(o);if(s!==null&&s.layer==="raw"&&n.has(s.namespace)){i.push(o);continue}r.push(o)}return{ancestry:r,related:i}}function NCe(e,t){let n=new Map;for(let r of e){let i=Ub(r);if(i===null||i.layer==="predecessorSummary")continue;let o=[i.namespace,...COt[i.namespace]??[]],s=t.find(c=>o.includes(c.stage));if(s===void 0)continue;let a=i.layer==="raw"?bOt(i.rest,s.contentJson):TOt(r,s.stage,s.contentJson);a!==void 0&&n.set(r,a)}return n}function PCe(e,t){let n=new Map;for(let r of e){let i=Ub(r);if(i===null||i.rest.length!==1||i.layer==="predecessorSummary")continue;let o=t.find(l=>l.namespace===i.namespace);if(o===void 0)continue;let s=i.layer==="raw"?o.raw:o.summary;if(s===void 0)continue;let[a]=i.rest;if(a===void 0||j9.has(a)||!Object.hasOwn(s,a))continue;let c=s[a];c!==void 0&&n.set(r,c)}return n}function LCe(e,t){let n=new Map(e);for(let r of t)for(let[i,o]of r)n.has(i)||n.set(i,o);return n}function MCe(e){let t=new Set(e.absent),n=new Set(e.truncated.map(r=>r.fieldPath));return e.required.filter(r=>t.has(r)||n.has(r))}var K9={pollIntervalMs:5e3,timeoutMs:3e5,defaultMaxAttempts:3,agentId:"peer-runner",coreGrounding:!0};function kOt(e,t){return{pollIntervalMs:e.pollIntervalMs??K9.pollIntervalMs,timeoutMs:e.timeoutMs??K9.timeoutMs,defaultMaxAttempts:e.defaultMaxAttempts??K9.defaultMaxAttempts,owner:e.owner,runtimeKind:e.runtimeKind,agentId:e.agentId??t,outputLanguage:e.outputLanguage,coreGrounding:e.coreGrounding??!0}}function ROt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function DOt(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=JSON.parse(e)}catch{return null}if(!ROt(t)||!Object.hasOwn(t,"sourcePainId"))return null;let{sourcePainId:n}=t;return typeof n!="string"||n.length===0?null:n}var Ai=class{stateManager;runtimeAdapter;eventEmitter;artifactStore;resolvedOptions;config;pendingAgentDraftStore;contentHashFn;phase=Hn.Idle;currentLeasedAttempt;constructor(t,n,r){this.stateManager=t.stateManager,this.runtimeAdapter=t.runtimeAdapter,this.eventEmitter=t.eventEmitter,this.artifactStore=t.artifactStore,this.pendingAgentDraftStore=t.pendingAgentDraftStore,this.contentHashFn=t.contentHashFn,this.config=r,this.resolvedOptions=kOt(n,r.defaultAgentId)}get currentPhase(){return this.phase}getRuntimeKind(){return typeof this.runtimeAdapter.kind=="function"?this.runtimeAdapter.kind():this.resolvedOptions.runtimeKind}async maybeResumePendingIntent(t,n){return null}emitSuccessTelemetry(t,n,r){}checkLineageIntegrity(t,n,r){}postFetchTransform(t,n,r){typeof n=="object"&&n!==null&&!Array.isArray(n)&&Reflect.set(n,"generatedAt",new Date().toISOString())}async run(t){this.phase=Hn.Idle;let n=this.getRuntimeKind(),r;try{r=await this.stateManager.acquireLease({taskId:t,owner:this.resolvedOptions.owner,runtimeKind:n})}catch(o){return await this.handleLeaseOrPhaseError(t,o)}if(r.taskKind!==this.config.expectedTaskKind)return this.emitEvent("wrong_task_kind",t,{expectedKind:this.config.expectedTaskKind,actualKind:r.taskKind}),await this.stateManager.markTaskFailed(t,"input_invalid"),{status:"failed",taskId:t,errorCategory:"input_invalid",failureReason:`Task kind must be '${this.config.expectedTaskKind}', got '${r.taskKind}'`,attemptCount:r.attemptCount};this.emitEvent("task_leased",t,{taskKind:this.config.expectedTaskKind,attemptCount:r.attemptCount});let i=await this.maybeResumePendingIntent(t,r);if(i)return this.phase=Hn.Completed,i;try{let o=await this.resolveStoreRunId(t);this.phase=Hn.BuildingContext,this.currentLeasedAttempt=r.attemptCount;let s=await this.buildContext(t);this.emitEvent("context_built",t,{contextHash:s.contextHash}),this.phase=Hn.Invoking;let a=await this.invokeRuntime(t,s);this.emitEvent("run_started",t,{runtimeKind:n}),this.phase=Hn.Polling;let c=await this.pollUntilTerminal(a);if(c.status!=="succeeded")return await this.handleRuntimeFailure(t,r,c);this.phase=Hn.FetchingOutput;let l=await this.fetchAndParseOutput(a.runId,t);this.postFetchTransform(t,l,s),this.phase=Hn.Validating;let u=await this.validateOutput(l,t,s);if(!u.valid)return await this.handleValidationError({taskId:t,task:r,errors:u.errors,errorCategory:u.errorCategory});let d=l;this.emitEvent("output_validated",t,{}),this.checkLineageIntegrity(t,d,s),this.emitSuccessTelemetry(t,d,s);let p=await this.succeedTask(t,o,d,r,s.contextHash,s);return p.status==="succeeded"&&(this.phase=Hn.Completed),p}catch(o){return await this.handlePostLeaseError(t,r,o)}}emitEvent(t,n,r){this.eventEmitter.emitTelemetry({eventType:`${this.config.runnerName}_${t}`,traceId:n,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:r})}async pollUntilTerminal(t){let n=Date.now()+this.resolvedOptions.timeoutMs,r=["succeeded","failed","timed_out","cancelled"];for(;Date.now()<n;){let s=await this.runtimeAdapter.pollRun(t.runId);if(r.includes(s.status))return s;await this.sleep(this.resolvedOptions.pollIntervalMs)}try{let s=await this.runtimeAdapter.pollRun(t.runId);if(r.includes(s.status))return s}catch{}let i=!1;try{await this.runtimeAdapter.cancelRun(t.runId)}catch(s){i=!0,this.emitEvent("cancel_run_failed",t.runId,{runId:t.runId,errorMessage:s instanceof Error?s.message:String(s)})}let o=i?" (cancelRun also failed)":"";throw new Y("timeout",`Run ${t.runId} timed out after ${this.resolvedOptions.timeoutMs}ms${o}`)}async fetchAndParseOutput(t,n){let r;try{r=await this.runtimeAdapter.fetchOutput(t)}catch(o){throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"fetchOutput",errorMessage:o instanceof Error?o.message:String(o)}),o}if(!r||!r.payload)throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"payload_missing",errorMessage:`No output available for run ${t}`}),new Y("output_invalid",`No output available for run ${t}`);let{payload:i}=r;if(typeof i!="object"||i===null)throw this.emitEvent("output_extraction_failed",n,{runId:t,stage:"payload_not_object",errorMessage:`Output payload is not an object for run ${t}`}),new Y("output_invalid",`Output payload is not an object for run ${t}`);return i}async resolveLineageArtifactIds(t){let{hydratePITaskRecord:n}=await Promise.resolve().then(()=>(Po(),Nbe)),r=await this.stateManager.getTask(t);if(!r)return{ids:[],hasRejected:!1};let o=n(r)?.dependencyTaskIds??[];if(o.length===0)return{ids:[],hasRejected:!1};let s=[],a=!1,c=await Promise.allSettled(o.map(l=>this.artifactStore.listBySourceTaskId(l)));for(let l of c)if(l.status==="fulfilled")for(let u of l.value)s.push(u.artifactId);else a=!0;return{ids:s,hasRejected:a}}async resolveStoreRunId(t){let{runs:n,degradedRuns:r}=await this.stateManager.getValidRunsByTaskTolerant(t);r.length>0&&this.eventEmitter.emitTelemetry({eventType:"degradation_triggered",traceId:t,timestamp:new Date().toISOString(),sessionId:this.resolvedOptions.owner,agentId:this.resolvedOptions.agentId,payload:{component:"BasePeerRunner",runnerName:this.config.runnerName,trigger:"malformed_historical_run_rows",degradedCount:r.length,runIds:r.map(o=>o.runId),errors:r.map(o=>o.error),nextAction:"Quarantine malformed run rows: pd runtime internalization integrity-repair --confirm"}});let i=n[n.length-1];if(!i)throw new Y("execution_failed",`No valid run records found for task ${t} after lease acquisition. If historical runs are malformed, quarantine them first: pd runtime internalization integrity-repair --confirm`);return i.runId}static hashContextRefs(t){if(t.length===0)return"empty";let n=t.join("|"),r=0;for(let i=0;i<n.length;i++)r=Math.imul(31,r)+n.charCodeAt(i)|0;return`ctx-${Math.abs(r).toString(16)}`}async handleLeaseOrPhaseError(t,n){let r=this.classifyError(n);if(r.category==="lease_conflict")return this.emitEvent("run_failed",t,{errorCategory:"lease_conflict",errorMessage:r.message}),{status:"failed",taskId:t,errorCategory:"lease_conflict",failureReason:r.message,attemptCount:1};this.emitEvent("run_failed",t,{errorCategory:r.category,errorMessage:r.message});let i={taskId:t,taskKind:this.config.expectedTaskKind,status:"leased",createdAt:new Date().toISOString(),updatedAt:new Date().toISOString(),attemptCount:1,maxAttempts:this.resolvedOptions.defaultMaxAttempts};return r.details&&Object.keys(r.details).length>0&&await this.persistOutputFailureDetails(t,void 0,{errorCategory:r.category,errorMessage:r.message,...r.details}),this.retryOrFail({taskId:t,task:i,errorCategory:r.category,failureReason:r.message})}async handlePostLeaseError(t,n,r){let i=this.classifyError(r);return this.emitEvent("run_failed",t,{errorCategory:i.category,errorMessage:i.message}),i.details&&Object.keys(i.details).length>0&&await this.persistOutputFailureDetails(t,n.diagnosticJson,{errorCategory:i.category,errorMessage:i.message,...i.details}),this.retryOrFail({taskId:t,task:n,errorCategory:i.category,failureReason:i.message})}async handleRuntimeFailure(t,n,r){let i=this.mapRunStatusToErrorCategory(r.status,r.reason);return this.emitEvent("run_failed",t,{runStatus:r.status,errorCategory:i}),this.retryOrFail({taskId:t,task:n,errorCategory:i,failureReason:r.reason?`Runtime execution ended with status: ${r.status}. Reason: ${r.reason}`:`Runtime execution ended with status: ${r.status}`})}async handleValidationError(t){let n=t.errorCategory??"output_invalid";return this.emitEvent("output_invalid",t.taskId,{errorCount:t.errors.length,errorCategory:n}),await this.persistOutputFailureDetails(t.taskId,t.task.diagnosticJson,{errorCategory:n,validatorErrors:[...t.errors],errorCount:t.errors.length},{lastValidatorErrors:{recordedAt:new Date().toISOString(),errorCategory:n,errors:[...t.errors],sourceAttemptCount:t.task.attemptCount}}),this.retryOrFail({taskId:t.taskId,task:t.task,errorCategory:n,failureReason:`Validation failed: ${t.errors.join("; ")}`})}async retryOrFail(t){if(this.permanentErrorCategories.has(t.errorCategory)){try{await this.stateManager.markTaskFailed(t.taskId,t.errorCategory,t.failureReason)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount,failureReason:t.failureReason}),this.phase=Hn.Failed,this.injectAgentDraftOnPermanentFailure(t),{status:"failed",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}if(t.errorCategory==="rate_limit"&&this.isDegradationEnabled()){try{await this.stateManager.markTaskFailed(t.taskId,"rate_limit",`LLM rate limit degraded: ${t.failureReason}`)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("diag_llm_rate_limit_degraded",t.taskId,{errorCategory:"rate_limit",attemptCount:t.task.attemptCount,failureReason:t.failureReason,nextAction:"Retry diagnosis manually with `pd pain retry` when rate limit clears, or enable fallback provider."}),this.phase=Hn.Failed,{status:"failed",taskId:t.taskId,errorCategory:"rate_limit",failureReason:`LLM rate limit degraded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}if(this.stateManager.getRetryPolicy().shouldRetry(t.task)){try{await this.stateManager.markTaskRetryWait(t.taskId,t.errorCategory,t.failureReason)}catch(r){return this.emitEvent("mark_retry_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_retried",t.taskId,{errorCategory:t.errorCategory,attemptCount:t.task.attemptCount}),this.phase=Hn.RetryWaiting,{status:"retried",taskId:t.taskId,errorCategory:t.errorCategory,failureReason:t.failureReason,attemptCount:t.task.attemptCount}}try{await this.stateManager.markTaskFailed(t.taskId,"max_attempts_exceeded",`Max attempts exceeded: ${t.failureReason}`)}catch(r){return this.emitEvent("mark_failed_error",t.taskId,{errorCategory:"storage_unavailable",attemptCount:t.task.attemptCount,errorMessage:r instanceof Error?r.message:String(r)}),{status:"failed",taskId:t.taskId,errorCategory:"storage_unavailable",failureReason:`State manager error: ${t.failureReason}`,attemptCount:t.task.attemptCount}}return this.emitEvent("task_failed",t.taskId,{errorCategory:"max_attempts_exceeded",attemptCount:t.task.attemptCount,failureReason:`Max attempts exceeded: ${t.failureReason}`}),this.phase=Hn.Failed,{status:"failed",taskId:t.taskId,errorCategory:"max_attempts_exceeded",failureReason:`Max attempts exceeded: ${t.failureReason}`,attemptCount:t.task.attemptCount}}classifyError(t){return t instanceof Y?{category:t.category,message:t.message,details:t.details}:t instanceof Error?{category:"execution_failed",message:t.message}:{category:"execution_failed",message:String(t)}}async persistOutputFailureDetails(t,n,r,i){try{let o={};if(n){let s=JSON.parse(n);typeof s=="object"&&s!==null&&!Array.isArray(s)&&(o=s)}o.output_failure_details={recordedAt:new Date().toISOString(),...r},i!==void 0&&Object.assign(o,i),await this.stateManager.updateTask(t,{diagnosticJson:JSON.stringify(o)})}catch(o){this.emitEvent("mark_failed_error",t,{errorCategory:"storage_unavailable",errorMessage:`persistOutputFailureDetails failed: ${o instanceof Error?o.message:String(o)}`})}}mapRunStatusToErrorCategory(t,n){switch(t){case"failed":return"execution_failed";case"timed_out":return"timeout";case"cancelled":return"cancelled";default:return"execution_failed"}}sleep(t){return new Promise(n=>setTimeout(n,t))}isDegradationEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"diagnostician_llm_degradation")}isArtifactSummaryEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"artifact_summary_redundancy")}buildArtifactContentJson(t,n,r,i){if(!this.isArtifactSummaryEnabled())return JSON.stringify(r);try{let o=this.contentHashFn,s=o?i:null;!o&&i!==null&&this.emitEvent("artifact_summary_predecessor_skipped",t,{runnerKind:n,reason:"content_hash_fn_not_injected",nextAction:"Inject contentHashFn into PeerRunnerDeps (plugin/CLI layer) to enable predecessorSummary."});let a=_Ce(n,r,s,o??(u=>u),u=>{this.emitEvent(u.type,t,{runnerKind:u.runnerKind,reason:u.reason})});if(a.summary===void 0||r===null||typeof r!="object"||Array.isArray(r))return JSON.stringify(r);let c=r,l=Object.hasOwn(c,"summary");return l&&this.emitEvent("artifact_summary_skipped",t,{runnerKind:n,reason:"output_summary_key_collision",nextAction:"Runner output already declares a top-level `summary` field; the Layer 0 envelope summary key is skipped to avoid overwriting it. predecessorSummary is still attached."}),JSON.stringify({...c,...l?{}:{summary:a.summary},...a.predecessorSummary!==void 0?{predecessorSummary:a.predecessorSummary}:{}})}catch(o){return this.emitEvent("artifact_summary_skipped",t,{runnerKind:n,reason:"unexpected_error",errorMessage:o instanceof Error?o.message:String(o)}),JSON.stringify(r)}}isContextManifestBudgetEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"context_manifest_budget")}isProgressiveEvaluatorEnabled(){let{effectiveConfig:t}=this.config;if(!t)return!1;let n=li(t);return Is(n,"progressive_evaluator")}async runSingleEvaluation(t,n,r){let i=this.getRuntimeKind(),o=await this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:n,contextItems:[],outputSchemaRef:this.config.resultRefPrefix.includes("evaluator")?"evaluator-output-v1":`${this.config.expectedTaskKind}-output-v1`,timeoutMs:this.resolvedOptions.timeoutMs,systemPrompt:r});this.emitEvent("run_started",t,{runtimeKind:i,stage:"progressive_evaluation"});let s=await this.pollUntilTerminal(o);if(s.status!=="succeeded")throw new Y(s.status==="timed_out"?"timeout":"execution_failed",`Progressive evaluation run ${o.runId} ended with status ${s.status}`);return this.fetchAndParseOutput(o.runId,t)}resolveContextInjection(t,n,r){if(!this.isContextManifestBudgetEnabled())return{mode:"disabled"};let i=k_(n),o=q9(i,r);return this.runResolveInjection({taskId:t,manifest:n,available:o,requiredPaths:[]})}async resolveContextInjectionAsync(t){let{taskId:n,manifest:r}=t;if(!this.isContextManifestBudgetEnabled())return{mode:"disabled"};let i=k_(r),o=t.requiredPaths??[],s=q9(i,t.predecessorContentJson),a=[],c=(t.relatedSources??[]).map(g=>g.namespace),{ancestry:l}=OCe(r.tier2,c),u=new Set(c),d=[...r.tier0,...r.tier1].filter(g=>{let A=Ub(g);return A!==null&&A.layer==="summary"&&!u.has(A.namespace)}),p=[...l,...d];if(p.length>0&&t.startArtifactId!==void 0){let A=await new iN({artifacts:this.artifactStore,tasks:{getTaskById:async _=>{let x=await this.stateManager.getTask(_);return x===null?null:{taskId:_,taskKind:x.taskKind}}}}).resolve(t.startArtifactId);if(A.ok)a.push(NCe(p,DCe(A.value.nodes)));else if(this.emitEvent("context_lineage_unavailable",n,{runnerKind:r.runnerKind,manifestId:r.manifestId,errorKind:A.error.kind,detail:A.error.detail,fallback:"full_predecessor_injection",nextAction:"verify_durable_artifact_ancestry_before_tier2_resolution"}),o.length>0)return{mode:"fallback",reason:"lineage_unavailable",unresolvedRequired:[...o]}}t.relatedSources!==void 0&&t.relatedSources.length>0&&a.push(PCe(i,t.relatedSources));let m=LCe(s,a);return this.runResolveInjection({taskId:n,manifest:r,available:m,requiredPaths:o})}runResolveInjection(t){let{taskId:n,manifest:r,available:i,requiredPaths:o}=t,a=TCe(r,i,l=>{l.type==="manifest_resolution_insufficient"?this.emitEvent("manifest_resolution_insufficient",n,{runnerKind:l.runnerKind,manifestId:l.manifestId,absentCount:l.absentCount,declaredCount:l.declaredCount,absentRatio:l.absentRatio,fallback:l.fallback}):this.emitEvent("context_truncated",n,{runnerKind:l.runnerKind,manifestId:l.manifestId,fieldPath:l.fieldPath,reason:l.reason,remainingBudgetTokens:l.remainingBudgetTokens})}),c=MCe({required:o,absent:a.allocated.absent,truncated:a.allocated.truncated});return c.length>0?(this.emitEvent("required_context_evidence_unresolved",n,{runnerKind:r.runnerKind,manifestId:r.manifestId,requiredPaths:c,fallback:"full_predecessor_injection",nextAction:"verify_durable_ancestry_or_related_reference_availability"}),{mode:"fallback",reason:"required_evidence_unresolved",unresolvedRequired:c}):a.kind==="focused"?{mode:"focused",fields:a.allocated.fields}:{mode:"fallback",reason:a.reason,unresolvedRequired:[]}}injectAgentDraftOnPermanentFailure(t){if(!this.pendingAgentDraftStore)return;let{taskKind:n}=t.task,{errorCategory:r}=t,i=t.failureReason,o=um(cm(lm(i))),s={summary:`${n} failed with category=${r} at ${new Date().toISOString()}`,observedFailure:o},a=DOt(t.task.diagnosticJson);try{let c=this.pendingAgentDraftStore.insertPendingDraft({taskId:t.taskId,painId:a??void 0,agentDraft:s});if(!c.ok){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,errorMessage:c.error,nextAction:"Inspect pending_agent_drafts table integrity; draft will be retried on next permanent failure of the same taskId (idempotent UPDATE)."});return}this.emitEvent("agent_draft_inserted",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,draftId:c.id,painIdLinked:a!==null})}catch(c){this.emitEvent("agent_draft_insert_failed",t.taskId,{errorCategory:r,attemptCount:t.task.attemptCount,errorMessage:c instanceof Error?c.message:String(c),nextAction:"PendingAgentDraftStore.insertPendingDraft threw unexpectedly; inspect the store implementation."})}}};var oN=class extends Ai{validator;contextAssembler;effectiveConfig;intentDocReader;constructor(t,n){super(t,n,{runnerName:"diag_rootcause",expectedTaskKind:"diag_rootcause",defaultAgentId:"main",resultRefPrefix:"diag-rootcause",effectiveConfig:n.effectiveConfig}),this.validator=t.validator,this.contextAssembler=t.contextAssembler,this.effectiveConfig=n.effectiveConfig,this.intentDocReader=t.intentDocReader}get permanentErrorCategories(){return new Set(["storage_unavailable","workspace_invalid","capability_missing","cancelled","input_invalid"])}async buildContext(t){let n=await this.stateManager.getTask(t);if(!n)throw new Y("input_invalid",`Task ${t} not found`);let r=n.inputRef||t,i=await this.contextAssembler.assemble(r),s=ht(n)?.dependencyTaskIds??[],a=[...i.sourceRefs];if(s.length>0){let l=await Promise.allSettled(s.map(u=>this.stateManager.getTask(u)));for(let u=0;u<l.length;u++){let d=l[u],p=s[u];if(!(!d||p===void 0)&&d.status==="fulfilled"&&d.value){d.value.resultRef&&a.push(d.value.resultRef);let m=d.value?ht(d.value):null;m?.outputArtifactRefs&&a.push(...m.outputArtifactRefs.map(g=>g.ref))}}}return{contextHash:Ai.hashContextRefs(a),contextRefs:a,painPayload:i}}async invokeRuntime(t,n){let r=!1,i=!1,o=!1;if(this.effectiveConfig){let u=li(this.effectiveConfig);r=Is(u,"diagnostician_core_grounding"),i=Is(u,"intent_engineering"),o=Is(u,"pain_diagnosis_persistence")}let s;if(i&&!this.intentDocReader)i=!1;else if(i&&this.intentDocReader){let u=this.intentDocReader.readIntentDoc();u.ok&&u.doc?s={raw:u.doc.raw,contentHash:u.doc.contentHash,path:u.doc.path}:(this.emitEvent("intent_doc_read_failed",t,{reason:u.reason??"unknown",nextAction:u.nextAction??"Check INTENT.md configuration.",flagEnabled:u.flagEnabled,found:u.found}),i=!1)}let a=new N2,{message:c,systemPrompt:l}=a.buildPrompt(n.painPayload,{outputLanguage:this.resolvedOptions.outputLanguage,coreGrounding:r,intentGrounding:i,intentDoc:s,evidenceFirstAttribution:o});return this.runtimeAdapter.startRun({agentSpec:{agentId:this.resolvedOptions.agentId,schemaVersion:"v1"},taskRef:{taskId:t},inputPayload:c,contextItems:[],outputSchemaRef:"diag-rootcause-output-v1",timeoutMs:this.resolvedOptions.timeoutMs,systemPrompt:l})}async validateOutput(t,n,r){let i=await this.validator.validate(t,n);return{valid:i.valid,errors:i.errors,errorCategory:i.errorCategory,warnings:i.warnings}}async succeedTask(t,n,r,i,o,s){try{await this.stateManager.updateRunOutput(n,JSON.stringify(r))}catch(p){throw this.emitEvent("update_output_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)}),p}let a=[],c=!1;try{let p=await this.resolveLineageArtifactIds(t);a=p.ids,c=p.hasRejected}catch(p){this.emitEvent("lineage_resolve_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)})}c&&this.emitEvent("lineage_partial",t,{runId:n,resolvedCount:a.length,warning:"Some dependency artifact queries were rejected; lineage may be incomplete"});let l=`pi-art-${t}-${n}`,u=new Date().toISOString();try{await this.artifactStore.upsertArtifact({artifactId:l,artifactKind:"principle",sourceTaskId:t,lineageArtifactIds:a,validationStatus:"pending",contentJson:this.buildArtifactContentJson(t,"diag_rootcause",r,null),createdAt:u,updatedAt:u})}catch(p){return this.emitEvent("artifact_write_failed",t,{runId:n,errorMessage:p instanceof Error?p.message:String(p)}),this.retryOrFail({taskId:t,task:i,errorCategory:"artifact_commit_failed",failureReason:`PIArtifact write failed: ${p instanceof Error?p.message:String(p)}`})}let d=`${this.config.resultRefPrefix}://${n}`;try{await this.stateManager.markTaskSucceeded(t,d)}catch(p){throw this.emitEvent("mark_succeeded_failed",t,{taskId:t,runId:n,errorMessage:p instanceof Error?p.message:String(p)}),p}return this.emitEvent("task_succeeded",t,{attemptCount:i.attemptCount,resultRef:d,rootCauseCategory:r.rootCauseCategory,causalChainDepth:r.causalChain.length}),{status:"succeeded",taskId:t,runId:n,artifactId:l,resultRef:d,contextHash:o,output:r,attemptCount:i.attemptCount}}postFetchTransform(t,n){y_(n,"taskId",t)}emitSuccessTelemetry(t,n,r){this.emitEvent("rootcause_completed",t,{rootCauseCategory:n.rootCauseCategory,causalChainDepth:n.causalChain.length})}};Po();var OOt=f.Union([f.Literal("general"),f.Literal("domain"),f.Literal("scenario")]),dm=f.Object({valid:f.Boolean(),taskId:f.String({minLength:1}),sourceRootCauseArtifactId:f.String({minLength:1,description:"Lineage consistency check \u2014 must match the artifact ID from Stage A"}),abstractedPrinciple:f.String({minLength:1,maxLength:200,description:"Highly abstracted, cross-scenario principle (\u2264200 chars)"}),rationale:f.String({minLength:1,description:"Why this principle addresses the root cause"}),groundedOnCorePrincipleIds:f.Array(f.String({minLength:1}),{description:"Subset of T-01..T-10. Validated against registry \u2014 fabricated IDs cause validation failure."}),scope:OOt,confidence:f.Number({minimum:0,maximum:1}),ambiguityNotes:f.Optional(f.Array(f.String()))}),sN=class{async validate(t,n){let r=[],i=[];if(typeof t!="object"||t===null)return{valid:!1,errors:["Output is not an object"],errorCategory:"output_invalid"};let o=t;if(typeof o.taskId!="string"||o.taskId!==n){let s=["diag_rootcause-","diag_distiller-","diag_router-"],a=u=>{for(let d of s)if(u.startsWith(d))return u.slice(d.length);return u},c=a(n),l=typeof o.taskId=="string"?a(o.taskId):"";if(l!==""&&l===c){let u=o.taskId;o.taskId=n,i.push(`taskId re-injected: LLM output "${u}", corrected to "${n}" (ERR-008)`)}else r.push(`taskId mismatch: expected ${n}, got ${String(o.taskId)}`)}if(!Ct.Check(dm,t)){let a=[...Ct.Errors(dm,t)].map(c=>`${c.path}: ${c.message}`);r.push(...a)}if(Array.isArray(o.groundedOnCorePrincipleIds))for(let s of o.groundedOnCorePrincipleIds)typeof s=="string"&&!Db(s)&&r.push(`Fabricated axiom ID ${s} not in core principle registry`);return r.length>0?{valid:!1,errors:r,errorCategory:"output_invalid"}:{valid:!0,errors:[],warnings:i}}};function NOt(e={}){let t=e.adapter??new Cd,n=e.schema??dm,{outputLanguage:r,coreGrounding:i}=e,o=t.generateExample(n),s=t.generateConstraints(n),a=Ws(r);return`You are a principle distiller. Your job is to abstract a specific root cause into a general, cross-scenario principle.
1055
1055
 
1056
1056
  INPUT:
1057
1057
  You will receive the Stage A root cause output as structured data. This contains:
@@ -1406,7 +1406,7 @@ If you want to use the OpenClaw CLI runtime instead, set runtimeKind: openclaw-c
1406
1406
  `);for(let p of i){let m=p.replacement??"",g=l,A=p.pattern.flags.includes("g")?p.pattern.flags:p.pattern.flags+"g",_=new RegExp(p.pattern.source,A);l=l.replace(_,m),l!==g&&!o.includes(p.description)&&o.push(p.description)}if(s){let p="[Historical: confirm-first gate was removed in PRI-286. This section is preserved for reference only.]";l.endsWith(`
1407
1407
  `)||(l=l+`
1408
1408
  `),l=l+p}let u=l!==e,d=u?`Migrated stale PLAN.md guidance: ${o.join("; ")}`:void 0;return{migrated:l,changed:u,reason:d}}function Hfe(e,t){let n=Gfe.filter(r=>r.filenameSuffixes.some(i=>Wfe(t,i)));for(let r of n)if(r.pattern.test(e))return!0;return!1}import qki from"better-sqlite3";import*as cR from"fs";import*as Let from"path";function $_n(e){return Let.join(e,".state","pruning_reviews.jsonl")}function jfe(e,t){let n=$_n(e);if(!cR.existsSync(n))return[];let i=cR.readFileSync(n,"utf-8").split(`
1409
- `),o=[];for(let s of i){let a=s.trim();if(a)try{let c=JSON.parse(a);if(t?.principleId&&c.principleId!==t.principleId)continue;o.push(c)}catch{}}return o}import Jki from"better-sqlite3";var Rf={stageThresholds:{elevated:40,critical:70,saturated:100},repeatedFailureMultiplier:{base:1.5,max:3},decayRatesPerMinute:{stable:.5,elevated:1,critical:2,saturated:4},relief:{toolSuccessRatio:.25,minPruneBelow:8},sourceWeights:{}};function kV(e,t,n){let i=e.lastErrorHash!==void 0&&e.lastErrorHash===t.hash?e.consecutiveErrors+1:1,o=Math.max(0,i-1),s=Math.min(Math.pow(n.repeatedFailureMultiplier.base,o),n.repeatedFailureMultiplier.max),a=t.baseScore*s,c=e.currentGfi+a,l={...e.gfiBySource};return l[t.source]=(l[t.source]??0)+a,{...e,currentGfi:c,gfiBySource:l,consecutiveErrors:i,lastErrorHash:t.hash,lastErrorSource:t.source,dailyGfiPeak:Math.max(e.dailyGfiPeak??0,c)}}function RV(e,t,n,r,i){let o=n.decayRatesPerMinute[r],s={};for(let[c,l]of Object.entries(e.gfiBySource)){let u=l-o*t,d=Math.max(0,Math.round(u*10)/10);d>=n.relief.minPruneBelow&&(s[c]=d)}let a=Object.keys(s).length>0?Math.max(0,Math.round(Object.values(s).reduce((c,l)=>c+l,0)*10)/10):Object.keys(e.gfiBySource).length>0?0:Math.max(0,Math.round((e.currentGfi-o*t)*10)/10);return{...e,currentGfi:a,gfiBySource:s,lastGfiDecayAt:i}}function kB(e,t,n,r=Rf){let{source:i,amount:o=0}=t;if(i==="all"&&o>=100)return{currentGfi:0,gfiBySource:{},consecutiveErrors:0,lastErrorHash:void 0,lastErrorSource:void 0,lastGfiDecayAt:n,dailyGfiPeak:e.dailyGfiPeak};let s={...e.gfiBySource};if(o>0){let u=i;s[u]!==void 0&&(s[u]=Math.max(0,(s[u]??0)-o),s[u]===0&&delete s[u])}else{let u=r.relief.toolSuccessRatio;for(let d of Object.keys(s)){let p=d;s[p]=Math.max(0,Math.round((s[p]??0)*(1-u)*10)/10),s[p]===0&&delete s[p]}}let a=Object.values(s).reduce((u,d)=>u+d,0),l=i===e.lastErrorSource&&i!=="all"?0:e.consecutiveErrors;return{...e,currentGfi:a,gfiBySource:s,consecutiveErrors:l,lastErrorHash:l===0?void 0:e.lastErrorHash,lastErrorSource:l===0?void 0:e.lastErrorSource,lastGfiDecayAt:n}}function DV(e,t){return e>=t.stageThresholds.saturated?"saturated":e>=t.stageThresholds.critical?"critical":e>=t.stageThresholds.elevated?"elevated":"stable"}var oRi=7200*1e3;var Kfe=["hook","service","startup"],Vfe=["core","quiet","gone","legacy_retire"],ZI=[{id:"hook:before_prompt_build",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Principle injection + workspace init on prompt build"},{id:"hook:before_tool_call",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Security gate for tool calls (risk assessment, plan approval)"},{id:"hook:after_tool_call",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Pain detection + empathy observer on tool call result"},{id:"hook:llm_output",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"LLM output analysis for pain signal extraction"},{id:"hook:before_reset",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for context reset",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:before_compaction",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for before compaction",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:after_compaction",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for after compaction",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:before_message_write",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-06-09",description:"Fallback trajectory collection (SQLite) when llm_output is blocked by missing allowConversationAccess (PRI-346)"},{id:"service:evolution-worker",kind:"service",category:"quiet",enabledByDefault:!1,since:"2026-06-01",description:"Background evolution worker for pain processing (MVP-Quiet per PRI-288/ADR-0014)",disabledReason:"MVP-Quiet: evolution worker gated behind evolution_worker feature flag (PRI-288); default off per ADR-0014 \xA72.5"},{id:"service:correction-observer",kind:"service",category:"core",enabledByDefault:!0,since:"2026-06-02",description:"Independent correction observer service for keyword self-correction (MVP-Core per ADR-0014 amendment, PRI-293)"},{id:"service:trajectory",kind:"service",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Trajectory collection service \u2014 pre-initializes TrajectoryDB registry; hooks (llm_output, before_message_write) are the primary writers (PRI-346/353)"},{id:"service:pd-task",kind:"service",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"PD task management service",disabledReason:"Disabled by default: pd-task service is opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"service:internalization-auto-consumer",kind:"service",category:"core",enabledByDefault:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381)"},{id:"startup:workspace-init",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Workspace migration + template setup on first prompt"},{id:"startup:evolution-worker",kind:"startup",category:"quiet",enabledByDefault:!1,since:"2026-06-01",description:"Evolution worker start on first prompt per workspace (MVP-Quiet per PRI-288/ADR-0014)",disabledReason:"MVP-Quiet: evolution worker startup gated behind evolution_worker feature flag (PRI-288); default off per ADR-0014 \xA72.5"},{id:"startup:correction-observer",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-06-02",description:"Correction observer start on first prompt per workspace (MVP-Core per ADR-0014 amendment, PRI-293)"},{id:"startup:internalization-auto-consumer",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-06-13",description:"Internalization auto-consumer start on first prompt per workspace (MVP-Core, PRI-381)"}];function OV(e){let t=[],n=[],r=new Set;for(let i of e)r.has(i.id)&&t.push(`duplicate surface id: '${i.id}'`),r.add(i.id),(typeof i.id!="string"||i.id.length===0)&&t.push(`surface entry has invalid id: '${String(i.id)}'`),Kfe.includes(i.kind)||t.push(`surface '${i.id}': invalid kind '${i.kind}'`),Vfe.includes(i.category)||t.push(`surface '${i.id}': invalid category '${i.category}'`),typeof i.enabledByDefault!="boolean"&&t.push(`surface '${i.id}': enabledByDefault must be boolean`),(typeof i.since!="string"||i.since.length===0)&&t.push(`surface '${i.id}': since must be a non-empty string`),(typeof i.description!="string"||i.description.length===0)&&t.push(`surface '${i.id}': description must be a non-empty string`),i.category==="core"&&!i.enabledByDefault&&t.push(`surface '${i.id}': core surface must be enabledByDefault=true`),i.category!=="core"&&i.enabledByDefault&&t.push(`surface '${i.id}': non-core surface (${i.category}) must not be enabledByDefault=true`),(i.category==="quiet"||i.category==="gone"||i.category==="legacy_retire")&&!i.disabledReason&&n.push(`surface '${i.id}': ${i.category} surface has no disabledReason \u2014 observability gap (ERR-002)`);return{valid:t.length===0,errors:t,warnings:n}}function NV(e,t){return e.filter(n=>n.category===t)}var Uet=new Set;function Qet(e,t,n){return Uet.has(e)||!t?.info?!1:(Uet.add(e),t.info(n),!0)}function PV(){let e=OV(ZI),t=[],n=[...e.warnings],i=NV(ZI,"core").filter(s=>s.enabledByDefault),o=ZI.filter(s=>s.category!=="core"&&s.enabledByDefault);if(o.length>0)for(let s of o)t.push(`non-core surface '${s.id}' (${s.category}) is enabledByDefault=true \u2014 must be false per ADR-0014`);return e.valid||t.push(...e.errors),{passed:t.length===0,enabledCoreSurfaces:i.map(s=>s.id),disabledNonCoreSurfaces:ZI.filter(s=>s.category!=="core"&&!s.enabledByDefault).map(s=>s.id),violations:t,warnings:n}}function LV(e,t={}){let n=ZI.find(r=>r.id===e);if(!n)return{enabled:!1,reason:`surface '${e}' not found in registry \u2014 classify before enabling (PRI-289)`};if(Object.hasOwn(t,e)){let r=t[e];return typeof r!="boolean"?{enabled:n.enabledByDefault,reason:`override for '${e}' is not boolean, using default`}:n.category==="gone"?{enabled:!1,reason:`surface '${e}' is gone and cannot be re-enabled`}:n.category==="core"&&!r?{enabled:!0,reason:`surface '${e}' is core and cannot be disabled`}:{enabled:r}}return!n.enabledByDefault&&n.disabledReason?{enabled:!1,reason:n.disabledReason}:{enabled:n.enabledByDefault}}function Df(e,t,n){let r=LV(e);if(r.enabled)return n;let i=r.reason??"surface not enabled";return(o,s)=>{Qet(e,t,`[PD:surface-guard] SKIP ${e}: ${i}`)}}function cv(e,t,n){let r=LV(e);if(r.enabled)return t;let i=r.reason??"surface not enabled";return Qet(e,n,`[PD:surface-guard] SKIP service ${e}: ${i}`),null}function MV(e){if(!(typeof e!="object"||e===null||Array.isArray(e))&&Object.hasOwn(e,"sourcePrincipleId")){let t=Reflect.get(e,"sourcePrincipleId");typeof t=="string"&&!Db(t)&&Reflect.deleteProperty(e,"sourcePrincipleId")}}var Yfe=["prompt","defer_archive"],zfe={skill:"medium",code_tool_hook:"high"},BV=.95,FV=["skill"];function RB(e,t){return`${e}::${t}`}function DB(e){return Yfe.includes(e)}function UV(e){return DB(e)?"low":zfe[e]??"high"}function QV(e,t){return t==null||t<0||t>1||!FV.includes(e)?!1:t>=BV}function $et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dv(e){if(typeof e.sourcePrincipleId=="string"){let t=e.sourcePrincipleId.trim();if(t!=="")return t}try{let t=JSON.parse(e.contentJson);if(!$et(t))return null;if(typeof t.principleId=="string"&&t.principleId.trim()!=="")return t.principleId.trim();if(typeof t.sourcePrincipleId=="string"&&t.sourcePrincipleId.trim()!=="")return t.sourcePrincipleId.trim();if($et(t.principleDraft)){let n=t.principleDraft;if(typeof n.title=="string"&&n.title.trim()!=="")return n.title.trim()}}catch{return null}return null}var lv=class{channel="prompt";async canActivate(t){return t.artifactKind!=="principle"?{ok:!1,reason:"artifact_kind_not_principle",riskLevel:"low"}:t.validationStatus!=="validated"?{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"low"}:dv(t)?{ok:!0,riskLevel:"low"}:{ok:!1,reason:"no_principle_id_in_artifact",riskLevel:"low"}}async activate(t,n){return{activationId:`act_prompt_${t.principleId}`,action:"prompt_activate",targetRef:`ledger://${t.principleId}`}}},uv=class{channel="defer_archive";async canActivate(t){return t.artifactKind!=="principle"?{ok:!1,reason:"artifact_kind_not_principle",riskLevel:"low"}:t.validationStatus!=="validated"?{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"low"}:dv(t)?{ok:!0,riskLevel:"low"}:{ok:!1,reason:"no_principle_id_in_artifact",riskLevel:"low"}}async activate(t,n){return{activationId:`act_archive_${t.principleId}`,action:"defer_archive",targetRef:`ledger://${t.principleId}#archived`}}};function t0n(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Wet(e,t,n){try{let r=await e.canActivate(t);return r.ok?{decision:null,result:r}:{decision:{decision:"refused",reason:r.reason??"can_activate_refused",riskLevel:r.riskLevel,channel:e.channel,...r.failure?{failure:r.failure}:{}}}}catch(r){let i=r instanceof Error?r.message:String(r);if(n)try{n.emitTelemetry({eventType:"degradation_triggered",traceId:t.artifactId,timestamp:new Date().toISOString(),sessionId:"activation-dispatcher",payload:{component:"ActivationDispatcher",event:"ACTIVATION_CAN_ACTIVATE_FAILED",trigger:"can_activate_check_failed",channel:e.channel,artifactId:t.artifactId,originalError:i,errorCategory:"can_activate_check_failed",nextAction:"Investigate the ChannelWriter.canActivate implementation for this channel; it threw during the pre-activation guard check."}})}catch{}return{decision:{decision:"refused",reason:"can_activate_check_failed",channel:e.channel,details:{originalError:i,errorCategory:"can_activate_check_failed"}}}}}function n0n(e,t,n,r){let i="";try{let c=JSON.parse(e.contentJson);t0n(c)&&(i=String(c.text??c.description??""))}catch{}let o=e.artifactKind??"artifact",s=r!==void 0?Math.round(r*100)+"%":"unknown",a={skill:"This principle will be activated as a skill that monitors and influences agent behavior in real-time.",code_tool_hook:"This principle will be injected as a code tool hook that intercepts and validates tool calls before execution."};return{summary:i?`Activate ${o}: "${i.slice(0,200)}"`:`Activate ${o} artifact ${e.artifactId}`,triggerReason:`Rollout reviewer recommended activation via ${t} channel (risk: ${n}).`,confidenceExplanation:r!==void 0?`Confidence score: ${s}. `+(r>=.8?"High confidence based on multiple validations.":r>=.5?"Moderate confidence, additional review recommended.":"Low confidence, manual review strongly recommended."):"Confidence score not available.",effectDescription:a[t]??`This artifact will be activated via the ${t} channel.`,rejectionEffect:`The artifact will remain inactive and will not be deployed to the ${t} channel. You can request activation again later.`}}var pv=class{artifactReadModel;stateReadModel;writers;approvalQueueStore;eventEmitter;constructor(t,n,r){this.artifactReadModel=t,this.stateReadModel=n,this.approvalQueueStore=r.approvalQueueStore,this.eventEmitter=r.eventEmitter,this.writers=new Map;for(let i of r.writers)this.writers.set(i.channel,i)}async dispatch(t){let n=await this.readArtifact(t.artifactId);if(n.decision)return n.decision;let{artifact:r}=n;if(!r.artifactId||typeof r.artifactKind!="string")return{decision:"invalid_artifact",reason:"malformed_artifact"};let i=t.idempotencyKey??RB(t.artifactId,t.channel),o=await this.checkIdempotency(i,t.artifactId);if(o.decision)return o.decision;if(t.rolloutDecision==="reject")return{decision:"refused",reason:"rollout_rejected",channel:t.channel};if(t.rolloutDecision==="approved"){if(!t.approvalId)return{decision:"refused",reason:"approved_dispatch_requires_approval_id",nextAction:"provide approvalId from a verified owner approval record",channel:t.channel};if(!this.approvalQueueStore)return{decision:"refused",reason:"approved_dispatch_without_approval_store",nextAction:"configure dispatcher with approvalQueueStore to verify approvals",channel:t.channel};let a;try{a=await this.approvalQueueStore.getById(t.approvalId)}catch{return{decision:"refused",reason:"approval_record_read_failed",nextAction:"check_approval_store_availability",channel:t.channel}}return a?a.status!=="approved"?{decision:"refused",reason:`approval_status_is_${a.status}_expected_approved`,nextAction:a.status==="pending"?"owner_must_approve_before_dispatch":"rejected_or_expired_approvals_cannot_be_activated",channel:t.channel}:a.artifactId!==t.artifactId?{decision:"refused",reason:`approval_artifact_mismatch: approval=${a.artifactId} dispatch=${t.artifactId}`,nextAction:"ensure_dispatch_artifact_matches_approved_artifact",channel:t.channel}:a.channel!==t.channel?{decision:"refused",reason:`approval_channel_mismatch: approval=${a.channel} dispatch=${t.channel}`,nextAction:"ensure_dispatch_channel_matches_approved_channel",channel:t.channel}:this.activateArtifact(t,r,i):{decision:"refused",reason:`approval_record_not_found: ${t.approvalId}`,nextAction:"verify_approval_id",channel:t.channel}}return t.rolloutDecision==="require_approval"||!DB(t.channel)?QV(t.channel,t.confidence)?this.activateArtifact(t,r,i):this.enqueueForApproval(t,r,i):this.activateArtifact(t,r,i)}async enqueueForApproval(t,n,r){let i=UV(t.channel);if(!this.approvalQueueStore)return{decision:"refused",reason:"requires_approval",channel:t.channel,riskLevel:i};let o=this.writers.get(t.channel);if(o){let s=await Wet(o,n,this.eventEmitter);if(s.decision)return s.decision}if(!t.confirm)return{decision:"queued_for_approval",approvalId:"apr_"+t.channel+"_"+t.artifactId,queuedAt:t.now,channel:t.channel,riskLevel:i};try{let s=o?.buildApprovalContext?.({artifactId:t.artifactId,channel:t.channel,principleId:dv(n)??"",idempotencyKey:r,now:t.now},n,t.confidence),a=await this.approvalQueueStore.enqueue({artifactId:t.artifactId,channel:t.channel,riskLevel:i,confidence:t.confidence,...s??n0n(n,t.channel,i,t.confidence)},t.now);return{decision:"queued_for_approval",approvalId:a.approvalId,queuedAt:a.requestedAt,channel:t.channel,riskLevel:i}}catch{return{decision:"refused",reason:"approval_enqueue_failed",channel:t.channel,riskLevel:i}}}async activateArtifact(t,n,r){let i=dv(n);if(!i)return{decision:"invalid_artifact",reason:"no_principle_id"};let o=this.writers.get(t.channel);if(!o)return{decision:"refused",reason:"no_writer_for_channel_"+t.channel,channel:t.channel};let s=await Wet(o,n,this.eventEmitter);if(s.decision)return s.decision;let a={artifactId:t.artifactId,channel:t.channel,principleId:i,idempotencyKey:r,now:t.now},c;try{c=await o.activate(a,n)}catch{return{decision:"refused",reason:"activation_write_failed",channel:t.channel}}if(!t.confirm)return{decision:"would_activate",activationId:c.activationId,action:c.action,targetRef:c.targetRef};try{await this.stateReadModel.recordActivation({activationId:c.activationId,idempotencyKey:r,artifactId:t.artifactId,channel:t.channel,action:c.action,targetRef:c.targetRef,activatedAt:t.now,deactivatedAt:null})}catch{return{decision:"refused",reason:"activation_record_failed",channel:t.channel}}return{decision:"activated",activationId:c.activationId,action:c.action,targetRef:c.targetRef}}async readArtifact(t){try{let n=await this.artifactReadModel.getArtifactById(t);return n?{artifact:n,decision:null}:{artifact:null,decision:{decision:"invalid_artifact",reason:"artifact_not_found",nextAction:"check_pi_artifacts_table_or_remove_stale_activation"}}}catch{return{artifact:null,decision:{decision:"refused",reason:"artifact_read_failed"}}}}async checkIdempotency(t,n){try{let r=await this.stateReadModel.getActivationStatus(t);return r?r.artifactId!==n?{decision:{decision:"refused",reason:`idempotency_artifact_mismatch: existing=${r.artifactId} input=${n}`,nextAction:"Investigate data corruption. The existing activation references a different artifact_id than the dispatch input. Run `pd runtime internalization integrity` for full chain diagnostics."}}:{decision:{decision:"already_activated",activationId:r.activationId,action:r.action,targetRef:r.targetRef}}:{decision:null}}catch{return{decision:{decision:"refused",reason:"activation_state_read_failed"}}}}};function OB(e){switch(e){case"principle":return"FAILED_PRINCIPLE";case"rule":return"FAILED_RULE";case"evaluation":return"FAILED_EVALUATION";case"test":return"FAILED_TEST";case"runtime":return"INFRA_BLOCKED";default:return"UNKNOWN"}}var r0n=new Map([["v2-unavailable","allow"],["v2-truncated","allow"],["v2-alias","allow"]]);function i0n(e){return r0n.has(e)?"allow":e==="v2-path-boundary"||e==="v2-combination"?"block":null}function qet(e){if(e==null||e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t;if(!Object.hasOwn(n,"requiresContextVersion"))return;let r=n.requiresContextVersion;return typeof r=="number"?r:null}function Jfe(e){let{requiresContextVersion:t,failedCases:n}=e;if(t===2)return{outOfScope:[],inScope:n.map(o=>o.caseId),isPureOutOfScope:!1};let r=[],i=[];for(let o of n)i0n(o.caseId)==="allow"&&o.expectedDecision==="allow"?r.push(o.caseId):i.push(o.caseId);return{outOfScope:r,inScope:i,isPureOutOfScope:r.length>0&&i.length===0}}var Get=300;function hA(e){return e.length>Get?`${e.slice(0,Get)}\u2026`:e}function Xfe(e){if(!e.toolSemantics.hasHostLayer)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_registry_host_layer_missing",evidence:"ToolSemanticRegistry has no host-declared layer \u2014 tool existence cannot be verified against the production host",nextAction:"supply a host-declared registry (host mappings), or run the host once so its declaration is persisted for the workspace"}};let t=s=>e.toolSemantics.hasHostTool(s)?"ok":e.toolSemantics.lookup(s)===null?"unknown":"not_dispatchable",n=e.affectedTools.filter(s=>t(s)==="unknown"),r=e.affectedTools.filter(s=>t(s)==="not_dispatchable");if(n.length>0)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_alias_unknown",evidence:hA(`affectedTools unknown to any tool vocabulary: ${n.join(", ")}`),nextAction:"regenerate the rule using real host tool names (see the host tool semantic declaration)"}};if(r.length>0)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_not_host_dispatchable",evidence:hA(`affectedTools semantically classifiable but NOT dispatched by this host (never reach the RuleHost gate): ${r.join(", ")}`),nextAction:"regenerate the rule against host-declared tool names \u2014 generic LLM vocabulary and read/search-family names cannot trigger rules in production"}};let i=e.goldenTraceCaseToolNames.filter(s=>t(s)==="unknown"),o=e.goldenTraceCaseToolNames.filter(s=>t(s)==="not_dispatchable");if(i.length>0||o.length>0){let s=[];return i.length>0&&s.push(`unknown: ${i.join(", ")}`),o.length>0&&s.push(`not host-dispatchable: ${o.join(", ")}`),{valid:!1,failure:{layer:"adapter",reasonCode:i.length>0?"tool_alias_unknown":"tool_not_host_dispatchable",evidence:hA(`goldenTraceCases toolName ${s.join("; ")}`),nextAction:"regenerate golden trace cases against host-declared tool names so replay exercises inputs production can actually produce"}}}return{valid:!0}}var o0n=new Set(["__sandbox__","__no_evaluator__","__compile__","__return_shape__","__matched_false_decision__"]);function dh(e,t){switch(e){case"rejected_no_cases":return{layer:"test",reasonCode:"golden_trace_empty",evidence:"goldenTrace.cases is empty \u2014 no test material to validate against",nextAction:"regenerate the artifact with at least one positive and one negative golden trace case"};case"rejected_forbidden_pattern":return{layer:"rule",reasonCode:"forbidden_pattern",evidence:hA(`forbidden patterns: ${t.forbiddenPatternViolations.join(", ")}`),nextAction:"regenerate RuleCode without forbidden APIs (no fs/process/require/eval/network)"};case"rejected_timeout":return{layer:"rule",reasonCode:"evaluation_timeout",evidence:hA(t.failedCases.map(n=>`${n.caseId}: ${n.message}`).join("; ")),nextAction:"regenerate RuleCode with bounded logic (no unbounded loops)"};case"rejected_validation_failed":{let n=t.failedCases.filter(r=>r.errorType==="validation_failed").map(r=>`${r.caseId}: ${r.message}`).join("; ");return{layer:"rule",reasonCode:"replay_decision_mismatch",evidence:hA(n||"validation failed with no case detail"),nextAction:"fix the RuleCode decision logic to satisfy the golden trace expectations"}}case"rejected_runtime_error":{let n=t.failedCases.filter(i=>o0n.has(i.caseId));if(n.length>0)return{layer:"runtime",reasonCode:"sandbox_infrastructure_failure",evidence:hA(n.map(i=>`${i.caseId}: ${i.message}`).join("; ")),nextAction:"inspect the sandbox/gate adapter wiring, then re-run the gate"};let r=t.failedCases.map(i=>`${i.caseId}: ${i.errorType} \u2014 ${i.message}`);return{layer:"rule",reasonCode:"rule_code_execution_error",evidence:hA(r.join("; ")),nextAction:"fix the RuleCode so evaluate() handles every input shape without throwing"}}default:return{layer:"unknown",reasonCode:"unclassified",evidence:hA(`gate decision ${String(e)}`),nextAction:"inspect the full gate result manually"}}}var Het={success:!1,failedCases:[],executionTimeMs:0,forbiddenPatternViolations:[]};function s0n(e){if(e instanceof Error)return e.message;if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="symbol")return e.toString();try{return JSON.stringify(e)??String(e)}catch{return"[unserializable]"}}function a0n(e){let t=s0n(e);return{success:!1,failedCases:[{caseId:"__sandbox__",errorType:e instanceof Error?"runtime_error":"unknown",message:t}],executionTimeMs:0,forbiddenPatternViolations:[]}}function c0n(e,t){try{return{result:e.evaluateInSandbox(t.code,t.goldenTrace,t.opts),threw:!1}}catch(n){return{result:a0n(n),threw:!0}}}function lR(e,t){let n=[];if(e.requestedMode==="live"&&n.push("requestedMode=live is not supported in PRI-173; applicationMode forced to shadow"),e.goldenTrace.cases.length===0){let u="rejected_no_cases";return{decision:u,applicationMode:"shadow",sandboxResult:Het,reasons:["goldenTrace.cases is empty \u2014 no test cases to validate against",...n],failure:dh(u,Het)}}let r={...e.softTimeoutMs!==void 0?{softTimeoutMs:e.softTimeoutMs}:{},...e.toolSemantics!==void 0?{toolSemantics:e.toolSemantics}:{},...e.projectDir!==void 0?{projectDir:e.projectDir}:{}},i=c0n(t,{code:e.code,goldenTrace:e.goldenTrace,opts:r});if(i.threw){let u="rejected_runtime_error";return{decision:u,applicationMode:"shadow",sandboxResult:i.result,reasons:["sandbox adapter failure: evaluateInSandbox threw",...n],failure:dh(u,i.result)}}let o=i.result;if(o.forbiddenPatternViolations.length>0){let u="rejected_forbidden_pattern";return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[`forbidden patterns detected: ${o.forbiddenPatternViolations.join(", ")}`,...n],failure:dh(u,o)}}if(o.failedCases.length===0){if(!o.success){let u="rejected_runtime_error";return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:["sandbox reported success=false with no failedCases or forbiddenPatternViolations \u2014 fail closed",...n],failure:dh(u,o)}}return{decision:"accepted_shadow",applicationMode:"shadow",sandboxResult:o,reasons:n}}let s=new Set(o.failedCases.map(u=>u.errorType));if(s.has("timeout")){let u="rejected_timeout",d=o.failedCases.filter(p=>p.errorType==="timeout");return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: timeout \u2014 ${p.message}`),...n],failure:dh(u,o)}}let a=new Set(["runtime_error","syntax_error","unknown"]);if([...s].some(u=>a.has(u))){let u="rejected_runtime_error",d=o.failedCases.filter(p=>a.has(p.errorType));return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: ${p.errorType} \u2014 ${p.message}`),...n],failure:dh(u,o)}}if(s.has("validation_failed")){let u="rejected_validation_failed",d=o.failedCases.filter(p=>p.errorType==="validation_failed");return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: validation_failed \u2014 ${p.message}`),...n],failure:dh(u,o)}}let l="rejected_runtime_error";return{decision:l,applicationMode:"shadow",sandboxResult:o,reasons:[...o.failedCases.map(u=>`case ${u.caseId}: ${u.errorType} \u2014 ${u.message}`),...n],failure:dh(l,o)}}function $V(e,t){if(!e||typeof e!="string")return"";let n=e.replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),i=n.length>=2&&n[1]===":",o=r.length>=2&&r[1]===":",s=n;i&&!o&&(s=`/mnt/${n.charAt(0).toLowerCase()}${n.slice(2)}`);let a=i&&o?s.slice(2):s,c=o?r.slice(2):r,l=a.startsWith("/"),u=c.startsWith("/");if(l&&u){let d=jet(c,a);return d.startsWith("../")?s:d}if(!l){let d=l0n(c,a),p=jet(c,d);return p.startsWith("../")?s:p}return s}function jet(e,t){let n=e.split("/").filter(c=>c.length>0),r=t.split("/").filter(c=>c.length>0),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;let o=n.length-i,s=r.slice(i),a=[];for(let c=0;c<o;c++)a.push("..");return a.push(...s),a.length===0?".":a.join("/")}function l0n(e,t){let n=e.split("/").filter(o=>o.length>0),r=t.split("/").filter(o=>o.length>0),i=[];for(let o of n)o===".."?i.length>0&&i.pop():o!=="."&&i.push(o);for(let o of r)o===".."?i.length>0&&i.pop():o!=="."&&i.push(o);return"/"+i.join("/")}function WV(e,t={}){let n=e.file_path||e.path||e.file||e.target;if(typeof n=="string"&&n.length>0)return n;if(t.isBashTool){let r=String(e.command||e.args||"");if(r){let i=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(r);return i&&i[1]?i[1]:r}}return t.isWriteTool&&t.toolName?`<tool:${t.toolName}>`:null}function GV(e){return{isBashTool:e==="execute",isWriteTool:e==="write"}}function u0n(e){if(e.canonicalKind===void 0)return e;let t=GV(e.canonicalKind);return{...e,isBashTool:e.isBashTool??t.isBashTool,isWriteTool:e.isWriteTool??t.isWriteTool}}function eE(e,t,n,r={}){let i=u0n(r),o=WV(t,{...i,toolName:e}),s=$V(o,n);return{toolName:e,normalizedPath:s,paramsSummary:{...t},...i.canonicalKind!==void 0?{canonicalKind:i.canonicalKind}:{}}}var Ket=f.Record(f.String(),f.Unknown()),d0n="^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$",Yet=f.Union([f.Literal("shadow"),f.Literal("live")]),zet=f.Union([f.Literal("allow"),f.Literal("block"),f.Literal("propose_correction")]),Jet=f.Union([f.Literal("negative"),f.Literal("positive")]),Zfe=f.Object({caseId:f.String({minLength:1}),kind:Jet,toolName:f.String({minLength:1}),params:Ket,expectedDecision:zet,expectedProposedParams:f.Optional(Ket),expectedApplicationMode:f.Optional(Yet),sourceRefs:f.Optional(f.Object({painId:f.Optional(f.String({minLength:1})),candidateId:f.Optional(f.String({minLength:1})),artifactId:f.Optional(f.String({minLength:1})),auditEventId:f.Optional(f.String({minLength:1}))})),ruleContext:f.Optional(f.Unknown())}),Xet=f.Object({traceId:f.String({minLength:1}),sourcePainId:f.Optional(f.String({minLength:1})),sourceCandidateId:f.Optional(f.String({minLength:1})),sourceArtifactId:f.Optional(f.String({minLength:1})),cases:f.Array(Zfe,{minItems:1}),createdAt:f.String({pattern:d0n}),version:f.Literal(1)});function Zet(e,t){return[...Ct.Errors(e,t)].map(n=>String(n.path||n.message))}function NB(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vet(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"case"}function p0n(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function eme(e){let t=Zet(Zfe,e);return t.length===0&&NB(e)&&(e.expectedDecision==="propose_correction"&&!NB(e.expectedProposedParams)&&t.push("expectedProposedParams is required when expectedDecision is propose_correction"),e.expectedDecision==="propose_correction"&&e.expectedApplicationMode===void 0&&t.push("expectedApplicationMode is required when expectedDecision is propose_correction"),e.kind==="positive"&&e.expectedDecision!=="allow"&&t.push("positive cases must expect allow")),{valid:t.length===0,errors:t}}function uR(e){let t=Zet(Xet,e);if(!NB(e))return{valid:!1,errors:t};if(Object.hasOwn(e,"createdAt")&&!p0n(e.createdAt)&&t.push("createdAt must be a parseable ISO-8601 timestamp"),Array.isArray(e.cases)){let n=!1,r=!1;e.cases.forEach((i,o)=>{let s=eme(i);s.valid||t.push(...s.errors.map(a=>`cases[${o}].${a}`)),NB(i)&&i.kind==="negative"&&(n=!0),NB(i)&&i.kind==="positive"&&(r=!0)}),n||t.push("cases must include at least one negative case"),r||t.push("cases must include at least one positive case")}return{valid:t.length===0,errors:t}}function PB(e,t={},n={}){let r=n.toolSemantics?.resolve(e.toolName);return{action:n.projectDir&&t.normalizedPath===void 0?eE(e.toolName,e.params,n.projectDir,r!==void 0?{canonicalKind:r}:{}):{toolName:e.toolName,normalizedPath:t.normalizedPath??null,paramsSummary:{...e.params},...r!==void 0?{canonicalKind:r}:{}},workspace:{isRiskPath:!1,...t.workspace},session:{currentGfi:0,...t.session},evolution:{epTier:0,...t.evolution},derived:{estimatedLineChanges:0,bashRisk:"unknown",...t.derived},...t.context!==void 0?{context:t.context}:{}}}function tme(e){return{traceId:`golden-trace-${Vet(e.toolName)}-${Vet(e.expectedDecision)}`,sourcePainId:e.sourcePainId,sourceCandidateId:e.sourceCandidateId,sourceArtifactId:e.sourceArtifactId,version:1,createdAt:e.createdAt??"2026-05-11T00:00:00.000Z",cases:[{caseId:"negative-1",kind:"negative",toolName:e.toolName,params:{...e.negativeParams},expectedDecision:e.expectedDecision,expectedProposedParams:e.expectedProposedParams?{...e.expectedProposedParams}:void 0,expectedApplicationMode:e.expectedApplicationMode??(e.expectedDecision==="propose_correction"?"shadow":void 0)},{caseId:"positive-1",kind:"positive",toolName:e.toolName,params:{...e.positiveParams},expectedDecision:"allow"}]}}function tE(e){if(!Array.isArray(e.cases))return{ok:!1,reason:"cases must be an array"};if(e.cases.length===0)return{ok:!1,reason:"cases must contain at least 1 positive + 1 negative case, got 0"};let t=!1,n=!1,r=[];for(let s of e.cases){let a=eme(s);if(!a.valid)return{ok:!1,reason:`invalid golden trace case: ${a.errors.join("; ")}`};s.kind==="positive"?t=!0:n=!0,r.push(s)}if(!t||!n)return{ok:!1,reason:`cases must include at least one ${!t&&!n?"positive and negative":t?"negative":"positive"} case`};let i={traceId:`golden-trace-artificer-${Date.now().toString(36)}`,sourceArtifactId:e.sourceArtifactId,version:1,createdAt:e.createdAt??new Date().toISOString(),cases:r},o=uR(i);return o.valid?{ok:!0,trace:i}:{ok:!1,reason:`produced trace failed validation: ${o.errors.join("; ")}`}}var f0n=["edit","write","delete","bash","exec","remove"],m0n="rulecode_context_v2";function ett(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function h0n(e){let t=e.implementationCode;return typeof t=="string"&&t.trim().length>0?t:null}function g0n(e){let t=e.goldenTrace;if(typeof t!="object"||t===null||Array.isArray(t))return{ok:!1,reason:"no_golden_trace"};let n=uR(t);return n.valid?{ok:!0,trace:t}:{ok:!1,reason:`golden_trace_schema_invalid: ${n.errors.slice(0,3).join("; ")}`}}function A0n(e){let t=e.ruleHostGateDecision;return typeof t=="string"&&t.trim().length>0?t:null}function y0n(e){let{affectedTools:t}=e;return Array.isArray(t)&&t.some(r=>{if(typeof r!="string")return!1;let i=r.toLowerCase();return f0n.some(o=>i.includes(o))})?"critical":"high"}function qV(e){if(!Object.hasOwn(e,"evidenceRefs"))return null;let t=e.evidenceRefs;if(!Array.isArray(t)||t.length===0)return null;let n=[];for(let r of t){if(typeof r!="string"||r.trim()==="")return null;n.push(r)}return n}function I0n(e,t){for(let r of t.cases)if(r.expectedDecision==="propose_correction")return"v2_seed_rule_forbidden_decision:propose_correction";return qV(e)===null?Object.hasOwn(e,"evidenceRefs")?"v2_seed_rule_invalid_evidence_refs":"v2_seed_rule_missing_evidence_refs":null}var fv=class{channel="code_tool_hook";gateDeps;featureFlagProbe;toolSemantics;projectDir;constructor(t){this.gateDeps=t.gateDeps,this.featureFlagProbe=t.featureFlagProbe,this.toolSemantics=t.toolSemantics,this.projectDir=t.projectDir}async canActivate(t){if(t.artifactKind!=="rule")return{ok:!1,reason:"artifact_kind_not_rule",riskLevel:"high"};if(t.validationStatus!=="validated")return{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"high"};let n=ett(t.contentJson);if(!n)return{ok:!1,reason:"content_json_parse_failed",riskLevel:"high"};if(Object.hasOwn(n,"requiresContextVersion")&&n.requiresContextVersion!==2)return{ok:!1,reason:"unsupported_context_version",riskLevel:"high"};if(n.requiresContextVersion===2&&!(this.featureFlagProbe?this.featureFlagProbe(m0n):!1))return{ok:!1,reason:"rulecode_context_v2_disabled",riskLevel:"high"};let r=h0n(n);if(!r)return{ok:!1,reason:"no_implementation_code",riskLevel:"high"};let i=g0n(n);if(!i.ok)return{ok:!1,reason:i.reason,riskLevel:"high"};let o=i.trace;if(A0n(n)!=="accepted_shadow")return{ok:!1,reason:"gate_decision_not_accepted_shadow",riskLevel:"high"};if(n.requiresContextVersion===2){let d=I0n(n,o);if(d)return{ok:!1,reason:d,riskLevel:"high"}}if(this.toolSemantics){let d=Array.isArray(n.affectedTools)?n.affectedTools.filter(m=>typeof m=="string"&&m.trim().length>0):[],p=Xfe({affectedTools:d,goldenTraceCaseToolNames:o.cases.map(m=>m.toolName),toolSemantics:this.toolSemantics});if(!p.valid&&p.failure){let{failure:m}=p;return{ok:!1,reason:`rule_reliability_${m.reasonCode}:${m.layer} \u2014 ${m.evidence} (nextAction=${m.nextAction})`,riskLevel:"high",failure:m}}}let a=lR({code:r,goldenTrace:o,...this.toolSemantics?{toolSemantics:this.toolSemantics}:{},...this.projectDir?{projectDir:this.projectDir}:{}},this.gateDeps);if(a.decision!=="accepted_shadow")return{ok:!1,reason:[`gate_decision_not_accepted_shadow:${a.decision}`,...a.reasons.slice(0,3)].join(" \u2014 "),riskLevel:"high",...a.failure?{failure:a.failure}:{}};let c=Array.isArray(n.affectedTools)?n.affectedTools.filter(d=>typeof d=="string"&&d.trim().length>0):[],l=new Set(["pd_status","rulecode_deactivate","rulecode_global_pause","owner_review_access"]);return c.length===0?{ok:!1,reason:"rulecode_scope_empty",riskLevel:"high"}:c.some(d=>d==="*"||d.toLowerCase()==="all")?{ok:!1,reason:"rulecode_scope_wildcard_forbidden",riskLevel:"high"}:c.some(d=>l.has(d))?{ok:!1,reason:"rulecode_scope_protected_capability",riskLevel:"high"}:{ok:!0,riskLevel:y0n(n)}}async activate(t,n){let r=typeof n.sourceRuleId=="string"&&n.sourceRuleId.trim().length>0?n.sourceRuleId.trim():t.principleId;return{activationId:`act_code_${r}`,action:"code_tool_hook_shadow_activate",targetRef:`impl://${r}`}}buildApprovalContext(t,n,r){let i=typeof n.sourceRuleId=="string"&&n.sourceRuleId.trim().length>0?n.sourceRuleId.trim():n.artifactId,o=ett(n.contentJson),s=o?.painReasonSummary,a=typeof s=="string"?s.trim():"",c=Array.isArray(o?.affectedTools)?o.affectedTools.filter(v=>typeof v=="string"):[],l=o?qV(o):null,u=`Rule activation request for code_tool_hook: ${i}`,d=a.length>0?a:"RuleHost candidate requires human approval before activation.",m=typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<=1?`Confidence: ${Math.round(r*100)}%. Evaluated through shadow replay and sandbox gate.`:"Confidence score unavailable. Manual review recommended.",g=c.length>0?`This rule will intercept tool calls: ${c.join(", ")}. After approval, matching calls will be evaluated against the rule logic.`:"This candidate may affect code_tool_hook behavior after approval. Tool scope is not specified.",A=l&&l.length>0?` Evidence backing this rule: ${l.join(", ")}.`:"",_=`${g}${A}`;return{summary:u,triggerReason:d,confidenceExplanation:m,effectDescription:_,rejectionEffect:"The rule will not be activated. Current tool calls will continue unchanged."}}};var nme={maxRepairAttempts:0},v0n=new Set(["block","requireApproval"]);function ttt(e){try{return Object.keys(e)}catch{return null}}function HV(e,t){let n=[],r=ttt(e);if(!r)return n.push("cannot enumerate expected keys"),n;let i=ttt(t);if(!i)return n.push("cannot enumerate actual keys"),n;let o=new Set(r),s=new Set(i),a=new Set([...r,...i]);for(let c of a){let l=o.has(c);if(!s.has(c))n.push(`missing field "${c}"`);else if(!l)n.push(`unexpected field "${c}"`);else try{let d=JSON.stringify(e[c]),p=JSON.stringify(t[c]);d!==p&&n.push(`field "${c}": expected ${d}, got ${p}`)}catch{n.push(`field "${c}": comparison failed (possibly circular reference)`)}}return n}function w0n(e,t){let n=t.decision==="allow"||t.matched===!1;return{...e,passed:n,failureReason:n?void 0:`Expected allow but got ${t.decision}`,repairHint:n?void 0:"Rule incorrectly blocks or intervenes on benign input"}}function b0n(e,t){let n=v0n.has(t.decision);return{...e,passed:n,failureReason:n?void 0:`Expected block but got ${t.decision}`,repairHint:n?void 0:"Rule failed to block harmful input -- check condition matching"}}function C0n(e,t,n){if(t.decision!=="auto_correct")return{...e,passed:!1,failureReason:`Expected auto_correct (propose_correction) but got ${t.decision}`,repairHint:"Rule must return auto_correct decision with correctionProposal"};let r=t.correctionProposal;if(!r)return{...e,passed:!1,failureReason:"auto_correct decision missing correctionProposal",repairHint:"Return correctionProposal with proposedParams when decision is auto_correct"};let i={...e,passed:!0};if(n.expectedProposedParams){let o=HV(n.expectedProposedParams,r.proposedParams);i.proposedParamsMatch=o.length===0,i.proposedParamsDiff=o.length>0?o:void 0,o.length>0&&(i.passed=!1,i.failureReason=`proposedParams mismatch: ${o.join("; ")}`,i.repairHint="Ensure correctionProposal.proposedParams matches expected corrected params")}return n.expectedApplicationMode&&(i.applicationModeMatch=r.applicationMode===n.expectedApplicationMode,i.applicationModeMatch||(i.passed=!1,i.failureReason=(i.failureReason?i.failureReason+"; ":"")+`applicationMode mismatch: expected ${n.expectedApplicationMode}, got ${r.applicationMode}`,i.repairHint=(i.repairHint?i.repairHint+"; ":"")+"Set correctionProposal.applicationMode to match expected mode")),i}function S0n(e,t,n={}){let{projectDir:r,toolSemantics:i}=n,o=PB({toolName:t.toolName,params:t.params},t.ruleContext!==void 0?{context:t.ruleContext}:{},r||i?{...r?{projectDir:r}:{},...i?{toolSemantics:i}:{}}:{}),s={caseId:t.caseId,passed:!1,expectedDecision:t.expectedDecision,actualDecision:"error"},a=(()=>{let u={isRiskPath:()=>o.workspace.isRiskPath,getToolName:()=>o.action.toolName,getEstimatedLineChanges:()=>o.derived.estimatedLineChanges,getBashRisk:()=>o.derived.bashRisk,getEpTier:()=>o.evolution.epTier};try{return{ok:!0,value:e(o,u)}}catch(d){return{ok:!1,error:d.message}}})();if(!a.ok)return{...s,actualDecision:"error",failureReason:`evaluate() threw: ${a.error}`,repairHint:"Ensure evaluate() handles all input shapes without throwing"};let c=a.value,l={...s,actualDecision:c.decision};switch(t.expectedDecision){case"allow":return w0n(l,c);case"block":return b0n(l,c);case"propose_correction":return C0n(l,c,t);default:return{...s,failureReason:`Unknown expectedDecision: ${String(t.expectedDecision)}`}}}function jV(e,t,n){let r={...nme,...n};if(t.length===0)return{passed:!0,totalCases:0,passedCases:0,failedCases:0,perCaseResults:[],failureReasons:[],repairHints:[]};let i=t.map(l=>S0n(e,l,{...r.projectDir!==void 0?{projectDir:r.projectDir}:{},...r.toolSemantics!==void 0?{toolSemantics:r.toolSemantics}:{}})),o=i.filter(l=>l.passed).length,s=i.length-o,a=i.filter(l=>!l.passed&&l.failureReason).map(l=>`[${l.caseId}] ${l.failureReason??""}`),c=i.filter(l=>!l.passed&&l.repairHint).map(l=>l.repairHint??"");return r.maxRepairAttempts,{passed:s===0,totalCases:i.length,passedCases:o,failedCases:s,perCaseResults:i,failureReasons:a,repairHints:c}}var T0n=[{symbol:"recentThinking",pattern:/\brecentThinking\b/},{symbol:"planStatus",pattern:/\bplanStatus\b/},{symbol:"getPlanStatus",pattern:/\bgetPlanStatus\s*\(/},{symbol:"hasPlanFileHelper",pattern:/\bhasPlanFile\s*\(/},{symbol:"hasPlanFile",pattern:/\bhasPlanFile\b(?!\s*\()/}];function rme(e){let t="code",n=0,r="";for(let i=0;i<e.length;i+=1){let o=e[i]??"",s=e[i+1]??"";if(t==="code"){n>0&&o==="{"?(n+=1,r+=o):n>0&&o==="}"?(n-=1,r+=o,n===0&&(t="template")):o==="/"&&s==="/"?(r+=" ",i+=1,t="line_comment"):o==="/"&&s==="*"?(r+=" ",i+=1,t="block_comment"):o==="'"?(r+=" ",t="single_quote"):o==='"'?(r+=" ",t="double_quote"):o==="`"?(r+=" ",t="template"):r+=o;continue}if(t==="line_comment"){r+=o===`
1409
+ `),o=[];for(let s of i){let a=s.trim();if(a)try{let c=JSON.parse(a);if(t?.principleId&&c.principleId!==t.principleId)continue;o.push(c)}catch{}}return o}import Jki from"better-sqlite3";var Rf={stageThresholds:{elevated:40,critical:70,saturated:100},repeatedFailureMultiplier:{base:1.5,max:3},decayRatesPerMinute:{stable:.5,elevated:1,critical:2,saturated:4},relief:{toolSuccessRatio:.25,minPruneBelow:8},sourceWeights:{}};function kV(e,t,n){let i=e.lastErrorHash!==void 0&&e.lastErrorHash===t.hash?e.consecutiveErrors+1:1,o=Math.max(0,i-1),s=Math.min(Math.pow(n.repeatedFailureMultiplier.base,o),n.repeatedFailureMultiplier.max),a=t.baseScore*s,c=e.currentGfi+a,l={...e.gfiBySource};return l[t.source]=(l[t.source]??0)+a,{...e,currentGfi:c,gfiBySource:l,consecutiveErrors:i,lastErrorHash:t.hash,lastErrorSource:t.source,dailyGfiPeak:Math.max(e.dailyGfiPeak??0,c)}}function RV(e,t,n,r,i){let o=n.decayRatesPerMinute[r],s={};for(let[c,l]of Object.entries(e.gfiBySource)){let u=l-o*t,d=Math.max(0,Math.round(u*10)/10);d>=n.relief.minPruneBelow&&(s[c]=d)}let a=Object.keys(s).length>0?Math.max(0,Math.round(Object.values(s).reduce((c,l)=>c+l,0)*10)/10):Object.keys(e.gfiBySource).length>0?0:Math.max(0,Math.round((e.currentGfi-o*t)*10)/10);return{...e,currentGfi:a,gfiBySource:s,lastGfiDecayAt:i}}function kB(e,t,n,r=Rf){let{source:i,amount:o=0}=t;if(i==="all"&&o>=100)return{currentGfi:0,gfiBySource:{},consecutiveErrors:0,lastErrorHash:void 0,lastErrorSource:void 0,lastGfiDecayAt:n,dailyGfiPeak:e.dailyGfiPeak};let s={...e.gfiBySource};if(o>0){let u=i;s[u]!==void 0&&(s[u]=Math.max(0,(s[u]??0)-o),s[u]===0&&delete s[u])}else{let u=r.relief.toolSuccessRatio;for(let d of Object.keys(s)){let p=d;s[p]=Math.max(0,Math.round((s[p]??0)*(1-u)*10)/10),s[p]===0&&delete s[p]}}let a=Object.values(s).reduce((u,d)=>u+d,0),l=i===e.lastErrorSource&&i!=="all"?0:e.consecutiveErrors;return{...e,currentGfi:a,gfiBySource:s,consecutiveErrors:l,lastErrorHash:l===0?void 0:e.lastErrorHash,lastErrorSource:l===0?void 0:e.lastErrorSource,lastGfiDecayAt:n}}function DV(e,t){return e>=t.stageThresholds.saturated?"saturated":e>=t.stageThresholds.critical?"critical":e>=t.stageThresholds.elevated?"elevated":"stable"}var oRi=7200*1e3;var Kfe=["hook","service","startup"],Vfe=["core","quiet","gone","legacy_retire"],ZI=[{id:"hook:before_prompt_build",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Principle injection + workspace init on prompt build"},{id:"hook:before_tool_call",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Security gate for tool calls (risk assessment, plan approval)"},{id:"hook:after_tool_call",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Pain detection + empathy observer on tool call result"},{id:"hook:llm_output",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"LLM output analysis for pain signal extraction"},{id:"hook:before_reset",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for context reset",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:before_compaction",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for before compaction",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:after_compaction",kind:"hook",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"Lifecycle hook for after compaction",disabledReason:"Disabled by default: lifecycle hooks are opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"hook:before_message_write",kind:"hook",category:"core",enabledByDefault:!0,since:"2026-06-09",description:"Fallback trajectory collection (SQLite) when llm_output is blocked by missing allowConversationAccess (PRI-346)"},{id:"service:correction-observer",kind:"service",category:"core",enabledByDefault:!0,since:"2026-06-02",description:"Independent correction observer service for keyword self-correction (MVP-Core per ADR-0014 amendment, PRI-293)"},{id:"service:trajectory",kind:"service",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Trajectory collection service \u2014 pre-initializes TrajectoryDB registry; hooks (llm_output, before_message_write) are the primary writers (PRI-346/353)"},{id:"service:pd-task",kind:"service",category:"quiet",enabledByDefault:!1,since:"2026-05-24",description:"PD task management service",disabledReason:"Disabled by default: pd-task service is opt-in; default off per ADR-0014 \xA72.5 (preserved in plugin code, not active in production)."},{id:"service:internalization-auto-consumer",kind:"service",category:"core",enabledByDefault:!0,since:"2026-06-13",description:"Bounded auto-consumer for dreamer internalization tasks \u2014 prevents ready tasks from pending forever (PRI-381)"},{id:"startup:workspace-init",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-05-24",description:"Workspace migration + template setup on first prompt"},{id:"startup:correction-observer",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-06-02",description:"Correction observer start on first prompt per workspace (MVP-Core per ADR-0014 amendment, PRI-293)"},{id:"startup:internalization-auto-consumer",kind:"startup",category:"core",enabledByDefault:!0,since:"2026-06-13",description:"Internalization auto-consumer start on first prompt per workspace (MVP-Core, PRI-381)"}];function OV(e){let t=[],n=[],r=new Set;for(let i of e)r.has(i.id)&&t.push(`duplicate surface id: '${i.id}'`),r.add(i.id),(typeof i.id!="string"||i.id.length===0)&&t.push(`surface entry has invalid id: '${String(i.id)}'`),Kfe.includes(i.kind)||t.push(`surface '${i.id}': invalid kind '${i.kind}'`),Vfe.includes(i.category)||t.push(`surface '${i.id}': invalid category '${i.category}'`),typeof i.enabledByDefault!="boolean"&&t.push(`surface '${i.id}': enabledByDefault must be boolean`),(typeof i.since!="string"||i.since.length===0)&&t.push(`surface '${i.id}': since must be a non-empty string`),(typeof i.description!="string"||i.description.length===0)&&t.push(`surface '${i.id}': description must be a non-empty string`),i.category==="core"&&!i.enabledByDefault&&t.push(`surface '${i.id}': core surface must be enabledByDefault=true`),i.category!=="core"&&i.enabledByDefault&&t.push(`surface '${i.id}': non-core surface (${i.category}) must not be enabledByDefault=true`),(i.category==="quiet"||i.category==="gone"||i.category==="legacy_retire")&&!i.disabledReason&&n.push(`surface '${i.id}': ${i.category} surface has no disabledReason \u2014 observability gap (ERR-002)`);return{valid:t.length===0,errors:t,warnings:n}}function NV(e,t){return e.filter(n=>n.category===t)}var Uet=new Set;function Qet(e,t,n){return Uet.has(e)||!t?.info?!1:(Uet.add(e),t.info(n),!0)}function PV(){let e=OV(ZI),t=[],n=[...e.warnings],i=NV(ZI,"core").filter(s=>s.enabledByDefault),o=ZI.filter(s=>s.category!=="core"&&s.enabledByDefault);if(o.length>0)for(let s of o)t.push(`non-core surface '${s.id}' (${s.category}) is enabledByDefault=true \u2014 must be false per ADR-0014`);return e.valid||t.push(...e.errors),{passed:t.length===0,enabledCoreSurfaces:i.map(s=>s.id),disabledNonCoreSurfaces:ZI.filter(s=>s.category!=="core"&&!s.enabledByDefault).map(s=>s.id),violations:t,warnings:n}}function LV(e,t={}){let n=ZI.find(r=>r.id===e);if(!n)return{enabled:!1,reason:`surface '${e}' not found in registry \u2014 classify before enabling (PRI-289)`};if(Object.hasOwn(t,e)){let r=t[e];return typeof r!="boolean"?{enabled:n.enabledByDefault,reason:`override for '${e}' is not boolean, using default`}:n.category==="gone"?{enabled:!1,reason:`surface '${e}' is gone and cannot be re-enabled`}:n.category==="core"&&!r?{enabled:!0,reason:`surface '${e}' is core and cannot be disabled`}:{enabled:r}}return!n.enabledByDefault&&n.disabledReason?{enabled:!1,reason:n.disabledReason}:{enabled:n.enabledByDefault}}function Df(e,t,n){let r=LV(e);if(r.enabled)return n;let i=r.reason??"surface not enabled";return(o,s)=>{Qet(e,t,`[PD:surface-guard] SKIP ${e}: ${i}`)}}function cv(e,t,n){let r=LV(e);if(r.enabled)return t;let i=r.reason??"surface not enabled";return Qet(e,n,`[PD:surface-guard] SKIP service ${e}: ${i}`),null}function MV(e){if(!(typeof e!="object"||e===null||Array.isArray(e))&&Object.hasOwn(e,"sourcePrincipleId")){let t=Reflect.get(e,"sourcePrincipleId");typeof t=="string"&&!Db(t)&&Reflect.deleteProperty(e,"sourcePrincipleId")}}var Yfe=["prompt","defer_archive"],zfe={skill:"medium",code_tool_hook:"high"},BV=.95,FV=["skill"];function RB(e,t){return`${e}::${t}`}function DB(e){return Yfe.includes(e)}function UV(e){return DB(e)?"low":zfe[e]??"high"}function QV(e,t){return t==null||t<0||t>1||!FV.includes(e)?!1:t>=BV}function $et(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function dv(e){if(typeof e.sourcePrincipleId=="string"){let t=e.sourcePrincipleId.trim();if(t!=="")return t}try{let t=JSON.parse(e.contentJson);if(!$et(t))return null;if(typeof t.principleId=="string"&&t.principleId.trim()!=="")return t.principleId.trim();if(typeof t.sourcePrincipleId=="string"&&t.sourcePrincipleId.trim()!=="")return t.sourcePrincipleId.trim();if($et(t.principleDraft)){let n=t.principleDraft;if(typeof n.title=="string"&&n.title.trim()!=="")return n.title.trim()}}catch{return null}return null}var lv=class{channel="prompt";async canActivate(t){return t.artifactKind!=="principle"?{ok:!1,reason:"artifact_kind_not_principle",riskLevel:"low"}:t.validationStatus!=="validated"?{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"low"}:dv(t)?{ok:!0,riskLevel:"low"}:{ok:!1,reason:"no_principle_id_in_artifact",riskLevel:"low"}}async activate(t,n){return{activationId:`act_prompt_${t.principleId}`,action:"prompt_activate",targetRef:`ledger://${t.principleId}`}}},uv=class{channel="defer_archive";async canActivate(t){return t.artifactKind!=="principle"?{ok:!1,reason:"artifact_kind_not_principle",riskLevel:"low"}:t.validationStatus!=="validated"?{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"low"}:dv(t)?{ok:!0,riskLevel:"low"}:{ok:!1,reason:"no_principle_id_in_artifact",riskLevel:"low"}}async activate(t,n){return{activationId:`act_archive_${t.principleId}`,action:"defer_archive",targetRef:`ledger://${t.principleId}#archived`}}};function t0n(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}async function Wet(e,t,n){try{let r=await e.canActivate(t);return r.ok?{decision:null,result:r}:{decision:{decision:"refused",reason:r.reason??"can_activate_refused",riskLevel:r.riskLevel,channel:e.channel,...r.failure?{failure:r.failure}:{}}}}catch(r){let i=r instanceof Error?r.message:String(r);if(n)try{n.emitTelemetry({eventType:"degradation_triggered",traceId:t.artifactId,timestamp:new Date().toISOString(),sessionId:"activation-dispatcher",payload:{component:"ActivationDispatcher",event:"ACTIVATION_CAN_ACTIVATE_FAILED",trigger:"can_activate_check_failed",channel:e.channel,artifactId:t.artifactId,originalError:i,errorCategory:"can_activate_check_failed",nextAction:"Investigate the ChannelWriter.canActivate implementation for this channel; it threw during the pre-activation guard check."}})}catch{}return{decision:{decision:"refused",reason:"can_activate_check_failed",channel:e.channel,details:{originalError:i,errorCategory:"can_activate_check_failed"}}}}}function n0n(e,t,n,r){let i="";try{let c=JSON.parse(e.contentJson);t0n(c)&&(i=String(c.text??c.description??""))}catch{}let o=e.artifactKind??"artifact",s=r!==void 0?Math.round(r*100)+"%":"unknown",a={skill:"This principle will be activated as a skill that monitors and influences agent behavior in real-time.",code_tool_hook:"This principle will be injected as a code tool hook that intercepts and validates tool calls before execution."};return{summary:i?`Activate ${o}: "${i.slice(0,200)}"`:`Activate ${o} artifact ${e.artifactId}`,triggerReason:`Rollout reviewer recommended activation via ${t} channel (risk: ${n}).`,confidenceExplanation:r!==void 0?`Confidence score: ${s}. `+(r>=.8?"High confidence based on multiple validations.":r>=.5?"Moderate confidence, additional review recommended.":"Low confidence, manual review strongly recommended."):"Confidence score not available.",effectDescription:a[t]??`This artifact will be activated via the ${t} channel.`,rejectionEffect:`The artifact will remain inactive and will not be deployed to the ${t} channel. You can request activation again later.`}}var pv=class{artifactReadModel;stateReadModel;writers;approvalQueueStore;eventEmitter;constructor(t,n,r){this.artifactReadModel=t,this.stateReadModel=n,this.approvalQueueStore=r.approvalQueueStore,this.eventEmitter=r.eventEmitter,this.writers=new Map;for(let i of r.writers)this.writers.set(i.channel,i)}async dispatch(t){let n=await this.readArtifact(t.artifactId);if(n.decision)return n.decision;let{artifact:r}=n;if(!r.artifactId||typeof r.artifactKind!="string")return{decision:"invalid_artifact",reason:"malformed_artifact"};let i=t.idempotencyKey??RB(t.artifactId,t.channel),o=await this.checkIdempotency(i,t.artifactId);if(o.decision)return o.decision;if(t.rolloutDecision==="reject")return{decision:"refused",reason:"rollout_rejected",channel:t.channel};if(t.rolloutDecision==="approved"){if(!t.approvalId)return{decision:"refused",reason:"approved_dispatch_requires_approval_id",nextAction:"provide approvalId from a verified owner approval record",channel:t.channel};if(!this.approvalQueueStore)return{decision:"refused",reason:"approved_dispatch_without_approval_store",nextAction:"configure dispatcher with approvalQueueStore to verify approvals",channel:t.channel};let a;try{a=await this.approvalQueueStore.getById(t.approvalId)}catch{return{decision:"refused",reason:"approval_record_read_failed",nextAction:"check_approval_store_availability",channel:t.channel}}return a?a.status!=="approved"?{decision:"refused",reason:`approval_status_is_${a.status}_expected_approved`,nextAction:a.status==="pending"?"owner_must_approve_before_dispatch":"rejected_or_expired_approvals_cannot_be_activated",channel:t.channel}:a.artifactId!==t.artifactId?{decision:"refused",reason:`approval_artifact_mismatch: approval=${a.artifactId} dispatch=${t.artifactId}`,nextAction:"ensure_dispatch_artifact_matches_approved_artifact",channel:t.channel}:a.channel!==t.channel?{decision:"refused",reason:`approval_channel_mismatch: approval=${a.channel} dispatch=${t.channel}`,nextAction:"ensure_dispatch_channel_matches_approved_channel",channel:t.channel}:this.activateArtifact(t,r,i):{decision:"refused",reason:`approval_record_not_found: ${t.approvalId}`,nextAction:"verify_approval_id",channel:t.channel}}return t.rolloutDecision==="require_approval"||!DB(t.channel)?QV(t.channel,t.confidence)?this.activateArtifact(t,r,i):this.enqueueForApproval(t,r,i):this.activateArtifact(t,r,i)}async enqueueForApproval(t,n,r){let i=UV(t.channel);if(!this.approvalQueueStore)return{decision:"refused",reason:"requires_approval",channel:t.channel,riskLevel:i};let o=this.writers.get(t.channel);if(o){let s=await Wet(o,n,this.eventEmitter);if(s.decision)return s.decision}if(!t.confirm)return{decision:"queued_for_approval",approvalId:"apr_"+t.channel+"_"+t.artifactId,queuedAt:t.now,channel:t.channel,riskLevel:i};try{let s=o?.buildApprovalContext?.({artifactId:t.artifactId,channel:t.channel,principleId:dv(n)??"",idempotencyKey:r,now:t.now},n,t.confidence),a=await this.approvalQueueStore.enqueue({artifactId:t.artifactId,channel:t.channel,riskLevel:i,confidence:t.confidence,...s??n0n(n,t.channel,i,t.confidence)},t.now);return{decision:"queued_for_approval",approvalId:a.approvalId,queuedAt:a.requestedAt,channel:t.channel,riskLevel:i}}catch{return{decision:"refused",reason:"approval_enqueue_failed",channel:t.channel,riskLevel:i}}}async activateArtifact(t,n,r){let i=dv(n);if(!i)return{decision:"invalid_artifact",reason:"no_principle_id"};let o=this.writers.get(t.channel);if(!o)return{decision:"refused",reason:"no_writer_for_channel_"+t.channel,channel:t.channel};let s=await Wet(o,n,this.eventEmitter);if(s.decision)return s.decision;let a={artifactId:t.artifactId,channel:t.channel,principleId:i,idempotencyKey:r,now:t.now},c;try{c=await o.activate(a,n)}catch{return{decision:"refused",reason:"activation_write_failed",channel:t.channel}}if(!t.confirm)return{decision:"would_activate",activationId:c.activationId,action:c.action,targetRef:c.targetRef};try{await this.stateReadModel.recordActivation({activationId:c.activationId,idempotencyKey:r,artifactId:t.artifactId,channel:t.channel,action:c.action,targetRef:c.targetRef,activatedAt:t.now,deactivatedAt:null})}catch{return{decision:"refused",reason:"activation_record_failed",channel:t.channel}}return{decision:"activated",activationId:c.activationId,action:c.action,targetRef:c.targetRef}}async readArtifact(t){try{let n=await this.artifactReadModel.getArtifactById(t);return n?{artifact:n,decision:null}:{artifact:null,decision:{decision:"invalid_artifact",reason:"artifact_not_found",nextAction:"check_pi_artifacts_table_or_remove_stale_activation"}}}catch{return{artifact:null,decision:{decision:"refused",reason:"artifact_read_failed"}}}}async checkIdempotency(t,n){try{let r=await this.stateReadModel.getActivationStatus(t);return r?r.artifactId!==n?{decision:{decision:"refused",reason:`idempotency_artifact_mismatch: existing=${r.artifactId} input=${n}`,nextAction:"Investigate data corruption. The existing activation references a different artifact_id than the dispatch input. Run `pd runtime internalization integrity` for full chain diagnostics."}}:{decision:{decision:"already_activated",activationId:r.activationId,action:r.action,targetRef:r.targetRef}}:{decision:null}}catch{return{decision:{decision:"refused",reason:"activation_state_read_failed"}}}}};function OB(e){switch(e){case"principle":return"FAILED_PRINCIPLE";case"rule":return"FAILED_RULE";case"evaluation":return"FAILED_EVALUATION";case"test":return"FAILED_TEST";case"runtime":return"INFRA_BLOCKED";default:return"UNKNOWN"}}var r0n=new Map([["v2-unavailable","allow"],["v2-truncated","allow"],["v2-alias","allow"]]);function i0n(e){return r0n.has(e)?"allow":e==="v2-path-boundary"||e==="v2-combination"?"block":null}function qet(e){if(e==null||e.trim()==="")return null;let t;try{t=JSON.parse(e)}catch{return null}if(typeof t!="object"||t===null||Array.isArray(t))return null;let n=t;if(!Object.hasOwn(n,"requiresContextVersion"))return;let r=n.requiresContextVersion;return typeof r=="number"?r:null}function Jfe(e){let{requiresContextVersion:t,failedCases:n}=e;if(t===2)return{outOfScope:[],inScope:n.map(o=>o.caseId),isPureOutOfScope:!1};let r=[],i=[];for(let o of n)i0n(o.caseId)==="allow"&&o.expectedDecision==="allow"?r.push(o.caseId):i.push(o.caseId);return{outOfScope:r,inScope:i,isPureOutOfScope:r.length>0&&i.length===0}}var Get=300;function hA(e){return e.length>Get?`${e.slice(0,Get)}\u2026`:e}function Xfe(e){if(!e.toolSemantics.hasHostLayer)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_registry_host_layer_missing",evidence:"ToolSemanticRegistry has no host-declared layer \u2014 tool existence cannot be verified against the production host",nextAction:"supply a host-declared registry (host mappings), or run the host once so its declaration is persisted for the workspace"}};let t=s=>e.toolSemantics.hasHostTool(s)?"ok":e.toolSemantics.lookup(s)===null?"unknown":"not_dispatchable",n=e.affectedTools.filter(s=>t(s)==="unknown"),r=e.affectedTools.filter(s=>t(s)==="not_dispatchable");if(n.length>0)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_alias_unknown",evidence:hA(`affectedTools unknown to any tool vocabulary: ${n.join(", ")}`),nextAction:"regenerate the rule using real host tool names (see the host tool semantic declaration)"}};if(r.length>0)return{valid:!1,failure:{layer:"adapter",reasonCode:"tool_not_host_dispatchable",evidence:hA(`affectedTools semantically classifiable but NOT dispatched by this host (never reach the RuleHost gate): ${r.join(", ")}`),nextAction:"regenerate the rule against host-declared tool names \u2014 generic LLM vocabulary and read/search-family names cannot trigger rules in production"}};let i=e.goldenTraceCaseToolNames.filter(s=>t(s)==="unknown"),o=e.goldenTraceCaseToolNames.filter(s=>t(s)==="not_dispatchable");if(i.length>0||o.length>0){let s=[];return i.length>0&&s.push(`unknown: ${i.join(", ")}`),o.length>0&&s.push(`not host-dispatchable: ${o.join(", ")}`),{valid:!1,failure:{layer:"adapter",reasonCode:i.length>0?"tool_alias_unknown":"tool_not_host_dispatchable",evidence:hA(`goldenTraceCases toolName ${s.join("; ")}`),nextAction:"regenerate golden trace cases against host-declared tool names so replay exercises inputs production can actually produce"}}}return{valid:!0}}var o0n=new Set(["__sandbox__","__no_evaluator__","__compile__","__return_shape__","__matched_false_decision__"]);function dh(e,t){switch(e){case"rejected_no_cases":return{layer:"test",reasonCode:"golden_trace_empty",evidence:"goldenTrace.cases is empty \u2014 no test material to validate against",nextAction:"regenerate the artifact with at least one positive and one negative golden trace case"};case"rejected_forbidden_pattern":return{layer:"rule",reasonCode:"forbidden_pattern",evidence:hA(`forbidden patterns: ${t.forbiddenPatternViolations.join(", ")}`),nextAction:"regenerate RuleCode without forbidden APIs (no fs/process/require/eval/network)"};case"rejected_timeout":return{layer:"rule",reasonCode:"evaluation_timeout",evidence:hA(t.failedCases.map(n=>`${n.caseId}: ${n.message}`).join("; ")),nextAction:"regenerate RuleCode with bounded logic (no unbounded loops)"};case"rejected_validation_failed":{let n=t.failedCases.filter(r=>r.errorType==="validation_failed").map(r=>`${r.caseId}: ${r.message}`).join("; ");return{layer:"rule",reasonCode:"replay_decision_mismatch",evidence:hA(n||"validation failed with no case detail"),nextAction:"fix the RuleCode decision logic to satisfy the golden trace expectations"}}case"rejected_runtime_error":{let n=t.failedCases.filter(i=>o0n.has(i.caseId));if(n.length>0)return{layer:"runtime",reasonCode:"sandbox_infrastructure_failure",evidence:hA(n.map(i=>`${i.caseId}: ${i.message}`).join("; ")),nextAction:"inspect the sandbox/gate adapter wiring, then re-run the gate"};let r=t.failedCases.map(i=>`${i.caseId}: ${i.errorType} \u2014 ${i.message}`);return{layer:"rule",reasonCode:"rule_code_execution_error",evidence:hA(r.join("; ")),nextAction:"fix the RuleCode so evaluate() handles every input shape without throwing"}}default:return{layer:"unknown",reasonCode:"unclassified",evidence:hA(`gate decision ${String(e)}`),nextAction:"inspect the full gate result manually"}}}var Het={success:!1,failedCases:[],executionTimeMs:0,forbiddenPatternViolations:[]};function s0n(e){if(e instanceof Error)return e.message;if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean"||typeof e=="bigint")return String(e);if(typeof e=="symbol")return e.toString();try{return JSON.stringify(e)??String(e)}catch{return"[unserializable]"}}function a0n(e){let t=s0n(e);return{success:!1,failedCases:[{caseId:"__sandbox__",errorType:e instanceof Error?"runtime_error":"unknown",message:t}],executionTimeMs:0,forbiddenPatternViolations:[]}}function c0n(e,t){try{return{result:e.evaluateInSandbox(t.code,t.goldenTrace,t.opts),threw:!1}}catch(n){return{result:a0n(n),threw:!0}}}function lR(e,t){let n=[];if(e.requestedMode==="live"&&n.push("requestedMode=live is not supported in PRI-173; applicationMode forced to shadow"),e.goldenTrace.cases.length===0){let u="rejected_no_cases";return{decision:u,applicationMode:"shadow",sandboxResult:Het,reasons:["goldenTrace.cases is empty \u2014 no test cases to validate against",...n],failure:dh(u,Het)}}let r={...e.softTimeoutMs!==void 0?{softTimeoutMs:e.softTimeoutMs}:{},...e.toolSemantics!==void 0?{toolSemantics:e.toolSemantics}:{},...e.projectDir!==void 0?{projectDir:e.projectDir}:{}},i=c0n(t,{code:e.code,goldenTrace:e.goldenTrace,opts:r});if(i.threw){let u="rejected_runtime_error";return{decision:u,applicationMode:"shadow",sandboxResult:i.result,reasons:["sandbox adapter failure: evaluateInSandbox threw",...n],failure:dh(u,i.result)}}let o=i.result;if(o.forbiddenPatternViolations.length>0){let u="rejected_forbidden_pattern";return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[`forbidden patterns detected: ${o.forbiddenPatternViolations.join(", ")}`,...n],failure:dh(u,o)}}if(o.failedCases.length===0){if(!o.success){let u="rejected_runtime_error";return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:["sandbox reported success=false with no failedCases or forbiddenPatternViolations \u2014 fail closed",...n],failure:dh(u,o)}}return{decision:"accepted_shadow",applicationMode:"shadow",sandboxResult:o,reasons:n}}let s=new Set(o.failedCases.map(u=>u.errorType));if(s.has("timeout")){let u="rejected_timeout",d=o.failedCases.filter(p=>p.errorType==="timeout");return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: timeout \u2014 ${p.message}`),...n],failure:dh(u,o)}}let a=new Set(["runtime_error","syntax_error","unknown"]);if([...s].some(u=>a.has(u))){let u="rejected_runtime_error",d=o.failedCases.filter(p=>a.has(p.errorType));return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: ${p.errorType} \u2014 ${p.message}`),...n],failure:dh(u,o)}}if(s.has("validation_failed")){let u="rejected_validation_failed",d=o.failedCases.filter(p=>p.errorType==="validation_failed");return{decision:u,applicationMode:"shadow",sandboxResult:o,reasons:[...d.map(p=>`case ${p.caseId}: validation_failed \u2014 ${p.message}`),...n],failure:dh(u,o)}}let l="rejected_runtime_error";return{decision:l,applicationMode:"shadow",sandboxResult:o,reasons:[...o.failedCases.map(u=>`case ${u.caseId}: ${u.errorType} \u2014 ${u.message}`),...n],failure:dh(l,o)}}function $V(e,t){if(!e||typeof e!="string")return"";let n=e.replace(/\\/g,"/"),r=t.replace(/\\/g,"/"),i=n.length>=2&&n[1]===":",o=r.length>=2&&r[1]===":",s=n;i&&!o&&(s=`/mnt/${n.charAt(0).toLowerCase()}${n.slice(2)}`);let a=i&&o?s.slice(2):s,c=o?r.slice(2):r,l=a.startsWith("/"),u=c.startsWith("/");if(l&&u){let d=jet(c,a);return d.startsWith("../")?s:d}if(!l){let d=l0n(c,a),p=jet(c,d);return p.startsWith("../")?s:p}return s}function jet(e,t){let n=e.split("/").filter(c=>c.length>0),r=t.split("/").filter(c=>c.length>0),i=0;for(;i<n.length&&i<r.length&&n[i]===r[i];)i++;let o=n.length-i,s=r.slice(i),a=[];for(let c=0;c<o;c++)a.push("..");return a.push(...s),a.length===0?".":a.join("/")}function l0n(e,t){let n=e.split("/").filter(o=>o.length>0),r=t.split("/").filter(o=>o.length>0),i=[];for(let o of n)o===".."?i.length>0&&i.pop():o!=="."&&i.push(o);for(let o of r)o===".."?i.length>0&&i.pop():o!=="."&&i.push(o);return"/"+i.join("/")}function WV(e,t={}){let n=e.file_path||e.path||e.file||e.target;if(typeof n=="string"&&n.length>0)return n;if(t.isBashTool){let r=String(e.command||e.args||"");if(r){let i=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(r);return i&&i[1]?i[1]:r}}return t.isWriteTool&&t.toolName?`<tool:${t.toolName}>`:null}function GV(e){return{isBashTool:e==="execute",isWriteTool:e==="write"}}function u0n(e){if(e.canonicalKind===void 0)return e;let t=GV(e.canonicalKind);return{...e,isBashTool:e.isBashTool??t.isBashTool,isWriteTool:e.isWriteTool??t.isWriteTool}}function eE(e,t,n,r={}){let i=u0n(r),o=WV(t,{...i,toolName:e}),s=$V(o,n);return{toolName:e,normalizedPath:s,paramsSummary:{...t},...i.canonicalKind!==void 0?{canonicalKind:i.canonicalKind}:{}}}var Ket=f.Record(f.String(),f.Unknown()),d0n="^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d{3})?Z$",Yet=f.Union([f.Literal("shadow"),f.Literal("live")]),zet=f.Union([f.Literal("allow"),f.Literal("block"),f.Literal("propose_correction")]),Jet=f.Union([f.Literal("negative"),f.Literal("positive")]),Zfe=f.Object({caseId:f.String({minLength:1}),kind:Jet,toolName:f.String({minLength:1}),params:Ket,expectedDecision:zet,expectedProposedParams:f.Optional(Ket),expectedApplicationMode:f.Optional(Yet),sourceRefs:f.Optional(f.Object({painId:f.Optional(f.String({minLength:1})),candidateId:f.Optional(f.String({minLength:1})),artifactId:f.Optional(f.String({minLength:1})),auditEventId:f.Optional(f.String({minLength:1}))})),ruleContext:f.Optional(f.Unknown())}),Xet=f.Object({traceId:f.String({minLength:1}),sourcePainId:f.Optional(f.String({minLength:1})),sourceCandidateId:f.Optional(f.String({minLength:1})),sourceArtifactId:f.Optional(f.String({minLength:1})),cases:f.Array(Zfe,{minItems:1}),createdAt:f.String({pattern:d0n}),version:f.Literal(1)});function Zet(e,t){return[...Ct.Errors(e,t)].map(n=>String(n.path||n.message))}function NB(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Vet(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"case"}function p0n(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function eme(e){let t=Zet(Zfe,e);return t.length===0&&NB(e)&&(e.expectedDecision==="propose_correction"&&!NB(e.expectedProposedParams)&&t.push("expectedProposedParams is required when expectedDecision is propose_correction"),e.expectedDecision==="propose_correction"&&e.expectedApplicationMode===void 0&&t.push("expectedApplicationMode is required when expectedDecision is propose_correction"),e.kind==="positive"&&e.expectedDecision!=="allow"&&t.push("positive cases must expect allow")),{valid:t.length===0,errors:t}}function uR(e){let t=Zet(Xet,e);if(!NB(e))return{valid:!1,errors:t};if(Object.hasOwn(e,"createdAt")&&!p0n(e.createdAt)&&t.push("createdAt must be a parseable ISO-8601 timestamp"),Array.isArray(e.cases)){let n=!1,r=!1;e.cases.forEach((i,o)=>{let s=eme(i);s.valid||t.push(...s.errors.map(a=>`cases[${o}].${a}`)),NB(i)&&i.kind==="negative"&&(n=!0),NB(i)&&i.kind==="positive"&&(r=!0)}),n||t.push("cases must include at least one negative case"),r||t.push("cases must include at least one positive case")}return{valid:t.length===0,errors:t}}function PB(e,t={},n={}){let r=n.toolSemantics?.resolve(e.toolName);return{action:n.projectDir&&t.normalizedPath===void 0?eE(e.toolName,e.params,n.projectDir,r!==void 0?{canonicalKind:r}:{}):{toolName:e.toolName,normalizedPath:t.normalizedPath??null,paramsSummary:{...e.params},...r!==void 0?{canonicalKind:r}:{}},workspace:{isRiskPath:!1,...t.workspace},session:{currentGfi:0,...t.session},evolution:{epTier:0,...t.evolution},derived:{estimatedLineChanges:0,bashRisk:"unknown",...t.derived},...t.context!==void 0?{context:t.context}:{}}}function tme(e){return{traceId:`golden-trace-${Vet(e.toolName)}-${Vet(e.expectedDecision)}`,sourcePainId:e.sourcePainId,sourceCandidateId:e.sourceCandidateId,sourceArtifactId:e.sourceArtifactId,version:1,createdAt:e.createdAt??"2026-05-11T00:00:00.000Z",cases:[{caseId:"negative-1",kind:"negative",toolName:e.toolName,params:{...e.negativeParams},expectedDecision:e.expectedDecision,expectedProposedParams:e.expectedProposedParams?{...e.expectedProposedParams}:void 0,expectedApplicationMode:e.expectedApplicationMode??(e.expectedDecision==="propose_correction"?"shadow":void 0)},{caseId:"positive-1",kind:"positive",toolName:e.toolName,params:{...e.positiveParams},expectedDecision:"allow"}]}}function tE(e){if(!Array.isArray(e.cases))return{ok:!1,reason:"cases must be an array"};if(e.cases.length===0)return{ok:!1,reason:"cases must contain at least 1 positive + 1 negative case, got 0"};let t=!1,n=!1,r=[];for(let s of e.cases){let a=eme(s);if(!a.valid)return{ok:!1,reason:`invalid golden trace case: ${a.errors.join("; ")}`};s.kind==="positive"?t=!0:n=!0,r.push(s)}if(!t||!n)return{ok:!1,reason:`cases must include at least one ${!t&&!n?"positive and negative":t?"negative":"positive"} case`};let i={traceId:`golden-trace-artificer-${Date.now().toString(36)}`,sourceArtifactId:e.sourceArtifactId,version:1,createdAt:e.createdAt??new Date().toISOString(),cases:r},o=uR(i);return o.valid?{ok:!0,trace:i}:{ok:!1,reason:`produced trace failed validation: ${o.errors.join("; ")}`}}var f0n=["edit","write","delete","bash","exec","remove"],m0n="rulecode_context_v2";function ett(e){try{let t=JSON.parse(e);return typeof t=="object"&&t!==null&&!Array.isArray(t)?t:null}catch{return null}}function h0n(e){let t=e.implementationCode;return typeof t=="string"&&t.trim().length>0?t:null}function g0n(e){let t=e.goldenTrace;if(typeof t!="object"||t===null||Array.isArray(t))return{ok:!1,reason:"no_golden_trace"};let n=uR(t);return n.valid?{ok:!0,trace:t}:{ok:!1,reason:`golden_trace_schema_invalid: ${n.errors.slice(0,3).join("; ")}`}}function A0n(e){let t=e.ruleHostGateDecision;return typeof t=="string"&&t.trim().length>0?t:null}function y0n(e){let{affectedTools:t}=e;return Array.isArray(t)&&t.some(r=>{if(typeof r!="string")return!1;let i=r.toLowerCase();return f0n.some(o=>i.includes(o))})?"critical":"high"}function qV(e){if(!Object.hasOwn(e,"evidenceRefs"))return null;let t=e.evidenceRefs;if(!Array.isArray(t)||t.length===0)return null;let n=[];for(let r of t){if(typeof r!="string"||r.trim()==="")return null;n.push(r)}return n}function I0n(e,t){for(let r of t.cases)if(r.expectedDecision==="propose_correction")return"v2_seed_rule_forbidden_decision:propose_correction";return qV(e)===null?Object.hasOwn(e,"evidenceRefs")?"v2_seed_rule_invalid_evidence_refs":"v2_seed_rule_missing_evidence_refs":null}var fv=class{channel="code_tool_hook";gateDeps;featureFlagProbe;toolSemantics;projectDir;constructor(t){this.gateDeps=t.gateDeps,this.featureFlagProbe=t.featureFlagProbe,this.toolSemantics=t.toolSemantics,this.projectDir=t.projectDir}async canActivate(t){if(t.artifactKind!=="rule")return{ok:!1,reason:"artifact_kind_not_rule",riskLevel:"high"};if(t.validationStatus!=="validated")return{ok:!1,reason:`artifact_validation_status_${t.validationStatus}`,riskLevel:"high"};let n=ett(t.contentJson);if(!n)return{ok:!1,reason:"content_json_parse_failed",riskLevel:"high"};if(Object.hasOwn(n,"requiresContextVersion")&&n.requiresContextVersion!==2)return{ok:!1,reason:"unsupported_context_version",riskLevel:"high"};if(n.requiresContextVersion===2&&!(this.featureFlagProbe?this.featureFlagProbe(m0n):!1))return{ok:!1,reason:"rulecode_context_v2_disabled",riskLevel:"high"};let r=h0n(n);if(!r)return{ok:!1,reason:"no_implementation_code",riskLevel:"high"};let i=g0n(n);if(!i.ok)return{ok:!1,reason:i.reason,riskLevel:"high"};let o=i.trace;if(A0n(n)!=="accepted_shadow")return{ok:!1,reason:"gate_decision_not_accepted_shadow",riskLevel:"high"};if(n.requiresContextVersion===2){let d=I0n(n,o);if(d)return{ok:!1,reason:d,riskLevel:"high"}}if(this.toolSemantics){let d=Array.isArray(n.affectedTools)?n.affectedTools.filter(m=>typeof m=="string"&&m.trim().length>0):[],p=Xfe({affectedTools:d,goldenTraceCaseToolNames:o.cases.map(m=>m.toolName),toolSemantics:this.toolSemantics});if(!p.valid&&p.failure){let{failure:m}=p;return{ok:!1,reason:`rule_reliability_${m.reasonCode}:${m.layer} \u2014 ${m.evidence} (nextAction=${m.nextAction})`,riskLevel:"high",failure:m}}}let a=lR({code:r,goldenTrace:o,...this.toolSemantics?{toolSemantics:this.toolSemantics}:{},...this.projectDir?{projectDir:this.projectDir}:{}},this.gateDeps);if(a.decision!=="accepted_shadow")return{ok:!1,reason:[`gate_decision_not_accepted_shadow:${a.decision}`,...a.reasons.slice(0,3)].join(" \u2014 "),riskLevel:"high",...a.failure?{failure:a.failure}:{}};let c=Array.isArray(n.affectedTools)?n.affectedTools.filter(d=>typeof d=="string"&&d.trim().length>0):[],l=new Set(["pd_status","rulecode_deactivate","rulecode_global_pause","owner_review_access"]);return c.length===0?{ok:!1,reason:"rulecode_scope_empty",riskLevel:"high"}:c.some(d=>d==="*"||d.toLowerCase()==="all")?{ok:!1,reason:"rulecode_scope_wildcard_forbidden",riskLevel:"high"}:c.some(d=>l.has(d))?{ok:!1,reason:"rulecode_scope_protected_capability",riskLevel:"high"}:{ok:!0,riskLevel:y0n(n)}}async activate(t,n){let r=typeof n.sourceRuleId=="string"&&n.sourceRuleId.trim().length>0?n.sourceRuleId.trim():t.principleId;return{activationId:`act_code_${r}`,action:"code_tool_hook_shadow_activate",targetRef:`impl://${r}`}}buildApprovalContext(t,n,r){let i=typeof n.sourceRuleId=="string"&&n.sourceRuleId.trim().length>0?n.sourceRuleId.trim():n.artifactId,o=ett(n.contentJson),s=o?.painReasonSummary,a=typeof s=="string"?s.trim():"",c=Array.isArray(o?.affectedTools)?o.affectedTools.filter(v=>typeof v=="string"):[],l=o?qV(o):null,u=`Rule activation request for code_tool_hook: ${i}`,d=a.length>0?a:"RuleHost candidate requires human approval before activation.",m=typeof r=="number"&&Number.isFinite(r)&&r>=0&&r<=1?`Confidence: ${Math.round(r*100)}%. Evaluated through shadow replay and sandbox gate.`:"Confidence score unavailable. Manual review recommended.",g=c.length>0?`This rule will intercept tool calls: ${c.join(", ")}. After approval, matching calls will be evaluated against the rule logic.`:"This candidate may affect code_tool_hook behavior after approval. Tool scope is not specified.",A=l&&l.length>0?` Evidence backing this rule: ${l.join(", ")}.`:"",_=`${g}${A}`;return{summary:u,triggerReason:d,confidenceExplanation:m,effectDescription:_,rejectionEffect:"The rule will not be activated. Current tool calls will continue unchanged."}}};var nme={maxRepairAttempts:0},v0n=new Set(["block","requireApproval"]);function ttt(e){try{return Object.keys(e)}catch{return null}}function HV(e,t){let n=[],r=ttt(e);if(!r)return n.push("cannot enumerate expected keys"),n;let i=ttt(t);if(!i)return n.push("cannot enumerate actual keys"),n;let o=new Set(r),s=new Set(i),a=new Set([...r,...i]);for(let c of a){let l=o.has(c);if(!s.has(c))n.push(`missing field "${c}"`);else if(!l)n.push(`unexpected field "${c}"`);else try{let d=JSON.stringify(e[c]),p=JSON.stringify(t[c]);d!==p&&n.push(`field "${c}": expected ${d}, got ${p}`)}catch{n.push(`field "${c}": comparison failed (possibly circular reference)`)}}return n}function w0n(e,t){let n=t.decision==="allow"||t.matched===!1;return{...e,passed:n,failureReason:n?void 0:`Expected allow but got ${t.decision}`,repairHint:n?void 0:"Rule incorrectly blocks or intervenes on benign input"}}function b0n(e,t){let n=v0n.has(t.decision);return{...e,passed:n,failureReason:n?void 0:`Expected block but got ${t.decision}`,repairHint:n?void 0:"Rule failed to block harmful input -- check condition matching"}}function C0n(e,t,n){if(t.decision!=="auto_correct")return{...e,passed:!1,failureReason:`Expected auto_correct (propose_correction) but got ${t.decision}`,repairHint:"Rule must return auto_correct decision with correctionProposal"};let r=t.correctionProposal;if(!r)return{...e,passed:!1,failureReason:"auto_correct decision missing correctionProposal",repairHint:"Return correctionProposal with proposedParams when decision is auto_correct"};let i={...e,passed:!0};if(n.expectedProposedParams){let o=HV(n.expectedProposedParams,r.proposedParams);i.proposedParamsMatch=o.length===0,i.proposedParamsDiff=o.length>0?o:void 0,o.length>0&&(i.passed=!1,i.failureReason=`proposedParams mismatch: ${o.join("; ")}`,i.repairHint="Ensure correctionProposal.proposedParams matches expected corrected params")}return n.expectedApplicationMode&&(i.applicationModeMatch=r.applicationMode===n.expectedApplicationMode,i.applicationModeMatch||(i.passed=!1,i.failureReason=(i.failureReason?i.failureReason+"; ":"")+`applicationMode mismatch: expected ${n.expectedApplicationMode}, got ${r.applicationMode}`,i.repairHint=(i.repairHint?i.repairHint+"; ":"")+"Set correctionProposal.applicationMode to match expected mode")),i}function S0n(e,t,n={}){let{projectDir:r,toolSemantics:i}=n,o=PB({toolName:t.toolName,params:t.params},t.ruleContext!==void 0?{context:t.ruleContext}:{},r||i?{...r?{projectDir:r}:{},...i?{toolSemantics:i}:{}}:{}),s={caseId:t.caseId,passed:!1,expectedDecision:t.expectedDecision,actualDecision:"error"},a=(()=>{let u={isRiskPath:()=>o.workspace.isRiskPath,getToolName:()=>o.action.toolName,getEstimatedLineChanges:()=>o.derived.estimatedLineChanges,getBashRisk:()=>o.derived.bashRisk,getEpTier:()=>o.evolution.epTier};try{return{ok:!0,value:e(o,u)}}catch(d){return{ok:!1,error:d.message}}})();if(!a.ok)return{...s,actualDecision:"error",failureReason:`evaluate() threw: ${a.error}`,repairHint:"Ensure evaluate() handles all input shapes without throwing"};let c=a.value,l={...s,actualDecision:c.decision};switch(t.expectedDecision){case"allow":return w0n(l,c);case"block":return b0n(l,c);case"propose_correction":return C0n(l,c,t);default:return{...s,failureReason:`Unknown expectedDecision: ${String(t.expectedDecision)}`}}}function jV(e,t,n){let r={...nme,...n};if(t.length===0)return{passed:!0,totalCases:0,passedCases:0,failedCases:0,perCaseResults:[],failureReasons:[],repairHints:[]};let i=t.map(l=>S0n(e,l,{...r.projectDir!==void 0?{projectDir:r.projectDir}:{},...r.toolSemantics!==void 0?{toolSemantics:r.toolSemantics}:{}})),o=i.filter(l=>l.passed).length,s=i.length-o,a=i.filter(l=>!l.passed&&l.failureReason).map(l=>`[${l.caseId}] ${l.failureReason??""}`),c=i.filter(l=>!l.passed&&l.repairHint).map(l=>l.repairHint??"");return r.maxRepairAttempts,{passed:s===0,totalCases:i.length,passedCases:o,failedCases:s,perCaseResults:i,failureReasons:a,repairHints:c}}var T0n=[{symbol:"recentThinking",pattern:/\brecentThinking\b/},{symbol:"planStatus",pattern:/\bplanStatus\b/},{symbol:"getPlanStatus",pattern:/\bgetPlanStatus\s*\(/},{symbol:"hasPlanFileHelper",pattern:/\bhasPlanFile\s*\(/},{symbol:"hasPlanFile",pattern:/\bhasPlanFile\b(?!\s*\()/}];function rme(e){let t="code",n=0,r="";for(let i=0;i<e.length;i+=1){let o=e[i]??"",s=e[i+1]??"";if(t==="code"){n>0&&o==="{"?(n+=1,r+=o):n>0&&o==="}"?(n-=1,r+=o,n===0&&(t="template")):o==="/"&&s==="/"?(r+=" ",i+=1,t="line_comment"):o==="/"&&s==="*"?(r+=" ",i+=1,t="block_comment"):o==="'"?(r+=" ",t="single_quote"):o==='"'?(r+=" ",t="double_quote"):o==="`"?(r+=" ",t="template"):r+=o;continue}if(t==="line_comment"){r+=o===`
1410
1410
  `||o==="\r"?o:" ",(o===`
1411
1411
  `||o==="\r")&&(t="code");continue}if(t==="block_comment"){o==="*"&&s==="/"?(r+=" ",i+=1,t="code"):r+=o===`
1412
1412
  `||o==="\r"?o:" ";continue}if(t==="template"&&o==="$"&&s==="{"){r+=" {",i+=1,n=1,t="code";continue}if(o==="\\"){r+=" ",i+1<e.length&&(r+=e[i+1]===`
@@ -1902,7 +1902,7 @@ globalThis.__pdRuleModule = {
1902
1902
  meta: typeof meta === 'undefined' ? undefined : meta,
1903
1903
  evaluate: typeof evaluate === 'undefined' ? undefined : evaluate,
1904
1904
  };`}function $Ln(e){return typeof e=="object"&&e!==null}function WLn(e,t){if(typeof e!="string"||e.trim().length===0)throw new Error(`[${t}] rule code is empty or not a string`);let n=L6.createContext(Object.create(null));new L6.Script(QLn(e),{filename:t}).runInContext(n,{timeout:1e3,displayErrors:!0});let i=Reflect.get(n,"__pdRuleModule");if(Reflect.deleteProperty(n,"__pdRuleModule"),!$Ln(i))throw new Error(`[${t}] compiled module export shape is invalid`);let o=i.evaluate;if(typeof o!="function")throw new Error(`[${t}] compiled module has no evaluate function`);return(s,a)=>{let c=Reflect.apply(o,void 0,[s,a]);if(!ULn(c)){let{errors:l}=Ff(c);throw new Error(`[${t}]: evaluate returned invalid RuleHostResult (${l.join("; ")}) \u2014 got ${typeof c=="object"&&c!==null?$f(c):String(c)}`)}return c}}function Qv(e={}){return{evaluateInSandbox:(t,n,r)=>{let i=Date.now(),o=nE(t);if(o.length>0)return{success:!1,failedCases:[],executionTimeMs:Date.now()-i,forbiddenPatternViolations:o};let s=dR(t);if(s.length>0)return{success:!1,failedCases:s.map(l=>({caseId:"__return_shape__",errorType:"validation_failed",message:l})),executionTimeMs:Date.now()-i,forbiddenPatternViolations:[]};let a=VV(t);if(a.length>0)return{success:!1,failedCases:a.map(l=>({caseId:"__matched_false_decision__",errorType:"validation_failed",message:l})),executionTimeMs:Date.now()-i,forbiddenPatternViolations:[]};let c;try{c=WLn(t,"production-gate-deps")}catch(l){return{success:!1,failedCases:[{caseId:"__compile__",errorType:"syntax_error",message:l instanceof Error?l.message:String(l)}],executionTimeMs:Date.now()-i,forbiddenPatternViolations:[]}}return XV(t,n,{evaluateCode:c,...r,toolSemantics:r?.toolSemantics??e.toolSemantics,projectDir:r?.projectDir??e.projectDir})}}}function mF(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function GLn(e){try{return JSON.parse(e)}catch{return null}}function eD(e){return e.filter(t=>t.channel==="prompt"&&t.action==="prompt_activate"&&t.deactivatedAt===null)}function tD(e,t){if(!mF(e))return{ok:!1,warning:`artifact_query_unexpected: artifactId=${t.artifactId}; nextAction=check_pi_artifacts_table`};let n=Object.hasOwn(e,"artifact_id")&&typeof e.artifact_id=="string"&&e.artifact_id.length>0?e.artifact_id:null,r=Object.hasOwn(e,"artifact_kind")&&typeof e.artifact_kind=="string"?e.artifact_kind:null,i=Object.hasOwn(e,"content_json")&&typeof e.content_json=="string"?e.content_json:null,o=Object.hasOwn(e,"validation_status")&&typeof e.validation_status=="string"?e.validation_status:null;if(!n)return{ok:!1,warning:`artifact_not_found: artifactId=${t.artifactId} activationId=${t.activationId}; nextAction=verify_artifact_exists_or_remove_stale_activation`};if(r!=="principle")return{ok:!1,warning:`artifact_not_principle: artifactId=${n} kind=${r??"missing"}; nextAction=skip_non_principle_activations`};if(o!=="validated")return{ok:!1,warning:`artifact_not_validated: artifactId=${n} status=${o??"missing"}; nextAction=skip_unvalidated_artifacts`};if(i===null)return{ok:!1,warning:`artifact_missing_content_json: artifactId=${n}; nextAction=ensure_artifact_has_content_json`};let s=GLn(i);if(s===null)return{ok:!1,warning:`artifact_content_json_parse_error: artifactId=${t.artifactId} reason=invalid_json; nextAction=fix_artifact_content_json`};if(!mF(s))return{ok:!1,warning:`artifact_content_malformed: artifactId=${t.artifactId} reason=parsed_to_non_object; nextAction=fix_artifact_content_json`};let a=Object.hasOwn(s,"principleId")&&typeof s.principleId=="string"?s.principleId:void 0,c=Object.hasOwn(s,"text")&&typeof s.text=="string"?s.text:void 0,l=Object.hasOwn(s,"principleDraft")&&mF(s.principleDraft)?s.principleDraft:null,u=l&&Object.hasOwn(l,"title")&&typeof l.title=="string"?l.title:void 0,d=l&&Object.hasOwn(l,"statement")&&typeof l.statement=="string"?l.statement:void 0,p=a&&a.length>0?a:u,m=c&&c.length>0?c:d;return!p||p.length===0?{ok:!1,warning:`artifact_missing_principle_id: artifactId=${t.artifactId}; nextAction=ensure_artifact_has_principleId_or_principleDraft_title`}:!m||m.length===0?{ok:!1,warning:`artifact_missing_text: artifactId=${t.artifactId} principleId=${p}; nextAction=ensure_artifact_has_text_or_principleDraft_statement`}:{ok:!0,principle:{principleId:p,text:m,artifactId:t.artifactId,activationId:t.activationId}}}function M6(e,t,n=r=>r){let r=[],i=new Set,o=t,s=!1,a="Runtime V2 activated principles:";r.push(a),o-=a.length;for(let c of e){let l=`- [${n(c.principleId)}] ${n(c.text)}`;if(o<l.length+1){s=!0;break}r.push(l),o-=l.length+1,i.add(c.principleId)}return{lines:r,injectedIds:i,truncated:s}}function nD(e,t,n){if(t.size===0)return"";let r=n?.escapeFn??(o=>o),i=[];i.push(""),i.push("## \u3010ACTIVE BEHAVIOR DIRECTIVES\u3011"),i.push(""),i.push('Active behavior directives are operating constraints learned from prior owner corrections. Each directive carries its authorization: authority="owner" (approved in the owner approval queue) or authority="system_policy" (auto-activated by low-risk policy).'),i.push("These directives are mandatory for this session unless they conflict with safety, security, or higher-priority system policy."),i.push("For ambiguous coding or file-changing tasks, follow these directives before using mutating tools."),i.push("");for(let o of e){if(!t.has(o.principleId))continue;let s=o.authority==="owner"||o.authority==="system_policy"?` authority="${o.authority}"`:"";i.push(`<directive id="${r(o.principleId)}" source="runtime_v2_activation"${s}>`),i.push(`MANDATORY: ${r(o.text)}`),i.push("Apply this as an active behavior constraint. Do not treat this as background context."),i.push("</directive>"),i.push("")}return n?.selfReportInstruction&&(i.push("Self-report (OWNER visibility): when a directive above actually changes what you do in this turn, append exactly ONE line at the end of your reply in this format:"),i.push("\u{1F4CC} \u5E94\u7528\u4E86\u4F60\u7684\u539F\u5219\u300C<directive id>\u300D\uFF1A<\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u4F60\u8FD9\u6B21\u505A\u6CD5\u6709\u4F55\u4E0D\u540C>"),i.push("Use the directive's exact id attribute. At most one line per directive per session. Omit the line entirely if no directive changed your behavior."),i.push("")),i.push("Note: These directives do not override safety, security, or core system policy."),i.join(`
1905
- `)}import Fuo from"better-sqlite3";import Huo from"better-sqlite3";import Xuo from"better-sqlite3";var _c;(function(e){e[e.Seed=1]="Seed",e[e.Sprout=2]="Sprout",e[e.Sapling=3]="Sapling",e[e.Tree=4]="Tree",e[e.Forest=5]="Forest"})(_c||(_c={}));var $pt=[{tier:_c.Seed,name:"Seed",requiredPoints:0,permissions:{maxLinesPerWrite:150,maxFilesPerTask:3,allowRiskPath:!1,allowSubagentSpawn:!0}},{tier:_c.Sprout,name:"Sprout",requiredPoints:50,permissions:{maxLinesPerWrite:300,maxFilesPerTask:5,allowRiskPath:!1,allowSubagentSpawn:!0}},{tier:_c.Sapling,name:"Sapling",requiredPoints:200,permissions:{maxLinesPerWrite:500,maxFilesPerTask:10,allowRiskPath:!0,allowSubagentSpawn:!0}},{tier:_c.Tree,name:"Tree",requiredPoints:500,permissions:{maxLinesPerWrite:1e3,maxFilesPerTask:20,allowRiskPath:!0,allowSubagentSpawn:!0}},{tier:_c.Forest,name:"Forest",requiredPoints:1e3,permissions:{maxLinesPerWrite:Number.MAX_SAFE_INTEGER,maxFilesPerTask:Number.MAX_SAFE_INTEGER,allowRiskPath:!0,allowSubagentSpawn:!0}}];var Wpt={doubleRewardCooldownMs:3600*1e3,maxRecentEvents:50,difficultyPenalty:{tier4Trivial:.1,tier4Normal:.5,tier5Trivial:.1,tier5Normal:.5}};function SE(e){if(!e||typeof e!="object")return!1;let t=e,n=["high","medium","low"];if(typeof t.confidence!="string"||!n.includes(t.confidence))return!1;let r=o=>Array.isArray(o)&&o.length>0&&o.every(s=>typeof s=="string"&&s.length>0),i=o=>Array.isArray(o)&&o.every(s=>Array.isArray(s)&&s.every(a=>typeof a=="string"));return r(t.applicabilityTags)&&r(t.positiveSignals)&&r(t.negativeSignals)&&i(t.toolSequenceHints)}var $v=f.Union([f.Literal(_c.Seed),f.Literal(_c.Sprout),f.Literal(_c.Sapling),f.Literal(_c.Tree),f.Literal(_c.Forest)]),tye=f.Object({maxLinesPerWrite:f.Number(),maxFilesPerTask:f.Number(),allowRiskPath:f.Boolean(),allowSubagentSpawn:f.Boolean()}),lMn=f.Object({tier:$v,name:f.String(),requiredPoints:f.Number(),permissions:tye}),Gpt=f.Union([f.Literal("trivial"),f.Literal("normal"),f.Literal("hard")]),uMn=f.Object({basePoints:f.Number(),description:f.String()}),qpt=f.Union([f.Literal("success"),f.Literal("failure")]),Hpt=f.Object({id:f.String(),timestamp:f.String(),type:qpt,taskHash:f.String(),taskDifficulty:Gpt,toolName:f.Optional(f.String()),filePath:f.Optional(f.String()),reason:f.Optional(f.String()),pointsAwarded:f.Number(),isDoubleReward:f.Boolean(),sessionId:f.Optional(f.String())}),jpt=f.Object({totalSuccesses:f.Number(),totalFailures:f.Number(),consecutiveSuccesses:f.Number(),consecutiveFailures:f.Number(),doubleRewardsEarned:f.Number(),tierPromotions:f.Number(),pointsByDifficulty:f.Object({trivial:f.Number(),normal:f.Number(),hard:f.Number()})}),Kpt=f.Tuple([f.String(),f.String()]),Vpt=f.Object({version:f.Literal("2.0"),agentId:f.String(),totalPoints:f.Number(),availablePoints:f.Number(),currentTier:$v,lastDoubleRewardTime:f.Optional(f.String()),recentFailureHashes:f.Array(Kpt),stats:jpt,recentEvents:f.Array(Hpt),lastUpdated:f.String()}),dMn=f.Object({scorecard:Vpt,archivedStats:f.Object({totalEventsProcessed:f.Number(),pointsFromTrivial:f.Number(),pointsFromNormal:f.Number(),pointsFromHard:f.Number()})}),pMn=f.Object({doubleRewardCooldownMs:f.Number(),maxRecentEvents:f.Number(),difficultyPenalty:f.Object({tier4Trivial:f.Number(),tier4Normal:f.Number(),tier5Trivial:f.Number(),tier5Normal:f.Number()})}),fMn=f.Object({totalEventsProcessed:f.Number(),pointsFromTrivial:f.Number(),pointsFromNormal:f.Number(),pointsFromHard:f.Number()}),mMn=f.Object({allowed:f.Boolean(),reason:f.Optional(f.String()),currentTier:f.Optional($v),requiredTier:f.Optional($v)}),hMn=f.Object({toolName:f.String(),filePath:f.Optional(f.String()),content:f.Optional(f.String()),lineCount:f.Optional(f.Number()),isRiskPath:f.Optional(f.Boolean())}),gMn=f.Object({previousTier:$v,newTier:$v,totalPoints:f.Number(),timestamp:f.String(),newPermissions:tye}),B6=f.Union([f.Literal("candidate"),f.Literal("probation"),f.Literal("active"),f.Literal("deprecated"),f.Literal("archived")]),nye=f.Union([f.Literal("deterministic"),f.Literal("weak_heuristic"),f.Literal("manual_only")]);var rye=f.Object({applicabilityTags:f.Array(f.String()),positiveSignals:f.Array(f.String()),negativeSignals:f.Array(f.String()),toolSequenceHints:f.Array(f.Array(f.String())),confidence:f.Union([f.Literal("high"),f.Literal("medium"),f.Literal("low")])}),Ypt=f.Object({name:f.String(),type:f.Union([f.Literal("hook"),f.Literal("gate"),f.Literal("skill"),f.Literal("test"),f.Literal("prompt")]),triggerCondition:f.String(),enforcement:f.Union([f.Literal("block"),f.Literal("warn"),f.Literal("log")]),action:f.String(),implementationHint:f.Optional(f.String())}),zpt=f.Object({painPreventedCount:f.Number(),lastPainPreventedAt:f.Optional(f.String()),calculatedAt:f.String()}),AMn=f.Object({id:f.String(),version:f.Number(),text:f.String(),source:f.Object({painId:f.String(),painType:f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")]),timestamp:f.String()}),trigger:f.String(),action:f.String(),guardrails:f.Optional(f.Array(f.String())),contextTags:f.Array(f.String()),validation:f.Object({successCount:f.Number(),conflictCount:f.Number()}),status:B6,feedbackScore:f.Number(),usageCount:f.Number(),createdAt:f.String(),activatedAt:f.Optional(f.String()),deprecatedAt:f.Optional(f.String()),evaluability:nye,detectorMetadata:f.Optional(rye),abstractedPrinciple:f.Optional(f.String()),coreAxiomId:f.Optional(f.String()),priority:f.Optional(f.Union([f.Literal("P0"),f.Literal("P1"),f.Literal("P2")])),scope:f.Optional(f.Union([f.Literal("general"),f.Literal("domain")])),domain:f.Optional(f.String()),suggestedRules:f.Optional(f.Array(Ypt)),valueMetrics:f.Optional(zpt)}),yMn=f.Union([f.Literal("pain_detected"),f.Literal("candidate_created"),f.Literal("principle_promoted"),f.Literal("principle_deprecated"),f.Literal("principle_rolled_back"),f.Literal("circuit_breaker_opened"),f.Literal("legacy_import")]),eye=f.Object({painId:f.String(),painType:f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")]),source:f.String(),reason:f.String(),score:f.Optional(f.Number()),sessionId:f.Optional(f.String()),agentId:f.Optional(f.String()),taskId:f.Optional(f.String()),traceId:f.Optional(f.String()),provenance:f.Optional(f.Union([f.Literal("host_context_bound"),f.Literal("owner_reported_no_host_trace"),f.Literal("automatic_hook"),f.Literal("openclaw_context_bound")])),hostKind:f.Optional(f.Union([f.Literal("openclaw"),f.Literal("codex")]))}),Jpt=f.Object({painId:f.String(),principleId:f.String(),trigger:f.String(),action:f.String(),status:f.Literal("candidate"),painType:f.Optional(f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")])),evaluability:f.Optional(nye),detectorMetadata:f.Optional(rye),abstractedPrinciple:f.Optional(f.String()),coreAxiomId:f.Optional(f.String())}),Xpt=f.Object({principleId:f.String(),from:B6,to:B6,reason:f.String(),successCount:f.Optional(f.Number())}),Zpt=f.Object({principleId:f.String(),reason:f.String(),triggeredBy:f.Union([f.Literal("auto"),f.Literal("manual")])}),eft=f.Object({principleId:f.String(),reason:f.String(),triggeredBy:f.Union([f.Literal("user_command"),f.Literal("auto_conflict")]),blacklistPattern:f.Optional(f.String()),relatedPainId:f.Optional(f.String())}),tft=f.Object({taskId:f.String(),painId:f.String(),failCount:f.Number(),reason:f.String(),requireHuman:f.Boolean(),nextRetryAt:f.Optional(f.String())}),nft=f.Object({sourceFile:f.String(),content:f.String(),contentHash:f.Optional(f.String())}),IMn=f.Union([f.Object({ts:f.String(),type:f.Literal("pain_detected"),data:eye}),f.Object({ts:f.String(),type:f.Literal("pain_recorded"),data:eye}),f.Object({ts:f.String(),type:f.Literal("candidate_created"),data:Jpt}),f.Object({ts:f.String(),type:f.Literal("principle_promoted"),data:Xpt}),f.Object({ts:f.String(),type:f.Literal("principle_deprecated"),data:Zpt}),f.Object({ts:f.String(),type:f.Literal("principle_rolled_back"),data:eft}),f.Object({ts:f.String(),type:f.Literal("circuit_breaker_opened"),data:tft}),f.Object({ts:f.String(),type:f.Literal("legacy_import"),data:nft})]);var F6=200,rD=[{term:"\u4E0D\u662F\u8FD9\u4E2A",weight:.6,source:"seed",addedAt:""},{term:"\u4E0D\u5BF9",weight:.5,source:"seed",addedAt:""},{term:"\u9519\u4E86",weight:.5,source:"seed",addedAt:""},{term:"\u641E\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u7406\u89E3\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u4F60\u7406\u89E3\u9519\u4E86",weight:.8,source:"seed",addedAt:""},{term:"\u91CD\u65B0\u6765",weight:.6,source:"seed",addedAt:""},{term:"\u518D\u8BD5\u4E00\u6B21",weight:.4,source:"seed",addedAt:""},{term:"you are wrong",weight:.7,source:"seed",addedAt:""},{term:"wrong file",weight:.6,source:"seed",addedAt:""},{term:"not this",weight:.4,source:"seed",addedAt:""},{term:"redo",weight:.6,source:"seed",addedAt:""},{term:"try again",weight:.4,source:"seed",addedAt:""},{term:"again",weight:.3,source:"seed",addedAt:""},{term:"please redo",weight:.6,source:"seed",addedAt:""},{term:"please try again",weight:.5,source:"seed",addedAt:""}],rft=f.Object({term:f.String(),weight:f.Number(),source:f.Union([f.Literal("seed"),f.Literal("llm"),f.Literal("user")]),addedAt:f.String(),hitCount:f.Optional(f.Number({minimum:0})),truePositiveCount:f.Optional(f.Number({minimum:0})),falsePositiveCount:f.Optional(f.Number({minimum:0})),lastHitAt:f.Optional(f.String())}),EMn=f.Object({keywords:f.Array(rft),version:f.Integer({minimum:0}),lastOptimizedAt:f.String()}),_Mn=f.Object({matched:f.Boolean(),matchedTerms:f.Array(f.String()),score:f.Number({minimum:0,maximum:1}),confidence:f.Number({minimum:0,maximum:1})});var hF=class{registry=new Map;register(t){this.registry.set(t.agentId,t)}async dispatch(t,n){let r=this.registry.get(t);if(!r)throw new Error(`Agent ${t} is not registered in AgentScheduler`);return r.runner.run(n)}getRegisteredAgents(){return Array.from(this.registry.values()).map(t=>({agentId:t.agentId,mode:t.mode}))}};function TE(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Th(e){return typeof e=="string"}function U6(e){return typeof e=="boolean"}function Gf(e){return typeof e=="number"&&Number.isFinite(e)}function or(e,t){return{path:e,message:t}}function Xn(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var QMn=new Set(["info","warning","error","fatal"]);function $Mn(e,t){let n=[];return Xn(e,"gate")!==void 0&&n.push(or(`${t}.gate`,"deprecated: the built-in PLAN/confirm-first gate was removed (PRI-286); this key has no effect and can be deleted")),(Xn(e,"progressive_gate")!==void 0||Xn(e,"progressiveGate")!==void 0)&&n.push(or(`${t}.progressive_gate`,"deprecated: plan-approval gating was removed (PRI-286); this key has no effect and can be deleted")),Xn(e,"progressiveGate")!==void 0&&n.push(or(`${t}.progressiveGate`,"deprecated: plan-approval gating was removed (PRI-286); legacy camelCase alias, this key has no effect and can be deleted")),(Xn(e,"thinking_checkpoint")!==void 0||Xn(e,"thinkingCheckpoint")!==void 0)&&n.push(or(`${t}.thinking_checkpoint`,"deprecated: the thinking-checkpoint gate is retired; this key has no effect and can be deleted")),Xn(e,"thinkingCheckpoint")!==void 0&&n.push(or(`${t}.thinkingCheckpoint`,"deprecated: the thinking-checkpoint gate is retired; legacy camelCase alias, this key has no effect and can be deleted")),n}function WMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`tests must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"on_change");i!==void 0&&(Th(i)&&Nb.includes(i)?r.on_change=i:n.push(or(`${t}.on_change`,`must be one of: ${Nb.join(", ")}`)));let o=Xn(e,"on_risk_change");o!==void 0&&(Th(o)&&Nb.includes(o)?r.on_risk_change=o:n.push(or(`${t}.on_risk_change`,`must be one of: ${Nb.join(", ")}`)));let s=Xn(e,"commands");if(s!==void 0)if(TE(s)){let a={};for(let c of Object.keys(s)){let l=s[c];Th(l)?a[c]=l:n.push(or(`${t}.commands.${c}`,"command value must be a string"))}r.commands=a}else n.push(or(`${t}.commands`,"must be an object (string\u2192string map)"));return{value:r,warnings:n}}function GMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`adaptive must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"spiral_boost");o!==void 0&&(Gf(o)?r.spiral_boost=o:n.push(or(`${t}.spiral_boost`,"must be a finite number")));let s=Xn(e,"min_threshold");s!==void 0&&(Gf(s)?r.min_threshold=s:n.push(or(`${t}.min_threshold`,"must be a finite number")));let a=Xn(e,"max_threshold");a!==void 0&&(Gf(a)?r.max_threshold=a:n.push(or(`${t}.max_threshold`,"must be a finite number")));let c=Xn(e,"backlog_trigger");c!==void 0&&(Gf(c)?r.backlog_trigger=c:n.push(or(`${t}.backlog_trigger`,"must be a finite number")));let l=Xn(e,"hard_failure_trigger");l!==void 0&&(Gf(l)?r.hard_failure_trigger=l:n.push(or(`${t}.hard_failure_trigger`,"must be a finite number")));let u=Xn(e,"low_recent_success_boost");u!==void 0&&(Gf(u)?r.low_recent_success_boost=u:n.push(or(`${t}.low_recent_success_boost`,"must be a finite number")));let d=Xn(e,"high_recent_pain_boost");return d!==void 0&&(Gf(d)?r.high_recent_pain_boost=d:n.push(or(`${t}.high_recent_pain_boost`,"must be a finite number"))),{value:r,warnings:n}}function qMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`pain must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"soft_capture_threshold");i!==void 0&&(Gf(i)?r.soft_capture_threshold=i:n.push(or(`${t}.soft_capture_threshold`,"must be a finite number")));let o=Xn(e,"adaptive");if(o!==void 0){let s=GMn(o,`${t}.adaptive`);s.value&&(r.adaptive=s.value),n.push(...s.warnings)}return{value:r,warnings:n}}function HMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`lifecycle must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"heartbeat_stale_hours");return o!==void 0&&(Gf(o)?r.heartbeat_stale_hours=o:n.push(or(`${t}.heartbeat_stale_hours`,"must be a finite number"))),{value:r,warnings:n}}function jMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`edit_verification must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"max_file_size_bytes");o!==void 0&&(Gf(o)&&o>=0?r.max_file_size_bytes=o:n.push(or(`${t}.max_file_size_bytes`,"must be a non-negative number")));let s=Xn(e,"fuzzy_match_enabled");s!==void 0&&(U6(s)?r.fuzzy_match_enabled=s:n.push(or(`${t}.fuzzy_match_enabled`,"must be boolean")));let a=Xn(e,"fuzzy_match_threshold");a!==void 0&&(Gf(a)&&a>0&&a<=1?r.fuzzy_match_threshold=a:n.push(or(`${t}.fuzzy_match_threshold`,"must be a number in (0, 1]")));let c=Xn(e,"skip_large_file_action");return c!==void 0&&(c==="warn"||c==="block"?r.skip_large_file_action=c:n.push(or(`${t}.skip_large_file_action`,'must be "warn" or "block"'))),{value:r,warnings:n}}function KMn(e,t){let n=[];if(!Array.isArray(e))return n.push(or(t,`custom_guards must be an array, got ${typeof e}`)),{warnings:n};let r=[];for(let i=0;i<e.length;i++){let o=e[i];if(!TE(o)){n.push(or(`${t}[${i}]`,"must be an object"));continue}let s=Xn(o,"pattern"),a=Xn(o,"message"),c=Xn(o,"severity");if(!Th(s)||s.length===0){n.push(or(`${t}[${i}].pattern`,"must be a non-empty string"));continue}r.push({pattern:s,message:Th(a)?a:"Custom guard triggered",severity:Th(c)&&QMn.has(c.toLowerCase())?c.toLowerCase():"error"})}return{value:r,warnings:n}}function iye(e,t="profile"){let n=[];if(!TE(e))return{ok:!1,errors:[or(t,`profile must be an object, got ${typeof e}`)]};let r={},i=Xn(e,"audit_level");i!==void 0&&(Th(i)&&P2.includes(i)?r.audit_level=i:n.push(or(`${t}.audit_level`,`must be one of: ${P2.join(", ")}, got ${JSON.stringify(i)}`)));let o=Xn(e,"evolution_mode");o!==void 0&&(Th(o)&&L2.includes(o)?r.evolution_mode=o:n.push(or(`${t}.evolution_mode`,`must be one of: ${L2.join(", ")}, got ${JSON.stringify(o)}`)));let s=Xn(e,"risk_paths");s!==void 0&&(Array.isArray(s)?r.risk_paths=s.filter(Th):Th(s)?r.risk_paths=[s]:n.push(or(`${t}.risk_paths`,"must be an array of strings or a single string"))),n.push(...$Mn(e,t));let a=Xn(e,"tests");if(a!==void 0){let p=WMn(a,`${t}.tests`);p.value&&(r.tests=p.value),n.push(...p.warnings)}let c=Xn(e,"pain");if(c!==void 0){let p=qMn(c,`${t}.pain`);p.value&&(r.pain=p.value),n.push(...p.warnings)}let l=Xn(e,"lifecycle");if(l!==void 0){let p=HMn(l,`${t}.lifecycle`);p.value&&(r.lifecycle=p.value),n.push(...p.warnings)}let u=Xn(e,"edit_verification");if(u!==void 0){let p=jMn(u,`${t}.edit_verification`);p.value&&(r.edit_verification=p.value),n.push(...p.warnings)}let d=Xn(e,"custom_guards");if(d!==void 0){let p=KMn(d,`${t}.custom_guards`);p.value&&(r.custom_guards=p.value),n.push(...p.warnings)}return{ok:!0,value:r,warnings:n}}function Zl(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ps(e){return typeof e=="string"}function gF(e){return typeof e=="boolean"}function Xc(e){return typeof e=="number"&&Number.isFinite(e)}function nt(e,t,n){return{path:e,reason:t,nextAction:n}}function Zn(e,t){if(!ys.has(t))return Object.hasOwn(e,t)?e[t]:void 0}function qa(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t==="string"){let n=e;return n.length>50?`"${n.slice(0,50)}\u2026"`:`"${n}"`}return t==="number"||t==="boolean"?String(e):Array.isArray(e)?`array(${e.length})`:t==="object"?"object":t}function VMn(e,t,n){let r=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`feature '${n}' must be an object, got ${typeof e}`,`Fix feature '${n}' to be an object with category and enabled fields`)]};let i=Zn(e,"category");i===void 0?r.push(nt(`${t}.category`,`feature '${n}' missing required field 'category'`,`Add 'category' to feature '${n}' (one of: ${C_.join(", ")})`)):(!ps(i)||!C_.includes(i))&&r.push(nt(`${t}.category`,`feature '${n}' category must be one of: ${C_.join(", ")}, got ${qa(i)}`,`Change category of feature '${n}' to one of: ${C_.join(", ")}`));let o=Zn(e,"enabled");o===void 0?r.push(nt(`${t}.enabled`,`feature '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to feature '${n}'`)):gF(o)||r.push(nt(`${t}.enabled`,`feature '${n}' enabled must be boolean, got ${typeof o}`,`Change enabled of feature '${n}' to true or false`));let s=Zn(e,"source");return s!==void 0&&(typeof s!="string"||!VO.includes(s))&&r.push(nt(`${t}.source`,`feature '${n}' source must be one of: ${VO.join(", ")}, got ${qa(s)}`,`Set source to one of: ${VO.join(", ")}, or remove it (legacy override)`)),r.length>0?{ok:!1,errors:r}:{ok:!0,value:{category:i,enabled:o,...s!==void 0&&typeof s=="string"&&VO.includes(s)?{source:s}:{}}}}function YMn(e,t,n){let r=[],i=Zn(e,"provider");i!==void 0&&!ps(i)&&r.push(nt(`${t}.provider`,`profile '${n}' provider must be a string, got ${typeof i}`,`Fix provider in profile '${n}'`));let o=Zn(e,"model");o!==void 0&&!ps(o)&&r.push(nt(`${t}.model`,`profile '${n}' model must be a string, got ${typeof o}`,`Fix model in profile '${n}'`));let s=Zn(e,"source");s!==void 0&&!ps(s)&&r.push(nt(`${t}.source`,`profile '${n}' source must be a string, got ${typeof s}`,`Fix source in profile '${n}'`));let a=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let l of a)Object.hasOwn(e,l)&&r.push(nt(`${t}.${l}`,`profile '${n}' contains forbidden secret field '${l}'`,`Remove '${l}' from profile '${n}' \u2014 PD does not store provider credentials (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let c={type:"openclaw"};return ps(i)&&(c.provider=i),ps(o)&&(c.model=o),ps(s)&&(c.source=s),{ok:!0,value:c}}function zMn(e,t,n){let r=[],i=Zn(e,"provider");i===void 0?r.push(nt(`${t}.provider`,`profile '${n}' missing required field 'provider'`,`Add 'provider' to profile '${n}' (e.g. "anthropic", "openai")`)):ps(i)||r.push(nt(`${t}.provider`,`profile '${n}' provider must be a string, got ${qa(i)}`,`Fix provider in profile '${n}'`));let o=Zn(e,"model");o===void 0?r.push(nt(`${t}.model`,`profile '${n}' missing required field 'model'`,`Add 'model' to profile '${n}' (e.g. "claude-3-5-sonnet")`)):ps(o)||r.push(nt(`${t}.model`,`profile '${n}' model must be a string, got ${qa(o)}`,`Fix model in profile '${n}'`));let s=Zn(e,"apiKeyEnv");s===void 0?r.push(nt(`${t}.apiKeyEnv`,`profile '${n}' missing required field 'apiKeyEnv'`,`Add 'apiKeyEnv' to profile '${n}' (e.g. "ANTHROPIC_API_KEY")`)):ps(s)||r.push(nt(`${t}.apiKeyEnv`,`profile '${n}' apiKeyEnv must be a string (env var name), got ${qa(s)}`,`Fix apiKeyEnv in profile '${n}' to be an environment variable name`));let a=Zn(e,"baseUrl");a!==void 0&&!ps(a)&&r.push(nt(`${t}.baseUrl`,`profile '${n}' baseUrl must be a string, got ${typeof a}`,`Fix baseUrl in profile '${n}'`));let c=Zn(e,"timeoutMs");c!==void 0&&!Xc(c)&&r.push(nt(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be a finite number, got ${qa(c)}`,`Fix timeoutMs in profile '${n}'`)),Xc(c)&&c<=0&&r.push(nt(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be positive, got ${c}`,`Set timeoutMs in profile '${n}' to a positive number`));let l=Zn(e,"maxRetries");l!==void 0&&!Xc(l)&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be a finite number, got ${qa(l)}`,`Fix maxRetries in profile '${n}'`)),Xc(l)&&l<0&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be non-negative, got ${l}`,`Set maxRetries in profile '${n}' to a non-negative integer`)),Xc(l)&&!Number.isInteger(l)&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be an integer, got ${l}`,`Set maxRetries in profile '${n}' to a non-negative integer`));let u=Zn(e,"maxTokens");u!==void 0&&!Xc(u)&&r.push(nt(`${t}.maxTokens`,`profile '${n}' maxTokens must be a finite number, got ${qa(u)}`,`Fix maxTokens in profile '${n}'`)),Xc(u)&&u<=0&&r.push(nt(`${t}.maxTokens`,`profile '${n}' maxTokens must be positive, got ${u}`,`Set maxTokens in profile '${n}' to a positive number`));let d=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let m of d)Object.hasOwn(e,m)&&r.push(nt(`${t}.${m}`,`profile '${n}' contains forbidden secret field '${m}'`,`Remove '${m}' from profile '${n}' \u2014 use 'apiKeyEnv' for env var name reference (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let p={type:"pi-ai",provider:i,model:o,apiKeyEnv:s};return ps(a)&&(p.baseUrl=a),Xc(c)&&(p.timeoutMs=c),Xc(l)&&(p.maxRetries=l),Xc(u)&&(p.maxTokens=u),{ok:!0,value:p}}function JMn(e,t,n){if(!Zl(e))return{ok:!1,errors:[nt(t,`profile '${n}' must be an object, got ${typeof e}`,`Fix profile '${n}' to be an object with type, provider, model fields`)]};for(let i of ys)if(Object.hasOwn(e,i))return{ok:!1,errors:[nt(`${t}.${i}`,`profile '${n}' contains dangerous key '${i}'`,`Remove '${i}' from profile '${n}'`)]};let r=Zn(e,"type");return r===void 0?{ok:!1,errors:[nt(`${t}.type`,`profile '${n}' missing required field 'type'`,`Add 'type' to profile '${n}' (one of: ${Ob.join(", ")})`)]}:!ps(r)||!Ob.includes(r)?{ok:!1,errors:[nt(`${t}.type`,`profile '${n}' type must be one of: ${Ob.join(", ")}, got ${qa(r)}`,`Fix type in profile '${n}'`)]}:r==="openclaw"?YMn(e,t,n):zMn(e,t,n)}function XMn(e,t,n){let r=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`agent '${n}' must be an object, got ${typeof e}`,`Fix agent '${n}' to be an object with enabled and optional runtimeProfile fields`)]};let i=Zn(e,"enabled");i===void 0?r.push(nt(`${t}.enabled`,`agent '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to agent '${n}'`)):gF(i)||r.push(nt(`${t}.enabled`,`agent '${n}' enabled must be boolean, got ${typeof i}`,`Change enabled of agent '${n}' to true or false`));let o=Zn(e,"runtimeProfile");if(o!==void 0&&!ps(o)&&r.push(nt(`${t}.runtimeProfile`,`agent '${n}' runtimeProfile must be a string, got ${typeof o}`,`Fix runtimeProfile of agent '${n}' to a profile ID`)),r.length>0)return{ok:!1,errors:r};let s={enabled:i};return ps(o)&&(s.runtimeProfile=o),{ok:!0,value:s}}function ZMn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`internalAgents must be an object, got ${typeof e}`,"Fix internalAgents to be an object with defaultRuntime and agents")]};let r=Zn(e,"defaultRuntime");r===void 0?n.push(nt(`${t}.defaultRuntime`,"missing required field defaultRuntime","Add defaultRuntime with a runtime profile ID")):(!ps(r)||r.length===0)&&n.push(nt(`${t}.defaultRuntime`,`defaultRuntime must be a non-empty string, got ${qa(r)}`,"Fix defaultRuntime to a valid runtime profile ID"));let i=Zn(e,"agents"),o={};if(i===void 0)n.push(nt(`${t}.agents`,"missing required field agents",`Add agents section with per-agent bindings: ${Rc.join(", ")}`));else if(!Zl(i))n.push(nt(`${t}.agents`,`agents must be an object, got ${typeof i}`,"Fix agents to be an object mapping agent names to bindings"));else{for(let a of Rc){let c=Zn(i,a);if(c===void 0)continue;let l=XMn(c,`${t}.agents.${a}`,a);l.ok?o[a]=l.value:n.push(...l.errors)}for(let a of Object.keys(i))ys.has(a)||Rc.includes(a)||n.push(nt(`${t}.agents.${a}`,`unknown agent key '${a}'`,`Remove unknown agent '${a}' or use a known agent name: ${Rc.join(", ")}`))}let s=new Set(["defaultRuntime","agents"]);for(let a of Object.keys(e))ys.has(a)||s.has(a)||n.push(nt(`${t}.${a}`,`unknown key '${a}' in internalAgents`,`Remove unknown key '${a}' from internalAgents`));return n.length>0?{ok:!1,errors:n}:{ok:!0,value:{defaultRuntime:r,agents:o}}}function eBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`ui must be an object, got ${typeof e}`,"Fix ui to be an object with diagnostics settings")]};let r=Zn(e,"diagnostics");if(!Zl(r))return{ok:!1,errors:[nt(`${t}.diagnostics`,`ui.diagnostics must be an object, got ${typeof r}`,"Fix ui.diagnostics to be an object with mode field")]};let i=Zn(r,"mode");return i===void 0?n.push(nt(`${t}.diagnostics.mode`,"missing required field mode",`Add mode to ui.diagnostics (one of: ${S_.join(", ")})`)):(!ps(i)||!S_.includes(i))&&n.push(nt(`${t}.diagnostics.mode`,`mode must be one of: ${S_.join(", ")}, got ${qa(i)}`,`Fix mode to one of: ${S_.join(", ")}`)),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{diagnostics:{mode:i}}}}function tBn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function nBn(e){return YO.some(t=>t===e)}function rBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`workspace must be an object, got ${typeof e}`,"Fix workspace to be an object with a default field")]};for(let a of ys)if(Object.hasOwn(e,a))return{ok:!1,errors:[nt(`${t}.${a}`,`workspace contains dangerous key '${a}'`,`Remove '${a}' from workspace`)]};let r=Zn(e,"default");r===void 0?n.push(nt(`${t}.default`,"workspace missing required field default","Add default path to workspace section (must be an absolute path)")):!ps(r)||r.length===0?n.push(nt(`${t}.default`,`workspace.default must be a non-empty string, got ${qa(r)}`,"Set workspace.default to an absolute directory path")):tBn(r)||n.push(nt(`${t}.default`,`workspace.default must be an absolute path, got "${r}"`,'Use an absolute path like "D:\\.openclaw\\workspace" or "/home/user/.openclaw/workspace"'));let i=Zn(e,"environment"),o;i!==void 0&&(ps(i)&&nBn(i)?o=i:n.push(nt(`${t}.environment`,`workspace.environment must be one of ${YO.join("|")}, got ${qa(i)}`,`Set workspace.environment to one of ${YO.join(", ")}, or remove the key to leave the environment unknown`)));let s=new Set(["default","environment"]);for(let a of Object.keys(e))ys.has(a)||s.has(a)||n.push(nt(`${t}.${a}`,`unknown key '${a}' in workspace`,`Remove unknown key '${a}' from workspace`));return n.length>0?{ok:!1,errors:n}:!ps(r)||r.length===0?{ok:!1,errors:[nt(`${t}.default`,"workspace.default validation invariant failed","Re-validate the workspace section; this error indicates a validator bug \u2014 please report it")]}:{ok:!0,value:{default:r,...o!==void 0?{environment:o}:{}}}}function iBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,"evolutionContext must be an object","Fix evolutionContext to be an object with enabled, maxMessages, maxCharsPerMessage")]};let r=Zn(e,"enabled");r!==void 0&&!gF(r)&&n.push(nt(`${t}.enabled`,"evolutionContext.enabled must be a boolean","Set evolutionContext.enabled to true or false"));let i=Zn(e,"maxMessages");i!==void 0&&(!Xc(i)||!Number.isInteger(i)||i<0)&&n.push(nt(`${t}.maxMessages`,"evolutionContext.maxMessages must be a non-negative integer","Set evolutionContext.maxMessages to a non-negative integer"));let o=Zn(e,"maxCharsPerMessage");return o!==void 0&&(!Xc(o)||!Number.isInteger(o)||o<0)&&n.push(nt(`${t}.maxCharsPerMessage`,"evolutionContext.maxCharsPerMessage must be a non-negative integer","Set evolutionContext.maxCharsPerMessage to a non-negative integer")),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{enabled:gF(r)?r:!0,maxMessages:Xc(i)?i:4,maxCharsPerMessage:Xc(o)?o:200}}}function oBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,"contextInjection must be an object","Fix contextInjection to be an object with optional thinkingOs, projectFocus, evolutionContext fields")]};for(let c of ys)if(Object.hasOwn(e,c))return{ok:!1,errors:[nt(`${t}.${c}`,`contextInjection contains dangerous key '${c}'`,`Remove '${c}' from contextInjection`)]};let r={},i=Zn(e,"thinkingOs");i!==void 0&&(gF(i)?r.thinkingOs=i:n.push(nt(`${t}.thinkingOs`,"contextInjection.thinkingOs must be a boolean","Set contextInjection.thinkingOs to true or false")));let o=Zn(e,"projectFocus");o!==void 0&&(!ps(o)||!zO.includes(o)?n.push(nt(`${t}.projectFocus`,`contextInjection.projectFocus must be one of: ${zO.join(", ")}, got ${qa(o)}`,`Set contextInjection.projectFocus to one of: ${zO.join(", ")}`)):r.projectFocus=o);let s=Zn(e,"evolutionContext");if(s!==void 0){let c=iBn(s,`${t}.evolutionContext`);c.ok?r.evolutionContext=c.value:n.push(...c.errors)}let a=new Set(["thinkingOs","projectFocus","evolutionContext"]);for(let c of Object.keys(e))ys.has(c)||a.has(c)||n.push(nt(`${t}.${c}`,`unknown key '${c}' in contextInjection`,`Remove unknown key '${c}' from contextInjection`));return n.length>0?{ok:!1,errors:n}:{ok:!0,value:r}}function Q6(e){let t=[];if(e==null)return{ok:!1,errors:[nt("","config is null or undefined","Provide a valid .pd/config.yaml file or use defaults")]};if(!Zl(e))return{ok:!1,errors:[nt("",`config root must be an object, got ${typeof e}`,"Fix .pd/config.yaml to be a YAML object")]};for(let T of ys)Object.hasOwn(e,T)&&t.push(nt(T,`root contains dangerous key '${T}'`,`Remove '${T}' from config root`));let n=Zn(e,"version");n===void 0?t.push(nt("version","missing required field version",`Add version: ${1} to config`)):(!Xc(n)||n!==1)&&t.push(nt("version",`version must be ${1}, got ${qa(n)}`,`Set version to ${1}`));let r=Zn(e,"workspace"),i;if(r!==void 0){let T=rBn(r,"workspace");T.ok?i=T.value:t.push(...T.errors)}let o=Zn(e,"features"),s={};if(o===void 0)t.push(nt("features","missing required field features","Add features section with prompt, code_tool_hook, defer_archive entries"));else if(!Zl(o))t.push(nt("features",`features must be an object, got ${typeof o}`,"Fix features to be an object mapping flag names to {category, enabled}"));else for(let T of Object.keys(o)){if(ys.has(T)){t.push(nt(`features.${T}`,`dangerous key '${T}' rejected`,`Remove '${T}' from features`));continue}let D=VMn(o[T],`features.${T}`,T);D.ok?s[T]=D.value:t.push(...D.errors)}let a=Zn(e,"runtimeProfiles"),c={};if(a===void 0)t.push(nt("runtimeProfiles","missing required field runtimeProfiles","Add runtimeProfiles section with at least one profile"));else if(!Zl(a))t.push(nt("runtimeProfiles",`runtimeProfiles must be an object, got ${typeof a}`,"Fix runtimeProfiles to be an object mapping profile IDs to profile definitions"));else for(let T of Object.keys(a)){if(ys.has(T)){t.push(nt(`runtimeProfiles.${T}`,`dangerous key '${T}' rejected`,`Remove '${T}' from runtimeProfiles`));continue}let D=JMn(a[T],`runtimeProfiles.${T}`,T);D.ok?c[T]=D.value:t.push(...D.errors)}let l=Zn(e,"internalAgents"),u;if(l===void 0)t.push(nt("internalAgents","missing required field internalAgents","Add internalAgents section with defaultRuntime"));else{let T=ZMn(l,"internalAgents");T.ok?u=T.value:t.push(...T.errors)}let d=Zn(e,"ui"),p;if(d!==void 0){let T=eBn(d,"ui");T.ok?p=T.value:t.push(...T.errors)}let m=Zn(e,"profile"),g;if(m!==void 0){let T=iye(m);if(T.ok)g=T.value;else for(let D of T.errors)t.push(nt(D.path,D.message,"Fix profile section in .pd/config.yaml"))}let A=Zn(e,"contextInjection"),_;if(A!==void 0){let T=oBn(A,"contextInjection");T.ok?_=T.value:t.push(...T.errors)}let x=Zn(e,"principles"),v;if(x!==void 0)if(!Zl(x))t.push(nt("principles",`principles must be an object, got ${qa(x)}`,"Set principles to a mapping (e.g. principles: { outputLanguage: zh-CN })"));else{let T=Object.hasOwn(x,"outputLanguage")?x.outputLanguage:void 0;T===void 0?v={}:R2(T)?v={outputLanguage:T}:t.push(nt("principles.outputLanguage",`outputLanguage must be one of ${w_.join(", ")}, got ${qa(T)}`,`Set principles.outputLanguage to one of: ${w_.join(", ")}`))}return t.length>0?{ok:!1,errors:t}:u?{ok:!0,value:{version:1,...i?{workspace:i}:{},features:s,runtimeProfiles:c,internalAgents:u,ui:p??{diagnostics:{mode:"simple"}},...v?{principles:v}:{},...g?{profile:g}:{},..._?{contextInjection:_}:{}}}:{ok:!1,errors:[nt("internalAgents","internalAgents validation unexpectedly failed","Check internalAgents configuration")]}}var sBn={on_change:"smoke",on_risk_change:"unit",commands:{}},hft={enabled:!0,spiral_boost:20,min_threshold:15,max_threshold:70,backlog_trigger:6,hard_failure_trigger:1,low_recent_success_boost:15,high_recent_pain_boost:10},aBn={soft_capture_threshold:30,adaptive:{...hft}},cBn={enabled:!0,heartbeat_stale_hours:72},lBn={enabled:!0,max_file_size_bytes:10*1024*1024,fuzzy_match_enabled:!0,fuzzy_match_threshold:.8,skip_large_file_action:"warn"};var Xi={audit_level:"medium",risk_paths:[],evolution_mode:"realtime",tests:{...sBn},pain:{soft_capture_threshold:aBn.soft_capture_threshold,adaptive:{...hft}},lifecycle:{...cBn},edit_verification:{...lBn},custom_guards:[]};function $6(e){return e?{audit_level:e.audit_level??Xi.audit_level,risk_paths:e.risk_paths??Xi.risk_paths,evolution_mode:e.evolution_mode??Xi.evolution_mode,tests:{on_change:e.tests?.on_change??Xi.tests.on_change,on_risk_change:e.tests?.on_risk_change??Xi.tests.on_risk_change,commands:{...Xi.tests.commands,...e.tests?.commands??{}}},pain:{soft_capture_threshold:e.pain?.soft_capture_threshold??Xi.pain.soft_capture_threshold,adaptive:{enabled:e.pain?.adaptive?.enabled??Xi.pain.adaptive.enabled,spiral_boost:e.pain?.adaptive?.spiral_boost??Xi.pain.adaptive.spiral_boost,min_threshold:e.pain?.adaptive?.min_threshold??Xi.pain.adaptive.min_threshold,max_threshold:e.pain?.adaptive?.max_threshold??Xi.pain.adaptive.max_threshold,backlog_trigger:e.pain?.adaptive?.backlog_trigger??Xi.pain.adaptive.backlog_trigger,hard_failure_trigger:e.pain?.adaptive?.hard_failure_trigger??Xi.pain.adaptive.hard_failure_trigger,low_recent_success_boost:e.pain?.adaptive?.low_recent_success_boost??Xi.pain.adaptive.low_recent_success_boost,high_recent_pain_boost:e.pain?.adaptive?.high_recent_pain_boost??Xi.pain.adaptive.high_recent_pain_boost}},lifecycle:{enabled:e.lifecycle?.enabled??Xi.lifecycle.enabled,heartbeat_stale_hours:e.lifecycle?.heartbeat_stale_hours??Xi.lifecycle.heartbeat_stale_hours},edit_verification:{enabled:e.edit_verification?.enabled??Xi.edit_verification.enabled,max_file_size_bytes:e.edit_verification?.max_file_size_bytes??Xi.edit_verification.max_file_size_bytes,fuzzy_match_enabled:e.edit_verification?.fuzzy_match_enabled??Xi.edit_verification.fuzzy_match_enabled,fuzzy_match_threshold:e.edit_verification?.fuzzy_match_threshold??Xi.edit_verification.fuzzy_match_threshold,skip_large_file_action:e.edit_verification?.skip_large_file_action??Xi.edit_verification.skip_large_file_action},custom_guards:e.custom_guards??Xi.custom_guards}:{...Xi}}function gft(e){return e?{thinkingOs:e.thinkingOs??yl.thinkingOs,projectFocus:e.projectFocus??yl.projectFocus,evolutionContext:{enabled:e.evolutionContext?.enabled??yl.evolutionContext.enabled,maxMessages:e.evolutionContext?.maxMessages??yl.evolutionContext.maxMessages,maxCharsPerMessage:e.evolutionContext?.maxCharsPerMessage??yl.evolutionContext.maxCharsPerMessage}}:{...yl}}function kE(e){if(e==null)return{config:U2(),source:"defaults",warnings:[],featuresChangedFromDefault:[],resolvedProfile:$6({}),resolvedContextInjection:gft(void 0)};let t=[],n=[],{normalized:r,warnings:i}=M2(e.features);t.push(...i);let o={};for(let[_,x]of Object.entries(ly))if(Object.hasOwn(r,_)){let v=r[_];if(!v){o[_]={...x};continue}if(x.category==="gone"&&v.enabled){o[_]={...x},t.push(`feature '${_}': gone flag cannot be re-enabled`),n.push(_);continue}if(x.category==="core"&&!v.enabled){o[_]={category:v.category,enabled:!1,...v.source?{source:v.source}:{}},t.push(`feature '${_}': core flag explicitly disabled via config (emergency disable)`),n.push(_);continue}(v.category!==x.category||v.enabled!==x.enabled)&&n.push(_),o[_]={category:v.category,enabled:v.enabled,...v.source?{source:v.source}:{}}}else o[_]={...x};for(let _ of Object.keys(r))ys.has(_)||Object.hasOwn(o,_)||t.push(`feature '${_}': unknown flag ignored (not a registered capability)`);let s={};for(let[_,x]of Object.entries(e.runtimeProfiles))ys.has(_)||(s[_]={...x});Object.hasOwn(s,cy)||(s[cy]={...F2},t.push(`runtime profile '${cy}' not found in config, using default`));let a=JO(),c={};for(let _ of Rc){let x=e.internalAgents.agents[_],v=a.agents[_];x!==void 0?c[_]={enabled:x.enabled,runtimeProfile:x.runtimeProfile??e.internalAgents.defaultRuntime}:c[_]={enabled:v.enabled,runtimeProfile:e.internalAgents.defaultRuntime}}for(let _ of Rc){let x=c[_];x&&x.enabled&&x.runtimeProfile&&!Object.hasOwn(s,x.runtimeProfile)&&t.push(`agent '${_}': runtime profile '${x.runtimeProfile}' not found in runtimeProfiles`)}let l=r.diagnostician_split_pipeline;if(l!==void 0&&l.enabled===!1&&c.diagnostician?.enabled===!0){c.diagnostician={enabled:!1,runtimeProfile:e.internalAgents.defaultRuntime};let _=l.source??"unknown";t.push(`PRI-638 cutover: legacy diagnostician_split_pipeline=false (source: ${_}) honored as internalAgents.agents.diagnostician.enabled=false to avoid silently enabling a previously-disabled LLM pipeline. Recovery: toggle Diagnostician ON in Console \u2192 Control Center (the writer retires the conflicting legacy override), or edit .pd/config.yaml to remove the legacy diagnostician_split_pipeline flag. A standalone internalAgents.agents.diagnostician.enabled=true is NOT sufficient while the legacy override remains false.`)}let u={defaultRuntime:e.internalAgents.defaultRuntime,agents:c},d=e.ui??{...XO},p=e.principles??{outputLanguage:void 0},m=$6(e.profile??{}),g=gft(e.contextInjection);return{config:{version:1,...e.workspace?{workspace:e.workspace}:{},features:o,runtimeProfiles:s,internalAgents:u,ui:d,principles:p,...e.profile?{profile:e.profile}:{},...e.contextInjection?{contextInjection:e.contextInjection}:{}},source:"user_config",warnings:t,featuresChangedFromDefault:n,resolvedProfile:m,resolvedContextInjection:g}}var fBn=new Set(["owner_reported","agent_on_owner_request","tool_failure","dispatch_error","provider_failure","rate_limit","rulehost_block","empathy_inferred","semantic","llm_paralysis","subagent_error","gfi_threshold","unknown"]);function W6(e){return typeof e=="string"&&fBn.has(e)}var oye=new Map([["owner_reported",{kind:"owner_reported",defaultDecision:"admit",reason:"Owner explicitly reported pain. Highest confidence signal.",nextAction:"none",canUpgrade:!1}],["agent_on_owner_request",{kind:"agent_on_owner_request",defaultDecision:"admit",reason:"Agent recorded pain at owner request. Owner intent preserved.",nextAction:"none",canUpgrade:!1}],["tool_failure",{kind:"tool_failure",defaultDecision:"evidence_only",reason:"Tool failure is infrastructure noise. PD does not own tool repair (ADR-0014).",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["dispatch_error",{kind:"dispatch_error",defaultDecision:"evidence_only",reason:"Dispatch/subagent routing error. Not a behavior pattern.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["provider_failure",{kind:"provider_failure",defaultDecision:"health_only",reason:"LLM provider failure. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry",canUpgrade:!1}],["rate_limit",{kind:"rate_limit",defaultDecision:"health_only",reason:"LLM provider rate limit. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry",canUpgrade:!1}],["rulehost_block",{kind:"rulehost_block",defaultDecision:"evidence_only",reason:"RuleHost block is near-miss evidence. Default evidence-only.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!0}],["empathy_inferred",{kind:"empathy_inferred",defaultDecision:"owner_confirm",reason:"Empathy-inferred frustration. Never silently creates diagnosis (PRODUCT_IDENTITY: owner-governed).",nextAction:"request_owner_confirmation_before_diagnosis",canUpgrade:!1}],["semantic",{kind:"semantic",defaultDecision:"evidence_only",reason:"Keyword/detection match. Not explicit owner pain. Needs accumulation.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["llm_paralysis",{kind:"llm_paralysis",defaultDecision:"evidence_only",reason:"Session health signal. GFI alone cannot create diagnosis.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["subagent_error",{kind:"subagent_error",defaultDecision:"evidence_only",reason:"Subagent workflow failure. Not a behavior pattern by itself.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["gfi_threshold",{kind:"gfi_threshold",defaultDecision:"evidence_only",reason:"Accumulated GFI. GFI alone cannot create diagnosis per acceptance criteria.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["unknown",{kind:"unknown",defaultDecision:"evidence_only",reason:"Unclassified source. Conservative default.",nextAction:"classify_source_kind_and_store_as_evidence",canUpgrade:!1}]]);function iD(e){return oye.get(e)}var AF=70,yF=4;function mBn(e,t){return t!=="evidence_only"?t:e.sourceKind==="rulehost_block"&&e.isUnsafeHighConfidence===!0||e.isRisky===!0&&e.score>=AF||e.consecutiveErrors!==void 0&&e.consecutiveErrors>=yF?"admit":t}function hBn(e,t,n){return t!=="admit"?`Upgraded decision for ${e}: ${t}`:e==="rulehost_block"&&n.isUnsafeHighConfidence===!0?`RuleHost blocked a high-confidence unsafe action (score=${n.score}). Upgrading to direct diagnosis.`:n.isRisky===!0&&n.score>=AF?"Risky high-score operation overrides evidence-only decision. Immediate diagnosis required.":n.consecutiveErrors!==void 0&&n.consecutiveErrors>=yF?"Repeated failures override evidence-only decision. Pattern suggests systemic issue requiring diagnosis.":`Upgraded decision for ${e}: ${t}`}function gBn(e,t,n){return t!=="admit"||e==="rulehost_block"&&n.isUnsafeHighConfidence===!0?"none":n.isRisky===!0&&n.score>=AF||n.consecutiveErrors!==void 0&&n.consecutiveErrors>=yF?"create_diagnostic_task":"none"}function Wv(e){let t=W6(e.sourceKind)?e.sourceKind:"unknown",n=iD(t);if(!n)return{decision:"evidence_only",sourceKind:"unknown",reason:`Source kind '${t}' not found in descriptor registry. Conservative default.`,nextAction:"classify_source_kind_and_store_as_evidence"};if(n.canUpgrade||e.isRisky!==void 0||e.consecutiveErrors!==void 0){let i=mBn(e,n.defaultDecision);if(i!==n.defaultDecision)return{decision:i,sourceKind:t,reason:hBn(t,i,e),nextAction:gBn(t,i,e)}}return{decision:n.defaultDecision,sourceKind:t,reason:n.reason,nextAction:n.nextAction}}function rd(e){let{isManualEntry:t,isGateBlock:n,isSubagentError:r,isRateLimit:i,toolName:o,failureSource:s,isGfiTriggered:a,detectionSource:c,nonZeroExit:l,timedOut:u,toolNotFound:d}=e;if(t)return"owner_reported";if(n)return"rulehost_block";if(r)return"subagent_error";if(i===!0)return"rate_limit";if(i===!1)return"provider_failure";if(o==="pain"||o==="skill:pain")return e.provenance==="host_context_bound"?"agent_on_owner_request":"owner_reported";if(a)return"gfi_threshold";if(s)return s==="dispatch_error"?"dispatch_error":"tool_failure";if(d||(o!==void 0||l||u||d)&&(!o||o.trim()===""))return"dispatch_error";if(l||u)return"tool_failure";if(c){if(c==="llm_paralysis")return"llm_paralysis";if(c.startsWith("llm_"))return"semantic";if(c==="user_empathy")return"empathy_inferred"}return"unknown"}function ABn(e){if(!e)return"tool_failure";let t=String(e);return/\btool\s+(?:\S+\s+)?not\s+found\b/i.test(t)||/\bunknown\s+tool\b/i.test(t)?"dispatch_error":"tool_failure"}function bA(e){let{toolName:t,error:n,provenance:r}=e,i=typeof e.exitCode=="number"&&e.exitCode!==0,o;return!t||t.trim()===""?o="dispatch_error":o=ABn(n),!n&&!i&&(o=void 0),{observedAt:new Date().toISOString(),toolName:t,failureSource:o,nonZeroExit:i,provenance:r}}function IF(e){return{observedAt:new Date().toISOString(),isManualEntry:!0,sessionId:e.sessionId}}function Aft(e,t){let n=[];return e&&n.push(`canUpgrade=${e.canUpgrade}`),n.push(`score=${t.score}`),t.sessionId&&n.push(`session=${t.sessionId.slice(0,8)}`),n.join(", ")}function yBn(e){return{outcome:"refused",reason:e.validationError??"Input validation failed. Evidence is malformed or incomplete.",nextAction:"fix_input_and_retry_or_classify_as_unknown",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!1,decidedAt:new Date().toISOString(),operatorNote:`validationError=${e.validationError??"unknown"}`}}function IBn(e){return{outcome:"manual_owner_admitted",reason:"Owner explicit manual pain. Bypasses triage and cooldown. Highest confidence signal.",nextAction:"create_diagnostic_task",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!0,decidedAt:new Date().toISOString(),operatorNote:`score=${e.score}, sessionId=${e.sessionId??"unknown"}`}}function EBn(e){let{triageResult:t}=e,n=iD(t.sourceKind),r=new Date().toISOString();switch(t.decision){case"admit":return e.isCooldownActive&&!e.cooldownBypassAllowed?{outcome:"cooldown_skipped",reason:`Admitted by triage but cooldown is active for source '${t.sourceKind}'. Cooldown prevents diagnosis to avoid duplicate tasks.`,nextAction:"wait_for_cooldown_or_manual_retrigger",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`cooldown_active=true, score=${e.score}`}:{outcome:"diagnosis_created",reason:t.reason,nextAction:t.nextAction==="none"?"proceed_with_diagnostic_task":t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!0,decidedAt:r,operatorNote:Aft(n,e)};case"evidence_only":return{outcome:"evidence_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:Aft(n,e)};case"health_only":return{outcome:"health_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`provider_signal, score=${e.score}`};case"owner_confirm":return{outcome:"owner_confirm_required",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`requires_confirmation, score=${e.score}`};case"reject":return{outcome:"refused",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`rejected, score=${e.score}`};default:{let i=t.decision;return{outcome:"refused",reason:`Unhandled triage decision: ${String(t.decision)}. Conservative refusal.`,nextAction:"investigate_unknown_triage_decision",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r}}}}function id(e){return e.isValid?e.isOwnerManual?IBn(e):EBn(e):yBn(e)}var EF=class{cache;maxSize;constructor(t=100){this.cache=new Map,this.maxSize=t}get(t){let n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(t,n)}},oD=class{cache;asyncQueue=[];match;hash;shouldIgnoreProtocol;queueCapacity;constructor(t){this.match=t.match,this.hash=t.hash,this.shouldIgnoreProtocol=t.shouldIgnoreProtocol,this.cache=new EF(t.cacheSize??100),this.queueCapacity=t.queueCapacity??1e3}detect(t){if(this.shouldIgnoreProtocol(t))return{detected:!1,source:"l1_exact"};let n=this.match(t);if(n)return{detected:!0,severity:n.severity,ruleId:n.ruleId,source:"l1_exact"};let r=this.hash(t),i=this.cache.get(r);return i?{detected:i.detected,severity:i.severity,source:"l2_cache"}:(this.enqueueAsync(t),{detected:!1,source:"l3_async_queued"})}enqueueAsync(t){this.asyncQueue.length<this.queueCapacity&&this.asyncQueue.push(t)}updateCache(t,n){let r=this.hash(t);this.cache.set(r,n)}flushQueue(){let t=[...this.asyncQueue];return this.asyncQueue=[],t}};var Ift=[{key:"why",headerRegex:/^##\s+1\.\s*Why\s*$/im,label:"why",header:"## 1. Why"},{key:"desiredOutcome",headerRegex:/^##\s+2\.\s*Desired Outcome\s*$/im,label:"desiredOutcome",header:"## 2. Desired Outcome"},{key:"nonNegotiables",headerRegex:/^##\s+3\.\s*Non-negotiables\s*$/im,label:"nonNegotiables",header:"## 3. Non-negotiables"},{key:"stopEscalation",headerRegex:/^##\s+4\.\s*Stop\s*\/\s*Escalation\s*$/im,label:"stopEscalation",header:"## 4. Stop / Escalation"},{key:"currentStrategicFocus",headerRegex:/^##\s+5\.\s*Current Strategic Focus\s*$/im,label:"currentStrategicFocus",header:"## 5. Current Strategic Focus"}];function G6(e){let t={};for(let n of Ift){let r=n.headerRegex.exec(e);if(r===null)continue;let i=e.slice(r.index+r[0].length),o=/^##\s+/m.exec(i);t[n.key]=i.slice(0,o!==null?o.index:i.length).trim()}return t}function aye(e){let t=[];for(let n of Ift){let i=Object.hasOwn(e,n.key)?e[n.key]:void 0;if(i===void 0){t.push({code:"missing_section",message:`Section "${n.label}" is missing from INTENT.md.`,section:n.label});continue}if(typeof i!="string"){t.push({code:"parse_failed",message:`Section "${n.label}" has a non-string value.`,section:n.label});continue}if(i.trim().length===0){t.push({code:"empty_section",message:`Section "${n.label}" is empty.`,section:n.label});continue}i.length<10&&t.push({code:"too_vague",message:`Section "${n.label}" is too short.`,section:n.label})}return t}function qf(e){return`INTENT.${e}.md`}import{createHash as UBn}from"node:crypto";function q6(e){return`sha256:${UBn("sha256").update(e,"utf8").digest("hex")}`}function eu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var cye=4e3,lye=`
1905
+ `)}import Fuo from"better-sqlite3";import Huo from"better-sqlite3";import Xuo from"better-sqlite3";var _c;(function(e){e[e.Seed=1]="Seed",e[e.Sprout=2]="Sprout",e[e.Sapling=3]="Sapling",e[e.Tree=4]="Tree",e[e.Forest=5]="Forest"})(_c||(_c={}));var $pt=[{tier:_c.Seed,name:"Seed",requiredPoints:0,permissions:{maxLinesPerWrite:150,maxFilesPerTask:3,allowRiskPath:!1,allowSubagentSpawn:!0}},{tier:_c.Sprout,name:"Sprout",requiredPoints:50,permissions:{maxLinesPerWrite:300,maxFilesPerTask:5,allowRiskPath:!1,allowSubagentSpawn:!0}},{tier:_c.Sapling,name:"Sapling",requiredPoints:200,permissions:{maxLinesPerWrite:500,maxFilesPerTask:10,allowRiskPath:!0,allowSubagentSpawn:!0}},{tier:_c.Tree,name:"Tree",requiredPoints:500,permissions:{maxLinesPerWrite:1e3,maxFilesPerTask:20,allowRiskPath:!0,allowSubagentSpawn:!0}},{tier:_c.Forest,name:"Forest",requiredPoints:1e3,permissions:{maxLinesPerWrite:Number.MAX_SAFE_INTEGER,maxFilesPerTask:Number.MAX_SAFE_INTEGER,allowRiskPath:!0,allowSubagentSpawn:!0}}];var Wpt={doubleRewardCooldownMs:3600*1e3,maxRecentEvents:50,difficultyPenalty:{tier4Trivial:.1,tier4Normal:.5,tier5Trivial:.1,tier5Normal:.5}};function SE(e){if(!e||typeof e!="object")return!1;let t=e,n=["high","medium","low"];if(typeof t.confidence!="string"||!n.includes(t.confidence))return!1;let r=o=>Array.isArray(o)&&o.length>0&&o.every(s=>typeof s=="string"&&s.length>0),i=o=>Array.isArray(o)&&o.every(s=>Array.isArray(s)&&s.every(a=>typeof a=="string"));return r(t.applicabilityTags)&&r(t.positiveSignals)&&r(t.negativeSignals)&&i(t.toolSequenceHints)}var $v=f.Union([f.Literal(_c.Seed),f.Literal(_c.Sprout),f.Literal(_c.Sapling),f.Literal(_c.Tree),f.Literal(_c.Forest)]),tye=f.Object({maxLinesPerWrite:f.Number(),maxFilesPerTask:f.Number(),allowRiskPath:f.Boolean(),allowSubagentSpawn:f.Boolean()}),lMn=f.Object({tier:$v,name:f.String(),requiredPoints:f.Number(),permissions:tye}),Gpt=f.Union([f.Literal("trivial"),f.Literal("normal"),f.Literal("hard")]),uMn=f.Object({basePoints:f.Number(),description:f.String()}),qpt=f.Union([f.Literal("success"),f.Literal("failure")]),Hpt=f.Object({id:f.String(),timestamp:f.String(),type:qpt,taskHash:f.String(),taskDifficulty:Gpt,toolName:f.Optional(f.String()),filePath:f.Optional(f.String()),reason:f.Optional(f.String()),pointsAwarded:f.Number(),isDoubleReward:f.Boolean(),sessionId:f.Optional(f.String())}),jpt=f.Object({totalSuccesses:f.Number(),totalFailures:f.Number(),consecutiveSuccesses:f.Number(),consecutiveFailures:f.Number(),doubleRewardsEarned:f.Number(),tierPromotions:f.Number(),pointsByDifficulty:f.Object({trivial:f.Number(),normal:f.Number(),hard:f.Number()})}),Kpt=f.Tuple([f.String(),f.String()]),Vpt=f.Object({version:f.Literal("2.0"),agentId:f.String(),totalPoints:f.Number(),availablePoints:f.Number(),currentTier:$v,lastDoubleRewardTime:f.Optional(f.String()),recentFailureHashes:f.Array(Kpt),stats:jpt,recentEvents:f.Array(Hpt),lastUpdated:f.String()}),dMn=f.Object({scorecard:Vpt,archivedStats:f.Object({totalEventsProcessed:f.Number(),pointsFromTrivial:f.Number(),pointsFromNormal:f.Number(),pointsFromHard:f.Number()})}),pMn=f.Object({doubleRewardCooldownMs:f.Number(),maxRecentEvents:f.Number(),difficultyPenalty:f.Object({tier4Trivial:f.Number(),tier4Normal:f.Number(),tier5Trivial:f.Number(),tier5Normal:f.Number()})}),fMn=f.Object({totalEventsProcessed:f.Number(),pointsFromTrivial:f.Number(),pointsFromNormal:f.Number(),pointsFromHard:f.Number()}),mMn=f.Object({allowed:f.Boolean(),reason:f.Optional(f.String()),currentTier:f.Optional($v),requiredTier:f.Optional($v)}),hMn=f.Object({toolName:f.String(),filePath:f.Optional(f.String()),content:f.Optional(f.String()),lineCount:f.Optional(f.Number()),isRiskPath:f.Optional(f.Boolean())}),gMn=f.Object({previousTier:$v,newTier:$v,totalPoints:f.Number(),timestamp:f.String(),newPermissions:tye}),B6=f.Union([f.Literal("candidate"),f.Literal("probation"),f.Literal("active"),f.Literal("deprecated"),f.Literal("archived")]),nye=f.Union([f.Literal("deterministic"),f.Literal("weak_heuristic"),f.Literal("manual_only")]);var rye=f.Object({applicabilityTags:f.Array(f.String()),positiveSignals:f.Array(f.String()),negativeSignals:f.Array(f.String()),toolSequenceHints:f.Array(f.Array(f.String())),confidence:f.Union([f.Literal("high"),f.Literal("medium"),f.Literal("low")])}),Ypt=f.Object({name:f.String(),type:f.Union([f.Literal("hook"),f.Literal("gate"),f.Literal("skill"),f.Literal("test"),f.Literal("prompt")]),triggerCondition:f.String(),enforcement:f.Union([f.Literal("block"),f.Literal("warn"),f.Literal("log")]),action:f.String(),implementationHint:f.Optional(f.String())}),zpt=f.Object({painPreventedCount:f.Number(),lastPainPreventedAt:f.Optional(f.String()),calculatedAt:f.String()}),AMn=f.Object({id:f.String(),version:f.Number(),text:f.String(),source:f.Object({painId:f.String(),painType:f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")]),timestamp:f.String()}),trigger:f.String(),action:f.String(),guardrails:f.Optional(f.Array(f.String())),contextTags:f.Array(f.String()),validation:f.Object({successCount:f.Number(),conflictCount:f.Number()}),status:B6,feedbackScore:f.Number(),usageCount:f.Number(),createdAt:f.String(),activatedAt:f.Optional(f.String()),deprecatedAt:f.Optional(f.String()),evaluability:nye,detectorMetadata:f.Optional(rye),abstractedPrinciple:f.Optional(f.String()),coreAxiomId:f.Optional(f.String()),priority:f.Optional(f.Union([f.Literal("P0"),f.Literal("P1"),f.Literal("P2")])),scope:f.Optional(f.Union([f.Literal("general"),f.Literal("domain")])),domain:f.Optional(f.String()),suggestedRules:f.Optional(f.Array(Ypt)),valueMetrics:f.Optional(zpt)}),yMn=f.Union([f.Literal("pain_detected"),f.Literal("candidate_created"),f.Literal("principle_promoted"),f.Literal("principle_deprecated"),f.Literal("principle_rolled_back"),f.Literal("circuit_breaker_opened"),f.Literal("legacy_import")]),eye=f.Object({painId:f.String(),painType:f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")]),source:f.String(),reason:f.String(),score:f.Optional(f.Number()),sessionId:f.Optional(f.String()),agentId:f.Optional(f.String()),taskId:f.Optional(f.String()),traceId:f.Optional(f.String()),provenance:f.Optional(f.Union([f.Literal("host_context_bound"),f.Literal("owner_reported_no_host_trace"),f.Literal("automatic_hook"),f.Literal("openclaw_context_bound")])),hostKind:f.Optional(f.Union([f.Literal("openclaw"),f.Literal("codex")]))}),Jpt=f.Object({painId:f.String(),principleId:f.String(),trigger:f.String(),action:f.String(),status:f.Literal("candidate"),painType:f.Optional(f.Union([f.Literal("tool_failure"),f.Literal("dispatch_error"),f.Literal("subagent_error"),f.Literal("user_frustration")])),evaluability:f.Optional(nye),detectorMetadata:f.Optional(rye),abstractedPrinciple:f.Optional(f.String()),coreAxiomId:f.Optional(f.String())}),Xpt=f.Object({principleId:f.String(),from:B6,to:B6,reason:f.String(),successCount:f.Optional(f.Number())}),Zpt=f.Object({principleId:f.String(),reason:f.String(),triggeredBy:f.Union([f.Literal("auto"),f.Literal("manual")])}),eft=f.Object({principleId:f.String(),reason:f.String(),triggeredBy:f.Union([f.Literal("user_command"),f.Literal("auto_conflict")]),blacklistPattern:f.Optional(f.String()),relatedPainId:f.Optional(f.String())}),tft=f.Object({taskId:f.String(),painId:f.String(),failCount:f.Number(),reason:f.String(),requireHuman:f.Boolean(),nextRetryAt:f.Optional(f.String())}),nft=f.Object({sourceFile:f.String(),content:f.String(),contentHash:f.Optional(f.String())}),IMn=f.Union([f.Object({ts:f.String(),type:f.Literal("pain_detected"),data:eye}),f.Object({ts:f.String(),type:f.Literal("pain_recorded"),data:eye}),f.Object({ts:f.String(),type:f.Literal("candidate_created"),data:Jpt}),f.Object({ts:f.String(),type:f.Literal("principle_promoted"),data:Xpt}),f.Object({ts:f.String(),type:f.Literal("principle_deprecated"),data:Zpt}),f.Object({ts:f.String(),type:f.Literal("principle_rolled_back"),data:eft}),f.Object({ts:f.String(),type:f.Literal("circuit_breaker_opened"),data:tft}),f.Object({ts:f.String(),type:f.Literal("legacy_import"),data:nft})]);var F6=200,rD=[{term:"\u4E0D\u662F\u8FD9\u4E2A",weight:.6,source:"seed",addedAt:""},{term:"\u4E0D\u5BF9",weight:.5,source:"seed",addedAt:""},{term:"\u9519\u4E86",weight:.5,source:"seed",addedAt:""},{term:"\u641E\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u7406\u89E3\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u4F60\u7406\u89E3\u9519\u4E86",weight:.8,source:"seed",addedAt:""},{term:"\u91CD\u65B0\u6765",weight:.6,source:"seed",addedAt:""},{term:"\u518D\u8BD5\u4E00\u6B21",weight:.4,source:"seed",addedAt:""},{term:"you are wrong",weight:.7,source:"seed",addedAt:""},{term:"wrong file",weight:.6,source:"seed",addedAt:""},{term:"not this",weight:.4,source:"seed",addedAt:""},{term:"redo",weight:.6,source:"seed",addedAt:""},{term:"try again",weight:.4,source:"seed",addedAt:""},{term:"again",weight:.3,source:"seed",addedAt:""},{term:"please redo",weight:.6,source:"seed",addedAt:""},{term:"please try again",weight:.5,source:"seed",addedAt:""}],rft=f.Object({term:f.String(),weight:f.Number(),source:f.Union([f.Literal("seed"),f.Literal("llm"),f.Literal("user")]),addedAt:f.String(),hitCount:f.Optional(f.Number({minimum:0})),truePositiveCount:f.Optional(f.Number({minimum:0})),falsePositiveCount:f.Optional(f.Number({minimum:0})),lastHitAt:f.Optional(f.String())}),EMn=f.Object({keywords:f.Array(rft),version:f.Integer({minimum:0}),lastOptimizedAt:f.String()}),_Mn=f.Object({matched:f.Boolean(),matchedTerms:f.Array(f.String()),score:f.Number({minimum:0,maximum:1}),confidence:f.Number({minimum:0,maximum:1})});var hF=class{registry=new Map;register(t){this.registry.set(t.agentId,t)}async dispatch(t,n){let r=this.registry.get(t);if(!r)throw new Error(`Agent ${t} is not registered in AgentScheduler`);return r.runner.run(n)}getRegisteredAgents(){return Array.from(this.registry.values()).map(t=>({agentId:t.agentId,mode:t.mode}))}};function TE(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Th(e){return typeof e=="string"}function U6(e){return typeof e=="boolean"}function Gf(e){return typeof e=="number"&&Number.isFinite(e)}function or(e,t){return{path:e,message:t}}function Xn(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var QMn=new Set(["info","warning","error","fatal"]);function $Mn(e,t){let n=[];return Xn(e,"gate")!==void 0&&n.push(or(`${t}.gate`,"deprecated: the built-in PLAN/confirm-first gate was removed (PRI-286); this key has no effect and can be deleted")),(Xn(e,"progressive_gate")!==void 0||Xn(e,"progressiveGate")!==void 0)&&n.push(or(`${t}.progressive_gate`,"deprecated: plan-approval gating was removed (PRI-286); this key has no effect and can be deleted")),Xn(e,"progressiveGate")!==void 0&&n.push(or(`${t}.progressiveGate`,"deprecated: plan-approval gating was removed (PRI-286); legacy camelCase alias, this key has no effect and can be deleted")),(Xn(e,"thinking_checkpoint")!==void 0||Xn(e,"thinkingCheckpoint")!==void 0)&&n.push(or(`${t}.thinking_checkpoint`,"deprecated: the thinking-checkpoint gate is retired; this key has no effect and can be deleted")),Xn(e,"thinkingCheckpoint")!==void 0&&n.push(or(`${t}.thinkingCheckpoint`,"deprecated: the thinking-checkpoint gate is retired; legacy camelCase alias, this key has no effect and can be deleted")),n}function WMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`tests must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"on_change");i!==void 0&&(Th(i)&&Nb.includes(i)?r.on_change=i:n.push(or(`${t}.on_change`,`must be one of: ${Nb.join(", ")}`)));let o=Xn(e,"on_risk_change");o!==void 0&&(Th(o)&&Nb.includes(o)?r.on_risk_change=o:n.push(or(`${t}.on_risk_change`,`must be one of: ${Nb.join(", ")}`)));let s=Xn(e,"commands");if(s!==void 0)if(TE(s)){let a={};for(let c of Object.keys(s)){let l=s[c];Th(l)?a[c]=l:n.push(or(`${t}.commands.${c}`,"command value must be a string"))}r.commands=a}else n.push(or(`${t}.commands`,"must be an object (string\u2192string map)"));return{value:r,warnings:n}}function GMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`adaptive must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"spiral_boost");o!==void 0&&(Gf(o)?r.spiral_boost=o:n.push(or(`${t}.spiral_boost`,"must be a finite number")));let s=Xn(e,"min_threshold");s!==void 0&&(Gf(s)?r.min_threshold=s:n.push(or(`${t}.min_threshold`,"must be a finite number")));let a=Xn(e,"max_threshold");a!==void 0&&(Gf(a)?r.max_threshold=a:n.push(or(`${t}.max_threshold`,"must be a finite number")));let c=Xn(e,"backlog_trigger");c!==void 0&&(Gf(c)?r.backlog_trigger=c:n.push(or(`${t}.backlog_trigger`,"must be a finite number")));let l=Xn(e,"hard_failure_trigger");l!==void 0&&(Gf(l)?r.hard_failure_trigger=l:n.push(or(`${t}.hard_failure_trigger`,"must be a finite number")));let u=Xn(e,"low_recent_success_boost");u!==void 0&&(Gf(u)?r.low_recent_success_boost=u:n.push(or(`${t}.low_recent_success_boost`,"must be a finite number")));let d=Xn(e,"high_recent_pain_boost");return d!==void 0&&(Gf(d)?r.high_recent_pain_boost=d:n.push(or(`${t}.high_recent_pain_boost`,"must be a finite number"))),{value:r,warnings:n}}function qMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`pain must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"soft_capture_threshold");i!==void 0&&(Gf(i)?r.soft_capture_threshold=i:n.push(or(`${t}.soft_capture_threshold`,"must be a finite number")));let o=Xn(e,"adaptive");if(o!==void 0){let s=GMn(o,`${t}.adaptive`);s.value&&(r.adaptive=s.value),n.push(...s.warnings)}return{value:r,warnings:n}}function HMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`lifecycle must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"heartbeat_stale_hours");return o!==void 0&&(Gf(o)?r.heartbeat_stale_hours=o:n.push(or(`${t}.heartbeat_stale_hours`,"must be a finite number"))),{value:r,warnings:n}}function jMn(e,t){let n=[];if(!TE(e))return n.push(or(t,`edit_verification must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Xn(e,"enabled");i!==void 0&&(U6(i)?r.enabled=i:n.push(or(`${t}.enabled`,"must be boolean")));let o=Xn(e,"max_file_size_bytes");o!==void 0&&(Gf(o)&&o>=0?r.max_file_size_bytes=o:n.push(or(`${t}.max_file_size_bytes`,"must be a non-negative number")));let s=Xn(e,"fuzzy_match_enabled");s!==void 0&&(U6(s)?r.fuzzy_match_enabled=s:n.push(or(`${t}.fuzzy_match_enabled`,"must be boolean")));let a=Xn(e,"fuzzy_match_threshold");a!==void 0&&(Gf(a)&&a>0&&a<=1?r.fuzzy_match_threshold=a:n.push(or(`${t}.fuzzy_match_threshold`,"must be a number in (0, 1]")));let c=Xn(e,"skip_large_file_action");return c!==void 0&&(c==="warn"||c==="block"?r.skip_large_file_action=c:n.push(or(`${t}.skip_large_file_action`,'must be "warn" or "block"'))),{value:r,warnings:n}}function KMn(e,t){let n=[];if(!Array.isArray(e))return n.push(or(t,`custom_guards must be an array, got ${typeof e}`)),{warnings:n};let r=[];for(let i=0;i<e.length;i++){let o=e[i];if(!TE(o)){n.push(or(`${t}[${i}]`,"must be an object"));continue}let s=Xn(o,"pattern"),a=Xn(o,"message"),c=Xn(o,"severity");if(!Th(s)||s.length===0){n.push(or(`${t}[${i}].pattern`,"must be a non-empty string"));continue}r.push({pattern:s,message:Th(a)?a:"Custom guard triggered",severity:Th(c)&&QMn.has(c.toLowerCase())?c.toLowerCase():"error"})}return{value:r,warnings:n}}function iye(e,t="profile"){let n=[];if(!TE(e))return{ok:!1,errors:[or(t,`profile must be an object, got ${typeof e}`)]};let r={},i=Xn(e,"audit_level");i!==void 0&&(Th(i)&&P2.includes(i)?r.audit_level=i:n.push(or(`${t}.audit_level`,`must be one of: ${P2.join(", ")}, got ${JSON.stringify(i)}`)));let o=Xn(e,"evolution_mode");o!==void 0&&(Th(o)&&L2.includes(o)?r.evolution_mode=o:n.push(or(`${t}.evolution_mode`,`must be one of: ${L2.join(", ")}, got ${JSON.stringify(o)}`)));let s=Xn(e,"risk_paths");s!==void 0&&(Array.isArray(s)?r.risk_paths=s.filter(Th):Th(s)?r.risk_paths=[s]:n.push(or(`${t}.risk_paths`,"must be an array of strings or a single string"))),n.push(...$Mn(e,t));let a=Xn(e,"tests");if(a!==void 0){let p=WMn(a,`${t}.tests`);p.value&&(r.tests=p.value),n.push(...p.warnings)}let c=Xn(e,"pain");if(c!==void 0){let p=qMn(c,`${t}.pain`);p.value&&(r.pain=p.value),n.push(...p.warnings)}let l=Xn(e,"lifecycle");if(l!==void 0){let p=HMn(l,`${t}.lifecycle`);p.value&&(r.lifecycle=p.value),n.push(...p.warnings)}let u=Xn(e,"edit_verification");if(u!==void 0){let p=jMn(u,`${t}.edit_verification`);p.value&&(r.edit_verification=p.value),n.push(...p.warnings)}let d=Xn(e,"custom_guards");if(d!==void 0){let p=KMn(d,`${t}.custom_guards`);p.value&&(r.custom_guards=p.value),n.push(...p.warnings)}return{ok:!0,value:r,warnings:n}}function Zl(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ps(e){return typeof e=="string"}function gF(e){return typeof e=="boolean"}function Xc(e){return typeof e=="number"&&Number.isFinite(e)}function nt(e,t,n){return{path:e,reason:t,nextAction:n}}function Zn(e,t){if(!ys.has(t))return Object.hasOwn(e,t)?e[t]:void 0}function qa(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t==="string"){let n=e;return n.length>50?`"${n.slice(0,50)}\u2026"`:`"${n}"`}return t==="number"||t==="boolean"?String(e):Array.isArray(e)?`array(${e.length})`:t==="object"?"object":t}function VMn(e,t,n){let r=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`feature '${n}' must be an object, got ${typeof e}`,`Fix feature '${n}' to be an object with category and enabled fields`)]};let i=Zn(e,"category");i===void 0?r.push(nt(`${t}.category`,`feature '${n}' missing required field 'category'`,`Add 'category' to feature '${n}' (one of: ${C_.join(", ")})`)):(!ps(i)||!C_.includes(i))&&r.push(nt(`${t}.category`,`feature '${n}' category must be one of: ${C_.join(", ")}, got ${qa(i)}`,`Change category of feature '${n}' to one of: ${C_.join(", ")}`));let o=Zn(e,"enabled");o===void 0?r.push(nt(`${t}.enabled`,`feature '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to feature '${n}'`)):gF(o)||r.push(nt(`${t}.enabled`,`feature '${n}' enabled must be boolean, got ${typeof o}`,`Change enabled of feature '${n}' to true or false`));let s=Zn(e,"source");return s!==void 0&&(typeof s!="string"||!VO.includes(s))&&r.push(nt(`${t}.source`,`feature '${n}' source must be one of: ${VO.join(", ")}, got ${qa(s)}`,`Set source to one of: ${VO.join(", ")}, or remove it (legacy override)`)),r.length>0?{ok:!1,errors:r}:{ok:!0,value:{category:i,enabled:o,...s!==void 0&&typeof s=="string"&&VO.includes(s)?{source:s}:{}}}}function YMn(e,t,n){let r=[],i=Zn(e,"provider");i!==void 0&&!ps(i)&&r.push(nt(`${t}.provider`,`profile '${n}' provider must be a string, got ${typeof i}`,`Fix provider in profile '${n}'`));let o=Zn(e,"model");o!==void 0&&!ps(o)&&r.push(nt(`${t}.model`,`profile '${n}' model must be a string, got ${typeof o}`,`Fix model in profile '${n}'`));let s=Zn(e,"source");s!==void 0&&!ps(s)&&r.push(nt(`${t}.source`,`profile '${n}' source must be a string, got ${typeof s}`,`Fix source in profile '${n}'`));let a=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let l of a)Object.hasOwn(e,l)&&r.push(nt(`${t}.${l}`,`profile '${n}' contains forbidden secret field '${l}'`,`Remove '${l}' from profile '${n}' \u2014 PD does not store provider credentials (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let c={type:"openclaw"};return ps(i)&&(c.provider=i),ps(o)&&(c.model=o),ps(s)&&(c.source=s),{ok:!0,value:c}}function zMn(e,t,n){let r=[],i=Zn(e,"provider");i===void 0?r.push(nt(`${t}.provider`,`profile '${n}' missing required field 'provider'`,`Add 'provider' to profile '${n}' (e.g. "anthropic", "openai")`)):ps(i)||r.push(nt(`${t}.provider`,`profile '${n}' provider must be a string, got ${qa(i)}`,`Fix provider in profile '${n}'`));let o=Zn(e,"model");o===void 0?r.push(nt(`${t}.model`,`profile '${n}' missing required field 'model'`,`Add 'model' to profile '${n}' (e.g. "claude-3-5-sonnet")`)):ps(o)||r.push(nt(`${t}.model`,`profile '${n}' model must be a string, got ${qa(o)}`,`Fix model in profile '${n}'`));let s=Zn(e,"apiKeyEnv");s===void 0?r.push(nt(`${t}.apiKeyEnv`,`profile '${n}' missing required field 'apiKeyEnv'`,`Add 'apiKeyEnv' to profile '${n}' (e.g. "ANTHROPIC_API_KEY")`)):ps(s)||r.push(nt(`${t}.apiKeyEnv`,`profile '${n}' apiKeyEnv must be a string (env var name), got ${qa(s)}`,`Fix apiKeyEnv in profile '${n}' to be an environment variable name`));let a=Zn(e,"baseUrl");a!==void 0&&!ps(a)&&r.push(nt(`${t}.baseUrl`,`profile '${n}' baseUrl must be a string, got ${typeof a}`,`Fix baseUrl in profile '${n}'`));let c=Zn(e,"timeoutMs");c!==void 0&&!Xc(c)&&r.push(nt(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be a finite number, got ${qa(c)}`,`Fix timeoutMs in profile '${n}'`)),Xc(c)&&c<=0&&r.push(nt(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be positive, got ${c}`,`Set timeoutMs in profile '${n}' to a positive number`));let l=Zn(e,"maxRetries");l!==void 0&&!Xc(l)&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be a finite number, got ${qa(l)}`,`Fix maxRetries in profile '${n}'`)),Xc(l)&&l<0&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be non-negative, got ${l}`,`Set maxRetries in profile '${n}' to a non-negative integer`)),Xc(l)&&!Number.isInteger(l)&&r.push(nt(`${t}.maxRetries`,`profile '${n}' maxRetries must be an integer, got ${l}`,`Set maxRetries in profile '${n}' to a non-negative integer`));let u=Zn(e,"maxTokens");u!==void 0&&!Xc(u)&&r.push(nt(`${t}.maxTokens`,`profile '${n}' maxTokens must be a finite number, got ${qa(u)}`,`Fix maxTokens in profile '${n}'`)),Xc(u)&&u<=0&&r.push(nt(`${t}.maxTokens`,`profile '${n}' maxTokens must be positive, got ${u}`,`Set maxTokens in profile '${n}' to a positive number`));let d=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let m of d)Object.hasOwn(e,m)&&r.push(nt(`${t}.${m}`,`profile '${n}' contains forbidden secret field '${m}'`,`Remove '${m}' from profile '${n}' \u2014 use 'apiKeyEnv' for env var name reference (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let p={type:"pi-ai",provider:i,model:o,apiKeyEnv:s};return ps(a)&&(p.baseUrl=a),Xc(c)&&(p.timeoutMs=c),Xc(l)&&(p.maxRetries=l),Xc(u)&&(p.maxTokens=u),{ok:!0,value:p}}function JMn(e,t,n){if(!Zl(e))return{ok:!1,errors:[nt(t,`profile '${n}' must be an object, got ${typeof e}`,`Fix profile '${n}' to be an object with type, provider, model fields`)]};for(let i of ys)if(Object.hasOwn(e,i))return{ok:!1,errors:[nt(`${t}.${i}`,`profile '${n}' contains dangerous key '${i}'`,`Remove '${i}' from profile '${n}'`)]};let r=Zn(e,"type");return r===void 0?{ok:!1,errors:[nt(`${t}.type`,`profile '${n}' missing required field 'type'`,`Add 'type' to profile '${n}' (one of: ${Ob.join(", ")})`)]}:!ps(r)||!Ob.includes(r)?{ok:!1,errors:[nt(`${t}.type`,`profile '${n}' type must be one of: ${Ob.join(", ")}, got ${qa(r)}`,`Fix type in profile '${n}'`)]}:r==="openclaw"?YMn(e,t,n):zMn(e,t,n)}function XMn(e,t,n){let r=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`agent '${n}' must be an object, got ${typeof e}`,`Fix agent '${n}' to be an object with enabled and optional runtimeProfile fields`)]};let i=Zn(e,"enabled");i===void 0?r.push(nt(`${t}.enabled`,`agent '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to agent '${n}'`)):gF(i)||r.push(nt(`${t}.enabled`,`agent '${n}' enabled must be boolean, got ${typeof i}`,`Change enabled of agent '${n}' to true or false`));let o=Zn(e,"runtimeProfile");if(o!==void 0&&!ps(o)&&r.push(nt(`${t}.runtimeProfile`,`agent '${n}' runtimeProfile must be a string, got ${typeof o}`,`Fix runtimeProfile of agent '${n}' to a profile ID`)),r.length>0)return{ok:!1,errors:r};let s={enabled:i};return ps(o)&&(s.runtimeProfile=o),{ok:!0,value:s}}function ZMn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`internalAgents must be an object, got ${typeof e}`,"Fix internalAgents to be an object with defaultRuntime and agents")]};let r=Zn(e,"defaultRuntime");r===void 0?n.push(nt(`${t}.defaultRuntime`,"missing required field defaultRuntime","Add defaultRuntime with a runtime profile ID")):(!ps(r)||r.length===0)&&n.push(nt(`${t}.defaultRuntime`,`defaultRuntime must be a non-empty string, got ${qa(r)}`,"Fix defaultRuntime to a valid runtime profile ID"));let i=Zn(e,"agents"),o={};if(i===void 0)n.push(nt(`${t}.agents`,"missing required field agents",`Add agents section with per-agent bindings: ${Rc.join(", ")}`));else if(!Zl(i))n.push(nt(`${t}.agents`,`agents must be an object, got ${typeof i}`,"Fix agents to be an object mapping agent names to bindings"));else{for(let a of Rc){let c=Zn(i,a);if(c===void 0)continue;let l=XMn(c,`${t}.agents.${a}`,a);l.ok?o[a]=l.value:n.push(...l.errors)}for(let a of Object.keys(i))ys.has(a)||Rc.includes(a)||n.push(nt(`${t}.agents.${a}`,`unknown agent key '${a}'`,`Remove unknown agent '${a}' or use a known agent name: ${Rc.join(", ")}`))}let s=new Set(["defaultRuntime","agents"]);for(let a of Object.keys(e))ys.has(a)||s.has(a)||n.push(nt(`${t}.${a}`,`unknown key '${a}' in internalAgents`,`Remove unknown key '${a}' from internalAgents`));return n.length>0?{ok:!1,errors:n}:{ok:!0,value:{defaultRuntime:r,agents:o}}}function eBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`ui must be an object, got ${typeof e}`,"Fix ui to be an object with diagnostics settings")]};let r=Zn(e,"diagnostics");if(!Zl(r))return{ok:!1,errors:[nt(`${t}.diagnostics`,`ui.diagnostics must be an object, got ${typeof r}`,"Fix ui.diagnostics to be an object with mode field")]};let i=Zn(r,"mode");return i===void 0?n.push(nt(`${t}.diagnostics.mode`,"missing required field mode",`Add mode to ui.diagnostics (one of: ${S_.join(", ")})`)):(!ps(i)||!S_.includes(i))&&n.push(nt(`${t}.diagnostics.mode`,`mode must be one of: ${S_.join(", ")}, got ${qa(i)}`,`Fix mode to one of: ${S_.join(", ")}`)),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{diagnostics:{mode:i}}}}function tBn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function nBn(e){return YO.some(t=>t===e)}function rBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,`workspace must be an object, got ${typeof e}`,"Fix workspace to be an object with a default field")]};for(let a of ys)if(Object.hasOwn(e,a))return{ok:!1,errors:[nt(`${t}.${a}`,`workspace contains dangerous key '${a}'`,`Remove '${a}' from workspace`)]};let r=Zn(e,"default");r===void 0?n.push(nt(`${t}.default`,"workspace missing required field default","Add default path to workspace section (must be an absolute path)")):!ps(r)||r.length===0?n.push(nt(`${t}.default`,`workspace.default must be a non-empty string, got ${qa(r)}`,"Set workspace.default to an absolute directory path")):tBn(r)||n.push(nt(`${t}.default`,`workspace.default must be an absolute path, got "${r}"`,'Use an absolute path like "D:\\.openclaw\\workspace" or "/home/user/.openclaw/workspace"'));let i=Zn(e,"environment"),o;i!==void 0&&(ps(i)&&nBn(i)?o=i:n.push(nt(`${t}.environment`,`workspace.environment must be one of ${YO.join("|")}, got ${qa(i)}`,`Set workspace.environment to one of ${YO.join(", ")}, or remove the key to leave the environment unknown`)));let s=new Set(["default","environment"]);for(let a of Object.keys(e))ys.has(a)||s.has(a)||n.push(nt(`${t}.${a}`,`unknown key '${a}' in workspace`,`Remove unknown key '${a}' from workspace`));return n.length>0?{ok:!1,errors:n}:!ps(r)||r.length===0?{ok:!1,errors:[nt(`${t}.default`,"workspace.default validation invariant failed","Re-validate the workspace section; this error indicates a validator bug \u2014 please report it")]}:{ok:!0,value:{default:r,...o!==void 0?{environment:o}:{}}}}function iBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,"evolutionContext must be an object","Fix evolutionContext to be an object with enabled, maxMessages, maxCharsPerMessage")]};let r=Zn(e,"enabled");r!==void 0&&!gF(r)&&n.push(nt(`${t}.enabled`,"evolutionContext.enabled must be a boolean","Set evolutionContext.enabled to true or false"));let i=Zn(e,"maxMessages");i!==void 0&&(!Xc(i)||!Number.isInteger(i)||i<0)&&n.push(nt(`${t}.maxMessages`,"evolutionContext.maxMessages must be a non-negative integer","Set evolutionContext.maxMessages to a non-negative integer"));let o=Zn(e,"maxCharsPerMessage");return o!==void 0&&(!Xc(o)||!Number.isInteger(o)||o<0)&&n.push(nt(`${t}.maxCharsPerMessage`,"evolutionContext.maxCharsPerMessage must be a non-negative integer","Set evolutionContext.maxCharsPerMessage to a non-negative integer")),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{enabled:gF(r)?r:!0,maxMessages:Xc(i)?i:4,maxCharsPerMessage:Xc(o)?o:200}}}function oBn(e,t){let n=[];if(!Zl(e))return{ok:!1,errors:[nt(t,"contextInjection must be an object","Fix contextInjection to be an object with optional thinkingOs, projectFocus, evolutionContext fields")]};for(let c of ys)if(Object.hasOwn(e,c))return{ok:!1,errors:[nt(`${t}.${c}`,`contextInjection contains dangerous key '${c}'`,`Remove '${c}' from contextInjection`)]};let r={},i=Zn(e,"thinkingOs");i!==void 0&&(gF(i)?r.thinkingOs=i:n.push(nt(`${t}.thinkingOs`,"contextInjection.thinkingOs must be a boolean","Set contextInjection.thinkingOs to true or false")));let o=Zn(e,"projectFocus");o!==void 0&&(!ps(o)||!zO.includes(o)?n.push(nt(`${t}.projectFocus`,`contextInjection.projectFocus must be one of: ${zO.join(", ")}, got ${qa(o)}`,`Set contextInjection.projectFocus to one of: ${zO.join(", ")}`)):r.projectFocus=o);let s=Zn(e,"evolutionContext");if(s!==void 0){let c=iBn(s,`${t}.evolutionContext`);c.ok?r.evolutionContext=c.value:n.push(...c.errors)}let a=new Set(["thinkingOs","projectFocus","evolutionContext"]);for(let c of Object.keys(e))ys.has(c)||a.has(c)||n.push(nt(`${t}.${c}`,`unknown key '${c}' in contextInjection`,`Remove unknown key '${c}' from contextInjection`));return n.length>0?{ok:!1,errors:n}:{ok:!0,value:r}}function Q6(e){let t=[];if(e==null)return{ok:!1,errors:[nt("","config is null or undefined","Provide a valid .pd/config.yaml file or use defaults")]};if(!Zl(e))return{ok:!1,errors:[nt("",`config root must be an object, got ${typeof e}`,"Fix .pd/config.yaml to be a YAML object")]};for(let T of ys)Object.hasOwn(e,T)&&t.push(nt(T,`root contains dangerous key '${T}'`,`Remove '${T}' from config root`));let n=Zn(e,"version");n===void 0?t.push(nt("version","missing required field version",`Add version: ${1} to config`)):(!Xc(n)||n!==1)&&t.push(nt("version",`version must be ${1}, got ${qa(n)}`,`Set version to ${1}`));let r=Zn(e,"workspace"),i;if(r!==void 0){let T=rBn(r,"workspace");T.ok?i=T.value:t.push(...T.errors)}let o=Zn(e,"features"),s={};if(o===void 0)t.push(nt("features","missing required field features","Add features section with prompt, code_tool_hook, defer_archive entries"));else if(!Zl(o))t.push(nt("features",`features must be an object, got ${typeof o}`,"Fix features to be an object mapping flag names to {category, enabled}"));else for(let T of Object.keys(o)){if(ys.has(T)){t.push(nt(`features.${T}`,`dangerous key '${T}' rejected`,`Remove '${T}' from features`));continue}let D=VMn(o[T],`features.${T}`,T);D.ok?s[T]=D.value:t.push(...D.errors)}let a=Zn(e,"runtimeProfiles"),c={};if(a===void 0)t.push(nt("runtimeProfiles","missing required field runtimeProfiles","Add runtimeProfiles section with at least one profile"));else if(!Zl(a))t.push(nt("runtimeProfiles",`runtimeProfiles must be an object, got ${typeof a}`,"Fix runtimeProfiles to be an object mapping profile IDs to profile definitions"));else for(let T of Object.keys(a)){if(ys.has(T)){t.push(nt(`runtimeProfiles.${T}`,`dangerous key '${T}' rejected`,`Remove '${T}' from runtimeProfiles`));continue}let D=JMn(a[T],`runtimeProfiles.${T}`,T);D.ok?c[T]=D.value:t.push(...D.errors)}let l=Zn(e,"internalAgents"),u;if(l===void 0)t.push(nt("internalAgents","missing required field internalAgents","Add internalAgents section with defaultRuntime"));else{let T=ZMn(l,"internalAgents");T.ok?u=T.value:t.push(...T.errors)}let d=Zn(e,"ui"),p;if(d!==void 0){let T=eBn(d,"ui");T.ok?p=T.value:t.push(...T.errors)}let m=Zn(e,"profile"),g;if(m!==void 0){let T=iye(m);if(T.ok)g=T.value;else for(let D of T.errors)t.push(nt(D.path,D.message,"Fix profile section in .pd/config.yaml"))}let A=Zn(e,"contextInjection"),_;if(A!==void 0){let T=oBn(A,"contextInjection");T.ok?_=T.value:t.push(...T.errors)}let x=Zn(e,"principles"),v;if(x!==void 0)if(!Zl(x))t.push(nt("principles",`principles must be an object, got ${qa(x)}`,"Set principles to a mapping (e.g. principles: { outputLanguage: zh-CN })"));else{let T=Object.hasOwn(x,"outputLanguage")?x.outputLanguage:void 0;T===void 0?v={}:R2(T)?v={outputLanguage:T}:t.push(nt("principles.outputLanguage",`outputLanguage must be one of ${w_.join(", ")}, got ${qa(T)}`,`Set principles.outputLanguage to one of: ${w_.join(", ")}`))}return t.length>0?{ok:!1,errors:t}:u?{ok:!0,value:{version:1,...i?{workspace:i}:{},features:s,runtimeProfiles:c,internalAgents:u,ui:p??{diagnostics:{mode:"simple"}},...v?{principles:v}:{},...g?{profile:g}:{},..._?{contextInjection:_}:{}}}:{ok:!1,errors:[nt("internalAgents","internalAgents validation unexpectedly failed","Check internalAgents configuration")]}}var sBn={on_change:"smoke",on_risk_change:"unit",commands:{}},hft={enabled:!0,spiral_boost:20,min_threshold:15,max_threshold:70,backlog_trigger:6,hard_failure_trigger:1,low_recent_success_boost:15,high_recent_pain_boost:10},aBn={soft_capture_threshold:30,adaptive:{...hft}},cBn={enabled:!0,heartbeat_stale_hours:72},lBn={enabled:!0,max_file_size_bytes:10*1024*1024,fuzzy_match_enabled:!0,fuzzy_match_threshold:.8,skip_large_file_action:"warn"};var Xi={audit_level:"medium",risk_paths:[],evolution_mode:"realtime",tests:{...sBn},pain:{soft_capture_threshold:aBn.soft_capture_threshold,adaptive:{...hft}},lifecycle:{...cBn},edit_verification:{...lBn},custom_guards:[]};function $6(e){return e?{audit_level:e.audit_level??Xi.audit_level,risk_paths:e.risk_paths??Xi.risk_paths,evolution_mode:e.evolution_mode??Xi.evolution_mode,tests:{on_change:e.tests?.on_change??Xi.tests.on_change,on_risk_change:e.tests?.on_risk_change??Xi.tests.on_risk_change,commands:{...Xi.tests.commands,...e.tests?.commands??{}}},pain:{soft_capture_threshold:e.pain?.soft_capture_threshold??Xi.pain.soft_capture_threshold,adaptive:{enabled:e.pain?.adaptive?.enabled??Xi.pain.adaptive.enabled,spiral_boost:e.pain?.adaptive?.spiral_boost??Xi.pain.adaptive.spiral_boost,min_threshold:e.pain?.adaptive?.min_threshold??Xi.pain.adaptive.min_threshold,max_threshold:e.pain?.adaptive?.max_threshold??Xi.pain.adaptive.max_threshold,backlog_trigger:e.pain?.adaptive?.backlog_trigger??Xi.pain.adaptive.backlog_trigger,hard_failure_trigger:e.pain?.adaptive?.hard_failure_trigger??Xi.pain.adaptive.hard_failure_trigger,low_recent_success_boost:e.pain?.adaptive?.low_recent_success_boost??Xi.pain.adaptive.low_recent_success_boost,high_recent_pain_boost:e.pain?.adaptive?.high_recent_pain_boost??Xi.pain.adaptive.high_recent_pain_boost}},lifecycle:{enabled:e.lifecycle?.enabled??Xi.lifecycle.enabled,heartbeat_stale_hours:e.lifecycle?.heartbeat_stale_hours??Xi.lifecycle.heartbeat_stale_hours},edit_verification:{enabled:e.edit_verification?.enabled??Xi.edit_verification.enabled,max_file_size_bytes:e.edit_verification?.max_file_size_bytes??Xi.edit_verification.max_file_size_bytes,fuzzy_match_enabled:e.edit_verification?.fuzzy_match_enabled??Xi.edit_verification.fuzzy_match_enabled,fuzzy_match_threshold:e.edit_verification?.fuzzy_match_threshold??Xi.edit_verification.fuzzy_match_threshold,skip_large_file_action:e.edit_verification?.skip_large_file_action??Xi.edit_verification.skip_large_file_action},custom_guards:e.custom_guards??Xi.custom_guards}:{...Xi}}function gft(e){return e?{thinkingOs:e.thinkingOs??yl.thinkingOs,projectFocus:e.projectFocus??yl.projectFocus,evolutionContext:{enabled:e.evolutionContext?.enabled??yl.evolutionContext.enabled,maxMessages:e.evolutionContext?.maxMessages??yl.evolutionContext.maxMessages,maxCharsPerMessage:e.evolutionContext?.maxCharsPerMessage??yl.evolutionContext.maxCharsPerMessage}}:{...yl}}function kE(e){if(e==null)return{config:U2(),source:"defaults",warnings:[],featuresChangedFromDefault:[],resolvedProfile:$6({}),resolvedContextInjection:gft(void 0)};let t=[],n=[],{normalized:r,warnings:i}=M2(e.features);t.push(...i);let o={};for(let[_,x]of Object.entries(ly))if(Object.hasOwn(r,_)){let v=r[_];if(!v){o[_]={...x};continue}if(x.category==="gone"){o[_]={...x},v.enabled&&(t.push(`feature '${_}': gone flag cannot be re-enabled`),n.push(_));continue}if(x.category==="core"&&!v.enabled){o[_]={category:v.category,enabled:!1,...v.source?{source:v.source}:{}},t.push(`feature '${_}': core flag explicitly disabled via config (emergency disable)`),n.push(_);continue}(v.category!==x.category||v.enabled!==x.enabled)&&n.push(_),o[_]={category:v.category,enabled:v.enabled,...v.source?{source:v.source}:{}}}else o[_]={...x};for(let _ of Object.keys(r))ys.has(_)||Object.hasOwn(o,_)||t.push(`feature '${_}': unknown flag ignored (not a registered capability)`);let s={};for(let[_,x]of Object.entries(e.runtimeProfiles))ys.has(_)||(s[_]={...x});Object.hasOwn(s,cy)||(s[cy]={...F2},t.push(`runtime profile '${cy}' not found in config, using default`));let a=JO(),c={};for(let _ of Rc){let x=e.internalAgents.agents[_],v=a.agents[_];x!==void 0?c[_]={enabled:x.enabled,runtimeProfile:x.runtimeProfile??e.internalAgents.defaultRuntime}:c[_]={enabled:v.enabled,runtimeProfile:e.internalAgents.defaultRuntime}}for(let _ of Rc){let x=c[_];x&&x.enabled&&x.runtimeProfile&&!Object.hasOwn(s,x.runtimeProfile)&&t.push(`agent '${_}': runtime profile '${x.runtimeProfile}' not found in runtimeProfiles`)}let l=r.diagnostician_split_pipeline;if(l!==void 0&&l.enabled===!1&&c.diagnostician?.enabled===!0){c.diagnostician={enabled:!1,runtimeProfile:e.internalAgents.defaultRuntime};let _=l.source??"unknown";t.push(`PRI-638 cutover: legacy diagnostician_split_pipeline=false (source: ${_}) honored as internalAgents.agents.diagnostician.enabled=false to avoid silently enabling a previously-disabled LLM pipeline. Recovery: toggle Diagnostician ON in Console \u2192 Control Center (the writer retires the conflicting legacy override), or edit .pd/config.yaml to remove the legacy diagnostician_split_pipeline flag. A standalone internalAgents.agents.diagnostician.enabled=true is NOT sufficient while the legacy override remains false.`)}let u={defaultRuntime:e.internalAgents.defaultRuntime,agents:c},d=e.ui??{...XO},p=e.principles??{outputLanguage:void 0},m=$6(e.profile??{}),g=gft(e.contextInjection);return{config:{version:1,...e.workspace?{workspace:e.workspace}:{},features:o,runtimeProfiles:s,internalAgents:u,ui:d,principles:p,...e.profile?{profile:e.profile}:{},...e.contextInjection?{contextInjection:e.contextInjection}:{}},source:"user_config",warnings:t,featuresChangedFromDefault:n,resolvedProfile:m,resolvedContextInjection:g}}var fBn=new Set(["owner_reported","agent_on_owner_request","tool_failure","dispatch_error","provider_failure","rate_limit","rulehost_block","empathy_inferred","semantic","llm_paralysis","subagent_error","gfi_threshold","unknown"]);function W6(e){return typeof e=="string"&&fBn.has(e)}var oye=new Map([["owner_reported",{kind:"owner_reported",defaultDecision:"admit",reason:"Owner explicitly reported pain. Highest confidence signal.",nextAction:"none",canUpgrade:!1}],["agent_on_owner_request",{kind:"agent_on_owner_request",defaultDecision:"admit",reason:"Agent recorded pain at owner request. Owner intent preserved.",nextAction:"none",canUpgrade:!1}],["tool_failure",{kind:"tool_failure",defaultDecision:"evidence_only",reason:"Tool failure is infrastructure noise. PD does not own tool repair (ADR-0014).",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["dispatch_error",{kind:"dispatch_error",defaultDecision:"evidence_only",reason:"Dispatch/subagent routing error. Not a behavior pattern.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["provider_failure",{kind:"provider_failure",defaultDecision:"health_only",reason:"LLM provider failure. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry",canUpgrade:!1}],["rate_limit",{kind:"rate_limit",defaultDecision:"health_only",reason:"LLM provider rate limit. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry",canUpgrade:!1}],["rulehost_block",{kind:"rulehost_block",defaultDecision:"evidence_only",reason:"RuleHost block is near-miss evidence. Default evidence-only.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!0}],["empathy_inferred",{kind:"empathy_inferred",defaultDecision:"owner_confirm",reason:"Empathy-inferred frustration. Never silently creates diagnosis (PRODUCT_IDENTITY: owner-governed).",nextAction:"request_owner_confirmation_before_diagnosis",canUpgrade:!1}],["semantic",{kind:"semantic",defaultDecision:"evidence_only",reason:"Keyword/detection match. Not explicit owner pain. Needs accumulation.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["llm_paralysis",{kind:"llm_paralysis",defaultDecision:"evidence_only",reason:"Session health signal. GFI alone cannot create diagnosis.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["subagent_error",{kind:"subagent_error",defaultDecision:"evidence_only",reason:"Subagent workflow failure. Not a behavior pattern by itself.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["gfi_threshold",{kind:"gfi_threshold",defaultDecision:"evidence_only",reason:"Accumulated GFI. GFI alone cannot create diagnosis per acceptance criteria.",nextAction:"store_as_evidence_for_later_correlation",canUpgrade:!1}],["unknown",{kind:"unknown",defaultDecision:"evidence_only",reason:"Unclassified source. Conservative default.",nextAction:"classify_source_kind_and_store_as_evidence",canUpgrade:!1}]]);function iD(e){return oye.get(e)}var AF=70,yF=4;function mBn(e,t){return t!=="evidence_only"?t:e.sourceKind==="rulehost_block"&&e.isUnsafeHighConfidence===!0||e.isRisky===!0&&e.score>=AF||e.consecutiveErrors!==void 0&&e.consecutiveErrors>=yF?"admit":t}function hBn(e,t,n){return t!=="admit"?`Upgraded decision for ${e}: ${t}`:e==="rulehost_block"&&n.isUnsafeHighConfidence===!0?`RuleHost blocked a high-confidence unsafe action (score=${n.score}). Upgrading to direct diagnosis.`:n.isRisky===!0&&n.score>=AF?"Risky high-score operation overrides evidence-only decision. Immediate diagnosis required.":n.consecutiveErrors!==void 0&&n.consecutiveErrors>=yF?"Repeated failures override evidence-only decision. Pattern suggests systemic issue requiring diagnosis.":`Upgraded decision for ${e}: ${t}`}function gBn(e,t,n){return t!=="admit"||e==="rulehost_block"&&n.isUnsafeHighConfidence===!0?"none":n.isRisky===!0&&n.score>=AF||n.consecutiveErrors!==void 0&&n.consecutiveErrors>=yF?"create_diagnostic_task":"none"}function Wv(e){let t=W6(e.sourceKind)?e.sourceKind:"unknown",n=iD(t);if(!n)return{decision:"evidence_only",sourceKind:"unknown",reason:`Source kind '${t}' not found in descriptor registry. Conservative default.`,nextAction:"classify_source_kind_and_store_as_evidence"};if(n.canUpgrade||e.isRisky!==void 0||e.consecutiveErrors!==void 0){let i=mBn(e,n.defaultDecision);if(i!==n.defaultDecision)return{decision:i,sourceKind:t,reason:hBn(t,i,e),nextAction:gBn(t,i,e)}}return{decision:n.defaultDecision,sourceKind:t,reason:n.reason,nextAction:n.nextAction}}function rd(e){let{isManualEntry:t,isGateBlock:n,isSubagentError:r,isRateLimit:i,toolName:o,failureSource:s,isGfiTriggered:a,detectionSource:c,nonZeroExit:l,timedOut:u,toolNotFound:d}=e;if(t)return"owner_reported";if(n)return"rulehost_block";if(r)return"subagent_error";if(i===!0)return"rate_limit";if(i===!1)return"provider_failure";if(o==="pain"||o==="skill:pain")return e.provenance==="host_context_bound"?"agent_on_owner_request":"owner_reported";if(a)return"gfi_threshold";if(s)return s==="dispatch_error"?"dispatch_error":"tool_failure";if(d||(o!==void 0||l||u||d)&&(!o||o.trim()===""))return"dispatch_error";if(l||u)return"tool_failure";if(c){if(c==="llm_paralysis")return"llm_paralysis";if(c.startsWith("llm_"))return"semantic";if(c==="user_empathy")return"empathy_inferred"}return"unknown"}function ABn(e){if(!e)return"tool_failure";let t=String(e);return/\btool\s+(?:\S+\s+)?not\s+found\b/i.test(t)||/\bunknown\s+tool\b/i.test(t)?"dispatch_error":"tool_failure"}function bA(e){let{toolName:t,error:n,provenance:r}=e,i=typeof e.exitCode=="number"&&e.exitCode!==0,o;return!t||t.trim()===""?o="dispatch_error":o=ABn(n),!n&&!i&&(o=void 0),{observedAt:new Date().toISOString(),toolName:t,failureSource:o,nonZeroExit:i,provenance:r}}function IF(e){return{observedAt:new Date().toISOString(),isManualEntry:!0,sessionId:e.sessionId}}function Aft(e,t){let n=[];return e&&n.push(`canUpgrade=${e.canUpgrade}`),n.push(`score=${t.score}`),t.sessionId&&n.push(`session=${t.sessionId.slice(0,8)}`),n.join(", ")}function yBn(e){return{outcome:"refused",reason:e.validationError??"Input validation failed. Evidence is malformed or incomplete.",nextAction:"fix_input_and_retry_or_classify_as_unknown",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!1,decidedAt:new Date().toISOString(),operatorNote:`validationError=${e.validationError??"unknown"}`}}function IBn(e){return{outcome:"manual_owner_admitted",reason:"Owner explicit manual pain. Bypasses triage and cooldown. Highest confidence signal.",nextAction:"create_diagnostic_task",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!0,decidedAt:new Date().toISOString(),operatorNote:`score=${e.score}, sessionId=${e.sessionId??"unknown"}`}}function EBn(e){let{triageResult:t}=e,n=iD(t.sourceKind),r=new Date().toISOString();switch(t.decision){case"admit":return e.isCooldownActive&&!e.cooldownBypassAllowed?{outcome:"cooldown_skipped",reason:`Admitted by triage but cooldown is active for source '${t.sourceKind}'. Cooldown prevents diagnosis to avoid duplicate tasks.`,nextAction:"wait_for_cooldown_or_manual_retrigger",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`cooldown_active=true, score=${e.score}`}:{outcome:"diagnosis_created",reason:t.reason,nextAction:t.nextAction==="none"?"proceed_with_diagnostic_task":t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!0,decidedAt:r,operatorNote:Aft(n,e)};case"evidence_only":return{outcome:"evidence_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:Aft(n,e)};case"health_only":return{outcome:"health_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`provider_signal, score=${e.score}`};case"owner_confirm":return{outcome:"owner_confirm_required",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`requires_confirmation, score=${e.score}`};case"reject":return{outcome:"refused",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`rejected, score=${e.score}`};default:{let i=t.decision;return{outcome:"refused",reason:`Unhandled triage decision: ${String(t.decision)}. Conservative refusal.`,nextAction:"investigate_unknown_triage_decision",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r}}}}function id(e){return e.isValid?e.isOwnerManual?IBn(e):EBn(e):yBn(e)}var EF=class{cache;maxSize;constructor(t=100){this.cache=new Map,this.maxSize=t}get(t){let n=this.cache.get(t);return n!==void 0&&(this.cache.delete(t),this.cache.set(t,n)),n}set(t,n){if(this.cache.has(t))this.cache.delete(t);else if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r!==void 0&&this.cache.delete(r)}this.cache.set(t,n)}},oD=class{cache;asyncQueue=[];match;hash;shouldIgnoreProtocol;queueCapacity;constructor(t){this.match=t.match,this.hash=t.hash,this.shouldIgnoreProtocol=t.shouldIgnoreProtocol,this.cache=new EF(t.cacheSize??100),this.queueCapacity=t.queueCapacity??1e3}detect(t){if(this.shouldIgnoreProtocol(t))return{detected:!1,source:"l1_exact"};let n=this.match(t);if(n)return{detected:!0,severity:n.severity,ruleId:n.ruleId,source:"l1_exact"};let r=this.hash(t),i=this.cache.get(r);return i?{detected:i.detected,severity:i.severity,source:"l2_cache"}:(this.enqueueAsync(t),{detected:!1,source:"l3_async_queued"})}enqueueAsync(t){this.asyncQueue.length<this.queueCapacity&&this.asyncQueue.push(t)}updateCache(t,n){let r=this.hash(t);this.cache.set(r,n)}flushQueue(){let t=[...this.asyncQueue];return this.asyncQueue=[],t}};var Ift=[{key:"why",headerRegex:/^##\s+1\.\s*Why\s*$/im,label:"why",header:"## 1. Why"},{key:"desiredOutcome",headerRegex:/^##\s+2\.\s*Desired Outcome\s*$/im,label:"desiredOutcome",header:"## 2. Desired Outcome"},{key:"nonNegotiables",headerRegex:/^##\s+3\.\s*Non-negotiables\s*$/im,label:"nonNegotiables",header:"## 3. Non-negotiables"},{key:"stopEscalation",headerRegex:/^##\s+4\.\s*Stop\s*\/\s*Escalation\s*$/im,label:"stopEscalation",header:"## 4. Stop / Escalation"},{key:"currentStrategicFocus",headerRegex:/^##\s+5\.\s*Current Strategic Focus\s*$/im,label:"currentStrategicFocus",header:"## 5. Current Strategic Focus"}];function G6(e){let t={};for(let n of Ift){let r=n.headerRegex.exec(e);if(r===null)continue;let i=e.slice(r.index+r[0].length),o=/^##\s+/m.exec(i);t[n.key]=i.slice(0,o!==null?o.index:i.length).trim()}return t}function aye(e){let t=[];for(let n of Ift){let i=Object.hasOwn(e,n.key)?e[n.key]:void 0;if(i===void 0){t.push({code:"missing_section",message:`Section "${n.label}" is missing from INTENT.md.`,section:n.label});continue}if(typeof i!="string"){t.push({code:"parse_failed",message:`Section "${n.label}" has a non-string value.`,section:n.label});continue}if(i.trim().length===0){t.push({code:"empty_section",message:`Section "${n.label}" is empty.`,section:n.label});continue}i.length<10&&t.push({code:"too_vague",message:`Section "${n.label}" is too short.`,section:n.label})}return t}function qf(e){return`INTENT.${e}.md`}import{createHash as UBn}from"node:crypto";function q6(e){return`sha256:${UBn("sha256").update(e,"utf8").digest("hex")}`}function eu(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var cye=4e3,lye=`
1906
1906
  ...[truncated: intent doc exceeds injection budget]`;function uye(e){if(e==null)return"";let t=typeof e.rawIntentMd=="string"?e.rawIntentMd:"";if(t.trim().length===0)return"";let n=eu(t);if(n.length>cye){let s=cye-lye.length;n=n.slice(0,Math.max(0,s))+lye}let r=`<intent_anchor>
1907
1907
  This is the Owner-owned project intent.
1908
1908