create-principles-disciple 1.147.5 → 1.147.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/_release/product-identity.json +1 -1
  2. package/codex-adapter/package.json +1 -1
  3. package/console/dist/server/models/HealthCheckModel.d.ts +0 -1
  4. package/console/dist/server/models/HealthCheckModel.js +0 -54
  5. package/console/dist/server/types/index.d.ts +1 -9
  6. package/console/dist/web/assets/app.js +18 -18
  7. package/core/dist/index.d.ts +1 -1
  8. package/core/dist/index.d.ts.map +1 -1
  9. package/core/dist/index.js +1 -1
  10. package/core/dist/index.js.map +1 -1
  11. package/core/dist/prompt-builder/index.d.ts +0 -1
  12. package/core/dist/prompt-builder/index.d.ts.map +1 -1
  13. package/core/dist/prompt-builder/index.js +0 -1
  14. package/core/dist/prompt-builder/index.js.map +1 -1
  15. package/core/dist/runtime-v2/adapter/output-schema-registry.js +2 -2
  16. package/core/dist/runtime-v2/control-plane-triage.d.ts +1 -1
  17. package/core/dist/runtime-v2/control-plane-triage.d.ts.map +1 -1
  18. package/core/dist/runtime-v2/control-plane-triage.js +0 -15
  19. package/core/dist/runtime-v2/control-plane-triage.js.map +1 -1
  20. package/core/dist/runtime-v2/evidence-triage/observation-resolver.d.ts +3 -6
  21. package/core/dist/runtime-v2/evidence-triage/observation-resolver.d.ts.map +1 -1
  22. package/core/dist/runtime-v2/evidence-triage/observation-resolver.js +5 -10
  23. package/core/dist/runtime-v2/evidence-triage/observation-resolver.js.map +1 -1
  24. package/core/dist/runtime-v2/evidence-triage/source-descriptors.d.ts +2 -1
  25. package/core/dist/runtime-v2/evidence-triage/source-descriptors.d.ts.map +1 -1
  26. package/core/dist/runtime-v2/evidence-triage/source-descriptors.js +3 -8
  27. package/core/dist/runtime-v2/evidence-triage/source-descriptors.js.map +1 -1
  28. package/core/dist/runtime-v2/evidence-triage/types.d.ts +1 -1
  29. package/core/dist/runtime-v2/evidence-triage/types.d.ts.map +1 -1
  30. package/core/dist/runtime-v2/evidence-triage/types.js +0 -1
  31. package/core/dist/runtime-v2/evidence-triage/types.js.map +1 -1
  32. package/core/dist/runtime-v2/feature-flags/feature-flag-contract.d.ts.map +1 -1
  33. package/core/dist/runtime-v2/feature-flags/feature-flag-contract.js +4 -1
  34. package/core/dist/runtime-v2/feature-flags/feature-flag-contract.js.map +1 -1
  35. package/core/dist/runtime-v2/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  36. package/core/dist/runtime-v2/feature-flags/feature-flag-lifecycle.js +3 -8
  37. package/core/dist/runtime-v2/feature-flags/feature-flag-lifecycle.js.map +1 -1
  38. package/core/dist/runtime-v2/golden-trace.d.ts.map +1 -1
  39. package/core/dist/runtime-v2/golden-trace.js +0 -1
  40. package/core/dist/runtime-v2/golden-trace.js.map +1 -1
  41. package/core/dist/runtime-v2/index.d.ts +5 -9
  42. package/core/dist/runtime-v2/index.d.ts.map +1 -1
  43. package/core/dist/runtime-v2/index.js +4 -8
  44. package/core/dist/runtime-v2/index.js.map +1 -1
  45. package/core/dist/runtime-v2/internalization/artificer-run-correlation.d.ts +1 -1
  46. package/core/dist/runtime-v2/internalization/artificer-run-correlation.js +1 -1
  47. package/core/dist/runtime-v2/internalization/consumer-evidence-preflight.d.ts +1 -1
  48. package/core/dist/runtime-v2/internalization/evidence-readiness.js +1 -1
  49. package/core/dist/runtime-v2/internalization/owner-evidence-recovery.d.ts +1 -1
  50. package/core/dist/runtime-v2/internalization/rule-host-contracts.d.ts +0 -1
  51. package/core/dist/runtime-v2/internalization/rule-host-contracts.d.ts.map +1 -1
  52. package/core/dist/runtime-v2/operator-health-read-model.d.ts +0 -2
  53. package/core/dist/runtime-v2/operator-health-read-model.d.ts.map +1 -1
  54. package/core/dist/runtime-v2/operator-health-read-model.js +1 -55
  55. package/core/dist/runtime-v2/operator-health-read-model.js.map +1 -1
  56. package/core/dist/runtime-v2/principle-reuse/reuse-domain.d.ts +1 -1
  57. package/core/dist/runtime-v2/principle-reuse/reuse-domain.js +1 -1
  58. package/core/dist/runtime-v2/principle-reuse/reuse-proposal.d.ts +1 -1
  59. package/core/dist/runtime-v2/principle-reuse/reuse-proposal.js +1 -1
  60. package/core/dist/runtime-v2/principle-reuse/reuse-retrieval.d.ts +1 -1
  61. package/core/dist/runtime-v2/principle-reuse/reuse-retrieval.js +1 -1
  62. package/core/dist/runtime-v2/signal-collector/confidence-gate.d.ts +1 -5
  63. package/core/dist/runtime-v2/signal-collector/confidence-gate.d.ts.map +1 -1
  64. package/core/dist/runtime-v2/signal-collector/confidence-gate.js +0 -9
  65. package/core/dist/runtime-v2/signal-collector/confidence-gate.js.map +1 -1
  66. package/core/dist/runtime-v2/signal-collector/keyword-stage.d.ts +2 -2
  67. package/core/dist/runtime-v2/signal-collector/keyword-stage.d.ts.map +1 -1
  68. package/core/dist/runtime-v2/signal-collector/keyword-stage.js +6 -10
  69. package/core/dist/runtime-v2/signal-collector/keyword-stage.js.map +1 -1
  70. package/core/dist/runtime-v2/signal-collector/llm-stage.d.ts +1 -1
  71. package/core/dist/runtime-v2/signal-collector/llm-stage.d.ts.map +1 -1
  72. package/core/dist/runtime-v2/signal-collector/llm-stage.js +3 -4
  73. package/core/dist/runtime-v2/signal-collector/llm-stage.js.map +1 -1
  74. package/core/dist/runtime-v2/signal-collector/signal-collector.js +4 -4
  75. package/core/dist/runtime-v2/signal-collector/signal-collector.js.map +1 -1
  76. package/core/dist/runtime-v2/signal-collector/types.d.ts +6 -8
  77. package/core/dist/runtime-v2/signal-collector/types.d.ts.map +1 -1
  78. package/core/dist/runtime-v2/signal-collector/types.js +6 -6
  79. package/core/dist/runtime-v2/signal-collector/types.js.map +1 -1
  80. package/core/dist/runtime-v2/trajectory-schema.d.ts +25 -5
  81. package/core/dist/runtime-v2/trajectory-schema.d.ts.map +1 -1
  82. package/core/dist/runtime-v2/trajectory-schema.js +58 -2
  83. package/core/dist/runtime-v2/trajectory-schema.js.map +1 -1
  84. package/core/dist/runtime-v2/types/event-types.d.ts +0 -35
  85. package/core/dist/runtime-v2/types/event-types.d.ts.map +1 -1
  86. package/core/dist/runtime-v2/types/event-types.js +0 -19
  87. package/core/dist/runtime-v2/types/event-types.js.map +1 -1
  88. package/core/dist/runtime-v2/types/index.d.ts +2 -2
  89. package/core/dist/runtime-v2/types/index.d.ts.map +1 -1
  90. package/core/dist/runtime-v2/types/index.js +1 -1
  91. package/core/dist/runtime-v2/types/index.js.map +1 -1
  92. package/core/dist/trajectory-types.d.ts +0 -2
  93. package/core/dist/trajectory-types.d.ts.map +1 -1
  94. package/core/package.json +1 -1
  95. package/dist/installer.d.ts +0 -7
  96. package/dist/installer.d.ts.map +1 -1
  97. package/dist/installer.js +112 -28
  98. package/dist/installer.js.map +1 -1
  99. package/dist/mvp-config.d.ts +2 -2
  100. package/dist/mvp-config.d.ts.map +1 -1
  101. package/dist/mvp-config.js +4 -2
  102. package/dist/mvp-config.js.map +1 -1
  103. package/host-runtime/dist/governance-signal-admission.d.ts +0 -2
  104. package/host-runtime/dist/governance-signal-admission.js +14 -15
  105. package/host-runtime/dist/production-pain-evidence.d.ts +1 -1
  106. package/host-runtime/dist/production-pain-evidence.js +42 -7
  107. package/host-runtime/dist/production-rulehost-gate.d.ts +0 -1
  108. package/host-runtime/dist/production-rulehost-gate.js +3 -4
  109. package/host-runtime/dist/signal-classifier.d.ts +8 -0
  110. package/host-runtime/dist/signal-classifier.js +10 -2
  111. package/host-runtime/package.json +1 -1
  112. package/package.json +3 -3
  113. package/pd-cli/dist/commands/pain-evidence.d.ts +2 -4
  114. package/pd-cli/dist/commands/pain-evidence.d.ts.map +1 -1
  115. package/pd-cli/dist/commands/pain-evidence.js +2 -4
  116. package/pd-cli/dist/commands/pain-evidence.js.map +1 -1
  117. package/pd-cli/dist/commands/runtime-canary.d.ts.map +1 -1
  118. package/pd-cli/dist/commands/runtime-canary.js +2 -68
  119. package/pd-cli/dist/commands/runtime-canary.js.map +1 -1
  120. package/pd-cli/dist/commands/runtime-diagnostics-export.d.ts.map +1 -1
  121. package/pd-cli/dist/commands/runtime-diagnostics-export.js +1 -25
  122. package/pd-cli/dist/commands/runtime-diagnostics-export.js.map +1 -1
  123. package/pd-cli/dist/commands/runtime-health-snapshot.d.ts.map +1 -1
  124. package/pd-cli/dist/commands/runtime-health-snapshot.js +0 -9
  125. package/pd-cli/dist/commands/runtime-health-snapshot.js.map +1 -1
  126. package/pd-cli/dist/index.js +0 -9
  127. package/pd-cli/dist/index.js.map +1 -1
  128. package/pd-cli/package.json +1 -1
  129. package/pd-mcp-server/dist/version.d.ts +1 -1
  130. package/pd-mcp-server/dist/version.js +1 -1
  131. package/pd-mcp-server/package.json +1 -1
  132. package/plugin/dist/bundle.js +492 -481
  133. package/plugin/dist/config/defaults/runtime.d.ts +0 -4
  134. package/plugin/dist/core/config.d.ts +0 -35
  135. package/plugin/dist/core/pain.d.ts +0 -1
  136. package/plugin/dist/core/session-tracker.d.ts +3 -51
  137. package/plugin/dist/core/signal-collector-host.d.ts +5 -13
  138. package/plugin/dist/core/signal-keyword-store.d.ts +2 -2
  139. package/plugin/dist/core/trajectory.d.ts +0 -2
  140. package/plugin/dist/governance-audit.js +2 -2
  141. package/plugin/dist/hooks/after-tool-call-helpers.d.ts +5 -12
  142. package/plugin/dist/hooks/after-tool-call-types.d.ts +0 -2
  143. package/plugin/dist/hooks/gate-block-helper.d.ts +1 -1
  144. package/plugin/dist/hooks/gate.d.ts +3 -4
  145. package/plugin/dist/hooks/pain.d.ts +4 -4
  146. package/plugin/dist/openclaw.plugin.json +1 -1
  147. package/plugin/dist/rulehost-evidence.js +45 -45
  148. package/plugin/dist/templates/pain_settings.json +0 -46
  149. package/plugin/dist/types/event-types.d.ts +1 -1
  150. package/plugin/openclaw.plugin.json +1 -1
  151. package/plugin/package.json +1 -1
  152. package/plugin/templates/pain_settings.json +0 -46
  153. package/release-manager/dist/installer.js +112 -28
  154. package/release-manager/dist/mvp-config.js +4 -2
  155. package/release-manager/package.json +1 -1
  156. package/workbuddy-adapter/package.json +1 -1
  157. package/core/dist/prompt-builder/attitude-directive.d.ts +0 -7
  158. package/core/dist/prompt-builder/attitude-directive.d.ts.map +0 -1
  159. package/core/dist/prompt-builder/attitude-directive.js +0 -39
  160. package/core/dist/prompt-builder/attitude-directive.js.map +0 -1
  161. package/core/dist/runtime-v2/gfi/gfi-kernel.d.ts +0 -12
  162. package/core/dist/runtime-v2/gfi/gfi-kernel.d.ts.map +0 -1
  163. package/core/dist/runtime-v2/gfi/gfi-kernel.js +0 -148
  164. package/core/dist/runtime-v2/gfi/gfi-kernel.js.map +0 -1
  165. package/core/dist/runtime-v2/gfi/gfi-policy.d.ts +0 -3
  166. package/core/dist/runtime-v2/gfi/gfi-policy.d.ts.map +0 -1
  167. package/core/dist/runtime-v2/gfi/gfi-policy.js +0 -23
  168. package/core/dist/runtime-v2/gfi/gfi-policy.js.map +0 -1
  169. package/core/dist/runtime-v2/gfi/gfi-read-model.d.ts +0 -78
  170. package/core/dist/runtime-v2/gfi/gfi-read-model.d.ts.map +0 -1
  171. package/core/dist/runtime-v2/gfi/gfi-read-model.js +0 -129
  172. package/core/dist/runtime-v2/gfi/gfi-read-model.js.map +0 -1
  173. package/core/dist/runtime-v2/gfi/gfi-types.d.ts +0 -70
  174. package/core/dist/runtime-v2/gfi/gfi-types.d.ts.map +0 -1
  175. package/core/dist/runtime-v2/gfi/gfi-types.js +0 -2
  176. package/core/dist/runtime-v2/gfi/gfi-types.js.map +0 -1
  177. package/core/dist/runtime-v2/gfi/index.d.ts +0 -6
  178. package/core/dist/runtime-v2/gfi/index.d.ts.map +0 -1
  179. package/core/dist/runtime-v2/gfi/index.js +0 -4
  180. package/core/dist/runtime-v2/gfi/index.js.map +0 -1
  181. package/pd-cli/dist/commands/runtime-gfi-snapshot.d.ts +0 -7
  182. package/pd-cli/dist/commands/runtime-gfi-snapshot.d.ts.map +0 -1
  183. package/pd-cli/dist/commands/runtime-gfi-snapshot.js +0 -101
  184. package/pd-cli/dist/commands/runtime-gfi-snapshot.js.map +0 -1
@@ -1,41 +1,41 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- var De=(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 ne=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 se="",Me="|;&<>()";function k(n){return Me.includes(n)?`${se}${n}`:n}function re(n){if(n.includes(se))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]===`
2
+ var Me=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var re=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 oe="",Pe="|;&<>()";function k(t){return Pe.includes(t)?`${oe}${t}`:t}function se(t){if(t.includes(oe))return null;let e=[],n="",r=!1,s=0,o=t.length,i="plain";for(;s<o;){let c=t[s];if(c===void 0)break;if(i==="single"){c==="'"?i="plain":n+=k(c),s+=1;continue}if(i==="double"){if(c==='"')i="plain";else if(c==="\\"&&s+1<o&&'"\\$`'.includes(t[s+1]??"")){n+=k(t[s+1]??""),s+=2;continue}else n+=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){n+=k(t[s+1]??""),r=!0,s+=2;continue}if(c==="\r"||c===`
3
+ `){(r||n)&&(e.push(n),n="",r=!1),c==="\r"&&t[s+1]===`
4
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 oe(n){if(/[\\$`|;&<>()*?~{}]/.test(n)||[...n].some(s=>s.charCodeAt(0)<32))return;let e=re(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 ne){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=re(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}}var Pe=["verbose","debug"],je=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(n,e){return{switches:new Set([...Pe,...n]),valued:new Set([...je,...e])}}var qt=Object.freeze({"get-content":S(["raw","force","wait","asbytestream"],["path","literalpath","totalcount","first","tail","last","encoding","delimiter","readcount","stream","credential"]),"get-childitem":S(["recurse","force","name","file","directory","hidden","readonly","system","followsymlink"],["path","literalpath","filter","include","exclude","depth","attributes","credential"]),"get-item":S(["force","followsymlink"],["path","literalpath","filter","include","exclude","stream","credential"]),"get-itemproperty":S(["force"],["path","literalpath","name","filter","include","exclude","credential"]),"select-string":S(["simplematch","casesensitive","notmatch","allmatches","quiet","list","raw"],["pattern","path","literalpath","inputobject","encoding","context","include","exclude","credential"]),"test-path":S(["isvalid"],["path","literalpath","pathtype","filter","credential"]),"resolve-path":S(["relative"],["path","literalpath","relativebasepath","credential"]),"get-location":S(["stack"],["psprovider","psdrive"])});function C(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 X(n){let e=/^([a-zA-Z]):(?:\/|$)/.exec(n);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(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:C(t.slice(2).join("/"))}}return n.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(n)}:{kind:"relative",root:"",segments:C(n,!0)}}function ie(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 Ue(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 ae(n){let[e,t]=n.root.slice(4).split("/"),r=n.segments.join("/");return`//${e??""}/${t??""}${r?`/${r}`:""}`}function ce(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))||!ie(n.segments,e.segments,n.kind==="drive"||n.kind==="unc")?n.kind==="unc"?ae(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 ie(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":Ue(e.segments,r,s)}function Be(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=X(t),o=X(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=X(c),ce(s,o,c)}return ce(s,o,t)}function Fe(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 We(n){return{isBashTool:n==="execute",isWriteTool:n==="write"}}function Xe(n){if(n.canonicalKind===void 0)return n;let e=We(n.canonicalKind);return{...n,isBashTool:n.isBashTool??e.isBashTool,isWriteTool:n.isWriteTool??e.isWriteTool}}function D(n,e,t,r={}){let s=Xe(r),o=Fe(e,{...s,toolName:n}),i=o.isPath?Be(o.value,t):o.value,c=e.command??e.args,a=s.isBashTool&&typeof c=="string"?oe(c):void 0;return{toolName:n,normalizedPath:i,...a?{recoveryControl:a}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var $=new Set(["read","search","write","execute","agent","other"]);function le(n){return typeof n=="string"&&$.has(n)}var M=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 ue(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 de={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(de);var H={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(H.calls);Object.freeze(H);var $e={version:2,history:H,facts:de};Object.freeze($e);var He=new Set(["__proto__","constructor","prototype"]),pe=3,Ye=5,Ke=new Set(["allow","block","propose_correction"]),Ge={valid:!0,errors:[]};function Y(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function me(n){for(let e of Object.keys(n))if(He.has(e))return!1;return!0}function qe(n){return n.length===0?Ge:{valid:!1,errors:n}}function K(n){return typeof n=="string"&&n.trim().length>0}function fe(n,e,t){let r=[];return Y(n)?me(n)?((!Object.hasOwn(n,"caseId")||!K(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")||!K(n.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(n,"params")||!Y(n.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(n,"expectedDecision")||typeof n.expectedDecision!="string"||!Ke.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 _e(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 P(n){return Array.isArray(n)?`[${n.map(e=>P(e)).join(",")}]`:typeof n=="object"&&n!==null?`{${Object.keys(n).filter(t=>t!=="__proto__"&&t!=="constructor"&&t!=="prototype").sort().map(t=>`${JSON.stringify(t)}:${P(n[t])}`).join(",")}}`:JSON.stringify(n)??"null"}function G(n){if(!Y(n))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!me(n))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(n,"sourceNegativeCase")?e.push(...fe(n.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(n,"ownerDesiredOutcome")||!K(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>pe&&e.push(`positiveCounterexamples must contain at most ${pe} items, got ${t.length}`);for(let r=0;r<t.length;r++)e.push(...fe(t[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(n,"evidenceRefs")?e.push(..._e(n.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ye,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(n,"redactionNotes")?e.push(..._e(n.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let t=n.sourceNegativeCase,r=n.positiveCounterexamples,s=P({toolName:t.toolName,params:t.params,ruleContext:t.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&P({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 qe(e)}var ze="OwnerEvidenceScopeError";function A(n,e){let t=new Error(e);return t.name=ze,Object.assign(t,{ownerEvidenceScopeKind:n}),t}var Ve=new Set(["success","failure","blocked"]);function Je(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ze(n){return typeof n=="string"&&Ve.has(n)}function I(n){return{status:"unavailable",unavailableReason:n,truncated:!1,calls:[]}}function Ee(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 I(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!Ze(a))return I(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return I(`row id=${i.id}: params_json must be a string`);let T;try{T=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Je(T))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,T,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:T,outcome:a})}return{status:"available",truncated:e,calls:o}}var Qe=3,et=5,tt=100,Te=new Set(["__proto__","constructor","prototype"]);function j(n,e){try{return e()}catch(t){let r=t instanceof Error?t.message:String(t);throw A("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${n} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function nt(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function rt(n){for(let e of Object.keys(n))if(Te.has(e))return!1;return!0}function st(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>Qe)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 he(n,e){if(!n)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return n}function ot(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(!nt(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${n.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!rt(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 it(n){return n.startsWith("/")||/^[A-Za-z]:[\\/]/.test(n)}var at=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ct(n){if(n.length<20)return!1;for(let e of at)if(e.test(n))return!0;return!1}function lt(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(it(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ct(o)){r[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}r[s]=o}return{redacted:r,notes:t}}var U=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=j(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!t)throw A("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);st(e);let r=he(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>he(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==t.sessionId)throw A("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,et),redactionNotes:o},T=G(d);if(!T.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${T.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,r){let{projectDir:s,redactionNotes:o}=r,i=ot(e,t,t==="negative"?"block":"allow"),c=lt(i.params,s);o.push(...c.notes);let a=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,tt)),d=Ee(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),T=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:ue(d,T.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import vt from"better-sqlite3";import f from"fs";import h from"path";import Z from"crypto";import*as p from"fs";import*as Se from"path";var q=class extends Error{filePath;lockPath;constructor(e,t,r){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=r}},ut={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function be(n){try{return process.kill(n,0),!0}catch{return!1}}function ge(n,e){try{let t=Se.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 w(n){try{let e=p.readFileSync(n,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function dt(n,e){try{w(n)===e&&p.unlinkSync(n)}catch{}}function pt(n,e){try{let t=p.statSync(n),r=w(n),s=Date.now()-t.mtimeMs>e,o=r===null||!be(r);if(s||o)try{return p.unlinkSync(n),!0}catch{return!1}return!1}catch{return!1}}function ft(n,e,t){let r=Math.min(e*Math.pow(2,n),t),s=r*.2*Math.random();return Math.floor(r+s)}function _t(n){let e=Date.now()+n;for(;Date.now()<e;);}function mt(n,e){let t=w(e),r=t!==null?be(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new q(`Failed to acquire lock for ${n}. Lock holder: ${r}.`,n,e)}function Et(n,e,t){let r=n+e.lockSuffix;return ge(r,t)&&w(r)===t?{lockPath:r,pid:t,acquiredAt:Date.now()}:(pt(r,e.lockStaleMs),ge(r,t)&&w(r)===t?{lockPath:r,pid:t,acquiredAt:Date.now()}:null)}function ht(n,e={}){let t={...ut,...e},{pid:r}=process;for(let s=0;s<t.maxRetries;s++){let o=Et(n,t,r);if(o)return o;if(s<t.maxRetries-1){let i=ft(s,t.baseRetryDelayMs,t.maxRetryDelayMs);_t(i)}}throw mt(n,n+t.lockSuffix)}function Tt(n){dt(n.lockPath,n.pid)}function ye(n,e,t={}){let r=ht(n,t);try{return e()}finally{Tt(r)}}import*as O from"fs";var Oe=3,gt=50;function B(n,e){let t=n+".tmp";O.writeFileSync(t,e,"utf8");let r;for(let s=0;s<Oe;s++)try{O.renameSync(t,n);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Oe-1){let c=gt*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{De("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{O.unlinkSync(t)}catch{}throw r}import*as b from"path";var l=(...n)=>b.posix.join(...n);function St(n){return/^[A-Za-z]:[\\/]/.test(n)||n.startsWith("\\\\")}function bt(n,e){return St(n)?b.win32.join(n,e):n.startsWith("/")?b.posix.join(n,e):b.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")},yt={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 bt(n,yt[e])}var Ot={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"},z=class extends Error{constructor(t,r,s){super(t,s);this.code=r;this.name="PdError",this.category=Ot[r]??"execution_failed"}code;category};var v=class extends z{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var Rt=["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 Nt(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=[...Rt];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"),Nt(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 V from"path";import*as Ne from"os";var At=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],It=V.join(Ne.tmpdir(),".pd-test-quarantine");function wt(n){if(!n)return!1;let e=n.replace(/\\/g,"/");return At.some(t=>t.test(e))}function Ae(n){if(!n||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!wt(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 V.join(It,t)}var xt=16*1024,Lt=5e3,kt=7;function ve(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Ct(n){return!ve(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 Dt(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 Ie(n){try{return f.existsSync(n)?f.statSync(n).size:0}catch{return 0}}function Mt(n){return n.length>240?`${n.slice(0,237)}...`:n}function we(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 Pt(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 F=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Ae(h.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??xt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??kt)*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 vt(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??Lt)}`),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(`
5
+ `),s+=1;continue}if(" ".includes(c)){(r||n)&&(e.push(n),n="",r=!1),s+=1;continue}if("|;&<>()".includes(c)){(r||n)&&(e.push(n),n="",r=!1);let a=c,d=t[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}n+=c,r=!0,s+=1}return i!=="plain"?null:((r||n)&&e.push(n),e)}function ie(t){if(/[\\$`|;&<>()*?~{}]/.test(t)||[...t].some(s=>s.charCodeAt(0)<32))return;let e=se(t);if(!e)return;let n=[...e],r=n.findIndex(s=>s==="-w"||s==="--workspace");if(r!==-1){let s=n[r+1];if(r!==n.length-2||!s||s.startsWith("-"))return;n.splice(r,2)}for(let s of re){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=se(s.cliCommand);if(!o||o.length!==n.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(n[a]??""):c===n[a]))return s.capabilityId}}var je=["verbose","debug"],Ue=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...je,...t]),valued:new Set([...Ue,...e])}}var Vt=Object.freeze({"get-content":S(["raw","force","wait","asbytestream"],["path","literalpath","totalcount","first","tail","last","encoding","delimiter","readcount","stream","credential"]),"get-childitem":S(["recurse","force","name","file","directory","hidden","readonly","system","followsymlink"],["path","literalpath","filter","include","exclude","depth","attributes","credential"]),"get-item":S(["force","followsymlink"],["path","literalpath","filter","include","exclude","stream","credential"]),"get-itemproperty":S(["force"],["path","literalpath","name","filter","include","exclude","credential"]),"select-string":S(["simplematch","casesensitive","notmatch","allmatches","quiet","list","raw"],["pattern","path","literalpath","inputobject","encoding","context","include","exclude","credential"]),"test-path":S(["isvalid"],["path","literalpath","pathtype","filter","credential"]),"resolve-path":S(["relative"],["path","literalpath","relativebasepath","credential"]),"get-location":S(["stack"],["psprovider","psdrive"])});function C(t,e=!1){let n=[];for(let r of t.split("/").filter(s=>s.length>0))r!=="."&&(r===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e&&n.push(".."):n.push(r));return n}function $(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 n=t.slice(2).split("/").filter(o=>o.length>0),r=n[0]??"",s=n[1]??"";return{kind:"unc",root:`unc:${r}/${s}`,segments:C(n.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ae(t,e,n){return t.length<e.length?!1:e.every((r,s)=>{let o=t[s]??"";return n?o.toLowerCase()===r.toLowerCase():o===r})}function Be(t,e,n){let r=0;for(;r<t.length&&r<e.length;){let o=t[r]??"",i=e[r]??"";if(!(n?o.toLowerCase()===i.toLowerCase():o===i))break;r++}return[...Array.from({length:t.length-r},()=>".."),...e.slice(r)].join("/")||"."}function ce(t){let[e,n]=t.root.slice(4).split("/"),r=t.segments.join("/");return`//${e??""}/${n??""}${r?`/${r}`:""}`}function le(t,e,n){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return n;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ae(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?ce(t):n:t.segments.slice(e.segments.length).join("/")||".";let r=[...e.segments];for(let o of n.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 ae(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":Be(e.segments,r,s)}function Fe(t,e){if(!t||typeof t!="string")return"";let n=t.replace(/\\/g,"/"),r=e.replace(/\\/g,"/");if(n.startsWith("<tool:")&&n.endsWith(">"))return n;let s=$(n),o=$(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=$(c),le(s,o,c)}return le(s,o,n)}function We(t,e){let n=t.file_path||t.path||t.file||t.target;if(typeof n=="string"&&n.length>0)return{value:n,isPath:!0};if(e.isBashTool){let r=String(t.command||t.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 Xe(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function $e(t){if(t.canonicalKind===void 0)return t;let e=Xe(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function D(t,e,n,r={}){let s=$e(r),o=We(e,{...s,toolName:t}),i=o.isPath?Fe(o.value,n):o.value,c=e.command??e.args,a=s.isBashTool&&typeof c=="string"?ie(c):void 0;return{toolName:t,normalizedPath:i,...a?{recoveryControl:a}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var H=new Set(["read","search","write","execute","agent","other"]);function ue(t){return typeof t=="string"&&H.has(t)}var M=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 de(t,e,n){if(t.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}=t;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:n}}var pe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(pe);var Y={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(Y.calls);Object.freeze(Y);var He={version:2,history:Y,facts:pe};Object.freeze(He);var Ye=new Set(["__proto__","constructor","prototype"]),fe=3,Ke=5,Ge=new Set(["allow","block","propose_correction"]),qe={valid:!0,errors:[]};function K(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ee(t){for(let e of Object.keys(t))if(Ye.has(e))return!1;return!0}function ze(t){return t.length===0?qe:{valid:!1,errors:t}}function G(t){return typeof t=="string"&&t.trim().length>0}function _e(t,e,n){let r=[];return K(t)?Ee(t)?((!Object.hasOwn(t,"caseId")||!G(t.caseId))&&r.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==n)&&r.push(`${e}.kind must be '${n}'`),(!Object.hasOwn(t,"toolName")||!G(t.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!K(t.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!Ge.has(t.expectedDecision)?r.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):n==="positive"&&t.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 me(t,e){let{fieldName:n,maxLength:r,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${n} must be an array`),o;s&&t.length===0&&o.push(`${n} must contain at least 1 item`),r!==void 0&&t.length>r&&o.push(`${n} must contain at most ${r} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${n}[${i}] must be a string`);return o}function P(t){return Array.isArray(t)?`[${t.map(e=>P(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(n=>n!=="__proto__"&&n!=="constructor"&&n!=="prototype").sort().map(n=>`${JSON.stringify(n)}:${P(t[n])}`).join(",")}}`:JSON.stringify(t)??"null"}function q(t){if(!K(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!Ee(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(..._e(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!G(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 n=t.positiveCounterexamples;n.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),n.length>fe&&e.push(`positiveCounterexamples must contain at most ${fe} items, got ${n.length}`);for(let r=0;r<n.length;r++)e.push(..._e(n[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...me(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ke,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...me(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let n=t.sourceNegativeCase,r=t.positiveCounterexamples,s=P({toolName:n.toolName,params:n.params,ruleContext:n.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&P({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 ze(e)}var Ve="OwnerEvidenceScopeError";function A(t,e){let n=new Error(e);return n.name=Ve,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var Je=new Set(["success","failure","blocked"]);function Ze(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Qe(t){return typeof t=="string"&&Je.has(t)}function I(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function he(t,e,n){let{projectDir:r,toolSemantics:s}=n,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return I(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!Qe(a))return I(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return I(`row id=${i.id}: params_json must be a string`);let T;try{T=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Ze(T))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,T,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:T,outcome:a})}return{status:"available",truncated:e,calls:o}}var et=3,tt=5,nt=100,ge=new Set(["__proto__","constructor","prototype"]);function j(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw A("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function st(t){for(let e of Object.keys(t))if(ge.has(e))return!1;return!0}function ot(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>et)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(n=>!Number.isSafeInteger(n)||n<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function Te(t,e){if(!t)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function it(t,e,n){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 r;try{r=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!rt(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!st(r))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:r,expectedDecision:n}}function at(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var ct=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function lt(t){if(t.length<20)return!1;for(let e of ct)if(e.test(t))return!0;return!1}function ut(t,e){let n=[],r={};for(let s of Object.keys(t)){if(ge.has(s))continue;let o=t[s];if(typeof o!="string"){r[s]=o;continue}if(at(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(lt(o)){r[s]="<redacted:secret>",n.push(`redacted possible secret in field "${s}"`);continue}r[s]=o}return{redacted:r,notes:n}}var U=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let n=j(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!n)throw A("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ot(e);let r=Te(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>Te(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==n.sessionId)throw A("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${n.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:${n.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,tt),redactionNotes:o},T=q(d);if(!T.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${T.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=it(e,n,n==="negative"?"block":"allow"),c=ut(i.params,s);o.push(...c.notes);let a=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,nt)),d=he(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),T=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:de(d,T.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import Lt from"better-sqlite3";import f from"fs";import h from"path";import Q from"crypto";import*as p from"fs";import*as ye from"path";var z=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},dt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Oe(t){try{return process.kill(t,0),!0}catch{return!1}}function Se(t,e){try{let n=ye.dirname(t);p.existsSync(n)||p.mkdirSync(n,{recursive:!0});let r=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(t,r);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function v(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function pt(t,e){try{v(t)===e&&p.unlinkSync(t)}catch{}}function ft(t,e){try{let n=p.statSync(t),r=v(t),s=Date.now()-n.mtimeMs>e,o=r===null||!Oe(r);if(s||o)try{return p.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function _t(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function mt(t){let e=Date.now()+t;for(;Date.now()<e;);}function Et(t,e){let n=v(e),r=n!==null?Oe(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new z(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function ht(t,e,n){let r=t+e.lockSuffix;return Se(r,n)&&v(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(ft(r,e.lockStaleMs),Se(r,n)&&v(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function Tt(t,e={}){let n={...dt,...e},{pid:r}=process;for(let s=0;s<n.maxRetries;s++){let o=ht(t,n,r);if(o)return o;if(s<n.maxRetries-1){let i=_t(s,n.baseRetryDelayMs,n.maxRetryDelayMs);mt(i)}}throw Et(t,t+n.lockSuffix)}function gt(t){pt(t.lockPath,t.pid)}function Re(t,e,n={}){let r=Tt(t,n);try{return e()}finally{gt(r)}}import*as R from"fs";var be=3,St=50;function B(t,e){let n=t+".tmp";R.writeFileSync(n,e,"utf8");let r;for(let s=0;s<be;s++)try{R.renameSync(n,t);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<be-1){let c=St*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Me("fs").accessSync?.(n)}catch{}d=!0}}continue}break}try{R.unlinkSync(n)}catch{}throw r}import*as y from"path";var l=(...t)=>y.posix.join(...t);function yt(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function Ot(t,e){return yt(t)?y.win32.join(t,e):t.startsWith("/")?y.posix.join(t,e):y.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")},Rt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(t,e){return Ot(t,Rt[e])}var bt={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"},V=class extends Error{constructor(n,r,s){super(n,s);this.code=r;this.name="PdError",this.category=bt[r]??"execution_failed"}code;category};var w=class extends V{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var Nt=["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 F(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function At(t){if(!F(t,"schema_version"))return;let e=t.prepare("SELECT version FROM schema_version LIMIT 1").get();if(e===void 0){t.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2);return}e.version!==2&&t.prepare("UPDATE schema_version SET version = ?").run(2)}function It(t){if(F(t,"tool_calls"))for(let e of["gfi_before","gfi_after"])t.prepare("SELECT name FROM pragma_table_info('tool_calls') WHERE name = ?").get(e)!==void 0&&t.exec(`ALTER TABLE tool_calls DROP COLUMN ${e}`);F(t,"signal_confirmations")&&t.prepare("UPDATE signal_confirmations SET status = 'abandoned', resolved_at = ?, resolution = ? WHERE status = 'pending' AND suggested_type = 'empathy'").run(new Date().toISOString(),"gfi_removal"),At(t)}function Ne(t,e={}){let n=[],r=[...Nt];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, 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"),F(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 It(t),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:r,warnings:n}}import*as J from"path";import*as Ae from"os";var vt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],wt=J.join(Ae.tmpdir(),".pd-test-quarantine");function xt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return vt.some(n=>n.test(e))}function Ie(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!xt(t))return t;let n=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;n.startsWith("_");)n=n.slice(1);for(;n.endsWith("_");)n=n.slice(0,-1);return J.join(wt,n)}var kt=16*1024,Ct=5e3,Dt=7;function xe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mt(t){return!xe(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 Pt(t){let e=Ne(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function ve(t){try{return f.existsSync(t)?f.statSync(t).size:0}catch{return 0}}function jt(t){return t.length>240?`${t.slice(0,237)}...`:t}function we(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 Ut(t){let e=[],n=!1;try{let r=JSON.parse(String(t.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"),n=!0)}}}catch{e=[],n=!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:n,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 W=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Ie(h.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??kt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??Dt)*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 Lt(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??Ct)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let n=e.startedAt??_();this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,n)})}upsertSessionUnlocked(e,n){this.db.prepare(`
6
6
  INSERT INTO sessions (session_id, started_at, updated_at)
7
7
  VALUES (?, ?, ?)
8
8
  ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
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(`
9
+ `).run(e,n,_())}recordAssistantTurn(e){let n=this.storeRawText("assistant",e.rawText),r=e.createdAt??_();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??r);let s=this.db.prepare(`
10
10
  INSERT INTO assistant_turns (
11
11
  session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
12
12
  empathy_signal_json, blob_ref, raw_excerpt, stop_reason, thinking_blocks_count, created_at
13
13
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
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(`
14
+ `).run(e.sessionId,e.runId,e.provider,e.model,n.inlineText,e.sanitizedText,b(e.usageJson),b(e.empathySignalJson),n.blobRef,n.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,r);return Number(s.lastInsertRowid)})}recordUserTurn(e){let n=this.storeRawText("user",e.rawText),r=e.createdAt??_();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??r);let s=this.db.prepare(`
15
15
  INSERT INTO user_turns (
16
16
  session_id, turn_index, raw_text, blob_ref, raw_excerpt,
17
17
  correction_detected, correction_cue, references_assistant_turn_id, created_at
18
18
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
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(`
19
+ `).run(e.sessionId,e.turnIndex,n.inlineText,n.blobRef,n.excerpt,e.correctionDetected?1:0,e.correctionCue??null,e.referencesAssistantTurnId??null,r);return Number(s.lastInsertRowid)})}markUserTurnCorrection(e,n){let r=this.withWrite(()=>this.db.prepare(`
20
20
  UPDATE user_turns
21
21
  SET correction_detected = 1, correction_cue = ?
22
22
  WHERE id = ?
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(`
23
+ `).run(n??null,e));return Number(r.changes)>0}recordToolCall(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let n=e.createdAt??_(),r=this.withWrite(()=>{let s=this.db.prepare(`
24
24
  INSERT INTO tool_calls (
25
25
  session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
26
- gfi_before, gfi_after, params_json, result_preview, created_at
27
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
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
+ params_json, result_preview, created_at
27
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
28
+ `).run(e.sessionId,e.toolName,e.outcome,e.durationMs??null,e.exitCode??null,e.errorType??null,e.errorMessage??null,b(e.paramsJson),e.resultPreview??null,n);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),r}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let n=-1;return this.withWrite(()=>{try{let r=this.db.prepare(`
29
29
  INSERT INTO pain_events (
30
30
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
31
31
  canonical_pain_id, runtime_task_id, host_kind
32
32
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
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(`
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);n=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(`
34
34
  UPDATE pain_events
35
35
  SET runtime_task_id = COALESCE(?, runtime_task_id),
36
36
  host_kind = COALESCE(host_kind, ?)
37
37
  WHERE canonical_pain_id = ?
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(`
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"?n=s.id:n=-1}else throw r}}),n}recordGateBlock(e){this.withWrite(()=>{this.db.prepare(`
39
39
  INSERT INTO gate_blocks (session_id, tool_name, file_path, reason, created_at)
40
40
  VALUES (?, ?, ?, ?, ?)
41
41
  `).run(e.sessionId??null,e.toolName,e.filePath??null,e.reason,e.createdAt??_())})}recordTrustChange(e){this.withWrite(()=>{this.db.prepare(`
@@ -44,10 +44,10 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
44
44
  `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??_())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
45
45
  INSERT INTO principle_events (principle_id, event_type, payload_json, created_at)
46
46
  VALUES (?, ?, ?, ?)
47
- `).run(e.principleId??null,e.eventType,R(e.payload),e.createdAt??_())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
47
+ `).run(e.principleId??null,e.eventType,b(e.payload),e.createdAt??_())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
48
48
  INSERT INTO task_outcomes (session_id, task_id, outcome, summary, principle_ids_json, created_at)
49
49
  VALUES (?, ?, ?, ?, ?, ?)
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(`
50
+ `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,b(e.principleIdsJson),e.createdAt??_())})}evolutionTableMissing(e){let n=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!n||typeof n.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let n=[],r=[];e.status&&(n.push("status = ?"),r.push(e.status)),e.dateFrom&&(n.push("created_at >= ?"),r.push(e.dateFrom)),e.dateTo&&(n.push("created_at <= ?"),r.push(e.dateTo));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",o=e.limit??50,i=e.offset??0;return this.db.prepare(`
51
51
  SELECT id, task_id, trace_id, source, reason, score, status,
52
52
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
53
53
  task_kind, priority, retry_count, max_retries, last_error, result_ref
@@ -55,7 +55,7 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
55
55
  ${s}
56
56
  ORDER BY created_at DESC
57
57
  LIMIT ? OFFSET ?
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(`
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,n={}){if(this.evolutionTableMissing("evolution_events"))return[];let r=n.limit??100,s=n.offset??0,o;return e?o=this.db.prepare(`
59
59
  SELECT id, trace_id, task_id, stage, level, message, summary, metadata_json, created_at
60
60
  FROM evolution_events
61
61
  WHERE trace_id = ?
@@ -66,16 +66,16 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
66
66
  FROM evolution_events
67
67
  ORDER BY created_at DESC
68
68
  LIMIT ? OFFSET ?
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(`
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 n=this.db.prepare(`
70
70
  SELECT id, task_id, trace_id, source, reason, score, status,
71
71
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
72
72
  task_kind, priority, retry_count, max_retries, last_error, result_ref
73
73
  FROM evolution_tasks
74
74
  WHERE trace_id = ?
75
75
  LIMIT 1
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(`
76
+ `).get(e);return n?{id:Number(n.id),taskId:String(n.task_id),traceId:String(n.trace_id),source:String(n.source),reason:n.reason?String(n.reason):null,score:Number(n.score??0),status:String(n.status),enqueuedAt:n.enqueued_at?String(n.enqueued_at):null,startedAt:n.started_at?String(n.started_at):null,completedAt:n.completed_at?String(n.completed_at):null,resolution:n.resolution?String(n.resolution):null,createdAt:String(n.created_at),updatedAt:String(n.updated_at),taskKind:n.task_kind?n.task_kind:null,priority:n.priority?n.priority:null,retryCount:n.retry_count!=null?Number(n.retry_count):null,maxRetries:n.max_retries!=null?Number(n.max_retries):null,lastError:n.last_error?String(n.last_error):null,resultRef:n.result_ref?String(n.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(`
77
77
  SELECT status, COUNT(*) as count FROM evolution_tasks GROUP BY status
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(`
78
+ `).all(),n={total:0,pending:0,inProgress:0,completed:0,failed:0};for(let r of e)n.total+=r.count,r.status==="pending"?n.pending=r.count:r.status==="in_progress"?n.inProgress=r.count:r.status==="completed"?n.completed=r.count:r.status==="failed"&&(n.failed=r.count);return n}listRecentSessions(e={}){let n=[],r=[];e.dateFrom&&(n.push("updated_at >= ?"),r.push(e.dateFrom)),e.dateTo&&(n.push("updated_at <= ?"),r.push(e.dateTo));let s=n.length>0?`WHERE ${n.join(" AND ")}`:"",o=e.limit??20;return this.db.prepare(`
79
79
  SELECT session_id, started_at, updated_at
80
80
  FROM sessions
81
81
  ${s}
@@ -89,54 +89,54 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
89
89
  ORDER BY id ASC
90
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(`
91
91
  SELECT id, tool_name, outcome, params_json, duration_ms, exit_code, error_type, error_message,
92
- gfi_before, gfi_after, result_preview, created_at
92
+ result_preview, created_at
93
93
  FROM tool_calls
94
94
  WHERE session_id = ?
95
95
  ORDER BY id ASC
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(`
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,resultPreview:r.result_preview!=null?String(r.result_preview):null,createdAt:String(r.created_at)}})}getRuleHostContextRows(e,n=20){let r=Math.max(1,Math.floor(n)),s=this.db.prepare(`
97
97
  SELECT id, tool_name, outcome, params_json
98
98
  FROM tool_calls
99
99
  WHERE session_id = ?
100
100
  ORDER BY id DESC
101
101
  LIMIT ?
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(`
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 n=this.db.prepare(`
103
103
  SELECT id, session_id, tool_name, outcome, params_json
104
104
  FROM tool_calls
105
105
  WHERE id = ?
106
106
  LIMIT 1
107
- `).get(e);return!ve(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(`
107
+ `).get(e);return!xe(n)||typeof n.id!="number"||typeof n.session_id!="string"||typeof n.tool_name!="string"||typeof n.outcome!="string"||typeof n.params_json!="string"?null:{id:n.id,sessionId:n.session_id,toolName:n.tool_name,outcome:n.outcome,paramsJson:n.params_json}}getRuleHostContextRowsBefore(e,n,r=20){let s=Math.max(1,Math.floor(r)),o=this.db.prepare(`
108
108
  SELECT id, tool_name, outcome, params_json
109
109
  FROM tool_calls
110
110
  WHERE session_id = ? AND id < ?
111
111
  ORDER BY id DESC
112
112
  LIMIT ?
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(`
113
+ `).all(e,n,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(`
114
114
  SELECT id, source, score, reason, severity, origin, confidence, created_at
115
115
  FROM pain_events
116
116
  WHERE session_id = ?
117
117
  ORDER BY created_at ASC
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(`
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 n=this.db.prepare(`
119
119
  SELECT id, session_id, source, score, reason, severity, origin, confidence,
120
120
  text, canonical_pain_id, runtime_task_id, created_at
121
121
  FROM pain_events
122
122
  WHERE canonical_pain_id = ?
123
123
  LIMIT 1
124
- `).get(e);return Ct(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(`
124
+ `).get(e);return Mt(n)?{id:n.id,sessionId:n.session_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,text:n.text?String(n.text):null,canonicalPainId:String(n.canonical_pain_id),runtimeTaskId:n.runtime_task_id?String(n.runtime_task_id):null,createdAt:String(n.created_at)}:null}listUserTurnsForSession(e){return this.db.prepare(`
125
125
  SELECT id, turn_index, raw_excerpt, correction_detected, correction_cue, created_at
126
126
  FROM user_turns
127
127
  WHERE session_id = ?
128
128
  ORDER BY turn_index ASC
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(`
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,n){let r=this.db.prepare(`
130
130
  SELECT turn_index, raw_text, blob_ref, raw_excerpt, references_assistant_turn_id, created_at
131
131
  FROM user_turns
132
132
  WHERE session_id = ? AND correction_detected = 1
133
133
  ORDER BY id DESC
134
134
  LIMIT 1
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(`
135
+ `).get(e);if(!r)return;let s=String(r.created_at??""),o=n?.maxAgeMs??1800*1e3,i=Date.parse(s);if(Number.isFinite(i)&&(n?.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 n=this.db.prepare(`
136
136
  SELECT turn_index, raw_text, blob_ref, raw_excerpt, references_assistant_turn_id, created_at
137
137
  FROM user_turns
138
138
  WHERE id = ?
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(`
139
+ `).get(e);if(!n)return;let r=String(n.raw_excerpt??""),s=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))||r;if(s.length!==0)return{turnIndex:Number(n.turn_index),text:s,referencesAssistantTurnId:n.references_assistant_turn_id===null||n.references_assistant_turn_id===void 0?null:Number(n.references_assistant_turn_id),occurredAt:String(n.created_at??"")}}listCorrectionSamples(e="pending"){return this.db.prepare(`
140
140
  SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
141
141
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
142
142
  review_status, export_mode, created_at, updated_at
@@ -149,37 +149,37 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
149
149
  LEFT JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
150
150
  WHERE cs.session_id = ?
151
151
  ORDER BY cs.created_at DESC
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(`
152
+ `).all(e).map(r=>({correctionCue:r.correction_cue?String(r.correction_cue):null}))}reviewCorrectionSample(e,n,r){let s=_();if(!this.withWrite(()=>this.db.prepare(`
153
153
  UPDATE correction_samples
154
154
  SET review_status = ?, updated_at = ?
155
155
  WHERE sample_id = ?
156
- `).run(t,s,e).changes===0?!1:(this.db.prepare(`
156
+ `).run(n,s,e).changes===0?!1:(this.db.prepare(`
157
157
  INSERT INTO sample_reviews (sample_id, review_status, note, created_at)
158
158
  VALUES (?, ?, ?, ?)
159
- `).run(e,t,r??null,s),!0)))throw new v(e);let i=this.db.prepare(`
159
+ `).run(e,n,r??null,s),!0)))throw new w(e);let i=this.db.prepare(`
160
160
  SELECT sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
161
161
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
162
162
  review_status, export_mode, created_at, updated_at
163
163
  FROM correction_samples
164
164
  WHERE sample_id = ?
165
- `).get(e);if(!i)throw new v(`${e} (after update)`);return{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)}}enqueueSignalConfirmation(e){let t=`sq_${Z.createHash("sha256").update(`${e.sessionId}:${e.userTurnRowid}`).digest("hex").slice(0,12)}`;this.withWrite(()=>{this.db.prepare(`
165
+ `).get(e);if(!i)throw new w(`${e} (after update)`);return{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)}}enqueueSignalConfirmation(e){let n=`sq_${Q.createHash("sha256").update(`${e.sessionId}:${e.userTurnRowid}`).digest("hex").slice(0,12)}`;this.withWrite(()=>{this.db.prepare(`
166
166
  INSERT OR IGNORE INTO signal_confirmations (
167
167
  id, session_id, user_turn_rowid, occurrence_id, excerpt,
168
168
  terms_json, suggested_type, status, attempts, created_at
169
169
  ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)
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(`
170
+ `).run(n,e.sessionId,e.userTurnRowid,e.occurrenceId,e.excerpt,JSON.stringify({correction:e.terms}),e.suggestedType,e.createdAt)})}listPendingSignalConfirmations(e){return this.db.prepare(`
171
171
  SELECT * FROM signal_confirmations
172
172
  WHERE status = 'pending'
173
173
  ORDER BY attempts ASC, created_at ASC
174
174
  LIMIT ?
175
- `).all(e).map(Pt)}bumpSignalConfirmationAttempt(e){return this.withWrite(()=>{this.db.prepare(`
175
+ `).all(e).map(Ut)}bumpSignalConfirmationAttempt(e){return this.withWrite(()=>{this.db.prepare(`
176
176
  UPDATE signal_confirmations SET attempts = attempts + 1
177
177
  WHERE id = ? AND status = 'pending'
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(`
178
+ `).run(e)}),this.db.prepare("SELECT attempts FROM signal_confirmations WHERE id = ?").get(e)?.attempts??0}markSignalConfirmationResult(e,n,r){let s=this.withWrite(()=>this.db.prepare(`
179
179
  UPDATE signal_confirmations
180
180
  SET status = ?, resolved_at = ?, resolution = ?
181
181
  WHERE id = ? AND status = 'pending'
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(`
182
+ `).run(n,_(),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 n=this.db.prepare(`
183
183
  SELECT cs.sample_id, cs.session_id, cs.recovery_tool_span_json, cs.diff_excerpt, cs.quality_score,
184
184
  at.raw_text AS assistant_raw_text, at.blob_ref AS assistant_blob_ref, at.sanitized_text,
185
185
  ut.raw_text AS user_raw_text, ut.blob_ref AS user_blob_ref, ut.correction_cue
@@ -188,16 +188,16 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
188
188
  JOIN user_turns ut ON ut.id = cs.user_correction_turn_id
189
189
  WHERE (? = 0 OR cs.review_status = 'approved')
190
190
  ORDER BY cs.created_at ASC
191
- `).all(e.approvedOnly?1:0),r=h.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"?we(i):i,d=e.mode==="redacted"?we(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 B(r,`${s.join(`
191
+ `).all(e.approvedOnly?1:0),r=h.join(this.exportDir,`corrections-${Date.now()}-${e.mode}.jsonl`),s=n.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"?we(i):i,d=e.mode==="redacted"?we(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 B(r,`${s.join(`
192
192
  `)}${s.length>0?`
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=h.join(this.exportDir,`analytics-${Date.now()}.json`);return B(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(`
193
+ `:""}`),this.recordExportAudit("corrections",e.mode,e.approvedOnly,r,n.length),{filePath:r,count:n.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()},n=h.join(this.exportDir,`analytics-${Date.now()}.json`);return B(n,JSON.stringify(e,null,2)),this.recordExportAudit("analytics","raw",!0,n,Array.isArray(e.dailyMetrics)?e.dailyMetrics.length:0),{filePath:n,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)},n=this.db.prepare(`
194
194
  SELECT MAX(ts) AS ts FROM (
195
195
  SELECT MAX(created_at) AS ts FROM assistant_turns
196
196
  UNION ALL SELECT MAX(created_at) AS ts FROM user_turns
197
197
  UNION ALL SELECT MAX(created_at) AS ts FROM tool_calls
198
198
  UNION ALL SELECT MAX(created_at) AS ts FROM pain_events
199
199
  )
200
- `).get();return{dbPath:this.dbPath,dbSizeBytes:Ie(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=Dt(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(`
200
+ `).get();return{dbPath:this.dbPath,dbSizeBytes:ve(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:n.ts??null}}cleanupBlobStorage(){return this.pruneUnreferencedBlobs()}initSchema(){let e=Pt(this.db);for(let r of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${r}`);let n=this.db.prepare("SELECT version FROM schema_version LIMIT 1").get();this.migrateSchema(n?.version),n?n.version!==2&&this.db.prepare("UPDATE schema_version SET version = ?").run(2):this.db.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2)}importLegacyArtifacts(){this.importLegacySessions(),this.importLegacyEvents(),this.importLegacyEvolution()}migrateSchema(e){this.db.exec(`
201
201
  DROP VIEW IF EXISTS v_daily_metrics;
202
202
  CREATE VIEW IF NOT EXISTS v_daily_metrics AS
203
203
  WITH tool_daily AS (
@@ -222,8 +222,8 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
222
222
  COALESCE(correction_daily.user_corrections, 0) AS user_corrections
223
223
  FROM tool_daily
224
224
  LEFT JOIN correction_daily ON correction_daily.day = tool_daily.day;
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(h.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=h.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(`
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 n=O(this.workspaceDir,"SESSION_DIR");if(f.existsSync(n)){for(let r of f.readdirSync(n).filter(s=>s.endsWith(".json")))try{let s=JSON.parse(f.readFileSync(h.join(n,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 n=h.join(this.stateDir,"logs","events.jsonl");if(!f.existsSync(n))return;let r=f.readFileSync(n,"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 n=O(this.workspaceDir,"EVOLUTION_STREAM");if(!f.existsSync(n))return;let r=f.readFileSync(n,"utf8").trim();if(!r){this.markImported(e);return}for(let s of r.split(`
227
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(`
228
228
  INSERT INTO ingest_checkpoint (source_key, imported_at)
229
229
  VALUES (?, ?)
@@ -251,17 +251,17 @@ var De=(n=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(n,{get:(e,t)=>(
251
251
  WHERE session_id = ?
252
252
  ORDER BY id DESC
253
253
  LIMIT 5
254
- `).all(e).filter(g=>g.outcome==="success"),c=i[0]?.id??r.id,a=`sample_${Z.createHash("sha256").update(`${e}:${r.id}:${c}`).digest("hex").slice(0,12)}`,d=this.restoreRawText(r.raw_text,r.blob_ref),T=[r.references_assistant_turn_id?35:0,r.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((g,Ce)=>g+Ce,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(`
254
+ `).all(e).filter(g=>g.outcome==="success"),c=i[0]?.id??r.id,a=`sample_${Q.createHash("sha256").update(`${e}:${r.id}:${c}`).digest("hex").slice(0,12)}`,d=this.restoreRawText(r.raw_text,r.blob_ref),T=[r.references_assistant_turn_id?35:0,r.correction_cue?20:0,s?20:0,Math.min(i.length,3)*5].reduce((g,De)=>g+De,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(`
255
255
  INSERT OR IGNORE INTO correction_samples (
256
256
  sample_id, session_id, bad_assistant_turn_id, user_correction_turn_id,
257
257
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
258
258
  review_status, export_mode, created_at, updated_at
259
259
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'raw', ?, ?)
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}))),Mt(m),"[]",T,_(),_())})}recordExportAudit(e,t,r,s,o){this.withWrite(()=>{this.db.prepare(`
260
+ `).run(a,e,Number(r.references_assistant_turn_id),Number(r.id),b(i.map(g=>({id:g.id,toolName:g.tool_name,outcome:g.outcome}))),jt(m),"[]",T,_(),_())})}recordExportAudit(e,n,r,s,o){this.withWrite(()=>{this.db.prepare(`
261
261
  INSERT INTO exports_audit (export_kind, mode, approved_only, file_path, row_count, created_at)
262
262
  VALUES (?, ?, ?, ?, ?, ?)
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=Z.createHash("sha256").update(t).digest("hex"),i=`${e}-${o}.txt`,c=h.join(this.blobDir,i);return f.existsSync(c)||B(c,t),{inlineText:null,blobRef:i,excerpt:r}}restoreRawText(e,t){if(e)return e;if(!t)return"";let r=h.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+Ie(h.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(`
263
+ `).run(e,n,r?1:0,s,o,_())})}storeRawText(e,n){let r=n.length>200?`${n.slice(0,197)}...`:n;if(Buffer.byteLength(n,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:n,blobRef:null,excerpt:r};let o=Q.createHash("sha256").update(n).digest("hex"),i=`${e}-${o}.txt`,c=h.join(this.blobDir,i);return f.existsSync(c)||B(c,n),{inlineText:null,blobRef:i,excerpt:r}}restoreRawText(e,n){if(e)return e;if(!n)return"";let r=h.join(this.blobDir,n);return f.existsSync(r)?f.readFileSync(r,"utf8"):""}computeBlobBytes(){return f.existsSync(this.blobDir)?f.readdirSync(this.blobDir).reduce((e,n)=>e+ve(h.join(this.blobDir,n)),0):0}pruneUnreferencedBlobs(){if(!f.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,n=this.db.prepare(`
264
264
  SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
265
265
  UNION
266
266
  SELECT blob_ref FROM user_turns WHERE blob_ref IS NOT NULL
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=h.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})}},x=class{static instances=new Map;static get(e,t={}){let r=h.resolve(e),s=this.instances.get(r);if(s)return s;let o=new F({workspaceDir:r,...t});return this.instances.set(r,o),o}static dispose(e){let t=h.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=h.resolve(e),o=this.instances.get(s);if(o)return t(o);let i=new F({workspaceDir:s,...r});try{return t(i)}finally{i.dispose()}}};var jt=new Set(["__proto__","constructor","prototype"]);function Ut(n){return typeof n=="object"&&n!==null&&!Array.isArray(n)}function Bt(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(!Ut(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(jt.has(r.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=r.canonicalKind;if(!le(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...$].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 xe(n){let e,t=new Set,r=[];if(n===void 0)e=M;else{let s=Bt(n);if(!s.valid)return{ok:!1,errors:s.errors};let o={...M};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 Le=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],N=["write","edit","apply_patch"],L=["exec"],Ft=[...L],W=["sessions_spawn"],Wt=[...N],Xt=[...N,...L,...W],$t=[...Le],Bn=new Set(Le),Fn=new Set(N),Wn=new Set(Ft),Xn=new Set(L),$n=new Set(W),Hn=new Set(Wt),Yn=new Set(Xt),Kn=new Set($t),Gn=new Set([...N]);function Q(n,e){return n.map(t=>({rawToolName:t,canonicalKind:e}))}var Ht=Object.freeze([...Q(L,"execute"),...Q(N,"write"),...Q(W,"agent")]),ee=xe(Ht);if(!ee.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${ee.errors.join("; ")}`);var ke=ee.registry;var te=class extends U{constructor(e){super({source:x.get(e.workspaceDir),toolSemantics:ke})}};export{te as BehaviorExamplePackAssembler,x as RuleHostEvidenceRegistry};
267
+ `).all();for(let i of n)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=h.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 Re(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},x=class{static instances=new Map;static get(e,n={}){let r=h.resolve(e),s=this.instances.get(r);if(s)return s;let o=new W({workspaceDir:r,...n});return this.instances.set(r,o),o}static dispose(e){let n=h.resolve(e),r=this.instances.get(n);r&&(r.dispose(),this.instances.delete(n))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,n,r={}){let s=h.resolve(e),o=this.instances.get(s);if(o)return n(o);let i=new W({workspaceDir:s,...r});try{return n(i)}finally{i.dispose()}}};var Bt=new Set(["__proto__","constructor","prototype"]);function Ft(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Wt(t){if(!Array.isArray(t))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],n=new Map;return t.forEach((r,s)=>{if(!Ft(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(Bt.has(r.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=r.canonicalKind;if(!ue(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...H].join("|")}, got ${String(o)}`);return}let i=n.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}n.set(r.rawToolName,o)}),{valid:e.length===0,errors:e}}function Le(t){let e,n=new Set,r=[];if(t===void 0)e=M;else{let s=Wt(t);if(!s.valid)return{ok:!1,errors:s.errors};let o={...M};for(let i of t)o[i.rawToolName]=i.canonicalKind,n.add(i.rawToolName);r=Object.freeze(t.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:n.size>0,hasHostTool(s){return typeof s!="string"?!1:n.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 ke=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],N=["write","edit","apply_patch"],L=["exec"],Xt=[...L],X=["sessions_spawn"],$t=[...N],Ht=[...N,...L,...X],Yt=[...ke],Wn=new Set(ke),Xn=new Set(N),$n=new Set(Xt),Hn=new Set(L),Yn=new Set(X),Kn=new Set($t),Gn=new Set(Ht),qn=new Set(Yt),zn=new Set([...N]);function ee(t,e){return t.map(n=>({rawToolName:n,canonicalKind:e}))}var Kt=Object.freeze([...ee(L,"execute"),...ee(N,"write"),...ee(X,"agent")]),te=Le(Kt);if(!te.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${te.errors.join("; ")}`);var Ce=te.registry;var ne=class extends U{constructor(e){super({source:x.get(e.workspaceDir),toolSemantics:Ce})}};export{ne as BehaviorExamplePackAssembler,x as RuleHostEvidenceRegistry};
@@ -1,7 +1,6 @@
1
1
  {
2
2
  "language": "zh",
3
3
  "thresholds": {
4
- "pain_trigger": 40,
5
4
  "cognitive_paralysis_input": 4000,
6
5
  "semantic_min_score": 0.7,
7
6
  "promotion_count_threshold": 3,
@@ -10,18 +9,12 @@
10
9
  "scores": {
11
10
  "default_confusion": 30,
12
11
  "default_loop": 40,
13
- "tool_failure_friction": 15,
14
12
  "exit_code_penalty": 50,
15
13
  "spiral_penalty": 30,
16
14
  "missing_test_command_penalty": 20,
17
15
  "subagent_error_penalty": 60,
18
16
  "subagent_timeout_penalty": 50
19
17
  },
20
- "severity_thresholds": {
21
- "high": 70,
22
- "medium": 40,
23
- "low": 20
24
- },
25
18
  "trust": {
26
19
  "stages": {
27
20
  "stage_1_observer": 30,
@@ -52,44 +45,5 @@
52
45
  "stage_2_max_lines": 50,
53
46
  "stage_3_max_lines": 300
54
47
  }
55
- },
56
- "empathy_engine": {
57
- "enabled": true,
58
- "dedupe_window_ms": 60000,
59
- "penalties": {
60
- "mild": 10,
61
- "moderate": 25,
62
- "severe": 40
63
- },
64
- "rate_limit": {
65
- "max_per_turn": 40,
66
- "max_per_hour": 120
67
- },
68
- "model_calibration": {}
69
- },
70
- "gfi_gate": {
71
- "enabled": true,
72
- "thresholds": {
73
- "low_risk_block": 70,
74
- "high_risk_block": 40,
75
- "large_change_block": 50
76
- },
77
- "large_change_lines": 50,
78
- "bash_safe_patterns": [
79
- "^(ls|dir|pwd|which|where|echo|env|cat|type|head|tail|less|more)\\b",
80
- "^git\\s+(status|log|diff|branch|show|remote)\\b",
81
- "^npm\\s+(run|test|build|start)\\b",
82
- "^(make|gradle|mvn)\\b"
83
- ],
84
- "bash_dangerous_patterns": [
85
- "rm\\s+(-[a-z]*r[a-z]*f|-rf)",
86
- "del\\s+/s",
87
- "rmdir\\s+/s",
88
- "git\\s+(push\\s+.*--force|reset\\s+--hard|clean\\s+-fd)",
89
- "npm\\s+publish",
90
- "pip\\s+upload",
91
- "docker\\s+push",
92
- "(curl|wget).*\\|\\s*(ba)?sh"
93
- ]
94
48
  }
95
49
  }