principles-disciple 3.0.1 → 3.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/bundle.js +443 -442
- package/dist/core/event-log.d.ts +13 -1
- package/dist/governance-audit.js +2 -2
- package/dist/hooks/llm-input-presence.d.ts +42 -0
- package/dist/hooks/prompt-presence-expectations.d.ts +6 -1
- package/dist/hooks/prompt-presence-lite.d.ts +53 -0
- package/dist/hooks/prompt-presence-measure.d.mts +1 -0
- package/dist/hooks/prompt-presence-registry.d.ts +150 -0
- package/dist/openclaw-sdk.d.ts +17 -0
- package/dist/openclaw.plugin.json +1 -1
- package/dist/rulehost-evidence.js +9 -9
- package/dist/types/event-types.d.ts +1 -1
- package/openclaw.plugin.json +1 -1
- package/package.json +4 -4
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PRI-1150 Path A: in-memory registry of frozen assembly snapshots for prompt
|
|
3
|
+
* presence forensics (design v2 §4, as amended by the owner's three revision
|
|
4
|
+
* constraints).
|
|
5
|
+
*
|
|
6
|
+
* Guarantees and honest limits:
|
|
7
|
+
* - Fully bounded: registry keys, snapshots per key, total snapshots, total
|
|
8
|
+
* body bytes and snapshot TTL are internal constants below; every eviction
|
|
9
|
+
* or expiry is counted and DEGRADES BINDING (history loss), never silently.
|
|
10
|
+
* - History loss is sticky for a key: once any snapshot of a key is dropped
|
|
11
|
+
* (TTL or capacity) the key can never regain unique-binding qualification —
|
|
12
|
+
* not by re-registration, not by remaining the only survivor. A bounded
|
|
13
|
+
* lossy-key marker set persists the fact after its entry is gone; it is NOT
|
|
14
|
+
* an unbounded tombstone table.
|
|
15
|
+
* - Late/duplicate/out-of-order llm_input callbacks are evaluated against the
|
|
16
|
+
* CURRENT live set under the same verdict rules; ordering is never assumed.
|
|
17
|
+
* - PD-internal assemblySeq numbers are diagnostic only; the official host
|
|
18
|
+
* event carries no assembly identity and none is claimed.
|
|
19
|
+
* - Memory only. Nothing here is persisted, logged or emitted with body text.
|
|
20
|
+
*/
|
|
21
|
+
/** Central bound constants (single authority; all limits observable via verdicts). */
|
|
22
|
+
export declare const PRESENCE_REGISTRY_LIMITS: {
|
|
23
|
+
/** Distinct runId+sessionId keys kept at once. Chosen above any plausible concurrent-run count on one host. */
|
|
24
|
+
readonly MAX_KEYS: 64;
|
|
25
|
+
/** Prompt builds (tool loops, compaction retries) retained per run. */
|
|
26
|
+
readonly MAX_SNAPSHOTS_PER_KEY: 8;
|
|
27
|
+
/** Global snapshot ceiling across all keys. */
|
|
28
|
+
readonly MAX_TOTAL_SNAPSHOTS: 128;
|
|
29
|
+
/** Aggregate bodyText bytes across the whole registry. */
|
|
30
|
+
readonly MAX_TOTAL_BODY_BYTES: number;
|
|
31
|
+
/** Snapshots older than this are expired (history loss — see below). */
|
|
32
|
+
readonly SNAPSHOT_TTL_MS: number;
|
|
33
|
+
/** Per-snapshot body-bytes ceiling; larger sets register as degraded. */
|
|
34
|
+
readonly MAX_SNAPSHOT_BODY_BYTES: number;
|
|
35
|
+
};
|
|
36
|
+
export interface RegisteredExpectation {
|
|
37
|
+
activationId: string;
|
|
38
|
+
bodyText: string;
|
|
39
|
+
bodyChars: number;
|
|
40
|
+
bodyComplete: boolean;
|
|
41
|
+
}
|
|
42
|
+
export interface PresenceSnapshot {
|
|
43
|
+
/** PD-internal per-key monotonic ordinal. Diagnostic only — the host event carries no assembly identity and none is claimed. */
|
|
44
|
+
assemblySeq: number;
|
|
45
|
+
frozenAtMs: number;
|
|
46
|
+
expectations: readonly RegisteredExpectation[];
|
|
47
|
+
/** Host-runtime-side overflow reported with this assembly (entries dropped at its own cap). */
|
|
48
|
+
overflowCount: number;
|
|
49
|
+
bodyBytes: number;
|
|
50
|
+
/**
|
|
51
|
+
* PRI-1150 review: present when this snapshot was registered DEGRADED —
|
|
52
|
+
* its expectation set exceeded the per-snapshot body cap, so the frozen
|
|
53
|
+
* set is empty and the observation can only be unknown:snapshot_over_limit.
|
|
54
|
+
* Distinguishes "over-limit" from "nothing injected" (empty_snapshot).
|
|
55
|
+
*/
|
|
56
|
+
degradedReason?: 'snapshot_over_limit';
|
|
57
|
+
/** Why this snapshot's expectation set is empty/degraded (design revision: distinct sources). */
|
|
58
|
+
emptyKind?: 'none_injected' | 'shared_field_absent' | 'target_removed_by_fallback' | 'generation_failed';
|
|
59
|
+
/** Canonical workspace identity this snapshot belongs to (existing path.resolve mechanism). */
|
|
60
|
+
workspaceId: string;
|
|
61
|
+
}
|
|
62
|
+
export type BindingStatus = 'no_key' | 'history_incomplete' | 'expired' | 'unique' | 'ambiguous' | 'empty_snapshot';
|
|
63
|
+
export type BindingVerdict = {
|
|
64
|
+
status: 'no_key';
|
|
65
|
+
} | {
|
|
66
|
+
status: 'history_incomplete';
|
|
67
|
+
} | {
|
|
68
|
+
status: 'expired';
|
|
69
|
+
} | {
|
|
70
|
+
status: 'empty_snapshot';
|
|
71
|
+
snapshot: PresenceSnapshot;
|
|
72
|
+
} | {
|
|
73
|
+
status: 'unique';
|
|
74
|
+
snapshot: PresenceSnapshot;
|
|
75
|
+
} | {
|
|
76
|
+
status: 'ambiguous';
|
|
77
|
+
liveSnapshots: number;
|
|
78
|
+
};
|
|
79
|
+
export declare class PromptPresenceRegistry {
|
|
80
|
+
private readonly now;
|
|
81
|
+
private readonly entries;
|
|
82
|
+
private totalSnapshots;
|
|
83
|
+
private totalBodyBytes;
|
|
84
|
+
private evictedCount;
|
|
85
|
+
private expiredCount;
|
|
86
|
+
/**
|
|
87
|
+
* PRI-1150 review (D2/D2b resolution, owner round-9 amendments): whole-key
|
|
88
|
+
* evictions keep a SCAR entry (snapshots=[], historyComplete=false) bounded
|
|
89
|
+
* by MAX_KEYS — the entry itself IS the loss marker; no tombstone table.
|
|
90
|
+
* When scars overflow (heavy churn beyond MAX_KEYS keys), the OLDEST scar is
|
|
91
|
+
* evicted: the registry then enters CAPACITY-EXHAUSTED mode (sticky, process
|
|
92
|
+
* scope) — entries created afterwards cannot prove candidate-history
|
|
93
|
+
* completeness, so they NEVER resolve unique (owner round-9 §一: no unique
|
|
94
|
+
* without provable complete history; degradation is process-scope, sticky
|
|
95
|
+
* until restart, and observable via stats). Entries that already held
|
|
96
|
+
* snapshots before exhaustion keep their provable continuity.
|
|
97
|
+
*/
|
|
98
|
+
private scarEvictions;
|
|
99
|
+
/** Sticky: true once any scar had to be evicted (bounded observation window begun). */
|
|
100
|
+
private capacityExhausted;
|
|
101
|
+
constructor(now?: () => number);
|
|
102
|
+
/** Observable counters (for events/diagnostics; no body content). */
|
|
103
|
+
stats(): {
|
|
104
|
+
keys: number;
|
|
105
|
+
snapshots: number;
|
|
106
|
+
totalBodyBytes: number;
|
|
107
|
+
evictedCount: number;
|
|
108
|
+
expiredCount: number;
|
|
109
|
+
scars: number;
|
|
110
|
+
scarEvictions: number;
|
|
111
|
+
capacityExhausted: boolean;
|
|
112
|
+
};
|
|
113
|
+
private keyOf;
|
|
114
|
+
private workspaceIdOf;
|
|
115
|
+
/** Drops TTL-expired snapshots; returns true when any expired (history loss). */
|
|
116
|
+
private sweepExpiredLocked;
|
|
117
|
+
/**
|
|
118
|
+
* PRI-1150 review (D2/D2b): whole-key evictions leave a bounded SCAR ENTRY
|
|
119
|
+
* (snapshots=[], historyComplete=false) — the entry itself carries the loss
|
|
120
|
+
* fact. Scar entries are bounded by MAX_KEYS; overflowing scars increment
|
|
121
|
+
* scarEvictions, flip the registry into CAPACITY-EXHAUSTED mode (sticky),
|
|
122
|
+
* and the affected keys become indistinguishable from brand-new keys —
|
|
123
|
+
* which post-exhaustion resolve conservatively (never unique).
|
|
124
|
+
*/
|
|
125
|
+
private pushScar;
|
|
126
|
+
/** Drops whole oldest entries / oldest snapshots until the global caps hold. */
|
|
127
|
+
private enforceGlobalCapsLocked;
|
|
128
|
+
registerAssemblySnapshot(params: {
|
|
129
|
+
runId: string;
|
|
130
|
+
sessionId: string;
|
|
131
|
+
expectations: readonly RegisteredExpectation[];
|
|
132
|
+
overflowCount?: number;
|
|
133
|
+
/** Canonical workspace identity (existing path.resolve mechanism); scopes the key. */
|
|
134
|
+
workspaceDir?: string;
|
|
135
|
+
/** Why this assembly's expectation set is empty/degraded (distinct sources, design revision). */
|
|
136
|
+
emptyKind?: PresenceSnapshot['emptyKind'];
|
|
137
|
+
}): {
|
|
138
|
+
registered: boolean;
|
|
139
|
+
degradedReason?: 'snapshot_over_limit';
|
|
140
|
+
assemblySeq?: number;
|
|
141
|
+
};
|
|
142
|
+
resolveBinding(params: {
|
|
143
|
+
runId: string;
|
|
144
|
+
sessionId: string;
|
|
145
|
+
workspaceDir?: string;
|
|
146
|
+
}): BindingVerdict;
|
|
147
|
+
/** Test/diagnostic reset (per-workspace isolation); never called in production paths. */
|
|
148
|
+
resetForTest(): void;
|
|
149
|
+
}
|
|
150
|
+
export declare function getPromptPresenceRegistry(): PromptPresenceRegistry;
|
package/dist/openclaw-sdk.d.ts
CHANGED
|
@@ -193,6 +193,23 @@ export interface PluginHookBeforePromptBuildEvent {
|
|
|
193
193
|
currentUserMessageId?: string;
|
|
194
194
|
messages: unknown[];
|
|
195
195
|
}
|
|
196
|
+
/**
|
|
197
|
+
* PRI-1150: local mirror of the official llm_input observation contract
|
|
198
|
+
* (release/2026.11.1 `PluginHookLlmInputEvent`). systemPrompt is the FULL
|
|
199
|
+
* assembled system-prompt text (post-guard/post-fallback); historyMessages is
|
|
200
|
+
* the host's isolated snapshot. Read-only observation surface.
|
|
201
|
+
*/
|
|
202
|
+
export interface PluginHookLlmInputEvent {
|
|
203
|
+
runId: string;
|
|
204
|
+
sessionId: string;
|
|
205
|
+
provider: string;
|
|
206
|
+
model: string;
|
|
207
|
+
systemPrompt?: string;
|
|
208
|
+
prompt: string;
|
|
209
|
+
historyMessages: unknown[];
|
|
210
|
+
imagesCount: number;
|
|
211
|
+
tools?: unknown[];
|
|
212
|
+
}
|
|
196
213
|
export interface PluginHookBeforePromptBuildResult {
|
|
197
214
|
systemPrompt?: string;
|
|
198
215
|
prependContext?: string;
|
|
@@ -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": "3.
|
|
5
|
+
"version": "3.1.1",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { createRequire } from 'module'; const require = createRequire(import.meta.url);
|
|
2
|
-
var Pe=(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/
|
|
2
|
+
var Pe=(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/activations/emergency-pause"}),Object.freeze({capabilityId:"owner_review_access",channel:"console",consoleRoute:"/api/activations/{activationId}/owner-review"})]);var oe="",je="|;&<>()";function L(t){return je.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+=L(c),s+=1;continue}if(i==="double"){if(c==='"')i="plain";else if(c==="\\"&&s+1<o&&'"\\$`'.includes(t[s+1]??"")){n+=L(t[s+1]??""),s+=2;continue}else n+=L(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+=L(t[s+1]??""),r=!0,s+=2;continue}if(c==="\r"||c===`
|
|
3
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||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 Ue=["verbose","debug"],Be=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...Ue,...t]),valued:new Set([...Be,...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 Xe(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("/")||".":Xe(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 $e(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function He(t){if(t.canonicalKind===void 0)return t;let e=$e(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function D(t,e,n,r={}){let s=He(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 Ye={version:2,history:Y,facts:pe};Object.freeze(Ye);var Ke=new Set(["__proto__","constructor","prototype"]),fe=3,Ge=5,qe=new Set(["allow","block","propose_correction"]),ze={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(Ke.has(e))return!1;return!0}function Ve(t){return t.length===0?ze:{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"||!qe.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:Ge,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 Ve(e)}var Je="OwnerEvidenceScopeError";function A(t,e){let n=new Error(e);return n.name=Je,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var Ze=new Set(["success","failure","blocked"]);function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function et(t){return typeof t=="string"&&Ze.has(t)}function I(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Te(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(!et(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 h;try{h=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Qe(h))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,h,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:h,outcome:a})}return{status:"available",truncated:e,calls:o}}var tt=3,nt=5,rt=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 st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ot(t){for(let e of Object.keys(t))if(ge.has(e))return!1;return!0}function it(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>tt)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 he(t,e){if(!t)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function at(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(!st(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!ot(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 ct(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var lt=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ut(t){if(t.length<20)return!1;for(let e of lt)if(e.test(t))return!0;return!1}function dt(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(ct(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ut(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)`);it(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!==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,nt),redactionNotes:o},h=q(d);if(!h.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${h.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=at(e,n,n==="negative"?"block":"allow"),c=dt(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,rt)),d=Te(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),h=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:de(d,h.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import Lt from"better-sqlite3";import f from"fs";import T 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}},pt={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 w(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function ft(t,e){try{w(t)===e&&p.unlinkSync(t)}catch{}}function _t(t,e){try{let n=p.statSync(t),r=w(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 mt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function Et(t){let e=Date.now()+t;for(;Date.now()<e;);}function Tt(t,e){let n=w(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)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(_t(r,e.lockStaleMs),Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function gt(t,e={}){let n={...pt,...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=mt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);Et(i)}}throw Tt(t,t+n.lockSuffix)}function St(t){ft(t.lockPath,t.pid)}function Re(t,e,n={}){let r=gt(t,n);try{return e()}finally{St(r)}}import*as R from"fs";var be=3,yt=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=yt*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Pe("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 Ot(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function Rt(t,e){return Ot(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")},bt={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 Rt(t,bt[e])}var Nt={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=Nt[r]??"execution_failed"}code;category};var v=class extends V{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var At=["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"],Ne={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT",project_dir:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",host_kind:"TEXT",created_at:"TEXT"}};for(let t of Object.values(Ne))Object.freeze(t);Object.freeze(Ne);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function X(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function J(t){if(!X(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(X(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}`);X(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"),J(t)}function Ae(t,e={}){let n=[],r=[...At];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"),X(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 Z from"path";import*as Ie from"os";var wt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],vt=Z.join(Ie.tmpdir(),".pd-test-quarantine");function xt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return wt.some(n=>n.test(e))}function we(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 Z.join(vt,n)}var kt=16*1024,Ct=5e3,Dt=7;function Le(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mt(t){return!Le(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=Ae(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 xe(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 F=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=we(T.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(`
|
|
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 Ue=["verbose","debug"],Be=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...Ue,...t]),valued:new Set([...Be,...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 Xe(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("/")||".":Xe(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 $e(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function He(t){if(t.canonicalKind===void 0)return t;let e=$e(t.canonicalKind);return{...t,isBashTool:t.isBashTool??e.isBashTool,isWriteTool:t.isWriteTool??e.isWriteTool}}function D(t,e,n,r={}){let s=He(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 Ye={version:2,history:Y,facts:pe};Object.freeze(Ye);var Ke=new Set(["__proto__","constructor","prototype"]),fe=3,Ge=5,qe=new Set(["allow","block","propose_correction"]),ze={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(Ke.has(e))return!1;return!0}function Ve(t){return t.length===0?ze:{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"||!qe.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:Ge,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 Ve(e)}var Je="OwnerEvidenceScopeError";function A(t,e){let n=new Error(e);return n.name=Je,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var Ze=new Set(["success","failure","blocked"]);function Qe(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function et(t){return typeof t=="string"&&Ze.has(t)}function I(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Te(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(!et(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 h;try{h=JSON.parse(d)}catch{return I(`row id=${i.id}: params_json is not valid JSON`)}if(!Qe(h))return I(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(c),{normalizedPath:g}=D(c,h,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:c,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:h,outcome:a})}return{status:"available",truncated:e,calls:o}}var tt=3,nt=5,rt=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 st(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ot(t){for(let e of Object.keys(t))if(ge.has(e))return!1;return!0}function it(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>tt)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 he(t,e){if(!t)throw A("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function at(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(!st(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!ot(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 ct(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var lt=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function ut(t){if(t.length<20)return!1;for(let e of lt)if(e.test(t))return!0;return!1}function dt(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(ct(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(ut(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)`);it(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!==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,nt),redactionNotes:o},h=q(d);if(!h.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${h.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=at(e,n,n==="negative"?"block":"allow"),c=dt(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,rt)),d=Te(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),h=D(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:de(d,h.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:m}}};import kt from"better-sqlite3";import f from"fs";import T 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}},pt={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 w(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function ft(t,e){try{w(t)===e&&p.unlinkSync(t)}catch{}}function _t(t,e){try{let n=p.statSync(t),r=w(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 mt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function Et(t){let e=Date.now()+t;for(;Date.now()<e;);}function Tt(t,e){let n=w(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)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(_t(r,e.lockStaleMs),Se(r,n)&&w(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function gt(t,e={}){let n={...pt,...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=mt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);Et(i)}}throw Tt(t,t+n.lockSuffix)}function St(t){ft(t.lockPath,t.pid)}function Re(t,e,n={}){let r=gt(t,n);try{return e()}finally{St(r)}}import*as R from"fs";var be=3,yt=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=yt*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Pe("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 Ot(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function Rt(t,e){return Ot(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")},bt={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 Rt(t,bt[e])}var Nt={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=Nt[r]??"execution_failed"}code;category};var x=class extends V{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var At=["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"],Ne={sessions:{session_id:"TEXT",started_at:"TEXT",updated_at:"TEXT"},tool_calls:{session_id:"TEXT",tool_name:"TEXT",outcome:"TEXT",duration_ms:"INTEGER",exit_code:"INTEGER",error_type:"TEXT",error_message:"TEXT",params_json:"TEXT",result_preview:"TEXT",created_at:"TEXT",project_dir:"TEXT"},pain_events:{session_id:"TEXT",source:"TEXT",score:"REAL",reason:"TEXT",severity:"TEXT",origin:"TEXT",confidence:"REAL",text:"TEXT",canonical_pain_id:"TEXT",runtime_task_id:"TEXT",host_kind:"TEXT",created_at:"TEXT"}};for(let t of Object.values(Ne))Object.freeze(t);Object.freeze(Ne);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function X(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function J(t){if(!X(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(X(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}`);X(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"),J(t)}function Ae(t,e={}){let n=[],r=[...At];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"),X(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 Z from"path";import*as Ie from"os";var wt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],xt=Z.join(Ie.tmpdir(),".pd-test-quarantine");function vt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return wt.some(n=>n.test(e))}function we(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!vt(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 Z.join(xt,n)}var Lt=16*1024,Ct=5e3,Dt=7;function ke(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Mt(t){return!ke(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=Ae(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function xe(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 ve(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 F=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=we(T.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??Lt,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 kt(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
|
|
@@ -104,7 +104,7 @@ var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
|
|
|
104
104
|
FROM tool_calls
|
|
105
105
|
WHERE id = ?
|
|
106
106
|
LIMIT 1
|
|
107
|
-
`).get(e);return!
|
|
107
|
+
`).get(e);return!ke(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 < ?
|
|
@@ -156,13 +156,13 @@ var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
|
|
|
156
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,n,r??null,s),!0)))throw new
|
|
159
|
+
`).run(e,n,r??null,s),!0)))throw new x(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
|
|
165
|
+
`).get(e);if(!i)throw new x(`${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
|
|
@@ -188,7 +188,7 @@ var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
|
|
|
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=T.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"?
|
|
191
|
+
`).all(e.approvedOnly?1:0),r=T.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"?ve(i):i,d=e.mode==="redacted"?ve(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
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=T.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 (
|
|
@@ -197,7 +197,7 @@ var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
|
|
|
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:
|
|
200
|
+
`).get();return{dbPath:this.dbPath,dbSizeBytes:xe(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 n of e.warnings)console.info(`[PD:TrajectoryDatabase] schema init warning: ${n}`);this.migrateSchema(),J(this.db)}importLegacyArtifacts(){this.importLegacySessions(),this.importLegacyEvents(),this.importLegacyEvolution()}migrateSchema(){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 (
|
|
@@ -260,8 +260,8 @@ var Pe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
|
|
|
260
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),"[]",h,_(),_())})}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,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=T.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=T.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+
|
|
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=T.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=T.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+xe(T.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 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=T.join(this.blobDir,i),a;try{a=f.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&r-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,f.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Re(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},
|
|
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=T.join(this.blobDir,i),a;try{a=f.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&r-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,f.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Re(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},v=class{static instances=new Map;static get(e,n={}){let r=T.resolve(e),s=this.instances.get(r);if(s)return s;let o=new F({workspaceDir:r,...n});return this.instances.set(r,o),o}static dispose(e){let n=T.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=T.resolve(e),o=this.instances.get(s);if(o)return n(o);let i=new F({workspaceDir:s,...r});try{return n(i)}finally{i.dispose()}}};var Bt=new Set(["__proto__","constructor","prototype"]);function Xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Ft(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(!Xt(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=Ft(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 Ce=["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"],k=["exec"],Wt=[...k],W=["sessions_spawn"],$t=[...N],Ht=[...N,...k,...W],Yt=[...Ce],Fn=new Set(Ce),Wn=new Set(N),$n=new Set(Wt),Hn=new Set(k),Yn=new Set(W),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(k,"execute"),...ee(N,"write"),...ee(W,"agent")]),te=Le(Kt);if(!te.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${te.errors.join("; ")}`);var De=te.registry;var ne=class extends U{constructor(e){super({source:v.get(e.workspaceDir),toolSemantics:De})}};export{ne as BehaviorExamplePackAssembler,v as RuleHostEvidenceRegistry};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RulePromotionEventData, GovernanceActionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimePromptActivationsInjectedEventData, RuleHostUnhealthyEventData, RuleHostSkippedEventData, TrajectoryObservabilityFailureEventData, ToolCallStats, ErrorStats, EmpathyEventStats, HookStats, DailyStats, } from '@principles/core/runtime';
|
|
1
|
+
export type { EventType, EventCategory, EventLogEntry, ToolCallEventData, PainSignalEventData, RulePromotionEventData, GovernanceActionEventData, HookExecutionEventData, GateBlockEventData, GateBypassEventData, EvolutionTaskEventData, EmpathyRollbackEventData, HeartbeatDiagnosisEventData, DiagnosisTaskEventData, DiagnosticianReportEventData, PrincipleCandidateEventData, RuleEnforcedEventData, RuleHostEvaluatedEventData, RuleHostBlockedEventData, RuleHostRequireApprovalEventData, RuleHostAutoCorrectProposedEventData, RuleHostAutoCorrectAppliedEventData, RuntimePromptActivationsInjectedEventData, PromptPresenceObservedEventData, RuleHostUnhealthyEventData, RuleHostSkippedEventData, TrajectoryObservabilityFailureEventData, ToolCallStats, ErrorStats, EmpathyEventStats, HookStats, DailyStats, } from '@principles/core/runtime';
|
|
2
2
|
export { createEmptyDailyStats, } from '@principles/core/runtime/types/event-types';
|
package/openclaw.plugin.json
CHANGED
|
@@ -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": "3.
|
|
5
|
+
"version": "3.1.1",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "3.
|
|
3
|
+
"version": "3.1.1",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -76,8 +76,8 @@
|
|
|
76
76
|
"compile-principles": "node scripts/compile-principles.mjs"
|
|
77
77
|
},
|
|
78
78
|
"devDependencies": {
|
|
79
|
-
"@principles/core": "^
|
|
80
|
-
"@principles/host-runtime": "^3.
|
|
79
|
+
"@principles/core": "^6.0.0",
|
|
80
|
+
"@principles/host-runtime": "^3.1.0",
|
|
81
81
|
"@types/better-sqlite3": "^9.6.0",
|
|
82
82
|
"@types/js-yaml": "^4.0.9",
|
|
83
83
|
"@types/micromatch": "^4.0.10",
|
|
@@ -109,5 +109,5 @@
|
|
|
109
109
|
"js-yaml": "^5.4.3",
|
|
110
110
|
"micromatch": "^4.0.8"
|
|
111
111
|
},
|
|
112
|
-
"gitHead": "
|
|
112
|
+
"gitHead": "1dd3b8e871ed88bac3cf2cc3a7dcaea9838271ba"
|
|
113
113
|
}
|