principles-disciple 1.236.3 → 1.237.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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:"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:"gone",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking \u2014 retired (PRI-751, reality re-verified PRI-752): detection moved to signal-collector-host; gone tombstone"},{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. PRI-752: no executable consumers \u2014 flag value has no runtime effect; disposition pending Owner decision."},{id:"painEvidenceAdmissionDefault",category:"quiet",enabled:!0,since:"2026-06-24",description:"PRI-454: historical kill switch for the Gate B migration. PRI-752: the documented flag-off Gate A rollback does not exist as code \u2014 flag value has no runtime effect; disposition pending Owner decision."},{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:"gone",enabled:!1,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders \u2014 retired (PRI-751, reality re-verified PRI-752): unconditional runner behavior; gone tombstone"},{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={};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:"gone",enabled:!1,since:"2026-06-02",description:"Empathy observer service for sentiment checking \u2014 retired (PRI-751, reality re-verified PRI-752): detection moved to signal-collector-host; gone tombstone"},{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:"gone",enabled:!1,since:"2026-06-16",description:"Core principle grounding in internalization prompt builders \u2014 retired (PRI-751, reality re-verified PRI-752): unconditional runner behavior; gone tombstone"},{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:
|
|
@@ -5,16 +5,15 @@
|
|
|
5
5
|
* (TriggerController + EvidenceTriage). Do not add new callers. New admission
|
|
6
6
|
* logic must use `evaluateTriggerController` from runtime-v2/evidence-triage.
|
|
7
7
|
*
|
|
8
|
-
* Reality note (PRI-
|
|
9
|
-
* `
|
|
10
|
-
*
|
|
11
|
-
*
|
|
12
|
-
* (
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* see docs/plans/2026-06-pain-evidence-admission-track.md.
|
|
8
|
+
* Reality note (PRI-763, 2026-09-12): the `painEvidenceAdmission` /
|
|
9
|
+
* `painEvidenceAdmissionDefault` flags were RETIRED and REMOVED from the
|
|
10
|
+
* registry (PRI-763) — they never re-activated this module and had zero
|
|
11
|
+
* executable consumers (PRI-651-B1 / PRI-752 / PRI-762). Gate B
|
|
12
|
+
* (TriggerController) is the only admission authority. This adapter keeps
|
|
13
|
+
* ZERO production importers; only tests import it. The module itself is left
|
|
14
|
+
* archived (Phase 5 discipline: core export surface and plugin shim are not
|
|
15
|
+
* removed in the flag-contract PR — retirement of this module is a separate
|
|
16
|
+
* Owner decision).
|
|
18
17
|
*
|
|
19
18
|
* The pure decision logic (threshold tree, cooldown comparison, episode-key
|
|
20
19
|
* construction) now lives in principles-core
|