create-principles-disciple 1.145.6 → 1.145.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +2 -2
- package/console/dist/server/models/CodexGovernanceHealthModel.d.ts +39 -2
- package/console/dist/server/models/CodexGovernanceHealthModel.js +228 -29
- package/core/dist/runtime-v2/adapter/artificer-l2-adapter.d.ts.map +1 -1
- package/core/dist/runtime-v2/adapter/artificer-l2-adapter.js +28 -9
- package/core/dist/runtime-v2/adapter/artificer-l2-adapter.js.map +1 -1
- package/core/dist/runtime-v2/adapter/l2-agent-loop-adapter.d.ts.map +1 -1
- package/core/dist/runtime-v2/adapter/l2-agent-loop-adapter.js +29 -9
- package/core/dist/runtime-v2/adapter/l2-agent-loop-adapter.js.map +1 -1
- package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.d.ts +6 -0
- package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.d.ts.map +1 -1
- package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.js +105 -1
- package/core/dist/runtime-v2/adapter/pi-ai-runtime-adapter.js.map +1 -1
- package/core/dist/runtime-v2/index.d.ts +6 -2
- package/core/dist/runtime-v2/index.d.ts.map +1 -1
- package/core/dist/runtime-v2/index.js +3 -1
- package/core/dist/runtime-v2/index.js.map +1 -1
- package/core/dist/runtime-v2/internalization/artificer-intent-preflight.d.ts +154 -0
- package/core/dist/runtime-v2/internalization/artificer-intent-preflight.d.ts.map +1 -0
- package/core/dist/runtime-v2/internalization/artificer-intent-preflight.js +686 -0
- package/core/dist/runtime-v2/internalization/artificer-intent-preflight.js.map +1 -0
- package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts +21 -3
- package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js +48 -5
- package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js.map +1 -1
- package/core/dist/runtime-v2/internalization/artificer-runner.d.ts +17 -0
- package/core/dist/runtime-v2/internalization/artificer-runner.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/artificer-runner.js +45 -2
- package/core/dist/runtime-v2/internalization/artificer-runner.js.map +1 -1
- package/core/dist/runtime-v2/internalization/behavior-example-pack.d.ts +0 -19
- package/core/dist/runtime-v2/internalization/behavior-example-pack.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/behavior-example-pack.js +31 -0
- package/core/dist/runtime-v2/internalization/behavior-example-pack.js.map +1 -1
- package/core/dist/runtime-v2/internalization/intent-contract.d.ts +31 -0
- package/core/dist/runtime-v2/internalization/intent-contract.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/intent-contract.js +42 -0
- package/core/dist/runtime-v2/internalization/intent-contract.js.map +1 -1
- package/core/dist/runtime-v2/internalization/peer-runner-contracts.d.ts +14 -1
- package/core/dist/runtime-v2/internalization/peer-runner-contracts.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/peer-runner-contracts.js.map +1 -1
- package/core/dist/runtime-v2/internalization/pitask-metadata.d.ts +64 -0
- package/core/dist/runtime-v2/internalization/pitask-metadata.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/pitask-metadata.js +84 -0
- package/core/dist/runtime-v2/internalization/pitask-metadata.js.map +1 -1
- package/core/dist/runtime-v2/internalization/scribe-output.d.ts +13 -1
- package/core/dist/runtime-v2/internalization/scribe-output.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/scribe-output.js +13 -1
- package/core/dist/runtime-v2/internalization/scribe-output.js.map +1 -1
- package/core/dist/runtime-v2/internalization/scribe-prompt-builder.d.ts +15 -1
- package/core/dist/runtime-v2/internalization/scribe-prompt-builder.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/scribe-prompt-builder.js +29 -1
- package/core/dist/runtime-v2/internalization/scribe-prompt-builder.js.map +1 -1
- package/core/dist/runtime-v2/tools/agent-tool-contract.d.ts +2 -1
- package/core/dist/runtime-v2/tools/agent-tool-contract.d.ts.map +1 -1
- package/core/dist/runtime-v2/tools/agent-tool-contract.js +1 -1
- package/core/dist/runtime-v2/tools/agent-tool-contract.js.map +1 -1
- package/core/dist/runtime-v2/tools/artificer-l2-tool-contract.d.ts +1 -1
- package/core/dist/telemetry-event.d.ts +4 -2
- package/core/dist/telemetry-event.d.ts.map +1 -1
- package/core/dist/telemetry-event.js +12 -0
- package/core/dist/telemetry-event.js.map +1 -1
- package/core/package.json +3 -3
- package/host-runtime/dist/internalization-consumer-cycle.d.ts +10 -1
- package/host-runtime/dist/internalization-consumer-cycle.js +85 -4
- package/host-runtime/dist/production-rulehost-gate.js +40 -3
- package/host-runtime/package.json +1 -1
- package/package.json +1 -1
- package/plugin/dist/bundle.js +655 -781
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +27 -27
- package/release-manager/package.json +1 -1
|
@@ -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.
|
|
5
|
+
"version": "2.1.8",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function U(r,e){if(!r||typeof r!="string")return"";let t=r.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s=t.length>=2&&t[1]===":",o=n.length>=2&&n[1]===":",i=t;s&&!o&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2)}`);let c=s&&o?i.slice(2):i,a=o?n.slice(2):n,d=c.startsWith("/"),f=a.startsWith("/");if(d&&f){let _=Q(a,c);return _.startsWith("../")?i:_}if(!d){let _=Ae(a,c),g=Q(a,_);return g.startsWith("../")?i:g}return i}function Q(r,e){let t=r.split("/").filter(a=>a.length>0),n=e.split("/").filter(a=>a.length>0),s=0;for(;s<t.length&&s<n.length&&t[s]===n[s];)s++;let o=t.length-s,i=n.slice(s),c=[];for(let a=0;a<o;a++)c.push("..");return c.push(...i),c.length===0?".":c.join("/")}function Ae(r,e){let t=r.split("/").filter(o=>o.length>0),n=e.split("/").filter(o=>o.length>0),s=[];for(let o of t)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);for(let o of n)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);return"/"+s.join("/")}function B(r,e={}){let t=r.file_path||r.path||r.file||r.target;if(typeof t=="string"&&t.length>0)return t;if(e.isBashTool){let n=String(r.command||r.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]?s[1]:n}}return e.isWriteTool&&e.toolName?`<tool:${e.toolName}>`:null}function Ie(r){return{isBashTool:r==="execute",isWriteTool:r==="write"}}function ve(r){if(r.canonicalKind===void 0)return r;let e=Ie(r.canonicalKind);return{...r,isBashTool:r.isBashTool??e.isBashTool,isWriteTool:r.isWriteTool??e.isWriteTool}}function ee(r,e,t,n={}){let s=ve(n),o=B(e,{...s,toolName:r}),i=U(o,t);return{toolName:r,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var F=new Set(["read","search","write","execute","agent","other"]);function te(r){return typeof r=="string"&&F.has(r)}var w=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 re(r,e,t){if(r.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}=r;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:t}}var ne={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ne);var X={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(X.calls);Object.freeze(X);var Le={version:2,history:X,facts:ne};Object.freeze(Le);var xe=new Set(["__proto__","constructor","prototype"]),se=3,Ce=5,we=new Set(["allow","block","propose_correction"]),ke={valid:!0,errors:[]};function W(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ae(r){for(let e of Object.keys(r))if(xe.has(e))return!1;return!0}function De(r){return r.length===0?ke:{valid:!1,errors:r}}function $(r){return typeof r=="string"&&r.trim().length>0}function oe(r,e,t){let n=[];return W(r)?ae(r)?((!Object.hasOwn(r,"caseId")||!$(r.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(r,"kind")||r.kind!==t)&&n.push(`${e}.kind must be '${t}'`),(!Object.hasOwn(r,"toolName")||!$(r.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(r,"params")||!W(r.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(r,"expectedDecision")||typeof r.expectedDecision!="string"||!we.has(r.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):t==="positive"&&r.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 ie(r,e){let{fieldName:t,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(r))return o.push(`${t} must be an array`),o;s&&r.length===0&&o.push(`${t} must contain at least 1 item`),n!==void 0&&r.length>n&&o.push(`${t} must contain at most ${n} items, got ${r.length}`);for(let i=0;i<r.length;i++)typeof r[i]!="string"&&o.push(`${t}[${i}] must be a string`);return o}function H(r){if(!W(r))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ae(r))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(r,"sourceNegativeCase")?e.push(...oe(r.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(r,"ownerDesiredOutcome")||!$(r.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(r,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(r.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let t=r.positiveCounterexamples;t.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),t.length>se&&e.push(`positiveCounterexamples must contain at most ${se} items, got ${t.length}`);for(let n=0;n<t.length;n++)e.push(...oe(t[n],`positiveCounterexamples[${n}]`,"positive"))}return Object.hasOwn(r,"evidenceRefs")?e.push(...ie(r.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ce,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(r,"redactionNotes")?e.push(...ie(r.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),De(e)}var Me="OwnerEvidenceScopeError";function N(r,e){let t=new Error(e);return t.name=Me,Object.assign(t,{ownerEvidenceScopeKind:r}),t}var Pe=new Set(["success","failure","blocked"]);function je(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ue(r){return typeof r=="string"&&Pe.has(r)}function A(r){return{status:"unavailable",unavailableReason:r,truncated:!1,calls:[]}}function ce(r,e,t){let{projectDir:n,toolSemantics:s}=t,o=[];for(let i of r){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(!Ue(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return A(`row id=${i.id}: params_json must be a string`);let f;try{f=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!je(f))return A(`row id=${i.id}: params_json must parse to a non-array object`);let _=s.resolve(c),g=B(f,{isBashTool:_==="execute",isWriteTool:_==="write",toolName:c}),C=U(g,n);o.push({sequenceId:i.id,toolName:c,canonicalKind:_,normalizedPath:C===""?null:C,paramsSummary:f,outcome:a})}return{status:"available",truncated:e,calls:o}}var Be=3,Fe=5,Xe=100,ue=new Set(["__proto__","constructor","prototype"]);function k(r,e){try{return e()}catch(t){let n=t instanceof Error?t.message:String(t);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${r} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function We(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function $e(r){for(let e of Object.keys(r))if(ue.has(e))return!1;return!0}function He(r){if(!Number.isSafeInteger(r.sourceNegativeToolCallId)||r.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(r.positiveToolCallIds)||r.positiveToolCallIds.length===0||r.positiveToolCallIds.length>Be)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[r.sourceNegativeToolCallId,...r.positiveToolCallIds];if(e.some(t=>!Number.isSafeInteger(t)||t<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function le(r,e){if(!r)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return r}function Ye(r,e,t){if(typeof r.toolName!="string"||r.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof r.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(r.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!We(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!$e(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${r.id}`,kind:e,toolName:r.toolName,params:n,expectedDecision:t}}function Ke(r){return r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)}var Ge=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function qe(r){if(r.length<20)return!1;for(let e of Ge)if(e.test(r))return!0;return!1}function ze(r,e){let t=[],n={};for(let s of Object.keys(r)){if(ue.has(s))continue;let o=r[s];if(typeof o!="string"){n[s]=o;continue}if(Ke(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(qe(o)){n[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:t}}var D=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=k(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!t)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);He(e);let n=le(k(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(_=>le(k(`evidence row read for id=${_}`,()=>this.db.getRuleHostEvidenceRow(_)),_));for(let _ of[n,...s])if(_.sessionId!==t.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${_.id} session mismatch; all examples must belong to pain session ${t.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(_=>this.buildSelectedCase(_,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${t.id}`,`tool_call:${n.id}`,...s.map(_=>`tool_call:${_.id}`)].slice(0,Fe),redactionNotes:o},f=H(d);if(!f.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${f.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,n){let{projectDir:s,redactionNotes:o}=n,i=Ye(e,t,t==="negative"?"block":"allow"),c=ze(i.params,s);o.push(...c.notes);let a=k(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Xe)),d=ce(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),f=ee(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),_={version:2,history:d,facts:re(d,f.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:_}}};import mt from"better-sqlite3";import E from"fs";import S from"path";import z from"crypto";import*as p from"fs";import*as _e from"path";var Y=class extends Error{filePath;lockPath;constructor(e,t,n){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=n}},Ve={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function pe(r){try{return process.kill(r,0),!0}catch{return!1}}function de(r,e){try{let t=_e.dirname(r);p.existsSync(t)||p.mkdirSync(t,{recursive:!0});let n=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(r,n);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}}function I(r){try{let e=p.readFileSync(r,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function Je(r,e){try{I(r)===e&&p.unlinkSync(r)}catch{}}function Ze(r,e){try{let t=p.statSync(r),n=I(r),s=Date.now()-t.mtimeMs>e,o=n===null||!pe(n);if(s||o)try{return p.unlinkSync(r),!0}catch{return!1}return!1}catch{return!1}}function Qe(r,e,t){let n=Math.min(e*Math.pow(2,r),t),s=n*.2*Math.random();return Math.floor(n+s)}function et(r){let e=Date.now()+r;for(;Date.now()<e;);}function tt(r,e){let t=I(e),n=t!==null?pe(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new Y(`Failed to acquire lock for ${r}. Lock holder: ${n}.`,r,e)}function rt(r,e,t){let n=r+e.lockSuffix;return de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:(Ze(n,e.lockStaleMs),de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:null)}function nt(r,e={}){let t={...Ve,...e},{pid:n}=process;for(let s=0;s<t.maxRetries;s++){let o=rt(r,t,n);if(o)return o;if(s<t.maxRetries-1){let i=Qe(s,t.baseRetryDelayMs,t.maxRetryDelayMs);et(i)}}throw tt(r,r+t.lockSuffix)}function st(r){Je(r.lockPath,r.pid)}function Ee(r,e,t={}){let n=nt(r,t);try{return e()}finally{st(n)}}import*as R from"fs";var me=3,ot=50;function M(r,e){let t=r+".tmp";R.writeFileSync(t,e,"utf8");let n;for(let s=0;s<me;s++)try{R.renameSync(t,r);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<me-1){let c=ot*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Ne("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{R.unlinkSync(t)}catch{}throw n}import*as h from"path";var l=(...r)=>h.posix.join(...r);function it(r){return/^[A-Za-z]:[\\/]/.test(r)||r.startsWith("\\\\")}function at(r,e){return it(r)?h.win32.join(r,e):r.startsWith("/")?h.posix.join(r,e):h.join(r,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")},ct={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(r,e){return at(r,ct[e])}var lt={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"},K=class extends Error{constructor(t,n,s){super(t,s);this.code=n;this.name="PdError",this.category=lt[n]??"execution_failed"}code;category};var v=class extends K{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var ut=["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(r){let e=r instanceof Error?r.message:String(r);return e.includes("duplicate column name")||e.includes("no column named")}function dt(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Te(r,e={}){let t=[],n=[...ut];r.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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{r.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!T(s))throw s}if(r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)"),r.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"),dt(r,"evolution_tasks")){try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!T(s))throw s}}return r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),r.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),r.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(r.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"),r.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"),r.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:t}}import*as G from"path";import*as fe from"os";var _t=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],pt=G.join(fe.tmpdir(),".pd-test-quarantine");function Et(r){if(!r)return!1;let e=r.replace(/\\/g,"/");return _t.some(t=>t.test(e))}function ge(r){if(!r||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Et(r))return r;let t=r.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;t.startsWith("_");)t=t.slice(1);for(;t.endsWith("_");)t=t.slice(0,-1);return G.join(pt,t)}var Tt=16*1024,ft=5e3,gt=7;function Oe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function St(r){return!Oe(r)||typeof r.id!="number"||typeof r.session_id!="string"?!1:Object.hasOwn(r,"source")&&Object.hasOwn(r,"score")&&Object.hasOwn(r,"reason")&&Object.hasOwn(r,"severity")&&Object.hasOwn(r,"origin")&&Object.hasOwn(r,"confidence")&&Object.hasOwn(r,"text")&&Object.hasOwn(r,"canonical_pain_id")&&Object.hasOwn(r,"runtime_task_id")&&Object.hasOwn(r,"created_at")}function ht(r){let e=Te(r,{views:!0});return{tables:e.tables,warnings:e.warnings}}function m(){return new Date().toISOString()}function b(r){return JSON.stringify(r??{})}function Se(r){try{return E.existsSync(r)?E.statSync(r).size:0}catch{return 0}}function Ot(r){return r.length>240?`${r.slice(0,237)}...`:r}function he(r){return r.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 Rt(r){let e=[],t=!1;try{let n=JSON.parse(String(r.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"),t=!0)}}}catch{e=[],t=!1}return{id:String(r.id),sessionId:String(r.session_id),userTurnRowid:Number(r.user_turn_rowid),occurrenceId:String(r.occurrence_id),excerpt:String(r.excerpt),terms:e,termsVerified:t,suggestedType:String(r.suggested_type),status:String(r.status),attempts:Number(r.attempts??0),createdAt:String(r.created_at),resolvedAt:r.resolved_at===null||r.resolved_at===void 0?null:String(r.resolved_at),resolution:r.resolution===null||r.resolution===void 0?null:String(r.resolution)}}var P=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=ge(S.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??Tt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??gt)*24*60*60*1e3),E.mkdirSync(this.stateDir,{recursive:!0}),E.mkdirSync(this.blobDir,{recursive:!0}),E.mkdirSync(this.exportDir,{recursive:!0}),this.db=new mt(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??ft)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let t=e.startedAt??m();this.withWrite(()=>{this.db.prepare(`
|
|
2
|
+
var Ae=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function B(r,e){if(!r||typeof r!="string")return"";let t=r.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s=t.length>=2&&t[1]===":",o=n.length>=2&&n[1]===":",i=t;s&&!o&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2)}`);let c=s&&o?i.slice(2):i,a=o?n.slice(2):n,d=c.startsWith("/"),f=a.startsWith("/");if(d&&f){let _=ee(a,c);return _.startsWith("../")?i:_}if(!d){let _=Ie(a,c),g=ee(a,_);return g.startsWith("../")?i:g}return i}function ee(r,e){let t=r.split("/").filter(a=>a.length>0),n=e.split("/").filter(a=>a.length>0),s=0;for(;s<t.length&&s<n.length&&t[s]===n[s];)s++;let o=t.length-s,i=n.slice(s),c=[];for(let a=0;a<o;a++)c.push("..");return c.push(...i),c.length===0?".":c.join("/")}function Ie(r,e){let t=r.split("/").filter(o=>o.length>0),n=e.split("/").filter(o=>o.length>0),s=[];for(let o of t)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);for(let o of n)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);return"/"+s.join("/")}function F(r,e={}){let t=r.file_path||r.path||r.file||r.target;if(typeof t=="string"&&t.length>0)return t;if(e.isBashTool){let n=String(r.command||r.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]?s[1]:n}}return e.isWriteTool&&e.toolName?`<tool:${e.toolName}>`:null}function xe(r){return{isBashTool:r==="execute",isWriteTool:r==="write"}}function ve(r){if(r.canonicalKind===void 0)return r;let e=xe(r.canonicalKind);return{...r,isBashTool:r.isBashTool??e.isBashTool,isWriteTool:r.isWriteTool??e.isWriteTool}}function te(r,e,t,n={}){let s=ve(n),o=F(e,{...s,toolName:r}),i=B(o,t);return{toolName:r,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function re(r){return typeof r=="string"&&X.has(r)}var w=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 ne(r,e,t){if(r.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}=r;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:t}}var se={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(se);var W={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(W.calls);Object.freeze(W);var Le={version:2,history:W,facts:se};Object.freeze(Le);var Ce=new Set(["__proto__","constructor","prototype"]),oe=3,we=5,ke=new Set(["allow","block","propose_correction"]),De={valid:!0,errors:[]};function $(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ce(r){for(let e of Object.keys(r))if(Ce.has(e))return!1;return!0}function Me(r){return r.length===0?De:{valid:!1,errors:r}}function H(r){return typeof r=="string"&&r.trim().length>0}function ie(r,e,t){let n=[];return $(r)?ce(r)?((!Object.hasOwn(r,"caseId")||!H(r.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(r,"kind")||r.kind!==t)&&n.push(`${e}.kind must be '${t}'`),(!Object.hasOwn(r,"toolName")||!H(r.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(r,"params")||!$(r.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(r,"expectedDecision")||typeof r.expectedDecision!="string"||!ke.has(r.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):t==="positive"&&r.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 ae(r,e){let{fieldName:t,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(r))return o.push(`${t} must be an array`),o;s&&r.length===0&&o.push(`${t} must contain at least 1 item`),n!==void 0&&r.length>n&&o.push(`${t} must contain at most ${n} items, got ${r.length}`);for(let i=0;i<r.length;i++)typeof r[i]!="string"&&o.push(`${t}[${i}] must be a string`);return o}function k(r){return Array.isArray(r)?`[${r.map(e=>k(e)).join(",")}]`:typeof r=="object"&&r!==null?`{${Object.keys(r).filter(t=>t!=="__proto__"&&t!=="constructor"&&t!=="prototype").sort().map(t=>`${JSON.stringify(t)}:${k(r[t])}`).join(",")}}`:JSON.stringify(r)??"null"}function Y(r){if(!$(r))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ce(r))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(r,"sourceNegativeCase")?e.push(...ie(r.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(r,"ownerDesiredOutcome")||!H(r.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(r,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(r.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let t=r.positiveCounterexamples;t.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),t.length>oe&&e.push(`positiveCounterexamples must contain at most ${oe} items, got ${t.length}`);for(let n=0;n<t.length;n++)e.push(...ie(t[n],`positiveCounterexamples[${n}]`,"positive"))}if(Object.hasOwn(r,"evidenceRefs")?e.push(...ae(r.evidenceRefs,{fieldName:"evidenceRefs",maxLength:we,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(r,"redactionNotes")?e.push(...ae(r.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let t=r.sourceNegativeCase,n=r.positiveCounterexamples,s=k({toolName:t.toolName,params:t.params,ruleContext:t.ruleContext});for(let o=0;o<n.length;o++){let i=n[o];i!==void 0&&k({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 Me(e)}var Pe="OwnerEvidenceScopeError";function N(r,e){let t=new Error(e);return t.name=Pe,Object.assign(t,{ownerEvidenceScopeKind:r}),t}var je=new Set(["success","failure","blocked"]);function Ue(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Be(r){return typeof r=="string"&&je.has(r)}function A(r){return{status:"unavailable",unavailableReason:r,truncated:!1,calls:[]}}function le(r,e,t){let{projectDir:n,toolSemantics:s}=t,o=[];for(let i of r){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(!Be(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return A(`row id=${i.id}: params_json must be a string`);let f;try{f=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!Ue(f))return A(`row id=${i.id}: params_json must parse to a non-array object`);let _=s.resolve(c),g=F(f,{isBashTool:_==="execute",isWriteTool:_==="write",toolName:c}),C=B(g,n);o.push({sequenceId:i.id,toolName:c,canonicalKind:_,normalizedPath:C===""?null:C,paramsSummary:f,outcome:a})}return{status:"available",truncated:e,calls:o}}var Fe=3,Xe=5,We=100,de=new Set(["__proto__","constructor","prototype"]);function D(r,e){try{return e()}catch(t){let n=t instanceof Error?t.message:String(t);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${r} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function $e(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function He(r){for(let e of Object.keys(r))if(de.has(e))return!1;return!0}function Ye(r){if(!Number.isSafeInteger(r.sourceNegativeToolCallId)||r.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(r.positiveToolCallIds)||r.positiveToolCallIds.length===0||r.positiveToolCallIds.length>Fe)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[r.sourceNegativeToolCallId,...r.positiveToolCallIds];if(e.some(t=>!Number.isSafeInteger(t)||t<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function ue(r,e){if(!r)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return r}function Ke(r,e,t){if(typeof r.toolName!="string"||r.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof r.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(r.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!$e(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!He(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${r.id}`,kind:e,toolName:r.toolName,params:n,expectedDecision:t}}function Ge(r){return r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)}var qe=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ze(r){if(r.length<20)return!1;for(let e of qe)if(e.test(r))return!0;return!1}function Je(r,e){let t=[],n={};for(let s of Object.keys(r)){if(de.has(s))continue;let o=r[s];if(typeof o!="string"){n[s]=o;continue}if(Ge(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ze(o)){n[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:t}}var M=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=D(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!t)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);Ye(e);let n=ue(D(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(_=>ue(D(`evidence row read for id=${_}`,()=>this.db.getRuleHostEvidenceRow(_)),_));for(let _ of[n,...s])if(_.sessionId!==t.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${_.id} session mismatch; all examples must belong to pain session ${t.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(_=>this.buildSelectedCase(_,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${t.id}`,`tool_call:${n.id}`,...s.map(_=>`tool_call:${_.id}`)].slice(0,Xe),redactionNotes:o},f=Y(d);if(!f.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${f.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,n){let{projectDir:s,redactionNotes:o}=n,i=Ke(e,t,t==="negative"?"block":"allow"),c=Je(i.params,s);o.push(...c.notes);let a=D(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,We)),d=le(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),f=te(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),_={version:2,history:d,facts:ne(d,f.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:_}}};import Tt from"better-sqlite3";import m from"fs";import S from"path";import J from"crypto";import*as p from"fs";import*as pe from"path";var K=class extends Error{filePath;lockPath;constructor(e,t,n){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=n}},Ve={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function me(r){try{return process.kill(r,0),!0}catch{return!1}}function _e(r,e){try{let t=pe.dirname(r);p.existsSync(t)||p.mkdirSync(t,{recursive:!0});let n=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(r,n);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}}function I(r){try{let e=p.readFileSync(r,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function Ze(r,e){try{I(r)===e&&p.unlinkSync(r)}catch{}}function Qe(r,e){try{let t=p.statSync(r),n=I(r),s=Date.now()-t.mtimeMs>e,o=n===null||!me(n);if(s||o)try{return p.unlinkSync(r),!0}catch{return!1}return!1}catch{return!1}}function et(r,e,t){let n=Math.min(e*Math.pow(2,r),t),s=n*.2*Math.random();return Math.floor(n+s)}function tt(r){let e=Date.now()+r;for(;Date.now()<e;);}function rt(r,e){let t=I(e),n=t!==null?me(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new K(`Failed to acquire lock for ${r}. Lock holder: ${n}.`,r,e)}function nt(r,e,t){let n=r+e.lockSuffix;return _e(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:(Qe(n,e.lockStaleMs),_e(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:null)}function st(r,e={}){let t={...Ve,...e},{pid:n}=process;for(let s=0;s<t.maxRetries;s++){let o=nt(r,t,n);if(o)return o;if(s<t.maxRetries-1){let i=et(s,t.baseRetryDelayMs,t.maxRetryDelayMs);tt(i)}}throw rt(r,r+t.lockSuffix)}function ot(r){Ze(r.lockPath,r.pid)}function Ee(r,e,t={}){let n=st(r,t);try{return e()}finally{ot(n)}}import*as R from"fs";var Te=3,it=50;function P(r,e){let t=r+".tmp";R.writeFileSync(t,e,"utf8");let n;for(let s=0;s<Te;s++)try{R.renameSync(t,r);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Te-1){let c=it*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Ae("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{R.unlinkSync(t)}catch{}throw n}import*as h from"path";var l=(...r)=>h.posix.join(...r);function at(r){return/^[A-Za-z]:[\\/]/.test(r)||r.startsWith("\\\\")}function ct(r,e){return at(r)?h.win32.join(r,e):r.startsWith("/")?h.posix.join(r,e):h.join(r,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")},lt={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(r,e){return ct(r,lt[e])}var ut={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(t,n,s){super(t,s);this.code=n;this.name="PdError",this.category=ut[n]??"execution_failed"}code;category};var x=class extends G{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var dt=["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(r){let e=r instanceof Error?r.message:String(r);return e.includes("duplicate column name")||e.includes("no column named")}function _t(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function fe(r,e={}){let t=[],n=[...dt];r.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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)"),r.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{r.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!T(s))throw s}if(r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)"),r.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"),_t(r,"evolution_tasks")){try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!T(s))throw s}}return r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),r.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),r.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(r.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"),r.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"),r.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:t}}import*as q from"path";import*as ge from"os";var pt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],mt=q.join(ge.tmpdir(),".pd-test-quarantine");function Et(r){if(!r)return!1;let e=r.replace(/\\/g,"/");return pt.some(t=>t.test(e))}function Se(r){if(!r||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Et(r))return r;let t=r.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;t.startsWith("_");)t=t.slice(1);for(;t.endsWith("_");)t=t.slice(0,-1);return q.join(mt,t)}var ft=16*1024,gt=5e3,St=7;function Re(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ht(r){return!Re(r)||typeof r.id!="number"||typeof r.session_id!="string"?!1:Object.hasOwn(r,"source")&&Object.hasOwn(r,"score")&&Object.hasOwn(r,"reason")&&Object.hasOwn(r,"severity")&&Object.hasOwn(r,"origin")&&Object.hasOwn(r,"confidence")&&Object.hasOwn(r,"text")&&Object.hasOwn(r,"canonical_pain_id")&&Object.hasOwn(r,"runtime_task_id")&&Object.hasOwn(r,"created_at")}function Ot(r){let e=fe(r,{views:!0});return{tables:e.tables,warnings:e.warnings}}function E(){return new Date().toISOString()}function y(r){return JSON.stringify(r??{})}function he(r){try{return m.existsSync(r)?m.statSync(r).size:0}catch{return 0}}function Rt(r){return r.length>240?`${r.slice(0,237)}...`:r}function Oe(r){return r.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 yt(r){let e=[],t=!1;try{let n=JSON.parse(String(r.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"),t=!0)}}}catch{e=[],t=!1}return{id:String(r.id),sessionId:String(r.session_id),userTurnRowid:Number(r.user_turn_rowid),occurrenceId:String(r.occurrence_id),excerpt:String(r.excerpt),terms:e,termsVerified:t,suggestedType:String(r.suggested_type),status:String(r.status),attempts:Number(r.attempts??0),createdAt:String(r.created_at),resolvedAt:r.resolved_at===null||r.resolved_at===void 0?null:String(r.resolved_at),resolution:r.resolution===null||r.resolution===void 0?null:String(r.resolution)}}var j=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Se(S.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??ft,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??St)*24*60*60*1e3),m.mkdirSync(this.stateDir,{recursive:!0}),m.mkdirSync(this.blobDir,{recursive:!0}),m.mkdirSync(this.exportDir,{recursive:!0}),this.db=new Tt(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??gt)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let t=e.startedAt??E();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,t,
|
|
6
|
+
`).run(e.sessionId,t,E())})}recordAssistantTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=this.storeRawText("assistant",e.rawText),n=e.createdAt??E();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,t.inlineText,e.sanitizedText,
|
|
11
|
+
`).run(e.sessionId,e.runId,e.provider,e.model,t.inlineText,e.sanitizedText,y(e.usageJson),y(e.empathySignalJson),t.blobRef,t.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=this.storeRawText("user",e.rawText),n=e.createdAt??E();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,17 +17,17 @@ var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
17
17
|
UPDATE user_turns
|
|
18
18
|
SET correction_detected = 1, correction_cue = ?
|
|
19
19
|
WHERE id = ?
|
|
20
|
-
`).run(t??null,e));return Number(n.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=e.createdAt??
|
|
20
|
+
`).run(t??null,e));return Number(n.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=e.createdAt??E(),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
|
|
24
24
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
25
|
-
`).run(e.sessionId,e.toolName,e.outcome,e.durationMs??null,e.exitCode??null,e.errorType??null,e.errorMessage??null,e.gfiBefore??null,e.gfiAfter??null,
|
|
25
|
+
`).run(e.sessionId,e.toolName,e.outcome,e.durationMs??null,e.exitCode??null,e.errorType??null,e.errorMessage??null,e.gfiBefore??null,e.gfiAfter??null,y(e.paramsJson),e.resultPreview??null,t);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),n}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=-1;return this.withWrite(()=>{try{let n=this.db.prepare(`
|
|
26
26
|
INSERT INTO pain_events (
|
|
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??
|
|
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??E(),e.canonicalPainId??null,e.runtimeTaskId??null,e.hostKind??null);t=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 Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
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"?t=s.id:t=-1}else throw n}}),t}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??
|
|
38
|
+
`).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??E())})}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??
|
|
41
|
+
`).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??E())})}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,
|
|
44
|
+
`).run(e.principleId??null,e.eventType,y(e.payload),e.createdAt??E())})}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,
|
|
47
|
+
`).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,y(e.principleIdsJson),e.createdAt??E())})}evolutionTableMissing(e){let t=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!t||typeof t.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let t=[],n=[];e.status&&(t.push("status = ?"),n.push(e.status)),e.dateFrom&&(t.push("created_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(t.push("created_at <= ?"),n.push(e.dateTo));let s=t.length>0?`WHERE ${t.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
|
|
@@ -101,7 +101,7 @@ var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
101
101
|
FROM tool_calls
|
|
102
102
|
WHERE id = ?
|
|
103
103
|
LIMIT 1
|
|
104
|
-
`).get(e);return!
|
|
104
|
+
`).get(e);return!Re(t)||typeof t.id!="number"||typeof t.session_id!="string"||typeof t.tool_name!="string"||typeof t.outcome!="string"||typeof t.params_json!="string"?null:{id:t.id,sessionId:t.session_id,toolName:t.tool_name,outcome:t.outcome,paramsJson:t.params_json}}getRuleHostContextRowsBefore(e,t,n=20){let s=Math.max(1,Math.floor(n)),o=this.db.prepare(`
|
|
105
105
|
SELECT id, tool_name, outcome, params_json
|
|
106
106
|
FROM tool_calls
|
|
107
107
|
WHERE session_id = ? AND id < ?
|
|
@@ -118,7 +118,7 @@ var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
118
118
|
FROM pain_events
|
|
119
119
|
WHERE canonical_pain_id = ?
|
|
120
120
|
LIMIT 1
|
|
121
|
-
`).get(e);return
|
|
121
|
+
`).get(e);return ht(t)?{id:t.id,sessionId:t.session_id,source:String(t.source),score:Number(t.score),reason:t.reason?String(t.reason):null,severity:t.severity?String(t.severity):null,origin:t.origin?String(t.origin):null,confidence:t.confidence!=null?Number(t.confidence):null,text:t.text?String(t.text):null,canonicalPainId:String(t.canonical_pain_id),runtimeTaskId:t.runtime_task_id?String(t.runtime_task_id):null,createdAt:String(t.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 Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
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,t,n){let s=
|
|
149
|
+
`).all(e).map(n=>({correctionCue:n.correction_cue?String(n.correction_cue):null}))}reviewCorrectionSample(e,t,n){let s=E();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(t,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,t,n??null,s),!0)))throw new
|
|
156
|
+
`).run(e,t,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
|
|
162
|
+
`).get(e);if(!i)throw new x(`${e} (after update)`);return t==="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 t=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:t,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 t=`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
|
|
@@ -169,14 +169,14 @@ var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
169
169
|
WHERE status = 'pending'
|
|
170
170
|
ORDER BY attempts ASC, created_at ASC
|
|
171
171
|
LIMIT ?
|
|
172
|
-
`).all(e).map(
|
|
172
|
+
`).all(e).map(yt)}bumpSignalConfirmationAttempt(e){return this.withWrite(()=>{this.db.prepare(`
|
|
173
173
|
UPDATE signal_confirmations SET attempts = attempts + 1
|
|
174
174
|
WHERE id = ? AND status = 'pending'
|
|
175
175
|
`).run(e)}),this.db.prepare("SELECT attempts FROM signal_confirmations WHERE id = ?").get(e)?.attempts??0}markSignalConfirmationResult(e,t,n){let s=this.withWrite(()=>this.db.prepare(`
|
|
176
176
|
UPDATE signal_confirmations
|
|
177
177
|
SET status = ?, resolved_at = ?, resolution = ?
|
|
178
178
|
WHERE id = ? AND status = 'pending'
|
|
179
|
-
`).run(t,
|
|
179
|
+
`).run(t,E(),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 t=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 Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
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=S.join(this.exportDir,`corrections-${Date.now()}-${e.mode}.jsonl`),s=t.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"?
|
|
188
|
+
`).all(e.approvedOnly?1:0),n=S.join(this.exportDir,`corrections-${Date.now()}-${e.mode}.jsonl`),s=t.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,d=e.mode==="redacted"?Oe(c):c;return JSON.stringify({sample_id:o.sample_id,session_id:o.session_id,instruction:d,input_context:a,bad_attempt_summary:String(o.diff_excerpt??""),preferred_response:d,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 P(n,`${s.join(`
|
|
189
189
|
`)}${s.length>0?`
|
|
190
|
-
`:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,n,t.length),{filePath:n,count:t.length,mode:e.mode}}exportAnalytics(){let e={generatedAt:
|
|
190
|
+
`:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,n,t.length),{filePath:n,count:t.length,mode:e.mode}}exportAnalytics(){let e={generatedAt:E(),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()},t=S.join(this.exportDir,`analytics-${Date.now()}.json`);return P(t,JSON.stringify(e,null,2)),this.recordExportAudit("analytics","raw",!0,t,Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0),{filePath:t,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)},t=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:
|
|
197
|
+
`).get();return{dbPath:this.dbPath,dbSizeBytes:he(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:t.ts??null}}cleanupBlobStorage(){return this.pruneUnreferencedBlobs()}initSchema(){let e=Ot(this.db);for(let n of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${n}`);let t=this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();this.migrateSchema(t?.version),t?t.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 Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
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 t=O(this.workspaceDir,"SESSION_DIR");if(
|
|
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 t=O(this.workspaceDir,"EVOLUTION_STREAM");if(!
|
|
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 t=O(this.workspaceDir,"SESSION_DIR");if(m.existsSync(t)){for(let n of m.readdirSync(t).filter(s=>s.endsWith(".json")))try{let s=JSON.parse(m.readFileSync(S.join(t,n),"utf8"));if(s.sessionId){let o=typeof s.lastActivityAt=="number"?new Date(s.lastActivityAt).toISOString():E();this.recordSession({sessionId:s.sessionId,startedAt:o})}}catch{}this.markImported(e)}}importLegacyEvents(){let e="legacy:events";if(this.isImported(e))return;let t=S.join(this.stateDir,"logs","events.jsonl");if(!m.existsSync(t))return;let n=m.readFileSync(t,"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 t=O(this.workspaceDir,"EVOLUTION_STREAM");if(!m.existsSync(t))return;let n=m.readFileSync(t,"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,
|
|
228
|
+
`).run(e,E())})}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 Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
|
|
|
248
248
|
WHERE session_id = ?
|
|
249
249
|
ORDER BY id DESC
|
|
250
250
|
LIMIT 5
|
|
251
|
-
`).all(e).filter(g=>g.outcome==="success"),c=i[0]?.id??n.id,a=`sample_${
|
|
251
|
+
`).all(e).filter(g=>g.outcome==="success"),c=i[0]?.id??n.id,a=`sample_${J.createHash("sha256").update(`${e}:${n.id}:${c}`).digest("hex").slice(0,12)}`,d=this.restoreRawText(n.raw_text,n.blob_ref),f=[n.references_assistant_turn_id?35:0,n.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((g,C)=>g+C,0),_=d||(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),
|
|
257
|
+
`).run(a,e,Number(n.references_assistant_turn_id),Number(n.id),y(i.map(g=>({id:g.id,toolName:g.tool_name,outcome:g.outcome}))),Rt(_),"[]",f,E(),E())})}recordExportAudit(e,t,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,t,n?1:0,s,o,
|
|
260
|
+
`).run(e,t,n?1:0,s,o,E())})}storeRawText(e,t){let n=t.length>200?`${t.slice(0,197)}...`:t;if(Buffer.byteLength(t,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:t,blobRef:null,excerpt:n};let o=J.createHash("sha256").update(t).digest("hex"),i=`${e}-${o}.txt`,c=S.join(this.blobDir,i);return m.existsSync(c)||P(c,t),{inlineText:null,blobRef:i,excerpt:n}}restoreRawText(e,t){if(e)return e;if(!t)return"";let n=S.join(this.blobDir,t);return m.existsSync(n)?m.readFileSync(n,"utf8"):""}computeBlobBytes(){return m.existsSync(this.blobDir)?m.readdirSync(this.blobDir).reduce((e,t)=>e+he(S.join(this.blobDir,t)),0):0}pruneUnreferencedBlobs(){if(!m.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,t=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 t)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of
|
|
264
|
+
`).all();for(let i of t)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of m.readdirSync(this.blobDir)){if(e.has(i))continue;let c=S.join(this.blobDir,i),a;try{a=m.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&n-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,m.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ee(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},v=class{static instances=new Map;static get(e,t={}){let n=S.resolve(e),s=this.instances.get(n);if(s)return s;let o=new j({workspaceDir:n,...t});return this.instances.set(n,o),o}static dispose(e){let t=S.resolve(e),n=this.instances.get(t);n&&(n.dispose(),this.instances.delete(t))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,t,n={}){let s=S.resolve(e),o=this.instances.get(s);if(o)return t(o);let i=new j({workspaceDir:s,...n});try{return t(i)}finally{i.dispose()}}};var bt=new Set(["__proto__","constructor","prototype"]);function Nt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function At(r){if(!Array.isArray(r))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],t=new Map;return r.forEach((n,s)=>{if(!Nt(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(bt.has(n.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=n.canonicalKind;if(!re(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...X].join("|")}, got ${String(o)}`);return}let i=t.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}t.set(n.rawToolName,o)}),{valid:e.length===0,errors:e}}function ye(r){let e,t=new Set,n=[];if(r===void 0)e=w;else{let s=At(r);if(!s.valid)return{ok:!1,errors:s.errors};let o={...w};for(let i of r)o[i.rawToolName]=i.canonicalKind,t.add(i.rawToolName);n=Object.freeze(r.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:t.size>0,hasHostTool(s){return typeof s!="string"?!1:t.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"],b=["write","edit","apply_patch"],L=["exec"],It=[...L],U=["sessions_spawn"],xt=[...b],vt=[...b,...L,...U],Lt=[...be],fr=new Set(be),gr=new Set(b),Sr=new Set(It),hr=new Set(L),Or=new Set(U),Rr=new Set(xt),yr=new Set(vt),br=new Set(Lt),Nr=new Set([...b]);function V(r,e){return r.map(t=>({rawToolName:t,canonicalKind:e}))}var Ct=Object.freeze([...V(L,"execute"),...V(b,"write"),...V(U,"agent")]),Z=ye(Ct);if(!Z.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${Z.errors.join("; ")}`);var Ne=Z.registry;var Q=class extends M{constructor(e){super({source:v.get(e.workspaceDir),toolSemantics:Ne})}};export{Q as BehaviorExamplePackAssembler,v as RuleHostEvidenceRegistry};
|