principles-disciple 4.1.1 → 4.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -29,6 +29,19 @@
29
29
  *
30
30
  * Fail loud at module load if the derived declaration is invalid — a broken
31
31
  * static declaration is a programming error, not a runtime condition (rc-3).
32
+ *
33
+ * OG-4 DELIBERATE OMISSION (2026-11-13): `pd_submit_pain` (the shared MCP
34
+ * write tool) is NOT declared here. Two independent reasons, both required by
35
+ * this file's own contract:
36
+ * 1. DISPATCHABILITY — `hooks/gate.ts:363-366` only enters the RuleHost for
37
+ * `WRITE_TOOLS | BASH_TOOLS_SET | AGENT_TOOLS`; the MCP tool is in none
38
+ * of them, so declaring it would make `hasHostTool` true for a name no
39
+ * rule can ever fire on (the exact PRI-741 failure this list fixes).
40
+ * 2. SEMANTICS — `CanonicalKind` is a file-mutation axis. `write` feeds
41
+ * `computeBehaviorFacts.writeCount` and disables the `'other' ⇒ facts
42
+ * incomplete` conservative guard, but the MCP payload carries no target
43
+ * path. It stays `'other'` (conservative) until the enum grows a
44
+ * non-file mutation kind AND the gate routes it.
32
45
  */
33
46
  import { type ToolSemanticMappingV1, type ToolSemanticRegistry } from '@principles/core/runtime/internalization/tool-semantic-registry';
34
47
  export declare const OPENCLAW_TOOL_SEMANTIC_MAPPINGS: readonly ToolSemanticMappingV1[];
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Correction → assistant-turn anchoring.
3
+ *
4
+ * A user correction must point at the turn the user is actually objecting to.
5
+ * "The most recent assistant turn" is only correct when the correction lands
6
+ * directly on the offending answer. The failure this module exists for is the
7
+ * cross-turn case:
8
+ *
9
+ * T1 assistant edits a config without evidence ← the real error
10
+ * T2 user asks "why did you touch it?"
11
+ * T3 assistant explains / apologises ← most recent turn
12
+ * T4 user: "不对,你刚才没有任何实测依据就修改了参数。"
13
+ *
14
+ * Anchoring T4 to the T3 explanation attaches the Pain to words the Owner was
15
+ * not objecting to, and the Diagnostician reasons about the wrong turn. Round 3
16
+ * observed exactly this: the correction referenced the explanation turn.
17
+ *
18
+ * Policy (round-3 brief: prefer an exact reference, never pretend the most
19
+ * recent turn is the target, allow a structured `unresolved`):
20
+ * 1. no back-reference → the latest assistant turn IS the target;
21
+ * 2. back-reference → anchor to the most recent assistant turn that actually
22
+ * EXECUTED something (write-type tool call, from runtime evidence);
23
+ * 3. back-reference with no such turn → unresolved (null), never fabricated.
24
+ */
25
+ export interface AnchoredAssistantTurn {
26
+ readonly id: number;
27
+ readonly text?: string;
28
+ readonly createdAt?: string;
29
+ }
30
+ export interface AnchoredToolCall {
31
+ readonly toolName: string;
32
+ readonly createdAt: string;
33
+ }
34
+ export type CorrectionAnchorReason = 'latest_turn' | 'back_reference_tool_evidence' | 'unresolved_back_reference' | 'unresolved_missing_turn_timestamp' | 'no_assistant_turn';
35
+ export interface CorrectionAnchorResult {
36
+ readonly turnId: number | null;
37
+ readonly reason: CorrectionAnchorReason;
38
+ }
39
+ export declare function hasBackReference(userMessage: string): boolean;
40
+ export declare function resolveCorrectionAnchor(userMessage: string, turns: readonly AnchoredAssistantTurn[], toolCalls?: readonly AnchoredToolCall[]): CorrectionAnchorResult;
@@ -11,6 +11,16 @@ export type ExperimentIsolationViolation = {
11
11
  */
12
12
  export declare function canonicalForIsolation(candidate: string): string;
13
13
  export declare function experimentRootFromEnv(env?: NodeJS.ProcessEnv): string | null;
14
+ /**
15
+ * The PD workspace this experiment process DECLARED it belongs to.
16
+ *
17
+ * Containment alone is not identity: a profile that resolves to a DIFFERENT
18
+ * workspace inside the same experiment root would silently fork the experiment
19
+ * (two state DBs, two owner identities, evidence split across both). P0-1
20
+ * round 3 therefore compares the resolved workspace with this declaration
21
+ * whenever the operator made one.
22
+ */
23
+ export declare function declaredExperimentWorkspace(env?: NodeJS.ProcessEnv): string | null;
14
24
  export declare function experimentIsolationNextAction(): string;
15
25
  /**
16
26
  * Returns `null` when the workspace is acceptable, else a structured violation.
@@ -7,8 +7,6 @@ import { EvolutionReducerImpl } from './evolution-reducer.js';
7
7
  import type { TrajectoryDatabase } from './trajectory.js';
8
8
  import { PrincipleLifecycleService } from './principle-internalization/principle-lifecycle-service.js';
9
9
  import { type PrincipleSubtree, type LedgerPrinciple, type PrincipleValueMetrics } from './principle-tree-ledger.js';
10
- import { RuleHost } from './rule-host.js';
11
- import type { RuleHostLogger } from './rule-host.js';
12
10
  interface PrincipleTreeLedgerAccessor {
13
11
  getPrincipleSubtree(_principleId: string): PrincipleSubtree | undefined;
14
12
  updatePrinciple(_principleId: string, updates: Partial<LedgerPrinciple>): LedgerPrinciple;
@@ -31,7 +29,6 @@ export declare class WorkspaceContext {
31
29
  private _trajectory?;
32
30
  private _principleTreeLedger?;
33
31
  private _principleLifecycle?;
34
- private _ruleHost?;
35
32
  private constructor();
36
33
  /**
37
34
  * Governance configuration for this workspace.
@@ -64,7 +61,6 @@ export declare class WorkspaceContext {
64
61
  * injected principle on prompt build).
65
62
  */
66
63
  get trajectory(): TrajectoryDatabase;
67
- getRuleHost(logger: RuleHostLogger): RuleHost;
68
64
  /**
69
65
  * Locked ledger access for principle tree reads and metric writes in this workspace.
70
66
  */
@@ -12,11 +12,6 @@ import { WorkspaceContext } from '../core/workspace-context.js';
12
12
  import type { RuleContextV2 } from '@principles/core/runtime';
13
13
  import type { PluginHookBeforeToolCallEvent, PluginHookToolContext, PluginHookBeforeToolCallResult, PluginLogger } from '../openclaw-sdk.js';
14
14
  import type { HostEventResult } from '@principles/core/host';
15
- export declare function handleBeforeToolCall(event: PluginHookBeforeToolCallEvent, ctx: PluginHookToolContext & {
16
- workspaceDir?: string;
17
- pluginConfig?: Record<string, unknown>;
18
- logger?: Partial<PluginLogger>;
19
- }): PluginHookBeforeToolCallResult | void;
20
15
  export declare function buildOpenClawRuleInputEnrichment(event: PluginHookBeforeToolCallEvent): {
21
16
  epTier: number;
22
17
  bashRisk: "dangerous" | "normal" | "safe" | "unknown";
@@ -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": "4.1.1",
5
+ "version": "4.1.2",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
@@ -2,7 +2,7 @@ import { createRequire } from 'module'; const require = createRequire(import.met
2
2
  var Be=(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 ie=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 ce="",Xe="|;&<>()";function k(t){return Xe.includes(t)?`${ce}${t}`:t}function ae(t){if(t.includes(ce))return null;let e=[],n="",r=!1,s=0,o=t.length,i="plain";for(;s<o;){let a=t[s];if(a===void 0)break;if(i==="single"){a==="'"?i="plain":n+=k(a),s+=1;continue}if(i==="double"){if(a==='"')i="plain";else if(a==="\\"&&s+1<o&&'"\\$`'.includes(t[s+1]??"")){n+=k(t[s+1]??""),s+=2;continue}else n+=k(a);s+=1;continue}if(a==="'"){i="single",r=!0,s+=1;continue}if(a==='"'){i="double",r=!0,s+=1;continue}if(a==="\\"&&s+1<o){n+=k(t[s+1]??""),r=!0,s+=2;continue}if(a==="\r"||a===`
3
3
  `){(r||n)&&(e.push(n),n="",r=!1),a==="\r"&&t[s+1]===`
4
4
  `&&(s+=1),e.push(`
5
- `),s+=1;continue}if(" ".includes(a)){(r||n)&&(e.push(n),n="",r=!1),s+=1;continue}if("|;&<>()".includes(a)){(r||n)&&(e.push(n),n="",r=!1);let c=a,d=t[s+1];a==="<"&&d===">"?c="<>":(a==="|"||a==="&"||a===">"||a==="<")&&d===a&&(c+=d),(a===">"||a==="<")&&d==="("&&(c+=d),e.push(c),s+=c.length;continue}n+=a,r=!0,s+=1}return i!=="plain"?null:((r||n)&&e.push(n),e)}function le(t){if(/[\\$`|;&<>()*?~{}]/.test(t)||[...t].some(s=>s.charCodeAt(0)<32))return;let e=ae(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 ie){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=ae(s.cliCommand);if(!o||o.length!==n.length)continue;if(o.every((a,c)=>s.capabilityId==="rulecode_deactivate"&&o[c-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(n[c]??""):a===n[c]))return s.capabilityId}}var We=["verbose","debug"],$e=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...We,...t]),valued:new Set([...$e,...e])}}var rn=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 H(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 ue(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 He(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 de(t){let[e,n]=t.root.slice(4).split("/"),r=t.segments.join("/");return`//${e??""}/${n??""}${r?`/${r}`:""}`}function pe(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))||!ue(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?de(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 ue(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":He(e.segments,r,s)}function Ye(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=H(n),o=H(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let a=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=H(a),pe(s,o,a)}return pe(s,o,n)}function Ke(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 Ge(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function qe(t){if(t.canonicalKind===void 0)return t;let e=Ge(t.canonicalKind);return{...t,isBashTool:e.isBashTool,isWriteTool:e.isWriteTool}}function D(t,e,n,r={}){let s=qe(r),o=Ke(e,{...s,toolName:t}),i=o.isPath?Ye(o.value,n):o.value,a=e.command??e.args,c=s.isBashTool&&typeof a=="string"?le(a):void 0;return{toolName:t,normalizedPath:i,...c?{recoveryControl:c}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var Y=new Set(["read","search","write","execute","agent","other"]);function fe(t){return typeof t=="string"&&Y.has(t)}var P=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 _e(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:a}=t;for(let c of a){let d=c.canonicalKind;d==="read"||d==="search"?(r++,e!==null&&c.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof c.normalizedPath=="string"&&o.add(c.normalizedPath))}return{priorReadOfTarget:i,readCount:r,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var me={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(me);var K={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(K.calls);Object.freeze(K);var ze={version:2,history:K,facts:me};Object.freeze(ze);var Ve=new Set(["__proto__","constructor","prototype"]),Ee=3,Je=5,Ze=new Set(["allow","block","propose_correction"]),Qe={valid:!0,errors:[]};function G(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ge(t){for(let e of Object.keys(t))if(Ve.has(e))return!1;return!0}function et(t){return t.length===0?Qe:{valid:!1,errors:t}}function q(t){return typeof t=="string"&&t.trim().length>0}function Te(t,e,n){let r=[];return G(t)?ge(t)?((!Object.hasOwn(t,"caseId")||!q(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")||!q(t.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!G(t.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!Ze.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 he(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 M(t){return Array.isArray(t)?`[${t.map(e=>M(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(n=>n!=="__proto__"&&n!=="constructor"&&n!=="prototype").sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`:JSON.stringify(t)??"null"}function z(t){if(!G(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ge(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...Te(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!q(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>Ee&&e.push(`positiveCounterexamples must contain at most ${Ee} items, got ${n.length}`);for(let r=0;r<n.length;r++)e.push(...Te(n[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...he(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Je,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...he(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let n=t.sourceNegativeCase,r=t.positiveCounterexamples,s=M({toolName:n.toolName,params:n.params,ruleContext:n.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&M({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return et(e)}var tt="OwnerEvidenceScopeError";function N(t,e){let n=new Error(e);return n.name=tt,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var nt=new Set(["success","failure","blocked"]);function rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function st(t){return typeof t=="string"&&nt.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Se(t,e,n){let{projectDir:r,toolSemantics:s}=n,o=[];for(let i of t){let{toolName:a}=i;if(typeof a!="string"||a.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:c}=i;if(!st(c))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 T;try{T=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!rt(T))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(a),{normalizedPath:g}=D(a,T,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:a,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:T,outcome:c})}return{status:"available",truncated:e,calls:o}}var ot=3,it=5,at=100,Oe=new Set(["__proto__","constructor","prototype"]);function j(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lt(t){for(let e of Object.keys(t))if(Oe.has(e))return!1;return!0}function ut(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>ot)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 ye(t,e){if(!t)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function dt(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(!ct(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!lt(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 pt(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var ft=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function _t(t){if(t.length<20)return!1;for(let e of ft)if(e.test(t))return!0;return!1}function mt(t,e){let n=[],r={};for(let s of Object.keys(t)){if(Oe.has(s))continue;let o=t[s];if(typeof o!="string"){r[s]=o;continue}if(pt(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(_t(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 N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ut(e);let r=ye(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>ye(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==n.sessionId)throw N("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},a=this.buildSelectedCase(r,"negative",i),c=s.map(m=>this.buildSelectedCase(m,"positive",i)),d={sourceNegativeCase:a,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,it),redactionNotes:o},T=z(d);if(!T.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${T.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=dt(e,n,n==="negative"?"block":"allow"),a=mt(i.params,s);o.push(...a.notes);let c=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,at)),d=Se(c.rows,c.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),T=D(e.toolName,a.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:_e(d,T.normalizedPath||null,null)};return{...i,params:a.redacted,ruleContext:m}}};import Pt from"better-sqlite3";import f from"fs";import h from"path";import ee from"crypto";import*as p from"fs";import*as be from"path";var V=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},Et={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Ne(t){try{return process.kill(t,0),!0}catch{return!1}}function Re(t,e){try{let n=be.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 I(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function Tt(t,e){try{I(t)===e&&p.unlinkSync(t)}catch{}}function ht(t,e){try{let n=p.statSync(t),r=I(t),s=Date.now()-n.mtimeMs>e,o=r===null||!Ne(r);if(s||o)try{return p.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function gt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function St(t){let e=Date.now()+t;for(;Date.now()<e;);}function yt(t,e){let n=I(e),r=n!==null?Ne(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new V(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function Ot(t,e,n){let r=t+e.lockSuffix;return Re(r,n)&&I(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(ht(r,e.lockStaleMs),Re(r,n)&&I(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function Rt(t,e={}){let n={...Et,...e},{pid:r}=process;for(let s=0;s<n.maxRetries;s++){let o=Ot(t,n,r);if(o)return o;if(s<n.maxRetries-1){let i=gt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);St(i)}}throw yt(t,t+n.lockSuffix)}function bt(t){Tt(t.lockPath,t.pid)}function Ae(t,e,n={}){let r=Rt(t,n);try{return e()}finally{bt(r)}}import*as R from"fs";var Ie=3,Nt=50;function w(t,e){let n=t+".tmp";R.writeFileSync(n,e,"utf8");let r;for(let s=0;s<Ie;s++)try{R.renameSync(n,t);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Ie-1){let a=Nt*Math.pow(2,s),c=Date.now()+a,d=!1;for(;Date.now()<c;)if(!d&&Date.now()>=c-10){try{Be("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 At(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function It(t,e){return At(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")},wt={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 It(t,wt[e])}var vt={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"},J=class extends Error{constructor(n,r,s){super(n,s);this.code=r;this.name="PdError",this.category=vt[r]??"execution_failed"}code;category};var v=class extends J{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var xt=["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"],we={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(we))Object.freeze(t);Object.freeze(we);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function F(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Z(t){if(!F(t,"schema_version"))return;let e=t.prepare("SELECT version FROM schema_version LIMIT 1").get();if(e===void 0){t.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2);return}e.version!==2&&t.prepare("UPDATE schema_version SET version = ?").run(2)}function Lt(t){if(F(t,"tool_calls"))for(let e of["gfi_before","gfi_after"])t.prepare("SELECT name FROM pragma_table_info('tool_calls') WHERE name = ?").get(e)!==void 0&&t.exec(`ALTER TABLE tool_calls DROP COLUMN ${e}`);F(t,"signal_confirmations")&&t.prepare("UPDATE signal_confirmations SET status = 'abandoned', resolved_at = ?, resolution = ? WHERE status = 'pending' AND suggested_type = 'empathy'").run(new Date().toISOString(),"gfi_removal"),Z(t)}function ve(t,e={}){let n=[],r=[...xt];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),F(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return Lt(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 Q from"path";import*as xe from"os";var kt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],Ct=Q.join(xe.tmpdir(),".pd-test-quarantine");function Dt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return kt.some(n=>n.test(e))}function Le(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Dt(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 Q.join(Ct,n)}var Mt=16*1024,jt=5e3,Ut=7,Ft=1440*60*1e3,Bt="trajectory-blob-prune.json",ke=!1;function te(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xt(t){return!te(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 Wt(t){let e=ve(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function Ce(t){try{return f.existsSync(t)?f.statSync(t).size:0}catch{return 0}}function $t(t){return t.length>240?`${t.slice(0,237)}...`:t}function De(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 Ht(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 B=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Le(h.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Mt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??Ut)*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 Pt(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??jt)}`),this.initSchema(),this.importLegacyArtifacts(),this.maybePruneUnreferencedBlobs()}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(a)){(r||n)&&(e.push(n),n="",r=!1),s+=1;continue}if("|;&<>()".includes(a)){(r||n)&&(e.push(n),n="",r=!1);let c=a,d=t[s+1];a==="<"&&d===">"?c="<>":(a==="|"||a==="&"||a===">"||a==="<")&&d===a&&(c+=d),(a===">"||a==="<")&&d==="("&&(c+=d),e.push(c),s+=c.length;continue}n+=a,r=!0,s+=1}return i!=="plain"?null:((r||n)&&e.push(n),e)}function le(t){if(/[\\$`|;&<>()*?~{}]/.test(t)||[...t].some(s=>s.charCodeAt(0)<32))return;let e=ae(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 ie){if(s.channel!=="cli"||!s.cliCommand||s.capabilityId!=="pd_status"&&s.capabilityId!=="rulecode_deactivate")continue;let o=ae(s.cliCommand);if(!o||o.length!==n.length)continue;if(o.every((a,c)=>s.capabilityId==="rulecode_deactivate"&&o[c-1]==="--activation-id"?/^[a-zA-Z0-9][a-zA-Z0-9_.:-]*$/.test(n[c]??""):a===n[c]))return s.capabilityId}}var We=["verbose","debug"],$e=["erroraction","warningaction","informationaction","progressaction","errorvariable","warningvariable","informationvariable","outvariable","outbuffer","pipelinevariable"];function S(t,e){return{switches:new Set([...We,...t]),valued:new Set([...$e,...e])}}var rn=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 H(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 ue(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 He(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 de(t){let[e,n]=t.root.slice(4).split("/"),r=t.segments.join("/");return`//${e??""}/${n??""}${r?`/${r}`:""}`}function pe(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))||!ue(t.segments,e.segments,t.kind==="drive"||t.kind==="unc")?t.kind==="unc"?de(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 ue(r,e.segments,s)?r.slice(e.segments.length).join("/")||".":He(e.segments,r,s)}function Ye(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=H(n),o=H(r);if(s.kind==="drive"&&o.kind!=="drive"&&o.kind!=="unc"){let a=`/mnt/${s.root.slice(-1).toLowerCase()}/${s.segments.join("/")}`;return s=H(a),pe(s,o,a)}return pe(s,o,n)}function Ke(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 Ge(t){return{isBashTool:t==="execute",isWriteTool:t==="write"}}function qe(t){if(t.canonicalKind===void 0)return t;let e=Ge(t.canonicalKind);return{...t,isBashTool:e.isBashTool,isWriteTool:e.isWriteTool}}function D(t,e,n,r={}){let s=qe(r),o=Ke(e,{...s,toolName:t}),i=o.isPath?Ye(o.value,n):o.value,a=e.command??e.args,c=s.isBashTool&&typeof a=="string"?le(a):void 0;return{toolName:t,normalizedPath:i,...c?{recoveryControl:c}:{},paramsSummary:{...e},...s.canonicalKind!==void 0?{canonicalKind:s.canonicalKind}:{}}}var Y=new Set(["read","search","write","execute","agent","other"]);function fe(t){return typeof t=="string"&&Y.has(t)}var P=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 _e(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:a}=t;for(let c of a){let d=c.canonicalKind;d==="read"||d==="search"?(r++,e!==null&&c.normalizedPath===e&&(i="yes")):d==="write"&&(s++,typeof c.normalizedPath=="string"&&o.add(c.normalizedPath))}return{priorReadOfTarget:i,readCount:r,writeCount:s,uniqueWritePathCount:o.size,sameActionBlockCount:n}}var me={priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null};Object.freeze(me);var K={status:"unavailable",unavailableReason:"host did not provide a history window",truncated:!1,calls:[]};Object.freeze(K.calls);Object.freeze(K);var ze={version:2,history:K,facts:me};Object.freeze(ze);var Ve=new Set(["__proto__","constructor","prototype"]),Ee=3,Je=5,Ze=new Set(["allow","block","propose_correction"]),Qe={valid:!0,errors:[]};function G(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function ge(t){for(let e of Object.keys(t))if(Ve.has(e))return!1;return!0}function et(t){return t.length===0?Qe:{valid:!1,errors:t}}function q(t){return typeof t=="string"&&t.trim().length>0}function Te(t,e,n){let r=[];return G(t)?ge(t)?((!Object.hasOwn(t,"caseId")||!q(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")||!q(t.toolName))&&r.push(`${e}.toolName must be a non-empty string`),(!Object.hasOwn(t,"params")||!G(t.params))&&r.push(`${e}.params must be a plain object`),!Object.hasOwn(t,"expectedDecision")||typeof t.expectedDecision!="string"||!Ze.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 he(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 M(t){return Array.isArray(t)?`[${t.map(e=>M(e)).join(",")}]`:typeof t=="object"&&t!==null?`{${Object.keys(t).filter(n=>n!=="__proto__"&&n!=="constructor"&&n!=="prototype").sort().map(n=>`${JSON.stringify(n)}:${M(t[n])}`).join(",")}}`:JSON.stringify(t)??"null"}function z(t){if(!G(t))return{valid:!1,errors:["BehaviorExamplePack must be a plain object"]};if(!ge(t))return{valid:!1,errors:["BehaviorExamplePack must not carry prototype-pollution keys"]};let e=[];if(Object.hasOwn(t,"sourceNegativeCase")?e.push(...Te(t.sourceNegativeCase,"sourceNegativeCase","negative")):e.push("sourceNegativeCase is required"),(!Object.hasOwn(t,"ownerDesiredOutcome")||!q(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>Ee&&e.push(`positiveCounterexamples must contain at most ${Ee} items, got ${n.length}`);for(let r=0;r<n.length;r++)e.push(...Te(n[r],`positiveCounterexamples[${r}]`,"positive"))}if(Object.hasOwn(t,"evidenceRefs")?e.push(...he(t.evidenceRefs,{fieldName:"evidenceRefs",maxLength:Je,requireNonEmpty:!0})):e.push("evidenceRefs is required"),Object.hasOwn(t,"redactionNotes")?e.push(...he(t.redactionNotes,{fieldName:"redactionNotes"})):e.push("redactionNotes is required"),e.length===0){let n=t.sourceNegativeCase,r=t.positiveCounterexamples,s=M({toolName:n.toolName,params:n.params,ruleContext:n.ruleContext});for(let o=0;o<r.length;o++){let i=r[o];i!==void 0&&M({toolName:i.toolName,params:i.params,ruleContext:i.ruleContext})===s&&e.push(`positiveCounterexamples[${o}] conflicting_label: identical effective input (toolName + params + ruleContext) as sourceNegativeCase but opposite expectedDecision \u2014 same input cannot carry both labels`)}}return et(e)}var tt="OwnerEvidenceScopeError";function N(t,e){let n=new Error(e);return n.name=tt,Object.assign(n,{ownerEvidenceScopeKind:t}),n}var nt=new Set(["success","failure","blocked"]);function rt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function st(t){return typeof t=="string"&&nt.has(t)}function A(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function Se(t,e,n){let{projectDir:r,toolSemantics:s}=n,o=[];for(let i of t){let{toolName:a}=i;if(typeof a!="string"||a.length===0)return A(`row id=${i.id}: tool_name must be a non-empty string`);let{outcome:c}=i;if(!st(c))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 T;try{T=JSON.parse(d)}catch{return A(`row id=${i.id}: params_json is not valid JSON`)}if(!rt(T))return A(`row id=${i.id}: params_json must parse to a non-array object`);let m=s.resolve(a),{normalizedPath:g}=D(a,T,r,{canonicalKind:m});o.push({sequenceId:i.id,toolName:a,canonicalKind:m,normalizedPath:g===""?null:g,paramsSummary:T,outcome:c})}return{status:"available",truncated:e,calls:o}}var ot=3,it=5,at=100,Oe=new Set(["__proto__","constructor","prototype"]);function j(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw N("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function ct(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function lt(t){for(let e of Object.keys(t))if(Oe.has(e))return!1;return!0}function ut(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>ot)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 ye(t,e){if(!t)throw N("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function dt(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(!ct(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!lt(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 pt(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var ft=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function _t(t){if(t.length<20)return!1;for(let e of ft)if(e.test(t))return!0;return!1}function mt(t,e){let n=[],r={};for(let s of Object.keys(t)){if(Oe.has(s))continue;let o=t[s];if(typeof o!="string"){r[s]=o;continue}if(pt(o)&&!o.startsWith(e)){r[s]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${s}" (outside project tree)`);continue}if(_t(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 N("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);ut(e);let r=ye(j(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),s=e.positiveToolCallIds.map(m=>ye(j(`evidence row read for id=${m}`,()=>this.db.getRuleHostEvidenceRow(m)),m));for(let m of[r,...s])if(m.sessionId!==n.sessionId)throw N("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},a=this.buildSelectedCase(r,"negative",i),c=s.map(m=>this.buildSelectedCase(m,"positive",i)),d={sourceNegativeCase:a,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...s.map(m=>`tool_call:${m.id}`)].slice(0,it),redactionNotes:o},T=z(d);if(!T.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${T.errors.join("; ")} (ERR-069 fail loud)`);return d}buildSelectedCase(e,n,r){let{projectDir:s,redactionNotes:o}=r,i=dt(e,n,n==="negative"?"block":"allow"),a=mt(i.params,s);o.push(...a.notes);let c=j(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,at)),d=Se(c.rows,c.truncated,{projectDir:s,toolSemantics:this.toolSemantics}),T=D(e.toolName,a.redacted,s,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),m={version:2,history:d,facts:_e(d,T.normalizedPath||null,null)};return{...i,params:a.redacted,ruleContext:m}}};import Pt from"better-sqlite3";import f from"fs";import h from"path";import ee from"crypto";import*as p from"fs";import*as be from"path";var V=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},Et={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Ne(t){try{return process.kill(t,0),!0}catch{return!1}}function Re(t,e){try{let n=be.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 I(t){try{let e=p.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function Tt(t,e){try{I(t)===e&&p.unlinkSync(t)}catch{}}function ht(t,e){try{let n=p.statSync(t),r=I(t),s=Date.now()-n.mtimeMs>e,o=r===null||!Ne(r);if(s||o)try{return p.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function gt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),s=r*.2*Math.random();return Math.floor(r+s)}function St(t){let e=Date.now()+t;for(;Date.now()<e;);}function yt(t,e){let n=I(e),r=n!==null?Ne(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new V(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function Ot(t,e,n){let r=t+e.lockSuffix;return Re(r,n)&&I(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(ht(r,e.lockStaleMs),Re(r,n)&&I(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function Rt(t,e={}){let n={...Et,...e},{pid:r}=process;for(let s=0;s<n.maxRetries;s++){let o=Ot(t,n,r);if(o)return o;if(s<n.maxRetries-1){let i=gt(s,n.baseRetryDelayMs,n.maxRetryDelayMs);St(i)}}throw yt(t,t+n.lockSuffix)}function bt(t){Tt(t.lockPath,t.pid)}function Ae(t,e,n={}){let r=Rt(t,n);try{return e()}finally{bt(r)}}import*as R from"fs";var Ie=3,Nt=50;function w(t,e){let n=t+".tmp";R.writeFileSync(n,e,"utf8");let r;for(let s=0;s<Ie;s++)try{R.renameSync(n,t);return}catch(o){r=o;let i=o.code;if(i==="EPERM"||i==="EBUSY"||i==="EACCES"){if(s<Ie-1){let a=Nt*Math.pow(2,s),c=Date.now()+a,d=!1;for(;Date.now()<c;)if(!d&&Date.now()>=c-10){try{Be("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 At(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function It(t,e){return At(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")},wt={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 It(t,wt[e])}var xt={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"},J=class extends Error{constructor(n,r,s){super(n,s);this.code=r;this.name="PdError",this.category=xt[r]??"execution_failed"}code;category};var x=class extends J{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};var vt=["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"],we={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(we))Object.freeze(t);Object.freeze(we);function E(t){let e=t instanceof Error?t.message:String(t);return e.includes("duplicate column name")||e.includes("no column named")}function F(t,e){return t.prepare("SELECT name FROM sqlite_master WHERE type = 'table' AND name = ?").get(e)!==void 0}function Z(t){if(!F(t,"schema_version"))return;let e=t.prepare("SELECT version FROM schema_version LIMIT 1").get();if(e===void 0){t.prepare("INSERT INTO schema_version (version) VALUES (?)").run(2);return}e.version!==2&&t.prepare("UPDATE schema_version SET version = ?").run(2)}function Lt(t){if(F(t,"tool_calls"))for(let e of["gfi_before","gfi_after"])t.prepare("SELECT name FROM pragma_table_info('tool_calls') WHERE name = ?").get(e)!==void 0&&t.exec(`ALTER TABLE tool_calls DROP COLUMN ${e}`);F(t,"signal_confirmations")&&t.prepare("UPDATE signal_confirmations SET status = 'abandoned', resolved_at = ?, resolution = ? WHERE status = 'pending' AND suggested_type = 'empathy'").run(new Date().toISOString(),"gfi_removal"),Z(t)}function xe(t,e={}){let n=[],r=[...vt];t.exec("CREATE TABLE IF NOT EXISTS schema_version (version INTEGER NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS ingest_checkpoint (source_key TEXT PRIMARY KEY, imported_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sessions (session_id TEXT PRIMARY KEY, started_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS assistant_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, run_id TEXT NOT NULL, provider TEXT NOT NULL, model TEXT NOT NULL, raw_text TEXT, sanitized_text TEXT NOT NULL, usage_json TEXT NOT NULL, empathy_signal_json TEXT NOT NULL, blob_ref TEXT, raw_excerpt TEXT, stop_reason TEXT, thinking_blocks_count INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS user_turns (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, turn_index INTEGER NOT NULL, raw_text TEXT, blob_ref TEXT, raw_excerpt TEXT, correction_detected INTEGER NOT NULL DEFAULT 0, correction_cue TEXT, references_assistant_turn_id INTEGER, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS tool_calls (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, tool_name TEXT NOT NULL, outcome TEXT NOT NULL, duration_ms INTEGER, exit_code INTEGER, error_type TEXT, error_message TEXT, params_json TEXT NOT NULL, result_preview TEXT, created_at TEXT NOT NULL, project_dir TEXT, host_kind TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS pain_events (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, source TEXT NOT NULL, score REAL NOT NULL, reason TEXT, severity TEXT, origin TEXT, confidence REAL, text TEXT, canonical_pain_id TEXT, runtime_task_id TEXT, host_kind TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS gate_blocks (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, tool_name TEXT NOT NULL, file_path TEXT, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS trust_changes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT, previous_score REAL NOT NULL, new_score REAL NOT NULL, delta REAL NOT NULL, reason TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS principle_events (id INTEGER PRIMARY KEY AUTOINCREMENT, principle_id TEXT, event_type TEXT NOT NULL, payload_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS task_outcomes (id INTEGER PRIMARY KEY AUTOINCREMENT, session_id TEXT NOT NULL, task_id TEXT, outcome TEXT NOT NULL, summary TEXT, principle_ids_json TEXT NOT NULL, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS correction_samples (sample_id TEXT PRIMARY KEY, session_id TEXT NOT NULL, bad_assistant_turn_id INTEGER NOT NULL, user_correction_turn_id INTEGER NOT NULL, recovery_tool_span_json TEXT NOT NULL, diff_excerpt TEXT NOT NULL, principle_ids_json TEXT NOT NULL, quality_score REAL NOT NULL, review_status TEXT NOT NULL, export_mode TEXT NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS sample_reviews (id INTEGER PRIMARY KEY AUTOINCREMENT, sample_id TEXT NOT NULL, review_status TEXT NOT NULL, note TEXT, created_at TEXT NOT NULL)"),t.exec("CREATE TABLE IF NOT EXISTS signal_confirmations (id TEXT PRIMARY KEY, session_id TEXT NOT NULL, user_turn_rowid INTEGER NOT NULL UNIQUE, occurrence_id TEXT NOT NULL, excerpt TEXT NOT NULL, terms_json TEXT NOT NULL, suggested_type TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending' CHECK (status IN ('pending','confirmed','rejected','abandoned')), attempts INTEGER NOT NULL DEFAULT 0, created_at TEXT NOT NULL, resolved_at TEXT, resolution TEXT)"),t.exec("CREATE TABLE IF NOT EXISTS exports_audit (id INTEGER PRIMARY KEY AUTOINCREMENT, export_kind TEXT NOT NULL, mode TEXT NOT NULL, approved_only INTEGER NOT NULL, file_path TEXT NOT NULL, row_count INTEGER NOT NULL, created_at TEXT NOT NULL)");try{t.exec("ALTER TABLE pain_events ADD COLUMN text TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN canonical_pain_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN runtime_task_id TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE pain_events ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN stop_reason TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE assistant_turns ADD COLUMN thinking_blocks_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN result_preview TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN tool_use_id TEXT")}catch(s){if(!E(s))throw s}t.exec("CREATE INDEX IF NOT EXISTS idx_tool_calls_session_tool_use_id ON tool_calls(session_id, tool_use_id)");try{t.exec("ALTER TABLE tool_calls ADD COLUMN project_dir TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE tool_calls ADD COLUMN host_kind TEXT")}catch(s){if(!E(s))throw s}if(t.exec("CREATE UNIQUE INDEX IF NOT EXISTS idx_pain_events_canonical_pain_id ON pain_events(canonical_pain_id) WHERE canonical_pain_id IS NOT NULL"),F(t,"evolution_tasks")){try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN task_kind TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN priority TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN retry_count INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN max_retries INTEGER")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN last_error TEXT")}catch(s){if(!E(s))throw s}try{t.exec("ALTER TABLE evolution_tasks ADD COLUMN result_ref TEXT")}catch(s){if(!E(s))throw s}}return Lt(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 Q from"path";import*as ve from"os";var kt=[/(^|[/\\])fake([/\\]|$)/i,/(^|[/\\])mock([/\\]|$)/i,/(^|[/\\])tmp[/\\]fake-/i],Ct=Q.join(ve.tmpdir(),".pd-test-quarantine");function Dt(t){if(!t)return!1;let e=t.replace(/\\/g,"/");return kt.some(n=>n.test(e))}function Le(t){if(!t||!(process.env.NODE_ENV==="test"||!!process.env.VITEST)||!Dt(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 Q.join(Ct,n)}var Mt=16*1024,jt=5e3,Ut=7,Ft=1440*60*1e3,Bt="trajectory-blob-prune.json",ke=!1;function te(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Xt(t){return!te(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 Wt(t){let e=xe(t,{views:!0});return{tables:e.tables,warnings:e.warnings}}function _(){return new Date().toISOString()}function b(t){return JSON.stringify(t??{})}function Ce(t){try{return f.existsSync(t)?f.statSync(t).size:0}catch{return 0}}function $t(t){return t.length>240?`${t.slice(0,237)}...`:t}function De(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 Ht(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 B=class{workspaceDir;stateDir;dbPath;blobDir;exportDir;blobInlineThresholdBytes;orphanBlobGraceMs;db;constructor(e){this.workspaceDir=Le(h.resolve(e.workspaceDir)),this.stateDir=O(this.workspaceDir,"STATE_DIR"),this.dbPath=O(this.workspaceDir,"TRAJECTORY_DB"),this.blobDir=O(this.workspaceDir,"TRAJECTORY_BLOBS_DIR"),this.exportDir=O(this.workspaceDir,"EXPORTS_DIR"),this.blobInlineThresholdBytes=e.blobInlineThresholdBytes??Mt,this.orphanBlobGraceMs=Math.max(0,(e.orphanBlobGraceDays??Ut)*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 Pt(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??jt)}`),this.initSchema(),this.importLegacyArtifacts(),this.maybePruneUnreferencedBlobs()}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
@@ -156,13 +156,13 @@ var Be=(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 v(e);let i=this.db.prepare(`
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 v(`${e} (after update)`);return{sampleId:String(i.sample_id),sessionId:String(i.session_id),badAssistantTurnId:Number(i.bad_assistant_turn_id),userCorrectionTurnId:Number(i.user_correction_turn_id),recoveryToolSpanJson:String(i.recovery_tool_span_json),diffExcerpt:String(i.diff_excerpt??""),principleIdsJson:String(i.principle_ids_json??"[]"),qualityScore:Number(i.quality_score),reviewStatus:i.review_status,exportMode:i.export_mode,createdAt:String(i.created_at),updatedAt:String(i.updated_at)}}enqueueSignalConfirmation(e){let n=`sq_${ee.createHash("sha256").update(`${e.sessionId}:${e.userTurnRowid}`).digest("hex").slice(0,12)}`;this.withWrite(()=>{this.db.prepare(`
165
+ `).get(e);if(!i)throw new x(`${e} (after update)`);return{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_${ee.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
@@ -270,4 +270,4 @@ var Be=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(
270
270
  SELECT blob_ref FROM assistant_turns WHERE blob_ref IS NOT NULL
271
271
  UNION
272
272
  SELECT blob_ref FROM user_turns WHERE blob_ref IS NOT NULL
273
- `).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 a=h.join(this.blobDir,i),c;try{c=f.statSync(a)}catch{continue}c.isFile()&&(this.orphanBlobGraceMs>0&&r-c.mtimeMs<this.orphanBlobGraceMs||(o+=c.size,s+=1,f.rmSync(a,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ae(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},x=class{static instances=new Map;static get(e,n={}){let r=h.resolve(e),s=this.instances.get(r);if(s)return s;let o=new B({workspaceDir:r,...n});return this.instances.set(r,o),o}static dispose(e){let n=h.resolve(e),r=this.instances.get(n);r&&(r.dispose(),this.instances.delete(n))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,n,r={}){let s=h.resolve(e),o=this.instances.get(s);if(o)return n(o);let i=new B({workspaceDir:s,...r});try{return n(i)}finally{i.dispose()}}};var Pe=["file-header-patch"];function Yt(t){return typeof t=="string"&&Pe.includes(t)}var Kt=new Set(["__proto__","constructor","prototype"]);function Gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qt(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(!Gt(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(Kt.has(r.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=r.canonicalKind;if(!fe(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...Y].join("|")}, got ${String(o)}`);return}let i=r.writePayloadFormat;if(i!==void 0){if(!Yt(i)){e.push(`toolSemanticMappings[${s}].writePayloadFormat must be one of ${Pe.join("|")}, got ${String(i)}`);return}if(o!=="write"){e.push(`toolSemanticMappings[${s}].writePayloadFormat is only valid for canonicalKind 'write' (got '${o}')`);return}}let a=n.get(r.rawToolName);if(a!==void 0&&a.kind!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${r.rawToolName}' declared twice with conflicting kinds (${a.kind} vs ${o})`);return}if(a!==void 0&&a.writePayloadFormat!==i){e.push(`toolSemanticMappings[${s}]: rawToolName '${r.rawToolName}' declared twice with conflicting writePayloadFormat (${a.writePayloadFormat??"unset"} vs ${i??"unset"})`);return}n.set(r.rawToolName,{kind:o,...i!==void 0?{writePayloadFormat:i}:{}})}),{valid:e.length===0,errors:e}}function Me(t){let e,n=new Set,r=new Map,s=[];if(t===void 0)e=P;else{let o=qt(t);if(!o.valid)return{ok:!1,errors:o.errors};let i={...P};for(let a of t)i[a.rawToolName]=a.canonicalKind,n.add(a.rawToolName),a.writePayloadFormat!==void 0&&r.set(a.rawToolName,a.writePayloadFormat);s=Object.freeze(t.map(a=>Object.freeze({rawToolName:a.rawToolName,canonicalKind:a.canonicalKind,...a.writePayloadFormat!==void 0?{writePayloadFormat:a.writePayloadFormat}:{}}))),e=Object.freeze(i)}return{ok:!0,registry:{version:1,hasHostLayer:n.size>0,hasHostTool(o){return typeof o!="string"?!1:n.has(o)},hostMappings(){return s},resolveWritePayloadFormat(o){if(typeof o=="string")return r.get(o)},lookup(o){return typeof o!="string"||!Object.hasOwn(e,o)?null:e[o]??null},resolve(o){return this.lookup(o)??"other"}}}}var je=["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"],ne=["write","edit"],re=["apply_patch"],X=[...ne,...re],L=["exec"],zt=[...L],W=["sessions_spawn"],Vt=[...X],Jt=[...X,...L,...W],Zt=[...je],qn=new Set(je),zn=new Set(X),Vn=new Set(zt),Jn=new Set(L),Zn=new Set(W),Qn=new Set(Vt),er=new Set(Jt),tr=new Set(Zt),nr=new Set([...X]);function $(t,e,n){return t.map(r=>({rawToolName:r,canonicalKind:e,...n!==void 0?{writePayloadFormat:n}:{}}))}var Qt=Object.freeze([...$(L,"execute"),...$(ne,"write"),...$(re,"write","file-header-patch"),...$(W,"agent")]),se=Me(Qt);if(!se.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${se.errors.join("; ")}`);var Ue=se.registry;var oe=class extends U{constructor(e){super({source:x.get(e.workspaceDir),toolSemantics:Ue})}};export{oe as BehaviorExamplePackAssembler,x as RuleHostEvidenceRegistry};
273
+ `).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 a=h.join(this.blobDir,i),c;try{c=f.statSync(a)}catch{continue}c.isFile()&&(this.orphanBlobGraceMs>0&&r-c.mtimeMs<this.orphanBlobGraceMs||(o+=c.size,s+=1,f.rmSync(a,{force:!0})))}return{removedFiles:s,reclaimedBytes:o}}withWrite(e){return Ae(this.dbPath,e,{lockSuffix:".trajectory.lock",lockStaleMs:3e4})}},v=class{static instances=new Map;static get(e,n={}){let r=h.resolve(e),s=this.instances.get(r);if(s)return s;let o=new B({workspaceDir:r,...n});return this.instances.set(r,o),o}static dispose(e){let n=h.resolve(e),r=this.instances.get(n);r&&(r.dispose(),this.instances.delete(n))}static clear(){for(let e of this.instances.values())e.dispose();this.instances.clear()}static use(e,n,r={}){let s=h.resolve(e),o=this.instances.get(s);if(o)return n(o);let i=new B({workspaceDir:s,...r});try{return n(i)}finally{i.dispose()}}};var Pe=["file-header-patch"];function Yt(t){return typeof t=="string"&&Pe.includes(t)}var Kt=new Set(["__proto__","constructor","prototype"]);function Gt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function qt(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(!Gt(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(Kt.has(r.rawToolName)){e.push(`toolSemanticMappings[${s}].rawToolName must not be a prototype-pollution key`);return}let o=r.canonicalKind;if(!fe(o)){e.push(`toolSemanticMappings[${s}].canonicalKind must be one of ${[...Y].join("|")}, got ${String(o)}`);return}let i=r.writePayloadFormat;if(i!==void 0){if(!Yt(i)){e.push(`toolSemanticMappings[${s}].writePayloadFormat must be one of ${Pe.join("|")}, got ${String(i)}`);return}if(o!=="write"){e.push(`toolSemanticMappings[${s}].writePayloadFormat is only valid for canonicalKind 'write' (got '${o}')`);return}}let a=n.get(r.rawToolName);if(a!==void 0&&a.kind!==o){e.push(`toolSemanticMappings[${s}]: rawToolName '${r.rawToolName}' declared twice with conflicting kinds (${a.kind} vs ${o})`);return}if(a!==void 0&&a.writePayloadFormat!==i){e.push(`toolSemanticMappings[${s}]: rawToolName '${r.rawToolName}' declared twice with conflicting writePayloadFormat (${a.writePayloadFormat??"unset"} vs ${i??"unset"})`);return}n.set(r.rawToolName,{kind:o,...i!==void 0?{writePayloadFormat:i}:{}})}),{valid:e.length===0,errors:e}}function Me(t){let e,n=new Set,r=new Map,s=[];if(t===void 0)e=P;else{let o=qt(t);if(!o.valid)return{ok:!1,errors:o.errors};let i={...P};for(let a of t)i[a.rawToolName]=a.canonicalKind,n.add(a.rawToolName),a.writePayloadFormat!==void 0&&r.set(a.rawToolName,a.writePayloadFormat);s=Object.freeze(t.map(a=>Object.freeze({rawToolName:a.rawToolName,canonicalKind:a.canonicalKind,...a.writePayloadFormat!==void 0?{writePayloadFormat:a.writePayloadFormat}:{}}))),e=Object.freeze(i)}return{ok:!0,registry:{version:1,hasHostLayer:n.size>0,hasHostTool(o){return typeof o!="string"?!1:n.has(o)},hostMappings(){return s},resolveWritePayloadFormat(o){if(typeof o=="string")return r.get(o)},lookup(o){return typeof o!="string"||!Object.hasOwn(e,o)?null:e[o]??null},resolve(o){return this.lookup(o)??"other"}}}}var je=["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"],ne=["write","edit"],re=["apply_patch"],X=[...ne,...re],L=["exec"],zt=[...L],W=["sessions_spawn"],Vt=[...X],Jt=[...X,...L,...W],Zt=[...je],qn=new Set(je),zn=new Set(X),Vn=new Set(zt),Jn=new Set(L),Zn=new Set(W),Qn=new Set(Vt),er=new Set(Jt),tr=new Set(Zt),nr=new Set([...X]);function $(t,e,n){return t.map(r=>({rawToolName:r,canonicalKind:e,...n!==void 0?{writePayloadFormat:n}:{}}))}var Qt=Object.freeze([...$(L,"execute"),...$(ne,"write"),...$(re,"write","file-header-patch"),...$(W,"agent")]),se=Me(Qt);if(!se.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${se.errors.join("; ")}`);var Ue=se.registry;var oe=class extends U{constructor(e){super({source:v.get(e.workspaceDir),toolSemantics:Ue})}};export{oe as BehaviorExamplePackAssembler,v as RuleHostEvidenceRegistry};
@@ -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": "4.1.1",
5
+ "version": "4.1.2",
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": "4.1.1",
3
+ "version": "4.1.2",
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": "^7.6.1",
80
- "@principles/host-runtime": "^4.1.1",
79
+ "@principles/core": "^7.6.2",
80
+ "@principles/host-runtime": "^4.1.2",
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": "8582e5dde27a582c63f3ad6804675a84c0d0c11e"
112
+ "gitHead": "80b43dd1b98d261b580215cff8b815594606178c"
113
113
  }
@@ -1,203 +0,0 @@
1
- /**
2
- * Rule Host — Constrained execution layer for active code implementations
3
- *
4
- * PURPOSE: Load active code implementations from the SQLite activations table
5
- * (code_tool_hook channel), execute them in a constrained node:vm context,
6
- * and merge their decisions.
7
- *
8
- * ARCHITECTURE (PRI-436):
9
- * - SQLite is the SOLE production source of active RuleCode
10
- * - No filesystem ledger or implementation asset reads occur during evaluation
11
- * - Constructor takes stateDir for API compatibility (no longer used for impl loading)
12
- * - workspaceDir enables reading code_tool_hook activations from SQLite
13
- * - evaluate(input) loads active code implementations and runs them
14
- * - Each implementation executes in an isolated vm context with minimal helpers
15
- * - Decision merge: block short-circuits, requireApproval collects, allow is implicit
16
- *
17
- * SECURITY CONSTRAINTS (T-12-01, T-12-04):
18
- * - Candidate code loads through a dedicated vm context, not the host realm
19
- * - No importModuleDynamically callback
20
- * - Helpers are a frozen object — implementations cannot modify the helper surface
21
- *
22
- * CONSERVATIVE DEGRADATION (T-12-02, D-08):
23
- * - On ANY host error (load failure, eval error, vm error): return undefined
24
- * - Never throw, never bypass downstream gates (Progressive Gate, Edit Verification)
25
- */
26
- import type { RuleHostInput, RuleHostResult } from '@principles/core/runtime';
27
- import type { RuleHostLogger } from '@principles/core/runtime';
28
- export type { RuleHostLogger } from '@principles/core/runtime';
29
- export interface RuleHostOptions {
30
- /** Workspace directory for SQLite access. Required for RuleHost to load active code_tool_hook activations. */
31
- workspaceDir?: string;
32
- }
33
- type RuleHostActivationMode = 'shadow' | 'live';
34
- export interface RuleHostObservedDecision extends RuleHostResult {
35
- readonly activationId: string;
36
- }
37
- /**
38
- * PRI-491 — A structured record of an activation that was skipped at load
39
- * time (flag-off v2, unsupported action, unsupported context version,
40
- * missing target_ref, content_json not an object, no implementationCode,
41
- * or duplicate active activation for target_ref).
42
- *
43
- * Unlike compile/load failures (which emit rulehost_unhealthy), skipped
44
- * activations have a configuration/flag reason — the RuleCode itself may be
45
- * valid, but the runtime chose not to execute it. Duplicate activations are
46
- * a special case: they ALSO emit rulehost_unhealthy (for telemetry), but are
47
- * surfaced in skippedActivations so the owner can observe and act (rc-9).
48
- *
49
- * ERR-002 (rc-9): every skip carries a reason + nextAction, never silent.
50
- */
51
- export interface SkippedActivation {
52
- readonly activationId: string;
53
- readonly ruleId: string;
54
- /**
55
- * The mode the activation WOULD have had if loaded. Optional for cases
56
- * where the action itself is unrecognized (neither shadow nor live).
57
- */
58
- readonly mode?: RuleHostActivationMode;
59
- readonly reason: string;
60
- readonly nextAction: string;
61
- }
62
- export interface RuleHostEvaluationReport {
63
- readonly liveDecision: RuleHostResult | undefined;
64
- /**
65
- * P1 (ISSUE-023): live 聚合决策的溯源 — 贡献该决策的 live activation id
66
- * (经 ruleId 反查 implementationSources)。审计开放项: 414 次 live-mode
67
- * 评估无法对账到具体规则,因为 live 事件不带 activationId。
68
- */
69
- readonly liveDecisionActivationId?: string;
70
- readonly shadowDecisions: readonly RuleHostObservedDecision[];
71
- /**
72
- * PRI-491 — Activations that were skipped at load time. Empty when all
73
- * active activations loaded successfully. Each entry carries a structured
74
- * reason + nextAction so the owner can act without reading SQLite rows.
75
- */
76
- readonly skippedActivations: readonly SkippedActivation[];
77
- /**
78
- * PRI-567 — Number of live-mode implementations loaded for this evaluation.
79
- * Lets the gate distinguish "live rule evaluated → allow" from
80
- * "no live rules armed at all" (which previously both logged decision='allow',
81
- * making enforcement statistics read as if rules were active when none were).
82
- */
83
- readonly liveRulesLoaded: number;
84
- /** Distinguishes an empty live set from a failed evaluation. */
85
- readonly evaluationStatus: 'ok' | 'failed';
86
- }
87
- export declare class RuleHost {
88
- private readonly stateDir;
89
- private logger;
90
- private readonly workspaceDir;
91
- private readonly implementationSources;
92
- private activationFingerprint;
93
- private cachedImplementations;
94
- /**
95
- * PRI-491: Cached skipped activations from the last load. Returned alongside
96
- * cachedImplementations on fingerprint hit so evaluateDetailed can surface
97
- * them without re-scanning SQLite.
98
- */
99
- private cachedSkipped;
100
- private sqliteConnection;
101
- /**
102
- * R2-RH-002: Guards the "armed but empty" warn so it fires at most once per
103
- * RuleHost instance. Without this, the 0-rules path (workspaceDir missing OR
104
- * zero active code_tool_hook activations) returns [] silently on every
105
- * evaluation — an observability gap (rc-9-no-silent-fallback). The warn is
106
- * NOT a degradation fallback (RuleHost correctly has no opinion when empty);
107
- * it makes the empty-armed state visible so operators can investigate why
108
- * no live rules are loaded.
109
- */
110
- private emptyLoadWarnEmitted;
111
- /**
112
- * PRI-1044 step 3-1 (LOCKSTEP twin of the host-runtime gate): an ACTIVE
113
- * activation whose pi_artifacts row is gone is dropped by the INNER JOIN in
114
- * `_loadFromActivationsTable`, so the RuleHost silently enforces fewer rules
115
- * than the Owner armed. Suppression is keyed on the dangling descriptor SET
116
- * (not a one-shot latch, which would never re-arm on this cached singleton
117
- * instance): an unchanged set is not re-logged, a changed set is, and an
118
- * empty set clears the signature so a later recurrence warns again.
119
- */
120
- private danglingArtifactSignature;
121
- constructor(stateDir: string, logger?: RuleHostLogger, options?: RuleHostOptions);
122
- /**
123
- * Update the logger sink on a cached RuleHost instance.
124
- *
125
- * WorkspaceContext caches the RuleHost singleton, but each gate call may
126
- * pass a request-level logger. Without this update, warn/unhealthy logs
127
- * would forever go to the first logger sink, making the new path hard to
128
- * debug.
129
- */
130
- updateLogger(logger: RuleHostLogger): void;
131
- /**
132
- * Evaluate the input against all active code implementations.
133
- *
134
- * Returns:
135
- * - undefined when no active code implementations exist (no opinion)
136
- * - undefined when all implementations return allow or matched=false
137
- * - { decision: 'block', ... } when any implementation returns block (short-circuits)
138
- * - { decision: 'requireApproval', ... } when any implementation returns requireApproval
139
- */
140
- evaluate(input: RuleHostInput): RuleHostResult | undefined;
141
- dispose(): void;
142
- evaluateDetailed(input: RuleHostInput): RuleHostEvaluationReport;
143
- /**
144
- * Load active code implementations from the SQLite activations table.
145
- *
146
- * PRI-436: SQLite is the SOLE production source. The filesystem ledger
147
- * (principle-tree-ledger) and implementation asset paths have been deleted.
148
- * No fallback, no dual-source, no deprecated adapter.
149
- *
150
- * Source: activations table (code_tool_hook channel, deactivated_at IS NULL)
151
- * → JOIN pi_artifacts for content_json → extract implementationCode → compile
152
- */
153
- private _loadActiveCodeImplementations;
154
- /**
155
- * R2-RH-002: Emit the "armed but empty" warn at most once per RuleHost
156
- * instance. The warn is cached via `emptyLoadWarnEmitted` so repeated
157
- * evaluations (which all hit the empty path) do not spam the log.
158
- *
159
- * This is an observability signal, NOT a degradation fallback — RuleHost
160
- * correctly returns "no opinion" when there are no active rules. The warn
161
- * makes the empty state visible so operators can distinguish "RuleHost is
162
- * working but has no rules" from "RuleHost is broken" (rc-9-no-silent-fallback).
163
- */
164
- private _emitEmptyLoadWarn;
165
- /**
166
- * Load active code implementations from the activations table (code_tool_hook channel).
167
- *
168
- * For each activation record:
169
- * 1. Query the pi_artifacts table for the artifact content
170
- * 2. Parse content_json to extract implementationCode (treated as unknown, EP-01)
171
- * 3. Compile via loadRuleImplementationModule (isolated vm context)
172
- *
173
- * PRI-436 invariant: at most one active activation per rule (target_ref).
174
- * Duplicate active activations for the same target_ref are ALL skipped
175
- * (zero executions) and emit structured unhealthy evidence via logger.warn
176
- * (Runtime Contract Rule 9: graceful degradation includes a reason).
177
- *
178
- * All data from SQLite is treated as unknown and validated before use.
179
- */
180
- private _loadFromActivationsTable;
181
- /**
182
- * PRI-437: Record an unhealthy activation state to EventLog.
183
- *
184
- * This makes compile/load failures visible to CLI (pd runtime health) and
185
- * Console API — NOT just a logger.warn that's silently skipped.
186
- *
187
- * ERR-002: degradation includes a reason and nextAction (not silent).
188
- * Failures in EventLog recording are caught and logged (never throw).
189
- */
190
- private _recordUnhealthy;
191
- /**
192
- * PRI-491: Record a skipped activation to EventLog.
193
- *
194
- * Unlike _recordUnhealthy (compile/load failures), skipped activations have
195
- * a configuration/flag reason — the RuleCode itself may be valid, but the
196
- * runtime chose not to execute it (flag-off v2, unsupported context version,
197
- * unsupported action, content_json not object, no implementationCode).
198
- *
199
- * ERR-002: degradation includes a reason and nextAction (rc-9-no-silent-fallback).
200
- * Failures in EventLog recording are caught and logged (never throw).
201
- */
202
- private _recordSkipped;
203
- }