create-principles-disciple 1.145.4 → 1.145.5

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.
@@ -7,8 +7,10 @@
7
7
  *
8
8
  * Persistence contract:
9
9
  * - Atomic write: temp-file-then-rename (T-38-02)
10
- * - Cache invalidated after every write (D-05)
11
- * - 200-term hard cap enforced before any write (T-38-01)
10
+ * - Cache invalidated after every write (D-05), keyed by stateDir (EP-07)
11
+ * - MAX_CORRECTION_KEYWORDS is a budget, not a freeze: at the cap the least
12
+ * valuable llm-learned term is evicted so learning never stops (T-38-01).
13
+ * seed/user terms are never evicted — they are Owner-authored authority.
12
14
  */
13
15
  import type { CorrectionKeyword, CorrectionKeywordStore } from './correction-types.js';
14
16
  export declare function _resetCorrectionCueCache(): void;
@@ -19,13 +21,49 @@ export declare class CorrectionCueLearner {
19
21
  private readonly store;
20
22
  private readonly stateDir;
21
23
  constructor(stateDir: string);
22
- recordTruePositive(term: string): void;
23
- recordFalsePositive(term: string): void;
24
- add(keyword: Omit<CorrectionKeyword, 'addedAt'>): void;
25
- updateWeight(term: string, weight: number): void;
26
- remove(term: string): void;
24
+ recordTruePositive(term: string): boolean;
25
+ recordFalsePositive(term: string): boolean;
26
+ /**
27
+ * Insert a term, keeping the store inside MAX_CORRECTION_KEYWORDS.
28
+ *
29
+ * At/over the cap the least valuable `llm` terms leave first (see
30
+ * evictionTier), because throwing instead froze the learning channel
31
+ * permanently once the store filled up. The store may already be OVERSIZED
32
+ * from an older build; in that case each ADD also evicts up to
33
+ * MAX_EVICTIONS_PER_ADD terms, so the count converges downwards instead of
34
+ * being replaced one-for-one forever.
35
+ *
36
+ * @returns the evicted terms (empty when the store had room).
37
+ * @throws when there are too few evictable learned terms to preserve the cap
38
+ * (at 200) or to reduce the count (above 200), without touching Owner
39
+ * seed/user authority. A failed ADD leaves the store unchanged.
40
+ */
41
+ add(keyword: Omit<CorrectionKeyword, 'addedAt'>): string[];
42
+ /**
43
+ * Rank learned terms by what the store itself proves about them, worst first:
44
+ * proven noise (FP without any TP) leaves before never-confirmed terms, which
45
+ * leave before confirmed-useful ones. Within a tier, low weight then old
46
+ * addition loses. seed/user entries are Owner authority and never compete.
47
+ *
48
+ * @param count maximum number of terms to evict (bounded by the caller).
49
+ * @returns evicted terms in eviction order (fewer than `count` when the store
50
+ * holds fewer learned terms).
51
+ */
52
+ private evictLeastValuable;
53
+ /** @returns false when the term is not in the store (caller logs the skip). */
54
+ updateWeight(term: string, weight: number): boolean;
55
+ /** @returns false when the term is not in the store (caller logs the skip). */
56
+ remove(term: string): boolean;
57
+ /** Look a term up with the store's own identity rule (trim + lowercase). */
58
+ find(term: string): CorrectionKeyword | undefined;
27
59
  getStore(): CorrectionKeywordStore;
28
60
  getLastOptimizedAt(): string;
61
+ /**
62
+ * The store's only durable write: an atomic temp-file-then-rename of
63
+ * correction_keywords.json (T-38-02). A successful flush — not a SYSTEM log
64
+ * line — is what makes a mutation real; the audit trail emitted by
65
+ * KeywordOptimizationService is best-effort and may be missing.
66
+ */
29
67
  flush(): void;
30
68
  static get(stateDir: string): CorrectionCueLearner;
31
69
  }
@@ -132,6 +132,12 @@ export declare class SignalCollectorHost {
132
132
  occurrenceId: string;
133
133
  excerpt: string;
134
134
  terms?: readonly string[];
135
+ /**
136
+ * PRI-2053: `terms` 是否为「enqueue 时按 Stage1 快照筛出的 correction 类
137
+ * 命中词」。缺省 / false ⇒ 归因不可信(旧格式队列项),保守降级为无关键词
138
+ * 证据(rc-9:降级可见,不伪造)。
139
+ */
140
+ termsVerified?: boolean;
135
141
  }, classifier: SignalLlmClassifier): Promise<{
136
142
  disposition: 'confirmed' | 'rejected' | 'failed';
137
143
  detail: 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": "2.1.6",
5
+ "version": "2.1.7",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
@@ -1,5 +1,5 @@
1
1
  import { createRequire } from 'module'; const require = createRequire(import.meta.url);
2
- var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function U(r,e){if(!r||typeof r!="string")return"";let t=r.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s=t.length>=2&&t[1]===":",o=n.length>=2&&n[1]===":",i=t;s&&!o&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2)}`);let c=s&&o?i.slice(2):i,a=o?n.slice(2):n,d=c.startsWith("/"),f=a.startsWith("/");if(d&&f){let _=Q(a,c);return _.startsWith("../")?i:_}if(!d){let _=Ae(a,c),g=Q(a,_);return g.startsWith("../")?i:g}return i}function Q(r,e){let t=r.split("/").filter(a=>a.length>0),n=e.split("/").filter(a=>a.length>0),s=0;for(;s<t.length&&s<n.length&&t[s]===n[s];)s++;let o=t.length-s,i=n.slice(s),c=[];for(let a=0;a<o;a++)c.push("..");return c.push(...i),c.length===0?".":c.join("/")}function Ae(r,e){let t=r.split("/").filter(o=>o.length>0),n=e.split("/").filter(o=>o.length>0),s=[];for(let o of t)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);for(let o of n)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);return"/"+s.join("/")}function B(r,e={}){let t=r.file_path||r.path||r.file||r.target;if(typeof t=="string"&&t.length>0)return t;if(e.isBashTool){let n=String(r.command||r.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?s[1]:n}}return e.isWriteTool&&e.toolName?`<tool:${e.toolName}>`:null}function Ie(r){return{isBashTool:r==="execute",isWriteTool:r==="write"}}function ve(r){if(r.canonicalKind===void 0)return r;let e=Ie(r.canonicalKind);return{...r,isBashTool:r.isBashTool??e.isBashTool,isWriteTool:r.isWriteTool??e.isWriteTool}}function ee(r,e,t,n={}){let s=ve(n),o=B(e,{...s,toolName:r}),i=U(o,t);return{toolName:r,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var F=new Set(["read","search","write","execute","agent","other"]);function te(r){return typeof r=="string"&&F.has(r)}var w=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function re(r,e,t){if(r.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=r;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:t}}var ne={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ne);var X={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(X.calls);Object.freeze(X);var Le={version:2,history:X,facts:ne};Object.freeze(Le);var xe=new Set(["__proto__","constructor","prototype"]),se=3,Ce=5,we=new Set(["allow","block","propose_correction"]),ke={valid:!0,errors:[]};function W(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ae(r){for(let e of Object.keys(r))if(xe.has(e))return!1;return!0}function De(r){return r.length===0?ke:{valid:!1,errors:r}}function $(r){return typeof r=="string"&&r.trim().length>0}function oe(r,e,t){let n=[];return W(r)?ae(r)?((!Object.hasOwn(r,"caseId")||!$(r.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(r,"kind")||r.kind!==t)&&n.push(`${e}.kind must be '${t}'`),(!Object.hasOwn(r,"toolName")||!$(r.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(r,"params")||!W(r.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(r,"expectedDecision")||typeof r.expectedDecision!="string"||!we.has(r.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):t==="positive"&&r.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ie(r,e){let{fieldName:t,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(r))return o.push(`${t} must be an array`),o;s&&r.length===0&&o.push(`${t} must contain at least 1 item`),n!==void 0&&r.length>n&&o.push(`${t} must contain at most ${n} items, got ${r.length}`);for(let i=0;i<r.length;i++)typeof r[i]!="string"&&o.push(`${t}[${i}] must be a string`);return o}function H(r){if(!W(r))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ae(r))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(r,"sourceNegativeCase")?e.push(...oe(r.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(r,"ownerDesiredOutcome")||!$(r.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(r,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(r.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let t=r.positiveCounterexamples;t.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),t.length>se&&e.push(`positiveCounterexamples must contain at most ${se} items, got ${t.length}`);for(let n=0;n<t.length;n++)e.push(...oe(t[n],`positiveCounterexamples[${n}]`,"positive"))}return Object.hasOwn(r,"evidenceRefs")?e.push(...ie(r.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ce,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(r,"redactionNotes")?e.push(...ie(r.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),De(e)}var Me="OwnerEvidenceScopeError";function y(r,e){let t=new Error(e);return t.name=Me,Object.assign(t,{ownerEvidenceScopeKind:r}),t}var Pe=new Set(["success","failure","blocked"]);function je(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ue(r){return typeof r=="string"&&Pe.has(r)}function A(r){return{status:"unavailable",unavailableReason:r,truncated:!1,calls:[]}}function ce(r,e,t){let{projectDir:n,toolSemantics:s}=t,o=[];for(let i of r){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!Ue(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return A(`row id=${i.id}: params_json must be a string`);let f;try{f=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!je(f))return A(`row id=${i.id}: params_json must parse to a non-array object`);let _=s.resolve(c),g=B(f,{isBashTool:_==="execute",isWriteTool:_==="write",toolName:c}),C=U(g,n);o.push({sequenceId:i.id,toolName:c,canonicalKind:_,normalizedPath:C===""?null:C,paramsSummary:f,outcome:a})}return{status:"available",truncated:e,calls:o}}var Be=3,Fe=5,Xe=100,ue=new Set(["__proto__","constructor","prototype"]);function k(r,e){try{return e()}catch(t){let n=t instanceof Error?t.message:String(t);throw y("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${r} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function We(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function $e(r){for(let e of Object.keys(r))if(ue.has(e))return!1;return!0}function He(r){if(!Number.isSafeInteger(r.sourceNegativeToolCallId)||r.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(r.positiveToolCallIds)||r.positiveToolCallIds.length===0||r.positiveToolCallIds.length>Be)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[r.sourceNegativeToolCallId,...r.positiveToolCallIds];if(e.some(t=>!Number.isSafeInteger(t)||t<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function le(r,e){if(!r)throw y("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return r}function Ye(r,e,t){if(typeof r.toolName!="string"||r.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof r.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(r.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!We(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!$e(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${r.id}`,kind:e,toolName:r.toolName,params:n,expectedDecision:t}}function Ke(r){return r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)}var Ge=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function qe(r){if(r.length<20)return!1;for(let e of Ge)if(e.test(r))return!0;return!1}function ze(r,e){let t=[],n={};for(let s of Object.keys(r)){if(ue.has(s))continue;let o=r[s];if(typeof o!="string"){n[s]=o;continue}if(Ke(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(qe(o)){n[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:t}}var D=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=k(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!t)throw y("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);He(e);let n=le(k(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(_=>le(k(`evidence row read for id=${_}`,()=>this.db.getRuleHostEvidenceRow(_)),_));for(let _ of[n,...s])if(_.sessionId!==t.sessionId)throw y("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${_.id} session mismatch; all examples must belong to pain session ${t.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(_=>this.buildSelectedCase(_,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${t.id}`,`tool_call:${n.id}`,...s.map(_=>`tool_call:${_.id}`)].slice(0,Fe),redactionNotes:o},f=H(d);if(!f.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${f.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,n){let{projectDir:s,redactionNotes:o}=n,i=Ye(e,t,t==="negative"?"block":"allow"),c=ze(i.params,s);o.push(...c.notes);let a=k(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Xe)),d=ce(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),f=ee(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),_={version:2,history:d,facts:re(d,f.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:_}}};import mt from"better-sqlite3";import E from"fs";import S from"path";import z from"crypto";import*as p from"fs";import*as _e from"path";var Y=class extends Error{filePath;lockPath;constructor(e,t,n){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=n}},Je={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function pe(r){try{return process.kill(r,0),!0}catch{return!1}}function de(r,e){try{let t=_e.dirname(r);p.existsSync(t)||p.mkdirSync(t,{recursive:!0});let n=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(r,n);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}}function I(r){try{let e=p.readFileSync(r,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function Ve(r,e){try{I(r)===e&&p.unlinkSync(r)}catch{}}function Ze(r,e){try{let t=p.statSync(r),n=I(r),s=Date.now()-t.mtimeMs>e,o=n===null||!pe(n);if(s||o)try{return p.unlinkSync(r),!0}catch{return!1}return!1}catch{return!1}}function Qe(r,e,t){let n=Math.min(e*Math.pow(2,r),t),s=n*.2*Math.random();return Math.floor(n+s)}function et(r){let e=Date.now()+r;for(;Date.now()<e;);}function tt(r,e){let t=I(e),n=t!==null?pe(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new Y(`Failed to acquire lock for ${r}. Lock holder: ${n}.`,r,e)}function rt(r,e,t){let n=r+e.lockSuffix;return de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:(Ze(n,e.lockStaleMs),de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:null)}function nt(r,e={}){let t={...Je,...e},{pid:n}=process;for(let s=0;s<t.maxRetries;s++){let o=rt(r,t,n);if(o)return o;if(s<t.maxRetries-1){let i=Qe(s,t.baseRetryDelayMs,t.maxRetryDelayMs);et(i)}}throw tt(r,r+t.lockSuffix)}function st(r){Ve(r.lockPath,r.pid)}function Ee(r,e,t={}){let n=nt(r,t);try{return e()}finally{st(n)}}import*as R from"fs";var me=3,ot=50;function M(r,e){let t=r+".tmp";R.writeFileSync(t,e,"utf8");let n;for(let s=0;s<me;s++)try{R.renameSync(t,r);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<me-1){let c=ot*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{ye("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{R.unlinkSync(t)}catch{}throw n}import*as h from"path";var l=(...r)=>h.posix.join(...r);function it(r){return/^[A-Za-z]:[\\/]/.test(r)||r.startsWith("\\\\")}function at(r,e){return it(r)?h.win32.join(r,e):r.startsWith("/")?h.posix.join(r,e):h.join(r,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},ct={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(r,e){return at(r,ct[e])}var lt={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},K=class extends Error{constructor(t,n,s){super(t,s);this.code=n;this.name="PdError",this.category=lt[n]??"execution_failed"}code;category};var v=class extends K{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var ut=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function T(r){let e=r instanceof Error?r.message:String(r);return e.includes("duplicate column name")||e.includes("no column named")}function dt(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Te(r,e={}){let t=[],n=[...ut];r.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),r.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{r.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!T(s))throw s}if(r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)"),r.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),dt(r,"evolution_tasks")){try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!T(s))throw s}}return r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),r.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),r.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(r.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),r.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),r.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:t}}import*as G from"path";import*as fe from"os";var _t=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],pt=G.join(fe.tmpdir(),".pd-test-quarantine");function Et(r){if(!r)return!1;let e=r.replace(/\\/g,"/");return _t.some(t=>t.test(e))}function ge(r){if(!r||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Et(r))return r;let t=r.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;t.startsWith("_");)t=t.slice(1);for(;t.endsWith("_");)t=t.slice(0,-1);return G.join(pt,t)}var Tt=16*1024,ft=5e3,gt=7;function Oe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function St(r){return!Oe(r)||typeof r.id!="number"||typeof r.session_id!="string"?!1:Object.hasOwn(r,"source")&&Object.hasOwn(r,"score")&&Object.hasOwn(r,"reason")&&Object.hasOwn(r,"severity")&&Object.hasOwn(r,"origin")&&Object.hasOwn(r,"confidence")&&Object.hasOwn(r,"text")&&Object.hasOwn(r,"canonical_pain_id")&&Object.hasOwn(r,"runtime_task_id")&&Object.hasOwn(r,"created_at")}function ht(r){let e=Te(r,{views:!0});return{tables:e.tables,warnings:e.warnings}}function m(){return new Date().toISOString()}function N(r){return JSON.stringify(r??{})}function Se(r){try{return E.existsSync(r)?E.statSync(r).size:0}catch{return 0}}function Ot(r){return r.length>240?`${r.slice(0,237)}...`:r}function he(r){return r.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function Rt(r){let e=[];try{let t=JSON.parse(String(r.terms_json??"[]"));Array.isArray(t)&&(e=t.filter(n=>typeof n=="string"))}catch{e=[]}return{id:String(r.id),sessionId:String(r.session_id),userTurnRowid:Number(r.user_turn_rowid),occurrenceId:String(r.occurrence_id),excerpt:String(r.excerpt),terms:e,suggestedType:String(r.suggested_type),status:String(r.status),attempts:Number(r.attempts??0),createdAt:String(r.created_at),resolvedAt:r.resolved_at===null||r.resolved_at===void 0?null:String(r.resolved_at),resolution:r.resolution===null||r.resolution===void 0?null:String(r.resolution)}}var P=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=ge(S.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Tt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??gt)*24*60*60*1e3),E.mkdirSync(this.stateDir,{recursive:!0}),E.mkdirSync(this.blobDir,{recursive:!0}),E.mkdirSync(this.exportDir,{recursive:!0}),this.db=new mt(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??ft)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let t=e.startedAt??m();this.withWrite(()=>{this.db.prepare(`
2
+ var Ne=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(typeof require<"u"?require:e)[t]}):r)(function(r){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+r+'" is not supported')});function U(r,e){if(!r||typeof r!="string")return"";let t=r.replace(/\\/g,"/"),n=e.replace(/\\/g,"/"),s=t.length>=2&&t[1]===":",o=n.length>=2&&n[1]===":",i=t;s&&!o&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2)}`);let c=s&&o?i.slice(2):i,a=o?n.slice(2):n,d=c.startsWith("/"),f=a.startsWith("/");if(d&&f){let _=Q(a,c);return _.startsWith("../")?i:_}if(!d){let _=Ae(a,c),g=Q(a,_);return g.startsWith("../")?i:g}return i}function Q(r,e){let t=r.split("/").filter(a=>a.length>0),n=e.split("/").filter(a=>a.length>0),s=0;for(;s<t.length&&s<n.length&&t[s]===n[s];)s++;let o=t.length-s,i=n.slice(s),c=[];for(let a=0;a<o;a++)c.push("..");return c.push(...i),c.length===0?".":c.join("/")}function Ae(r,e){let t=r.split("/").filter(o=>o.length>0),n=e.split("/").filter(o=>o.length>0),s=[];for(let o of t)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);for(let o of n)o===".."?s.length>0&&s.pop():o!=="."&&s.push(o);return"/"+s.join("/")}function B(r,e={}){let t=r.file_path||r.path||r.file||r.target;if(typeof t=="string"&&t.length>0)return t;if(e.isBashTool){let n=String(r.command||r.args||"");if(n){let s=/(?:>|>>|sed\s+-i|rm|mv|mkdir|touch|cp)\s+(?:-[a-zA-Z]+\s+)*([^\s;&|<>]+)/.exec(n);return s&&s[1]?s[1]:n}}return e.isWriteTool&&e.toolName?`<tool:${e.toolName}>`:null}function Ie(r){return{isBashTool:r==="execute",isWriteTool:r==="write"}}function ve(r){if(r.canonicalKind===void 0)return r;let e=Ie(r.canonicalKind);return{...r,isBashTool:r.isBashTool??e.isBashTool,isWriteTool:r.isWriteTool??e.isWriteTool}}function ee(r,e,t,n={}){let s=ve(n),o=B(e,{...s,toolName:r}),i=U(o,t);return{toolName:r,normalizedPath:i,paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var F=new Set(["read","search","write","execute","agent","other"]);function te(r){return typeof r=="string"&&F.has(r)}var w=Object.freeze({read:"read",read_file:"read",read_many_files:"read",grep:"search",grep_search:"search",search_file_content:"search",glob:"search",write:"write",write_file:"write",edit:"write",edit_file:"write",replace:"write",apply_patch:"write",bash:"execute",exec:"execute",execute:"execute",run_shell_command:"execute",execute_command:"execute",run_script:"execute",code_interpreter:"execute",sessions_spawn:"agent"});function re(r,e,t){if(r.status==="unavailable")return{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};let n=0,s=0,o=new Set,i=e===null?"unknown":"no",{calls:c}=r;for(let a of c){let d=a.canonicalKind;d==="read"||d==="search"?(n++,e!==null&&a.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof a.normalizedPath=="string"&&o.add(a.normalizedPath))}return{priorReadOfTarget:i,readCount:n,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:t}}var ne={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(ne);var X={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(X.calls);Object.freeze(X);var Le={version:2,history:X,facts:ne};Object.freeze(Le);var xe=new Set(["__proto__","constructor","prototype"]),se=3,Ce=5,we=new Set(["allow","block","propose_correction"]),ke={valid:!0,errors:[]};function W(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function ae(r){for(let e of Object.keys(r))if(xe.has(e))return!1;return!0}function De(r){return r.length===0?ke:{valid:!1,errors:r}}function $(r){return typeof r=="string"&&r.trim().length>0}function oe(r,e,t){let n=[];return W(r)?ae(r)?((!Object.hasOwn(r,"caseId")||!$(r.caseId))&&n.push(`${e}.caseId must be a non-empty string`),(!Object.hasOwn(r,"kind")||r.kind!==t)&&n.push(`${e}.kind must be '${t}'`),(!Object.hasOwn(r,"toolName")||!$(r.toolName))&&n.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(r,"params")||!W(r.params))&&n.push(`${e}.params must be a plain object`),!Object.hasOwn(r,"expectedDecision")||typeof r.expectedDecision!="string"||!we.has(r.expectedDecision)?n.push(`${e}.expectedDecision must be one of allow|block|propose_correction`):t==="positive"&&r.expectedDecision!=="allow"&&n.push(`${e}: positive cases must expect allow`),n):(n.push(`${e} must not carry prototype-pollution keys`),n):(n.push(`${e} must be a plain object`),n)}function ie(r,e){let{fieldName:t,maxLength:n,requireNonEmpty:s}=e,o=[];if(!Array.isArray(r))return o.push(`${t} must be an array`),o;s&&r.length===0&&o.push(`${t} must contain at least 1 item`),n!==void 0&&r.length>n&&o.push(`${t} must contain at most ${n} items, got ${r.length}`);for(let i=0;i<r.length;i++)typeof r[i]!="string"&&o.push(`${t}[${i}] must be a string`);return o}function H(r){if(!W(r))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ae(r))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(r,"sourceNegativeCase")?e.push(...oe(r.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(r,"ownerDesiredOutcome")||!$(r.ownerDesiredOutcome))&&e.push("ownerDesiredOutcome must be a non-empty string"),!Object.hasOwn(r,"positiveCounterexamples"))e.push("positiveCounterexamples is required");else if(!Array.isArray(r.positiveCounterexamples))e.push("positiveCounterexamples must be an array");else{let t=r.positiveCounterexamples;t.length===0&&e.push("positiveCounterexamples must contain at least 1 item"),t.length>se&&e.push(`positiveCounterexamples must contain at most ${se} items, got ${t.length}`);for(let n=0;n<t.length;n++)e.push(...oe(t[n],`positiveCounterexamples[${n}]`,"positive"))}return Object.hasOwn(r,"evidenceRefs")?e.push(...ie(r.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Ce,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(r,"redactionNotes")?e.push(...ie(r.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),De(e)}var Me="OwnerEvidenceScopeError";function N(r,e){let t=new Error(e);return t.name=Me,Object.assign(t,{ownerEvidenceScopeKind:r}),t}var Pe=new Set(["success","failure","blocked"]);function je(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ue(r){return typeof r=="string"&&Pe.has(r)}function A(r){return{status:"unavailable",unavailableReason:r,truncated:!1,calls:[]}}function ce(r,e,t){let{projectDir:n,toolSemantics:s}=t,o=[];for(let i of r){let{toolName:c}=i;if(typeof c!="string"||c.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:a}=i;if(!Ue(a))return A(`row id=${i.id}: outcome "${i.outcome}" is not a valid RuleToolOutcome`);let d=i.paramsJson;if(typeof d!="string")return A(`row id=${i.id}: params_json must be a string`);let f;try{f=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!je(f))return A(`row id=${i.id}: params_json must parse to a non-array object`);let _=s.resolve(c),g=B(f,{isBashTool:_==="execute",isWriteTool:_==="write",toolName:c}),C=U(g,n);o.push({sequenceId:i.id,toolName:c,canonicalKind:_,normalizedPath:C===""?null:C,paramsSummary:f,outcome:a})}return{status:"available",truncated:e,calls:o}}var Be=3,Fe=5,Xe=100,ue=new Set(["__proto__","constructor","prototype"]);function k(r,e){try{return e()}catch(t){let n=t instanceof Error?t.message:String(t);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${r} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${n}`)}}function We(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function $e(r){for(let e of Object.keys(r))if(ue.has(e))return!1;return!0}function He(r){if(!Number.isSafeInteger(r.sourceNegativeToolCallId)||r.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(r.positiveToolCallIds)||r.positiveToolCallIds.length===0||r.positiveToolCallIds.length>Be)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let e=[r.sourceNegativeToolCallId,...r.positiveToolCallIds];if(e.some(t=>!Number.isSafeInteger(t)||t<=0)||new Set(e).size!==e.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function le(r,e){if(!r)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return r}function Ye(r,e,t){if(typeof r.toolName!="string"||r.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof r.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must be a string (rc-9 fail loud)`);let n;try{n=JSON.parse(r.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!We(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!$e(n))throw new Error(`[BehaviorExamplePackAssembler] row id=${r.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${e}-${r.id}`,kind:e,toolName:r.toolName,params:n,expectedDecision:t}}function Ke(r){return r.startsWith("/")||/^[A-Za-z]:[\\/]/.test(r)}var Ge=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function qe(r){if(r.length<20)return!1;for(let e of Ge)if(e.test(r))return!0;return!1}function ze(r,e){let t=[],n={};for(let s of Object.keys(r)){if(ue.has(s))continue;let o=r[s];if(typeof o!="string"){n[s]=o;continue}if(Ke(o)&&!o.startsWith(e)){n[s]="<redacted:absolute-path>",t.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(qe(o)){n[s]="<redacted:secret>",t.push(`redacted possible secret in field "${s}"`);continue}n[s]=o}return{redacted:n,notes:t}}var D=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let t=k(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!t)throw N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);He(e);let n=le(k(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(_=>le(k(`evidence row read for id=${_}`,()=>this.db.getRuleHostEvidenceRow(_)),_));for(let _ of[n,...s])if(_.sessionId!==t.sessionId)throw N("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${_.id} session mismatch; all examples must belong to pain session ${t.sessionId}`);let o=[],i={projectDir:e.projectDir,redactionNotes:o},c=this.buildSelectedCase(n,"negative",i),a=s.map(_=>this.buildSelectedCase(_,"positive",i)),d={sourceNegativeCase:c,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:a,evidenceRefs:[`pain:${t.id}`,`tool_call:${n.id}`,...s.map(_=>`tool_call:${_.id}`)].slice(0,Fe),redactionNotes:o},f=H(d);if(!f.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${f.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,t,n){let{projectDir:s,redactionNotes:o}=n,i=Ye(e,t,t==="negative"?"block":"allow"),c=ze(i.params,s);o.push(...c.notes);let a=k(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,Xe)),d=ce(a.rows,a.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),f=ee(e.toolName,c.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),_={version:2,history:d,facts:re(d,f.normalizedPath||null,null)};return{...i,params:c.redacted,ruleContext:_}}};import mt from"better-sqlite3";import E from"fs";import S from"path";import z from"crypto";import*as p from"fs";import*as _e from"path";var Y=class extends Error{filePath;lockPath;constructor(e,t,n){super(e),this.name="LockAcquisitionError",this.filePath=t,this.lockPath=n}},Ve={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function pe(r){try{return process.kill(r,0),!0}catch{return!1}}function de(r,e){try{let t=_e.dirname(r);p.existsSync(t)||p.mkdirSync(t,{recursive:!0});let n=p.constants.O_WRONLY|p.constants.O_CREAT|p.constants.O_EXCL,s=p.openSync(r,n);return p.writeSync(s,String(e)),p.fsyncSync(s),p.closeSync(s),!0}catch(t){if(t.code==="EEXIST")return!1;throw t}}function I(r){try{let e=p.readFileSync(r,"utf8"),t=parseInt(e.trim(),10);return Number.isNaN(t)?null:t}catch{return null}}function Je(r,e){try{I(r)===e&&p.unlinkSync(r)}catch{}}function Ze(r,e){try{let t=p.statSync(r),n=I(r),s=Date.now()-t.mtimeMs>e,o=n===null||!pe(n);if(s||o)try{return p.unlinkSync(r),!0}catch{return!1}return!1}catch{return!1}}function Qe(r,e,t){let n=Math.min(e*Math.pow(2,r),t),s=n*.2*Math.random();return Math.floor(n+s)}function et(r){let e=Date.now()+r;for(;Date.now()<e;);}function tt(r,e){let t=I(e),n=t!==null?pe(t)?`alive (PID ${t})`:`dead (PID ${t})`:"unknown";return new Y(`Failed to acquire lock for ${r}. Lock holder: ${n}.`,r,e)}function rt(r,e,t){let n=r+e.lockSuffix;return de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:(Ze(n,e.lockStaleMs),de(n,t)&&I(n)===t?{lockPath:n,pid:t,acquiredAt:Date.now()}:null)}function nt(r,e={}){let t={...Ve,...e},{pid:n}=process;for(let s=0;s<t.maxRetries;s++){let o=rt(r,t,n);if(o)return o;if(s<t.maxRetries-1){let i=Qe(s,t.baseRetryDelayMs,t.maxRetryDelayMs);et(i)}}throw tt(r,r+t.lockSuffix)}function st(r){Je(r.lockPath,r.pid)}function Ee(r,e,t={}){let n=nt(r,t);try{return e()}finally{st(n)}}import*as R from"fs";var me=3,ot=50;function M(r,e){let t=r+".tmp";R.writeFileSync(t,e,"utf8");let n;for(let s=0;s<me;s++)try{R.renameSync(t,r);return}catch(o){n=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<me-1){let c=ot*Math.pow(2,s),a=Date.now()+c,d=!1;for(;Date.now()<a;)if(!d&&Date.now()>=a-10){try{Ne("fs").accessSync?.(t)}catch{}d=!0}}continue}break}try{R.unlinkSync(t)}catch{}throw n}import*as h from"path";var l=(...r)=>h.posix.join(...r);function it(r){return/^[A-Za-z]:[\\/]/.test(r)||r.startsWith("\\\\")}function at(r,e){return it(r)?h.win32.join(r,e):r.startsWith("/")?h.posix.join(r,e):h.join(r,e)}var u={IDENTITY:".principles",MODELS:l(".principles","models"),STATE:".state",MEMORY:"memory",OKR:l("memory","okr"),LOGS:l("memory","logs"),SESSIONS:l(".state","sessions"),PAIN_SAMPLES:l("memory","pain"),LOCKS:l("memory",".locks"),IMPL_CODE_DIR:l(".state","principles","implementations")},ct={PROFILE:l(u.IDENTITY,"PROFILE.json"),PRINCIPLES:l(u.IDENTITY,"PRINCIPLES.md"),THINKING_OS:l(u.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:l(u.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:u.MODELS,STATE_DIR:u.STATE,WORKBOARD:l(u.STATE,"WORKBOARD.json"),AGENT_SCORECARD:l(u.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:l(u.STATE,".pain_flag"),SYSTEM_CAPABILITIES:l(u.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:l(u.STATE,"pain_settings.json"),PAIN_CANDIDATES:l(u.STATE,"pain_candidates.json"),TRAJECTORY_DB:l(u.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:l(u.STATE,"blobs"),EXPORTS_DIR:l(u.STATE,"exports"),SESSION_DIR:u.SESSIONS,DICTIONARY:l(u.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:l(u.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:l(u.STATE,"workflows.yaml"),IMPL_CODE_DIR:u.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:l(u.LOGS,"SYSTEM.log"),REFLECTION_LOG:l(u.MEMORY,"reflection-log.md"),USER_CONTEXT:l(u.MEMORY,"USER_CONTEXT.md"),OKR_DIR:u.OKR,CURRENT_FOCUS:l(u.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:l(u.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:l(u.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:l(u.LOCKS,"evolution")};function O(r,e){return at(r,ct[e])}var lt={LOCK_UNAVAILABLE:"lease_conflict",PATH_RESOLUTION_ERROR:"workspace_invalid",WORKSPACE_NOT_FOUND:"workspace_invalid",SAMPLE_NOT_FOUND:"storage_unavailable",CONFIGURATION_ERROR:"input_invalid",DEPENDENCY_ERROR:"runtime_unavailable",EVOLUTION_PROCESSING_ERROR:"execution_failed",TRAJECTORY_ERROR:"storage_unavailable"},K=class extends Error{constructor(t,n,s){super(t,s);this.code=n;this.name="PdError",this.category=lt[n]??"execution_failed"}code;category};var v=class extends K{constructor(e,t){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",t),this.name="SampleNotFoundError"}};var ut=["schema_version","ingest_checkpoint","sessions","assistant_turns","user_turns","tool_calls","pain_events","gate_blocks","trust_changes","principle_events","task_outcomes","correction_samples","sample_reviews","signal_confirmations","exports_audit"];function T(r){let e=r instanceof Error?r.message:String(r);return e.includes("duplicate column name")||e.includes("no column named")}function dt(r,e){return r.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Te(r,e={}){let t=[],n=[...ut];r.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, gfi_before REAL, gfi_after REAL, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),r.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),r.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{r.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!T(s))throw s}if(r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)"),r.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),dt(r,"evolution_tasks")){try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!T(s))throw s}try{r.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!T(s))throw s}}return r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_session_id ON assistant_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_created_at ON assistant_turns(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_assistant_turns_provider_model ON assistant_turns(provider, model)"),r.exec("CREATE INDEX IF NOT EXISTS idx_user_turns_session_id ON user_turns(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_id ON tool_calls(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_created_at ON tool_calls(created_at)"),r.exec("CREATE INDEX IF NOT EXISTS idx_pain_events_session_id ON pain_events(session_id)"),r.exec("CREATE INDEX IF NOT EXISTS idx_correction_samples_review_status ON correction_samples(review_status)"),r.exec("CREATE INDEX IF NOT EXISTS idx_signal_confirmations_status ON signal_confirmations(status, attempts)"),e.views===!0&&(r.exec("CREATE VIEW IF NOT EXISTS v_error_clusters AS SELECT tool_name, COALESCE(error_type, 'unknown') AS error_type, COUNT(*) AS occurrences FROM tool_calls WHERE outcome = 'failure' GROUP BY tool_name, COALESCE(error_type, 'unknown') ORDER BY occurrences DESC"),r.exec("CREATE VIEW IF NOT EXISTS v_principle_effectiveness AS SELECT event_type, COUNT(*) AS total FROM principle_events GROUP BY event_type ORDER BY total DESC"),r.exec("CREATE VIEW IF NOT EXISTS v_sample_queue AS SELECT review_status, COUNT(*) AS total FROM correction_samples GROUP BY review_status")),{tables:n,warnings:t}}import*as G from"path";import*as fe from"os";var _t=[/(^|[/\\])fake[/\\]/i,/(^|[/\\])mock[/\\]/i,/(^|[/\\])tmp[/\\]fake-/i],pt=G.join(fe.tmpdir(),".pd-test-quarantine");function Et(r){if(!r)return!1;let e=r.replace(/\\/g,"/");return _t.some(t=>t.test(e))}function ge(r){if(!r||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Et(r))return r;let t=r.replace(/[:*?"<>|]/g,"_").replace(/[/\\]/g,"_");for(;t.startsWith("_");)t=t.slice(1);for(;t.endsWith("_");)t=t.slice(0,-1);return G.join(pt,t)}var Tt=16*1024,ft=5e3,gt=7;function Oe(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function St(r){return!Oe(r)||typeof r.id!="number"||typeof r.session_id!="string"?!1:Object.hasOwn(r,"source")&&Object.hasOwn(r,"score")&&Object.hasOwn(r,"reason")&&Object.hasOwn(r,"severity")&&Object.hasOwn(r,"origin")&&Object.hasOwn(r,"confidence")&&Object.hasOwn(r,"text")&&Object.hasOwn(r,"canonical_pain_id")&&Object.hasOwn(r,"runtime_task_id")&&Object.hasOwn(r,"created_at")}function ht(r){let e=Te(r,{views:!0});return{tables:e.tables,warnings:e.warnings}}function m(){return new Date().toISOString()}function b(r){return JSON.stringify(r??{})}function Se(r){try{return E.existsSync(r)?E.statSync(r).size:0}catch{return 0}}function Ot(r){return r.length>240?`${r.slice(0,237)}...`:r}function he(r){return r.replace(/[A-Za-z]:\\[^\s"'`]+/g,"<WINDOWS_PATH>").replace(/\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)+/g,"<PATH>").replace(/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/gi,"<EMAIL>").replace(/\b(sk|rk|pk)_[A-Za-z0-9]+\b/g,"<TOKEN>")}function Rt(r){let e=[],t=!1;try{let n=JSON.parse(String(r.terms_json??"[]"));if(Array.isArray(n))e=n.filter(s=>typeof s=="string");else if(n!==null&&typeof n=="object"){let s=n;if(Object.hasOwn(s,"correction")){let o=s.correction;Array.isArray(o)&&(e=o.filter(i=>typeof i=="string"),t=!0)}}}catch{e=[],t=!1}return{id:String(r.id),sessionId:String(r.session_id),userTurnRowid:Number(r.user_turn_rowid),occurrenceId:String(r.occurrence_id),excerpt:String(r.excerpt),terms:e,termsVerified:t,suggestedType:String(r.suggested_type),status:String(r.status),attempts:Number(r.attempts??0),createdAt:String(r.created_at),resolvedAt:r.resolved_at===null||r.resolved_at===void 0?null:String(r.resolved_at),resolution:r.resolution===null||r.resolution===void 0?null:String(r.resolution)}}var P=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=ge(S.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Tt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??gt)*24*60*60*1e3),E.mkdirSync(this.stateDir,{recursive:!0}),E.mkdirSync(this.blobDir,{recursive:!0}),E.mkdirSync(this.exportDir,{recursive:!0}),this.db=new mt(this.dbPath),this.db.pragma("journal_mode = WAL"),this.db.pragma("foreign_keys = ON"),this.db.pragma("synchronous = NORMAL"),this.db.pragma(`busy_timeout = ${Math.max(0,e.busyTimeoutMs??ft)}`),this.initSchema(),this.importLegacyArtifacts(),this.pruneUnreferencedBlobs()}dispose(){this.db.close()}get isOpen(){return this.db.open}recordSession(e){let t=e.startedAt??m();this.withWrite(()=>{this.db.prepare(`
3
3
  INSERT INTO sessions (session_id, started_at, updated_at)
4
4
  VALUES (?, ?, ?)
5
5
  ON CONFLICT(session_id) DO UPDATE SET updated_at = excluded.updated_at
@@ -8,7 +8,7 @@ var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
8
8
  session_id, run_id, provider, model, raw_text, sanitized_text, usage_json,
9
9
  empathy_signal_json, blob_ref, raw_excerpt, stop_reason, thinking_blocks_count, created_at
10
10
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
11
- `).run(e.sessionId,e.runId,e.provider,e.model,t.inlineText,e.sanitizedText,N(e.usageJson),N(e.empathySignalJson),t.blobRef,t.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=this.storeRawText("user",e.rawText),n=e.createdAt??m();return this.withWrite(()=>{let s=this.db.prepare(`
11
+ `).run(e.sessionId,e.runId,e.provider,e.model,t.inlineText,e.sanitizedText,b(e.usageJson),b(e.empathySignalJson),t.blobRef,t.excerpt,e.stopReason??null,e.thinkingBlocksCount??null,n);return Number(s.lastInsertRowid)})}recordUserTurn(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=this.storeRawText("user",e.rawText),n=e.createdAt??m();return this.withWrite(()=>{let s=this.db.prepare(`
12
12
  INSERT INTO user_turns (
13
13
  session_id, turn_index, raw_text, blob_ref, raw_excerpt,
14
14
  correction_detected, correction_cue, references_assistant_turn_id, created_at
@@ -22,7 +22,7 @@ var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
22
22
  session_id, tool_name, outcome, duration_ms, exit_code, error_type, error_message,
23
23
  gfi_before, gfi_after, params_json, result_preview, created_at
24
24
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
25
- `).run(e.sessionId,e.toolName,e.outcome,e.durationMs??null,e.exitCode??null,e.errorType??null,e.errorMessage??null,e.gfiBefore??null,e.gfiAfter??null,N(e.paramsJson),e.resultPreview??null,t);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),n}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=-1;return this.withWrite(()=>{try{let n=this.db.prepare(`
25
+ `).run(e.sessionId,e.toolName,e.outcome,e.durationMs??null,e.exitCode??null,e.errorType??null,e.errorMessage??null,e.gfiBefore??null,e.gfiAfter??null,b(e.paramsJson),e.resultPreview??null,t);return Number(s.lastInsertRowid)});return e.outcome==="success"&&this.maybeCreateCorrectionSample(e.sessionId),n}recordPainEvent(e){this.recordSession({sessionId:e.sessionId,startedAt:e.createdAt});let t=-1;return this.withWrite(()=>{try{let n=this.db.prepare(`
26
26
  INSERT INTO pain_events (
27
27
  session_id, source, score, reason, severity, origin, confidence, text, created_at,
28
28
  canonical_pain_id, runtime_task_id, host_kind
@@ -41,10 +41,10 @@ var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
41
41
  `).run(e.sessionId??null,e.previousScore,e.newScore,e.delta,e.reason,e.createdAt??m())})}recordPrincipleEvent(e){this.withWrite(()=>{this.db.prepare(`
42
42
  INSERT INTO principle_events (principle_id, event_type, payload_json, created_at)
43
43
  VALUES (?, ?, ?, ?)
44
- `).run(e.principleId??null,e.eventType,N(e.payload),e.createdAt??m())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
44
+ `).run(e.principleId??null,e.eventType,b(e.payload),e.createdAt??m())})}recordTaskOutcome(e){this.withWrite(()=>{this.db.prepare(`
45
45
  INSERT INTO task_outcomes (session_id, task_id, outcome, summary, principle_ids_json, created_at)
46
46
  VALUES (?, ?, ?, ?, ?, ?)
47
- `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,N(e.principleIdsJson),e.createdAt??m())})}evolutionTableMissing(e){let t=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!t||typeof t.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let t=[],n=[];e.status&&(t.push("status = ?"),n.push(e.status)),e.dateFrom&&(t.push("created_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(t.push("created_at <= ?"),n.push(e.dateTo));let s=t.length>0?`WHERE ${t.join(" AND ")}`:"",o=e.limit??50,i=e.offset??0;return this.db.prepare(`
47
+ `).run(e.sessionId,e.taskId??null,e.outcome,e.summary??null,b(e.principleIdsJson),e.createdAt??m())})}evolutionTableMissing(e){let t=this.db.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e);return!t||typeof t.name!="string"}listEvolutionTasks(e={}){if(this.evolutionTableMissing("evolution_tasks"))return[];let t=[],n=[];e.status&&(t.push("status = ?"),n.push(e.status)),e.dateFrom&&(t.push("created_at >= ?"),n.push(e.dateFrom)),e.dateTo&&(t.push("created_at <= ?"),n.push(e.dateTo));let s=t.length>0?`WHERE ${t.join(" AND ")}`:"",o=e.limit??50,i=e.offset??0;return this.db.prepare(`
48
48
  SELECT id, task_id, trace_id, source, reason, score, status,
49
49
  enqueued_at, started_at, completed_at, resolution, created_at, updated_at,
50
50
  task_kind, priority, retry_count, max_retries, last_error, result_ref
@@ -164,7 +164,7 @@ var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
164
164
  id, session_id, user_turn_rowid, occurrence_id, excerpt,
165
165
  terms_json, suggested_type, status, attempts, created_at
166
166
  ) VALUES (?, ?, ?, ?, ?, ?, ?, 'pending', 0, ?)
167
- `).run(t,e.sessionId,e.userTurnRowid,e.occurrenceId,e.excerpt,JSON.stringify(e.terms),e.suggestedType,e.createdAt)})}listPendingSignalConfirmations(e){return this.db.prepare(`
167
+ `).run(t,e.sessionId,e.userTurnRowid,e.occurrenceId,e.excerpt,JSON.stringify({correction:e.terms}),e.suggestedType,e.createdAt)})}listPendingSignalConfirmations(e){return this.db.prepare(`
168
168
  SELECT * FROM signal_confirmations
169
169
  WHERE status = 'pending'
170
170
  ORDER BY attempts ASC, created_at ASC
@@ -254,11 +254,11 @@ var ye=(r=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(r,{get:(e,t)=>(
254
254
  recovery_tool_span_json, diff_excerpt, principle_ids_json, quality_score,
255
255
  review_status, export_mode, created_at, updated_at
256
256
  ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'pending', 'raw', ?, ?)
257
- `).run(a,e,Number(n.references_assistant_turn_id),Number(n.id),N(i.map(g=>({id:g.id,toolName:g.tool_name,outcome:g.outcome}))),Ot(_),"[]",f,m(),m())})}recordExportAudit(e,t,n,s,o){this.withWrite(()=>{this.db.prepare(`
257
+ `).run(a,e,Number(n.references_assistant_turn_id),Number(n.id),b(i.map(g=>({id:g.id,toolName:g.tool_name,outcome:g.outcome}))),Ot(_),"[]",f,m(),m())})}recordExportAudit(e,t,n,s,o){this.withWrite(()=>{this.db.prepare(`
258
258
  INSERT INTO exports_audit (export_kind, mode, approved_only, file_path, row_count, created_at)
259
259
  VALUES (?, ?, ?, ?, ?, ?)
260
260
  `).run(e,t,n?1:0,s,o,m())})}storeRawText(e,t){let n=t.length>200?`${t.slice(0,197)}...`:t;if(Buffer.byteLength(t,"utf8")<=this.blobInlineThresholdBytes)return{inlineText:t,blobRef:null,excerpt:n};let o=z.createHash("sha256").update(t).digest("hex"),i=`${e}-${o}.txt`,c=S.join(this.blobDir,i);return E.existsSync(c)||M(c,t),{inlineText:null,blobRef:i,excerpt:n}}restoreRawText(e,t){if(e)return e;if(!t)return"";let n=S.join(this.blobDir,t);return E.existsSync(n)?E.readFileSync(n,"utf8"):""}computeBlobBytes(){return E.existsSync(this.blobDir)?E.readdirSync(this.blobDir).reduce((e,t)=>e+Se(S.join(this.blobDir,t)),0):0}pruneUnreferencedBlobs(){if(!E.existsSync(this.blobDir))return{removedFiles:0,reclaimedBytes:0};let e=new Set,t=this.db.prepare(`
261
261
  SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
262
262
  UNION
263
263
  SELECT blob_ref FROM user_turns WHERE blob_ref IS NOT NULL
264
- `).all();for(let i of t)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of E.readdirSync(this.blobDir)){if(e.has(i))continue;let c=S.join(this.blobDir,i),a;try{a=E.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&n-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,E.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ee(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},L=class{static instances=new Map;static get(e,t={}){let n=S.resolve(e),s=this.instances.get(n);if(s)return s;let o=new P({workspaceDir:n,...t});return this.instances.set(n,o),o}static dispose(e){let t=S.resolve(e),n=this.instances.get(t);n&&(n.dispose(),this.instances.delete(t))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,t,n={}){let s=S.resolve(e),o=this.instances.get(s);if(o)return t(o);let i=new P({workspaceDir:s,...n});try{return t(i)}finally{i.dispose()}}};var Nt=new Set(["__proto__","constructor","prototype"]);function bt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function yt(r){if(!Array.isArray(r))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],t=new Map;return r.forEach((n,s)=>{if(!bt(n)){e.push(`toolSemanticMappings[${s}] must be a plain object`);return}if(!Object.hasOwn(n,"rawToolName")||typeof n.rawToolName!="string"||n.rawToolName.trim()===""){e.push(`toolSemanticMappings[${s}].rawToolName must be a non-empty string`);return}if(Nt.has(n.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=n.canonicalKind;if(!te(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...F].join("|")}, got ${String(o)}`);return}let i=t.get(n.rawToolName);if(i!==void 0&&i!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${n.rawToolName}' declared twice with conflicting kinds (${i} vs ${o})`);return}t.set(n.rawToolName,o)}),{valid:e.length===0,errors:e}}function Re(r){let e,t=new Set,n=[];if(r===void 0)e=w;else{let s=yt(r);if(!s.valid)return{ok:!1,errors:s.errors};let o={...w};for(let i of r)o[i.rawToolName]=i.canonicalKind,t.add(i.rawToolName);n=Object.freeze(r.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:t.size>0,hasHostTool(s){return typeof s!="string"?!1:t.has(s)},hostMappings(){return n},lookup(s){return typeof s!="string"||!Object.hasOwn(e,s)?null:e[s]??null},resolve(s){return this.lookup(s)??"other"}}}}var Ne=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],b=["write","edit","apply_patch"],x=["exec"],At=[...x],j=["sessions_spawn"],It=[...b],vt=[...b,...x,...j],Lt=[...Ne],Tr=new Set(Ne),fr=new Set(b),gr=new Set(At),Sr=new Set(x),hr=new Set(j),Or=new Set(It),Rr=new Set(vt),Nr=new Set(Lt),br=new Set([...b]);function J(r,e){return r.map(t=>({rawToolName:t,canonicalKind:e}))}var xt=Object.freeze([...J(x,"execute"),...J(b,"write"),...J(j,"agent")]),V=Re(xt);if(!V.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${V.errors.join("; ")}`);var be=V.registry;var Z=class extends D{constructor(e){super({source:L.get(e.workspaceDir),toolSemantics:be})}};export{Z as BehaviorExamplePackAssembler,L as RuleHostEvidenceRegistry};
264
+ `).all();for(let i of t)i.blob_ref&&e.add(String(i.blob_ref));let n=Date.now(),s=0,o=0;for(let i of E.readdirSync(this.blobDir)){if(e.has(i))continue;let c=S.join(this.blobDir,i),a;try{a=E.statSync(c)}catch{continue}a.isFile()&&(this.orphanBlobGraceMs>0&&n-a.mtimeMs<this.orphanBlobGraceMs||(o+=a.size,s+=1,E.rmSync(c,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ee(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},L=class{static instances=new Map;static get(e,t={}){let n=S.resolve(e),s=this.instances.get(n);if(s)return s;let o=new P({workspaceDir:n,...t});return this.instances.set(n,o),o}static dispose(e){let t=S.resolve(e),n=this.instances.get(t);n&&(n.dispose(),this.instances.delete(t))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,t,n={}){let s=S.resolve(e),o=this.instances.get(s);if(o)return t(o);let i=new P({workspaceDir:s,...n});try{return t(i)}finally{i.dispose()}}};var bt=new Set(["__proto__","constructor","prototype"]);function yt(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Nt(r){if(!Array.isArray(r))return{valid:!1,errors:["toolSemanticMappings must be an array"]};let e=[],t=new Map;return r.forEach((n,s)=>{if(!yt(n)){e.push(`toolSemanticMappings[${s}] must be a plain object`);return}if(!Object.hasOwn(n,"rawToolName")||typeof n.rawToolName!="string"||n.rawToolName.trim()===""){e.push(`toolSemanticMappings[${s}].rawToolName must be a non-empty string`);return}if(bt.has(n.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=n.canonicalKind;if(!te(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...F].join("|")}, got ${String(o)}`);return}let i=t.get(n.rawToolName);if(i!==void 0&&i!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${n.rawToolName}' declared twice with conflicting kinds (${i} vs ${o})`);return}t.set(n.rawToolName,o)}),{valid:e.length===0,errors:e}}function Re(r){let e,t=new Set,n=[];if(r===void 0)e=w;else{let s=Nt(r);if(!s.valid)return{ok:!1,errors:s.errors};let o={...w};for(let i of r)o[i.rawToolName]=i.canonicalKind,t.add(i.rawToolName);n=Object.freeze(r.map(i=>Object.freeze({rawToolName:i.rawToolName,canonicalKind:i.canonicalKind}))),e=Object.freeze(o)}return{ok:!0,registry:{version:1,hasHostLayer:t.size>0,hasHostTool(s){return typeof s!="string"?!1:t.has(s)},hostMappings(){return n},lookup(s){return typeof s!="string"||!Object.hasOwn(e,s)?null:e[s]??null},resolve(s){return this.lookup(s)??"other"}}}}var be=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],y=["write","edit","apply_patch"],x=["exec"],At=[...x],j=["sessions_spawn"],It=[...y],vt=[...y,...x,...j],Lt=[...be],Tr=new Set(be),fr=new Set(y),gr=new Set(At),Sr=new Set(x),hr=new Set(j),Or=new Set(It),Rr=new Set(vt),br=new Set(Lt),yr=new Set([...y]);function V(r,e){return r.map(t=>({rawToolName:t,canonicalKind:e}))}var xt=Object.freeze([...V(x,"execute"),...V(y,"write"),...V(j,"agent")]),J=Re(xt);if(!J.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${J.errors.join("; ")}`);var ye=J.registry;var Z=class extends D{constructor(e){super({source:L.get(e.workspaceDir),toolSemantics:ye})}};export{Z as BehaviorExamplePackAssembler,L as RuleHostEvidenceRegistry};
@@ -9,9 +9,25 @@ import type { CorrectionObserverOutputV1 as CorrectionObserverResult } from '@pr
9
9
  import type { PluginLogger } from '../openclaw-sdk.js';
10
10
  /**
11
11
  * Applies CorrectionObserverResult mutations to the keyword store.
12
- * - ADD: calls learner.add() with new keyword
13
- * - UPDATE: updates weight on existing keyword
14
- * - REMOVE: removes keyword from store
12
+ * - ADD: calls learner.add() with new keyword (evicts least-valuable learned
13
+ * terms at/over the cap, with bounded convergence when the store is oversized)
14
+ * - UPDATE: updates weight on an existing keyword
15
+ * - REMOVE: removes keyword from store; Owner-authored seed terms and terms
16
+ * with confirmed TPs are protected
17
+ *
18
+ * Every key is resolved with the store's own identity rule (trim + lowercase),
19
+ * and a key that does not resolve is an observable skip, not a thrown error:
20
+ * the model paraphrases terms constantly, and the old per-op exceptions turned
21
+ * that into ~47 WARN lines a day that hid real failures.
22
+ *
23
+ * Persistence is layered and must not be conflated (P2-3):
24
+ * - the keyword store itself is persisted synchronously and atomically by
25
+ * CorrectionCueLearner.flush() (temp-file-then-rename). That is the only
26
+ * durable mutation of record.
27
+ * - the SYSTEM line emitted by audit() is best-effort, asynchronous and may
28
+ * drop entries (SystemLogger appends fire-and-forget and swallows write
29
+ * errors). It is an Owner-visible trace, not proof that the store write
30
+ * happened; under disk pressure the two can legitimately disagree.
15
31
  */
16
32
  export declare class KeywordOptimizationService {
17
33
  private readonly stateDir;
@@ -19,6 +35,21 @@ export declare class KeywordOptimizationService {
19
35
  private readonly logger;
20
36
  constructor(stateDir: string, workspaceDir: string, logger: PluginLogger);
21
37
  applyResult(result: CorrectionObserverResult): void;
38
+ /**
39
+ * One Owner-visible line per store mutation: plugin log + SYSTEM log.
40
+ *
41
+ * The mutation is durable because the learner flushed the store before this
42
+ * call. The SYSTEM line is a best-effort audit trace (async appendFile that
43
+ * swallows errors): its absence never means the mutation did not happen, and
44
+ * its presence is never by itself evidence that it did.
45
+ */
46
+ private audit;
47
+ /**
48
+ * A verdict the store cannot act on. Reported, not thrown: the model
49
+ * paraphrases term keys constantly, and each refusal still needs a reason
50
+ * (rc-9 — degradation must be observable).
51
+ */
52
+ private skip;
22
53
  /**
23
54
  * Builds trajectory history for payload:
24
55
  * - Calls TrajectoryDatabase.listUserTurnsForSession() for recent sessions
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "create-principles-disciple",
3
- "version": "1.145.4",
3
+ "version": "1.145.5",
4
4
  "description": "Interactive CLI installer for Principles Disciple OpenClaw plugin",
5
5
  "type": "module",
6
6
  "bin": {