principles-disciple 2.1.12 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,14 +1,14 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function C(t,e=!1){let r=[];for(let n of t.split("/").filter(s=>s.length>0))n!=="."&&(n===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e&&r.push(".."):r.push(n));return r}function F(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let r=t.slice(2).split("/").filter(o=>o.length>0),n=r[0]??"",s=r[1]??"";return{kind:"unc",root:`unc:${n}/${s}`,segments:C(r.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ee(t,e,r){return t.length<e.length?!1:e.every((n,s)=>{let o=t[s]??"";return r?o.toLowerCase()===n.toLowerCase():o===n})}function Le(t,e,r){let n=0;for(;n<t.length&&n<e.length;){let o=t[n]??"",i=e[n]??"";if(!(r?o.toLowerCase()===i.toLowerCase():o===i))break;n++}return[...Array.from({length:t.length-n},()=>".."),...e.slice(n)].join("/")||"."}function te(t){let[e,r]=t.root.slice(4).split("/"),n=t.segments.join("/");return`//${e??""}/${r??""}${n?`/${n}`:""}`}function re(t,e,r){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return r;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ee(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?te(t):r:t.segments.slice(e.segments.length).join("/")||".";let n=[...e.segments];for(let o of r.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e.kind==="relative"&&n.push(".."):n.push(o));let s=e.kind==="drive"||e.kind==="unc";return ee(n,e.segments,s)?n.slice(e.segments.length).join("/")||".":Le(e.segments,n,s)}function xe(t,e){if(!t||typeof t!="string")return"";let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/");if(r.startsWith("<tool:")&&r.endsWith(">"))return r;let s=F(r),o=F(n);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=F(c),re(s,o,c)}return re(s,o,r)}function Ce(t,e){let r=t.file_path||t.path||t.file||t.target;if(typeof r=="string"&&r.length>0)return{value:r,isPath:!0};if(e.isBashTool){let n=String(t.command||t.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?{value:s[1],isPath:!0}:{value:n,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function we(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function ke(t){if(t.canonicalKind===void 0)return t;let e=we(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function w(t,e,r,n={}){let s=ke(n),o=Ce(e,{...s,toolName:t}),i=o.isPath?xe(o.value,r):o.value;return{toolName:t,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function ne(t){return typeof t=="string"&&X.has(t)}var k=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function se(t,e,r){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let _=a.canonicalKind;_==="read"||_==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):_==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:r}}var oe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(oe);var $={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($.calls);Object.freeze($);var De={version:2,history:$,facts:oe};Object.freeze(De);var Me=new Set(["__proto__","constructor","prototype"]),ie=3,Pe=5,je=new Set(["allow","block","propose_correction"]),Ue={valid:!0,errors:[]};function W(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function le(t){for(let e of Object.keys(t))if(Me.has(e))return!1;return!0}function Be(t){return t.length===0?Ue:{valid:!1,errors:t}}function H(t){return typeof t=="string"&&t.trim().length>0}function ae(t,e,r){let n=[];return W(t)?le(t)?((!Object.hasOwn(t,"caseId")||!H(t.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==r)&&n.push(`${e}.kind must be '${r}'`),(!Object.hasOwn(t,"toolName")||!H(t.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!W(t.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!je.has(t.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):r==="positive"&&t.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ce(t,e){let{fieldName:r,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${r} must be an array`),o;s&&t.length===0&&o.push(`${r} must contain at least 1 item`),n!==void 0&&t.length>n&&o.push(`${r} must contain at most ${n} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${r}[${i}] must be a string`);return o}function D(t){return Array.isArray(t)?`[${t.map(e=>D(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(r=>r!=="__proto__"&&r!=="constructor"&&r!=="prototype").sort().map(r=>`${JSON.stringify(r)}:${D(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){if(!W(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!le(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...ae(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!H(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let r=t.positiveCounterexamples;r.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),r.length>ie&&e.push(`positiveCounterexamples must contain at most ${ie} items, got ${r.length}`);for(let n=0;n<r.length;n++)e.push(...ae(r[n],`positiveCounterexamples[${n}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...ce(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Pe,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...ce(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let r=t.sourceNegativeCase,n=t.positiveCounterexamples,s=D({toolName:r.toolName,params:r.params,ruleContext:r.ruleContext});for(let o=0;o<n.length;o++){let i=n[o];i!==void 0&&D({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Be(e)}var Fe="OwnerEvidenceScopeError";function b(t,e){let r=new Error(e);return r.name=Fe,Object.assign(r,{ownerEvidenceScopeKind:t}),r}var Xe=new Set(["success","failure","blocked"]);function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function We(t){return typeof t=="string"&&Xe.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function ue(t,e,r){let{projectDir:n,toolSemantics:s}=r,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!We(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let _=i.paramsJson;if(typeof _!="string")return A(`row id=${i.id}: params_json must be a string`);let g;try{g=JSON.parse(_)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!$e(g))return A(`row id=${i.id}: params_json must parse to a non-array object`);let E=s.resolve(c),{normalizedPath:S}=w(c,g,n,{canonicalKind:E});o.push({sequenceId:i.id,toolName:c,canonicalKind:E,normalizedPath:S===""?null:S,paramsSummary:g,outcome:a})}return{status:"available",truncated:e,calls:o}}var He=3,Ye=5,Ke=100,_e=new Set(["__proto__","constructor","prototype"]);function M(t,e){try{return e()}catch(r){let n=r instanceof Error?r.message:String(r);throw b("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function Ge(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t){for(let e of Object.keys(t))if(_e.has(e))return!1;return!0}function ze(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>He)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(r=>!Number.isSafeInteger(r)||r<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function de(t,e){if(!t)throw b("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function Je(t,e,r){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Ge(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!qe(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:n,expectedDecision:r}}function Ve(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var Ze=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Qe(t){if(t.length<20)return!1;for(let e of Ze)if(e.test(t))return!0;return!1}function et(t,e){let r=[],n={};for(let s of Object.keys(t)){if(_e.has(s))continue;let o=t[s];if(typeof o!="string"){n[s]=o;continue}if(Ve(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",r.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(Qe(o)){n[s]="<redacted:secret>",r.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:r}}var P=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let r=M(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!r)throw b("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ze(e);let n=de(M(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(E=>de(M(`evidence row read for id=${E}`,()=>this.db.getRuleHostEvidenceRow(E)),E));for(let E of[n,...s])if(E.sessionId!==r.sessionId)throw b("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${E.id} session mismatch; all examples must belong to pain session ${r.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(E=>this.buildSelectedCase(E,"positive",i)),_={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${r.id}`,`tool_call:${n.id}`,...s.map(E=>`tool_call:${E.id}`)].slice(0,Ye),redactionNotes:o},g=Y(_);if(!g.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${g.errors.join("; ")} (ERR-069 fail loud)`);return _}buildSelectedCase(e,r,n){let{projectDir:s,redactionNotes:o}=n,i=Je(e,r,r==="negative"?"block":"allow"),c=et(i.params,s);o.push(...c.notes);let a=M(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Ke)),_=ue(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),g=w(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),E={version:2,history:_,facts:se(_,g.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:E}}};import ht from"better-sqlite3";import p from"fs";import f from"path";import J from"crypto";import*as d from"fs";import*as me from"path";var K=class extends Error{filePath;lockPath;constructor(e,r,n){super(e),this.name="LockAcquisitionError",this.filePath=r,this.lockPath=n}},tt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Ee(t){try{return process.kill(t,0),!0}catch{return!1}}function pe(t,e){try{let r=me.dirname(t);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let n=d.constants.O_WRONLY|d.constants.O_CREAT|d.constants.O_EXCL,s=d.openSync(t,n);return d.writeSync(s,String(e)),d.fsyncSync(s),d.closeSync(s),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}}function I(t){try{let e=d.readFileSync(t,"utf8"),r=parseInt(e.trim(),10);return Number.isNaN(r)?null:r}catch{return null}}function rt(t,e){try{I(t)===e&&d.unlinkSync(t)}catch{}}function nt(t,e){try{let r=d.statSync(t),n=I(t),s=Date.now()-r.mtimeMs>e,o=n===null||!Ee(n);if(s||o)try{return d.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function st(t,e,r){let n=Math.min(e*Math.pow(2,t),r),s=n*.2*Math.random();return Math.floor(n+s)}function ot(t){let e=Date.now()+t;for(;Date.now()<e;);}function it(t,e){let r=I(e),n=r!==null?Ee(r)?`alive (PID ${r})`:`dead (PID ${r})`:"unknown";return new K(`Failed to acquire lock for ${t}. Lock holder: ${n}.`,t,e)}function at(t,e,r){let n=t+e.lockSuffix;return pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:(nt(n,e.lockStaleMs),pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:null)}function ct(t,e={}){let r={...tt,...e},{pid:n}=process;for(let s=0;s<r.maxRetries;s++){let o=at(t,r,n);if(o)return o;if(s<r.maxRetries-1){let i=st(s,r.baseRetryDelayMs,r.maxRetryDelayMs);ot(i)}}throw it(t,t+r.lockSuffix)}function lt(t){rt(t.lockPath,t.pid)}function Te(t,e,r={}){let n=ct(t,r);try{return e()}finally{lt(n)}}import*as R from"fs";var fe=3,ut=50;function j(t,e){let r=t+".tmp";R.writeFileSync(r,e,"utf8");let n;for(let s=0;s<fe;s++)try{R.renameSync(r,t);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<fe-1){let c=ut*Math.pow(2,s),a=Date.now()+c,_=!1;for(;Date.now()<a;)if(!_&&Date.now()>=a-10){try{ve("fs").accessSync?.(r)}catch{}_=!0}}continue}break}try{R.unlinkSync(r)}catch{}throw n}import*as h from"path";var l=(...t)=>h.posix.join(...t);function dt(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function _t(t,e){return dt(t)?h.win32.join(t,e):t.startsWith("/")?h.posix.join(t,e):h.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},pt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(t,e){return _t(t,pt[e])}var mt={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},G=class extends Error{constructor(r,n,s){super(r,s);this.code=n;this.name="PdError",this.category=mt[n]??"execution_failed"}code;category};var v=class extends G{constructor(e,r){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",r),this.name="SampleNotFoundError"}};var Et=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function T(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function Tt(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ge(t,e={}){let r=[],n=[...Et];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!T(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!T(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),Tt(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!T(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!T(s))throw s}}return t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:r}}import*as q from"path";import*as Se from"os";var ft=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],gt=q.join(Se.tmpdir(),".pd-test-quarantine");function St(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return ft.some(r=>r.test(e))}function he(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!St(t))return t;let r=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;r.startsWith("_");)r=r.slice(1);for(;r.endsWith("_");)r=r.slice(0,-1);return q.join(gt,r)}var Ot=16*1024,Rt=5e3,yt=7;function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Nt(t){return!ye(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function bt(t){let e=ge(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function m(){return new Date().toISOString()}function y(t){return JSON.stringify(t??{})}function Oe(t){try{return p.existsSync(t)?p.statSync(t).size:0}catch{return 0}}function At(t){return t.length>240?`${t.slice(0,237)}...`:t}function Re(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function It(t){let e=[],r=!1;try{let n=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(n))e=n.filter(s=>typeof s=="string");else if(n!==null&&typeof n=="object"){let s=n;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),r=!0)}}}catch{e=[],r=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:r,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var U=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=he(f.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Ot,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??yt)*24*60*60*1e3),p.mkdirSync(this.stateDir,{recursive:!0}),p.mkdirSync(this.blobDir,{recursive:!0}),p.mkdirSync(this.exportDir,{recursive:!0}),this.db=new ht(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Rt)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let r=e.startedAt??m();this.withWrite(()=>{this.db.prepare(`
2
+ var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function C(t,e=!1){let r=[];for(let n of t.split("/").filter(s=>s.length>0))n!=="."&&(n===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e&&r.push(".."):r.push(n));return r}function F(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let r=t.slice(2).split("/").filter(o=>o.length>0),n=r[0]??"",s=r[1]??"";return{kind:"unc",root:`unc:${n}/${s}`,segments:C(r.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ee(t,e,r){return t.length<e.length?!1:e.every((n,s)=>{let o=t[s]??"";return r?o.toLowerCase()===n.toLowerCase():o===n})}function Le(t,e,r){let n=0;for(;n<t.length&&n<e.length;){let o=t[n]??"",i=e[n]??"";if(!(r?o.toLowerCase()===i.toLowerCase():o===i))break;n++}return[...Array.from({length:t.length-n},()=>".."),...e.slice(n)].join("/")||"."}function te(t){let[e,r]=t.root.slice(4).split("/"),n=t.segments.join("/");return`//${e??""}/${r??""}${n?`/${n}`:""}`}function re(t,e,r){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return r;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ee(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?te(t):r:t.segments.slice(e.segments.length).join("/")||".";let n=[...e.segments];for(let o of r.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e.kind==="relative"&&n.push(".."):n.push(o));let s=e.kind==="drive"||e.kind==="unc";return ee(n,e.segments,s)?n.slice(e.segments.length).join("/")||".":Le(e.segments,n,s)}function ve(t,e){if(!t||typeof t!="string")return"";let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/");if(r.startsWith("<tool:")&&r.endsWith(">"))return r;let s=F(r),o=F(n);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=F(c),re(s,o,c)}return re(s,o,r)}function Ce(t,e){let r=t.file_path||t.path||t.file||t.target;if(typeof r=="string"&&r.length>0)return{value:r,isPath:!0};if(e.isBashTool){let n=String(t.command||t.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?{value:s[1],isPath:!0}:{value:n,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function we(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function ke(t){if(t.canonicalKind===void 0)return t;let e=we(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function w(t,e,r,n={}){let s=ke(n),o=Ce(e,{...s,toolName:t}),i=o.isPath?ve(o.value,r):o.value;return{toolName:t,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function ne(t){return typeof t=="string"&&X.has(t)}var k=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function se(t,e,r){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let _=a.canonicalKind;_==="read"||_==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):_==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:r}}var oe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(oe);var $={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($.calls);Object.freeze($);var De={version:2,history:$,facts:oe};Object.freeze(De);var Me=new Set(["__proto__","constructor","prototype"]),ie=3,Pe=5,je=new Set(["allow","block","propose_correction"]),Ue={valid:!0,errors:[]};function W(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function le(t){for(let e of Object.keys(t))if(Me.has(e))return!1;return!0}function Be(t){return t.length===0?Ue:{valid:!1,errors:t}}function H(t){return typeof t=="string"&&t.trim().length>0}function ae(t,e,r){let n=[];return W(t)?le(t)?((!Object.hasOwn(t,"caseId")||!H(t.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==r)&&n.push(`${e}.kind must be '${r}'`),(!Object.hasOwn(t,"toolName")||!H(t.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!W(t.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!je.has(t.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):r==="positive"&&t.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ce(t,e){let{fieldName:r,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${r} must be an array`),o;s&&t.length===0&&o.push(`${r} must contain at least 1 item`),n!==void 0&&t.length>n&&o.push(`${r} must contain at most ${n} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${r}[${i}] must be a string`);return o}function D(t){return Array.isArray(t)?`[${t.map(e=>D(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(r=>r!=="__proto__"&&r!=="constructor"&&r!=="prototype").sort().map(r=>`${JSON.stringify(r)}:${D(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){if(!W(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!le(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...ae(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!H(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let r=t.positiveCounterexamples;r.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),r.length>ie&&e.push(`positiveCounterexamples must contain at most ${ie} items, got ${r.length}`);for(let n=0;n<r.length;n++)e.push(...ae(r[n],`positiveCounterexamples[${n}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...ce(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Pe,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...ce(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let r=t.sourceNegativeCase,n=t.positiveCounterexamples,s=D({toolName:r.toolName,params:r.params,ruleContext:r.ruleContext});for(let o=0;o<n.length;o++){let i=n[o];i!==void 0&&D({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Be(e)}var Fe="OwnerEvidenceScopeError";function N(t,e){let r=new Error(e);return r.name=Fe,Object.assign(r,{ownerEvidenceScopeKind:t}),r}var Xe=new Set(["success","failure","blocked"]);function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function We(t){return typeof t=="string"&&Xe.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function ue(t,e,r){let{projectDir:n,toolSemantics:s}=r,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!We(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let _=i.paramsJson;if(typeof _!="string")return A(`row id=${i.id}: params_json must be a string`);let g;try{g=JSON.parse(_)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!$e(g))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:S}=w(c,g,n,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:S===""?null:S,paramsSummary:g,outcome:a})}return{status:"available",truncated:e,calls:o}}var He=3,Ye=5,Ke=100,_e=new Set(["__proto__","constructor","prototype"]);function M(t,e){try{return e()}catch(r){let n=r instanceof Error?r.message:String(r);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function Ge(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t){for(let e of Object.keys(t))if(_e.has(e))return!1;return!0}function ze(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>He)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(r=>!Number.isSafeInteger(r)||r<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function de(t,e){if(!t)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function Je(t,e,r){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Ge(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!qe(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:n,expectedDecision:r}}function Ve(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var Ze=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Qe(t){if(t.length<20)return!1;for(let e of Ze)if(e.test(t))return!0;return!1}function et(t,e){let r=[],n={};for(let s of Object.keys(t)){if(_e.has(s))continue;let o=t[s];if(typeof o!="string"){n[s]=o;continue}if(Ve(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",r.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(Qe(o)){n[s]="<redacted:secret>",r.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:r}}var P=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let r=M(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!r)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ze(e);let n=de(M(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>de(M(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[n,...s])if(m.sessionId!==r.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${r.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),_={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${r.id}`,`tool_call:${n.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,Ye),redactionNotes:o},g=Y(_);if(!g.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${g.errors.join("; ")} (ERR-069 fail loud)`);return _}buildSelectedCase(e,r,n){let{projectDir:s,redactionNotes:o}=n,i=Je(e,r,r==="negative"?"block":"allow"),c=et(i.params,s);o.push(...c.notes);let a=M(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Ke)),_=ue(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),g=w(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:_,facts:se(_,g.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import ht from"better-sqlite3";import p from"fs";import T from"path";import J from"crypto";import*as d from"fs";import*as fe from"path";var K=class extends Error{filePath;lockPath;constructor(e,r,n){super(e),this.name="LockAcquisitionError",this.filePath=r,this.lockPath=n}},tt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function me(t){try{return process.kill(t,0),!0}catch{return!1}}function pe(t,e){try{let r=fe.dirname(t);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let n=d.constants.O_WRONLY|d.constants.O_CREAT|d.constants.O_EXCL,s=d.openSync(t,n);return d.writeSync(s,String(e)),d.fsyncSync(s),d.closeSync(s),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}}function I(t){try{let e=d.readFileSync(t,"utf8"),r=parseInt(e.trim(),10);return Number.isNaN(r)?null:r}catch{return null}}function rt(t,e){try{I(t)===e&&d.unlinkSync(t)}catch{}}function nt(t,e){try{let r=d.statSync(t),n=I(t),s=Date.now()-r.mtimeMs>e,o=n===null||!me(n);if(s||o)try{return d.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function st(t,e,r){let n=Math.min(e*Math.pow(2,t),r),s=n*.2*Math.random();return Math.floor(n+s)}function ot(t){let e=Date.now()+t;for(;Date.now()<e;);}function it(t,e){let r=I(e),n=r!==null?me(r)?`alive (PID ${r})`:`dead (PID ${r})`:"unknown";return new K(`Failed to acquire lock for ${t}. Lock holder: ${n}.`,t,e)}function at(t,e,r){let n=t+e.lockSuffix;return pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:(nt(n,e.lockStaleMs),pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:null)}function ct(t,e={}){let r={...tt,...e},{pid:n}=process;for(let s=0;s<r.maxRetries;s++){let o=at(t,r,n);if(o)return o;if(s<r.maxRetries-1){let i=st(s,r.baseRetryDelayMs,r.maxRetryDelayMs);ot(i)}}throw it(t,t+r.lockSuffix)}function lt(t){rt(t.lockPath,t.pid)}function Ee(t,e,r={}){let n=ct(t,r);try{return e()}finally{lt(n)}}import*as O from"fs";var Te=3,ut=50;function j(t,e){let r=t+".tmp";O.writeFileSync(r,e,"utf8");let n;for(let s=0;s<Te;s++)try{O.renameSync(r,t);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Te-1){let c=ut*Math.pow(2,s),a=Date.now()+c,_=!1;for(;Date.now()<a;)if(!_&&Date.now()>=a-10){try{xe("fs").accessSync?.(r)}catch{}_=!0}}continue}break}try{O.unlinkSync(r)}catch{}throw n}import*as h from"path";var l=(...t)=>h.posix.join(...t);function dt(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function _t(t,e){return dt(t)?h.win32.join(t,e):t.startsWith("/")?h.posix.join(t,e):h.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},pt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function R(t,e){return _t(t,pt[e])}var ft={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},G=class extends Error{constructor(r,n,s){super(r,s);this.code=n;this.name="PdError",this.category=ft[n]??"execution_failed"}code;category};var x=class extends G{constructor(e,r){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",r),this.name="SampleNotFoundError"}};var mt=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function Et(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ge(t,e={}){let r=[],n=[...mt];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),Et(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:r}}import*as q from"path";import*as Se from"os";var Tt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],gt=q.join(Se.tmpdir(),".pd-test-quarantine");function St(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return Tt.some(r=>r.test(e))}function he(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!St(t))return t;let r=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;r.startsWith("_");)r=r.slice(1);for(;r.endsWith("_");)r=r.slice(0,-1);return q.join(gt,r)}var Rt=16*1024,Ot=5e3,yt=7;function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bt(t){return!ye(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function Nt(t){let e=ge(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function f(){return new Date().toISOString()}function y(t){return JSON.stringify(t??{})}function Re(t){try{return p.existsSync(t)?p.statSync(t).size:0}catch{return 0}}function At(t){return t.length>240?`${t.slice(0,237)}...`:t}function Oe(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function It(t){let e=[],r=!1;try{let n=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(n))e=n.filter(s=>typeof s=="string");else if(n!==null&&typeof n=="object"){let s=n;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),r=!0)}}}catch{e=[],r=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:r,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var U=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=he(T.resolve(e.workspaceDir)),this.stateDir=R(this.workspaceDir,"STATE_DIR"),this.dbPath=R(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=R(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=R(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Rt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??yt)*24*60*60*1e3),p.mkdirSync(this.stateDir,{recursive:!0}),p.mkdirSync(this.blobDir,{recursive:!0}),p.mkdirSync(this.exportDir,{recursive:!0}),this.db=new ht(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Ot)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let r=e.startedAt??f();this.withWrite(()=>{this.db.prepare(`
3
3
  INSERT INTO sessions (session_id, started_at, updated_at)
4
4
  VALUES (?, ?, ?)
5
5
  ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
6
- `).run(e.sessionId,r,m())})}recordAssistantTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=this.storeRawText("assistant",e.rawText),n=e.createdAt??m();return this.withWrite(()=>{let s=this.db.prepare(`
6
+ `).run(e.sessionId,r,f())})}recordAssistantTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=this.storeRawText("assistant",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{let s=this.db.prepare(`
7
7
  INSERT INTO assistant_turns (
8
8
  session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
9
9
  empathy_signal_json, blob_ref, raw_excerpt, stop_reason, thinking_blocks_count, created_at
10
10
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
11
- `).run(e.sessionId,e.runId,e.provider,e.model,r.inlineText,e.sanitizedText,y(e.usageJson),y(e.empathySignalJson),r.blobRef,r.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=this.storeRawText("user",e.rawText),n=e.createdAt??m();return this.withWrite(()=>{let s=this.db.prepare(`
11
+ `).run(e.sessionId,e.runId,e.provider,e.model,r.inlineText,e.sanitizedText,y(e.usageJson),y(e.empathySignalJson),r.blobRef,r.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=this.storeRawText("user",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{let s=this.db.prepare(`
12
12
  INSERT INTO user_turns (
13
13
  session_id, turn_index, raw_text, blob_ref, raw_excerpt,
14
14
  correction_detected, correction_cue, references_assistant_turn_id, created_at
@@ -17,7 +17,7 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
17
17
  UPDATE user_turns
18
18
  SET correction_detected = 1, correction_cue = ?
19
19
  WHERE id = ?
20
- `).run(r??null,e));return Number(n.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=e.createdAt??m(),n=this.withWrite(()=>{let s=this.db.prepare(`
20
+ `).run(r??null,e));return Number(n.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=e.createdAt??f(),n=this.withWrite(()=>{let s=this.db.prepare(`
21
21
  INSERT INTO tool_calls (
22
22
  session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
23
23
  gfi_before, gfi_after, params_json, result_preview, created_at
@@ -27,7 +27,7 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
27
27
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
28
28
  canonical_pain_id, runtime_task_id, host_kind
29
29
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
30
- `).run(e.sessionId,e.source,e.score,e.reason??null,e.severity??null,e.origin??null,e.confidence??null,e.text??null,e.createdAt??m(),e.canonicalPainId??null,e.runtimeTaskId??null,e.hostKind??null);r=Number(n.lastInsertRowid)}catch(n){if(e.canonicalPainId&&n instanceof Error&&n.message.includes("UNIQUE constraint failed")&&n.message.includes("canonical_pain_id")){this.db.prepare(`
30
+ `).run(e.sessionId,e.source,e.score,e.reason??null,e.severity??null,e.origin??null,e.confidence??null,e.text??null,e.createdAt??f(),e.canonicalPainId??null,e.runtimeTaskId??null,e.hostKind??null);r=Number(n.lastInsertRowid)}catch(n){if(e.canonicalPainId&&n instanceof Error&&n.message.includes("UNIQUE constraint failed")&&n.message.includes("canonical_pain_id")){this.db.prepare(`
31
31
  UPDATE pain_events
32
32
  SET runtime_task_id = COALESCE(?, runtime_task_id),
33
33
  host_kind = COALESCE(host_kind, ?)
@@ -35,16 +35,16 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
35
35
  `).run(e.runtimeTaskId??null,e.hostKind??null,e.canonicalPainId);let s=this.db.prepare("SELECT id FROM pain_events WHERE canonical_pain_id = ?").get(e.canonicalPainId);s&&typeof s=="object"&&Object.hasOwn(s,"id")&&typeof s.id=="number"?r=s.id:r=-1}else throw n}}),r}recordGateBlock(e){this.withWrite(()=>{this.db.prepare(`
36
36
  INSERT INTO gate_blocks (session_id, tool_name, file_path, reason, created_at)
37
37
  VALUES (?, ?, ?, ?, ?)
38
- `).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??m())})}recordTrustChange(e){this.withWrite(()=>{this.db.prepare(`
38
+ `).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??f())})}recordTrustChange(e){this.withWrite(()=>{this.db.prepare(`
39
39
  INSERT INTO trust_changes (session_id, previous_score, new_score, delta, reason, created_at)
40
40
  VALUES (?, ?, ?, ?, ?, ?)
41
- `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??m())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
41
+ `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??f())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
42
42
  INSERT INTO principle_events (principle_id, event_type, payload_json, created_at)
43
43
  VALUES (?, ?, ?, ?)
44
- `).run(e.principleId??null,e.eventType,y(e.payload),e.createdAt??m())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
44
+ `).run(e.principleId??null,e.eventType,y(e.payload),e.createdAt??f())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
45
45
  INSERT INTO task_outcomes (session_id, task_id, outcome, summary, principle_ids_json, created_at)
46
46
  VALUES (?, ?, ?, ?, ?, ?)
47
- `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,y(e.principleIdsJson),e.createdAt??m())})}evolutionTableMissing(e){let r=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!r||typeof r.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let r=[],n=[];e.status&&(r.push("status = ?"),n.push(e.status)),e.dateFrom&&(r.push("created_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(r.push("created_at <= ?"),n.push(e.dateTo));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"",o=e.limit??50,i=e.offset??0;return this.db.prepare(`
47
+ `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,y(e.principleIdsJson),e.createdAt??f())})}evolutionTableMissing(e){let r=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!r||typeof r.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let r=[],n=[];e.status&&(r.push("status = ?"),n.push(e.status)),e.dateFrom&&(r.push("created_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(r.push("created_at <= ?"),n.push(e.dateTo));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"",o=e.limit??50,i=e.offset??0;return this.db.prepare(`
48
48
  SELECT id, task_id, trace_id, source, reason, score, status,
49
49
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
50
50
  task_kind, priority, retry_count, max_retries, last_error, result_ref
@@ -118,7 +118,7 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
118
118
  FROM pain_events
119
119
  WHERE canonical_pain_id = ?
120
120
  LIMIT 1
121
- `).get(e);return Nt(r)?{id:r.id,sessionId:r.session_id,source:String(r.source),score:Number(r.score),reason:r.reason?String(r.reason):null,severity:r.severity?String(r.severity):null,origin:r.origin?String(r.origin):null,confidence:r.confidence!=null?Number(r.confidence):null,text:r.text?String(r.text):null,canonicalPainId:String(r.canonical_pain_id),runtimeTaskId:r.runtime_task_id?String(r.runtime_task_id):null,createdAt:String(r.created_at)}:null}listUserTurnsForSession(e){return this.db.prepare(`
121
+ `).get(e);return bt(r)?{id:r.id,sessionId:r.session_id,source:String(r.source),score:Number(r.score),reason:r.reason?String(r.reason):null,severity:r.severity?String(r.severity):null,origin:r.origin?String(r.origin):null,confidence:r.confidence!=null?Number(r.confidence):null,text:r.text?String(r.text):null,canonicalPainId:String(r.canonical_pain_id),runtimeTaskId:r.runtime_task_id?String(r.runtime_task_id):null,createdAt:String(r.created_at)}:null}listUserTurnsForSession(e){return this.db.prepare(`
122
122
  SELECT id, turn_index, raw_excerpt, correction_detected, correction_cue, created_at
123
123
  FROM user_turns
124
124
  WHERE session_id = ?
@@ -146,20 +146,20 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
146
146
  LEFT JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
147
147
  WHERE cs.session_id = ?
148
148
  ORDER BY cs.created_at DESC
149
- `).all(e).map(n=>({correctionCue:n.correction_cue?String(n.correction_cue):null}))}reviewCorrectionSample(e,r,n){let s=m();if(!this.withWrite(()=>this.db.prepare(`
149
+ `).all(e).map(n=>({correctionCue:n.correction_cue?String(n.correction_cue):null}))}reviewCorrectionSample(e,r,n){let s=f();if(!this.withWrite(()=>this.db.prepare(`
150
150
  UPDATE correction_samples
151
151
  SET review_status = ?, updated_at = ?
152
152
  WHERE sample_id = ?
153
153
  `).run(r,s,e).changes===0?!1:(this.db.prepare(`
154
154
  INSERT INTO sample_reviews (sample_id, review_status, note, created_at)
155
155
  VALUES (?, ?, ?, ?)
156
- `).run(e,r,n??null,s),!0)))throw new v(e);let i=this.db.prepare(`
156
+ `).run(e,r,n??null,s),!0)))throw new x(e);let i=this.db.prepare(`
157
157
  SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
158
158
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
159
159
  review_status, export_mode, created_at, updated_at
160
160
  FROM correction_samples
161
161
  WHERE sample_id = ?
162
- `).get(e);if(!i)throw new v(`${e} (after update)`);return r==="rejected"&&this.recordCorrectionRejectedPain({session_id:i.session_id,quality_score:i.quality_score,diff_excerpt:i.diff_excerpt,principle_ids_json:i.principle_ids_json,created_at:i.created_at}),{sampleId:String(i.sample_id),sessionId:String(i.session_id),badAssistantTurnId:Number(i.bad_assistant_turn_id),userCorrectionTurnId:Number(i.user_correction_turn_id),recoveryToolSpanJson:String(i.recovery_tool_span_json),diffExcerpt:String(i.diff_excerpt??""),principleIdsJson:String(i.principle_ids_json??"[]"),qualityScore:Number(i.quality_score),reviewStatus:i.review_status,exportMode:i.export_mode,createdAt:String(i.created_at),updatedAt:String(i.updated_at)}}recordCorrectionRejectedPain(e){let r=String(e.session_id),n=Number(e.quality_score),s=String(e.diff_excerpt??""),o=String(e.principle_ids_json??"[]"),i=Math.max(0,Math.min(100,Math.round(Number(n)||0))),c=`Correction rejected (quality ${n.toFixed(2)}). Principles: ${o}${s?` \u2014 ${s.slice(0,120)}`:""}`;try{this.recordPainEvent({sessionId:r,source:"correction_rejected",score:i,reason:c,severity:i>=70?"severe":i>=40?"moderate":"mild",origin:"system_infer",text:s||void 0,createdAt:String(e.created_at),hostKind:"openclaw"})}catch(a){console.warn(`[Trajectory] Failed to record correction_rejected pain event: ${String(a)}`)}}enqueueSignalConfirmation(e){let r=`sq_${J.createHash("sha256").update(`${e.sessionId}:${e.userTurnRowid}`).digest("hex").slice(0,12)}`;this.withWrite(()=>{this.db.prepare(`
162
+ `).get(e);if(!i)throw new x(`${e} (after update)`);return r==="rejected"&&this.recordCorrectionRejectedPain({session_id:i.session_id,quality_score:i.quality_score,diff_excerpt:i.diff_excerpt,principle_ids_json:i.principle_ids_json,created_at:i.created_at}),{sampleId:String(i.sample_id),sessionId:String(i.session_id),badAssistantTurnId:Number(i.bad_assistant_turn_id),userCorrectionTurnId:Number(i.user_correction_turn_id),recoveryToolSpanJson:String(i.recovery_tool_span_json),diffExcerpt:String(i.diff_excerpt??""),principleIdsJson:String(i.principle_ids_json??"[]"),qualityScore:Number(i.quality_score),reviewStatus:i.review_status,exportMode:i.export_mode,createdAt:String(i.created_at),updatedAt:String(i.updated_at)}}recordCorrectionRejectedPain(e){let r=String(e.session_id),n=Number(e.quality_score),s=String(e.diff_excerpt??""),o=String(e.principle_ids_json??"[]"),i=Math.max(0,Math.min(100,Math.round(Number(n)||0))),c=`Correction rejected (quality ${n.toFixed(2)}). Principles: ${o}${s?` \u2014 ${s.slice(0,120)}`:""}`;try{this.recordPainEvent({sessionId:r,source:"correction_rejected",score:i,reason:c,severity:i>=70?"severe":i>=40?"moderate":"mild",origin:"system_infer",text:s||void 0,createdAt:String(e.created_at),hostKind:"openclaw"})}catch(a){console.warn(`[Trajectory] Failed to record correction_rejected pain event: ${String(a)}`)}}enqueueSignalConfirmation(e){let r=`sq_${J.createHash("sha256").update(`${e.sessionId}:${e.userTurnRowid}`).digest("hex").slice(0,12)}`;this.withWrite(()=>{this.db.prepare(`
163
163
  INSERT OR IGNORE INTO signal_confirmations (
164
164
  id, session_id, user_turn_rowid, occurrence_id, excerpt,
165
165
  terms_json, suggested_type, status, attempts, created_at
@@ -176,7 +176,7 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
176
176
  UPDATE signal_confirmations
177
177
  SET status = ?, resolved_at = ?, resolution = ?
178
178
  WHERE id = ? AND status = 'pending'
179
- `).run(r,m(),n.slice(0,500),e));return Number(s.changes)>0}countPendingSignalConfirmations(){return this.db.prepare("SELECT COUNT(*) AS n FROM signal_confirmations WHERE status = 'pending'").get().n}exportCorrections(e){let r=this.db.prepare(`
179
+ `).run(r,f(),n.slice(0,500),e));return Number(s.changes)>0}countPendingSignalConfirmations(){return this.db.prepare("SELECT COUNT(*) AS n FROM signal_confirmations WHERE status = 'pending'").get().n}exportCorrections(e){let r=this.db.prepare(`
180
180
  SELECT cs.sample_id, cs.session_id, cs.recovery_tool_span_json, cs.diff_excerpt, cs.quality_score,
181
181
  at.raw_text AS assistant_raw_text, at.blob_ref AS assistant_blob_ref, at.sanitized_text,
182
182
  ut.raw_text AS user_raw_text, ut.blob_ref AS user_blob_ref, ut.correction_cue
@@ -185,16 +185,16 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
185
185
  JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
186
186
  WHERE (? = 0 OR cs.review_status = 'approved')
187
187
  ORDER BY cs.created_at ASC
188
- `).all(e.approvedOnly?1:0),n=f.join(this.exportDir,`corrections-${Date.now()}-${e.mode}.jsonl`),s=r.map(o=>{let i=this.restoreRawText(o.assistant_raw_text,o.assistant_blob_ref),c=this.restoreRawText(o.user_raw_text,o.user_blob_ref),a=e.mode==="redacted"?Re(i):i,_=e.mode==="redacted"?Re(c):c;return JSON.stringify({sample_id:o.sample_id,session_id:o.session_id,instruction:_,input_context:a,bad_attempt_summary:String(o.diff_excerpt??""),preferred_response:_,labels:{correction_cue:o.correction_cue,quality_score:o.quality_score},metadata:{mode:e.mode,recovery_tool_span_json:o.recovery_tool_span_json}})});return j(n,`${s.join(`
188
+ `).all(e.approvedOnly?1:0),n=T.join(this.exportDir,`corrections-${Date.now()}-${e.mode}.jsonl`),s=r.map(o=>{let i=this.restoreRawText(o.assistant_raw_text,o.assistant_blob_ref),c=this.restoreRawText(o.user_raw_text,o.user_blob_ref),a=e.mode==="redacted"?Oe(i):i,_=e.mode==="redacted"?Oe(c):c;return JSON.stringify({sample_id:o.sample_id,session_id:o.session_id,instruction:_,input_context:a,bad_attempt_summary:String(o.diff_excerpt??""),preferred_response:_,labels:{correction_cue:o.correction_cue,quality_score:o.quality_score},metadata:{mode:e.mode,recovery_tool_span_json:o.recovery_tool_span_json}})});return j(n,`${s.join(`
189
189
  `)}${s.length>0?`
190
- `:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,n,r.length),{filePath:n,count:r.length,mode:e.mode}}exportAnalytics(){let e={generatedAt:m(),stats:this.getDataStats(),dailyMetrics:this.dailyMetrics(),errorClusters:this.db.prepare("SELECT * FROM v_error_clusters").all(),principleEffectiveness:this.db.prepare("SELECT * FROM v_principle_effectiveness").all(),sampleQueue:this.db.prepare("SELECT * FROM v_sample_queue").all()},r=f.join(this.exportDir,`analytics-${Date.now()}.json`);return j(r,JSON.stringify(e,null,2)),this.recordExportAudit("analytics","raw",!0,r,Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0),{filePath:r,count:Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0}}getDataStats(){let e=(n,s)=>{let o=s?`SELECT COUNT(*) as count FROM ${n} WHERE ${s}`:`SELECT COUNT(*) as count FROM ${n}`;return Number(this.db.prepare(o).get().count)},r=this.db.prepare(`
190
+ `:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,n,r.length),{filePath:n,count:r.length,mode:e.mode}}exportAnalytics(){let e={generatedAt:f(),stats:this.getDataStats(),dailyMetrics:this.dailyMetrics(),errorClusters:this.db.prepare("SELECT * FROM v_error_clusters").all(),principleEffectiveness:this.db.prepare("SELECT * FROM v_principle_effectiveness").all(),sampleQueue:this.db.prepare("SELECT * FROM v_sample_queue").all()},r=T.join(this.exportDir,`analytics-${Date.now()}.json`);return j(r,JSON.stringify(e,null,2)),this.recordExportAudit("analytics","raw",!0,r,Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0),{filePath:r,count:Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0}}getDataStats(){let e=(n,s)=>{let o=s?`SELECT COUNT(*) as count FROM ${n} WHERE ${s}`:`SELECT COUNT(*) as count FROM ${n}`;return Number(this.db.prepare(o).get().count)},r=this.db.prepare(`
191
191
  SELECT MAX(ts) AS ts FROM (
192
192
  SELECT MAX(created_at) AS ts FROM assistant_turns
193
193
  UNION ALL SELECT MAX(created_at) AS ts FROM user_turns
194
194
  UNION ALL SELECT MAX(created_at) AS ts FROM tool_calls
195
195
  UNION ALL SELECT MAX(created_at) AS ts FROM pain_events
196
196
  )
197
- `).get();return{dbPath:this.dbPath,dbSizeBytes:Oe(this.dbPath),assistantTurns:e("assistant_turns"),userTurns:e("user_turns"),toolCalls:e("tool_calls"),painEvents:e("pain_events"),pendingSamples:e("correction_samples","review_status = 'pending'"),approvedSamples:e("correction_samples","review_status = 'approved'"),blobBytes:this.computeBlobBytes(),lastIngestAt:r.ts??null}}cleanupBlobStorage(){return this.pruneUnreferencedBlobs()}initSchema(){let e=bt(this.db);for(let n of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${n}`);let r=this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();this.migrateSchema(r?.version),r?r.version!==1&&this.db.prepare("UPDATE schema_version SET version = ?").run(1):this.db.prepare("INSERT INTO schema_version (version) VALUES (?)").run(1)}importLegacyArtifacts(){this.importLegacySessions(),this.importLegacyEvents(),this.importLegacyEvolution()}migrateSchema(e){this.db.exec(`
197
+ `).get();return{dbPath:this.dbPath,dbSizeBytes:Re(this.dbPath),assistantTurns:e("assistant_turns"),userTurns:e("user_turns"),toolCalls:e("tool_calls"),painEvents:e("pain_events"),pendingSamples:e("correction_samples","review_status = 'pending'"),approvedSamples:e("correction_samples","review_status = 'approved'"),blobBytes:this.computeBlobBytes(),lastIngestAt:r.ts??null}}cleanupBlobStorage(){return this.pruneUnreferencedBlobs()}initSchema(){let e=Nt(this.db);for(let n of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${n}`);let r=this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();this.migrateSchema(r?.version),r?r.version!==1&&this.db.prepare("UPDATE schema_version SET version = ?").run(1):this.db.prepare("INSERT INTO schema_version (version) VALUES (?)").run(1)}importLegacyArtifacts(){this.importLegacySessions(),this.importLegacyEvents(),this.importLegacyEvolution()}migrateSchema(e){this.db.exec(`
198
198
  DROP VIEW IF EXISTS v_daily_metrics;
199
199
  CREATE VIEW IF NOT EXISTS v_daily_metrics AS
200
200
  WITH tool_daily AS (
@@ -219,13 +219,13 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
219
219
  COALESCE(correction_daily.user_corrections, 0) AS user_corrections
220
220
  FROM tool_daily
221
221
  LEFT JOIN correction_daily ON correction_daily.day = tool_daily.day;
222
- `)}dailyMetrics(){return this.db.prepare("SELECT * FROM v_daily_metrics ORDER BY day ASC").all()}importLegacySessions(){let e="legacy:sessions";if(this.isImported(e))return;let r=O(this.workspaceDir,"SESSION_DIR");if(p.existsSync(r)){for(let n of p.readdirSync(r).filter(s=>s.endsWith(".json")))try{let s=JSON.parse(p.readFileSync(f.join(r,n),"utf8"));if(s.sessionId){let o=typeof s.lastActivityAt=="number"?new Date(s.lastActivityAt).toISOString():m();this.recordSession({sessionId:s.sessionId,startedAt:o})}}catch{}this.markImported(e)}}importLegacyEvents(){let e="legacy:events";if(this.isImported(e))return;let r=f.join(this.stateDir,"logs","events.jsonl");if(!p.existsSync(r))return;let n=p.readFileSync(r,"utf8").trim();if(!n){this.markImported(e);return}for(let s of n.split(`
223
- `))try{let o=JSON.parse(s);o.type==="pain_signal"&&o.sessionId&&this.recordPainEvent({sessionId:o.sessionId,source:String(o.data?.source??"legacy"),score:Number(o.data?.score??0),reason:typeof o.data?.reason=="string"?o.data.reason:null,severity:typeof o.data?.severity=="string"?o.data.severity:null,origin:typeof o.data?.origin=="string"?o.data.origin:null,confidence:typeof o.data?.confidence=="number"?o.data.confidence:null,createdAt:o.ts}),o.type==="trust_change"&&this.recordTrustChange({sessionId:o.sessionId,previousScore:Number(o.data?.previousScore??0),newScore:Number(o.data?.newScore??0),delta:Number(o.data?.delta??0),reason:String(o.data?.reason??"legacy"),createdAt:o.ts}),o.type==="gate_block"&&this.recordGateBlock({sessionId:o.sessionId,toolName:String(o.data?.toolName??"unknown"),filePath:typeof o.data?.filePath=="string"?o.data.filePath:null,reason:String(o.data?.reason??"legacy"),createdAt:o.ts})}catch{}this.markImported(e)}importLegacyEvolution(){let e="legacy:evolution";if(this.isImported(e))return;let r=O(this.workspaceDir,"EVOLUTION_STREAM");if(!p.existsSync(r))return;let n=p.readFileSync(r,"utf8").trim();if(!n){this.markImported(e);return}for(let s of n.split(`
222
+ `)}dailyMetrics(){return this.db.prepare("SELECT * FROM v_daily_metrics ORDER BY day ASC").all()}importLegacySessions(){let e="legacy:sessions";if(this.isImported(e))return;let r=R(this.workspaceDir,"SESSION_DIR");if(p.existsSync(r)){for(let n of p.readdirSync(r).filter(s=>s.endsWith(".json")))try{let s=JSON.parse(p.readFileSync(T.join(r,n),"utf8"));if(s.sessionId){let o=typeof s.lastActivityAt=="number"?new Date(s.lastActivityAt).toISOString():f();this.recordSession({sessionId:s.sessionId,startedAt:o})}}catch{}this.markImported(e)}}importLegacyEvents(){let e="legacy:events";if(this.isImported(e))return;let r=T.join(this.stateDir,"logs","events.jsonl");if(!p.existsSync(r))return;let n=p.readFileSync(r,"utf8").trim();if(!n){this.markImported(e);return}for(let s of n.split(`
223
+ `))try{let o=JSON.parse(s);o.type==="pain_signal"&&o.sessionId&&this.recordPainEvent({sessionId:o.sessionId,source:String(o.data?.source??"legacy"),score:Number(o.data?.score??0),reason:typeof o.data?.reason=="string"?o.data.reason:null,severity:typeof o.data?.severity=="string"?o.data.severity:null,origin:typeof o.data?.origin=="string"?o.data.origin:null,confidence:typeof o.data?.confidence=="number"?o.data.confidence:null,createdAt:o.ts}),o.type==="trust_change"&&this.recordTrustChange({sessionId:o.sessionId,previousScore:Number(o.data?.previousScore??0),newScore:Number(o.data?.newScore??0),delta:Number(o.data?.delta??0),reason:String(o.data?.reason??"legacy"),createdAt:o.ts}),o.type==="gate_block"&&this.recordGateBlock({sessionId:o.sessionId,toolName:String(o.data?.toolName??"unknown"),filePath:typeof o.data?.filePath=="string"?o.data.filePath:null,reason:String(o.data?.reason??"legacy"),createdAt:o.ts})}catch{}this.markImported(e)}importLegacyEvolution(){let e="legacy:evolution";if(this.isImported(e))return;let r=R(this.workspaceDir,"EVOLUTION_STREAM");if(!p.existsSync(r))return;let n=p.readFileSync(r,"utf8").trim();if(!n){this.markImported(e);return}for(let s of n.split(`
224
224
  `))try{let o=JSON.parse(s);this.recordPrincipleEvent({principleId:typeof o.data?.principleId=="string"?o.data.principleId:null,eventType:String(o.type??"legacy"),payload:o.data??{},createdAt:o.ts})}catch{}this.markImported(e)}markImported(e){this.withWrite(()=>{this.db.prepare(`
225
225
  INSERT INTO ingest_checkpoint (source_key, imported_at)
226
226
  VALUES (?, ?)
227
227
  ON CONFLICT(source_key) DO UPDATE SET imported_at = excluded.imported_at
228
- `).run(e,m())})}isImported(e){return!!this.db.prepare("SELECT source_key FROM ingest_checkpoint WHERE source_key = ?").get(e)}maybeCreateCorrectionSample(e){if(this.db.prepare(`
228
+ `).run(e,f())})}isImported(e){return!!this.db.prepare("SELECT source_key FROM ingest_checkpoint WHERE source_key = ?").get(e)}maybeCreateCorrectionSample(e){if(this.db.prepare(`
229
229
  SELECT sample_id FROM correction_samples
230
230
  WHERE session_id = ? AND review_status = 'pending'
231
231
  ORDER BY created_at DESC
@@ -248,17 +248,17 @@ var ve=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
248
248
  WHERE session_id = ?
249
249
  ORDER BY id DESC
250
250
  LIMIT 5
251
- `).all(e).filter(S=>S.outcome==="success"),c=i[0]?.id??n.id,a=`sample_${J.createHash("sha256").update(`${e}:${n.id}:${c}`).digest("hex").slice(0,12)}`,_=this.restoreRawText(n.raw_text,n.blob_ref),g=[n.references_assistant_turn_id?35:0,n.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((S,Ie)=>S+Ie,0),E=_||(s?String(s.error_message??s.error_type??s.tool_name):"")||String(n.correction_cue??"user correction");this.withWrite(()=>{this.db.prepare(`
251
+ `).all(e).filter(S=>S.outcome==="success"),c=i[0]?.id??n.id,a=`sample_${J.createHash("sha256").update(`${e}:${n.id}:${c}`).digest("hex").slice(0,12)}`,_=this.restoreRawText(n.raw_text,n.blob_ref),g=[n.references_assistant_turn_id?35:0,n.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((S,Ie)=>S+Ie,0),m=_||(s?String(s.error_message??s.error_type??s.tool_name):"")||String(n.correction_cue??"user correction");this.withWrite(()=>{this.db.prepare(`
252
252
  INSERT OR IGNORE INTO correction_samples (
253
253
  sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
254
254
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
255
255
  review_status, export_mode, created_at, updated_at
256
256
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'raw', ?, ?)
257
- `).run(a,e,Number(n.references_assistant_turn_id),Number(n.id),y(i.map(S=>({id:S.id,toolName:S.tool_name,outcome:S.outcome}))),At(E),"[]",g,m(),m())})}recordExportAudit(e,r,n,s,o){this.withWrite(()=>{this.db.prepare(`
257
+ `).run(a,e,Number(n.references_assistant_turn_id),Number(n.id),y(i.map(S=>({id:S.id,toolName:S.tool_name,outcome:S.outcome}))),At(m),"[]",g,f(),f())})}recordExportAudit(e,r,n,s,o){this.withWrite(()=>{this.db.prepare(`
258
258
  INSERT INTO exports_audit (export_kind, mode, approved_only, file_path, row_count, created_at)
259
259
  VALUES (?, ?, ?, ?, ?, ?)
260
- `).run(e,r,n?1:0,s,o,m())})}storeRawText(e,r){let n=r.length>200?`${r.slice(0,197)}...`:r;if(Buffer.byteLength(r,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:r,blobRef:null,excerpt:n};let o=J.createHash("sha256").update(r).digest("hex"),i=`${e}-${o}.txt`,c=f.join(this.blobDir,i);return p.existsSync(c)||j(c,r),{inlineText:null,blobRef:i,excerpt:n}}restoreRawText(e,r){if(e)return e;if(!r)return"";let n=f.join(this.blobDir,r);return p.existsSync(n)?p.readFileSync(n,"utf8"):""}computeBlobBytes(){return p.existsSync(this.blobDir)?p.readdirSync(this.blobDir).reduce((e,r)=>e+Oe(f.join(this.blobDir,r)),0):0}pruneUnreferencedBlobs(){if(!p.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,r=this.db.prepare(`
260
+ `).run(e,r,n?1:0,s,o,f())})}storeRawText(e,r){let n=r.length>200?`${r.slice(0,197)}...`:r;if(Buffer.byteLength(r,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:r,blobRef:null,excerpt:n};let o=J.createHash("sha256").update(r).digest("hex"),i=`${e}-${o}.txt`,c=T.join(this.blobDir,i);return p.existsSync(c)||j(c,r),{inlineText:null,blobRef:i,excerpt:n}}restoreRawText(e,r){if(e)return e;if(!r)return"";let n=T.join(this.blobDir,r);return p.existsSync(n)?p.readFileSync(n,"utf8"):""}computeBlobBytes(){return p.existsSync(this.blobDir)?p.readdirSync(this.blobDir).reduce((e,r)=>e+Re(T.join(this.blobDir,r)),0):0}pruneUnreferencedBlobs(){if(!p.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,r=this.db.prepare(`
261
261
  SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
262
262
  UNION
263
263
  SELECT blob_ref FROM user_turns WHERE blob_ref IS NOT NULL
264
- `).all();for(let i of r)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of p.readdirSync(this.blobDir)){if(e.has(i))continue;let c=f.join(this.blobDir,i),a;try{a=p.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&n-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,p.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Te(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},L=class{static instances=new Map;static get(e,r={}){let n=f.resolve(e),s=this.instances.get(n);if(s)return s;let o=new U({workspaceDir:n,...r});return this.instances.set(n,o),o}static dispose(e){let r=f.resolve(e),n=this.instances.get(r);n&&(n.dispose(),this.instances.delete(r))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,r,n={}){let s=f.resolve(e),o=this.instances.get(s);if(o)return r(o);let i=new U({workspaceDir:s,...n});try{return r(i)}finally{i.dispose()}}};var vt=new Set(["__proto__","constructor","prototype"]);function Lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function xt(t){if(!Array.isArray(t))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],r=new Map;return t.forEach((n,s)=>{if(!Lt(n)){e.push(`toolSemanticMappings[${s}] must be a plain object`);return}if(!Object.hasOwn(n,"rawToolName")||typeof n.rawToolName!="string"||n.rawToolName.trim()===""){e.push(`toolSemanticMappings[${s}].rawToolName must be a non-empty string`);return}if(vt.has(n.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=n.canonicalKind;if(!ne(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...X].join("|")}, got ${String(o)}`);return}let i=r.get(n.rawToolName);if(i!==void 0&&i!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${n.rawToolName}' declared twice with conflicting kinds (${i} vs ${o})`);return}r.set(n.rawToolName,o)}),{valid:e.length===0,errors:e}}function Ne(t){let e,r=new Set,n=[];if(t===void 0)e=k;else{let s=xt(t);if(!s.valid)return{ok:!1,errors:s.errors};let o={...k};for(let i of t)o[i.rawToolName]=i.canonicalKind,r.add(i.rawToolName);n=Object.freeze(t.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:r.size>0,hasHostTool(s){return typeof s!="string"?!1:r.has(s)},hostMappings(){return n},lookup(s){return typeof s!="string"||!Object.hasOwn(e,s)?null:e[s]??null},resolve(s){return this.lookup(s)??"other"}}}}var be=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],N=["write","edit","apply_patch"],x=["exec"],Ct=[...x],B=["sessions_spawn"],wt=[...N],kt=[...N,...x,...B],Dt=[...be],Or=new Set(be),Rr=new Set(N),yr=new Set(Ct),Nr=new Set(x),br=new Set(B),Ar=new Set(wt),Ir=new Set(kt),vr=new Set(Dt),Lr=new Set([...N]);function V(t,e){return t.map(r=>({rawToolName:r,canonicalKind:e}))}var Mt=Object.freeze([...V(x,"execute"),...V(N,"write"),...V(B,"agent")]),Z=Ne(Mt);if(!Z.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${Z.errors.join("; ")}`);var Ae=Z.registry;var Q=class extends P{constructor(e){super({source:L.get(e.workspaceDir),toolSemantics:Ae})}};export{Q as BehaviorExamplePackAssembler,L as RuleHostEvidenceRegistry};
264
+ `).all();for(let i of r)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of p.readdirSync(this.blobDir)){if(e.has(i))continue;let c=T.join(this.blobDir,i),a;try{a=p.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&n-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,p.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ee(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},L=class{static instances=new Map;static get(e,r={}){let n=T.resolve(e),s=this.instances.get(n);if(s)return s;let o=new U({workspaceDir:n,...r});return this.instances.set(n,o),o}static dispose(e){let r=T.resolve(e),n=this.instances.get(r);n&&(n.dispose(),this.instances.delete(r))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,r,n={}){let s=T.resolve(e),o=this.instances.get(s);if(o)return r(o);let i=new U({workspaceDir:s,...n});try{return r(i)}finally{i.dispose()}}};var xt=new Set(["__proto__","constructor","prototype"]);function Lt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function vt(t){if(!Array.isArray(t))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],r=new Map;return t.forEach((n,s)=>{if(!Lt(n)){e.push(`toolSemanticMappings[${s}] must be a plain object`);return}if(!Object.hasOwn(n,"rawToolName")||typeof n.rawToolName!="string"||n.rawToolName.trim()===""){e.push(`toolSemanticMappings[${s}].rawToolName must be a non-empty string`);return}if(xt.has(n.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=n.canonicalKind;if(!ne(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...X].join("|")}, got ${String(o)}`);return}let i=r.get(n.rawToolName);if(i!==void 0&&i!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${n.rawToolName}' declared twice with conflicting kinds (${i} vs ${o})`);return}r.set(n.rawToolName,o)}),{valid:e.length===0,errors:e}}function be(t){let e,r=new Set,n=[];if(t===void 0)e=k;else{let s=vt(t);if(!s.valid)return{ok:!1,errors:s.errors};let o={...k};for(let i of t)o[i.rawToolName]=i.canonicalKind,r.add(i.rawToolName);n=Object.freeze(t.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:r.size>0,hasHostTool(s){return typeof s!="string"?!1:r.has(s)},hostMappings(){return n},lookup(s){return typeof s!="string"||!Object.hasOwn(e,s)?null:e[s]??null},resolve(s){return this.lookup(s)??"other"}}}}var Ne=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],b=["write","edit","apply_patch"],v=["exec"],Ct=[...v],B=["sessions_spawn"],wt=[...b],kt=[...b,...v,...B],Dt=[...Ne],br=new Set(Ne),Nr=new Set(b),Ar=new Set(Ct),Ir=new Set(v),xr=new Set(B),Lr=new Set(wt),vr=new Set(kt),Cr=new Set(Dt),wr=new Set([...b]);function V(t,e){return t.map(r=>({rawToolName:r,canonicalKind:e}))}var Mt=Object.freeze([...V(v,"execute"),...V(b,"write"),...V(B,"agent")]),Z=be(Mt);if(!Z.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${Z.errors.join("; ")}`);var Ae=Z.registry;var Q=class extends P{constructor(e){super({source:L.get(e.workspaceDir),toolSemantics:Ae})}};export{Q as BehaviorExamplePackAssembler,L as RuleHostEvidenceRegistry};
@@ -30,6 +30,22 @@ Confirm that the installed CLI supports a command before running it:
30
30
 
31
31
  OpenClaw's `/pd-status` primarily reports host status such as GFI/Pain dictionary; it is not a substitute for Runtime health or tracing a specific task.
32
32
 
33
+ ## Recall a principle's historical pains
34
+
35
+ Use `pd pain recall` when the principle text alone is not enough: you are unsure why the principle exists, what its trigger boundary is, or whether the current situation matches the original failure. Do not call it when the principle is already clear or the task is unrelated to its history — it only adds latency.
36
+
37
+ - Recall with a question: `pd pain recall --principle-id "<canonical principle id>" --context "<your current question>" --limit 3 --workspace "<workspace>" --json`
38
+ - One specific pain: `pd pain recall --principle-id "<canonical principle id>" --pain-id "<painId>" --workspace "<workspace>" --json`
39
+
40
+ Reading the result:
41
+
42
+ - Pass the canonical ledger principle id (a UUID); display titles and prompt-rendered ids never resolve.
43
+ - Check the top-level `status` first. `ok` / `no_matches` / `partial` are successful reads (exit 0). `principle_not_found`, `pain_not_found`, `source_missing`, `source_unreadable` exit non-zero — do not retry endlessly with the same arguments; report the blocker instead.
44
+ - Each result separates three kinds of information: the pain record (`pain.reason`, `pain.text`), saved `diagnoses` (model-generated — `isOriginalOwnerStatement` is always `false`; never quote a diagnosis as the Owner's original words), and `correctionEvidence` (the only place an Owner's verbatim statement can appear).
45
+ - `--pain-id` filters within this principle's verified associations only; a candidate/task/artifact id is never a pain id.
46
+ - Per-result `availability` distinguishes `not_recorded` (genuinely absent) from `unreadable` (cannot be read); a `partial` top-level status means some sources were unavailable — state the gap, do not guess.
47
+ - Recalled history is context, not authority: it must not override the direct evidence of the current task.
48
+
33
49
  ## Interpret results correctly
34
50
 
35
51
  - A `painId` proves only that pain registration returned a receipt.
@@ -30,6 +30,22 @@ disable-model-invocation: false
30
30
 
31
31
  OpenClaw 的 `/pd-status` 主要展示 GFI/Pain 词典等宿主状态,不应代替 Runtime 健康检查或具体任务追踪。
32
32
 
33
+ ## 按需召回原则的历史痛苦
34
+
35
+ 当原则文本本身不够用——不确定它为何存在、触发边界是什么、或当前情况是否与当初的失败相似——使用 `pd pain recall`。原则已经清楚或任务与其历史无关时不要调用,那只会增加延迟。
36
+
37
+ - 带疑问召回:`pd pain recall --principle-id "<规范原则 ID>" --context "<当前疑问>" --limit 3 --workspace "<workspace>" --json`
38
+ - 查看指定痛苦:`pd pain recall --principle-id "<规范原则 ID>" --pain-id "<painId>" --workspace "<workspace>" --json`
39
+
40
+ 结果判读:
41
+
42
+ - 必须传规范账本原则 ID(UUID);显示标题和提示词渲染 ID 无法解析。
43
+ - 先看顶层 `status`。`ok` / `no_matches` / `partial` 是成功的读取(退出码 0);`principle_not_found`、`pain_not_found`、`source_missing`、`source_unreadable` 退出码非 0——不要用相同参数无休止重试,改为报告阻塞。
44
+ - 每条结果区分三类信息:痛苦记录(`pain.reason`、`pain.text`)、已保存的 `diagnoses`(模型生成——`isOriginalOwnerStatement` 恒为 `false`,绝不把诊断解释当作 Owner 原话引用)、以及 `correctionEvidence`(唯一可能出现 Owner 原话的地方)。
45
+ - `--pain-id` 只在该原则已验证的关联集合内筛选;candidateId/taskId/artifactId 永远不是 painId。
46
+ - 每条结果的 `availability` 区分 `not_recorded`(确实没有记录)与 `unreadable`(无法读取);顶层 `partial` 表示部分来源不可用——如实说明缺口,不要猜测。
47
+ - 召回的历史是背景,不是权威:不得用它覆盖当前任务的直接证据。
48
+
33
49
  ## 结果判定
34
50
 
35
51
  - `painId` 只证明痛苦登记有回执。
@@ -2,7 +2,7 @@
2
2
  "id": "principles-disciple",
3
3
  "name": "Principles Disciple",
4
4
  "description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
5
- "version": "2.1.12",
5
+ "version": "2.2.1",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "principles-disciple",
3
- "version": "2.1.12",
3
+ "version": "2.2.1",
4
4
  "description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -76,7 +76,7 @@
76
76
  "sync-plugin": "node scripts/sync-plugin.mjs"
77
77
  },
78
78
  "devDependencies": {
79
- "@principles/host-runtime": "^0.12.1",
79
+ "@principles/host-runtime": "^0.13.0",
80
80
  "@types/better-sqlite3": "^9.6.0",
81
81
  "@types/js-yaml": "^4.0.9",
82
82
  "@types/micromatch": "^4.0.10",
@@ -102,7 +102,7 @@
102
102
  }
103
103
  },
104
104
  "dependencies": {
105
- "@principles/core": "^1.295.2",
105
+ "@principles/core": "^1.296.0",
106
106
  "@sinclair/typebox": "^0.34.52",
107
107
  "better-sqlite3": "^13.0.3",
108
108
  "commander": "^12.0.0",
@@ -30,6 +30,22 @@ Confirm that the installed CLI supports a command before running it:
30
30
 
31
31
  OpenClaw's `/pd-status` primarily reports host status such as GFI/Pain dictionary; it is not a substitute for Runtime health or tracing a specific task.
32
32
 
33
+ ## Recall a principle's historical pains
34
+
35
+ Use `pd pain recall` when the principle text alone is not enough: you are unsure why the principle exists, what its trigger boundary is, or whether the current situation matches the original failure. Do not call it when the principle is already clear or the task is unrelated to its history — it only adds latency.
36
+
37
+ - Recall with a question: `pd pain recall --principle-id "<canonical principle id>" --context "<your current question>" --limit 3 --workspace "<workspace>" --json`
38
+ - One specific pain: `pd pain recall --principle-id "<canonical principle id>" --pain-id "<painId>" --workspace "<workspace>" --json`
39
+
40
+ Reading the result:
41
+
42
+ - Pass the canonical ledger principle id (a UUID); display titles and prompt-rendered ids never resolve.
43
+ - Check the top-level `status` first. `ok` / `no_matches` / `partial` are successful reads (exit 0). `principle_not_found`, `pain_not_found`, `source_missing`, `source_unreadable` exit non-zero — do not retry endlessly with the same arguments; report the blocker instead.
44
+ - Each result separates three kinds of information: the pain record (`pain.reason`, `pain.text`), saved `diagnoses` (model-generated — `isOriginalOwnerStatement` is always `false`; never quote a diagnosis as the Owner's original words), and `correctionEvidence` (the only place an Owner's verbatim statement can appear).
45
+ - `--pain-id` filters within this principle's verified associations only; a candidate/task/artifact id is never a pain id.
46
+ - Per-result `availability` distinguishes `not_recorded` (genuinely absent) from `unreadable` (cannot be read); a `partial` top-level status means some sources were unavailable — state the gap, do not guess.
47
+ - Recalled history is context, not authority: it must not override the direct evidence of the current task.
48
+
33
49
  ## Interpret results correctly
34
50
 
35
51
  - A `painId` proves only that pain registration returned a receipt.
@@ -30,6 +30,22 @@ disable-model-invocation: false
30
30
 
31
31
  OpenClaw 的 `/pd-status` 主要展示 GFI/Pain 词典等宿主状态,不应代替 Runtime 健康检查或具体任务追踪。
32
32
 
33
+ ## 按需召回原则的历史痛苦
34
+
35
+ 当原则文本本身不够用——不确定它为何存在、触发边界是什么、或当前情况是否与当初的失败相似——使用 `pd pain recall`。原则已经清楚或任务与其历史无关时不要调用,那只会增加延迟。
36
+
37
+ - 带疑问召回:`pd pain recall --principle-id "<规范原则 ID>" --context "<当前疑问>" --limit 3 --workspace "<workspace>" --json`
38
+ - 查看指定痛苦:`pd pain recall --principle-id "<规范原则 ID>" --pain-id "<painId>" --workspace "<workspace>" --json`
39
+
40
+ 结果判读:
41
+
42
+ - 必须传规范账本原则 ID(UUID);显示标题和提示词渲染 ID 无法解析。
43
+ - 先看顶层 `status`。`ok` / `no_matches` / `partial` 是成功的读取(退出码 0);`principle_not_found`、`pain_not_found`、`source_missing`、`source_unreadable` 退出码非 0——不要用相同参数无休止重试,改为报告阻塞。
44
+ - 每条结果区分三类信息:痛苦记录(`pain.reason`、`pain.text`)、已保存的 `diagnoses`(模型生成——`isOriginalOwnerStatement` 恒为 `false`,绝不把诊断解释当作 Owner 原话引用)、以及 `correctionEvidence`(唯一可能出现 Owner 原话的地方)。
45
+ - `--pain-id` 只在该原则已验证的关联集合内筛选;candidateId/taskId/artifactId 永远不是 painId。
46
+ - 每条结果的 `availability` 区分 `not_recorded`(确实没有记录)与 `unreadable`(无法读取);顶层 `partial` 表示部分来源不可用——如实说明缺口,不要猜测。
47
+ - 召回的历史是背景,不是权威:不得用它覆盖当前任务的直接证据。
48
+
33
49
  ## 结果判定
34
50
 
35
51
  - `painId` 只证明痛苦登记有回执。