create-principles-disciple 1.145.34 → 1.145.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +2 -2
- package/console/dist/server/models/ApprovalsConsoleModel.d.ts +22 -2
- package/console/dist/server/models/ApprovalsConsoleModel.js +56 -16
- package/console/dist/server/models/ApprovalsGroupedConsoleModel.d.ts +8 -0
- package/console/dist/server/models/ApprovalsGroupedConsoleModel.js +3 -2
- package/console/dist/server/models/approval-review-material.d.ts +15 -0
- package/console/dist/server/models/approval-review-material.js +32 -0
- package/console/dist/server/routes/approvals.js +32 -7
- package/console/dist/ui/api.d.ts +8 -2
- package/console/dist/ui/api.js +8 -4
- package/console/dist/ui/i18n/en.json +98 -7
- package/console/dist/ui/i18n/zh-CN.json +98 -7
- package/console/dist/ui/pages/focus/ApprovalSubjectReading.d.ts +24 -0
- package/console/dist/ui/pages/focus/ApprovalSubjectReading.js +133 -0
- package/console/dist/ui/pages/focus/FocusPage.d.ts +5 -26
- package/console/dist/ui/pages/focus/FocusPage.js +166 -459
- package/console/dist/ui/pages/focus/OwnerWorkbench.d.ts +19 -0
- package/console/dist/ui/pages/focus/OwnerWorkbench.js +75 -0
- package/console/dist/ui/pages/focus/RuleCandidateBindingPanel.d.ts +4 -1
- package/console/dist/ui/pages/focus/RuleCandidateBindingPanel.js +7 -3
- package/console/dist/ui/pages/focus/focus-validation.js +31 -0
- package/console/dist/ui/pages/principles/PrincipleDetailPage.js +110 -86
- package/console/dist/ui/pages/principles/PrinciplesPage.js +39 -30
- package/console/dist/ui/utils/approval-review.d.ts +30 -0
- package/console/dist/ui/utils/approval-review.js +50 -0
- package/console/dist/ui/utils/reading-layout.d.ts +1 -0
- package/console/dist/ui/utils/reading-layout.js +1 -1
- package/console/dist/ui/utils/validators.d.ts +4 -0
- package/console/dist/ui/utils/validators.js +10 -2
- package/console/dist/web/assets/app.css +119 -11
- package/console/dist/web/assets/app.js +40 -30
- package/core/dist/runtime-v2/activation/activation-types.d.ts +12 -2
- package/core/dist/runtime-v2/activation/activation-types.d.ts.map +1 -1
- package/core/dist/runtime-v2/activation/activation-types.js.map +1 -1
- package/core/dist/runtime-v2/activation/approval-queue.d.ts +3 -2
- package/core/dist/runtime-v2/activation/approval-queue.d.ts.map +1 -1
- package/core/dist/runtime-v2/activation/approval-queue.js +6 -4
- package/core/dist/runtime-v2/activation/approval-queue.js.map +1 -1
- package/core/dist/runtime-v2/activation/approval-review-guard.d.ts +26 -0
- package/core/dist/runtime-v2/activation/approval-review-guard.d.ts.map +1 -0
- package/core/dist/runtime-v2/activation/approval-review-guard.js +25 -0
- package/core/dist/runtime-v2/activation/approval-review-guard.js.map +1 -0
- package/core/dist/runtime-v2/activation/memory-approval-store.d.ts +6 -2
- package/core/dist/runtime-v2/activation/memory-approval-store.d.ts.map +1 -1
- package/core/dist/runtime-v2/activation/memory-approval-store.js +26 -2
- package/core/dist/runtime-v2/activation/memory-approval-store.js.map +1 -1
- package/core/dist/runtime-v2/activation/sqlite-approval-store.d.ts +6 -2
- package/core/dist/runtime-v2/activation/sqlite-approval-store.d.ts.map +1 -1
- package/core/dist/runtime-v2/activation/sqlite-approval-store.js +59 -2
- package/core/dist/runtime-v2/activation/sqlite-approval-store.js.map +1 -1
- package/core/dist/runtime-v2/diagnostician-association-shadow.d.ts +24 -0
- package/core/dist/runtime-v2/diagnostician-association-shadow.d.ts.map +1 -0
- package/core/dist/runtime-v2/diagnostician-association-shadow.js +84 -0
- package/core/dist/runtime-v2/diagnostician-association-shadow.js.map +1 -0
- package/core/dist/runtime-v2/diagnostician-association-validation.d.ts +18 -0
- package/core/dist/runtime-v2/diagnostician-association-validation.d.ts.map +1 -0
- package/core/dist/runtime-v2/diagnostician-association-validation.js +47 -0
- package/core/dist/runtime-v2/diagnostician-association-validation.js.map +1 -0
- package/core/dist/runtime-v2/diagnostician-output.d.ts +123 -0
- package/core/dist/runtime-v2/diagnostician-output.d.ts.map +1 -1
- package/core/dist/runtime-v2/diagnostician-output.js +41 -0
- package/core/dist/runtime-v2/diagnostician-output.js.map +1 -1
- package/core/dist/runtime-v2/index.d.ts +2 -0
- package/core/dist/runtime-v2/index.d.ts.map +1 -1
- package/core/dist/runtime-v2/index.js +1 -0
- package/core/dist/runtime-v2/index.js.map +1 -1
- package/core/dist/runtime-v2/internalization/diag-router-runner.d.ts +12 -1
- package/core/dist/runtime-v2/internalization/diag-router-runner.d.ts.map +1 -1
- package/core/dist/runtime-v2/internalization/diag-router-runner.js +50 -2
- package/core/dist/runtime-v2/internalization/diag-router-runner.js.map +1 -1
- package/core/dist/runtime-v2/internalization/router-context-evidence.d.ts +45 -0
- package/core/dist/runtime-v2/internalization/router-context-evidence.d.ts.map +1 -0
- package/core/dist/runtime-v2/internalization/router-context-evidence.js +64 -0
- package/core/dist/runtime-v2/internalization/router-context-evidence.js.map +1 -0
- package/core/dist/runtime-v2/signal-collector/types.d.ts +8 -0
- package/core/dist/runtime-v2/signal-collector/types.d.ts.map +1 -1
- package/core/dist/runtime-v2/signal-collector/types.js.map +1 -1
- package/core/package.json +1 -1
- package/package.json +2 -2
- package/pd-cli/dist/commands/config-doctor.js +1 -1
- package/pd-cli/dist/commands/config-doctor.js.map +1 -1
- package/pd-cli/dist/services/config-doctor.d.ts +2 -0
- package/pd-cli/dist/services/config-doctor.d.ts.map +1 -1
- package/pd-cli/dist/services/config-doctor.js +1 -0
- package/pd-cli/dist/services/config-doctor.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +462 -462
- package/plugin/dist/core/signal-collector-host.d.ts +9 -0
- package/plugin/dist/core/signal-health.d.ts +6 -0
- package/plugin/dist/core/trajectory.d.ts +8 -0
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/dist/rulehost-evidence.js +6 -6
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/package.json +2 -2
|
@@ -70,6 +70,8 @@ export declare class SignalCollectorHost {
|
|
|
70
70
|
private readonly cueFeedbackRecorder?;
|
|
71
71
|
/** rate limit 状态:sessionId → STRONG 计数桶 */
|
|
72
72
|
private readonly rateLimit;
|
|
73
|
+
/** 零命中「发现」调用的配额桶(每 host = 每 workspace,进程内) */
|
|
74
|
+
private discoveryBucket;
|
|
73
75
|
constructor(wctx: WorkspaceContext, options?: SignalCollectorHostOptions);
|
|
74
76
|
/**
|
|
75
77
|
* ★ 同步路径 (prompt.ts before_prompt_build 钩子里调用,绝不能阻塞)。
|
|
@@ -127,6 +129,13 @@ export declare class SignalCollectorHost {
|
|
|
127
129
|
* 虽在后台周期内,也复用同一惯例推迟到微任务,保证两种路径计数语义一致。
|
|
128
130
|
*/
|
|
129
131
|
private countStage2Invocation;
|
|
132
|
+
/**
|
|
133
|
+
* 零命中发现调用的配额判定(纯内存,同步安全)。
|
|
134
|
+
* 每 host 每小时最多 discoveryRateLimitPerHour 次;0/未设置 = 不限制。
|
|
135
|
+
*/
|
|
136
|
+
private takeDiscoveryBudget;
|
|
137
|
+
/** 被配额挡下的零命中发现计数(旁路,同 countStage2* 推迟到微任务)。 */
|
|
138
|
+
private countStage2DiscoverySkipped;
|
|
130
139
|
/**
|
|
131
140
|
* PRI-788 G4: stage1Strong 计数(旁路观测),刻意离开同步检测路径。
|
|
132
141
|
*
|
|
@@ -18,6 +18,12 @@ export interface SignalHealthState {
|
|
|
18
18
|
* 跨日归零;旧文件缺失按 0 读。
|
|
19
19
|
*/
|
|
20
20
|
stage2BatchSkipped: number;
|
|
21
|
+
/**
|
|
22
|
+
* 零命中「发现」调用被每小时配额挡下的次数(AUDIT-P2-03 性能整改)。
|
|
23
|
+
* 它回答「有多少普通消息本来要送去分类、被预算拦住了」——没有这个计数,
|
|
24
|
+
* 调用量下降就无法与「检测失效」区分。跨日归零;旧文件缺失按 0 读。
|
|
25
|
+
*/
|
|
26
|
+
stage2DiscoverySkipped: number;
|
|
21
27
|
/** 最近一次刷新的队列深度(非计数) */
|
|
22
28
|
pendingCount: number;
|
|
23
29
|
lastStage2SuccessAt: string | null;
|
|
@@ -39,6 +39,14 @@ export declare class TrajectoryDatabase {
|
|
|
39
39
|
*/
|
|
40
40
|
get isOpen(): boolean;
|
|
41
41
|
recordSession(input: TrajectorySessionInput): void;
|
|
42
|
+
/**
|
|
43
|
+
* Session upsert WITHOUT taking the file lock. `withWrite` serialises through a
|
|
44
|
+
* lock file (open+write+read+unlink) — ~6ms per acquisition on Windows, and it
|
|
45
|
+
* sits on the before_prompt_build critical path. Callers that already hold the
|
|
46
|
+
* lock (recordUserTurn / recordAssistantTurn) must reuse it instead of paying
|
|
47
|
+
* for a second acquisition.
|
|
48
|
+
*/
|
|
49
|
+
private upsertSessionUnlocked;
|
|
42
50
|
recordAssistantTurn(input: TrajectoryAssistantTurnInput): number;
|
|
43
51
|
recordUserTurn(input: TrajectoryUserTurnInput): number;
|
|
44
52
|
/**
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "2.2.
|
|
5
|
+
"version": "2.2.8",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function C(t,e=!1){let r=[];for(let n of t.split("/").filter(s=>s.length>0))n!=="."&&(n===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e&&r.push(".."):r.push(n));return r}function F(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let r=t.slice(2).split("/").filter(o=>o.length>0),n=r[0]??"",s=r[1]??"";return{kind:"unc",root:`unc:${n}/${s}`,segments:C(r.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ee(t,e,r){return t.length<e.length?!1:e.every((n,s)=>{let o=t[s]??"";return r?o.toLowerCase()===n.toLowerCase():o===n})}function Le(t,e,r){let n=0;for(;n<t.length&&n<e.length;){let o=t[n]??"",i=e[n]??"";if(!(r?o.toLowerCase()===i.toLowerCase():o===i))break;n++}return[...Array.from({length:t.length-n},()=>".."),...e.slice(n)].join("/")||"."}function te(t){let[e,r]=t.root.slice(4).split("/"),n=t.segments.join("/");return`//${e??""}/${r??""}${n?`/${n}`:""}`}function re(t,e,r){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return r;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ee(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?te(t):r:t.segments.slice(e.segments.length).join("/")||".";let n=[...e.segments];for(let o of r.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e.kind==="relative"&&n.push(".."):n.push(o));let s=e.kind==="drive"||e.kind==="unc";return ee(n,e.segments,s)?n.slice(e.segments.length).join("/")||".":Le(e.segments,n,s)}function ve(t,e){if(!t||typeof t!="string")return"";let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/");if(r.startsWith("<tool:")&&r.endsWith(">"))return r;let s=F(r),o=F(n);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=F(c),re(s,o,c)}return re(s,o,r)}function Ce(t,e){let r=t.file_path||t.path||t.file||t.target;if(typeof r=="string"&&r.length>0)return{value:r,isPath:!0};if(e.isBashTool){let n=String(t.command||t.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?{value:s[1],isPath:!0}:{value:n,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function we(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function ke(t){if(t.canonicalKind===void 0)return t;let e=we(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function w(t,e,r,n={}){let s=ke(n),o=Ce(e,{...s,toolName:t}),i=o.isPath?ve(o.value,r):o.value;return{toolName:t,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function ne(t){return typeof t=="string"&&X.has(t)}var k=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function se(t,e,r){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let _=a.canonicalKind;_==="read"||_==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):_==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:r}}var oe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(oe);var $={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($.calls);Object.freeze($);var De={version:2,history:$,facts:oe};Object.freeze(De);var Me=new Set(["__proto__","constructor","prototype"]),ie=3,Pe=5,je=new Set(["allow","block","propose_correction"]),Ue={valid:!0,errors:[]};function W(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function le(t){for(let e of Object.keys(t))if(Me.has(e))return!1;return!0}function Be(t){return t.length===0?Ue:{valid:!1,errors:t}}function H(t){return typeof t=="string"&&t.trim().length>0}function ae(t,e,r){let n=[];return W(t)?le(t)?((!Object.hasOwn(t,"caseId")||!H(t.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==r)&&n.push(`${e}.kind must be '${r}'`),(!Object.hasOwn(t,"toolName")||!H(t.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!W(t.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!je.has(t.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):r==="positive"&&t.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ce(t,e){let{fieldName:r,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${r} must be an array`),o;s&&t.length===0&&o.push(`${r} must contain at least 1 item`),n!==void 0&&t.length>n&&o.push(`${r} must contain at most ${n} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${r}[${i}] must be a string`);return o}function D(t){return Array.isArray(t)?`[${t.map(e=>D(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(r=>r!=="__proto__"&&r!=="constructor"&&r!=="prototype").sort().map(r=>`${JSON.stringify(r)}:${D(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){if(!W(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!le(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...ae(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!H(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let r=t.positiveCounterexamples;r.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),r.length>ie&&e.push(`positiveCounterexamples must contain at most ${ie} items, got ${r.length}`);for(let n=0;n<r.length;n++)e.push(...ae(r[n],`positiveCounterexamples[${n}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...ce(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Pe,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...ce(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let r=t.sourceNegativeCase,n=t.positiveCounterexamples,s=D({toolName:r.toolName,params:r.params,ruleContext:r.ruleContext});for(let o=0;o<n.length;o++){let i=n[o];i!==void 0&&D({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Be(e)}var Fe="OwnerEvidenceScopeError";function N(t,e){let r=new Error(e);return r.name=Fe,Object.assign(r,{ownerEvidenceScopeKind:t}),r}var Xe=new Set(["success","failure","blocked"]);function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function We(t){return typeof t=="string"&&Xe.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function ue(t,e,r){let{projectDir:n,toolSemantics:s}=r,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!We(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let _=i.paramsJson;if(typeof _!="string")return A(`row id=${i.id}: params_json must be a string`);let g;try{g=JSON.parse(_)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!$e(g))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:S}=w(c,g,n,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:S===""?null:S,paramsSummary:g,outcome:a})}return{status:"available",truncated:e,calls:o}}var He=3,Ye=5,Ke=100,_e=new Set(["__proto__","constructor","prototype"]);function M(t,e){try{return e()}catch(r){let n=r instanceof Error?r.message:String(r);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function Ge(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t){for(let e of Object.keys(t))if(_e.has(e))return!1;return!0}function ze(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>He)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(r=>!Number.isSafeInteger(r)||r<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function de(t,e){if(!t)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function Je(t,e,r){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Ge(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!qe(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:n,expectedDecision:r}}function Ve(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var Ze=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Qe(t){if(t.length<20)return!1;for(let e of Ze)if(e.test(t))return!0;return!1}function et(t,e){let r=[],n={};for(let s of Object.keys(t)){if(_e.has(s))continue;let o=t[s];if(typeof o!="string"){n[s]=o;continue}if(Ve(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",r.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(Qe(o)){n[s]="<redacted:secret>",r.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:r}}var P=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let r=M(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!r)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ze(e);let n=de(M(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>de(M(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[n,...s])if(m.sessionId!==r.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${r.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),_={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${r.id}`,`tool_call:${n.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,Ye),redactionNotes:o},g=Y(_);if(!g.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${g.errors.join("; ")} (ERR-069 fail loud)`);return _}buildSelectedCase(e,r,n){let{projectDir:s,redactionNotes:o}=n,i=Je(e,r,r==="negative"?"block":"allow"),c=et(i.params,s);o.push(...c.notes);let a=M(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Ke)),_=ue(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),g=w(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:_,facts:se(_,g.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import ht from"better-sqlite3";import p from"fs";import T from"path";import J from"crypto";import*as d from"fs";import*as fe from"path";var K=class extends Error{filePath;lockPath;constructor(e,r,n){super(e),this.name="LockAcquisitionError",this.filePath=r,this.lockPath=n}},tt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function me(t){try{return process.kill(t,0),!0}catch{return!1}}function pe(t,e){try{let r=fe.dirname(t);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let n=d.constants.O_WRONLY|d.constants.O_CREAT|d.constants.O_EXCL,s=d.openSync(t,n);return d.writeSync(s,String(e)),d.fsyncSync(s),d.closeSync(s),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}}function I(t){try{let e=d.readFileSync(t,"utf8"),r=parseInt(e.trim(),10);return Number.isNaN(r)?null:r}catch{return null}}function rt(t,e){try{I(t)===e&&d.unlinkSync(t)}catch{}}function nt(t,e){try{let r=d.statSync(t),n=I(t),s=Date.now()-r.mtimeMs>e,o=n===null||!me(n);if(s||o)try{return d.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function st(t,e,r){let n=Math.min(e*Math.pow(2,t),r),s=n*.2*Math.random();return Math.floor(n+s)}function ot(t){let e=Date.now()+t;for(;Date.now()<e;);}function it(t,e){let r=I(e),n=r!==null?me(r)?`alive (PID ${r})`:`dead (PID ${r})`:"unknown";return new K(`Failed to acquire lock for ${t}. Lock holder: ${n}.`,t,e)}function at(t,e,r){let n=t+e.lockSuffix;return pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:(nt(n,e.lockStaleMs),pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:null)}function ct(t,e={}){let r={...tt,...e},{pid:n}=process;for(let s=0;s<r.maxRetries;s++){let o=at(t,r,n);if(o)return o;if(s<r.maxRetries-1){let i=st(s,r.baseRetryDelayMs,r.maxRetryDelayMs);ot(i)}}throw it(t,t+r.lockSuffix)}function lt(t){rt(t.lockPath,t.pid)}function Ee(t,e,r={}){let n=ct(t,r);try{return e()}finally{lt(n)}}import*as O from"fs";var Te=3,ut=50;function j(t,e){let r=t+".tmp";O.writeFileSync(r,e,"utf8");let n;for(let s=0;s<Te;s++)try{O.renameSync(r,t);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Te-1){let c=ut*Math.pow(2,s),a=Date.now()+c,_=!1;for(;Date.now()<a;)if(!_&&Date.now()>=a-10){try{xe("fs").accessSync?.(r)}catch{}_=!0}}continue}break}try{O.unlinkSync(r)}catch{}throw n}import*as h from"path";var l=(...t)=>h.posix.join(...t);function dt(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function _t(t,e){return dt(t)?h.win32.join(t,e):t.startsWith("/")?h.posix.join(t,e):h.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},pt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function R(t,e){return _t(t,pt[e])}var ft={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},G=class extends Error{constructor(r,n,s){super(r,s);this.code=n;this.name="PdError",this.category=ft[n]??"execution_failed"}code;category};var x=class extends G{constructor(e,r){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",r),this.name="SampleNotFoundError"}};var mt=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function Et(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ge(t,e={}){let r=[],n=[...mt];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),Et(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:r}}import*as q from"path";import*as Se from"os";var Tt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],gt=q.join(Se.tmpdir(),".pd-test-quarantine");function St(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return Tt.some(r=>r.test(e))}function he(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!St(t))return t;let r=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;r.startsWith("_");)r=r.slice(1);for(;r.endsWith("_");)r=r.slice(0,-1);return q.join(gt,r)}var Rt=16*1024,Ot=5e3,yt=7;function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bt(t){return!ye(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function Nt(t){let e=ge(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function f(){return new Date().toISOString()}function y(t){return JSON.stringify(t??{})}function Re(t){try{return p.existsSync(t)?p.statSync(t).size:0}catch{return 0}}function At(t){return t.length>240?`${t.slice(0,237)}...`:t}function Oe(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function It(t){let e=[],r=!1;try{let n=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(n))e=n.filter(s=>typeof s=="string");else if(n!==null&&typeof n=="object"){let s=n;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),r=!0)}}}catch{e=[],r=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:r,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var U=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=he(T.resolve(e.workspaceDir)),this.stateDir=R(this.workspaceDir,"STATE_DIR"),this.dbPath=R(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=R(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=R(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Rt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??yt)*24*60*60*1e3),p.mkdirSync(this.stateDir,{recursive:!0}),p.mkdirSync(this.blobDir,{recursive:!0}),p.mkdirSync(this.exportDir,{recursive:!0}),this.db=new ht(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Ot)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let r=e.startedAt??f();this.withWrite(()=>{this.db.prepare(`
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
var xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,r)=>(typeof require<"u"?require:e)[r]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});function C(t,e=!1){let r=[];for(let n of t.split("/").filter(s=>s.length>0))n!=="."&&(n===".."?r.length>0&&r[r.length-1]!==".."?r.pop():e&&r.push(".."):r.push(n));return r}function F(t){let e=/^([a-zA-Z]):(?:\/|$)/.exec(t);if(e)return{kind:"drive",root:`drive:${(e[1]??"").toUpperCase()}`,segments:C(t.slice(2))};if(/^[a-zA-Z]:/.test(t))return{kind:"drive-relative",root:t.slice(0,2).toUpperCase(),segments:[]};if(/^\/\/[^/]+(?:\/|$)/.test(t)){let r=t.slice(2).split("/").filter(o=>o.length>0),n=r[0]??"",s=r[1]??"";return{kind:"unc",root:`unc:${n}/${s}`,segments:C(r.slice(2).join("/"))}}return t.startsWith("/")?{kind:"posix",root:"posix:/",segments:C(t)}:{kind:"relative",root:"",segments:C(t,!0)}}function ee(t,e,r){return t.length<e.length?!1:e.every((n,s)=>{let o=t[s]??"";return r?o.toLowerCase()===n.toLowerCase():o===n})}function Le(t,e,r){let n=0;for(;n<t.length&&n<e.length;){let o=t[n]??"",i=e[n]??"";if(!(r?o.toLowerCase()===i.toLowerCase():o===i))break;n++}return[...Array.from({length:t.length-n},()=>".."),...e.slice(n)].join("/")||"."}function te(t){let[e,r]=t.root.slice(4).split("/"),n=t.segments.join("/");return`//${e??""}/${r??""}${n?`/${n}`:""}`}function re(t,e,r){if(t.kind==="drive-relative"||t.kind==="unc"&&t.root.endsWith("/"))return r;if(t.kind!=="relative")return!(t.kind===e.kind&&(t.kind==="unc"?t.root.toLowerCase()===e.root.toLowerCase():t.root===e.root))||!ee(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?te(t):r:t.segments.slice(e.segments.length).join("/")||".";let n=[...e.segments];for(let o of r.split("/").filter(i=>i.length>0))o!=="."&&(o===".."?n.length>0&&n[n.length-1]!==".."?n.pop():e.kind==="relative"&&n.push(".."):n.push(o));let s=e.kind==="drive"||e.kind==="unc";return ee(n,e.segments,s)?n.slice(e.segments.length).join("/")||".":Le(e.segments,n,s)}function ve(t,e){if(!t||typeof t!="string")return"";let r=t.replace(/\\/g,"/"),n=e.replace(/\\/g,"/");if(r.startsWith("<tool:")&&r.endsWith(">"))return r;let s=F(r),o=F(n);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let c=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=F(c),re(s,o,c)}return re(s,o,r)}function Ce(t,e){let r=t.file_path||t.path||t.file||t.target;if(typeof r=="string"&&r.length>0)return{value:r,isPath:!0};if(e.isBashTool){let n=String(t.command||t.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?{value:s[1],isPath:!0}:{value:n,isPath:!1}}}return e.isWriteTool&&e.toolName?{value:`<tool:${e.toolName}>`,isPath:!0}:{value:null,isPath:!0}}function we(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function ke(t){if(t.canonicalKind===void 0)return t;let e=we(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function w(t,e,r,n={}){let s=ke(n),o=Ce(e,{...s,toolName:t}),i=o.isPath?ve(o.value,r):o.value;return{toolName:t,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var X=new Set(["read","search","write","execute","agent","other"]);function ne(t){return typeof t=="string"&&X.has(t)}var k=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function se(t,e,r){if(t.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=t;for(let a of c){let _=a.canonicalKind;_==="read"||_==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):_==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:r}}var oe={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(oe);var $={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze($.calls);Object.freeze($);var De={version:2,history:$,facts:oe};Object.freeze(De);var Me=new Set(["__proto__","constructor","prototype"]),ie=3,Pe=5,je=new Set(["allow","block","propose_correction"]),Ue={valid:!0,errors:[]};function W(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function le(t){for(let e of Object.keys(t))if(Me.has(e))return!1;return!0}function Be(t){return t.length===0?Ue:{valid:!1,errors:t}}function H(t){return typeof t=="string"&&t.trim().length>0}function ae(t,e,r){let n=[];return W(t)?le(t)?((!Object.hasOwn(t,"caseId")||!H(t.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(t,"kind")||t.kind!==r)&&n.push(`${e}.kind must be '${r}'`),(!Object.hasOwn(t,"toolName")||!H(t.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!W(t.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!je.has(t.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):r==="positive"&&t.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ce(t,e){let{fieldName:r,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(t))return o.push(`${r} must be an array`),o;s&&t.length===0&&o.push(`${r} must contain at least 1 item`),n!==void 0&&t.length>n&&o.push(`${r} must contain at most ${n} items, got ${t.length}`);for(let i=0;i<t.length;i++)typeof t[i]!="string"&&o.push(`${r}[${i}] must be a string`);return o}function D(t){return Array.isArray(t)?`[${t.map(e=>D(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(r=>r!=="__proto__"&&r!=="constructor"&&r!=="prototype").sort().map(r=>`${JSON.stringify(r)}:${D(t[r])}`).join(",")}}`:JSON.stringify(t)??"null"}function Y(t){if(!W(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!le(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...ae(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!H(t.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(t,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(t.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let r=t.positiveCounterexamples;r.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),r.length>ie&&e.push(`positiveCounterexamples must contain at most ${ie} items, got ${r.length}`);for(let n=0;n<r.length;n++)e.push(...ae(r[n],`positiveCounterexamples[${n}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...ce(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Pe,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...ce(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let r=t.sourceNegativeCase,n=t.positiveCounterexamples,s=D({toolName:r.toolName,params:r.params,ruleContext:r.ruleContext});for(let o=0;o<n.length;o++){let i=n[o];i!==void 0&&D({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return Be(e)}var Fe="OwnerEvidenceScopeError";function N(t,e){let r=new Error(e);return r.name=Fe,Object.assign(r,{ownerEvidenceScopeKind:t}),r}var Xe=new Set(["success","failure","blocked"]);function $e(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function We(t){return typeof t=="string"&&Xe.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function ue(t,e,r){let{projectDir:n,toolSemantics:s}=r,o=[];for(let i of t){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!We(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let _=i.paramsJson;if(typeof _!="string")return A(`row id=${i.id}: params_json must be a string`);let g;try{g=JSON.parse(_)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!$e(g))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:S}=w(c,g,n,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:S===""?null:S,paramsSummary:g,outcome:a})}return{status:"available",truncated:e,calls:o}}var He=3,Ye=5,Ke=100,_e=new Set(["__proto__","constructor","prototype"]);function M(t,e){try{return e()}catch(r){let n=r instanceof Error?r.message:String(r);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function Ge(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qe(t){for(let e of Object.keys(t))if(_e.has(e))return!1;return!0}function ze(t){if(!Number.isSafeInteger(t.sourceNegativeToolCallId)||t.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(t.positiveToolCallIds)||t.positiveToolCallIds.length===0||t.positiveToolCallIds.length>He)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[t.sourceNegativeToolCallId,...t.positiveToolCallIds];if(e.some(r=>!Number.isSafeInteger(r)||r<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function de(t,e){if(!t)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function Je(t,e,r){if(typeof t.toolName!="string"||t.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof t.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(t.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Ge(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!qe(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${t.id}`,kind:e,toolName:t.toolName,params:n,expectedDecision:r}}function Ve(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var Ze=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Qe(t){if(t.length<20)return!1;for(let e of Ze)if(e.test(t))return!0;return!1}function et(t,e){let r=[],n={};for(let s of Object.keys(t)){if(_e.has(s))continue;let o=t[s];if(typeof o!="string"){n[s]=o;continue}if(Ve(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",r.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(Qe(o)){n[s]="<redacted:secret>",r.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:r}}var P=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let r=M(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!r)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ze(e);let n=de(M(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>de(M(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[n,...s])if(m.sessionId!==r.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${m.id} session mismatch; all examples must belong to pain session ${r.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(m=>this.buildSelectedCase(m,"positive",i)),_={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${r.id}`,`tool_call:${n.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,Ye),redactionNotes:o},g=Y(_);if(!g.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${g.errors.join("; ")} (ERR-069 fail loud)`);return _}buildSelectedCase(e,r,n){let{projectDir:s,redactionNotes:o}=n,i=Je(e,r,r==="negative"?"block":"allow"),c=et(i.params,s);o.push(...c.notes);let a=M(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Ke)),_=ue(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),g=w(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:_,facts:se(_,g.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import ht from"better-sqlite3";import p from"fs";import T from"path";import J from"crypto";import*as d from"fs";import*as fe from"path";var K=class extends Error{filePath;lockPath;constructor(e,r,n){super(e),this.name="LockAcquisitionError",this.filePath=r,this.lockPath=n}},tt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function me(t){try{return process.kill(t,0),!0}catch{return!1}}function pe(t,e){try{let r=fe.dirname(t);d.existsSync(r)||d.mkdirSync(r,{recursive:!0});let n=d.constants.O_WRONLY|d.constants.O_CREAT|d.constants.O_EXCL,s=d.openSync(t,n);return d.writeSync(s,String(e)),d.fsyncSync(s),d.closeSync(s),!0}catch(r){if(r.code==="EEXIST")return!1;throw r}}function I(t){try{let e=d.readFileSync(t,"utf8"),r=parseInt(e.trim(),10);return Number.isNaN(r)?null:r}catch{return null}}function rt(t,e){try{I(t)===e&&d.unlinkSync(t)}catch{}}function nt(t,e){try{let r=d.statSync(t),n=I(t),s=Date.now()-r.mtimeMs>e,o=n===null||!me(n);if(s||o)try{return d.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function st(t,e,r){let n=Math.min(e*Math.pow(2,t),r),s=n*.2*Math.random();return Math.floor(n+s)}function ot(t){let e=Date.now()+t;for(;Date.now()<e;);}function it(t,e){let r=I(e),n=r!==null?me(r)?`alive (PID ${r})`:`dead (PID ${r})`:"unknown";return new K(`Failed to acquire lock for ${t}. Lock holder: ${n}.`,t,e)}function at(t,e,r){let n=t+e.lockSuffix;return pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:(nt(n,e.lockStaleMs),pe(n,r)&&I(n)===r?{lockPath:n,pid:r,acquiredAt:Date.now()}:null)}function ct(t,e={}){let r={...tt,...e},{pid:n}=process;for(let s=0;s<r.maxRetries;s++){let o=at(t,r,n);if(o)return o;if(s<r.maxRetries-1){let i=st(s,r.baseRetryDelayMs,r.maxRetryDelayMs);ot(i)}}throw it(t,t+r.lockSuffix)}function lt(t){rt(t.lockPath,t.pid)}function Ee(t,e,r={}){let n=ct(t,r);try{return e()}finally{lt(n)}}import*as O from"fs";var Te=3,ut=50;function j(t,e){let r=t+".tmp";O.writeFileSync(r,e,"utf8");let n;for(let s=0;s<Te;s++)try{O.renameSync(r,t);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Te-1){let c=ut*Math.pow(2,s),a=Date.now()+c,_=!1;for(;Date.now()<a;)if(!_&&Date.now()>=a-10){try{xe("fs").accessSync?.(r)}catch{}_=!0}}continue}break}try{O.unlinkSync(r)}catch{}throw n}import*as h from"path";var l=(...t)=>h.posix.join(...t);function dt(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function _t(t,e){return dt(t)?h.win32.join(t,e):t.startsWith("/")?h.posix.join(t,e):h.join(t,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},pt={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function R(t,e){return _t(t,pt[e])}var ft={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},G=class extends Error{constructor(r,n,s){super(r,s);this.code=n;this.name="PdError",this.category=ft[n]??"execution_failed"}code;category};var x=class extends G{constructor(e,r){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",r),this.name="SampleNotFoundError"}};var mt=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function Et(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function ge(t,e={}){let r=[],n=[...mt];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),Et(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),t.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),t.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),t.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),t.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(t.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),t.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:r}}import*as q from"path";import*as Se from"os";var Tt=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],gt=q.join(Se.tmpdir(),".pd-test-quarantine");function St(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return Tt.some(r=>r.test(e))}function he(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!St(t))return t;let r=t.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;r.startsWith("_");)r=r.slice(1);for(;r.endsWith("_");)r=r.slice(0,-1);return q.join(gt,r)}var Rt=16*1024,Ot=5e3,yt=7;function ye(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function bt(t){return!ye(t)||typeof t.id!="number"||typeof t.session_id!="string"?!1:Object.hasOwn(t,"source")&&Object.hasOwn(t,"score")&&Object.hasOwn(t,"reason")&&Object.hasOwn(t,"severity")&&Object.hasOwn(t,"origin")&&Object.hasOwn(t,"confidence")&&Object.hasOwn(t,"text")&&Object.hasOwn(t,"canonical_pain_id")&&Object.hasOwn(t,"runtime_task_id")&&Object.hasOwn(t,"created_at")}function Nt(t){let e=ge(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function f(){return new Date().toISOString()}function y(t){return JSON.stringify(t??{})}function Re(t){try{return p.existsSync(t)?p.statSync(t).size:0}catch{return 0}}function At(t){return t.length>240?`${t.slice(0,237)}...`:t}function Oe(t){return t.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function It(t){let e=[],r=!1;try{let n=JSON.parse(String(t.terms_json??"[]"));if(Array.isArray(n))e=n.filter(s=>typeof s=="string");else if(n!==null&&typeof n=="object"){let s=n;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),r=!0)}}}catch{e=[],r=!1}return{id:String(t.id),sessionId:String(t.session_id),userTurnRowid:Number(t.user_turn_rowid),occurrenceId:String(t.occurrence_id),excerpt:String(t.excerpt),terms:e,termsVerified:r,suggestedType:String(t.suggested_type),status:String(t.status),attempts:Number(t.attempts??0),createdAt:String(t.created_at),resolvedAt:t.resolved_at===null||t.resolved_at===void 0?null:String(t.resolved_at),resolution:t.resolution===null||t.resolution===void 0?null:String(t.resolution)}}var U=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=he(T.resolve(e.workspaceDir)),this.stateDir=R(this.workspaceDir,"STATE_DIR"),this.dbPath=R(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=R(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=R(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Rt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??yt)*24*60*60*1e3),p.mkdirSync(this.stateDir,{recursive:!0}),p.mkdirSync(this.blobDir,{recursive:!0}),p.mkdirSync(this.exportDir,{recursive:!0}),this.db=new ht(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??Ot)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let r=e.startedAt??f();this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,r)})}upsertSessionUnlocked(e,r){this.db.prepare(`
|
|
3
|
+
INSERT INTO sessions (session_id, started_at, updated_at)
|
|
4
|
+
VALUES (?, ?, ?)
|
|
5
|
+
ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
|
|
6
|
+
`).run(e,r,f())}recordAssistantTurn(e){let r=this.storeRawText("assistant",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??n);let s=this.db.prepare(`
|
|
7
7
|
INSERT INTO assistant_turns (
|
|
8
8
|
session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
|
|
9
9
|
empathy_signal_json, blob_ref, raw_excerpt, stop_reason, thinking_blocks_count, created_at
|
|
10
10
|
) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
11
|
-
`).run(e.sessionId,e.runId,e.provider,e.model,r.inlineText,e.sanitizedText,y(e.usageJson),y(e.empathySignalJson),r.blobRef,r.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){
|
|
11
|
+
`).run(e.sessionId,e.runId,e.provider,e.model,r.inlineText,e.sanitizedText,y(e.usageJson),y(e.empathySignalJson),r.blobRef,r.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){let r=this.storeRawText("user",e.rawText),n=e.createdAt??f();return this.withWrite(()=>{this.upsertSessionUnlocked(e.sessionId,e.createdAt??n);let s=this.db.prepare(`
|
|
12
12
|
INSERT INTO user_turns (
|
|
13
13
|
session_id, turn_index, raw_text, blob_ref, raw_excerpt,
|
|
14
14
|
correction_detected, correction_cue, references_assistant_turn_id, created_at
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "2.2.
|
|
5
|
+
"version": "2.2.8",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
package/plugin/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.8",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-principles-disciple",
|
|
3
|
-
"version": "1.145.
|
|
3
|
+
"version": "1.145.36",
|
|
4
4
|
"description": "Interactive CLI installer for Principles Disciple OpenClaw plugin",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
@@ -89,6 +89,6 @@
|
|
|
89
89
|
"directory": "packages/create-principles-disciple"
|
|
90
90
|
},
|
|
91
91
|
"pd": {
|
|
92
|
-
"bundledPluginVersion": "2.2.
|
|
92
|
+
"bundledPluginVersion": "2.2.8"
|
|
93
93
|
}
|
|
94
94
|
}
|