create-principles-disciple 1.145.38 → 1.145.41
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/_release/product-identity.json +1 -1
- package/codex-adapter/dist/ingestion/catch-up.d.ts +1 -1
- package/codex-adapter/dist/ingestion/catch-up.js +10 -2
- package/codex-adapter/dist/pd-hook.js +6 -2
- package/codex-adapter/dist/worker/workspace-worker.js +2 -1
- package/core/package.json +1 -1
- package/dist/installer.d.ts +20 -6
- package/dist/installer.d.ts.map +1 -1
- package/dist/installer.js +80 -30
- package/dist/installer.js.map +1 -1
- package/dist/installers/workbuddy-host-installer.d.ts +36 -0
- package/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
- package/dist/installers/workbuddy-host-installer.js +103 -8
- package/dist/installers/workbuddy-host-installer.js.map +1 -1
- package/dist/utils/config-file-io.d.ts +10 -2
- package/dist/utils/config-file-io.d.ts.map +1 -1
- package/dist/utils/config-file-io.js +32 -9
- package/dist/utils/config-file-io.js.map +1 -1
- package/host-runtime/dist/workbuddy-worker-status.js +4 -1
- package/host-runtime/package.json +1 -1
- package/package.json +10 -3
- package/pd-cli/dist/commands/health-codex-install.d.ts +4 -0
- package/pd-cli/dist/commands/health-codex-install.d.ts.map +1 -1
- package/pd-cli/dist/commands/health-codex-install.js +2 -2
- package/pd-cli/dist/commands/health-codex-install.js.map +1 -1
- package/pd-cli/dist/commands/health-codex.d.ts.map +1 -1
- package/pd-cli/dist/commands/health-codex.js +30 -2
- package/pd-cli/dist/commands/health-codex.js.map +1 -1
- package/pd-cli/dist/commands/pain-explicit.d.ts.map +1 -1
- package/pd-cli/dist/commands/pain-explicit.js +20 -20
- package/pd-cli/dist/commands/pain-explicit.js.map +1 -1
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +1 -1
- package/plugin/dist/openclaw.plugin.json +1 -1
- package/plugin/openclaw.plugin.json +1 -1
- package/plugin/package.json +1 -1
- package/release-manager/dist/installer.d.ts +20 -6
- package/release-manager/dist/installer.d.ts.map +1 -1
- package/release-manager/dist/installer.js +80 -30
- package/release-manager/dist/installer.js.map +1 -1
- package/release-manager/dist/installers/workbuddy-host-installer.d.ts +36 -0
- package/release-manager/dist/installers/workbuddy-host-installer.d.ts.map +1 -1
- package/release-manager/dist/installers/workbuddy-host-installer.js +103 -8
- package/release-manager/dist/installers/workbuddy-host-installer.js.map +1 -1
- package/release-manager/dist/utils/config-file-io.d.ts +10 -2
- package/release-manager/dist/utils/config-file-io.d.ts.map +1 -1
- package/release-manager/dist/utils/config-file-io.js +32 -9
- package/release-manager/dist/utils/config-file-io.js.map +1 -1
- package/release-manager/package.json +10 -3
- package/workbuddy-adapter/dist/pd-hook.js +5 -1
- package/workbuddy-adapter/dist/worker/workspace-worker.js +2 -1
package/plugin/dist/bundle.js
CHANGED
|
@@ -2194,7 +2194,7 @@ try {
|
|
|
2194
2194
|
`).get(f);oL(g)&&typeof g.content_json=="string"&&(m=`sha256:${jX("sha256").update(g.content_json,"utf8").digest("hex")}`)}let h={activationId:s,idempotencyKey:p.idempotency_key??null,artifactId:f,channel:p.channel??null,action:p.action??null,activatedAt:p.activated_at??null,artifactDigest:m};return{activationId:s,...typeof p.idempotency_key=="string"?{idempotencyKey:p.idempotency_key}:{},...f!==null?{artifactId:f}:{},...typeof p.channel=="string"?{channel:p.channel}:{},...typeof p.activated_at=="string"?{activatedAt:p.activated_at}:{},sourceSnapshotDigest:`sha256:${jX("sha256").update(JSON.stringify(h),"utf8").digest("hex")}`}}catch{return null}finally{try{c?.close()}catch{}}}function o(a,s){let c=null;try{c=new On({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let u=c.getDb().prepare(`
|
|
2195
2195
|
SELECT activation_ref_json, content_ref_json
|
|
2196
2196
|
FROM intervention_evidence_records WHERE source_kind = ? AND source_locator = ? AND observation_key = ?
|
|
2197
|
-
`).get(s.sourceKind,s.sourceLocator,s.observationKey);if(!oL(u)||typeof u.activation_ref_json!="string"||typeof u.content_ref_json!="string")return null;let l=JSON.parse(u.activation_ref_json),p=JSON.parse(u.content_ref_json),f=g=>typeof g=="string"&&/^sha256:[a-f0-9]{64}$/.test(g);if(!oL(l)||typeof l.activationId!="string"||!f(l.sourceSnapshotDigest)||!oL(p)||typeof p.principleId!="string"||p.resolution!=="resolved"&&p.resolution!=="revision_reference_unresolved"||p.resolution==="resolved"&&!f(p.payloadDigest)||p.resolution==="revision_reference_unresolved"&&p.payloadDigest!==void 0||l.activationId!==s.activationId||p.principleId!==s.principleId||typeof l.artifactId=="string"&&p.artifactId!==l.artifactId||s.artifactId!==void 0&&(l.artifactId!==s.artifactId||p.artifactId!==s.artifactId))return null;let m={activationId:l.activationId,sourceSnapshotDigest:l.sourceSnapshotDigest,...typeof l.idempotencyKey=="string"?{idempotencyKey:l.idempotencyKey}:{},...typeof l.artifactId=="string"?{artifactId:l.artifactId}:{},...typeof l.channel=="string"?{channel:l.channel}:{},...typeof l.activatedAt=="string"?{activatedAt:l.activatedAt}:{}},h={principleId:p.principleId,resolution:p.resolution,...typeof p.artifactId=="string"?{artifactId:p.artifactId}:{},...typeof p.version=="string"?{version:p.version}:{},...typeof p.payloadDigest=="string"?{payloadDigest:p.payloadDigest}:{},...typeof p.approvalRef=="string"?{approvalRef:p.approvalRef}:{}};return{activationRef:m,contentRef:h}}catch{return null}finally{try{c?.close()}catch{}}}return{appendObservationBatch:r,evidenceScopeIdFor:e,resolveInterventionContentRef:n,resolveActivationOccurrenceRef:i,existingObservationRefs:o}}var _Se=null;function VW(){return _Se||(_Se=iGn()),_Se}SC();h0();var oGn=new Set(["success","failure","blocked"]);function aGn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sGn(t){return typeof t=="string"&&oGn.has(t)}function zW(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function aL(t,e,n){let{projectDir:r,toolSemantics:i}=n,o=[];for(let a of t){let{toolName:s}=a;if(typeof s!="string"||s.length===0)return zW(`row id=${a.id}: tool_name must be a non-empty string`);let{outcome:c}=a;if(!sGn(c))return zW(`row id=${a.id}: outcome "${a.outcome}" is not a valid RuleToolOutcome`);let u=a.paramsJson;if(typeof u!="string")return zW(`row id=${a.id}: params_json must be a string`);let l;try{l=JSON.parse(u)}catch{return zW(`row id=${a.id}: params_json is not valid JSON`)}if(!aGn(l))return zW(`row id=${a.id}: params_json must parse to a non-array object`);let p=i.resolve(s),{normalizedPath:f}=zp(s,l,r,{canonicalKind:p});o.push({sequenceId:a.id,toolName:s,canonicalKind:p,normalizedPath:f===""?null:f,paramsSummary:l,outcome:c})}return{status:"available",truncated:e,calls:o}}var cGn=3,uGn=5,lGn=100,yEt=new Set(["__proto__","constructor","prototype"]);function GX(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw ev("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function dGn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pGn(t){for(let e of Object.keys(t))if(yEt.has(e))return!1;return!0}function fGn(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>cGn)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 AEt(t,e){if(!t)throw ev("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function mGn(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(!dGn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!pGn(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 hGn(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var gGn=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function AGn(t){if(t.length<20)return!1;for(let e of gGn)if(e.test(t))return!0;return!1}function yGn(t,e){let n=[],r={};for(let i of Object.keys(t)){if(yEt.has(i))continue;let o=t[i];if(typeof o!="string"){r[i]=o;continue}if(hGn(o)&&!o.startsWith(e)){r[i]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${i}" (outside project tree)`);continue}if(AGn(o)){r[i]="<redacted:secret>",n.push(`redacted possible secret in field "${i}"`);continue}r[i]=o}return{redacted:r,notes:n}}var YW=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let n=GX(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!n)throw ev("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);fGn(e);let r=AEt(GX(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),i=e.positiveToolCallIds.map(p=>AEt(GX(`evidence row read for id=${p}`,()=>this.db.getRuleHostEvidenceRow(p)),p));for(let p of[r,...i])if(p.sessionId!==n.sessionId)throw ev("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${p.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],a={projectDir:e.projectDir,redactionNotes:o},s=this.buildSelectedCase(r,"negative",a),c=i.map(p=>this.buildSelectedCase(p,"positive",a)),u={sourceNegativeCase:s,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...i.map(p=>`tool_call:${p.id}`)].slice(0,uGn),redactionNotes:o},l=zg(u);if(!l.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${l.errors.join("; ")} (ERR-069 fail loud)`);return u}buildSelectedCase(e,n,r){let{projectDir:i,redactionNotes:o}=r,a=mGn(e,n,n==="negative"?"block":"allow"),s=yGn(a.params,i);o.push(...s.notes);let c=GX(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,lGn)),u=aL(c.rows,c.truncated,{projectDir:i,toolSemantics:this.toolSemantics}),l=zp(e.toolName,s.redacted,i,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),p={version:2,history:u,facts:GE(u,l.normalizedPath||null,null)};return{...a,params:s.redacted,ruleContext:p}}};import kdo from"better-sqlite3";h0();var Ndo=2*1024*1024;var Hdo=1024*1024;var Gdo=1024*1024;var qX=["before_prompt_build","before_tool_call","after_tool_call"],sL=class extends Error{reason;nextAction;constructor(e,n){super(`${e}: ${n}`),this.reason=e,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function vGn(t,e){switch(t.kind){case"before_prompt_build":return e.beforePromptBuild;case"before_tool_call":return e.beforeToolCall;case"after_tool_call":return e.afterToolCall;default:throw new sL("unsupported_host_event",`Only ${qX.join(", ")} are supported by the MVP host runtime`)}}function eS(t){return typeof t=="string"&&t.trim().length>0}function EEt(t){return t.startsWith("/")||t.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(t)}function xGn(t){return!eS(t.context.workspaceDir)||!EEt(t.context.workspaceDir)||!eS(t.context.sessionId)||!eS(t.source)?!1:t.kind==="before_tool_call"||t.kind==="after_tool_call"?eS(t.context.toolName):!0}function _Et(t){return t===void 0||eS(t)}function wGn(t,e){if(e.warnings!==void 0&&(!Array.isArray(e.warnings)||!e.warnings.every(eS))||e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null||Array.isArray(e.metadata))||!eS(e.source)||!_Et(e.reason)||!_Et(e.additionalContext))return!1;let n=e.reason!==void 0,r=e.modifiedInput!==void 0,i=e.additionalContext!==void 0;switch(t.kind){case"before_prompt_build":return(e.decision==="allow"||e.decision==="modify")&&!n&&!r;case"before_tool_call":return e.decision==="observe"?!1:e.decision==="deny"?n&&!r&&!i:n?!1:!r||e.decision==="modify";case"after_tool_call":return e.decision==="observe"&&!n&&!r&&!i;default:return!1}}function bGn(t){return{async dispatch(e){if(!qbe(e)||!xGn(e))throw new sL("invalid_host_event","Decode and validate the host event before dispatch");let n=await vGn(e,t)(e);if(!Kbe(n)||!wGn(e,n))throw new sL("invalid_handler_result",`Handler for ${e.kind} must return a valid HostEventResult`);if(n.source!==e.source)throw new sL("lineage_mismatch",`Handler result source must match event source ${e.source}`);return n},async health(e){return e.trim().length===0?{ok:!1,workspaceDir:e,routes:qX,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:EEt(e)?{ok:!0,workspaceDir:e,routes:qX}:{ok:!1,workspaceDir:e,routes:qX,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function IEt(t={}){let e=v_t({...t.hostKind?{hostKind:t.hostKind}:{},...t.projectDir?{projectDir:t.projectDir}:{},...t.ruleContextProvider?{ruleContextProvider:t.ruleContextProvider}:{},...t.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:t.ruleInputEnrichmentProvider}:{},...t.ruleImplementationRuntime?{implementationRuntime:t.ruleImplementationRuntime}:{},...t.toolSemantics?{toolSemantics:t.toolSemantics}:{}});return bGn({afterToolCall:t.afterToolCall??C_t({...t.painEnrichmentProvider?{painEnrichmentProvider:t.painEnrichmentProvider}:{},...t.painDatabaseFactory?{painDatabaseFactory:t.painDatabaseFactory}:{},...t.hostKind?{hostKind:t.hostKind}:{},...t.projectDir?{projectDir:t.projectDir}:{},...t.events?{events:t.events}:{}}),beforeToolCall:t.beforeToolCall??e,async beforePromptBuild(n){let r=t.hostKind==="openclaw"||t.hostKind==="codex"||t.hostKind==="workbuddy"?t.hostKind:void 0,i=r===void 0?void 0:Gb(mr(n.context.workspaceDir).effective.config.promptBudget,r),o=await nSe({workspaceDir:n.context.workspaceDir,promptBudget:Eg({...i!==void 0?{operatorDeclared:{contextWindowTokens:i}}:{},hostCapacity:n.context.modelContext===void 0?void 0:{contextTokenBudget:n.context.modelContext.contextTokenBudget,contextWindowSource:n.context.modelContext.contextWindowSource},modelIdentity:n.context.modelContext===void 0?void 0:{providerId:n.context.modelContext.modelProviderId,modelId:n.context.modelContext.modelId},catalog:fU()})}),a=[];try{t.events?.recordRuntimeV2ActivationsInjected({sessionId:n.context.sessionId,workspaceDir:n.context.workspaceDir,principleIds:o.principleIds,activationIds:o.activationIds,artifactIds:o.artifactIds,injectedCount:o.principleIds.length,skippedWarnings:o.warnings,injectedCharCount:o.additionalContext.length,budget:o.budget,...t.hostKind==="openclaw"||t.hostKind==="codex"||t.hostKind==="workbuddy"?{hostKind:t.hostKind}:{},eventId:IGn(),...o.truncated!==void 0?{v2Truncated:o.truncated}:{},...n.context.turnId!==void 0?{runId:n.context.turnId}:{},...o.budgetPolicyVersion!==void 0?{budgetPolicyVersion:o.budgetPolicyVersion}:{},...o.budgetCapacitySource!==void 0?{budgetCapacitySource:o.budgetCapacitySource}:{},...o.budgetCapacityStatus!==void 0?{budgetCapacityStatus:o.budgetCapacityStatus}:{},...o.budgetContextWindowTokens!=null?{budgetContextWindowTokens:o.budgetContextWindowTokens}:{},...o.budgetFallbackReason!==void 0?{budgetFallbackReason:o.budgetFallbackReason}:{},...o.selectionPolicy!==void 0?{selectionPolicy:o.selectionPolicy}:{},...o.eligibleCount!==void 0?{eligibleCount:o.eligibleCount}:{},...o.rotationStartIndex!==void 0?{rotationStartIndex:o.rotationStartIndex}:{},...o.droppedActivationIds!==void 0&&o.droppedActivationIds.length>0?{droppedActivationIds:o.droppedActivationIds}:{},...o.oversizedActivationIds!==void 0&&o.oversizedActivationIds.length>0?{oversizedActivationIds:o.oversizedActivationIds}:{}})}catch(s){a.push(`receipt_event_write_failed:${s instanceof Error?s.message.slice(0,200):String(s).slice(0,200)}`)}if(t.beforePromptBuild){let s=await t.beforePromptBuild(n,o);return a.length===0?s:{...s,warnings:[...s.warnings??[],...a]}}return{decision:o.additionalContext.length>0?"modify":"allow",source:n.source,...o.additionalContext.length>0?{additionalContext:o.additionalContext}:{},...a.length>0?{warnings:a}:{}}}})}function My(t){return{source:t.source}}function tS(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,maxTokens:null,baseUrl:null}}function SGn(t){return Yc.some(e=>e===t)}function cL(t,e,n,r){let i=mr(t);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...My(i),...tS(),reason:`Config validation failed: ${i.errors.map(f=>f.reason).join("; ")}`,nextAction:i.errors[0]?.nextAction??"Fix .pd/config.yaml and retry",configErrors:i.errors};let o=i.effective.config;if(!o.features[e]?.enabled)return{enabled:!1,readiness:"disabled",...My(i),...tS(),reason:`${e} is disabled in .pd/config.yaml`,nextAction:`Set features.${e}.enabled=true in .pd/config.yaml to enable`};if(!SGn(n))return{enabled:!1,readiness:"needs_setup",...My(i),...tS(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${Yc.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...My(i),...tS(),reason:`${e} feature flag is enabled but internalAgents.agents.${n}.enabled is false`,nextAction:`Set internalAgents.agents.${n}.enabled=true in .pd/config.yaml, or disable features.${e}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,u=o.runtimeProfiles[c];if(!u)return{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,reason:`Runtime profile '${c}' not found in .pd/config.yaml`,nextAction:`Add runtime profile '${c}' to .pd/config.yaml runtimeProfiles`};if(u.type!=="pi-ai")return{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,runtimeProfileType:u.type,provider:u.provider??null,model:u.model??null,reason:`Runtime profile '${c}' has retired type '${u.type}' (ADR-0029: pi-ai only). Observers require a pi-ai profile with an API key.`,nextAction:`Configure a pi-ai runtime profile for ${n} in .pd/config.yaml (e.g., add a pi-ai profile with provider, model, and apiKeyEnv)`};let l=u.apiKeyEnv??null;return l?Object.hasOwn(process.env,l)&&!!process.env[l]?{enabled:!0,readiness:"not_ready",...My(i),runtimeProfileId:c,runtimeProfileType:u.type,apiKeyEnv:l,apiKeyPresent:!0,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`pi-ai profile configured with apiKeyEnv='${l}' (key present); runtime availability unknown`,nextAction:"Run pd runtime probe to verify end-to-end connectivity"}:{enabled:!0,readiness:"needs_setup",...My(i),runtimeProfileId:c,runtimeProfileType:u.type,apiKeyEnv:l,apiKeyPresent:!1,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`Environment variable '${l}' is not set or empty`,nextAction:`Set the environment variable '${l}' with a valid API key`}:{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,runtimeProfileType:u.type,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`pi-ai profile '${c}' missing apiKeyEnv`,nextAction:`Add apiKeyEnv to runtime profile '${c}' in .pd/config.yaml`}}function vEt(t,e){let n=mEt({...e!==void 0?{logger:e}:{}});hEt(n,t,e)}import{existsSync as DEt,readFileSync as PGn,writeFileSync as LGn,renameSync as NGn}from"fs";import{homedir as MGn}from"os";import*as PEt from"path";import*as Ro from"fs";import*as wEt from"path";var ESe=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},bEt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function SEt(t){try{return process.kill(t,0),!0}catch{return!1}}function xEt(t,e){try{let n=wEt.dirname(t);Ro.existsSync(n)||Ro.mkdirSync(n,{recursive:!0});let r=Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL,i=Ro.openSync(t,r);return Ro.writeSync(i,String(e)),Ro.fsyncSync(i),Ro.closeSync(i),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function JW(t){try{let e=Ro.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function CGn(t,e){try{JW(t)===e&&Ro.unlinkSync(t)}catch{}}function kGn(t,e){try{let n=Ro.statSync(t),r=JW(t),i=Date.now()-n.mtimeMs>e,o=r===null||!SEt(r);if(i||o)try{return Ro.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function CEt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),i=r*.2*Math.random();return Math.floor(r+i)}function TGn(t){return new Promise(e=>setTimeout(e,t))}function RGn(t){let e=Date.now()+t;for(;Date.now()<e;);}function kEt(t,e){let n=JW(e),r=n!==null?SEt(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new ESe(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function TEt(t,e,n){let r=t+e.lockSuffix;return xEt(r,n)&&JW(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(kGn(r,e.lockStaleMs),xEt(r,n)&&JW(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function OGn(t,e={}){let n={...bEt,...e},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=TEt(t,n,r);if(o)return o;if(i<n.maxRetries-1){let a=CEt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);RGn(a)}}throw kEt(t,t+n.lockSuffix)}async function DGn(t,e={}){let n={...bEt,...e},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=TEt(t,n,r);if(o)return o;if(i<n.maxRetries-1){let a=CEt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);await TGn(a)}}throw kEt(t,t+n.lockSuffix)}function REt(t){CGn(t.lockPath,t.pid)}function bu(t,e,n={}){let r=OGn(t,n);try{return e()}finally{REt(r)}}async function KX(t,e,n={}){let r=await DGn(t,n);try{return await e()}finally{REt(r)}}function VX(t,e){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.plugins;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n.entries;if(!(!r||typeof r!="object"||Array.isArray(r)))return r[e]}var vSe="allowConversationAccess",ISe="openclaw config set plugins.entries.principles-disciple.hooks.allowConversationAccess true --strict-json";function ZW(t){if(t==null||typeof t!="object"||Array.isArray(t))return{authorized:!1,reason:"pluginConfig is missing or invalid \u2014 conversation hooks cannot be registered",nextAction:ISe};let e=t;return typeof e.hooks!="object"||e.hooks===null||Array.isArray(e.hooks)?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ISe}:e.hooks[vSe]!==!0?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ISe}:{authorized:!0}}var OEt="principles-disciple";function BGn(){return PEt.join(MGn(),".openclaw","openclaw.json")}function XW(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function FGn(t){if(!DEt(t))return null;try{let e=PGn(t,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(e);return XW(n)?n:null}catch{return null}}function UGn(t,e){let n=t+".tmp."+Date.now();LGn(n,JSON.stringify(e,null,2),"utf8"),NGn(n,t)}function zX(){let t=BGn();return DEt(t)?bu(t,()=>{let e=FGn(t);if(!e)return!1;XW(e.plugins)||(e.plugins={});let n=e.plugins;XW(n.entries)||(n.entries={});let r=n.entries,i=r[OEt],o=XW(i)?i:{enabled:!0};XW(o.hooks)||(o.hooks={});let a=o.hooks;return Object.hasOwn(a,vSe)?!1:(a.allowConversationAccess=!0,r[OEt]=o,UGn(t,e),!0)}):!1}function xSe(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.hooks;return!e||typeof e!="object"||Array.isArray(e)?!1:e[vSe]===!1}function QGn(t){return t.toLowerCase().startsWith("zh")?"zh":"en"}var WGn={"pd-init":{zh:"\u521D\u59CB\u5316\u5DE5\u4F5C\u533A\uFF08\u751F\u6210 PRINCIPLES.md\u3001THINKING_OS.md \u7B49\uFF09",en:"Initialize workspace (generate PRINCIPLES.md, THINKING_OS.md, etc.)"},"pd-bootstrap":{zh:"\u626B\u63CF\u73AF\u5883\u5DE5\u5177\u5E76\u5EFA\u8BAE\u5347\u7EA7",en:"Scan environment tools and suggest upgrades"},"pd-research":{zh:"\u7814\u7A76\u5DE5\u5177\u5347\u7EA7\u65B9\u6848",en:"Research tool upgrade solutions"},"pd-help":{zh:"\u663E\u793A\u6240\u6709\u547D\u4EE4\u548C\u4F7F\u7528\u6307\u5357",en:"Show all commands and usage guide"},"pd-status":{zh:"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001\uFF08GFI\u3001Pain \u8BCD\u5178\uFF09",en:"View system status (GFI, Pain dictionary)"},"pd-context":{zh:"\u63A7\u5236\u4E0A\u4E0B\u6587\u6CE8\u5165 [status|thinking|reflection|focus|preset] - \u8F93\u5165 /pd-context help \u67E5\u770B\u8BE6\u60C5",en:"Control context injection [status|thinking|reflection|focus|preset] - Type /pd-context help for details"},"pd-focus":{zh:"\u7BA1\u7406 CURRENT_FOCUS.md [status|history|compress|rollback] - \u67E5\u770B/\u538B\u7F29/\u56DE\u6EDA\u7126\u70B9\u6587\u4EF6",en:"Manage CURRENT_FOCUS.md [status|history|compress|rollback] - View/compress/rollback focus file"},"pd-principle-rollback":{zh:"\u56DE\u6EDA\u539F\u5219\u5E76\u52A0\u5165\u9ED1\u540D\u5355 <principle-id> [reason]",en:"Rollback principle and blacklist pattern <principle-id> [reason]"},"pd-rollback":{zh:"\u56DE\u6EDA\u60C5\u7EEA\u4E8B\u4EF6\u60E9\u7F5A <event-id>|last",en:"Rollback empathy event penalty <event-id>|last"},"pd-export":{zh:"\u5BFC\u51FA\u6570\u636E [analytics|corrections --redacted]",en:"Export data [analytics|corrections --redacted]"},"pd-samples":{zh:"\u67E5\u770B\u6216\u5BA1\u6838\u7EA0\u9519\u6837\u672C [review approve|reject <sample-id> [note]]",en:"List or review correction samples [review approve|reject <sample-id> [note]]"},"pd-pain":{zh:"\u4ECE OpenClaw \u4F1A\u8BDD\u62A5\u544A pain\uFF08context-bound provenance\uFF09",en:"Report pain from OpenClaw session (context-bound provenance)"},"pd-promote-impl":{zh:"\u63D0\u5347\u5019\u9009\u5B9E\u73B0\u5230 active [list|show <id>|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Promote candidate implementation to active [list|show <id>|<id>] (semi-deprecated)"},"pd-disable-impl":{zh:'\u7981\u7528 active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Disable active implementation [list|<id> --reason "..."] (semi-deprecated)'},"pd-archive-impl":{zh:"\u6C38\u4E45\u5F52\u6863\u5B9E\u73B0 [list|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Archive implementation permanently [list|<id>] (semi-deprecated)"},"pd-rollback-impl":{zh:'\u56DE\u6EDA\u5230\u4E0A\u4E00\u4E2A active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Rollback to previous active implementation [list|<id> --reason "..."] (semi-deprecated)'}};function Xs(t,e){let n=QGn(e),r=WGn[t];return r&&(r[n]||r.en)||t}import*as nS from"path";var Ur=(...t)=>nS.posix.join(...t);function $Gn(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function HGn(t,e){return $Gn(t)?nS.win32.join(t,e):t.startsWith("/")?nS.posix.join(t,e):nS.join(t,e)}var sr={IDENTITY:".principles",MODELS:Ur(".principles","models"),STATE:".state",MEMORY:"memory",OKR:Ur("memory","okr"),LOGS:Ur("memory","logs"),SESSIONS:Ur(".state","sessions"),PAIN_SAMPLES:Ur("memory","pain"),LOCKS:Ur("memory",".locks"),IMPL_CODE_DIR:Ur(".state","principles","implementations")},YX={PROFILE:Ur(sr.IDENTITY,"PROFILE.json"),PRINCIPLES:Ur(sr.IDENTITY,"PRINCIPLES.md"),THINKING_OS:Ur(sr.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:Ur(sr.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:sr.MODELS,STATE_DIR:sr.STATE,WORKBOARD:Ur(sr.STATE,"WORKBOARD.json"),AGENT_SCORECARD:Ur(sr.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:Ur(sr.STATE,".pain_flag"),SYSTEM_CAPABILITIES:Ur(sr.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:Ur(sr.STATE,"pain_settings.json"),PAIN_CANDIDATES:Ur(sr.STATE,"pain_candidates.json"),TRAJECTORY_DB:Ur(sr.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:Ur(sr.STATE,"blobs"),EXPORTS_DIR:Ur(sr.STATE,"exports"),SESSION_DIR:sr.SESSIONS,DICTIONARY:Ur(sr.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:Ur(sr.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:Ur(sr.STATE,"workflows.yaml"),IMPL_CODE_DIR:sr.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:Ur(sr.LOGS,"SYSTEM.log"),REFLECTION_LOG:Ur(sr.MEMORY,"reflection-log.md"),USER_CONTEXT:Ur(sr.MEMORY,"USER_CONTEXT.md"),OKR_DIR:sr.OKR,CURRENT_FOCUS:Ur(sr.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:Ur(sr.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:Ur(sr.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:Ur(sr.LOCKS,"evolution")};function ca(t,e){return HGn(t,YX[e])}import*as Su from"path";import*as eZ from"os";import*as rS from"fs";var jGn={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"},JX=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="PdError",this.category=jGn[r]??"execution_failed"}code;category};var XX=class extends JX{constructor(e,n){super(`[PD:Path] Unknown path key: ${e}`,"PATH_RESOLUTION_ERROR",n),this.name="PathResolutionError"}};var e$=class extends JX{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};import*as Td from"path";import*as uL from"fs";var LEt=3,GGn=50;function Bt(t,e){let n=t+".tmp";uL.writeFileSync(n,e,"utf8");let r;for(let i=0;i<LEt;i++)try{uL.renameSync(n,t);return}catch(o){r=o;let a=o.code;if(a==="EPERM"||a==="EBUSY"||a==="EACCES"){if(i<LEt-1){let s=GGn*Math.pow(2,i),c=Date.now()+s,u=!1;for(;Date.now()<c;)if(!u&&Date.now()>=c-10){try{re("fs").accessSync?.(n)}catch{}u=!0}}continue}break}try{uL.unlinkSync(n)}catch{}throw r}function MEt(t,e){if(!t)return"";let n=e.includes("\\")||e.length>=2&&e[1]===":",r=t.includes("\\")||t.length>=2&&t[1]===":",i=t;n!==r&&r&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2).replace(/\\/g,"/")}`);let o=i.startsWith("/")&&!r,a=!n,s;if(n){let c=Td.resolve(e);if(o)s=i;else{let u=Td.isAbsolute(i)?i:Td.join(c,i);s=Td.relative(c,u)}}else if(a&&o){let c=e.replace(/\\/g,"/");s=Td.posix.relative(c,i)}else{let c=e.replace(/\\/g,"/"),u=Td.isAbsolute(i)?i:Td.posix.join(c,i.replace(/\\/g,"/"));s=Td.posix.relative(c,u)}return s=s.replace(/\\/g,"/"),s.startsWith("../")?i:s}function NEt(t){let e=t.replace(/\\/g,"/");return e.endsWith("/")&&(e=e.slice(0,-1)),e}function ZX(t,e){if(!t||!e||e.length===0)return!1;let n=NEt(t);for(let r of e){let i=NEt(r);if(n.startsWith(i)&&(n===i||n.charAt(i.length)==="/"))return!0}return!1}function Oo(t){return t==null?"":Array.isArray(t)?t.join(" "):t}var qGn=".openclaw/workspace";var wSe="principles-disciple.json",KGn=[Su.join(process.cwd(),wSe),Su.join(eZ.homedir(),".openclaw",wSe),Su.join(eZ.homedir(),".principles",wSe)];function VGn(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function zGn(t){return t.startsWith("/")}function lL(t){return VGn(t)?Su.win32:zGn(t)?Su.posix:Su}function YGn(){for(let t of KGn)if(rS.existsSync(t))return t;return null}function BEt(){let t=YGn();if(!t)return null;try{let e=rS.readFileSync(t,"utf8"),n=JSON.parse(e);return console.log(`[PD:PathResolver] Loaded config from: ${t}`),n}catch(e){return console.warn(`[PD:PathResolver] Failed to load config from ${t}: ${String(e)}`),null}}var Zp=class t{static extensionRoot=null;workspaceDir=null;stateDir=null;logger;normalizeWorkspace;initialized=!1;static setExtensionRoot(e){if(!e||!e.trim())return;let n=e.trim(),r=lL(n);t.extensionRoot=r.normalize(n)}static getExtensionRoot(){return t.extensionRoot}constructor(e={}){if(this.logger=e.logger,this.normalizeWorkspace=e.normalizeWorkspace??!0,e.workspaceDir){let n=e.workspaceDir,r=this.normalizeWorkspace?this.normalizePath(n):n;n!==r&&this.log("info",`Workspace path normalized: ${n} -> ${r}`),this.workspaceDir=r,this.initialized=!0}}log(e,n){let i=`[PD:PathResolver] ${n}`;switch(process.env.DEBUG==="true"&&this.logger?.debug?.(i),e){case"debug":this.logger?.debug?.(i);break;case"info":this.logger?.info?.(i);break;case"warn":this.logger?.warn?.(i);break;case"error":this.logger?.error?.(i);break}}detectWorkspaceDir(){let e=process.env.PD_WORKSPACE_DIR;if(e&&e.trim())return this.log("info",`Using workspace from PD_WORKSPACE_DIR: ${e}`),e.trim();let n=process.env.OPENCLAW_WORKSPACE;if(n&&n.trim())return this.log("info",`Using workspace from OPENCLAW_WORKSPACE: ${n}`),n.trim();let r=BEt();if(r?.workspace)return this.log("info",`Using workspace from config file: ${r.workspace}`),r.workspace;let i=eZ.homedir(),o=Su.join(i,qGn);return this.log("info",`Using default workspace: ${o}`),o}normalizePath(e){let n=lL(e),r=n===Su?Su.resolve(e):n.normalize(e);if(this.normalizeWorkspace){let i=["/memory","/docs","\\memory","\\docs"];for(let o of i)if(r.endsWith(o)){let a=n.dirname(r);this.log("warn",`Detected subdirectory suffix '${o}' in path. Normalized to parent: ${a}`),r=a;break}}return r}normalizeWorkspacePath(e){return this.normalizePath(e)}getWorkspaceDir(){if(this.initialized&&this.workspaceDir)return this.workspaceDir;let e=this.detectWorkspaceDir();if(this.normalizeWorkspace){let n=e;e=this.normalizePath(e),n!==e&&this.log("info",`Workspace path normalized: ${n} -> ${e}`)}return this.workspaceDir=e,this.initialized=!0,this.log("debug",`Final workspace directory: ${this.workspaceDir}`),this.workspaceDir}getStateDir(){if(this.stateDir)return this.stateDir;let e=process.env.PD_STATE_DIR;if(e&&e.trim())return this.stateDir=e.trim(),this.log("info",`Using state directory from PD_STATE_DIR: ${this.stateDir}`),this.stateDir;if(this.initialized&&this.workspaceDir){let o=lL(this.workspaceDir);return this.stateDir=o.join(this.workspaceDir,".state"),this.log("debug",`Using workspace-based state directory: ${this.stateDir}`),this.stateDir}let n=BEt();if(n?.state)return this.stateDir=n.state,this.log("info",`Using state directory from config file: ${this.stateDir}`),this.stateDir;let r=this.getWorkspaceDir(),i=lL(r);return this.stateDir=i.join(r,".state"),this.log("debug",`Computed state directory: ${this.stateDir}`),this.stateDir}resolve(e){let n=this.getWorkspaceDir(),r=this.getStateDir(),i=lL(n),o=t.extensionRoot||Su.resolve(process.cwd(),"packages","openclaw-plugin"),a=lL(o),s=i.join(n,"memory"),c=a.join(o,"src"),u=a.join(o,"dist"),p={PROFILE:i.join(n,".principles","PROFILE.json"),PRINCIPLES:i.join(n,".principles","PRINCIPLES.md"),THINKING_OS:i.join(n,".principles","THINKING_OS.md"),DECISION_POLICY:i.join(n,".principles","DECISION_POLICY.json"),MODELS_DIR:i.join(n,".principles","models"),AGENT_SCORECARD:i.join(r,"AGENT_SCORECARD.json"),PAIN_FLAG:i.join(r,".pain_flag"),WORKBOARD:i.join(r,"WORKBOARD.json"),SYSTEM_CAPABILITIES:i.join(r,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:i.join(r,"pain_settings.json"),PAIN_CANDIDATES:i.join(r,"pain_candidates.json"),DICTIONARY:i.join(r,"pain_dictionary.json"),STATE_DIR:r,EXTENSION_ROOT:o,EXTENSION_SRC:c,EXTENSION_DIST:u,LOGS:i.join(s,"logs"),SYSTEM_LOG:i.join(s,"logs","SYSTEM.log"),REFLECTION_LOG:i.join(s,"reflection-log.md"),USER_CONTEXT:i.join(s,"USER_CONTEXT.md"),OKR_DIR:i.join(s,"okr"),CURRENT_FOCUS:i.join(s,"okr","CURRENT_FOCUS.md"),WEEK_STATE:i.join(s,"okr","WEEK_STATE.json"),EVOLUTION_STREAM:i.join(s,"evolution.jsonl"),EVOLUTION_LOCK:i.join(s,".locks","evolution"),PRINCIPLE_BLACKLIST:i.join(r,"principle_blacklist.json"),MEMORY:s}[e];if(!p)throw this.log("warn",`Unknown path key: ${e}`),new XX(e);return this.log("debug",`Resolved path for '${e}': ${p}`),p}ensureStateDir(){let e=this.getStateDir();rS.existsSync(e)||(this.log("info",`Creating state directory: ${e}`),rS.mkdirSync(e,{recursive:!0}))}static createFromHookContext(e){let n=new t;if(e?.workspaceDir){let r=String(e.workspaceDir);n.normalizeWorkspace&&(r=n.normalizePath(r)),n.workspaceDir=r,n.initialized=!0,n.log("info",`Created from hook context with workspace: ${r}`)}return e?.stateDir&&(n.stateDir=String(e.stateDir)),n}};function FEt(t,e){if(!t)return;let n=t.runtime.agent;if(n?.resolveAgentWorkspaceDir)try{return n.resolveAgentWorkspaceDir(t.config,e??"main")}catch{}let r=t.config?.workspaceDir;if(r&&r.trim())return r.trim();try{return new Zp().getWorkspaceDir()}catch{return}}import*as UEt from"os";import*as tZ from"path";function bSe(t){return typeof t!="string"||!t.trim()||!tZ.isAbsolute(t)?!1:process.platform!=="win32"?!0:/^[A-Za-z]:[\\/]/.test(t)||/^\\\\[^\\/]/.test(t)}function Cl(t){if(!t)return"workspaceDir is undefined/null";if(/^[A-Za-z]:\\?$/.test(t))return`workspaceDir is a drive root: "${t}"`;let e=tZ.resolve(t),n=UEt.homedir();if(e===n)return`workspaceDir equals home directory (${n}), likely missing context field`;if(e==="/"||e==="")return`workspaceDir is root or empty: "${e}"`;if(/^[A-Za-z]:\\?$/.test(e))return`workspaceDir is a drive root: "${e}"`;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[{pattern:new RegExp(`^${r}[\\\\/]?$`),desc:"is home directory"}];for(let{pattern:o,desc:a}of i)if(o.test(e))return`workspaceDir ${a}: "${e}"`;return null}import*as iS from"fs";import*as rZ from"path";var QEt={language:"zh",diagnostician:{context:{time_window_minutes:5,max_message_length:500,max_summary_length:3e3}},thresholds:{pain_trigger:40,cognitive_paralysis_input:4e3,stuck_loops_trigger:4,semantic_min_score:.7,promotion_count_threshold:3,promotion_similarity_threshold:.8},scores:{paralysis:45,default_confusion:30,default_loop:40,tool_failure_friction:15,exit_code_penalty:50,spiral_penalty:30,missing_test_command_penalty:20,subagent_error_penalty:60,subagent_timeout_penalty:50},severity_thresholds:{high:70,medium:40,low:20},empathy_engine:{enabled:!0,dedupe_window_ms:6e4,penalties:{mild:10,moderate:25,severe:40},rate_limit:{max_per_turn:40,max_per_hour:120},model_calibration:{}},gfi_gate:{enabled:!0,thresholds:{low_risk_block:70,high_risk_block:40,large_change_block:50},large_change_lines:50,ep_tier_multipliers:{1:.5,2:.75,3:1,4:1.5,5:2},bash_safe_patterns:["^(ls|dir|pwd|which|where|echo|env|cat|type|head|tail|less|more)\\b","^git\\s+(status|log|diff|branch|show|remote)\\b","^npm\\s+(run|test|build|start)\\b","^make\\s*$","^make\\s+(-j\\d+|--jobs\\s*\\d+)$","^(gradle|mvn)\\s+(clean|build|test|compile)\\b"],bash_dangerous_patterns:["rm\\s+(-[a-z]*r[a-z]*f|-rf)","del\\s+/s","rmdir\\s+/s","git\\s+(push\\s+.*--force|reset\\s+--hard|clean\\s+-fd)","npm\\s+publish","pip\\s+upload","docker\\s+push","(curl|wget).*\\|\\s*(ba)?sh"]},compression:{line_threshold:100,size_threshold_kb:15,interval_hours:24,keep_completed_tasks:3,max_working_memory_artifacts:10}},nZ=class{settings={...QEt};filePath;constructor(e){this.filePath=rZ.join(e,"pain_settings.json")}load(){if(iS.existsSync(this.filePath))try{let e=JSON.parse(iS.readFileSync(this.filePath,"utf8"));this.settings=this.deepMerge(QEt,e)}catch{console.error("[PD] Failed to parse pain_settings.json, using defaults.")}else console.log(`[PD:Config] Settings not found at ${this.filePath}, creating with defaults`),this.save()}save(){try{let e=rZ.dirname(this.filePath);iS.existsSync(e)||iS.mkdirSync(e,{recursive:!0}),Bt(this.filePath,JSON.stringify(this.settings,null,2)),console.log(`[PD:Config] Settings saved to ${this.filePath}`)}catch(e){console.error(`[PD:Config] Failed to save settings: ${String(e)}`)}}deepMerge(e,n){let r={...e};return n&&typeof n=="object"&&Object.keys(n).forEach(i=>{n[i]!==void 0&&(n[i]&&typeof n[i]=="object"&&!Array.isArray(n[i])?i in e?r[i]=this.deepMerge(e[i],n[i]):Object.assign(r,{[i]:n[i]}):Object.assign(r,{[i]:n[i]}))}),r}get(e){let n=e.split("."),r=this.settings;for(let i of n){if(r===void 0||r[i]===void 0)return;r=r[i]}return r}getAll(){return this.settings}};var t$=null,WEt=null,iZ={get(t){return(!t$||WEt!==t)&&(t$=new nZ(t),t$.load(),WEt=t),t$},reset(){t$=null}};import*as Zs from"fs";import*as n$ from"path";var $Et=7,SSe=class{logsDir;statsFile;logger;statsCache=new Map;eventBuffer=[];maxBufferSize=20;flushIntervalMs=3e4;flushTimer;currentEventsFile;currentDate;constructor(e,n){let r=Ym(e);this.logsDir=n$.join(r,"logs"),Zs.existsSync(this.logsDir)||Zs.mkdirSync(this.logsDir,{recursive:!0}),this.statsFile=n$.join(this.logsDir,"daily-stats.json"),this.logger=n,this.loadStats(),this.startFlushTimer()}getEventsFile(e){return n$.join(this.logsDir,`events_${e}.jsonl`)}getTodayStr(){return new Date().toISOString().split("T")[0]??""}ensureEventsFile(){let e=this.getTodayStr();return(this.currentDate!==e||!this.currentEventsFile)&&(this.currentDate=e,this.currentEventsFile=this.getEventsFile(e),this.cleanupOldEventFiles(e)),this.currentEventsFile}cleanupOldEventFiles(e){if(!($Et<=0))try{let n=Date.now()-$Et*24*60*60*1e3,r=Zs.readdirSync(this.logsDir);for(let i of r){if(!i.startsWith("events_")||!i.endsWith(".jsonl"))continue;let o=n$.join(this.logsDir,i);Zs.statSync(o).mtimeMs<n&&Zs.unlinkSync(o)}}catch(n){this.logger?.debug?.(`[PD] Event file cleanup failed (non-blocking): ${String(n)}`)}}recordToolCall(e,n){let r=n.error||n.exitCode!==void 0&&n.exitCode!==0?"failure":"success";this.record("tool_call",r,e,n)}recordPainSignal(e,n){this.record("pain_signal","detected",e,n)}recordRulePromotion(e){this.record("rule_promotion","promoted",void 0,e)}recordGovernanceAction(e,n){this.record("governance_action","approved",void 0,e),n?.flushImmediately&&this.flushEvents()}recordHookExecution(e,n){let r=e.error?"failure":"success";this.record("hook_execution",r,void 0,e),n?.flushImmediately&&this.flushEvents()}recordGateBlock(e,n){this.record("gate_block","blocked",e,n)}recordGateBypass(e,n){this.record("gate_bypass","bypassed",e,n)}recordEmpathyRollback(e,n){this.record("empathy_rollback","rolled_back",e,n)}recordError(e,n,r){this.record("error","failure",e,{message:n,...r})}recordWarn(e,n,r){this.record("warn","failure",e,{message:n,...r})}recordDiagnosisTask(e){this.record("diagnosis_task","written",void 0,e)}recordHeartbeatDiagnosis(e){this.record("heartbeat_diagnosis","injected",void 0,e)}recordDiagnosticianReport(e){let n={success:"completed",missing_json:"failure",incomplete_fields:"failure"};this.record("diagnostician_report",n[e.category],void 0,e)}recordPrincipleCandidate(e){this.record("principle_candidate","created",void 0,e)}recordRuleEnforced(e){this.record("rule_enforced","matched",void 0,e)}recordRuleHostEvaluated(e){this.record("rulehost_evaluated","evaluated",void 0,e)}recordRuleHostBlocked(e){this.record("rulehost_blocked","blocked",void 0,e)}recordRuleHostRequireApproval(e){this.record("rulehost_requireApproval","requireApproval",void 0,e)}recordRuleHostAutoCorrectProposed(e){this.record("rulehost_auto_correct_proposed","auto_correct",void 0,e)}recordRuleHostAutoCorrectApplied(e){this.record("rulehost_auto_correct_applied","auto_correct",void 0,e)}recordRuntimeV2ActivationsInjected(e){this.record("runtime_v2_prompt_activations_injected","injected",e.sessionId,e)}recordRuleHostUnhealthy(e){this.record("rulehost_unhealthy","failure",void 0,e)}recordRuleHostSkipped(e){this.record("rulehost_skipped","failure",void 0,e)}recordTrajectoryObservabilityFailure(e){this.record("trajectory_observability_failure","failure",e.sessionId,e)}redactEventData(e,n){try{if(!new Set(["tool_call","rulehost_evaluated","rulehost_blocked","rulehost_requireApproval","rulehost_auto_correct_proposed","rulehost_auto_correct_applied","rulehost_skipped","trajectory_observability_failure","rule_enforced","hook_execution","gate_block","gate_bypass"]).has(e))return n;let i={};for(let[o,a]of Object.entries(n))if(typeof a=="string")i[o]=gv(a);else if(Array.isArray(a))i[o]=a.map(s=>{if(typeof s=="string")return gv(s);if(typeof s=="object"&&s!==null){let c={};for(let[u,l]of Object.entries(s))c[u]=typeof l=="string"?gv(l):l;return c}return s});else if(typeof a=="object"&&a!==null){let s={};for(let[c,u]of Object.entries(a))typeof u=="string"?s[c]=gv(u):s[c]=u;i[o]=s}else i[o]=a;return i}catch(r){return{redactionFailure:!0,redactionStatus:"failed","redaction.status":"failed",redactionReason:(r instanceof Error?r.message.slice(0,200):String(r).slice(0,200))||"unknown error",redactionDataDropped:!0,originalType:e,originalSessionId:n.sessionId??null}}}record(e,n,r,i){let o=new Date,a=this.formatDate(o),s=this.redactEventData(e,i),c={ts:o.toISOString(),date:a,type:e,category:n,sessionId:r,data:s};this.eventBuffer.push(c),this.updateStats(c),this.eventBuffer.length>=this.maxBufferSize&&this.flushEvents()}formatDate(e){return e.toISOString().split("T")[0]??""}loadStats(){if(Zs.existsSync(this.statsFile))try{let e=JSON.parse(Zs.readFileSync(this.statsFile,"utf-8"));for(let n in e)this.statsCache.set(n,e[n])}catch(e){this.logger&&this.logger.error(`[PD] Failed to load daily-stats.json: ${String(e)}`)}}updateStats(e){let n=this.statsCache.get(e.date);if(n||(n=_C(e.date),this.statsCache.set(e.date,n)),e.type==="tool_call"){n.tools.total++,e.category==="success"?n.tools.success++:n.tools.failure++;let r=e.data,i=r.gfiAfter??r.gfi;i!==void 0&&(n.gfi.samples++,n.gfi.total+=i,n.gfi.peak=Math.max(n.gfi.peak,i))}else if(e.type==="pain_signal"){let r=e.data;if(r.source==="user_empathy"){if(r.deduped)n.empathy.dedupedCount++;else{n.empathy.totalEvents++,n.empathy.totalPenaltyScore+=r.score||0,r.severity&&(n.empathy.bySeverity[r.severity]++,n.empathy.scoreBySeverity[r.severity]+=r.score||0),r.detection_mode&&n.empathy.byDetectionMode[r.detection_mode]++,r.origin&&n.empathy.byOrigin[r.origin]++;let o=r.confidence??1;o>=.8?n.empathy.confidenceDistribution.high++:o>=.5?n.empathy.confidenceDistribution.medium++:n.empathy.confidenceDistribution.low++}let i=n.empathy.totalEvents+n.empathy.dedupedCount;n.empathy.dedupeHitRate=i>0?n.empathy.dedupedCount/i:0}}else if(e.type==="hook_execution"){let r=e.data;if(n.hooks.total++,e.category==="success"?n.hooks.success++:n.hooks.failure++,r.hook){n.hooks.byType[r.hook]||(n.hooks.byType[r.hook]={total:0,success:0,failure:0});let i=n.hooks.byType[r.hook];i&&(i.total++,e.category==="success"?i.success++:i.failure++)}}else if(e.type==="empathy_rollback"){let r=e.data;n.empathy.rollbackCount++,n.empathy.rolledBackScore+=r.originalScore||0}else if(e.type==="rule_promotion")n.evolution.rulesPromoted++;else if(e.type==="evolution_task")e.category==="completed"?n.evolution.tasksCompleted++:e.category==="enqueued"&&n.evolution.tasksEnqueued++;else if(e.type==="diagnosis_task")n.evolution.diagnosisTasksWritten++;else if(e.type==="heartbeat_diagnosis")n.evolution.heartbeatsInjected++;else if(e.type==="diagnostician_report"){let r=e.data;if(Object.prototype.hasOwnProperty.call(r,"category")){let i=r.category;typeof i=="string"&&(i==="success"||i==="missing_json"||i==="incomplete_fields")&&n.evolution.diagnosticianReportsWritten++,typeof i=="string"&&i==="missing_json"&&n.evolution.reportsMissingJson++,typeof i=="string"&&i==="incomplete_fields"&&n.evolution.reportsIncompleteFields++}else Object.prototype.hasOwnProperty.call(r,"success")&&n.evolution.diagnosticianReportsWritten++}else e.type==="principle_candidate"?n.evolution.principleCandidatesCreated++:e.type==="rule_enforced"?n.evolution.rulesEnforced++:e.type==="rulehost_evaluated"?n.evolution.rulehostEvaluated++:e.type==="rulehost_blocked"?n.evolution.rulehostBlocked++:e.type==="rulehost_requireApproval"?n.evolution.rulehostRequireApproval++:e.type==="rulehost_auto_correct_proposed"?n.evolution.rulehostAutoCorrectProposed++:e.type==="rulehost_auto_correct_applied"&&n.evolution.rulehostAutoCorrectApplied++}startFlushTimer(){this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer.unref()}flush(){this.flushEvents(),this.flushStats()}getBufferedEvents(){return this.eventBuffer.map(e=>({...e,data:{...e.data}}))}getEventDedupKey(e){let n=typeof e.data?.eventId=="string"?String(e.data.eventId):null;if(n)return`${e.type}:${e.sessionId??"none"}:${n}`;let r=e.data??{};return[e.ts??"no-ts",e.type??"no-type",e.category??"no-category",e.sessionId??"no-session",typeof r.source=="string"?r.source:"no-source",typeof r.toolName=="string"?r.toolName:"no-tool",typeof r.reason=="string"?r.reason:"no-reason"].join("::")}readPersistedEvents(){let e=this.ensureEventsFile();if(!Zs.existsSync(e))return[];try{return Zs.readFileSync(e,"utf-8").trim().split(`
|
|
2197
|
+
`).get(s.sourceKind,s.sourceLocator,s.observationKey);if(!oL(u)||typeof u.activation_ref_json!="string"||typeof u.content_ref_json!="string")return null;let l=JSON.parse(u.activation_ref_json),p=JSON.parse(u.content_ref_json),f=g=>typeof g=="string"&&/^sha256:[a-f0-9]{64}$/.test(g);if(!oL(l)||typeof l.activationId!="string"||!f(l.sourceSnapshotDigest)||!oL(p)||typeof p.principleId!="string"||p.resolution!=="resolved"&&p.resolution!=="revision_reference_unresolved"||p.resolution==="resolved"&&!f(p.payloadDigest)||p.resolution==="revision_reference_unresolved"&&p.payloadDigest!==void 0||l.activationId!==s.activationId||p.principleId!==s.principleId||typeof l.artifactId=="string"&&p.artifactId!==l.artifactId||s.artifactId!==void 0&&(l.artifactId!==s.artifactId||p.artifactId!==s.artifactId))return null;let m={activationId:l.activationId,sourceSnapshotDigest:l.sourceSnapshotDigest,...typeof l.idempotencyKey=="string"?{idempotencyKey:l.idempotencyKey}:{},...typeof l.artifactId=="string"?{artifactId:l.artifactId}:{},...typeof l.channel=="string"?{channel:l.channel}:{},...typeof l.activatedAt=="string"?{activatedAt:l.activatedAt}:{}},h={principleId:p.principleId,resolution:p.resolution,...typeof p.artifactId=="string"?{artifactId:p.artifactId}:{},...typeof p.version=="string"?{version:p.version}:{},...typeof p.payloadDigest=="string"?{payloadDigest:p.payloadDigest}:{},...typeof p.approvalRef=="string"?{approvalRef:p.approvalRef}:{}};return{activationRef:m,contentRef:h}}catch{return null}finally{try{c?.close()}catch{}}}return{appendObservationBatch:r,evidenceScopeIdFor:e,resolveInterventionContentRef:n,resolveActivationOccurrenceRef:i,existingObservationRefs:o}}var _Se=null;function VW(){return _Se||(_Se=iGn()),_Se}SC();h0();var oGn=new Set(["success","failure","blocked"]);function aGn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function sGn(t){return typeof t=="string"&&oGn.has(t)}function zW(t){return{status:"unavailable",unavailableReason:t,truncated:!1,calls:[]}}function aL(t,e,n){let{projectDir:r,toolSemantics:i}=n,o=[];for(let a of t){let{toolName:s}=a;if(typeof s!="string"||s.length===0)return zW(`row id=${a.id}: tool_name must be a non-empty string`);let{outcome:c}=a;if(!sGn(c))return zW(`row id=${a.id}: outcome "${a.outcome}" is not a valid RuleToolOutcome`);let u=a.paramsJson;if(typeof u!="string")return zW(`row id=${a.id}: params_json must be a string`);let l;try{l=JSON.parse(u)}catch{return zW(`row id=${a.id}: params_json is not valid JSON`)}if(!aGn(l))return zW(`row id=${a.id}: params_json must parse to a non-array object`);let p=i.resolve(s),{normalizedPath:f}=zp(s,l,r,{canonicalKind:p});o.push({sequenceId:a.id,toolName:s,canonicalKind:p,normalizedPath:f===""?null:f,paramsSummary:l,outcome:c})}return{status:"available",truncated:e,calls:o}}var cGn=3,uGn=5,lGn=100,yEt=new Set(["__proto__","constructor","prototype"]);function GX(t,e){try{return e()}catch(n){let r=n instanceof Error?n.message:String(n);throw ev("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${t} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function dGn(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function pGn(t){for(let e of Object.keys(t))if(yEt.has(e))return!1;return!0}function fGn(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>cGn)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 AEt(t,e){if(!t)throw ev("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${e} not found`);return t}function mGn(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(!dGn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${t.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!pGn(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 hGn(t){return t.startsWith("/")||/^[A-Za-z]:[\\/]/.test(t)}var gGn=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function AGn(t){if(t.length<20)return!1;for(let e of gGn)if(e.test(t))return!0;return!1}function yGn(t,e){let n=[],r={};for(let i of Object.keys(t)){if(yEt.has(i))continue;let o=t[i];if(typeof o!="string"){r[i]=o;continue}if(hGn(o)&&!o.startsWith(e)){r[i]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${i}" (outside project tree)`);continue}if(AGn(o)){r[i]="<redacted:secret>",n.push(`redacted possible secret in field "${i}"`);continue}r[i]=o}return{redacted:r,notes:n}}var YW=class{db;toolSemantics;constructor(e){this.db=e.source,this.toolSemantics=e.toolSemantics}assemble(e){let n=GX(`pain lineage read for canonical_pain_id="${e.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(e.sourcePainId));if(!n)throw ev("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${e.sourcePainId}" (ERR-069 fail loud)`);fGn(e);let r=AEt(GX(`evidence row read for id=${e.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(e.sourceNegativeToolCallId)),e.sourceNegativeToolCallId),i=e.positiveToolCallIds.map(p=>AEt(GX(`evidence row read for id=${p}`,()=>this.db.getRuleHostEvidenceRow(p)),p));for(let p of[r,...i])if(p.sessionId!==n.sessionId)throw ev("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${p.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],a={projectDir:e.projectDir,redactionNotes:o},s=this.buildSelectedCase(r,"negative",a),c=i.map(p=>this.buildSelectedCase(p,"positive",a)),u={sourceNegativeCase:s,ownerDesiredOutcome:e.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...i.map(p=>`tool_call:${p.id}`)].slice(0,uGn),redactionNotes:o},l=zg(u);if(!l.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${l.errors.join("; ")} (ERR-069 fail loud)`);return u}buildSelectedCase(e,n,r){let{projectDir:i,redactionNotes:o}=r,a=mGn(e,n,n==="negative"?"block":"allow"),s=yGn(a.params,i);o.push(...s.notes);let c=GX(`context history read for session=${e.sessionId} before id=${e.id}`,()=>this.db.getRuleHostContextRowsBefore(e.sessionId,e.id,lGn)),u=aL(c.rows,c.truncated,{projectDir:i,toolSemantics:this.toolSemantics}),l=zp(e.toolName,s.redacted,i,{canonicalKind:this.toolSemantics.resolve(e.toolName)}),p={version:2,history:u,facts:GE(u,l.normalizedPath||null,null)};return{...a,params:s.redacted,ruleContext:p}}};import kdo from"better-sqlite3";h0();var Ndo=2*1024*1024;var Hdo=1024*1024;var Gdo=1024*1024;var qX=["before_prompt_build","before_tool_call","after_tool_call"],sL=class extends Error{reason;nextAction;constructor(e,n){super(`${e}: ${n}`),this.reason=e,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function vGn(t,e){switch(t.kind){case"before_prompt_build":return e.beforePromptBuild;case"before_tool_call":return e.beforeToolCall;case"after_tool_call":return e.afterToolCall;default:throw new sL("unsupported_host_event",`Only ${qX.join(", ")} are supported by the MVP host runtime`)}}function eS(t){return typeof t=="string"&&t.trim().length>0}function EEt(t){return t.startsWith("/")||t.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(t)}function xGn(t){return!eS(t.context.workspaceDir)||!EEt(t.context.workspaceDir)||!eS(t.context.sessionId)||!eS(t.source)?!1:t.kind==="before_tool_call"||t.kind==="after_tool_call"?eS(t.context.toolName):!0}function _Et(t){return t===void 0||eS(t)}function wGn(t,e){if(e.warnings!==void 0&&(!Array.isArray(e.warnings)||!e.warnings.every(eS))||e.metadata!==void 0&&(typeof e.metadata!="object"||e.metadata===null||Array.isArray(e.metadata))||!eS(e.source)||!_Et(e.reason)||!_Et(e.additionalContext))return!1;let n=e.reason!==void 0,r=e.modifiedInput!==void 0,i=e.additionalContext!==void 0;switch(t.kind){case"before_prompt_build":return(e.decision==="allow"||e.decision==="modify")&&!n&&!r;case"before_tool_call":return e.decision==="observe"?!1:e.decision==="deny"?n&&!r&&!i:n?!1:!r||e.decision==="modify";case"after_tool_call":return e.decision==="observe"&&!n&&!r&&!i;default:return!1}}function bGn(t){return{async dispatch(e){if(!qbe(e)||!xGn(e))throw new sL("invalid_host_event","Decode and validate the host event before dispatch");let n=await vGn(e,t)(e);if(!Kbe(n)||!wGn(e,n))throw new sL("invalid_handler_result",`Handler for ${e.kind} must return a valid HostEventResult`);if(n.source!==e.source)throw new sL("lineage_mismatch",`Handler result source must match event source ${e.source}`);return n},async health(e){return e.trim().length===0?{ok:!1,workspaceDir:e,routes:qX,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:EEt(e)?{ok:!0,workspaceDir:e,routes:qX}:{ok:!1,workspaceDir:e,routes:qX,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function IEt(t={}){let e=v_t({...t.hostKind?{hostKind:t.hostKind}:{},...t.projectDir?{projectDir:t.projectDir}:{},...t.ruleContextProvider?{ruleContextProvider:t.ruleContextProvider}:{},...t.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:t.ruleInputEnrichmentProvider}:{},...t.ruleImplementationRuntime?{implementationRuntime:t.ruleImplementationRuntime}:{},...t.toolSemantics?{toolSemantics:t.toolSemantics}:{}});return bGn({afterToolCall:t.afterToolCall??C_t({...t.painEnrichmentProvider?{painEnrichmentProvider:t.painEnrichmentProvider}:{},...t.painDatabaseFactory?{painDatabaseFactory:t.painDatabaseFactory}:{},...t.hostKind?{hostKind:t.hostKind}:{},...t.projectDir?{projectDir:t.projectDir}:{},...t.events?{events:t.events}:{}}),beforeToolCall:t.beforeToolCall??e,async beforePromptBuild(n){let r=t.hostKind==="openclaw"||t.hostKind==="codex"||t.hostKind==="workbuddy"?t.hostKind:void 0,i=r===void 0?void 0:Gb(mr(n.context.workspaceDir).effective.config.promptBudget,r),o=await nSe({workspaceDir:n.context.workspaceDir,promptBudget:Eg({...i!==void 0?{operatorDeclared:{contextWindowTokens:i}}:{},hostCapacity:n.context.modelContext===void 0?void 0:{contextTokenBudget:n.context.modelContext.contextTokenBudget,contextWindowSource:n.context.modelContext.contextWindowSource},modelIdentity:n.context.modelContext===void 0?void 0:{providerId:n.context.modelContext.modelProviderId,modelId:n.context.modelContext.modelId},catalog:fU()})}),a=[];try{t.events?.recordRuntimeV2ActivationsInjected({sessionId:n.context.sessionId,workspaceDir:n.context.workspaceDir,principleIds:o.principleIds,activationIds:o.activationIds,artifactIds:o.artifactIds,injectedCount:o.principleIds.length,skippedWarnings:o.warnings,injectedCharCount:o.additionalContext.length,budget:o.budget,...t.hostKind==="openclaw"||t.hostKind==="codex"||t.hostKind==="workbuddy"?{hostKind:t.hostKind}:{},eventId:IGn(),...o.truncated!==void 0?{v2Truncated:o.truncated}:{},...n.context.turnId!==void 0?{runId:n.context.turnId}:{},...o.budgetPolicyVersion!==void 0?{budgetPolicyVersion:o.budgetPolicyVersion}:{},...o.budgetCapacitySource!==void 0?{budgetCapacitySource:o.budgetCapacitySource}:{},...o.budgetCapacityStatus!==void 0?{budgetCapacityStatus:o.budgetCapacityStatus}:{},...o.budgetContextWindowTokens!=null?{budgetContextWindowTokens:o.budgetContextWindowTokens}:{},...o.budgetFallbackReason!==void 0?{budgetFallbackReason:o.budgetFallbackReason}:{},...o.selectionPolicy!==void 0?{selectionPolicy:o.selectionPolicy}:{},...o.eligibleCount!==void 0?{eligibleCount:o.eligibleCount}:{},...o.rotationStartIndex!==void 0?{rotationStartIndex:o.rotationStartIndex}:{},...o.droppedActivationIds!==void 0&&o.droppedActivationIds.length>0?{droppedActivationIds:o.droppedActivationIds}:{},...o.oversizedActivationIds!==void 0&&o.oversizedActivationIds.length>0?{oversizedActivationIds:o.oversizedActivationIds}:{}})}catch(s){a.push(`receipt_event_write_failed:${s instanceof Error?s.message.slice(0,200):String(s).slice(0,200)}`)}if(t.beforePromptBuild){let s=await t.beforePromptBuild(n,o);return a.length===0?s:{...s,warnings:[...s.warnings??[],...a]}}return{decision:o.additionalContext.length>0?"modify":"allow",source:n.source,...o.additionalContext.length>0?{additionalContext:o.additionalContext}:{},...a.length>0?{warnings:a}:{}}}})}function My(t){return{source:t.source}}function tS(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,maxTokens:null,baseUrl:null}}function SGn(t){return Yc.some(e=>e===t)}function cL(t,e,n,r){let i=mr(t);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...My(i),...tS(),reason:`Config validation failed: ${i.errors.map(f=>f.reason).join("; ")}`,nextAction:i.errors[0]?.nextAction??"Fix .pd/config.yaml and retry",configErrors:i.errors};let o=i.effective.config;if(!o.features[e]?.enabled)return{enabled:!1,readiness:"disabled",...My(i),...tS(),reason:`${e} is disabled in .pd/config.yaml`,nextAction:`Enable it in .pd/config.yaml \u2014 in the existing "features:" block set ${e}: {enabled: true} (one flat key, not nested)`};if(!SGn(n))return{enabled:!1,readiness:"needs_setup",...My(i),...tS(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${Yc.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...My(i),...tS(),reason:`${e} feature flag is enabled but internalAgents.agents.${n}.enabled is false`,nextAction:`Enable the agent in .pd/config.yaml \u2014 this path IS nested: internalAgents > agents > ${n} > enabled: true; or disable the flag instead (flat key): in the existing "features:" block set ${e}: {enabled: false}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,u=o.runtimeProfiles[c];if(!u)return{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,reason:`Runtime profile '${c}' not found in .pd/config.yaml`,nextAction:`Add runtime profile '${c}' to .pd/config.yaml runtimeProfiles`};if(u.type!=="pi-ai")return{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,runtimeProfileType:u.type,provider:u.provider??null,model:u.model??null,reason:`Runtime profile '${c}' has retired type '${u.type}' (ADR-0029: pi-ai only). Observers require a pi-ai profile with an API key.`,nextAction:`Configure a pi-ai runtime profile for ${n} in .pd/config.yaml (e.g., add a pi-ai profile with provider, model, and apiKeyEnv)`};let l=u.apiKeyEnv??null;return l?Object.hasOwn(process.env,l)&&!!process.env[l]?{enabled:!0,readiness:"not_ready",...My(i),runtimeProfileId:c,runtimeProfileType:u.type,apiKeyEnv:l,apiKeyPresent:!0,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`pi-ai profile configured with apiKeyEnv='${l}' (key present); runtime availability unknown`,nextAction:"Run pd runtime probe to verify end-to-end connectivity"}:{enabled:!0,readiness:"needs_setup",...My(i),runtimeProfileId:c,runtimeProfileType:u.type,apiKeyEnv:l,apiKeyPresent:!1,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`Environment variable '${l}' is not set or empty`,nextAction:`Set the environment variable '${l}' with a valid API key`}:{enabled:!0,readiness:"needs_setup",...My(i),...tS(),runtimeProfileId:c,runtimeProfileType:u.type,provider:u.provider??null,model:u.model??null,timeoutMs:u.timeoutMs??null,maxTokens:u.maxTokens??null,baseUrl:u.baseUrl??null,reason:`pi-ai profile '${c}' missing apiKeyEnv`,nextAction:`Add apiKeyEnv to runtime profile '${c}' in .pd/config.yaml`}}function vEt(t,e){let n=mEt({...e!==void 0?{logger:e}:{}});hEt(n,t,e)}import{existsSync as DEt,readFileSync as PGn,writeFileSync as LGn,renameSync as NGn}from"fs";import{homedir as MGn}from"os";import*as PEt from"path";import*as Ro from"fs";import*as wEt from"path";var ESe=class extends Error{filePath;lockPath;constructor(e,n,r){super(e),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},bEt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function SEt(t){try{return process.kill(t,0),!0}catch{return!1}}function xEt(t,e){try{let n=wEt.dirname(t);Ro.existsSync(n)||Ro.mkdirSync(n,{recursive:!0});let r=Ro.constants.O_WRONLY|Ro.constants.O_CREAT|Ro.constants.O_EXCL,i=Ro.openSync(t,r);return Ro.writeSync(i,String(e)),Ro.fsyncSync(i),Ro.closeSync(i),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function JW(t){try{let e=Ro.readFileSync(t,"utf8"),n=parseInt(e.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function CGn(t,e){try{JW(t)===e&&Ro.unlinkSync(t)}catch{}}function kGn(t,e){try{let n=Ro.statSync(t),r=JW(t),i=Date.now()-n.mtimeMs>e,o=r===null||!SEt(r);if(i||o)try{return Ro.unlinkSync(t),!0}catch{return!1}return!1}catch{return!1}}function CEt(t,e,n){let r=Math.min(e*Math.pow(2,t),n),i=r*.2*Math.random();return Math.floor(r+i)}function TGn(t){return new Promise(e=>setTimeout(e,t))}function RGn(t){let e=Date.now()+t;for(;Date.now()<e;);}function kEt(t,e){let n=JW(e),r=n!==null?SEt(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new ESe(`Failed to acquire lock for ${t}. Lock holder: ${r}.`,t,e)}function TEt(t,e,n){let r=t+e.lockSuffix;return xEt(r,n)&&JW(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(kGn(r,e.lockStaleMs),xEt(r,n)&&JW(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function OGn(t,e={}){let n={...bEt,...e},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=TEt(t,n,r);if(o)return o;if(i<n.maxRetries-1){let a=CEt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);RGn(a)}}throw kEt(t,t+n.lockSuffix)}async function DGn(t,e={}){let n={...bEt,...e},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=TEt(t,n,r);if(o)return o;if(i<n.maxRetries-1){let a=CEt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);await TGn(a)}}throw kEt(t,t+n.lockSuffix)}function REt(t){CGn(t.lockPath,t.pid)}function bu(t,e,n={}){let r=OGn(t,n);try{return e()}finally{REt(r)}}async function KX(t,e,n={}){let r=await DGn(t,n);try{return await e()}finally{REt(r)}}function VX(t,e){if(!t||typeof t!="object"||Array.isArray(t))return;let n=t.plugins;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n.entries;if(!(!r||typeof r!="object"||Array.isArray(r)))return r[e]}var vSe="allowConversationAccess",ISe="openclaw config set plugins.entries.principles-disciple.hooks.allowConversationAccess true --strict-json";function ZW(t){if(t==null||typeof t!="object"||Array.isArray(t))return{authorized:!1,reason:"pluginConfig is missing or invalid \u2014 conversation hooks cannot be registered",nextAction:ISe};let e=t;return typeof e.hooks!="object"||e.hooks===null||Array.isArray(e.hooks)?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ISe}:e.hooks[vSe]!==!0?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:ISe}:{authorized:!0}}var OEt="principles-disciple";function BGn(){return PEt.join(MGn(),".openclaw","openclaw.json")}function XW(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)}function FGn(t){if(!DEt(t))return null;try{let e=PGn(t,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(e);return XW(n)?n:null}catch{return null}}function UGn(t,e){let n=t+".tmp."+Date.now();LGn(n,JSON.stringify(e,null,2),"utf8"),NGn(n,t)}function zX(){let t=BGn();return DEt(t)?bu(t,()=>{let e=FGn(t);if(!e)return!1;XW(e.plugins)||(e.plugins={});let n=e.plugins;XW(n.entries)||(n.entries={});let r=n.entries,i=r[OEt],o=XW(i)?i:{enabled:!0};XW(o.hooks)||(o.hooks={});let a=o.hooks;return Object.hasOwn(a,vSe)?!1:(a.allowConversationAccess=!0,r[OEt]=o,UGn(t,e),!0)}):!1}function xSe(t){if(!t||typeof t!="object"||Array.isArray(t))return!1;let e=t.hooks;return!e||typeof e!="object"||Array.isArray(e)?!1:e[vSe]===!1}function QGn(t){return t.toLowerCase().startsWith("zh")?"zh":"en"}var WGn={"pd-init":{zh:"\u521D\u59CB\u5316\u5DE5\u4F5C\u533A\uFF08\u751F\u6210 PRINCIPLES.md\u3001THINKING_OS.md \u7B49\uFF09",en:"Initialize workspace (generate PRINCIPLES.md, THINKING_OS.md, etc.)"},"pd-bootstrap":{zh:"\u626B\u63CF\u73AF\u5883\u5DE5\u5177\u5E76\u5EFA\u8BAE\u5347\u7EA7",en:"Scan environment tools and suggest upgrades"},"pd-research":{zh:"\u7814\u7A76\u5DE5\u5177\u5347\u7EA7\u65B9\u6848",en:"Research tool upgrade solutions"},"pd-help":{zh:"\u663E\u793A\u6240\u6709\u547D\u4EE4\u548C\u4F7F\u7528\u6307\u5357",en:"Show all commands and usage guide"},"pd-status":{zh:"\u67E5\u770B\u7CFB\u7EDF\u72B6\u6001\uFF08GFI\u3001Pain \u8BCD\u5178\uFF09",en:"View system status (GFI, Pain dictionary)"},"pd-context":{zh:"\u63A7\u5236\u4E0A\u4E0B\u6587\u6CE8\u5165 [status|thinking|reflection|focus|preset] - \u8F93\u5165 /pd-context help \u67E5\u770B\u8BE6\u60C5",en:"Control context injection [status|thinking|reflection|focus|preset] - Type /pd-context help for details"},"pd-focus":{zh:"\u7BA1\u7406 CURRENT_FOCUS.md [status|history|compress|rollback] - \u67E5\u770B/\u538B\u7F29/\u56DE\u6EDA\u7126\u70B9\u6587\u4EF6",en:"Manage CURRENT_FOCUS.md [status|history|compress|rollback] - View/compress/rollback focus file"},"pd-principle-rollback":{zh:"\u56DE\u6EDA\u539F\u5219\u5E76\u52A0\u5165\u9ED1\u540D\u5355 <principle-id> [reason]",en:"Rollback principle and blacklist pattern <principle-id> [reason]"},"pd-rollback":{zh:"\u56DE\u6EDA\u60C5\u7EEA\u4E8B\u4EF6\u60E9\u7F5A <event-id>|last",en:"Rollback empathy event penalty <event-id>|last"},"pd-export":{zh:"\u5BFC\u51FA\u6570\u636E [analytics|corrections --redacted]",en:"Export data [analytics|corrections --redacted]"},"pd-samples":{zh:"\u67E5\u770B\u6216\u5BA1\u6838\u7EA0\u9519\u6837\u672C [review approve|reject <sample-id> [note]]",en:"List or review correction samples [review approve|reject <sample-id> [note]]"},"pd-pain":{zh:"\u4ECE OpenClaw \u4F1A\u8BDD\u62A5\u544A pain\uFF08context-bound provenance\uFF09",en:"Report pain from OpenClaw session (context-bound provenance)"},"pd-promote-impl":{zh:"\u63D0\u5347\u5019\u9009\u5B9E\u73B0\u5230 active [list|show <id>|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Promote candidate implementation to active [list|show <id>|<id>] (semi-deprecated)"},"pd-disable-impl":{zh:'\u7981\u7528 active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Disable active implementation [list|<id> --reason "..."] (semi-deprecated)'},"pd-archive-impl":{zh:"\u6C38\u4E45\u5F52\u6863\u5B9E\u73B0 [list|<id>]\uFF08\u534A\u5E9F\u5F03\uFF09",en:"Archive implementation permanently [list|<id>] (semi-deprecated)"},"pd-rollback-impl":{zh:'\u56DE\u6EDA\u5230\u4E0A\u4E00\u4E2A active \u5B9E\u73B0 [list|<id> --reason "..."]\uFF08\u534A\u5E9F\u5F03\uFF09',en:'Rollback to previous active implementation [list|<id> --reason "..."] (semi-deprecated)'}};function Xs(t,e){let n=QGn(e),r=WGn[t];return r&&(r[n]||r.en)||t}import*as nS from"path";var Ur=(...t)=>nS.posix.join(...t);function $Gn(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function HGn(t,e){return $Gn(t)?nS.win32.join(t,e):t.startsWith("/")?nS.posix.join(t,e):nS.join(t,e)}var sr={IDENTITY:".principles",MODELS:Ur(".principles","models"),STATE:".state",MEMORY:"memory",OKR:Ur("memory","okr"),LOGS:Ur("memory","logs"),SESSIONS:Ur(".state","sessions"),PAIN_SAMPLES:Ur("memory","pain"),LOCKS:Ur("memory",".locks"),IMPL_CODE_DIR:Ur(".state","principles","implementations")},YX={PROFILE:Ur(sr.IDENTITY,"PROFILE.json"),PRINCIPLES:Ur(sr.IDENTITY,"PRINCIPLES.md"),THINKING_OS:Ur(sr.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:Ur(sr.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:sr.MODELS,STATE_DIR:sr.STATE,WORKBOARD:Ur(sr.STATE,"WORKBOARD.json"),AGENT_SCORECARD:Ur(sr.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:Ur(sr.STATE,".pain_flag"),SYSTEM_CAPABILITIES:Ur(sr.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:Ur(sr.STATE,"pain_settings.json"),PAIN_CANDIDATES:Ur(sr.STATE,"pain_candidates.json"),TRAJECTORY_DB:Ur(sr.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:Ur(sr.STATE,"blobs"),EXPORTS_DIR:Ur(sr.STATE,"exports"),SESSION_DIR:sr.SESSIONS,DICTIONARY:Ur(sr.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:Ur(sr.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:Ur(sr.STATE,"workflows.yaml"),IMPL_CODE_DIR:sr.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:Ur(sr.LOGS,"SYSTEM.log"),REFLECTION_LOG:Ur(sr.MEMORY,"reflection-log.md"),USER_CONTEXT:Ur(sr.MEMORY,"USER_CONTEXT.md"),OKR_DIR:sr.OKR,CURRENT_FOCUS:Ur(sr.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:Ur(sr.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:Ur(sr.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:Ur(sr.LOCKS,"evolution")};function ca(t,e){return HGn(t,YX[e])}import*as Su from"path";import*as eZ from"os";import*as rS from"fs";var jGn={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"},JX=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="PdError",this.category=jGn[r]??"execution_failed"}code;category};var XX=class extends JX{constructor(e,n){super(`[PD:Path] Unknown path key: ${e}`,"PATH_RESOLUTION_ERROR",n),this.name="PathResolutionError"}};var e$=class extends JX{constructor(e,n){super(`[PD:Sample] Correction sample not found: ${e}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};import*as Td from"path";import*as uL from"fs";var LEt=3,GGn=50;function Bt(t,e){let n=t+".tmp";uL.writeFileSync(n,e,"utf8");let r;for(let i=0;i<LEt;i++)try{uL.renameSync(n,t);return}catch(o){r=o;let a=o.code;if(a==="EPERM"||a==="EBUSY"||a==="EACCES"){if(i<LEt-1){let s=GGn*Math.pow(2,i),c=Date.now()+s,u=!1;for(;Date.now()<c;)if(!u&&Date.now()>=c-10){try{re("fs").accessSync?.(n)}catch{}u=!0}}continue}break}try{uL.unlinkSync(n)}catch{}throw r}function MEt(t,e){if(!t)return"";let n=e.includes("\\")||e.length>=2&&e[1]===":",r=t.includes("\\")||t.length>=2&&t[1]===":",i=t;n!==r&&r&&(i=`/mnt/${t.charAt(0).toLowerCase()}${t.slice(2).replace(/\\/g,"/")}`);let o=i.startsWith("/")&&!r,a=!n,s;if(n){let c=Td.resolve(e);if(o)s=i;else{let u=Td.isAbsolute(i)?i:Td.join(c,i);s=Td.relative(c,u)}}else if(a&&o){let c=e.replace(/\\/g,"/");s=Td.posix.relative(c,i)}else{let c=e.replace(/\\/g,"/"),u=Td.isAbsolute(i)?i:Td.posix.join(c,i.replace(/\\/g,"/"));s=Td.posix.relative(c,u)}return s=s.replace(/\\/g,"/"),s.startsWith("../")?i:s}function NEt(t){let e=t.replace(/\\/g,"/");return e.endsWith("/")&&(e=e.slice(0,-1)),e}function ZX(t,e){if(!t||!e||e.length===0)return!1;let n=NEt(t);for(let r of e){let i=NEt(r);if(n.startsWith(i)&&(n===i||n.charAt(i.length)==="/"))return!0}return!1}function Oo(t){return t==null?"":Array.isArray(t)?t.join(" "):t}var qGn=".openclaw/workspace";var wSe="principles-disciple.json",KGn=[Su.join(process.cwd(),wSe),Su.join(eZ.homedir(),".openclaw",wSe),Su.join(eZ.homedir(),".principles",wSe)];function VGn(t){return/^[A-Za-z]:[\\/]/.test(t)||t.startsWith("\\\\")}function zGn(t){return t.startsWith("/")}function lL(t){return VGn(t)?Su.win32:zGn(t)?Su.posix:Su}function YGn(){for(let t of KGn)if(rS.existsSync(t))return t;return null}function BEt(){let t=YGn();if(!t)return null;try{let e=rS.readFileSync(t,"utf8"),n=JSON.parse(e);return console.log(`[PD:PathResolver] Loaded config from: ${t}`),n}catch(e){return console.warn(`[PD:PathResolver] Failed to load config from ${t}: ${String(e)}`),null}}var Zp=class t{static extensionRoot=null;workspaceDir=null;stateDir=null;logger;normalizeWorkspace;initialized=!1;static setExtensionRoot(e){if(!e||!e.trim())return;let n=e.trim(),r=lL(n);t.extensionRoot=r.normalize(n)}static getExtensionRoot(){return t.extensionRoot}constructor(e={}){if(this.logger=e.logger,this.normalizeWorkspace=e.normalizeWorkspace??!0,e.workspaceDir){let n=e.workspaceDir,r=this.normalizeWorkspace?this.normalizePath(n):n;n!==r&&this.log("info",`Workspace path normalized: ${n} -> ${r}`),this.workspaceDir=r,this.initialized=!0}}log(e,n){let i=`[PD:PathResolver] ${n}`;switch(process.env.DEBUG==="true"&&this.logger?.debug?.(i),e){case"debug":this.logger?.debug?.(i);break;case"info":this.logger?.info?.(i);break;case"warn":this.logger?.warn?.(i);break;case"error":this.logger?.error?.(i);break}}detectWorkspaceDir(){let e=process.env.PD_WORKSPACE_DIR;if(e&&e.trim())return this.log("info",`Using workspace from PD_WORKSPACE_DIR: ${e}`),e.trim();let n=process.env.OPENCLAW_WORKSPACE;if(n&&n.trim())return this.log("info",`Using workspace from OPENCLAW_WORKSPACE: ${n}`),n.trim();let r=BEt();if(r?.workspace)return this.log("info",`Using workspace from config file: ${r.workspace}`),r.workspace;let i=eZ.homedir(),o=Su.join(i,qGn);return this.log("info",`Using default workspace: ${o}`),o}normalizePath(e){let n=lL(e),r=n===Su?Su.resolve(e):n.normalize(e);if(this.normalizeWorkspace){let i=["/memory","/docs","\\memory","\\docs"];for(let o of i)if(r.endsWith(o)){let a=n.dirname(r);this.log("warn",`Detected subdirectory suffix '${o}' in path. Normalized to parent: ${a}`),r=a;break}}return r}normalizeWorkspacePath(e){return this.normalizePath(e)}getWorkspaceDir(){if(this.initialized&&this.workspaceDir)return this.workspaceDir;let e=this.detectWorkspaceDir();if(this.normalizeWorkspace){let n=e;e=this.normalizePath(e),n!==e&&this.log("info",`Workspace path normalized: ${n} -> ${e}`)}return this.workspaceDir=e,this.initialized=!0,this.log("debug",`Final workspace directory: ${this.workspaceDir}`),this.workspaceDir}getStateDir(){if(this.stateDir)return this.stateDir;let e=process.env.PD_STATE_DIR;if(e&&e.trim())return this.stateDir=e.trim(),this.log("info",`Using state directory from PD_STATE_DIR: ${this.stateDir}`),this.stateDir;if(this.initialized&&this.workspaceDir){let o=lL(this.workspaceDir);return this.stateDir=o.join(this.workspaceDir,".state"),this.log("debug",`Using workspace-based state directory: ${this.stateDir}`),this.stateDir}let n=BEt();if(n?.state)return this.stateDir=n.state,this.log("info",`Using state directory from config file: ${this.stateDir}`),this.stateDir;let r=this.getWorkspaceDir(),i=lL(r);return this.stateDir=i.join(r,".state"),this.log("debug",`Computed state directory: ${this.stateDir}`),this.stateDir}resolve(e){let n=this.getWorkspaceDir(),r=this.getStateDir(),i=lL(n),o=t.extensionRoot||Su.resolve(process.cwd(),"packages","openclaw-plugin"),a=lL(o),s=i.join(n,"memory"),c=a.join(o,"src"),u=a.join(o,"dist"),p={PROFILE:i.join(n,".principles","PROFILE.json"),PRINCIPLES:i.join(n,".principles","PRINCIPLES.md"),THINKING_OS:i.join(n,".principles","THINKING_OS.md"),DECISION_POLICY:i.join(n,".principles","DECISION_POLICY.json"),MODELS_DIR:i.join(n,".principles","models"),AGENT_SCORECARD:i.join(r,"AGENT_SCORECARD.json"),PAIN_FLAG:i.join(r,".pain_flag"),WORKBOARD:i.join(r,"WORKBOARD.json"),SYSTEM_CAPABILITIES:i.join(r,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:i.join(r,"pain_settings.json"),PAIN_CANDIDATES:i.join(r,"pain_candidates.json"),DICTIONARY:i.join(r,"pain_dictionary.json"),STATE_DIR:r,EXTENSION_ROOT:o,EXTENSION_SRC:c,EXTENSION_DIST:u,LOGS:i.join(s,"logs"),SYSTEM_LOG:i.join(s,"logs","SYSTEM.log"),REFLECTION_LOG:i.join(s,"reflection-log.md"),USER_CONTEXT:i.join(s,"USER_CONTEXT.md"),OKR_DIR:i.join(s,"okr"),CURRENT_FOCUS:i.join(s,"okr","CURRENT_FOCUS.md"),WEEK_STATE:i.join(s,"okr","WEEK_STATE.json"),EVOLUTION_STREAM:i.join(s,"evolution.jsonl"),EVOLUTION_LOCK:i.join(s,".locks","evolution"),PRINCIPLE_BLACKLIST:i.join(r,"principle_blacklist.json"),MEMORY:s}[e];if(!p)throw this.log("warn",`Unknown path key: ${e}`),new XX(e);return this.log("debug",`Resolved path for '${e}': ${p}`),p}ensureStateDir(){let e=this.getStateDir();rS.existsSync(e)||(this.log("info",`Creating state directory: ${e}`),rS.mkdirSync(e,{recursive:!0}))}static createFromHookContext(e){let n=new t;if(e?.workspaceDir){let r=String(e.workspaceDir);n.normalizeWorkspace&&(r=n.normalizePath(r)),n.workspaceDir=r,n.initialized=!0,n.log("info",`Created from hook context with workspace: ${r}`)}return e?.stateDir&&(n.stateDir=String(e.stateDir)),n}};function FEt(t,e){if(!t)return;let n=t.runtime.agent;if(n?.resolveAgentWorkspaceDir)try{return n.resolveAgentWorkspaceDir(t.config,e??"main")}catch{}let r=t.config?.workspaceDir;if(r&&r.trim())return r.trim();try{return new Zp().getWorkspaceDir()}catch{return}}import*as UEt from"os";import*as tZ from"path";function bSe(t){return typeof t!="string"||!t.trim()||!tZ.isAbsolute(t)?!1:process.platform!=="win32"?!0:/^[A-Za-z]:[\\/]/.test(t)||/^\\\\[^\\/]/.test(t)}function Cl(t){if(!t)return"workspaceDir is undefined/null";if(/^[A-Za-z]:\\?$/.test(t))return`workspaceDir is a drive root: "${t}"`;let e=tZ.resolve(t),n=UEt.homedir();if(e===n)return`workspaceDir equals home directory (${n}), likely missing context field`;if(e==="/"||e==="")return`workspaceDir is root or empty: "${e}"`;if(/^[A-Za-z]:\\?$/.test(e))return`workspaceDir is a drive root: "${e}"`;let r=n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),i=[{pattern:new RegExp(`^${r}[\\\\/]?$`),desc:"is home directory"}];for(let{pattern:o,desc:a}of i)if(o.test(e))return`workspaceDir ${a}: "${e}"`;return null}import*as iS from"fs";import*as rZ from"path";var QEt={language:"zh",diagnostician:{context:{time_window_minutes:5,max_message_length:500,max_summary_length:3e3}},thresholds:{pain_trigger:40,cognitive_paralysis_input:4e3,stuck_loops_trigger:4,semantic_min_score:.7,promotion_count_threshold:3,promotion_similarity_threshold:.8},scores:{paralysis:45,default_confusion:30,default_loop:40,tool_failure_friction:15,exit_code_penalty:50,spiral_penalty:30,missing_test_command_penalty:20,subagent_error_penalty:60,subagent_timeout_penalty:50},severity_thresholds:{high:70,medium:40,low:20},empathy_engine:{enabled:!0,dedupe_window_ms:6e4,penalties:{mild:10,moderate:25,severe:40},rate_limit:{max_per_turn:40,max_per_hour:120},model_calibration:{}},gfi_gate:{enabled:!0,thresholds:{low_risk_block:70,high_risk_block:40,large_change_block:50},large_change_lines:50,ep_tier_multipliers:{1:.5,2:.75,3:1,4:1.5,5:2},bash_safe_patterns:["^(ls|dir|pwd|which|where|echo|env|cat|type|head|tail|less|more)\\b","^git\\s+(status|log|diff|branch|show|remote)\\b","^npm\\s+(run|test|build|start)\\b","^make\\s*$","^make\\s+(-j\\d+|--jobs\\s*\\d+)$","^(gradle|mvn)\\s+(clean|build|test|compile)\\b"],bash_dangerous_patterns:["rm\\s+(-[a-z]*r[a-z]*f|-rf)","del\\s+/s","rmdir\\s+/s","git\\s+(push\\s+.*--force|reset\\s+--hard|clean\\s+-fd)","npm\\s+publish","pip\\s+upload","docker\\s+push","(curl|wget).*\\|\\s*(ba)?sh"]},compression:{line_threshold:100,size_threshold_kb:15,interval_hours:24,keep_completed_tasks:3,max_working_memory_artifacts:10}},nZ=class{settings={...QEt};filePath;constructor(e){this.filePath=rZ.join(e,"pain_settings.json")}load(){if(iS.existsSync(this.filePath))try{let e=JSON.parse(iS.readFileSync(this.filePath,"utf8"));this.settings=this.deepMerge(QEt,e)}catch{console.error("[PD] Failed to parse pain_settings.json, using defaults.")}else console.log(`[PD:Config] Settings not found at ${this.filePath}, creating with defaults`),this.save()}save(){try{let e=rZ.dirname(this.filePath);iS.existsSync(e)||iS.mkdirSync(e,{recursive:!0}),Bt(this.filePath,JSON.stringify(this.settings,null,2)),console.log(`[PD:Config] Settings saved to ${this.filePath}`)}catch(e){console.error(`[PD:Config] Failed to save settings: ${String(e)}`)}}deepMerge(e,n){let r={...e};return n&&typeof n=="object"&&Object.keys(n).forEach(i=>{n[i]!==void 0&&(n[i]&&typeof n[i]=="object"&&!Array.isArray(n[i])?i in e?r[i]=this.deepMerge(e[i],n[i]):Object.assign(r,{[i]:n[i]}):Object.assign(r,{[i]:n[i]}))}),r}get(e){let n=e.split("."),r=this.settings;for(let i of n){if(r===void 0||r[i]===void 0)return;r=r[i]}return r}getAll(){return this.settings}};var t$=null,WEt=null,iZ={get(t){return(!t$||WEt!==t)&&(t$=new nZ(t),t$.load(),WEt=t),t$},reset(){t$=null}};import*as Zs from"fs";import*as n$ from"path";var $Et=7,SSe=class{logsDir;statsFile;logger;statsCache=new Map;eventBuffer=[];maxBufferSize=20;flushIntervalMs=3e4;flushTimer;currentEventsFile;currentDate;constructor(e,n){let r=Ym(e);this.logsDir=n$.join(r,"logs"),Zs.existsSync(this.logsDir)||Zs.mkdirSync(this.logsDir,{recursive:!0}),this.statsFile=n$.join(this.logsDir,"daily-stats.json"),this.logger=n,this.loadStats(),this.startFlushTimer()}getEventsFile(e){return n$.join(this.logsDir,`events_${e}.jsonl`)}getTodayStr(){return new Date().toISOString().split("T")[0]??""}ensureEventsFile(){let e=this.getTodayStr();return(this.currentDate!==e||!this.currentEventsFile)&&(this.currentDate=e,this.currentEventsFile=this.getEventsFile(e),this.cleanupOldEventFiles(e)),this.currentEventsFile}cleanupOldEventFiles(e){if(!($Et<=0))try{let n=Date.now()-$Et*24*60*60*1e3,r=Zs.readdirSync(this.logsDir);for(let i of r){if(!i.startsWith("events_")||!i.endsWith(".jsonl"))continue;let o=n$.join(this.logsDir,i);Zs.statSync(o).mtimeMs<n&&Zs.unlinkSync(o)}}catch(n){this.logger?.debug?.(`[PD] Event file cleanup failed (non-blocking): ${String(n)}`)}}recordToolCall(e,n){let r=n.error||n.exitCode!==void 0&&n.exitCode!==0?"failure":"success";this.record("tool_call",r,e,n)}recordPainSignal(e,n){this.record("pain_signal","detected",e,n)}recordRulePromotion(e){this.record("rule_promotion","promoted",void 0,e)}recordGovernanceAction(e,n){this.record("governance_action","approved",void 0,e),n?.flushImmediately&&this.flushEvents()}recordHookExecution(e,n){let r=e.error?"failure":"success";this.record("hook_execution",r,void 0,e),n?.flushImmediately&&this.flushEvents()}recordGateBlock(e,n){this.record("gate_block","blocked",e,n)}recordGateBypass(e,n){this.record("gate_bypass","bypassed",e,n)}recordEmpathyRollback(e,n){this.record("empathy_rollback","rolled_back",e,n)}recordError(e,n,r){this.record("error","failure",e,{message:n,...r})}recordWarn(e,n,r){this.record("warn","failure",e,{message:n,...r})}recordDiagnosisTask(e){this.record("diagnosis_task","written",void 0,e)}recordHeartbeatDiagnosis(e){this.record("heartbeat_diagnosis","injected",void 0,e)}recordDiagnosticianReport(e){let n={success:"completed",missing_json:"failure",incomplete_fields:"failure"};this.record("diagnostician_report",n[e.category],void 0,e)}recordPrincipleCandidate(e){this.record("principle_candidate","created",void 0,e)}recordRuleEnforced(e){this.record("rule_enforced","matched",void 0,e)}recordRuleHostEvaluated(e){this.record("rulehost_evaluated","evaluated",void 0,e)}recordRuleHostBlocked(e){this.record("rulehost_blocked","blocked",void 0,e)}recordRuleHostRequireApproval(e){this.record("rulehost_requireApproval","requireApproval",void 0,e)}recordRuleHostAutoCorrectProposed(e){this.record("rulehost_auto_correct_proposed","auto_correct",void 0,e)}recordRuleHostAutoCorrectApplied(e){this.record("rulehost_auto_correct_applied","auto_correct",void 0,e)}recordRuntimeV2ActivationsInjected(e){this.record("runtime_v2_prompt_activations_injected","injected",e.sessionId,e)}recordRuleHostUnhealthy(e){this.record("rulehost_unhealthy","failure",void 0,e)}recordRuleHostSkipped(e){this.record("rulehost_skipped","failure",void 0,e)}recordTrajectoryObservabilityFailure(e){this.record("trajectory_observability_failure","failure",e.sessionId,e)}redactEventData(e,n){try{if(!new Set(["tool_call","rulehost_evaluated","rulehost_blocked","rulehost_requireApproval","rulehost_auto_correct_proposed","rulehost_auto_correct_applied","rulehost_skipped","trajectory_observability_failure","rule_enforced","hook_execution","gate_block","gate_bypass"]).has(e))return n;let i={};for(let[o,a]of Object.entries(n))if(typeof a=="string")i[o]=gv(a);else if(Array.isArray(a))i[o]=a.map(s=>{if(typeof s=="string")return gv(s);if(typeof s=="object"&&s!==null){let c={};for(let[u,l]of Object.entries(s))c[u]=typeof l=="string"?gv(l):l;return c}return s});else if(typeof a=="object"&&a!==null){let s={};for(let[c,u]of Object.entries(a))typeof u=="string"?s[c]=gv(u):s[c]=u;i[o]=s}else i[o]=a;return i}catch(r){return{redactionFailure:!0,redactionStatus:"failed","redaction.status":"failed",redactionReason:(r instanceof Error?r.message.slice(0,200):String(r).slice(0,200))||"unknown error",redactionDataDropped:!0,originalType:e,originalSessionId:n.sessionId??null}}}record(e,n,r,i){let o=new Date,a=this.formatDate(o),s=this.redactEventData(e,i),c={ts:o.toISOString(),date:a,type:e,category:n,sessionId:r,data:s};this.eventBuffer.push(c),this.updateStats(c),this.eventBuffer.length>=this.maxBufferSize&&this.flushEvents()}formatDate(e){return e.toISOString().split("T")[0]??""}loadStats(){if(Zs.existsSync(this.statsFile))try{let e=JSON.parse(Zs.readFileSync(this.statsFile,"utf-8"));for(let n in e)this.statsCache.set(n,e[n])}catch(e){this.logger&&this.logger.error(`[PD] Failed to load daily-stats.json: ${String(e)}`)}}updateStats(e){let n=this.statsCache.get(e.date);if(n||(n=_C(e.date),this.statsCache.set(e.date,n)),e.type==="tool_call"){n.tools.total++,e.category==="success"?n.tools.success++:n.tools.failure++;let r=e.data,i=r.gfiAfter??r.gfi;i!==void 0&&(n.gfi.samples++,n.gfi.total+=i,n.gfi.peak=Math.max(n.gfi.peak,i))}else if(e.type==="pain_signal"){let r=e.data;if(r.source==="user_empathy"){if(r.deduped)n.empathy.dedupedCount++;else{n.empathy.totalEvents++,n.empathy.totalPenaltyScore+=r.score||0,r.severity&&(n.empathy.bySeverity[r.severity]++,n.empathy.scoreBySeverity[r.severity]+=r.score||0),r.detection_mode&&n.empathy.byDetectionMode[r.detection_mode]++,r.origin&&n.empathy.byOrigin[r.origin]++;let o=r.confidence??1;o>=.8?n.empathy.confidenceDistribution.high++:o>=.5?n.empathy.confidenceDistribution.medium++:n.empathy.confidenceDistribution.low++}let i=n.empathy.totalEvents+n.empathy.dedupedCount;n.empathy.dedupeHitRate=i>0?n.empathy.dedupedCount/i:0}}else if(e.type==="hook_execution"){let r=e.data;if(n.hooks.total++,e.category==="success"?n.hooks.success++:n.hooks.failure++,r.hook){n.hooks.byType[r.hook]||(n.hooks.byType[r.hook]={total:0,success:0,failure:0});let i=n.hooks.byType[r.hook];i&&(i.total++,e.category==="success"?i.success++:i.failure++)}}else if(e.type==="empathy_rollback"){let r=e.data;n.empathy.rollbackCount++,n.empathy.rolledBackScore+=r.originalScore||0}else if(e.type==="rule_promotion")n.evolution.rulesPromoted++;else if(e.type==="evolution_task")e.category==="completed"?n.evolution.tasksCompleted++:e.category==="enqueued"&&n.evolution.tasksEnqueued++;else if(e.type==="diagnosis_task")n.evolution.diagnosisTasksWritten++;else if(e.type==="heartbeat_diagnosis")n.evolution.heartbeatsInjected++;else if(e.type==="diagnostician_report"){let r=e.data;if(Object.prototype.hasOwnProperty.call(r,"category")){let i=r.category;typeof i=="string"&&(i==="success"||i==="missing_json"||i==="incomplete_fields")&&n.evolution.diagnosticianReportsWritten++,typeof i=="string"&&i==="missing_json"&&n.evolution.reportsMissingJson++,typeof i=="string"&&i==="incomplete_fields"&&n.evolution.reportsIncompleteFields++}else Object.prototype.hasOwnProperty.call(r,"success")&&n.evolution.diagnosticianReportsWritten++}else e.type==="principle_candidate"?n.evolution.principleCandidatesCreated++:e.type==="rule_enforced"?n.evolution.rulesEnforced++:e.type==="rulehost_evaluated"?n.evolution.rulehostEvaluated++:e.type==="rulehost_blocked"?n.evolution.rulehostBlocked++:e.type==="rulehost_requireApproval"?n.evolution.rulehostRequireApproval++:e.type==="rulehost_auto_correct_proposed"?n.evolution.rulehostAutoCorrectProposed++:e.type==="rulehost_auto_correct_applied"&&n.evolution.rulehostAutoCorrectApplied++}startFlushTimer(){this.flushTimer=setInterval(()=>this.flush(),this.flushIntervalMs),this.flushTimer.unref()}flush(){this.flushEvents(),this.flushStats()}getBufferedEvents(){return this.eventBuffer.map(e=>({...e,data:{...e.data}}))}getEventDedupKey(e){let n=typeof e.data?.eventId=="string"?String(e.data.eventId):null;if(n)return`${e.type}:${e.sessionId??"none"}:${n}`;let r=e.data??{};return[e.ts??"no-ts",e.type??"no-type",e.category??"no-category",e.sessionId??"no-session",typeof r.source=="string"?r.source:"no-source",typeof r.toolName=="string"?r.toolName:"no-tool",typeof r.reason=="string"?r.reason:"no-reason"].join("::")}readPersistedEvents(){let e=this.ensureEventsFile();if(!Zs.existsSync(e))return[];try{return Zs.readFileSync(e,"utf-8").trim().split(`
|
|
2198
2198
|
`).filter(r=>r.trim().length>0).map(r=>{try{return JSON.parse(r)}catch(i){return this.logger?.warn?.(`[PD] Corrupted event line skipped: ${String(i).slice(0,100)}`),null}}).filter(r=>r!==null)}catch(n){return this.logger&&this.logger.error(`[PD] Failed to read events file: ${String(n)}`),[]}}getMergedEvents(){let e=new Map;for(let n of[...this.readPersistedEvents(),...this.getBufferedEvents()])e.set(this.getEventDedupKey(n),n);return[...e.values()].sort((n,r)=>n.ts.localeCompare(r.ts))}flushEvents(){if(this.eventBuffer.length===0)return;let e=this.ensureEventsFile(),n=this.eventBuffer.map(r=>JSON.stringify(r)).join(`
|
|
2199
2199
|
`)+`
|
|
2200
2200
|
`;try{Zs.appendFileSync(e,n,"utf-8"),this.eventBuffer=[]}catch(r){this.logger&&this.logger.error(`[PD] Failed to flush events: ${String(r)}`)}}flushStats(){if(this.statsCache.size===0)return;let e={};this.statsCache.forEach((n,r)=>{e[r]=n});try{Bt(this.statsFile,JSON.stringify(e,null,2))}catch(n){this.logger&&this.logger.error(`[PD] Failed to flush daily-stats.json: ${String(n)}`)}}getDailyStats(e){let n=this.statsCache.get(e);return n||(n=_C(e),this.statsCache.set(e,n)),n}getEmpathyStats(e,n){let r=new Date,i=this.formatDate(r),o={totalEvents:0,dedupedCount:0,dedupeHitRate:0,totalPenaltyScore:0,rolledBackScore:0,rollbackCount:0,bySeverity:{mild:0,moderate:0,severe:0},scoreBySeverity:{mild:0,moderate:0,severe:0},byDetectionMode:{structured:0,legacy_tag:0},byOrigin:{assistant_self_report:0,user_manual:0,system_infer:0},confidenceDistribution:{high:0,medium:0,low:0},dailyTrend:[]};if(e==="session"&&n)this.aggregateSessionEmpathy(n,o);else if(e==="week")for(let s=0;s<7;s++){let c=new Date(r);c.setDate(c.getDate()-s);let u=this.formatDate(c),l=this.getDailyStats(u);o.totalEvents+=l.empathy.totalEvents,o.dedupedCount+=l.empathy.dedupedCount,o.totalPenaltyScore+=l.empathy.totalPenaltyScore,o.rolledBackScore+=l.empathy.rolledBackScore,o.rollbackCount+=l.empathy.rollbackCount;for(let p of["mild","moderate","severe"])o.bySeverity[p]+=l.empathy.bySeverity[p],o.scoreBySeverity[p]+=l.empathy.scoreBySeverity[p];o.byDetectionMode.structured+=l.empathy.byDetectionMode.structured,o.byDetectionMode.legacy_tag+=l.empathy.byDetectionMode.legacy_tag;for(let p of["assistant_self_report","user_manual","system_infer"])o.byOrigin[p]+=l.empathy.byOrigin[p];o.confidenceDistribution.high+=l.empathy.confidenceDistribution.high,o.confidenceDistribution.medium+=l.empathy.confidenceDistribution.medium,o.confidenceDistribution.low+=l.empathy.confidenceDistribution.low,(l.empathy.totalEvents>0||l.empathy.dedupedCount>0)&&o.dailyTrend.push({date:u,count:l.empathy.totalEvents,score:l.empathy.totalPenaltyScore})}else{let s=this.getDailyStats(i);Object.assign(o,s.empathy),(s.empathy.totalEvents>0||s.empathy.dedupedCount>0)&&(o.dailyTrend=[{date:i,count:s.empathy.totalEvents,score:s.empathy.totalPenaltyScore}])}let a=o.totalEvents+o.dedupedCount;return o.dedupeHitRate=a>0?o.dedupedCount/a:0,o}aggregateSessionEmpathy(e,n){for(let r of this.getMergedEvents())if(r.sessionId===e&&r.type==="pain_signal"){let i=r.data;if(i.source==="user_empathy")if(i.deduped)n.dedupedCount++;else{n.totalEvents++,n.totalPenaltyScore+=i.score||0,i.severity&&(n.bySeverity[i.severity]++,n.scoreBySeverity[i.severity]+=i.score||0),i.detection_mode&&n.byDetectionMode[i.detection_mode]++,i.origin&&n.byOrigin[i.origin]++;let o=i.confidence??1;o>=.8?n.confidenceDistribution.high++:o>=.5?n.confidenceDistribution.medium++:n.confidenceDistribution.low++}}else if(r.sessionId===e&&r.type==="empathy_rollback"){let i=r.data;n.rollbackCount++,n.rolledBackScore+=i.originalScore||0}}rollbackEmpathyEvent(e,n,r,i){let o=this.getMergedEvents(),a=null;for(let c of o)if(c.type==="pain_signal"){let u=c.data;if(u.eventId===e&&u.source==="user_empathy"){a={entry:c,data:u};break}}if(!a||a.data.deduped)return 0;let s=a.data.score||0;return this.recordEmpathyRollback(n,{eventId:e,originalScore:s,originalSessionId:a.entry.sessionId,reason:r,triggeredBy:i}),s}getLastEmpathyEventId(e){let n=this.getMergedEvents();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i&&i.sessionId===e&&i.type==="pain_signal"){let o=i.data;if(o.source==="user_empathy"&&!o.deduped)return o.eventId||null}}return null}findLatestPainSignal(e){let n=this.getMergedEvents();for(let r=n.length-1;r>=0;r--){let i=n[r];if(i&&i.sessionId===e&&i.type==="pain_signal")return i.data}return null}dispose(){this.flushTimer&&(clearInterval(this.flushTimer),this.flushTimer=void 0),this.flush()}},ec=class{static instances=new Map;static get(e,n){let r=this.instances.get(e);return r||(r=new SSe(e,n),this.instances.set(e,r)),r}static flushAll(){for(let e of this.instances.values())e.flush()}static disposeAll(){for(let e of this.instances.values())e.dispose();this.instances.clear()}};import*as GEt from"fs";import*as CSe from"path";import*as oS from"fs";import*as HEt from"path";var oZ=class{filePath;defaultFactory;constructor(e,n){this.filePath=e,this.defaultFactory=n}load(){try{if(!oS.existsSync(this.filePath))return this.defaultFactory();let e=oS.readFileSync(this.filePath,"utf8");return e?JSON.parse(e):this.defaultFactory()}catch{return console.warn(`[JsonFileStore] File corrupt or unreadable, using defaults: ${this.filePath}`),this.defaultFactory()}}save(e){let n=HEt.dirname(this.filePath);oS.existsSync(n)||oS.mkdirSync(n,{recursive:!0}),Bt(this.filePath,JSON.stringify(e,null,2))}mutate(e){let n=this.load(),r=e(n);return this.save(n),r}};var JGn=["[EVOLUTION_ACK]","HEARTBEAT_OK","HEARTBEAT_CHECK"];function r$(t){let e=t.trim();return e?JGn.some(n=>e===n||e.startsWith(`${n} `)||e.includes(n)):!1}var jEt={P_CONFUSION_ZH:{type:"regex",pattern:"\u6211(\u4F3C\u4E4E|\u597D\u50CF)(\u4E0D\u786E\u5B9A|\u4E0D\u592A\u786E\u5B9A|\u4E0D\u6E05\u695A|\u56F0\u60D1)",severity:35,hits:0,status:"active"},P_CONFUSION_EN:{type:"regex",pattern:"i am (not sure|unsure|confused|uncertain|struggling to)",severity:35,hits:0,status:"active"},P_LOOP_ZH:{type:"regex",pattern:"\u4F3C\u4E4E(\u9677\u5165\u4E86?\u5FAA\u73AF|\u56DE\u5230\u4E86?\u539F\u70B9|\u539F\u5730\u6253\u8F6C)",severity:45,hits:0,status:"active"},P_LOOP_EN:{type:"exact_match",phrases:["going in circles","back to square one","looping"],severity:45,hits:0,status:"active"}},aZ=class{constructor(e){this.stateDir=e;let n=CSe.join(e,"pain_dictionary.json");this.store=new oZ(n,()=>({rules:{...jEt}}))}stateDir;data={rules:{}};store;compiledRegex=new Map;load(){let e=CSe.join(this.stateDir,"pain_dictionary.json"),n=GEt.existsSync(e),r=this.store.load();r.rules&&Object.keys(r.rules).length>0?this.data=r:(this.data={rules:{...jEt}},n?console.warn("[PD:Dictionary] Dictionary corrupt or empty, preserving file and using defaults"):(console.log("[PD:Dictionary] Dictionary not found, creating with default rules"),this.flush())),this.compile()}compile(){this.compiledRegex.clear();for(let[e,n]of Object.entries(this.data.rules))n.type==="regex"&&n.pattern&&this.compiledRegex.set(e,new RegExp(n.pattern,"i"))}getRule(e){return this.data.rules[e]}getAllRules(){return this.data.rules}addRule(e,n){this.data.rules[e]={...n,hits:this.data.rules[e]?.hits||0},n.type==="regex"&&n.pattern&&this.compiledRegex.set(e,new RegExp(n.pattern,"i"))}match(e){if(r$(e))return;let n;for(let[r,i]of Object.entries(this.data.rules)){if(i.status!=="active")continue;let o=!1;if(i.type==="regex"){let a=this.compiledRegex.get(r);a&&(a.lastIndex=0,a.test(e)&&(o=!0))}else if(i.type==="exact_match"&&i.phrases){let a=e.toLowerCase();i.phrases.some(s=>a.includes(s.toLowerCase()))&&(o=!0)}o&&(i.hits++,(!n||i.severity>n.severity)&&(n={ruleId:r,severity:i.severity}))}return n}flush(){this.store.save(this.data)}getStats(){let e=0;for(let n of Object.values(this.data.rules))e+=n.hits||0;return{totalRules:Object.keys(this.data.rules).length,totalHits:e}}};var i$=null,qEt=null,sZ={get(t){return(!i$||qEt!==t)&&(i$=new aZ(t),i$.load(),qEt=t),i$},reset(){i$=null}};import*as Lm from"fs";import*as uZ from"path";var cZ=class{statsFile;currentStats;logger;constructor(e,n){if(this.statsFile=uZ.join(e,"hygiene-stats.json"),this.logger=n,!Lm.existsSync(e))try{Lm.mkdirSync(e,{recursive:!0})}catch(r){this.logger?.error(`[PD] Failed to create state directory ${e}: ${String(r)}`)}this.currentStats=this.loadStats()}loadStats(){let e=new Date().toISOString().split("T")[0]??"";if(Lm.existsSync(this.statsFile))try{let n=Lm.readFileSync(this.statsFile,"utf-8");if(n.trim()){let r=JSON.parse(n);if(r[e])return r[e]}}catch(n){this.logger?.error(`[PD] Failed to load/parse hygiene-stats.json: ${String(n)}`);try{let r=`${this.statsFile}.bak`;Lm.renameSync(this.statsFile,r),this.logger?.warn(`[PD] Corrupted hygiene stats backed up to ${r}`)}catch{}}return VI(e)}saveStats(){let e={},n=new Date().toISOString().split("T")[0]??"";if(this.currentStats.date!==n&&(this.currentStats=VI(n)),Lm.existsSync(this.statsFile))try{let r=Lm.readFileSync(this.statsFile,"utf-8");r.trim()&&(e=JSON.parse(r))}catch(r){this.logger?.error(`[PD] Failed to parse hygiene-stats.json for saving: ${String(r)}`)}e[this.currentStats.date]=this.currentStats;try{Bt(this.statsFile,JSON.stringify(e,null,2))}catch(r){this.logger?.error(`[PD] Failed to write hygiene-stats.json: ${String(r)}`)}}recordPersistence(e){this.currentStats.persistenceCount++,this.currentStats.lastPersistenceTime=e.ts,this.currentStats.totalCharsPersisted+=e.contentLength;let n=uZ.basename(e.path);this.currentStats.persistenceByFile[n]=(this.currentStats.persistenceByFile[n]||0)+1,this.saveStats(),this.logger?.info(`[PD] Hygiene: Persisted state to ${n} (${e.contentLength} chars)`)}recordGrooming(){this.currentStats.groomingExecutedCount++,this.currentStats.lastGroomingTime=new Date().toISOString(),this.saveStats(),this.logger?.info("[PD] Hygiene: Workspace grooming executed.")}getStats(){let e=new Date().toISOString().split("T")[0]??"";return this.currentStats.date!==e&&(this.currentStats=VI(e)),this.currentStats}};import*as Ds from"fs";import*as sS from"path";import*as Rd from"fs";import*as ef from"path";var lZ=new Map,kSe=new Map,KEt=7;function XGn(t,e){let n=e.toISOString().slice(0,10),r=ef.dirname(ca(t,"SYSTEM_LOG")),i=ef.basename(YX.SYSTEM_LOG,".log");return ef.join(r,`${i}_${n}.log`)}function ZGn(){return new Date().toISOString().slice(0,10)}function e4n(t){if(!(KEt<=0))try{let e=ef.dirname(ca(t,"SYSTEM_LOG")),r=`${ef.basename(YX.SYSTEM_LOG,".log")}_`;if(!Rd.existsSync(e))return;let i=Date.now()-KEt*24*60*60*1e3,o=Rd.readdirSync(e);for(let a of o){if(!a.startsWith(r)||!a.endsWith(".log"))continue;let s=ef.join(e,a);Rd.statSync(s).mtimeMs<i&&Rd.unlinkSync(s)}}catch{}}var VEt=new Map,Ue={log(t,e,n){if(!t)return;let r=Ym(t);try{let i=ef.resolve(r),o=ZGn();kSe.get(i)!==o&&(kSe.set(i,o),lZ.delete(i),VEt.get(i)!==o&&(VEt.set(i,o),e4n(r)));let a=lZ.get(i);if(!a){a=XGn(r,new Date),lZ.set(i,a);let u=ef.dirname(a);Rd.existsSync(u)||Rd.mkdirSync(u,{recursive:!0})}let c=`[${new Date().toISOString()}] [${e.padEnd(15)}] ${n}
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "2.2.
|
|
5
|
+
"version": "2.2.10",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"id": "principles-disciple",
|
|
3
3
|
"name": "Principles Disciple",
|
|
4
4
|
"description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
|
|
5
|
-
"version": "2.2.
|
|
5
|
+
"version": "2.2.9",
|
|
6
6
|
"activation": {
|
|
7
7
|
"onStartup": true,
|
|
8
8
|
"onCapabilities": [
|
package/plugin/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "principles-disciple",
|
|
3
|
-
"version": "2.2.
|
|
3
|
+
"version": "2.2.9",
|
|
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",
|
|
@@ -257,12 +257,26 @@ export type LegacyRulePreflightRunner = (pdCliEntry: string, workspaceDir: strin
|
|
|
257
257
|
*/
|
|
258
258
|
export declare function parseCompatibilityScanStdout(stdout: unknown): LegacyRulePreflightOutcome;
|
|
259
259
|
/**
|
|
260
|
-
* PRI-693: materialize node_modules links for the BUNDLED (not yet
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
*
|
|
265
|
-
*
|
|
260
|
+
* PRI-693 / PRI-1060: materialize node_modules links for the BUNDLED (not yet
|
|
261
|
+
* deployed) components so the pre-deployment compatibility scan can execute
|
|
262
|
+
* the bundled pd-cli. Mirrors the links syncPdCli creates for the deployed
|
|
263
|
+
* copy — targets are the sibling component directories of the npm package
|
|
264
|
+
* (files whitelist: core/, host-runtime/, codex-adapter/, workbuddy-adapter/,
|
|
265
|
+
* install-layout/, plugin/). Idempotent.
|
|
266
|
+
*
|
|
267
|
+
* Links are materialized at BOTH levels:
|
|
268
|
+
*
|
|
269
|
+
* 1. <root>/pd-cli/node_modules/* — pd-cli's OWN first-hop imports.
|
|
270
|
+
* 2. <root>/node_modules/* — every OTHER bundled component's `file:../`
|
|
271
|
+
* sibling dependencies. Node resolves a component reached through a
|
|
272
|
+
* junction by its REAL path, so host-runtime/dist/index.js importing
|
|
273
|
+
* '@principles/core' never sees pd-cli's node_modules — it only resolves
|
|
274
|
+
* via the package root's node_modules (PRI-1060: this exact gap crashed
|
|
275
|
+
* the scan with ERR_MODULE_NOT_FOUND on every registry install). The
|
|
276
|
+
* third-party dependencies of the bundled graph (@sinclair/typebox,
|
|
277
|
+
* better-sqlite3, …) are declared as top-level installer dependencies so
|
|
278
|
+
* the surrounding npx/npm install places them one node_modules above the
|
|
279
|
+
* package, reachable by the same upward resolution.
|
|
266
280
|
*/
|
|
267
281
|
export declare function ensureBundledPdCliResolution(pdCliRoot: string): void;
|
|
268
282
|
export declare function runLegacyRuleContractPreflight(pluginDir: string, workspaceDir: string, runScan?: LegacyRulePreflightRunner): Promise<LegacyRulePreflightOutcome>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"installer.d.ts","sourceRoot":"","sources":["../src/installer.ts"],"names":[],"mappings":"AAaA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,cAAc,CAAC;AACnD,OAAO,EAoBL,KAAK,eAAe,EACpB,KAAK,kBAAkB,EAExB,MAAM,iBAAiB,CAAC;AACzB,OAAO,EAAqB,KAAK,UAAU,EAAE,MAAM,uBAAuB,CAAC;
|
|
1
|
+
{"version":3,"file":"installer.d.ts","sourceRoot":"","sources":["../src/installer.ts"],"names":[],"mappings":"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"}
|
|
@@ -13,6 +13,7 @@ import { checkOpenClawGateway, stopOpenClawGateway, restartOpenClawGateway } fro
|
|
|
13
13
|
import { t } from './i18n.js';
|
|
14
14
|
import { generateConfigYamlContent, ExistingConfigVerifyInfraError, validateExistingConfigYamlForPreserve, getConfigYamlPath, readEnabledChannelsFromConfigYaml, getOpenClawDir, getPdDir, getPdRuntimeDir, getInstallManifestPath, getPdRuntimeBackupsDir, getPluginExtDir, getInstalledPluginDir, getInstalledLayoutPackageDir, getPdBackupsDir, getInstalledPdCliDir, getInstalledBinDir, getInstalledConsoleDir, getHomeDir, isWindows, } from './mvp-config.js';
|
|
15
15
|
import { getHostInstallers } from './installers/index.js';
|
|
16
|
+
import { runWorkbuddyEarlyPreflight } from './installers/workbuddy-host-installer.js';
|
|
16
17
|
import { INSTALL_LAYOUT_VERSION, getWorkbuddyWorkspaceDir, installManifestHostsForPersist, mergeInstallManifestWorkspaces, parseInstallManifest } from '@principles/install-layout';
|
|
17
18
|
import { detectOpenClawMainWorkspaceDivergence } from './utils/workspace-divergence.js';
|
|
18
19
|
import { applySkillLanguageSelection } from './skill-language.js';
|
|
@@ -122,6 +123,9 @@ let activeHostTarget = 'openclaw';
|
|
|
122
123
|
function installsOpenClaw(host) {
|
|
123
124
|
return host === 'openclaw' || host === 'all';
|
|
124
125
|
}
|
|
126
|
+
function installsWorkbuddy(host) {
|
|
127
|
+
return host === 'workbuddy' || host === 'all';
|
|
128
|
+
}
|
|
125
129
|
function installedPluginDir() {
|
|
126
130
|
return getInstalledPluginDir();
|
|
127
131
|
}
|
|
@@ -1216,40 +1220,65 @@ export function parseCompatibilityScanStdout(stdout) {
|
|
|
1216
1220
|
return protocolInvalid(`ok is not a boolean`);
|
|
1217
1221
|
}
|
|
1218
1222
|
/**
|
|
1219
|
-
* PRI-693: materialize node_modules links for the BUNDLED (not yet
|
|
1220
|
-
*
|
|
1221
|
-
*
|
|
1222
|
-
*
|
|
1223
|
-
*
|
|
1224
|
-
*
|
|
1223
|
+
* PRI-693 / PRI-1060: materialize node_modules links for the BUNDLED (not yet
|
|
1224
|
+
* deployed) components so the pre-deployment compatibility scan can execute
|
|
1225
|
+
* the bundled pd-cli. Mirrors the links syncPdCli creates for the deployed
|
|
1226
|
+
* copy — targets are the sibling component directories of the npm package
|
|
1227
|
+
* (files whitelist: core/, host-runtime/, codex-adapter/, workbuddy-adapter/,
|
|
1228
|
+
* install-layout/, plugin/). Idempotent.
|
|
1229
|
+
*
|
|
1230
|
+
* Links are materialized at BOTH levels:
|
|
1231
|
+
*
|
|
1232
|
+
* 1. <root>/pd-cli/node_modules/* — pd-cli's OWN first-hop imports.
|
|
1233
|
+
* 2. <root>/node_modules/* — every OTHER bundled component's `file:../`
|
|
1234
|
+
* sibling dependencies. Node resolves a component reached through a
|
|
1235
|
+
* junction by its REAL path, so host-runtime/dist/index.js importing
|
|
1236
|
+
* '@principles/core' never sees pd-cli's node_modules — it only resolves
|
|
1237
|
+
* via the package root's node_modules (PRI-1060: this exact gap crashed
|
|
1238
|
+
* the scan with ERR_MODULE_NOT_FOUND on every registry install). The
|
|
1239
|
+
* third-party dependencies of the bundled graph (@sinclair/typebox,
|
|
1240
|
+
* better-sqlite3, …) are declared as top-level installer dependencies so
|
|
1241
|
+
* the surrounding npx/npm install places them one node_modules above the
|
|
1242
|
+
* package, reachable by the same upward resolution.
|
|
1225
1243
|
*/
|
|
1226
1244
|
export function ensureBundledPdCliResolution(pdCliRoot) {
|
|
1227
1245
|
const packageRoot = path.resolve(pdCliRoot, '..');
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
const linkSpecs = [
|
|
1236
|
-
{ linkPath: path.join(pdCliRoot, 'node_modules', '@principles', 'core'), windowsTarget: path.join(packageRoot, 'core'), unixTarget: '../../../core' },
|
|
1237
|
-
{ linkPath: path.join(pdCliRoot, 'node_modules', '@principles', 'host-runtime'), windowsTarget: path.join(packageRoot, 'host-runtime'), unixTarget: '../../../host-runtime' },
|
|
1238
|
-
{ linkPath: path.join(pdCliRoot, 'node_modules', '@principles', 'codex-adapter'), windowsTarget: path.join(packageRoot, 'codex-adapter'), unixTarget: '../../../codex-adapter' },
|
|
1239
|
-
{ linkPath: path.join(pdCliRoot, 'node_modules', '@principles', 'install-layout'), windowsTarget: path.join(packageRoot, 'install-layout'), unixTarget: '../../../install-layout' },
|
|
1240
|
-
{ linkPath: path.join(pdCliRoot, 'node_modules', 'principles-disciple'), windowsTarget: path.join(packageRoot, 'plugin'), unixTarget: '../../plugin' },
|
|
1246
|
+
const componentLinks = [
|
|
1247
|
+
{ linkName: path.join('@principles', 'core'), componentDir: 'core' },
|
|
1248
|
+
{ linkName: path.join('@principles', 'host-runtime'), componentDir: 'host-runtime' },
|
|
1249
|
+
{ linkName: path.join('@principles', 'codex-adapter'), componentDir: 'codex-adapter' },
|
|
1250
|
+
{ linkName: path.join('@principles', 'workbuddy-adapter'), componentDir: 'workbuddy-adapter' },
|
|
1251
|
+
{ linkName: path.join('@principles', 'install-layout'), componentDir: 'install-layout' },
|
|
1252
|
+
{ linkName: 'principles-disciple', componentDir: 'plugin' },
|
|
1241
1253
|
];
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1254
|
+
// Unix relative targets are computed from EACH link's own directory — a
|
|
1255
|
+
// wrong level produces a DANGLING link (existsSync() false, second run hits
|
|
1256
|
+
// EEXIST). Windows junctions take absolute targets and ignore the depth.
|
|
1257
|
+
const linkBases = [
|
|
1258
|
+
// <root>/pd-cli/node_modules/@principles/<name> → three levels up to
|
|
1259
|
+
// <root>; <root>/pd-cli/node_modules/principles-disciple → two levels.
|
|
1260
|
+
{ nodeModulesDir: path.join(pdCliRoot, 'node_modules'), depth: 3 },
|
|
1261
|
+
// <root>/node_modules/@principles/<name> → two levels up; principles-
|
|
1262
|
+
// disciple → one level.
|
|
1263
|
+
{ nodeModulesDir: path.join(packageRoot, 'node_modules'), depth: 2 },
|
|
1264
|
+
];
|
|
1265
|
+
for (const base of linkBases) {
|
|
1266
|
+
for (const spec of componentLinks) {
|
|
1267
|
+
const linkPath = path.join(base.nodeModulesDir, spec.linkName);
|
|
1268
|
+
if (existsSync(linkPath))
|
|
1269
|
+
continue;
|
|
1270
|
+
const windowsTarget = path.join(packageRoot, spec.componentDir);
|
|
1271
|
+
if (!existsSync(windowsTarget))
|
|
1272
|
+
continue; // component absent from this package layout — skip
|
|
1273
|
+
const depthUp = spec.linkName.includes(path.sep) ? base.depth : base.depth - 1;
|
|
1274
|
+
const unixTarget = `${'../'.repeat(depthUp)}${spec.componentDir}`;
|
|
1275
|
+
mkdirSync(path.dirname(linkPath), { recursive: true });
|
|
1276
|
+
if (isWindows()) {
|
|
1277
|
+
symlinkSync(windowsTarget, linkPath, 'junction');
|
|
1278
|
+
}
|
|
1279
|
+
else {
|
|
1280
|
+
symlinkSync(unixTarget, linkPath, 'dir');
|
|
1281
|
+
}
|
|
1253
1282
|
}
|
|
1254
1283
|
}
|
|
1255
1284
|
}
|
|
@@ -3231,6 +3260,27 @@ transaction) {
|
|
|
3231
3260
|
};
|
|
3232
3261
|
}
|
|
3233
3262
|
}
|
|
3263
|
+
// PRI-1062: WorkBuddy hard preflights run BEFORE any side effect — including
|
|
3264
|
+
// the gateway stop below. A running WorkBuddy holds settings.json with
|
|
3265
|
+
// exclusive sharing (the commit-stage rename fails with EPERM after minutes
|
|
3266
|
+
// of npm work) and hooks never launch without Git Bash. Both are knowable up
|
|
3267
|
+
// front; failing here costs one bash probe + two file opens instead of a
|
|
3268
|
+
// full install + rollback.
|
|
3269
|
+
//
|
|
3270
|
+
// Ordering is load-bearing: this must precede the gateway pre-flight. On
|
|
3271
|
+
// `--host all` the gateway block below may STOP the Owner's OpenClaw
|
|
3272
|
+
// gateway, and a refusal that returns from here would leave it stopped —
|
|
3273
|
+
// `restartedGateway` is only honoured at the end of the install flow.
|
|
3274
|
+
if (installsWorkbuddy(options.host)) {
|
|
3275
|
+
const workbuddyPreflight = runWorkbuddyEarlyPreflight();
|
|
3276
|
+
if (!workbuddyPreflight.ok) {
|
|
3277
|
+
logger.error(workbuddyPreflight.reason);
|
|
3278
|
+
return buildGatewayRefusalResult(options, {
|
|
3279
|
+
reason: `workbuddy_preflight_failed: ${workbuddyPreflight.reason}`,
|
|
3280
|
+
nextAction: workbuddyPreflight.nextAction,
|
|
3281
|
+
});
|
|
3282
|
+
}
|
|
3283
|
+
}
|
|
3234
3284
|
// Gateway lock pre-flight: a running gateway holds native-module file handles
|
|
3235
3285
|
// that make the backup rename fail with EPERM. Decide stop/abort/proceed
|
|
3236
3286
|
// BEFORE mutating anything (cli-5: abort/stop-failed paths must not mutate).
|