create-principles-disciple 1.146.1 → 1.146.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/console/dist/server/models/ActivationsConsoleModel.d.ts +3 -0
  3. package/console/dist/server/models/ActivationsConsoleModel.js +25 -1
  4. package/console/dist/server/models/ApprovalsConsoleModel.d.ts +5 -0
  5. package/console/dist/server/models/ApprovalsConsoleModel.js +40 -2
  6. package/console/dist/server/routes/activations.js +47 -0
  7. package/console/dist/server/routes/approvals.js +1 -1
  8. package/console/dist/shared/approved-rule-revision-contract.d.ts +8 -0
  9. package/console/dist/shared/approved-rule-revision-contract.js +48 -0
  10. package/console/dist/ui/api.d.ts +3 -0
  11. package/console/dist/ui/api.js +9 -0
  12. package/console/dist/ui/i18n/en.json +7 -0
  13. package/console/dist/ui/i18n/zh-CN.json +7 -0
  14. package/console/dist/ui/pages/activation/ActivationPage.js +69 -2
  15. package/console/dist/web/assets/app.css +3 -0
  16. package/console/dist/web/assets/app.js +31 -31
  17. package/core/dist/runtime-v2/activation/activation-dispatcher.d.ts +2 -0
  18. package/core/dist/runtime-v2/activation/activation-dispatcher.d.ts.map +1 -1
  19. package/core/dist/runtime-v2/activation/activation-dispatcher.js +60 -22
  20. package/core/dist/runtime-v2/activation/activation-dispatcher.js.map +1 -1
  21. package/core/dist/runtime-v2/activation/activation-types.d.ts +12 -2
  22. package/core/dist/runtime-v2/activation/activation-types.d.ts.map +1 -1
  23. package/core/dist/runtime-v2/activation/activation-types.js.map +1 -1
  24. package/core/dist/runtime-v2/activation/index.d.ts +2 -0
  25. package/core/dist/runtime-v2/activation/index.d.ts.map +1 -1
  26. package/core/dist/runtime-v2/activation/index.js +2 -0
  27. package/core/dist/runtime-v2/activation/index.js.map +1 -1
  28. package/core/dist/runtime-v2/activation/rule-replacement.d.ts +38 -0
  29. package/core/dist/runtime-v2/activation/rule-replacement.d.ts.map +1 -0
  30. package/core/dist/runtime-v2/activation/rule-replacement.js +44 -0
  31. package/core/dist/runtime-v2/activation/rule-replacement.js.map +1 -0
  32. package/core/dist/runtime-v2/activation/sqlite-activation-state-store.d.ts +9 -1
  33. package/core/dist/runtime-v2/activation/sqlite-activation-state-store.d.ts.map +1 -1
  34. package/core/dist/runtime-v2/activation/sqlite-activation-state-store.js +53 -23
  35. package/core/dist/runtime-v2/activation/sqlite-activation-state-store.js.map +1 -1
  36. package/core/dist/runtime-v2/activation/writers/rule-host-writer.d.ts.map +1 -1
  37. package/core/dist/runtime-v2/activation/writers/rule-host-writer.js +15 -2
  38. package/core/dist/runtime-v2/activation/writers/rule-host-writer.js.map +1 -1
  39. package/core/dist/runtime-v2/adapter/principle-tree-ledger-adapter.d.ts +2 -0
  40. package/core/dist/runtime-v2/adapter/principle-tree-ledger-adapter.d.ts.map +1 -1
  41. package/core/dist/runtime-v2/adapter/principle-tree-ledger-adapter.js +5 -1
  42. package/core/dist/runtime-v2/adapter/principle-tree-ledger-adapter.js.map +1 -1
  43. package/core/dist/runtime-v2/index.d.ts +3 -1
  44. package/core/dist/runtime-v2/index.d.ts.map +1 -1
  45. package/core/dist/runtime-v2/index.js +2 -1
  46. package/core/dist/runtime-v2/index.js.map +1 -1
  47. package/core/dist/runtime-v2/internalization/approved-rule-revision.d.ts +51 -0
  48. package/core/dist/runtime-v2/internalization/approved-rule-revision.d.ts.map +1 -0
  49. package/core/dist/runtime-v2/internalization/approved-rule-revision.js +211 -0
  50. package/core/dist/runtime-v2/internalization/approved-rule-revision.js.map +1 -0
  51. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts +1 -1
  52. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.d.ts.map +1 -1
  53. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js +2 -1
  54. package/core/dist/runtime-v2/internalization/artificer-prompt-builder.js.map +1 -1
  55. package/core/dist/runtime-v2/internalization/bash-risk.d.ts +4 -0
  56. package/core/dist/runtime-v2/internalization/bash-risk.d.ts.map +1 -1
  57. package/core/dist/runtime-v2/internalization/bash-risk.js +42 -0
  58. package/core/dist/runtime-v2/internalization/bash-risk.js.map +1 -1
  59. package/core/dist/runtime-v2/internalization/evaluator-runner.d.ts.map +1 -1
  60. package/core/dist/runtime-v2/internalization/evaluator-runner.js +4 -1
  61. package/core/dist/runtime-v2/internalization/evaluator-runner.js.map +1 -1
  62. package/core/dist/runtime-v2/internalization/peer-runner-contracts.d.ts +2 -1
  63. package/core/dist/runtime-v2/internalization/peer-runner-contracts.d.ts.map +1 -1
  64. package/core/dist/runtime-v2/internalization/peer-runner-contracts.js.map +1 -1
  65. package/core/dist/runtime-v2/internalization/pitask-metadata.d.ts +21 -0
  66. package/core/dist/runtime-v2/internalization/pitask-metadata.d.ts.map +1 -1
  67. package/core/dist/runtime-v2/internalization/pitask-metadata.js +30 -0
  68. package/core/dist/runtime-v2/internalization/pitask-metadata.js.map +1 -1
  69. package/core/dist/runtime-v2/internalization/rule-host-contracts.d.ts +2 -0
  70. package/core/dist/runtime-v2/internalization/rule-host-contracts.d.ts.map +1 -1
  71. package/core/dist/runtime-v2/internalization/rule-host-input-builder.d.ts.map +1 -1
  72. package/core/dist/runtime-v2/internalization/rule-host-input-builder.js +6 -0
  73. package/core/dist/runtime-v2/internalization/rule-host-input-builder.js.map +1 -1
  74. package/core/dist/runtime-v2/internalization/rulecode-verification-obligations.d.ts.map +1 -1
  75. package/core/dist/runtime-v2/internalization/rulecode-verification-obligations.js +32 -0
  76. package/core/dist/runtime-v2/internalization/rulecode-verification-obligations.js.map +1 -1
  77. package/core/dist/runtime-v2/proven-channel-baseline.js +1 -1
  78. package/core/dist/runtime-v2/proven-channel-baseline.js.map +1 -1
  79. package/core/dist/runtime-v2/store/task/sqlite-approved-rule-revision.d.ts +15 -0
  80. package/core/dist/runtime-v2/store/task/sqlite-approved-rule-revision.d.ts.map +1 -0
  81. package/core/dist/runtime-v2/store/task/sqlite-approved-rule-revision.js +39 -0
  82. package/core/dist/runtime-v2/store/task/sqlite-approved-rule-revision.js.map +1 -0
  83. package/core/package.json +1 -1
  84. package/host-runtime/dist/production-rulehost-gate.js +11 -2
  85. package/package.json +1 -1
  86. package/pd-cli/package.json +1 -1
  87. package/plugin/dist/bundle.js +477 -472
  88. package/plugin/dist/openclaw.plugin.json +1 -1
  89. package/plugin/dist/rulehost-evidence.js +52 -49
  90. 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.2.11",
5
+ "version": "2.2.12",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
@@ -1,50 +1,53 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
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, host_kind 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}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind 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.upsertSessionUnlocked(e.sessionId,r)})}upsertSessionUnlocked(e,r){this.db.prepare(`
2
+ var Ce=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):n)(function(n){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+n+'" is not supported')});var te=Object.freeze([Object.freeze({capabilityId:"pd_status",channel:"cli",cliCommand:"pd activation list --json"}),Object.freeze({capabilityId:"rulecode_deactivate",channel:"cli",cliCommand:"pd activation deactivate --activation-id recovery-probe"}),Object.freeze({capabilityId:"rulecode_global_pause",channel:"console",consoleRoute:"/api/v1/activations/emergency-pause"}),Object.freeze({capabilityId:"owner_review_access",channel:"console",consoleRoute:"/api/v1/activations/{activationId}/owner-review"})]);var re="",De="|;&<>()";function k(n){return De.includes(n)?`${re}${n}`:n}function ne(n){if(n.includes(re))return null;let e=[],t="",r=!1,s=0,o=n.length,i="plain";for(;s<o;){let c=n[s];if(c===void 0)break;if(i==="single"){c==="'"?i="plain":t+=k(c),s+=1;continue}if(i==="double"){if(c==='"')i="plain";else if(c==="\\"&&s+1<o&&'"\\$`'.includes(n[s+1]??"")){t+=k(n[s+1]??""),s+=2;continue}else t+=k(c);s+=1;continue}if(c==="'"){i="single",r=!0,s+=1;continue}if(c==='"'){i="double",r=!0,s+=1;continue}if(c==="\\"&&s+1<o){t+=k(n[s+1]??""),r=!0,s+=2;continue}if(c==="\r"||c===`
3
+ `){(r||t)&&(e.push(t),t="",r=!1),c==="\r"&&n[s+1]===`
4
+ `&&(s+=1),e.push(`
5
+ `),s+=1;continue}if(" ".includes(c)){(r||t)&&(e.push(t),t="",r=!1),s+=1;continue}if("|;&<>()".includes(c)){(r||t)&&(e.push(t),t="",r=!1);let a=c,d=n[s+1];c==="<"&&d===">"?a="<>":(c==="|"||c==="&"||c===">"||c==="<")&&d===c&&(a+=d),(c===">"||c==="<")&&d==="("&&(a+=d),e.push(a),s+=a.length;continue}t+=c,r=!0,s+=1}return i!=="plain"?null:((r||t)&&e.push(t),e)}function se(n){if(/[\\$`|;&<>()*?~{}]/.test(n)||[...n].some(s=>s.charCodeAt(0)<32))return;let e=ne(n);if(!e)return;let t=[...e],r=t.findIndex(s=>s==="-w"||s==="--workspace");if(r!==-1){let s=t[r+1];if(r!==t.length-2||!s||s.startsWith("-"))return;t.splice(r,2)}for(let s of te){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=ne(s.cliCommand);if(!o||o.length!==t.length)continue;if(o.every((c,a)=>s.capabilityId==="rulecode_deactivate"&&o[a-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(t[a]??""):c===t[a]))return s.capabilityId}}function L(n,e=!1){let t=[];for(let r of n.split("/").filter(s=>s.length>0))r!=="."&&(r===".."?t.length>0&&t[t.length-1]!==".."?t.pop():e&&t.push(".."):t.push(r));return t}function W(n){let e=/^([a-zA-Z]):(?:\/|$)/.exec(n);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:L(n.slice(2))};if(/^[a-zA-Z]:/.test(n))return{kind:"drive-relative",root:n.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(n)){let t=n.slice(2).split("/").filter(o=>o.length>0),r=t[0]??"",s=t[1]??"";return{kind:"unc",root:`unc:${r}/${s}`,segments:L(t.slice(2).join("/"))}}return n.startsWith("/")?{kind:"posix",root:"posix:/",segments:L(n)}:{kind:"relative",root:"",segments:L(n,!0)}}function oe(n,e,t){return n.length<e.length?!1:e.every((r,s)=>{let o=n[s]??"";return t?o.toLowerCase()===r.toLowerCase():o===r})}function Me(n,e,t){let r=0;for(;r<n.length&&r<e.length;){let o=n[r]??"",i=e[r]??"";if(!(t?o.toLowerCase()===i.toLowerCase():o===i))break;r++}return[...Array.from({length:n.length-r},()=>".."),...e.slice(r)].join("/")||"."}function ie(n){let[e,t]=n.root.slice(4).split("/"),r=n.segments.join("/");return`//${e??""}/${t??""}${r?`/${r}`:""}`}function ae(n,e,t){if(n.kind==="drive-relative"||n.kind==="unc"&&n.root.endsWith("/"))return t;if(n.kind!=="relative")return!(n.kind===e.kind&&(n.kind==="unc"?n.root.toLowerCase()===e.root.toLowerCase():n.root===e.root))||!oe(n.segments,e.segments,n.kind==="drive"||n.kind==="unc")?n.kind==="unc"?ie(n):t:n.segments.slice(e.segments.length).join("/")||".";let r=[...e.segments];for(let o of t.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e.kind==="relative"&&r.push(".."):r.push(o));let s=e.kind==="drive"||e.kind==="unc";return oe(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":Me(e.segments,r,s)}function Pe(n,e){if(!n||typeof n!="string")return"";let t=n.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(t.startsWith("<tool:")&&t.endsWith(">"))return t;let s=W(t),o=W(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=W(c),ae(s,o,c)}return ae(s,o,t)}function je(n,e){let t=n.file_path||n.path||n.file||n.target;if(typeof t=="string"&&t.length>0)return{value:t,isPath:!0};if(e.isBashTool){let r=String(n.command||n.args||"");if(r){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(r);return s&&s[1]?{value:s[1],isPath:!0}:{value:r,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function Ue(n){return{isBashTool:n==="execute",isWriteTool:n==="write"}}function Be(n){if(n.canonicalKind===void 0)return n;let e=Ue(n.canonicalKind);return{...n,isBashTool:n.isBashTool??e.isBashTool,isWriteTool:n.isWriteTool??e.isWriteTool}}function C(n,e,t,r={}){let s=Be(r),o=je(e,{...s,toolName:n}),i=o.isPath?Pe(o.value,t):o.value,c=e.command??e.args,a=s.isBashTool&&typeof c=="string"?se(c):void 0;return{toolName:n,normalizedPath:i,...a?{recoveryControl:a}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function ce(n){return typeof n=="string"&&X.has(n)}var D=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 le(n,e,t){if(n.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let r=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=n;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(r++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:r,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:t}}var ue={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ue);var $={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($.calls);Object.freeze($);var Fe={version:2,history:$,facts:ue};Object.freeze(Fe);var We=new Set(["__proto__","constructor","prototype"]),de=3,Xe=5,$e=new Set(["allow","block","propose_correction"]),He={valid:!0,errors:[]};function H(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function _e(n){for(let e of Object.keys(n))if(We.has(e))return!1;return!0}function Ye(n){return n.length===0?He:{valid:!1,errors:n}}function Y(n){return typeof n=="string"&&n.trim().length>0}function pe(n,e,t){let r=[];return H(n)?_e(n)?((!Object.hasOwn(n,"caseId")||!Y(n.caseId))&&r.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(n,"kind")||n.kind!==t)&&r.push(`${e}.kind must be '${t}'`),(!Object.hasOwn(n,"toolName")||!Y(n.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(n,"params")||!H(n.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(n,"expectedDecision")||typeof n.expectedDecision!="string"||!$e.has(n.expectedDecision)?r.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):t==="positive"&&n.expectedDecision!=="allow"&&r.push(`${e}: positive cases must expect allow`),r):(r.push(`${e} must not carry prototype-pollution keys`),r):(r.push(`${e} must be a plain object`),r)}function fe(n,e){let{fieldName:t,maxLength:r,requireNonEmpty:s}=e,o=[];if(!Array.isArray(n))return o.push(`${t} must be an array`),o;s&&n.length===0&&o.push(`${t} must contain at least 1 item`),r!==void 0&&n.length>r&&o.push(`${t} must contain at most ${r} items, got ${n.length}`);for(let i=0;i<n.length;i++)typeof n[i]!="string"&&o.push(`${t}[${i}] must be a string`);return o}function M(n){return Array.isArray(n)?`[${n.map(e=>M(e)).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.keys(n).filter(t=>t!=="__proto__"&&t!=="constructor"&&t!=="prototype").sort().map(t=>`${JSON.stringify(t)}:${M(n[t])}`).join(",")}}`:JSON.stringify(n)??"null"}function K(n){if(!H(n))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!_e(n))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(n,"sourceNegativeCase")?e.push(...pe(n.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(n,"ownerDesiredOutcome")||!Y(n.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(n,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(n.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let t=n.positiveCounterexamples;t.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),t.length>de&&e.push(`positiveCounterexamples must contain at most ${de} items, got ${t.length}`);for(let r=0;r<t.length;r++)e.push(...pe(t[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(n,"evidenceRefs")?e.push(...fe(n.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Xe,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(n,"redactionNotes")?e.push(...fe(n.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let t=n.sourceNegativeCase,r=n.positiveCounterexamples,s=M({toolName:t.toolName,params:t.params,ruleContext:t.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&M({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 Ye(e)}var Ke="OwnerEvidenceScopeError";function N(n,e){let t=new Error(e);return t.name=Ke,Object.assign(t,{ownerEvidenceScopeKind:n}),t}var Ge=new Set(["success","failure","blocked"]);function qe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function ze(n){return typeof n=="string"&&Ge.has(n)}function A(n){return{status:"unavailable",unavailableReason:n,truncated:!1,calls:[]}}function me(n,e,t){let{projectDir:r,toolSemantics:s}=t,o=[];for(let i of n){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(!ze(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 h;try{h=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!qe(h))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=C(c,h,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:h,outcome:a})}return{status:"available",truncated:e,calls:o}}var Ve=3,Je=5,Ze=100,Te=new Set(["__proto__","constructor","prototype"]);function P(n,e){try{return e()}catch(t){let r=t instanceof Error?t.message:String(t);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${n} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function Qe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function et(n){for(let e of Object.keys(n))if(Te.has(e))return!1;return!0}function tt(n){if(!Number.isSafeInteger(n.sourceNegativeToolCallId)||n.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(n.positiveToolCallIds)||n.positiveToolCallIds.length===0||n.positiveToolCallIds.length>Ve)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[n.sourceNegativeToolCallId,...n.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 Ee(n,e){if(!n)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return n}function nt(n,e,t){if(typeof n.toolName!="string"||n.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof n.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: paramsJson must be a string (rc-9 fail loud)`);let r;try{r=JSON.parse(n.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Qe(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!et(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${n.id}`,kind:e,toolName:n.toolName,params:r,expectedDecision:t}}function rt(n){return n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n)}var st=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ot(n){if(n.length<20)return!1;for(let e of st)if(e.test(n))return!0;return!1}function it(n,e){let t=[],r={};for(let s of Object.keys(n)){if(Te.has(s))continue;let o=n[s];if(typeof o!="string"){r[s]=o;continue}if(rt(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ot(o)){r[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}r[s]=o}return{redacted:r,notes:t}}var j=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=P(`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)`);tt(e);let r=Ee(P(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>Ee(P(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==t.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${t.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(r,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${t.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,Je),redactionNotes:o},h=K(d);if(!h.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${h.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,r){let{projectDir:s,redactionNotes:o}=r,i=nt(e,t,t==="negative"?"block":"allow"),c=it(i.params,s);o.push(...c.notes);let a=P(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Ze)),d=me(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),h=C(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:le(d,h.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import At from"better-sqlite3";import f from"fs";import T from"path";import J from"crypto";import*as p from"fs";import*as ge from"path";var G=class extends Error{filePath;lockPath;constructor(e,t,r){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=r}},at={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Se(n){try{return process.kill(n,0),!0}catch{return!1}}function he(n,e){try{let t=ge.dirname(n);p.existsSync(t)||p.mkdirSync(t,{recursive:!0});let r=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(n,r);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(n){try{let e=p.readFileSync(n,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function ct(n,e){try{I(n)===e&&p.unlinkSync(n)}catch{}}function lt(n,e){try{let t=p.statSync(n),r=I(n),s=Date.now()-t.mtimeMs>e,o=r===null||!Se(r);if(s||o)try{return p.unlinkSync(n),!0}catch{return!1}return!1}catch{return!1}}function ut(n,e,t){let r=Math.min(e*Math.pow(2,n),t),s=r*.2*Math.random();return Math.floor(r+s)}function dt(n){let e=Date.now()+n;for(;Date.now()<e;);}function pt(n,e){let t=I(e),r=t!==null?Se(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new G(`Failed to acquire lock for ${n}. Lock holder: ${r}.`,n,e)}function ft(n,e,t){let r=n+e.lockSuffix;return he(r,t)&&I(r)===t?{lockPath:r,pid:t,acquiredAt:Date.now()}:(lt(r,e.lockStaleMs),he(r,t)&&I(r)===t?{lockPath:r,pid:t,acquiredAt:Date.now()}:null)}function _t(n,e={}){let t={...at,...e},{pid:r}=process;for(let s=0;s<t.maxRetries;s++){let o=ft(n,t,r);if(o)return o;if(s<t.maxRetries-1){let i=ut(s,t.baseRetryDelayMs,t.maxRetryDelayMs);dt(i)}}throw pt(n,n+t.lockSuffix)}function mt(n){ct(n.lockPath,n.pid)}function ye(n,e,t={}){let r=_t(n,t);try{return e()}finally{mt(r)}}import*as b from"fs";var be=3,Et=50;function U(n,e){let t=n+".tmp";b.writeFileSync(t,e,"utf8");let r;for(let s=0;s<be;s++)try{b.renameSync(t,n);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<be-1){let c=Et*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Ce("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{b.unlinkSync(t)}catch{}throw r}import*as S from"path";var l=(...n)=>S.posix.join(...n);function Tt(n){return/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\\\")}function ht(n,e){return Tt(n)?S.win32.join(n,e):n.startsWith("/")?S.posix.join(n,e):S.join(n,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")},gt={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 y(n,e){return ht(n,gt[e])}var St={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"},q=class extends Error{constructor(t,r,s){super(t,s);this.code=r;this.name="PdError",this.category=St[r]??"execution_failed"}code;category};var x=class extends q{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var yt=["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(n){let e=n instanceof Error?n.message:String(n);return e.includes("duplicate column name")||e.includes("no column named")}function bt(n,e){return n.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Re(n,e={}){let t=[],r=[...yt];n.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),n.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),n.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),n.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)"),n.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)"),n.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, host_kind TEXT)"),n.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)"),n.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)"),n.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)"),n.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)"),n.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)"),n.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)"),n.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)"),n.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)"),n.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{n.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}n.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{n.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(n.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"),bt(n,"evolution_tasks")){try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{n.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return n.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),n.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),n.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),n.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),n.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),n.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),n.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),n.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),n.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(n.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"),n.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"),n.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:r,warnings:t}}import*as z from"path";import*as Oe from"os";var Rt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],Ot=z.join(Oe.tmpdir(),".pd-test-quarantine");function Nt(n){if(!n)return!1;let e=n.replace(/\\/g,"/");return Rt.some(t=>t.test(e))}function Ne(n){if(!n||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Nt(n))return n;let t=n.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;t.startsWith("_");)t=t.slice(1);for(;t.endsWith("_");)t=t.slice(0,-1);return z.join(Ot,t)}var It=16*1024,xt=5e3,vt=7;function xe(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function wt(n){return!xe(n)||typeof n.id!="number"||typeof n.session_id!="string"?!1:Object.hasOwn(n,"source")&&Object.hasOwn(n,"score")&&Object.hasOwn(n,"reason")&&Object.hasOwn(n,"severity")&&Object.hasOwn(n,"origin")&&Object.hasOwn(n,"confidence")&&Object.hasOwn(n,"text")&&Object.hasOwn(n,"canonical_pain_id")&&Object.hasOwn(n,"runtime_task_id")&&Object.hasOwn(n,"created_at")}function kt(n){let e=Re(n,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function R(n){return JSON.stringify(n??{})}function Ae(n){try{return f.existsSync(n)?f.statSync(n).size:0}catch{return 0}}function Lt(n){return n.length>240?`${n.slice(0,237)}...`:n}function Ie(n){return n.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 Ct(n){let e=[],t=!1;try{let r=JSON.parse(String(n.terms_json??"[]"));if(Array.isArray(r))e=r.filter(s=>typeof s=="string");else if(r!==null&&typeof r=="object"){let s=r;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(n.id),sessionId:String(n.session_id),userTurnRowid:Number(n.user_turn_rowid),occurrenceId:String(n.occurrence_id),excerpt:String(n.excerpt),terms:e,termsVerified:t,suggestedType:String(n.suggested_type),status:String(n.status),attempts:Number(n.attempts??0),createdAt:String(n.created_at),resolvedAt:n.resolved_at===null||n.resolved_at===void 0?null:String(n.resolved_at),resolution:n.resolution===null||n.resolution===void 0?null:String(n.resolution)}}var B=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Ne(T.resolve(e.workspaceDir)),this.stateDir=y(this.workspaceDir,"STATE_DIR"),this.dbPath=y(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=y(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=y(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??It,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??vt)*24*60*60*1e3),f.mkdirSync(this.stateDir,{recursive:!0}),f.mkdirSync(this.blobDir,{recursive:!0}),f.mkdirSync(this.exportDir,{recursive:!0}),this.db=new At(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??xt)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let t=e.startedAt??_();this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,t)})}upsertSessionUnlocked(e,t){this.db.prepare(`
3
6
  INSERT INTO sessions (session_id, started_at, updated_at)
4
7
  VALUES (?, ?, ?)
5
8
  ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
6
- `).run(e,r,f())}recordAssistantTurn(e){let r=this.storeRawText("assistant",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??n);let s=this.db.prepare(`
9
+ `).run(e,t,_())}recordAssistantTurn(e){let t=this.storeRawText("assistant",e.rawText),r=e.createdAt??_();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??r);let s=this.db.prepare(`
7
10
  INSERT INTO assistant_turns (
8
11
  session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
9
12
  empathy_signal_json, blob_ref, raw_excerpt, stop_reason, thinking_blocks_count, created_at
10
13
  ) 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){let r=this.storeRawText("user",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??n);let s=this.db.prepare(`
14
+ `).run(e.sessionId,e.runId,e.provider,e.model,t.inlineText,e.sanitizedText,R(e.usageJson),R(e.empathySignalJson),t.blobRef,t.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,r);return Number(s.lastInsertRowid)})}recordUserTurn(e){let t=this.storeRawText("user",e.rawText),r=e.createdAt??_();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??r);let s=this.db.prepare(`
12
15
  INSERT INTO user_turns (
13
16
  session_id, turn_index, raw_text, blob_ref, raw_excerpt,
14
17
  correction_detected, correction_cue, references_assistant_turn_id, created_at
15
18
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
16
- `).run(e.sessionId,e.turnIndex,r.inlineText,r.blobRef,r.excerpt,e.correctionDetected?1:0,e.correctionCue??null,e.referencesAssistantTurnId??null,n);return Number(s.lastInsertRowid)})}markUserTurnCorrection(e,r){let n=this.withWrite(()=>this.db.prepare(`
19
+ `).run(e.sessionId,e.turnIndex,t.inlineText,t.blobRef,t.excerpt,e.correctionDetected?1:0,e.correctionCue??null,e.referencesAssistantTurnId??null,r);return Number(s.lastInsertRowid)})}markUserTurnCorrection(e,t){let r=this.withWrite(()=>this.db.prepare(`
17
20
  UPDATE user_turns
18
21
  SET correction_detected = 1, correction_cue = ?
19
22
  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??f(),n=this.withWrite(()=>{let s=this.db.prepare(`
23
+ `).run(t??null,e));return Number(r.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=e.createdAt??_(),r=this.withWrite(()=>{let s=this.db.prepare(`
21
24
  INSERT INTO tool_calls (
22
25
  session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
23
26
  gfi_before, gfi_after, params_json, result_preview, created_at
24
27
  ) 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,y(e.paramsJson),e.resultPreview??null,r);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),n}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let r=-1;return this.withWrite(()=>{try{let n=this.db.prepare(`
28
+ `).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,R(e.paramsJson),e.resultPreview??null,t);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),r}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=-1;return this.withWrite(()=>{try{let r=this.db.prepare(`
26
29
  INSERT INTO pain_events (
27
30
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
28
31
  canonical_pain_id, runtime_task_id, host_kind
29
32
  ) 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??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(`
33
+ `).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.canonicalPainId??null,e.runtimeTaskId??null,e.hostKind??null);t=Number(r.lastInsertRowid)}catch(r){if(e.canonicalPainId&&r instanceof Error&&r.message.includes("UNIQUE constraint failed")&&r.message.includes("canonical_pain_id")){this.db.prepare(`
31
34
  UPDATE pain_events
32
35
  SET runtime_task_id = COALESCE(?, runtime_task_id),
33
36
  host_kind = COALESCE(host_kind, ?)
34
37
  WHERE canonical_pain_id = ?
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(`
38
+ `).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 r}}),t}recordGateBlock(e){this.withWrite(()=>{this.db.prepare(`
36
39
  INSERT INTO gate_blocks (session_id, tool_name, file_path, reason, created_at)
37
40
  VALUES (?, ?, ?, ?, ?)
38
- `).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??f())})}recordTrustChange(e){this.withWrite(()=>{this.db.prepare(`
41
+ `).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??_())})}recordTrustChange(e){this.withWrite(()=>{this.db.prepare(`
39
42
  INSERT INTO trust_changes (session_id, previous_score, new_score, delta, reason, created_at)
40
43
  VALUES (?, ?, ?, ?, ?, ?)
41
- `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??f())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
44
+ `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??_())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
42
45
  INSERT INTO principle_events (principle_id, event_type, payload_json, created_at)
43
46
  VALUES (?, ?, ?, ?)
44
- `).run(e.principleId??null,e.eventType,y(e.payload),e.createdAt??f())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
47
+ `).run(e.principleId??null,e.eventType,R(e.payload),e.createdAt??_())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
45
48
  INSERT INTO task_outcomes (session_id, task_id, outcome, summary, principle_ids_json, created_at)
46
49
  VALUES (?, ?, ?, ?, ?, ?)
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(`
50
+ `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,R(e.principleIdsJson),e.createdAt??_())})}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=[],r=[];e.status&&(t.push("status = ?"),r.push(e.status)),e.dateFrom&&(t.push("created_at >= ?"),r.push(e.dateFrom)),e.dateTo&&(t.push("created_at <= ?"),r.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
51
  SELECT id, task_id, trace_id, source, reason, score, status,
49
52
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
50
53
  task_kind, priority, retry_count, max_retries, last_error, result_ref
@@ -52,131 +55,131 @@ var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
52
55
  ${s}
53
56
  ORDER BY created_at DESC
54
57
  LIMIT ? OFFSET ?
55
- `).all(...n,o,i).map(a=>({id:Number(a.id),taskId:String(a.task_id),traceId:String(a.trace_id),source:String(a.source),reason:a.reason?String(a.reason):null,score:Number(a.score??0),status:String(a.status),enqueuedAt:a.enqueued_at?String(a.enqueued_at):null,startedAt:a.started_at?String(a.started_at):null,completedAt:a.completed_at?String(a.completed_at):null,resolution:a.resolution?String(a.resolution):null,createdAt:String(a.created_at),updatedAt:String(a.updated_at),taskKind:a.task_kind?a.task_kind:null,priority:a.priority?a.priority:null,retryCount:a.retry_count!=null?Number(a.retry_count):null,maxRetries:a.max_retries!=null?Number(a.max_retries):null,lastError:a.last_error?String(a.last_error):null,resultRef:a.result_ref?String(a.result_ref):null}))}listEvolutionEvents(e,r={}){if(this.evolutionTableMissing("evolution_events"))return[];let n=r.limit??100,s=r.offset??0,o;return e?o=this.db.prepare(`
58
+ `).all(...r,o,i).map(a=>({id:Number(a.id),taskId:String(a.task_id),traceId:String(a.trace_id),source:String(a.source),reason:a.reason?String(a.reason):null,score:Number(a.score??0),status:String(a.status),enqueuedAt:a.enqueued_at?String(a.enqueued_at):null,startedAt:a.started_at?String(a.started_at):null,completedAt:a.completed_at?String(a.completed_at):null,resolution:a.resolution?String(a.resolution):null,createdAt:String(a.created_at),updatedAt:String(a.updated_at),taskKind:a.task_kind?a.task_kind:null,priority:a.priority?a.priority:null,retryCount:a.retry_count!=null?Number(a.retry_count):null,maxRetries:a.max_retries!=null?Number(a.max_retries):null,lastError:a.last_error?String(a.last_error):null,resultRef:a.result_ref?String(a.result_ref):null}))}listEvolutionEvents(e,t={}){if(this.evolutionTableMissing("evolution_events"))return[];let r=t.limit??100,s=t.offset??0,o;return e?o=this.db.prepare(`
56
59
  SELECT id, trace_id, task_id, stage, level, message, summary, metadata_json, created_at
57
60
  FROM evolution_events
58
61
  WHERE trace_id = ?
59
62
  ORDER BY created_at ASC
60
63
  LIMIT ? OFFSET ?
61
- `).all(e,n,s):o=this.db.prepare(`
64
+ `).all(e,r,s):o=this.db.prepare(`
62
65
  SELECT id, trace_id, task_id, stage, level, message, summary, metadata_json, created_at
63
66
  FROM evolution_events
64
67
  ORDER BY created_at DESC
65
68
  LIMIT ? OFFSET ?
66
- `).all(n,s),o.map(i=>({id:Number(i.id),traceId:String(i.trace_id),taskId:i.task_id?String(i.task_id):null,stage:String(i.stage),level:String(i.level??"info"),message:String(i.message),summary:i.summary?String(i.summary):null,metadata:JSON.parse(String(i.metadata_json??"{}")),createdAt:String(i.created_at)}))}getEvolutionTaskByTraceId(e){if(this.evolutionTableMissing("evolution_tasks"))return null;let r=this.db.prepare(`
69
+ `).all(r,s),o.map(i=>({id:Number(i.id),traceId:String(i.trace_id),taskId:i.task_id?String(i.task_id):null,stage:String(i.stage),level:String(i.level??"info"),message:String(i.message),summary:i.summary?String(i.summary):null,metadata:JSON.parse(String(i.metadata_json??"{}")),createdAt:String(i.created_at)}))}getEvolutionTaskByTraceId(e){if(this.evolutionTableMissing("evolution_tasks"))return null;let t=this.db.prepare(`
67
70
  SELECT id, task_id, trace_id, source, reason, score, status,
68
71
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
69
72
  task_kind, priority, retry_count, max_retries, last_error, result_ref
70
73
  FROM evolution_tasks
71
74
  WHERE trace_id = ?
72
75
  LIMIT 1
73
- `).get(e);return r?{id:Number(r.id),taskId:String(r.task_id),traceId:String(r.trace_id),source:String(r.source),reason:r.reason?String(r.reason):null,score:Number(r.score??0),status:String(r.status),enqueuedAt:r.enqueued_at?String(r.enqueued_at):null,startedAt:r.started_at?String(r.started_at):null,completedAt:r.completed_at?String(r.completed_at):null,resolution:r.resolution?String(r.resolution):null,createdAt:String(r.created_at),updatedAt:String(r.updated_at),taskKind:r.task_kind?r.task_kind:null,priority:r.priority?r.priority:null,retryCount:r.retry_count!=null?Number(r.retry_count):null,maxRetries:r.max_retries!=null?Number(r.max_retries):null,lastError:r.last_error?String(r.last_error):null,resultRef:r.result_ref?String(r.result_ref):null}:null}getEvolutionStats(){if(this.evolutionTableMissing("evolution_tasks"))return{total:0,pending:0,inProgress:0,completed:0,failed:0};let e=this.db.prepare(`
76
+ `).get(e);return t?{id:Number(t.id),taskId:String(t.task_id),traceId:String(t.trace_id),source:String(t.source),reason:t.reason?String(t.reason):null,score:Number(t.score??0),status:String(t.status),enqueuedAt:t.enqueued_at?String(t.enqueued_at):null,startedAt:t.started_at?String(t.started_at):null,completedAt:t.completed_at?String(t.completed_at):null,resolution:t.resolution?String(t.resolution):null,createdAt:String(t.created_at),updatedAt:String(t.updated_at),taskKind:t.task_kind?t.task_kind:null,priority:t.priority?t.priority:null,retryCount:t.retry_count!=null?Number(t.retry_count):null,maxRetries:t.max_retries!=null?Number(t.max_retries):null,lastError:t.last_error?String(t.last_error):null,resultRef:t.result_ref?String(t.result_ref):null}:null}getEvolutionStats(){if(this.evolutionTableMissing("evolution_tasks"))return{total:0,pending:0,inProgress:0,completed:0,failed:0};let e=this.db.prepare(`
74
77
  SELECT status, COUNT(*) as count FROM evolution_tasks GROUP BY status
75
- `).all(),r={total:0,pending:0,inProgress:0,completed:0,failed:0};for(let n of e)r.total+=n.count,n.status==="pending"?r.pending=n.count:n.status==="in_progress"?r.inProgress=n.count:n.status==="completed"?r.completed=n.count:n.status==="failed"&&(r.failed=n.count);return r}listRecentSessions(e={}){let r=[],n=[];e.dateFrom&&(r.push("updated_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(r.push("updated_at <= ?"),n.push(e.dateTo));let s=r.length>0?`WHERE ${r.join(" AND ")}`:"",o=e.limit??20;return this.db.prepare(`
78
+ `).all(),t={total:0,pending:0,inProgress:0,completed:0,failed:0};for(let r of e)t.total+=r.count,r.status==="pending"?t.pending=r.count:r.status==="in_progress"?t.inProgress=r.count:r.status==="completed"?t.completed=r.count:r.status==="failed"&&(t.failed=r.count);return t}listRecentSessions(e={}){let t=[],r=[];e.dateFrom&&(t.push("updated_at >= ?"),r.push(e.dateFrom)),e.dateTo&&(t.push("updated_at <= ?"),r.push(e.dateTo));let s=t.length>0?`WHERE ${t.join(" AND ")}`:"",o=e.limit??20;return this.db.prepare(`
76
79
  SELECT session_id, started_at, updated_at
77
80
  FROM sessions
78
81
  ${s}
79
82
  ORDER BY updated_at DESC
80
83
  LIMIT ?
81
- `).all(...n,o).map(c=>({sessionId:String(c.session_id),startedAt:String(c.started_at),updatedAt:String(c.updated_at)}))}listAssistantTurns(e){return this.db.prepare(`
84
+ `).all(...r,o).map(c=>({sessionId:String(c.session_id),startedAt:String(c.started_at),updatedAt:String(c.updated_at)}))}listAssistantTurns(e){return this.db.prepare(`
82
85
  SELECT id, session_id, run_id, provider, model, raw_text, sanitized_text, blob_ref,
83
86
  stop_reason, thinking_blocks_count, created_at
84
87
  FROM assistant_turns
85
88
  WHERE session_id = ?
86
89
  ORDER BY id ASC
87
- `).all(e).map(n=>({id:Number(n.id),sessionId:String(n.session_id),runId:String(n.run_id),provider:String(n.provider),model:String(n.model),rawText:this.restoreRawText(n.raw_text,n.blob_ref),sanitizedText:String(n.sanitized_text??""),blobRef:n.blob_ref?String(n.blob_ref):null,stopReason:n.stop_reason!=null?String(n.stop_reason):null,thinkingBlocksCount:n.thinking_blocks_count!=null?Number(n.thinking_blocks_count):null,createdAt:String(n.created_at)}))}listToolCallsForSession(e){return this.db.prepare(`
90
+ `).all(e).map(r=>({id:Number(r.id),sessionId:String(r.session_id),runId:String(r.run_id),provider:String(r.provider),model:String(r.model),rawText:this.restoreRawText(r.raw_text,r.blob_ref),sanitizedText:String(r.sanitized_text??""),blobRef:r.blob_ref?String(r.blob_ref):null,stopReason:r.stop_reason!=null?String(r.stop_reason):null,thinkingBlocksCount:r.thinking_blocks_count!=null?Number(r.thinking_blocks_count):null,createdAt:String(r.created_at)}))}listToolCallsForSession(e){return this.db.prepare(`
88
91
  SELECT id, tool_name, outcome, params_json, duration_ms, exit_code, error_type, error_message,
89
92
  gfi_before, gfi_after, result_preview, created_at
90
93
  FROM tool_calls
91
94
  WHERE session_id = ?
92
95
  ORDER BY id ASC
93
- `).all(e).map(n=>{let s=null;if(n.params_json&&typeof n.params_json=="string")try{let o=JSON.parse(n.params_json);o&&typeof o.filePath=="string"&&(s=o.filePath)}catch{}return{id:Number(n.id),toolName:String(n.tool_name),outcome:String(n.outcome),filePath:s,durationMs:n.duration_ms!=null?Number(n.duration_ms):null,exitCode:n.exit_code!=null?Number(n.exit_code):null,errorType:n.error_type?String(n.error_type):null,errorMessage:n.error_message?String(n.error_message):null,gfiBefore:n.gfi_before!=null?Number(n.gfi_before):null,gfiAfter:n.gfi_after!=null?Number(n.gfi_after):null,resultPreview:n.result_preview!=null?String(n.result_preview):null,createdAt:String(n.created_at)}})}getRuleHostContextRows(e,r=20){let n=Math.max(1,Math.floor(r)),s=this.db.prepare(`
96
+ `).all(e).map(r=>{let s=null;if(r.params_json&&typeof r.params_json=="string")try{let o=JSON.parse(r.params_json);o&&typeof o.filePath=="string"&&(s=o.filePath)}catch{}return{id:Number(r.id),toolName:String(r.tool_name),outcome:String(r.outcome),filePath:s,durationMs:r.duration_ms!=null?Number(r.duration_ms):null,exitCode:r.exit_code!=null?Number(r.exit_code):null,errorType:r.error_type?String(r.error_type):null,errorMessage:r.error_message?String(r.error_message):null,gfiBefore:r.gfi_before!=null?Number(r.gfi_before):null,gfiAfter:r.gfi_after!=null?Number(r.gfi_after):null,resultPreview:r.result_preview!=null?String(r.result_preview):null,createdAt:String(r.created_at)}})}getRuleHostContextRows(e,t=20){let r=Math.max(1,Math.floor(t)),s=this.db.prepare(`
94
97
  SELECT id, tool_name, outcome, params_json
95
98
  FROM tool_calls
96
99
  WHERE session_id = ?
97
100
  ORDER BY id DESC
98
101
  LIMIT ?
99
- `).all(e,n+1),o=s.length>n,i=o?s.slice(0,n):s;return i.reverse(),{rows:i.map(c=>({id:Number(c.id),toolName:String(c.tool_name),outcome:String(c.outcome),paramsJson:String(c.params_json)})),truncated:o}}getRuleHostEvidenceRow(e){let r=this.db.prepare(`
102
+ `).all(e,r+1),o=s.length>r,i=o?s.slice(0,r):s;return i.reverse(),{rows:i.map(c=>({id:Number(c.id),toolName:String(c.tool_name),outcome:String(c.outcome),paramsJson:String(c.params_json)})),truncated:o}}getRuleHostEvidenceRow(e){let t=this.db.prepare(`
100
103
  SELECT id, session_id, tool_name, outcome, params_json
101
104
  FROM tool_calls
102
105
  WHERE id = ?
103
106
  LIMIT 1
104
- `).get(e);return!ye(r)||typeof r.id!="number"||typeof r.session_id!="string"||typeof r.tool_name!="string"||typeof r.outcome!="string"||typeof r.params_json!="string"?null:{id:r.id,sessionId:r.session_id,toolName:r.tool_name,outcome:r.outcome,paramsJson:r.params_json}}getRuleHostContextRowsBefore(e,r,n=20){let s=Math.max(1,Math.floor(n)),o=this.db.prepare(`
107
+ `).get(e);return!xe(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,r=20){let s=Math.max(1,Math.floor(r)),o=this.db.prepare(`
105
108
  SELECT id, tool_name, outcome, params_json
106
109
  FROM tool_calls
107
110
  WHERE session_id = ? AND id < ?
108
111
  ORDER BY id DESC
109
112
  LIMIT ?
110
- `).all(e,r,s+1),i=o.length>s;return{rows:(i?o.slice(0,s):o).reverse().map(a=>({id:Number(a.id),toolName:String(a.tool_name),outcome:String(a.outcome),paramsJson:String(a.params_json)})),truncated:i}}listPainEventsForSession(e){return this.db.prepare(`
113
+ `).all(e,t,s+1),i=o.length>s;return{rows:(i?o.slice(0,s):o).reverse().map(a=>({id:Number(a.id),toolName:String(a.tool_name),outcome:String(a.outcome),paramsJson:String(a.params_json)})),truncated:i}}listPainEventsForSession(e){return this.db.prepare(`
111
114
  SELECT id, source, score, reason, severity, origin, confidence, created_at
112
115
  FROM pain_events
113
116
  WHERE session_id = ?
114
117
  ORDER BY created_at ASC
115
- `).all(e).map(n=>({id:Number(n.id),source:String(n.source),score:Number(n.score),reason:n.reason?String(n.reason):null,severity:n.severity?String(n.severity):null,origin:n.origin?String(n.origin):null,confidence:n.confidence!=null?Number(n.confidence):null,createdAt:String(n.created_at)}))}getPainEventByCanonicalId(e){let r=this.db.prepare(`
118
+ `).all(e).map(r=>({id:Number(r.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,createdAt:String(r.created_at)}))}getPainEventByCanonicalId(e){let t=this.db.prepare(`
116
119
  SELECT id, session_id, source, score, reason, severity, origin, confidence,
117
120
  text, canonical_pain_id, runtime_task_id, created_at
118
121
  FROM pain_events
119
122
  WHERE canonical_pain_id = ?
120
123
  LIMIT 1
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(`
124
+ `).get(e);return wt(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
125
  SELECT id, turn_index, raw_excerpt, correction_detected, correction_cue, created_at
123
126
  FROM user_turns
124
127
  WHERE session_id = ?
125
128
  ORDER BY turn_index ASC
126
- `).all(e).map(n=>({id:Number(n.id),turnIndex:Number(n.turn_index),rawExcerpt:String(n.raw_excerpt??""),correctionDetected:!!n.correction_detected,correctionCue:n.correction_cue?String(n.correction_cue):null,createdAt:String(n.created_at)}))}getLatestCorrectionTurn(e,r){let n=this.db.prepare(`
129
+ `).all(e).map(r=>({id:Number(r.id),turnIndex:Number(r.turn_index),rawExcerpt:String(r.raw_excerpt??""),correctionDetected:!!r.correction_detected,correctionCue:r.correction_cue?String(r.correction_cue):null,createdAt:String(r.created_at)}))}getLatestCorrectionTurn(e,t){let r=this.db.prepare(`
127
130
  SELECT turn_index, raw_text, blob_ref, raw_excerpt, references_assistant_turn_id, created_at
128
131
  FROM user_turns
129
132
  WHERE session_id = ? AND correction_detected = 1
130
133
  ORDER BY id DESC
131
134
  LIMIT 1
132
- `).get(e);if(!n)return;let s=String(n.created_at??""),o=r?.maxAgeMs??1800*1e3,i=Date.parse(s);if(Number.isFinite(i)&&(r?.nowMs??Date.now())-i>o)return;let c=String(n.raw_excerpt??""),a=this.restoreRawText(typeof n.raw_text=="string"?n.raw_text:null,n.blob_ref===null||n.blob_ref===void 0?null:String(n.blob_ref))||c;if(a.length!==0)return{turnIndex:Number(n.turn_index),text:a,referencesAssistantTurnId:n.references_assistant_turn_id===null||n.references_assistant_turn_id===void 0?null:Number(n.references_assistant_turn_id),occurredAt:s}}getCorrectionTurnByRowid(e){let r=this.db.prepare(`
135
+ `).get(e);if(!r)return;let s=String(r.created_at??""),o=t?.maxAgeMs??1800*1e3,i=Date.parse(s);if(Number.isFinite(i)&&(t?.nowMs??Date.now())-i>o)return;let c=String(r.raw_excerpt??""),a=this.restoreRawText(typeof r.raw_text=="string"?r.raw_text:null,r.blob_ref===null||r.blob_ref===void 0?null:String(r.blob_ref))||c;if(a.length!==0)return{turnIndex:Number(r.turn_index),text:a,referencesAssistantTurnId:r.references_assistant_turn_id===null||r.references_assistant_turn_id===void 0?null:Number(r.references_assistant_turn_id),occurredAt:s}}getCorrectionTurnByRowid(e){let t=this.db.prepare(`
133
136
  SELECT turn_index, raw_text, blob_ref, raw_excerpt, references_assistant_turn_id, created_at
134
137
  FROM user_turns
135
138
  WHERE id = ?
136
- `).get(e);if(!r)return;let n=String(r.raw_excerpt??""),s=this.restoreRawText(typeof r.raw_text=="string"?r.raw_text:null,r.blob_ref===null||r.blob_ref===void 0?null:String(r.blob_ref))||n;if(s.length!==0)return{turnIndex:Number(r.turn_index),text:s,referencesAssistantTurnId:r.references_assistant_turn_id===null||r.references_assistant_turn_id===void 0?null:Number(r.references_assistant_turn_id),occurredAt:String(r.created_at??"")}}listCorrectionSamples(e="pending"){return this.db.prepare(`
139
+ `).get(e);if(!t)return;let r=String(t.raw_excerpt??""),s=this.restoreRawText(typeof t.raw_text=="string"?t.raw_text:null,t.blob_ref===null||t.blob_ref===void 0?null:String(t.blob_ref))||r;if(s.length!==0)return{turnIndex:Number(t.turn_index),text:s,referencesAssistantTurnId:t.references_assistant_turn_id===null||t.references_assistant_turn_id===void 0?null:Number(t.references_assistant_turn_id),occurredAt:String(t.created_at??"")}}listCorrectionSamples(e="pending"){return this.db.prepare(`
137
140
  SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
138
141
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
139
142
  review_status, export_mode, created_at, updated_at
140
143
  FROM correction_samples
141
144
  WHERE review_status = ?
142
145
  ORDER BY created_at DESC
143
- `).all(e).map(n=>({sampleId:String(n.sample_id),sessionId:String(n.session_id),badAssistantTurnId:Number(n.bad_assistant_turn_id),userCorrectionTurnId:Number(n.user_correction_turn_id),recoveryToolSpanJson:String(n.recovery_tool_span_json),diffExcerpt:String(n.diff_excerpt??""),principleIdsJson:String(n.principle_ids_json??"[]"),qualityScore:Number(n.quality_score),reviewStatus:n.review_status,exportMode:n.export_mode,createdAt:String(n.created_at),updatedAt:String(n.updated_at)}))}listCorrectionSamplesForSession(e){return this.db.prepare(`
146
+ `).all(e).map(r=>({sampleId:String(r.sample_id),sessionId:String(r.session_id),badAssistantTurnId:Number(r.bad_assistant_turn_id),userCorrectionTurnId:Number(r.user_correction_turn_id),recoveryToolSpanJson:String(r.recovery_tool_span_json),diffExcerpt:String(r.diff_excerpt??""),principleIdsJson:String(r.principle_ids_json??"[]"),qualityScore:Number(r.quality_score),reviewStatus:r.review_status,exportMode:r.export_mode,createdAt:String(r.created_at),updatedAt:String(r.updated_at)}))}listCorrectionSamplesForSession(e){return this.db.prepare(`
144
147
  SELECT cs.sample_id, ut.correction_cue
145
148
  FROM correction_samples cs
146
149
  LEFT JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
147
150
  WHERE cs.session_id = ?
148
151
  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=f();if(!this.withWrite(()=>this.db.prepare(`
152
+ `).all(e).map(r=>({correctionCue:r.correction_cue?String(r.correction_cue):null}))}reviewCorrectionSample(e,t,r){let s=_();if(!this.withWrite(()=>this.db.prepare(`
150
153
  UPDATE correction_samples
151
154
  SET review_status = ?, updated_at = ?
152
155
  WHERE sample_id = ?
153
- `).run(r,s,e).changes===0?!1:(this.db.prepare(`
156
+ `).run(t,s,e).changes===0?!1:(this.db.prepare(`
154
157
  INSERT INTO sample_reviews (sample_id, review_status, note, created_at)
155
158
  VALUES (?, ?, ?, ?)
156
- `).run(e,r,n??null,s),!0)))throw new x(e);let i=this.db.prepare(`
159
+ `).run(e,t,r??null,s),!0)))throw new x(e);let i=this.db.prepare(`
157
160
  SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
158
161
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
159
162
  review_status, export_mode, created_at, updated_at
160
163
  FROM correction_samples
161
164
  WHERE sample_id = ?
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(`
165
+ `).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),r=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(r)||0))),c=`Correction rejected (quality ${r.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
166
  INSERT OR IGNORE INTO signal_confirmations (
164
167
  id, session_id, user_turn_rowid, occurrence_id, excerpt,
165
168
  terms_json, suggested_type, status, attempts, created_at
166
169
  ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)
167
- `).run(r,e.sessionId,e.userTurnRowid,e.occurrenceId,e.excerpt,JSON.stringify({correction:e.terms}),e.suggestedType,e.createdAt)})}listPendingSignalConfirmations(e){return this.db.prepare(`
170
+ `).run(t,e.sessionId,e.userTurnRowid,e.occurrenceId,e.excerpt,JSON.stringify({correction:e.terms}),e.suggestedType,e.createdAt)})}listPendingSignalConfirmations(e){return this.db.prepare(`
168
171
  SELECT * FROM signal_confirmations
169
172
  WHERE status = 'pending'
170
173
  ORDER BY attempts ASC, created_at ASC
171
174
  LIMIT ?
172
- `).all(e).map(It)}bumpSignalConfirmationAttempt(e){return this.withWrite(()=>{this.db.prepare(`
175
+ `).all(e).map(Ct)}bumpSignalConfirmationAttempt(e){return this.withWrite(()=>{this.db.prepare(`
173
176
  UPDATE signal_confirmations SET attempts = attempts + 1
174
177
  WHERE id = ? AND status = 'pending'
175
- `).run(e)}),this.db.prepare("SELECT attempts FROM signal_confirmations WHERE id = ?").get(e)?.attempts??0}markSignalConfirmationResult(e,r,n){let s=this.withWrite(()=>this.db.prepare(`
178
+ `).run(e)}),this.db.prepare("SELECT attempts FROM signal_confirmations WHERE id = ?").get(e)?.attempts??0}markSignalConfirmationResult(e,t,r){let s=this.withWrite(()=>this.db.prepare(`
176
179
  UPDATE signal_confirmations
177
180
  SET status = ?, resolved_at = ?, resolution = ?
178
181
  WHERE id = ? AND status = 'pending'
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(`
182
+ `).run(t,_(),r.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
183
  SELECT cs.sample_id, cs.session_id, cs.recovery_tool_span_json, cs.diff_excerpt, cs.quality_score,
181
184
  at.raw_text AS assistant_raw_text, at.blob_ref AS assistant_blob_ref, at.sanitized_text,
182
185
  ut.raw_text AS user_raw_text, ut.blob_ref AS user_blob_ref, ut.correction_cue
@@ -185,16 +188,16 @@ var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
185
188
  JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
186
189
  WHERE (? = 0 OR cs.review_status = 'approved')
187
190
  ORDER BY cs.created_at ASC
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(`
191
+ `).all(e.approvedOnly?1:0),r=T.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"?Ie(i):i,d=e.mode==="redacted"?Ie(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 U(r,`${s.join(`
189
192
  `)}${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: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(`
193
+ `:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,r,t.length),{filePath:r,count:t.length,mode:e.mode}}exportAnalytics(){let e={generatedAt:_(),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=T.join(this.exportDir,`analytics-${Date.now()}.json`);return U(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=(r,s)=>{let o=s?`SELECT COUNT(*) as count FROM ${r} WHERE ${s}`:`SELECT COUNT(*) as count FROM ${r}`;return Number(this.db.prepare(o).get().count)},t=this.db.prepare(`
191
194
  SELECT MAX(ts) AS ts FROM (
192
195
  SELECT MAX(created_at) AS ts FROM assistant_turns
193
196
  UNION ALL SELECT MAX(created_at) AS ts FROM user_turns
194
197
  UNION ALL SELECT MAX(created_at) AS ts FROM tool_calls
195
198
  UNION ALL SELECT MAX(created_at) AS ts FROM pain_events
196
199
  )
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(`
200
+ `).get();return{dbPath:this.dbPath,dbSizeBytes:Ae(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=kt(this.db);for(let r of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${r}`);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
201
  DROP VIEW IF EXISTS v_daily_metrics;
199
202
  CREATE VIEW IF NOT EXISTS v_daily_metrics AS
200
203
  WITH tool_daily AS (
@@ -219,24 +222,24 @@ var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
219
222
  COALESCE(correction_daily.user_corrections, 0) AS user_corrections
220
223
  FROM tool_daily
221
224
  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=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(`
225
+ `)}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=y(this.workspaceDir,"SESSION_DIR");if(f.existsSync(t)){for(let r of f.readdirSync(t).filter(s=>s.endsWith(".json")))try{let s=JSON.parse(f.readFileSync(T.join(t,r),"utf8"));if(s.sessionId){let o=typeof s.lastActivityAt=="number"?new Date(s.lastActivityAt).toISOString():_();this.recordSession({sessionId:s.sessionId,startedAt:o})}}catch{}this.markImported(e)}}importLegacyEvents(){let e="legacy:events";if(this.isImported(e))return;let t=T.join(this.stateDir,"logs","events.jsonl");if(!f.existsSync(t))return;let r=f.readFileSync(t,"utf8").trim();if(!r){this.markImported(e);return}for(let s of r.split(`
226
+ `))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=y(this.workspaceDir,"EVOLUTION_STREAM");if(!f.existsSync(t))return;let r=f.readFileSync(t,"utf8").trim();if(!r){this.markImported(e);return}for(let s of r.split(`
224
227
  `))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
228
  INSERT INTO ingest_checkpoint (source_key, imported_at)
226
229
  VALUES (?, ?)
227
230
  ON CONFLICT(source_key) DO UPDATE SET imported_at = excluded.imported_at
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(`
231
+ `).run(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
232
  SELECT sample_id FROM correction_samples
230
233
  WHERE session_id = ? AND review_status = 'pending'
231
234
  ORDER BY created_at DESC
232
235
  LIMIT 1
233
- `).get(e)?.sample_id)return;let n=this.db.prepare(`
236
+ `).get(e)?.sample_id)return;let r=this.db.prepare(`
234
237
  SELECT id, references_assistant_turn_id, correction_cue, raw_text, blob_ref
235
238
  FROM user_turns
236
239
  WHERE session_id = ? AND correction_detected = 1
237
240
  ORDER BY id DESC
238
241
  LIMIT 1
239
- `).get(e);if(!n||!n.references_assistant_turn_id)return;let s=this.db.prepare(`
242
+ `).get(e);if(!r||!r.references_assistant_turn_id)return;let s=this.db.prepare(`
240
243
  SELECT id, tool_name, error_type, error_message
241
244
  FROM tool_calls
242
245
  WHERE session_id = ? AND outcome = 'failure'
@@ -248,17 +251,17 @@ var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(
248
251
  WHERE session_id = ?
249
252
  ORDER BY id DESC
250
253
  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),m=_||(s?String(s.error_message??s.error_type??s.tool_name):"")||String(n.correction_cue??"user correction");this.withWrite(()=>{this.db.prepare(`
254
+ `).all(e).filter(g=>g.outcome==="success"),c=i[0]?.id??r.id,a=`sample_${J.createHash("sha256").update(`${e}:${r.id}:${c}`).digest("hex").slice(0,12)}`,d=this.restoreRawText(r.raw_text,r.blob_ref),h=[r.references_assistant_turn_id?35:0,r.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((g,Le)=>g+Le,0),m=d||(s?String(s.error_message??s.error_type??s.tool_name):"")||String(r.correction_cue??"user correction");this.withWrite(()=>{this.db.prepare(`
252
255
  INSERT OR IGNORE INTO correction_samples (
253
256
  sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
254
257
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
255
258
  review_status, export_mode, created_at, updated_at
256
259
  ) 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(m),"[]",g,f(),f())})}recordExportAudit(e,r,n,s,o){this.withWrite(()=>{this.db.prepare(`
260
+ `).run(a,e,Number(r.references_assistant_turn_id),Number(r.id),R(i.map(g=>({id:g.id,toolName:g.tool_name,outcome:g.outcome}))),Lt(m),"[]",h,_(),_())})}recordExportAudit(e,t,r,s,o){this.withWrite(()=>{this.db.prepare(`
258
261
  INSERT INTO exports_audit (export_kind, mode, approved_only, file_path, row_count, created_at)
259
262
  VALUES (?, ?, ?, ?, ?, ?)
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(`
263
+ `).run(e,t,r?1:0,s,o,_())})}storeRawText(e,t){let r=t.length>200?`${t.slice(0,197)}...`:t;if(Buffer.byteLength(t,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:t,blobRef:null,excerpt:r};let o=J.createHash("sha256").update(t).digest("hex"),i=`${e}-${o}.txt`,c=T.join(this.blobDir,i);return f.existsSync(c)||U(c,t),{inlineText:null,blobRef:i,excerpt:r}}restoreRawText(e,t){if(e)return e;if(!t)return"";let r=T.join(this.blobDir,t);return f.existsSync(r)?f.readFileSync(r,"utf8"):""}computeBlobBytes(){return f.existsSync(this.blobDir)?f.readdirSync(this.blobDir).reduce((e,t)=>e+Ae(T.join(this.blobDir,t)),0):0}pruneUnreferencedBlobs(){if(!f.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,t=this.db.prepare(`
261
264
  SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
262
265
  UNION
263
266
  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=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};
267
+ `).all();for(let i of t)i.blob_ref&&e.add(String(i.blob_ref));let r=Date.now(),s=0,o=0;for(let i of f.readdirSync(this.blobDir)){if(e.has(i))continue;let c=T.join(this.blobDir,i),a;try{a=f.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&r-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,f.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return ye(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},v=class{static instances=new Map;static get(e,t={}){let r=T.resolve(e),s=this.instances.get(r);if(s)return s;let o=new B({workspaceDir:r,...t});return this.instances.set(r,o),o}static dispose(e){let t=T.resolve(e),r=this.instances.get(t);r&&(r.dispose(),this.instances.delete(t))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,t,r={}){let s=T.resolve(e),o=this.instances.get(s);if(o)return t(o);let i=new B({workspaceDir:s,...r});try{return t(i)}finally{i.dispose()}}};var Dt=new Set(["__proto__","constructor","prototype"]);function Mt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Pt(n){if(!Array.isArray(n))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],t=new Map;return n.forEach((r,s)=>{if(!Mt(r)){e.push(`toolSemanticMappings[${s}] must be a plain object`);return}if(!Object.hasOwn(r,"rawToolName")||typeof r.rawToolName!="string"||r.rawToolName.trim()===""){e.push(`toolSemanticMappings[${s}].rawToolName must be a non-empty string`);return}if(Dt.has(r.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=r.canonicalKind;if(!ce(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...X].join("|")}, got ${String(o)}`);return}let i=t.get(r.rawToolName);if(i!==void 0&&i!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${r.rawToolName}' declared twice with conflicting kinds (${i} vs ${o})`);return}t.set(r.rawToolName,o)}),{valid:e.length===0,errors:e}}function ve(n){let e,t=new Set,r=[];if(n===void 0)e=D;else{let s=Pt(n);if(!s.valid)return{ok:!1,errors:s.errors};let o={...D};for(let i of n)o[i.rawToolName]=i.canonicalKind,t.add(i.rawToolName);r=Object.freeze(n.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 r},lookup(s){return typeof s!="string"||!Object.hasOwn(e,s)?null:e[s]??null},resolve(s){return this.lookup(s)??"other"}}}}var we=["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"],O=["write","edit","apply_patch"],w=["exec"],jt=[...w],F=["sessions_spawn"],Ut=[...O],Bt=[...O,...w,...F],Ft=[...we],Mn=new Set(we),Pn=new Set(O),jn=new Set(jt),Un=new Set(w),Bn=new Set(F),Fn=new Set(Ut),Wn=new Set(Bt),Xn=new Set(Ft),$n=new Set([...O]);function Z(n,e){return n.map(t=>({rawToolName:t,canonicalKind:e}))}var Wt=Object.freeze([...Z(w,"execute"),...Z(O,"write"),...Z(F,"agent")]),Q=ve(Wt);if(!Q.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${Q.errors.join("; ")}`);var ke=Q.registry;var ee=class extends j{constructor(e){super({source:v.get(e.workspaceDir),toolSemantics:ke})}};export{ee as BehaviorExamplePackAssembler,v as RuleHostEvidenceRegistry};
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-principles-disciple",
3
- "version": "1.146.1",
3
+ "version": "1.146.2",
4
4
  "description": "Interactive CLI installer for Principles Disciple OpenClaw plugin",
5
5
  "type": "module",
6
6
  "bin": {