create-principles-disciple 1.148.9 → 1.148.10
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/package.json +1 -1
- package/console/dist/server/config/WorkspaceConfigStore.js +4 -3
- package/console/dist/server/console-ports.d.ts +13 -0
- package/console/dist/server/console-ports.js +15 -0
- package/console/dist/server/index.js +51 -5
- package/console/dist/server/routes/update-transaction.js +4 -4
- package/console/dist/server/routes/update.js +37 -21
- package/console/dist/server/utils/gateway.js +23 -6
- package/console/dist/server/utils/installed-layout.js +5 -3
- package/console/dist/server/utils/pd-backups.d.ts +6 -4
- package/console/dist/server/utils/pd-backups.js +8 -9
- package/console/dist/server/utils/pd-home.d.ts +34 -0
- package/console/dist/server/utils/pd-home.js +47 -0
- package/console/package.json +1 -1
- package/dist/update/bootstrap-executor.d.ts.map +1 -1
- package/dist/update/bootstrap-executor.js +33 -19
- package/dist/update/bootstrap-executor.js.map +1 -1
- package/host-runtime/package.json +1 -1
- package/install-layout/dist/index.d.ts +7 -0
- package/install-layout/dist/index.js +7 -0
- package/install-layout/dist/pd-home.d.ts +55 -0
- package/install-layout/dist/pd-home.js +226 -0
- package/install-layout/package.json +1 -1
- package/package.json +3 -3
- package/pd-cli/package.json +1 -1
- package/plugin/dist/bundle.js +5 -5
- package/release-manager/dist/update/bootstrap-executor.js +33 -19
- package/release-manager/package.json +1 -1
- package/workbuddy-adapter/package.json +1 -1
package/plugin/dist/bundle.js
CHANGED
|
@@ -2219,7 +2219,7 @@ try {
|
|
|
2219
2219
|
`}function zIt(){return H4n().replace(/-/g,"").slice(0,16)}function e$(e){try{return ra.readFileSync(e,"utf8")}catch{return}}function YIt(e){return e$(e.lockPath)===e.body}function QSe(e,t){let n;try{return n=ra.openSync(e,"wx"),ra.writeSync(n,t),ra.closeSync(n),n=void 0,"created"}catch(r){let i=typeof r=="object"&&r!==null&&Object.hasOwn(r,"code")?r.code:void 0;if(n!==void 0){try{ra.closeSync(n)}catch{}try{ra.rmSync(e,{force:!0})}catch{}}if(i==="EEXIST")return"busy";let o=r instanceof Error?r.message:String(r);return{error:`${typeof i=="string"?i:""} ${o}`.trim()}}}function WSe(e,t){let n=ZW.dirname(e),r=ZW.basename(e),i;try{i=ra.readdirSync(n)}catch{return}for(let o of i){if(!o.startsWith(`${r}.take-`)&&!o.startsWith(`${r}.rel-`))continue;let a=ZW.join(n,o);try{if(ra.statSync(a).mtimeMs>=Date.now()-t)continue;ra.rmSync(a,{force:!0})}catch{}}}function JIt(e){let{lockPath:t,staleBody:n,sidecarToken:r,staleMs:i}=e,o=`${t}.take-${r}`;try{ra.renameSync(t,o)}catch{return!1}let a;try{a=ra.statSync(o)}catch{return!1}let s=e$(o);if(a.mtimeMs<Date.now()-i&&s===n){try{ra.rmSync(o,{force:!0})}catch{}return!0}try{ra.existsSync(t)||ra.renameSync(o,t)}catch{}return!1}function mZ(e){let t=`${e.lockPath}.rel-${e.token}`;try{ra.renameSync(e.lockPath,t)}catch{return}if(e$(t)===e.body){try{ra.rmSync(t,{force:!0})}catch{}return}try{ra.existsSync(e.lockPath)||ra.renameSync(t,e.lockPath)}catch{}}async function XIt(e,t){let n=t?.lockPath??KIt(e),r=t?.staleMs??qIt,i=Date.now()+(t?.timeoutMs??j4n),o=zIt(),a=VIt(o);try{ra.mkdirSync(ZW.dirname(n),{recursive:!0})}catch(s){return{ok:!1,kind:"unwritable",detail:`mkdir failed: ${s instanceof Error?s.message:String(s)}`}}for(;;){let s=QSe(n,a);if(s==="created")return WSe(n,r),{ok:!0,handle:{lockPath:n,token:o,body:a}};if(typeof s=="object")return{ok:!1,kind:"unwritable",detail:s.error};let c=!1,u;try{ra.statSync(n).mtimeMs<Date.now()-r&&(u=e$(n),c=u!==void 0)}catch{}if(!(c&&u!==void 0&&JIt({lockPath:n,staleBody:u,sidecarToken:o,staleMs:r}))){if(Date.now()>=i)return{ok:!1,kind:"timeout"};await q4n(G4n)}}}function ZIt(e,t){let n=t?.lockPath??KIt(e),r=t?.staleMs??qIt,i=zIt(),o=VIt(i);try{ra.mkdirSync(ZW.dirname(n),{recursive:!0})}catch{return}let a=QSe(n,o);if(a==="created")return WSe(n,r),{lockPath:n,token:i,body:o};if(typeof a=="object")return;let s;try{ra.statSync(n).mtimeMs<Date.now()-r&&(s=e$(n))}catch{return}if(s!==void 0&&JIt({lockPath:n,staleBody:s,sidecarToken:i,staleMs:r})&&QSe(n,o)==="created")return WSe(n,r),{lockPath:n,token:i,body:o}}var K4n="product-telemetry.json",mf="2",$Se="1",evt=200,V4n=30;function jSe(){return{consent:"unset",consentVersion:iA,schemaVersion:mf}}function cS(e){return hZ.join(hZ.resolve(e),".pd",K4n)}function GSe(e){return e==="unset"||e==="granted"||e==="denied"}function AL(e){return e===void 0?!0:typeof e!="string"||e.length===0||e.length>40?!1:!Number.isNaN(Date.parse(e))}function tvt(e){return e===void 0?!0:UN(e)}function nvt(e){return e===void 0||typeof e=="number"&&Number.isInteger(e)&&e>=0&&e<=99}function rvt(e){return e===void 0||typeof e=="string"&&e.length>0&&e.length<=40}function ivt(e){return typeof e=="string"&&/^[0-9a-f]{4,32}$/.test(e)}function z4n(e,t){let n=[];for(let r of Object.keys(e))["lastAttemptedAt","lastSucceededAt","lastFailureCode","nextRetryAt","dailyAttemptCount","attemptBucketDate"].includes(r)||n.push(`${t}: unknown field '${r}'`);return(!AL(e.lastAttemptedAt)||!AL(e.lastSucceededAt)||!AL(e.nextRetryAt))&&n.push(`${t}: timestamps must be parseable ISO-8601 strings (\u226440 chars) when present`),nvt(e.dailyAttemptCount)||n.push(`${t}: dailyAttemptCount must be an integer 0\u201399 when present`),tvt(e.attemptBucketDate)||n.push(`${t}: attemptBucketDate must be a valid YYYY-MM-DD UTC date when present`),rvt(e.lastFailureCode)||n.push(`${t}: lastFailureCode must be a short non-empty string when present`),n}function HSe(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}var Y4n=["consent","consentVersion","telemetrySecret","workspaceExports","schemaVersion"],J4n=["consent","consentVersion","telemetrySecret","lastAttemptedAt","lastSucceededAt","lastFailureCode","nextRetryAt","dailyAttemptCount","attemptBucketDate","schemaVersion"];function X4n(e){return{consent:GSe(e.consent)?e.consent:"unset",consentVersion:typeof e.consentVersion=="string"?e.consentVersion:iA,...ip(e.telemetrySecret)?{telemetrySecret:e.telemetrySecret}:{},schemaVersion:mf}}function Z4n(e){let t={consent:GSe(e.consent)?e.consent:"unset",consentVersion:typeof e.consentVersion=="string"?e.consentVersion:iA,...ip(e.telemetrySecret)?{telemetrySecret:e.telemetrySecret}:{},...HSe(e.workspaceExports)?{workspaceExports:Object.fromEntries(Object.entries(e.workspaceExports).filter(([n,r])=>ivt(n)&&HSe(r)).map(([n,r])=>{let i=r;return[n,{...AL(i.lastAttemptedAt)&&i.lastAttemptedAt!==void 0?{lastAttemptedAt:i.lastAttemptedAt}:{},...AL(i.lastSucceededAt)&&i.lastSucceededAt!==void 0?{lastSucceededAt:i.lastSucceededAt}:{},...AL(i.nextRetryAt)&&i.nextRetryAt!==void 0?{nextRetryAt:i.nextRetryAt}:{},...rvt(i.lastFailureCode)&&i.lastFailureCode!==void 0?{lastFailureCode:i.lastFailureCode}:{},...nvt(i.dailyAttemptCount)&&i.dailyAttemptCount!==void 0?{dailyAttemptCount:i.dailyAttemptCount}:{},...tvt(i.attemptBucketDate)&&i.attemptBucketDate!==void 0?{attemptBucketDate:i.attemptBucketDate}:{}}]}))}:{},schemaVersion:mf};return t.workspaceExports!==void 0&&Object.keys(t.workspaceExports).length===0&&delete t.workspaceExports,t}function eqn(e){if(!HSe(e))return{ok:!1,errors:["state must be a JSON object"]};let t=e,{schemaVersion:n}=t,r=n===$Se;if(!r&&!(n===mf))return{ok:!1,errors:[`schemaVersion must be '${mf}' or legacy '${$Se}'`]};let o=r?J4n:Y4n,a=[];for(let s of Object.keys(t))o.includes(s)||a.push(`unknown field '${s}'`);if(GSe(t.consent)||a.push("consent must be unset|granted|denied"),(typeof t.consentVersion!="string"||t.consentVersion.length===0||t.consentVersion.length>8)&&a.push("consentVersion must be a short non-empty string"),!ip(t.telemetrySecret)&&t.telemetrySecret!==void 0&&a.push("telemetrySecret must be 64 hex chars when present"),r)return a.length>0?{ok:!1,errors:a}:{ok:!0,state:X4n(t),migratedFromLegacy:!0};if(t.workspaceExports!==void 0)if(typeof t.workspaceExports!="object"||t.workspaceExports===null||Array.isArray(t.workspaceExports))a.push("workspaceExports must be an object");else{let s=t.workspaceExports,c=Object.keys(s);c.length>evt&&a.push(`workspaceExports must track at most ${evt} workspaces`);for(let u of c){if(!ivt(u)){a.push(`workspaceExports key '${u}' must be 4\u201332 hex chars`);continue}let l=s[u];if(typeof l!="object"||l===null||Array.isArray(l)){a.push(`workspaceExports['${u}'] must be an object`);continue}a.push(...z4n(l,`workspaceExports['${u}']`))}}return a.length>0?{ok:!1,errors:a}:{ok:!0,state:Z4n(t),migratedFromLegacy:!1}}function tqn(e,t){if(t.schemaVersion!==mf)return{ok:!1,reason:`product_telemetry_state_write_refused: only schemaVersion '${mf}' is writable, got '${String(t.schemaVersion).slice(0,16)}'`,nextAction:"Build states via defaultProductTelemetryControlState / grantedControlState / deniedControlState / resetControlState (schemaVersion is not a free choice)"};let n=cS(e),r=hZ.dirname(n),i=`${n}.tmp-${process.pid}-${Date.now()}`;try{return t$.mkdirSync(r,{recursive:!0}),t$.writeFileSync(i,`${JSON.stringify(t,null,2)}
|
|
2220
2220
|
`,{encoding:"utf8",mode:384}),t$.renameSync(i,n),{ok:!0}}catch(o){let a=o instanceof Error?o.message:String(o);try{t$.rmSync(i,{force:!0})}catch{}return{ok:!1,reason:`product_telemetry_state_write_failed: ${a}`,nextAction:`Check permissions on ${r}`}}}function ovt(e){let t;try{t=t$.readFileSync(e,"utf8")}catch(i){let o=typeof i=="object"&&i!==null&&Object.hasOwn(i,"code")?i.code:void 0,a=typeof o=="string"?o:void 0;return a==="ENOENT"?{ok:!0,state:jSe(),existed:!1,diskSchemaVersion:mf}:{ok:!1,reason:`product_telemetry_state_unreadable: ${a??String(i)}`,nextAction:`Check permissions on ${e}`}}let n;try{n=JSON.parse(t)}catch{return{ok:!1,reason:"product_telemetry_state_malformed_json",nextAction:`Fix or delete ${e} (delete = consent returns to unset)`}}let r=eqn(n);return r.ok?{ok:!0,state:r.state,existed:!0,diskSchemaVersion:r.migratedFromLegacy?$Se:mf}:{ok:!1,reason:`product_telemetry_state_malformed: ${r.errors.join("; ")}`,nextAction:`Fix or delete ${e} (delete = consent returns to unset)`}}function n$(e){let t=ovt(cS(e));return t.ok?{ok:!0,state:t.state,existed:t.existed}:t}async function r$(e,t,n){let r=cS(e),i=await XIt(r,n?.timeoutMs!==void 0?{timeoutMs:n.timeoutMs}:void 0);if(!i.ok)return i.kind==="timeout"?{ok:!1,reason:"product_telemetry_state_lock_timeout: another process holds the control-state lock",nextAction:"Retry the operation; if it keeps failing, check for a stuck PD process before touching ~/.pd/product-telemetry.json.state-lock"}:{ok:!1,reason:`product_telemetry_state_lock_unwritable: ${i.detail}`,nextAction:`Check permissions on ${hZ.dirname(r)}`};let o=i.handle;try{return{ok:!0,value:await t({readLatest:()=>ovt(r),write:c=>YIt(o)?tqn(e,c):{ok:!1,reason:"product_telemetry_state_lock_lost: another process took over the lock during this transaction; nothing was written",nextAction:"Retry the operation"}})}}catch(a){return{ok:!1,reason:`product_telemetry_state_transaction_error: ${a instanceof Error?a.message:String(a)}`,nextAction:"Retry the operation; the control state on disk was not left half-written (atomic temp+rename)"}}finally{mZ(o)}}function avt(e,t){let n=e.workspaceExports;if(n===void 0)return e;let r=t-V4n*24*60*60*1e3,i={};for(let[a,s]of Object.entries(n)){let c=[s.lastAttemptedAt,s.lastSucceededAt].filter(l=>l!==void 0).map(l=>Date.parse(l)),u=c.length>0?Math.max(...c):Number.NEGATIVE_INFINITY;Number.isNaN(u)||u<r||(i[a]=s)}let o={...e};return Object.keys(i).length>0?o.workspaceExports=i:delete o.workspaceExports,o}function svt(e){return{consent:"granted",consentVersion:iA,telemetrySecret:ip(e.telemetrySecret)?e.telemetrySecret:OH(),...e.workspaceExports!==void 0?{workspaceExports:e.workspaceExports}:{},schemaVersion:mf}}function cvt(){return{consent:"denied",consentVersion:iA,schemaVersion:mf}}function uvt(e){return{consent:e.consent,consentVersion:iA,...e.consent==="granted"?{telemetrySecret:OH()}:{},schemaVersion:mf}}import lvt from"node:fs";import gZ from"node:path";function nqn(e){return e==="1"||e==="true"}function dvt(e){return e!==void 0&&e!==""&&e!=="false"&&e!=="0"}function rqn(e){let t=gZ.resolve(e);for(let n=0;n<8;n+=1){let r=lvt.existsSync(gZ.join(t,"packages","principles-core")),i=lvt.existsSync(gZ.join(t,"packages","host-runtime"));if(r&&i)return!0;let o=gZ.dirname(t);if(o===t)break;t=o}return!1}function pvt(e){let t=[];return nqn(e.env.killSwitch)&&t.push("env_kill_switch"),dvt(e.env.ci)&&t.push("ci_environment"),dvt(e.env.vitest)&&t.push("vitest_environment"),e.env.e2eMode==="1"&&t.push("e2e_mode"),(e.workspaceEnvironment==="test"||e.workspaceEnvironment==="demo"||e.workspaceEnvironment==="development")&&t.push("workspace_environment"),e.installMode==="missing"&&t.push("install_layout_missing"),rqn(e.moduleDir)&&t.push("repo_checkout"),{suppressed:t.length>0,reasons:t}}var qSe="https://principles-website.pages.dev/api/product-telemetry/snapshot";function iqn(e,t){return fetch.call(globalThis,e,t)}async function fvt(e){let t=e.endpoint??qSe,n=e.timeoutMs??8e3,r=e.fetchFn??iqn,i=JSON.stringify(e.snapshot);if(Buffer.byteLength(i,"utf8")>4096)return{ok:!1,code:"invalid_response",retryable:!1};let o=new AbortController,a=setTimeout(()=>o.abort(),n);try{let s=await r(t,{method:"POST",headers:{"content-type":"application/json"},body:i,signal:o.signal}),{status:c}=s;return c>=200&&c<300?{ok:!0,status:c}:c===400?{ok:!1,code:"http_400",retryable:!1}:c===429?{ok:!1,code:"http_429",retryable:!0}:c>=500?{ok:!1,code:"http_5xx",retryable:!0}:{ok:!1,code:"http_unexpected_status",retryable:!1}}catch(s){return s instanceof Error&&s.name==="AbortError"?{ok:!1,code:"timeout",retryable:!0}:{ok:!1,code:"network_error",retryable:!0}}finally{clearTimeout(a)}}function mvt(e){return e?360*60*1e3:3600*1e3}import AZ from"node:fs";import i$ from"node:path";import oqn from"better-sqlite3";var aqn="principle_receipt_ledger";function sqn(e,t){return e===!0||t===!0?!0:e===!1&&t===!1?!1:null}function hvt(e,t,n){let{notes:r,unavailableNote:i}=n,o={};try{if(!AZ.existsSync(e)){for(let s of Object.keys(t))o[s]=!1;return o}}catch{for(let s of Object.keys(t))o[s]=null;return r.push(i),o}let a;try{a=new oqn(e,{readonly:!0})}catch(s){let c=s instanceof Error?s.message.split(`
|
|
2221
2221
|
`)[0]:String(s);for(let u of Object.keys(t))o[u]=null;return r.push(`${i}: ${c}`),o}try{for(let[s,c]of Object.entries(t))try{o[s]=a.prepare(c).pluck().get()===1}catch(u){let l=u instanceof Error?u.message.split(`
|
|
2222
|
-
`)[0]:String(u);o[s]=null,r.push(`${i}: ${l}`)}}finally{a.close()}return o}function KSe(e){let t=[],n={initialized:!1,painObserved:!1,principleObserved:!1,activationObserved:!1,presenceReceiptObserved:!1,effectReceiptObserved:!1,initializationFailed:!1},r=i$.resolve(e),i=i$.join(r,".pd","state.db"),o=AZ.existsSync(i),a=hvt(i,{schemaTableExists:"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_version')",schemaVersionPopulated:"SELECT EXISTS(SELECT 1 FROM schema_version)",principleCandidates:"SELECT EXISTS(SELECT 1 FROM principle_candidates)",activations:"SELECT EXISTS(SELECT 1 FROM activations)",presenceReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='presence')",effectReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='effect')"},{notes:t,unavailableNote:"state_db_unreadable"});o||t.push("state_db_missing");let s=a.schemaTableExists??null,c=a.schemaVersionPopulated??null;n.initialized=s===null?null:s===!1?!1:c??null,n.initializationFailed=o?n.initialized===null?null:!n.initialized:!1,n.principleObserved=a.principleCandidates??null,n.activationObserved=a.activations??null,jr(r,aqn).enabled?(n.presenceReceiptObserved=a.presenceReceipts??null,n.effectReceiptObserved=a.effectReceipts??null):(n.presenceReceiptObserved=null,n.effectReceiptObserved=null,t.push("receipt_collection_disabled"));let l=hvt(i$.join(r,".state","trajectory.db"),{painEvents:"SELECT EXISTS(SELECT 1 FROM pain_events)"},{notes:t,unavailableNote:"trajectory_db_unreadable"});n.painObserved=l.painEvents??null;let p=!1,f=i$.join(r,".state"),m=i$.join(f,"principle_training_state.json");if((()=>{try{return AZ.existsSync(m)}catch{return!1}})())if(!(()=>{try{return JSON.parse(AZ.readFileSync(m,"utf8")),!0}catch{return!1}})())p=null,t.push("principle_ledger_malformed");else try{let _=jn(f)?.tree?.principles;p=_!==null&&typeof _=="object"&&Object.keys(_).length>0}catch{p=null,t.push("principle_ledger_malformed")}return n.principleObserved=sqn(n.principleObserved,p),{facts:n,notes:t}}import XSe from"node:fs";import hqn from"node:os";import o$ from"node:path";import{fileURLToPath as gqn}from"node:url";import*as ko from"node:path";var gvt=1;var cqn=["codex","openclaw","workbuddy"];function uqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Avt(e){return typeof e=="string"&&cqn.includes(e)}function yvt(e){return typeof e=="string"&&e.length>0}function lqn(e){if(e===void 0)return{workspaces:[]};if(!Array.isArray(e))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let t=[];for(let n of e){if(typeof n!="string"||n.length===0||!ko.isAbsolute(n))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let r=ko.resolve(n);t.includes(r)||t.push(r)}return{workspaces:t}}function VSe(e){if(!uqn(e))return{error:"install_manifest_malformed: expected an object"};if(e.layoutVersion!==gvt)return{error:`install_manifest_unsupported_version: ${String(e.layoutVersion)}`};if(e.mode!=="canonical"&&e.mode!=="legacy")return{error:"install_manifest_malformed: mode must be canonical or legacy"};if(!Array.isArray(e.hosts)||!e.hosts.every(yvt))return{error:"install_manifest_malformed: hosts must be an array of host name strings"};let t=[];if(e.unknownHosts!==void 0){if(!Array.isArray(e.unknownHosts)||!e.unknownHosts.every(yvt))return{error:"install_manifest_malformed: unknownHosts must be an array of host name strings"};t=e.unknownHosts.filter(a=>!Avt(a))}if(e.hosts.length===0&&t.length===0)return{error:"install_manifest_malformed: hosts must contain at least one host"};let n=[],r=[],i=[];for(let a of[...new Set(e.hosts)])Avt(a)?n.push(a):(r.push(a),i.push({code:"install_manifest_unknown_host",host:a}));for(let a of t)r.includes(a)||(r.push(a),i.push({code:"install_manifest_unknown_host",host:a}));let o=lqn(e.workspaces);return o.error?{error:o.error}:{manifest:{layoutVersion:gvt,mode:e.mode,hosts:n,...r.length>0?{unknownHosts:r}:{},workspaces:o.workspaces},...i.length>0?{warnings:i}:{}}}function zSe(e){let t=ko.resolve(e),n=ko.join(t,".pd"),r=ko.join(n,"runtime"),i=ko.join(t,".openclaw");return{homeDir:t,pdDir:n,manifest:ko.join(n,"install.json"),runtimeDir:r,pluginDir:ko.join(r,"plugin"),installLayoutDir:ko.join(r,"install-layout"),coreDir:ko.join(r,"core"),hostRuntimeDir:ko.join(r,"host-runtime"),pdCliDir:ko.join(r,"pd-cli"),consoleDir:ko.join(r,"console"),binDir:ko.join(r,"bin"),codexDir:ko.join(n,"codex"),openClawDir:i,openClawExtensionDir:ko.join(i,"extensions","principles-disciple"),releaseManagerDir:ko.join(r,"release-manager"),codexAdapterDir:ko.join(r,"codex-adapter"),workbuddyAdapterDir:ko.join(r,"workbuddy-adapter"),mcpServerDir:ko.join(r,"pd-mcp-server")}}var dqn="principles-disciple",pqn="principles-disciple-market",cho=`${dqn}@${pqn}`;function _vt(e){let t=zSe(e.homeDir),n=VSe(e.manifest),{warnings:r}=n;return n.manifest&&n.manifest.mode==="canonical"&&e.canonicalRuntimeExists?{mode:"canonical",paths:t,manifest:n.manifest,...r!==void 0?{warnings:r}:{}}:e.canonicalRuntimeExists&&e.manifest!==void 0&&n.manifest===void 0?{mode:"missing",paths:t,reason:n.error??"install_manifest_malformed",nextAction:n.error?.startsWith("install_manifest_unsupported_version")?"Update PD Companion from https://github.com/csuzngjh/principles/releases (companion-v* Windows installer); do not reinstall the healthy PD runtime.":"Run the PD installer/updater to repair the structurally damaged installation manifest.",...r!==void 0?{warnings:r}:{}}:e.legacyExtensionExists?{mode:"legacy",paths:t,...n.manifest?{manifest:n.manifest}:{},reason:n.error??"install_layout_legacy_fallback",nextAction:"Run the installer update to migrate the shared runtime to ~/.pd/runtime.",...r!==void 0?{warnings:r}:{}}:{mode:"missing",paths:t,reason:n.error??"install_runtime_missing",nextAction:"Run npx create-principles-disciple to install or repair PD."}}import fqn from"node:fs";import Ivt from"node:path";function mqn(e){let t=Ivt.resolve(e);try{t=fqn.realpathSync(t)}catch{}let n=t.split(Ivt.sep).join("/");return process.platform==="win32"&&(n=n.toLowerCase()),n.length>1&&n.endsWith("/")&&(n=n.slice(0,-1)),n}function yZ(e,t){return Cre(e,mqn(t))}function vvt(e,t){return`${e}.export-lock.${t}`}var Evt="anonymous_product_telemetry",xvt="PD_TELEMETRY_DISABLED",Aqn="Preview only. Nothing was sent.",yqn=5,_qn=300*1e3;function Iqn(e,t){return ZIt(e,{lockPath:vvt(e,t),staleMs:_qn})}async function vqn(e){let t=await r$(e.homeDir,n=>{let r=n.readLatest();if(!r.ok)return"skipped_unreadable";if(r.state.consent!=="granted"||r.state.telemetrySecret!==e.secret)return"skipped_identity_changed";let i=avt(r.state,e.timestamp),o={...i,workspaceExports:{...i.workspaceExports??{},[e.scopeKey]:e.nextEntry}};return n.write(o).ok?"written":"skipped_unreadable"});return t.ok?t.value:"skipped_contention"}var Eqn=o$.dirname(gqn(import.meta.url));function YSe(e){try{return JSON.parse(XSe.readFileSync(e,"utf8"))}catch{return}}function JSe(e){let t=zSe(e),r=VSe(YSe(t.manifest)).manifest,i=XSe.existsSync(t.hostRuntimeDir),o=XSe.existsSync(t.openClawExtensionDir),a=_vt({homeDir:e,manifest:r,canonicalRuntimeExists:i,legacyExtensionExists:o}),s="other";r&&r.hosts.length===1&&(r.hosts[0]==="codex"||r.hosts[0]==="openclaw"||r.hosts[0]==="workbuddy")?[s]=r.hosts:o&&(s="openclaw");let c=YSe(o$.join(t.pluginDir,"package.json"))??YSe(o$.join(t.openClawExtensionDir,"package.json")),u=c!==null&&typeof c=="object"&&!Array.isArray(c)?c.version:void 0,l=typeof u=="string"?u.slice(0,32):"unknown";return{installMode:a.mode,hostKind:s,pdVersion:l}}function xqn(e){return e?Lr(e).effective.config.workspace?.environment??"unknown":"unknown"}function wvt(e={}){let t=()=>o$.resolve(e.homeDir??hqn.homedir()),n=()=>e.env??process.env,r=()=>o$.resolve(e.moduleDir??Eqn),i=()=>(e.now??Date.now)(),o=e.logger??{};function a(u){return pvt({env:{killSwitch:n()[xvt],ci:n().CI,vitest:n().VITEST,e2eMode:n().PD_E2E_MODE},workspaceEnvironment:xqn(u),installMode:JSe(t()).installMode,moduleDir:r()})}function s(u,l){let p=null,f=null;if(l){let h=jr(l,Evt);p=h.enabled,f=h.source}let m=a(l),g=[];return p===null?g.push("feature_flag_unresolved"):p!==!0&&g.push("feature_flag_disabled"),u.consent!=="granted"&&g.push(`consent_${u.consent}`),g.push(...m.reasons),{flagEnabled:p,flagSource:f,consent:u.consent,environmentSuppressed:m.suppressed,suppressionReasons:m.reasons,canExport:g.length===0,blockers:g}}function c(u){if(!u.canExport)return u.suppressionReasons.includes("env_kill_switch")?`Unset ${xvt} to allow telemetry export.`:u.flagEnabled===!1?`Set features.${Evt}.enabled: true in the workspace .pd/config.yaml.`:u.consent!=="granted"?"Run: pd telemetry enable --confirm":u.environmentSuppressed?`Telemetry is suppressed in this environment (${u.suppressionReasons.join(", ")}). This is expected for CI/test/dev environments.`:"Resolve the blockers listed above."}return{getStatus(u){let l=n$(t());if(!l.ok)return l;let p=s(l.state,u),f,m=l.state.telemetrySecret;if(u!==void 0&&ip(m)){let h=yZ(m,u);f=l.state.workspaceExports?.[h]}return{ok:!0,view:{...p,consentVersion:l.state.consentVersion,hasSecret:ip(l.state.telemetrySecret),...f?.lastAttemptedAt!==void 0?{lastAttemptedAt:f.lastAttemptedAt}:{},...f?.lastSucceededAt!==void 0?{lastSucceededAt:f.lastSucceededAt}:{},...f?.lastFailureCode!==void 0?{lastFailureCode:f.lastFailureCode}:{},...f?.nextRetryAt!==void 0?{nextRetryAt:f.nextRetryAt}:{},endpoint:e.endpoint??qSe,...c(p)!==void 0?{nextAction:c(p)}:{}}}},preview(u){let l=n$(t()),p=l.ok?l.state:jSe(),f=s(p,u),m=i(),g=vC(m),h=!ip(p.telemetrySecret),y=p.telemetrySecret??"0".repeat(64),_=yZ(y,u),v=JSe(t()),{facts:w,notes:b}=KSe(u),k=NH({dailyTelemetryId:DH(y,_,g),bucketDate:g,pdVersion:v.pdVersion,hostKind:v.hostKind,milestones:{initialized:w.initialized,painObserved:w.painObserved,principleObserved:w.principleObserved,activationObserved:w.activationObserved,presenceReceiptObserved:w.presenceReceiptObserved,effectReceiptObserved:w.effectReceiptObserved},reliability:{initializationFailed:w.initializationFailed}}),P=[...b];return h&&P.push("payload shape is exact; dailyTelemetryId is provisional and will change after pd telemetry enable"),l.ok||P.push(`control state unreadable (${l.reason}) \u2014 showing defaults`),{banner:Aqn,snapshot:k,gates:f,notes:P,secretEphemeral:h}},async enable(){let u=await r$(t(),l=>{let p=l.readLatest();return p.ok?l.write(svt(p.state)):p});return u.ok?u.value.ok?(o.info?.(`[PD:Telemetry] Consent granted (control state: ${cS(t())}).`),{ok:!0,consent:"granted"}):u.value:u},async disable(){let u=await r$(t(),l=>{let p=l.readLatest();return p.ok?l.write(cvt()):p});return u.ok?u.value.ok?(o.info?.("[PD:Telemetry] Consent denied; local telemetry secret and export status deleted. Future export requests: 0."),{ok:!0,consent:"denied"}):u.value:u},async reset(){let u=await r$(t(),l=>{let p=l.readLatest();if(!p.ok)return p;let f=uvt(p.state),m=l.write(f);return m.ok?{ok:!0,consent:f.consent}:m});return u.ok?u.value.ok?(o.info?.("[PD:Telemetry] Telemetry identity reset; previous daily IDs are unlinkable going forward."),{ok:!0,consent:u.value.consent}):u.value:u},async maybeExportDaily(u){let l=n$(t());if(!l.ok)return o.warn?.(`[PD:Telemetry] Export skipped: ${l.reason}`),{attempted:!1,skipReason:"control_state_unreadable"};let{state:p}=l,f=s(p,u);if(!f.flagEnabled)return{attempted:!1,skipReason:"feature_flag_disabled"};if(p.consent!=="granted")return{attempted:!1,skipReason:`consent_${p.consent}`};if(f.environmentSuppressed)return o.info?.(`[PD:Telemetry] Export suppressed (${f.suppressionReasons.join(", ")}).`),{attempted:!1,skipReason:`environment_suppressed:${f.suppressionReasons.join("+")}`};if(!ip(p.telemetrySecret))return o.warn?.("[PD:Telemetry] Export skipped: telemetry secret missing/invalid. Run: pd telemetry enable --confirm"),{attempted:!1,skipReason:"secret_missing"};let m=p.telemetrySecret,g=i(),h=vC(g),y=yZ(m,u),_=p.workspaceExports?.[y];if(_?.lastSucceededAt!==void 0&&vC(Date.parse(_.lastSucceededAt))===h)return{attempted:!1,skipReason:"already_succeeded_today"};if(_?.nextRetryAt!==void 0&&g<Date.parse(_.nextRetryAt))return{attempted:!1,skipReason:"retry_backoff"};let v=_?.attemptBucketDate===h?_?.dailyAttemptCount??0:0;if(v>=yqn)return{attempted:!1,skipReason:"daily_attempt_cap"};let w=Iqn(cS(t()),y);if(w===void 0)return o.info?.("[PD:Telemetry] Export skipped: another export is in flight for this workspace (lock busy)."),{attempted:!1,skipReason:"export_lock_busy"};try{let b=n$(t()),k=b.ok?b.state.telemetrySecret:void 0,P=b.ok&&k===m?b.state:p;if(ip(P.telemetrySecret)){let Ie=P.workspaceExports?.[y];if(Ie?.lastSucceededAt!==void 0&&vC(Date.parse(Ie.lastSucceededAt))===h)return{attempted:!1,skipReason:"already_succeeded_today"}}let B=JSe(t()),{facts:N}=KSe(u),T=NH({dailyTelemetryId:DH(m,y,h),bucketDate:h,pdVersion:B.pdVersion,hostKind:B.hostKind,milestones:{initialized:N.initialized,painObserved:N.painObserved,principleObserved:N.principleObserved,activationObserved:N.activationObserved,presenceReceiptObserved:N.presenceReceiptObserved,effectReceiptObserved:N.effectReceiptObserved},reliability:{initializationFailed:N.initializationFailed}}),M=await fvt({snapshot:T,...e.endpoint!==void 0?{endpoint:e.endpoint}:{},...e.fetchFn!==void 0?{fetchFn:e.fetchFn}:{}}),Q=P.workspaceExports?.[y],H=Q?.lastAttemptedAt!==void 0&&g-Date.parse(Q.lastAttemptedAt)<1440*60*1e3,ne=M.ok?{lastAttemptedAt:new Date(g).toISOString(),lastSucceededAt:new Date(g).toISOString()}:{lastAttemptedAt:new Date(g).toISOString(),lastFailureCode:M.code,nextRetryAt:new Date(g+mvt(H)).toISOString(),dailyAttemptCount:v+1,attemptBucketDate:h},$=await vqn({homeDir:t(),secret:m,scopeKey:y,timestamp:g,nextEntry:ne});return $==="skipped_contention"?o.warn?.(`[PD:Telemetry] Export ${M.ok?"succeeded":`failed (${M.code})`} but control state update was skipped after 3s of state-lock contention \u2014 this workspace may re-attempt today.`):$==="skipped_unreadable"?o.warn?.(`[PD:Telemetry] Export ${M.ok?"succeeded":`failed (${M.code})`} but control state could not be read/updated \u2014 ${cS(t())}`):$==="skipped_identity_changed"&&o.info?.("[PD:Telemetry] Export finished after a consent/secret change; stale export bookkeeping was NOT written back."),M.ok?(o.info?.("[PD:Telemetry] Daily anonymous product telemetry snapshot exported."),{attempted:!0,ok:!0,httpStatus:M.status}):(o.warn?.(`[PD:Telemetry] Export failed (${M.code}); next retry after ${ne.nextRetryAt}. PD behavior is unaffected.`),{attempted:!0,ok:!1,failureCode:M.code})}finally{mZ(w)}}}}function bvt(e,t,n){setTimeout(()=>{e.maybeExportDaily(t).catch(i=>{let o=i instanceof Error?i.message:String(i);n?.warn?.(`[PD:Telemetry] Unexpected export error (PD unaffected): ${o}`)})},0).unref?.()}import{createHash as _Z}from"node:crypto";import{isAbsolute as wqn,resolve as Svt}from"node:path";import{realpathSync as bqn}from"node:fs";function yL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sqn(){function e(a){let s=wqn(a)?Svt(a):Svt(process.cwd(),a),c=s;try{c=bqn(s)}catch{}return`pd-evidence-scope:sha256:${_Z("sha256").update(c,"utf8").digest("hex").slice(0,32)}`}function t(a){let s=e(a),c=null;try{c=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let u=new lL(c).getEvidenceScope();if(u)return u.scopeId}catch{}finally{try{c?.close()}catch{}}return s}function n(a,s,c){if(!s.artifactId)return null;let u=null;try{u=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let l=u.getDb();if(!l.prepare(`
|
|
2222
|
+
`)[0]:String(u);o[s]=null,r.push(`${i}: ${l}`)}}finally{a.close()}return o}function KSe(e){let t=[],n={initialized:!1,painObserved:!1,principleObserved:!1,activationObserved:!1,presenceReceiptObserved:!1,effectReceiptObserved:!1,initializationFailed:!1},r=i$.resolve(e),i=i$.join(r,".pd","state.db"),o=AZ.existsSync(i),a=hvt(i,{schemaTableExists:"SELECT EXISTS(SELECT 1 FROM sqlite_master WHERE type='table' AND name='schema_version')",schemaVersionPopulated:"SELECT EXISTS(SELECT 1 FROM schema_version)",principleCandidates:"SELECT EXISTS(SELECT 1 FROM principle_candidates)",activations:"SELECT EXISTS(SELECT 1 FROM activations)",presenceReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='presence')",effectReceipts:"SELECT EXISTS(SELECT 1 FROM principle_applications WHERE level='effect')"},{notes:t,unavailableNote:"state_db_unreadable"});o||t.push("state_db_missing");let s=a.schemaTableExists??null,c=a.schemaVersionPopulated??null;n.initialized=s===null?null:s===!1?!1:c??null,n.initializationFailed=o?n.initialized===null?null:!n.initialized:!1,n.principleObserved=a.principleCandidates??null,n.activationObserved=a.activations??null,jr(r,aqn).enabled?(n.presenceReceiptObserved=a.presenceReceipts??null,n.effectReceiptObserved=a.effectReceipts??null):(n.presenceReceiptObserved=null,n.effectReceiptObserved=null,t.push("receipt_collection_disabled"));let l=hvt(i$.join(r,".state","trajectory.db"),{painEvents:"SELECT EXISTS(SELECT 1 FROM pain_events)"},{notes:t,unavailableNote:"trajectory_db_unreadable"});n.painObserved=l.painEvents??null;let p=!1,f=i$.join(r,".state"),m=i$.join(f,"principle_training_state.json");if((()=>{try{return AZ.existsSync(m)}catch{return!1}})())if(!(()=>{try{return JSON.parse(AZ.readFileSync(m,"utf8")),!0}catch{return!1}})())p=null,t.push("principle_ledger_malformed");else try{let _=jn(f)?.tree?.principles;p=_!==null&&typeof _=="object"&&Object.keys(_).length>0}catch{p=null,t.push("principle_ledger_malformed")}return n.principleObserved=sqn(n.principleObserved,p),{facts:n,notes:t}}import XSe from"node:fs";import hqn from"node:os";import o$ from"node:path";import{fileURLToPath as gqn}from"node:url";import*as ko from"node:path";var gvt=1;var cqn=["codex","openclaw","workbuddy"];function uqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Avt(e){return typeof e=="string"&&cqn.includes(e)}function yvt(e){return typeof e=="string"&&e.length>0}function lqn(e){if(e===void 0)return{workspaces:[]};if(!Array.isArray(e))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let t=[];for(let n of e){if(typeof n!="string"||n.length===0||!ko.isAbsolute(n))return{error:"install_manifest_malformed: workspaces must be non-empty absolute paths"};let r=ko.resolve(n);t.includes(r)||t.push(r)}return{workspaces:t}}function VSe(e){if(!uqn(e))return{error:"install_manifest_malformed: expected an object"};if(e.layoutVersion!==gvt)return{error:`install_manifest_unsupported_version: ${String(e.layoutVersion)}`};if(e.mode!=="canonical"&&e.mode!=="legacy")return{error:"install_manifest_malformed: mode must be canonical or legacy"};if(!Array.isArray(e.hosts)||!e.hosts.every(yvt))return{error:"install_manifest_malformed: hosts must be an array of host name strings"};let t=[];if(e.unknownHosts!==void 0){if(!Array.isArray(e.unknownHosts)||!e.unknownHosts.every(yvt))return{error:"install_manifest_malformed: unknownHosts must be an array of host name strings"};t=e.unknownHosts.filter(a=>!Avt(a))}if(e.hosts.length===0&&t.length===0)return{error:"install_manifest_malformed: hosts must contain at least one host"};let n=[],r=[],i=[];for(let a of[...new Set(e.hosts)])Avt(a)?n.push(a):(r.push(a),i.push({code:"install_manifest_unknown_host",host:a}));for(let a of t)r.includes(a)||(r.push(a),i.push({code:"install_manifest_unknown_host",host:a}));let o=lqn(e.workspaces);return o.error?{error:o.error}:{manifest:{layoutVersion:gvt,mode:e.mode,hosts:n,...r.length>0?{unknownHosts:r}:{},workspaces:o.workspaces},...i.length>0?{warnings:i}:{}}}function zSe(e){let t=ko.resolve(e),n=ko.join(t,".pd"),r=ko.join(n,"runtime"),i=ko.join(t,".openclaw");return{homeDir:t,pdDir:n,manifest:ko.join(n,"install.json"),runtimeDir:r,pluginDir:ko.join(r,"plugin"),installLayoutDir:ko.join(r,"install-layout"),coreDir:ko.join(r,"core"),hostRuntimeDir:ko.join(r,"host-runtime"),pdCliDir:ko.join(r,"pd-cli"),consoleDir:ko.join(r,"console"),binDir:ko.join(r,"bin"),codexDir:ko.join(n,"codex"),openClawDir:i,openClawExtensionDir:ko.join(i,"extensions","principles-disciple"),releaseManagerDir:ko.join(r,"release-manager"),codexAdapterDir:ko.join(r,"codex-adapter"),workbuddyAdapterDir:ko.join(r,"workbuddy-adapter"),mcpServerDir:ko.join(r,"pd-mcp-server")}}var dqn="principles-disciple",pqn="principles-disciple-market",hho=`${dqn}@${pqn}`;function _vt(e){let t=zSe(e.homeDir),n=VSe(e.manifest),{warnings:r}=n;return n.manifest&&n.manifest.mode==="canonical"&&e.canonicalRuntimeExists?{mode:"canonical",paths:t,manifest:n.manifest,...r!==void 0?{warnings:r}:{}}:e.canonicalRuntimeExists&&e.manifest!==void 0&&n.manifest===void 0?{mode:"missing",paths:t,reason:n.error??"install_manifest_malformed",nextAction:n.error?.startsWith("install_manifest_unsupported_version")?"Update PD Companion from https://github.com/csuzngjh/principles/releases (companion-v* Windows installer); do not reinstall the healthy PD runtime.":"Run the PD installer/updater to repair the structurally damaged installation manifest.",...r!==void 0?{warnings:r}:{}}:e.legacyExtensionExists?{mode:"legacy",paths:t,...n.manifest?{manifest:n.manifest}:{},reason:n.error??"install_layout_legacy_fallback",nextAction:"Run the installer update to migrate the shared runtime to ~/.pd/runtime.",...r!==void 0?{warnings:r}:{}}:{mode:"missing",paths:t,reason:n.error??"install_runtime_missing",nextAction:"Run npx create-principles-disciple to install or repair PD."}}import fqn from"node:fs";import Ivt from"node:path";function mqn(e){let t=Ivt.resolve(e);try{t=fqn.realpathSync(t)}catch{}let n=t.split(Ivt.sep).join("/");return process.platform==="win32"&&(n=n.toLowerCase()),n.length>1&&n.endsWith("/")&&(n=n.slice(0,-1)),n}function yZ(e,t){return Cre(e,mqn(t))}function vvt(e,t){return`${e}.export-lock.${t}`}var Evt="anonymous_product_telemetry",xvt="PD_TELEMETRY_DISABLED",Aqn="Preview only. Nothing was sent.",yqn=5,_qn=300*1e3;function Iqn(e,t){return ZIt(e,{lockPath:vvt(e,t),staleMs:_qn})}async function vqn(e){let t=await r$(e.homeDir,n=>{let r=n.readLatest();if(!r.ok)return"skipped_unreadable";if(r.state.consent!=="granted"||r.state.telemetrySecret!==e.secret)return"skipped_identity_changed";let i=avt(r.state,e.timestamp),o={...i,workspaceExports:{...i.workspaceExports??{},[e.scopeKey]:e.nextEntry}};return n.write(o).ok?"written":"skipped_unreadable"});return t.ok?t.value:"skipped_contention"}var Eqn=o$.dirname(gqn(import.meta.url));function YSe(e){try{return JSON.parse(XSe.readFileSync(e,"utf8"))}catch{return}}function JSe(e){let t=zSe(e),r=VSe(YSe(t.manifest)).manifest,i=XSe.existsSync(t.hostRuntimeDir),o=XSe.existsSync(t.openClawExtensionDir),a=_vt({homeDir:e,manifest:r,canonicalRuntimeExists:i,legacyExtensionExists:o}),s="other";r&&r.hosts.length===1&&(r.hosts[0]==="codex"||r.hosts[0]==="openclaw"||r.hosts[0]==="workbuddy")?[s]=r.hosts:o&&(s="openclaw");let c=YSe(o$.join(t.pluginDir,"package.json"))??YSe(o$.join(t.openClawExtensionDir,"package.json")),u=c!==null&&typeof c=="object"&&!Array.isArray(c)?c.version:void 0,l=typeof u=="string"?u.slice(0,32):"unknown";return{installMode:a.mode,hostKind:s,pdVersion:l}}function xqn(e){return e?Lr(e).effective.config.workspace?.environment??"unknown":"unknown"}function wvt(e={}){let t=()=>o$.resolve(e.homeDir??hqn.homedir()),n=()=>e.env??process.env,r=()=>o$.resolve(e.moduleDir??Eqn),i=()=>(e.now??Date.now)(),o=e.logger??{};function a(u){return pvt({env:{killSwitch:n()[xvt],ci:n().CI,vitest:n().VITEST,e2eMode:n().PD_E2E_MODE},workspaceEnvironment:xqn(u),installMode:JSe(t()).installMode,moduleDir:r()})}function s(u,l){let p=null,f=null;if(l){let h=jr(l,Evt);p=h.enabled,f=h.source}let m=a(l),g=[];return p===null?g.push("feature_flag_unresolved"):p!==!0&&g.push("feature_flag_disabled"),u.consent!=="granted"&&g.push(`consent_${u.consent}`),g.push(...m.reasons),{flagEnabled:p,flagSource:f,consent:u.consent,environmentSuppressed:m.suppressed,suppressionReasons:m.reasons,canExport:g.length===0,blockers:g}}function c(u){if(!u.canExport)return u.suppressionReasons.includes("env_kill_switch")?`Unset ${xvt} to allow telemetry export.`:u.flagEnabled===!1?`Set features.${Evt}.enabled: true in the workspace .pd/config.yaml.`:u.consent!=="granted"?"Run: pd telemetry enable --confirm":u.environmentSuppressed?`Telemetry is suppressed in this environment (${u.suppressionReasons.join(", ")}). This is expected for CI/test/dev environments.`:"Resolve the blockers listed above."}return{getStatus(u){let l=n$(t());if(!l.ok)return l;let p=s(l.state,u),f,m=l.state.telemetrySecret;if(u!==void 0&&ip(m)){let h=yZ(m,u);f=l.state.workspaceExports?.[h]}return{ok:!0,view:{...p,consentVersion:l.state.consentVersion,hasSecret:ip(l.state.telemetrySecret),...f?.lastAttemptedAt!==void 0?{lastAttemptedAt:f.lastAttemptedAt}:{},...f?.lastSucceededAt!==void 0?{lastSucceededAt:f.lastSucceededAt}:{},...f?.lastFailureCode!==void 0?{lastFailureCode:f.lastFailureCode}:{},...f?.nextRetryAt!==void 0?{nextRetryAt:f.nextRetryAt}:{},endpoint:e.endpoint??qSe,...c(p)!==void 0?{nextAction:c(p)}:{}}}},preview(u){let l=n$(t()),p=l.ok?l.state:jSe(),f=s(p,u),m=i(),g=vC(m),h=!ip(p.telemetrySecret),y=p.telemetrySecret??"0".repeat(64),_=yZ(y,u),v=JSe(t()),{facts:w,notes:b}=KSe(u),k=NH({dailyTelemetryId:DH(y,_,g),bucketDate:g,pdVersion:v.pdVersion,hostKind:v.hostKind,milestones:{initialized:w.initialized,painObserved:w.painObserved,principleObserved:w.principleObserved,activationObserved:w.activationObserved,presenceReceiptObserved:w.presenceReceiptObserved,effectReceiptObserved:w.effectReceiptObserved},reliability:{initializationFailed:w.initializationFailed}}),P=[...b];return h&&P.push("payload shape is exact; dailyTelemetryId is provisional and will change after pd telemetry enable"),l.ok||P.push(`control state unreadable (${l.reason}) \u2014 showing defaults`),{banner:Aqn,snapshot:k,gates:f,notes:P,secretEphemeral:h}},async enable(){let u=await r$(t(),l=>{let p=l.readLatest();return p.ok?l.write(svt(p.state)):p});return u.ok?u.value.ok?(o.info?.(`[PD:Telemetry] Consent granted (control state: ${cS(t())}).`),{ok:!0,consent:"granted"}):u.value:u},async disable(){let u=await r$(t(),l=>{let p=l.readLatest();return p.ok?l.write(cvt()):p});return u.ok?u.value.ok?(o.info?.("[PD:Telemetry] Consent denied; local telemetry secret and export status deleted. Future export requests: 0."),{ok:!0,consent:"denied"}):u.value:u},async reset(){let u=await r$(t(),l=>{let p=l.readLatest();if(!p.ok)return p;let f=uvt(p.state),m=l.write(f);return m.ok?{ok:!0,consent:f.consent}:m});return u.ok?u.value.ok?(o.info?.("[PD:Telemetry] Telemetry identity reset; previous daily IDs are unlinkable going forward."),{ok:!0,consent:u.value.consent}):u.value:u},async maybeExportDaily(u){let l=n$(t());if(!l.ok)return o.warn?.(`[PD:Telemetry] Export skipped: ${l.reason}`),{attempted:!1,skipReason:"control_state_unreadable"};let{state:p}=l,f=s(p,u);if(!f.flagEnabled)return{attempted:!1,skipReason:"feature_flag_disabled"};if(p.consent!=="granted")return{attempted:!1,skipReason:`consent_${p.consent}`};if(f.environmentSuppressed)return o.info?.(`[PD:Telemetry] Export suppressed (${f.suppressionReasons.join(", ")}).`),{attempted:!1,skipReason:`environment_suppressed:${f.suppressionReasons.join("+")}`};if(!ip(p.telemetrySecret))return o.warn?.("[PD:Telemetry] Export skipped: telemetry secret missing/invalid. Run: pd telemetry enable --confirm"),{attempted:!1,skipReason:"secret_missing"};let m=p.telemetrySecret,g=i(),h=vC(g),y=yZ(m,u),_=p.workspaceExports?.[y];if(_?.lastSucceededAt!==void 0&&vC(Date.parse(_.lastSucceededAt))===h)return{attempted:!1,skipReason:"already_succeeded_today"};if(_?.nextRetryAt!==void 0&&g<Date.parse(_.nextRetryAt))return{attempted:!1,skipReason:"retry_backoff"};let v=_?.attemptBucketDate===h?_?.dailyAttemptCount??0:0;if(v>=yqn)return{attempted:!1,skipReason:"daily_attempt_cap"};let w=Iqn(cS(t()),y);if(w===void 0)return o.info?.("[PD:Telemetry] Export skipped: another export is in flight for this workspace (lock busy)."),{attempted:!1,skipReason:"export_lock_busy"};try{let b=n$(t()),k=b.ok?b.state.telemetrySecret:void 0,P=b.ok&&k===m?b.state:p;if(ip(P.telemetrySecret)){let Ie=P.workspaceExports?.[y];if(Ie?.lastSucceededAt!==void 0&&vC(Date.parse(Ie.lastSucceededAt))===h)return{attempted:!1,skipReason:"already_succeeded_today"}}let B=JSe(t()),{facts:N}=KSe(u),T=NH({dailyTelemetryId:DH(m,y,h),bucketDate:h,pdVersion:B.pdVersion,hostKind:B.hostKind,milestones:{initialized:N.initialized,painObserved:N.painObserved,principleObserved:N.principleObserved,activationObserved:N.activationObserved,presenceReceiptObserved:N.presenceReceiptObserved,effectReceiptObserved:N.effectReceiptObserved},reliability:{initializationFailed:N.initializationFailed}}),M=await fvt({snapshot:T,...e.endpoint!==void 0?{endpoint:e.endpoint}:{},...e.fetchFn!==void 0?{fetchFn:e.fetchFn}:{}}),Q=P.workspaceExports?.[y],H=Q?.lastAttemptedAt!==void 0&&g-Date.parse(Q.lastAttemptedAt)<1440*60*1e3,ne=M.ok?{lastAttemptedAt:new Date(g).toISOString(),lastSucceededAt:new Date(g).toISOString()}:{lastAttemptedAt:new Date(g).toISOString(),lastFailureCode:M.code,nextRetryAt:new Date(g+mvt(H)).toISOString(),dailyAttemptCount:v+1,attemptBucketDate:h},$=await vqn({homeDir:t(),secret:m,scopeKey:y,timestamp:g,nextEntry:ne});return $==="skipped_contention"?o.warn?.(`[PD:Telemetry] Export ${M.ok?"succeeded":`failed (${M.code})`} but control state update was skipped after 3s of state-lock contention \u2014 this workspace may re-attempt today.`):$==="skipped_unreadable"?o.warn?.(`[PD:Telemetry] Export ${M.ok?"succeeded":`failed (${M.code})`} but control state could not be read/updated \u2014 ${cS(t())}`):$==="skipped_identity_changed"&&o.info?.("[PD:Telemetry] Export finished after a consent/secret change; stale export bookkeeping was NOT written back."),M.ok?(o.info?.("[PD:Telemetry] Daily anonymous product telemetry snapshot exported."),{attempted:!0,ok:!0,httpStatus:M.status}):(o.warn?.(`[PD:Telemetry] Export failed (${M.code}); next retry after ${ne.nextRetryAt}. PD behavior is unaffected.`),{attempted:!0,ok:!1,failureCode:M.code})}finally{mZ(w)}}}}function bvt(e,t,n){setTimeout(()=>{e.maybeExportDaily(t).catch(i=>{let o=i instanceof Error?i.message:String(i);n?.warn?.(`[PD:Telemetry] Unexpected export error (PD unaffected): ${o}`)})},0).unref?.()}import{createHash as _Z}from"node:crypto";import{isAbsolute as wqn,resolve as Svt}from"node:path";import{realpathSync as bqn}from"node:fs";function yL(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Sqn(){function e(a){let s=wqn(a)?Svt(a):Svt(process.cwd(),a),c=s;try{c=bqn(s)}catch{}return`pd-evidence-scope:sha256:${_Z("sha256").update(c,"utf8").digest("hex").slice(0,32)}`}function t(a){let s=e(a),c=null;try{c=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let u=new lL(c).getEvidenceScope();if(u)return u.scopeId}catch{}finally{try{c?.close()}catch{}}return s}function n(a,s,c){if(!s.artifactId)return null;let u=null;try{u=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let l=u.getDb();if(!l.prepare(`
|
|
2223
2223
|
SELECT 1 FROM activations
|
|
2224
2224
|
WHERE activation_id = ? AND idempotency_key = ? AND deactivated_at IS NULL
|
|
2225
2225
|
`).get(s.activationId,s.idempotencyKey??""))return null;let f=l.prepare("SELECT content_json, source_principle_id FROM pi_artifacts WHERE artifact_id = ?").get(s.artifactId);return!yL(f)||typeof f.content_json!="string"||f.source_principle_id!==c?null:{principleId:c,artifactId:s.artifactId,payloadDigest:`sha256:${_Z("sha256").update(f.content_json,"utf8").digest("hex")}`,resolution:"resolved"}}catch{return null}finally{try{u?.close()}catch{}}}function r(a){let s=_Se(a.batch);if(!s.ok)return{ok:!1,reason:`evidence_batch_rejected:${s.reason}`,nextAction:"Fix the producer payload; nothing was written. The raw source remains durable."};let c=null;try{c=new Yn({workspaceDir:a.workspaceDir,busyTimeoutMs:0});let u=new lL(c),l=u.getEvidenceScope()?.scopeId??e(a.workspaceDir);if(a.batch.evidenceScopeId!==l)return{ok:!1,reason:`evidence_scope_mismatch:${a.batch.evidenceScopeId}`,nextAction:"Resolve the evidence scope for this workspace and rebuild the batch before replay; no records were written."};let p=u.appendObservationBatch(s.batch);return{ok:p.ok,insertedCount:p.insertedCount,duplicateCount:p.duplicates.length,conflictCount:p.conflicts.length,...p.reason!==void 0?{reason:p.reason}:{},...p.nextAction!==void 0?{nextAction:p.nextAction}:{}}}catch(u){return{ok:!1,reason:`evidence_storage_failed:${u instanceof Error?u.message:String(u)}`,nextAction:"The raw source remains durable; replay the same observation batch later \u2014 idempotency makes replay safe."}}finally{try{c?.close()}catch{}}}function i(a,s){let c=null;try{c=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let u=c.getDb(),l=u.prepare(`
|
|
@@ -2234,7 +2234,7 @@ try {
|
|
|
2234
2234
|
`).get(f);yL(h)&&typeof h.content_json=="string"&&(m=`sha256:${_Z("sha256").update(h.content_json,"utf8").digest("hex")}`)}let g={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:${_Z("sha256").update(JSON.stringify(g),"utf8").digest("hex")}`}}catch{return null}finally{try{c?.close()}catch{}}}function o(a,s){let c=null;try{c=new Yn({workspaceDir:a,readonly:!0,bootstrapIfMissing:!1});let u=c.getDb().prepare(`
|
|
2235
2235
|
SELECT activation_ref_json, content_ref_json
|
|
2236
2236
|
FROM intervention_evidence_records WHERE source_kind = ? AND source_locator = ? AND observation_key = ?
|
|
2237
|
-
`).get(s.sourceKind,s.sourceLocator,s.observationKey);if(!yL(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=h=>typeof h=="string"&&/^sha256:[a-f0-9]{64}$/.test(h);if(!yL(l)||typeof l.activationId!="string"||!f(l.sourceSnapshotDigest)||!yL(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}:{}},g={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:g}}catch{return null}finally{try{c?.close()}catch{}}}return{appendObservationBatch:r,evidenceScopeIdFor:t,resolveInterventionContentRef:n,resolveActivationOccurrenceRef:i,existingObservationRefs:o}}var ZSe=null;function a$(){return ZSe||(ZSe=Sqn()),ZSe}DC();w0();var Cqn=new Set(["success","failure","blocked"]);function kqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rqn(e){return typeof e=="string"&&Cqn.has(e)}function s$(e){return{status:"unavailable",unavailableReason:e,truncated:!1,calls:[]}}function _L(e,t,n){let{projectDir:r,toolSemantics:i}=n,o=[];for(let a of e){let{toolName:s}=a;if(typeof s!="string"||s.length===0)return s$(`row id=${a.id}: tool_name must be a non-empty string`);let{outcome:c}=a;if(!Rqn(c))return s$(`row id=${a.id}: outcome "${a.outcome}" is not a valid RuleToolOutcome`);let u=a.paramsJson;if(typeof u!="string")return s$(`row id=${a.id}: params_json must be a string`);let l;try{l=JSON.parse(u)}catch{return s$(`row id=${a.id}: params_json is not valid JSON`)}if(!kqn(l))return s$(`row id=${a.id}: params_json must parse to a non-array object`);let p=i.resolve(s),{normalizedPath:f}=Bd(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:t,calls:o}}var Tqn=3,Oqn=5,Dqn=100,kvt=new Set(["__proto__","constructor","prototype"]);function IZ(e,t){try{return t()}catch(n){let r=n instanceof Error?n.message:String(n);throw uE("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${e} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function Pqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lqn(e){for(let t of Object.keys(e))if(kvt.has(t))return!1;return!0}function Nqn(e){if(!Number.isSafeInteger(e.sourceNegativeToolCallId)||e.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(e.positiveToolCallIds)||e.positiveToolCallIds.length===0||e.positiveToolCallIds.length>Tqn)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let t=[e.sourceNegativeToolCallId,...e.positiveToolCallIds];if(t.some(n=>!Number.isSafeInteger(n)||n<=0)||new Set(t).size!==t.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function Cvt(e,t){if(!e)throw uE("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${t} not found`);return e}function Mqn(e,t,n){if(typeof e.toolName!="string"||e.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof e.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must be a string (rc-9 fail loud)`);let r;try{r=JSON.parse(e.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Pqn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!Lqn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${t}-${e.id}`,kind:t,toolName:e.toolName,params:r,expectedDecision:n}}function Bqn(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)}var Fqn=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Uqn(e){if(e.length<20)return!1;for(let t of Fqn)if(t.test(e))return!0;return!1}function Qqn(e,t){let n=[],r={};for(let i of Object.keys(e)){if(kvt.has(i))continue;let o=e[i];if(typeof o!="string"){r[i]=o;continue}if(Bqn(o)&&!o.startsWith(t)){r[i]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${i}" (outside project tree)`);continue}if(Uqn(o)){r[i]="<redacted:secret>",n.push(`redacted possible secret in field "${i}"`);continue}r[i]=o}return{redacted:r,notes:n}}var c$=class{db;toolSemantics;constructor(t){this.db=t.source,this.toolSemantics=t.toolSemantics}assemble(t){let n=IZ(`pain lineage read for canonical_pain_id="${t.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(t.sourcePainId));if(!n)throw uE("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${t.sourcePainId}" (ERR-069 fail loud)`);Nqn(t);let r=Cvt(IZ(`evidence row read for id=${t.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(t.sourceNegativeToolCallId)),t.sourceNegativeToolCallId),i=t.positiveToolCallIds.map(p=>Cvt(IZ(`evidence row read for id=${p}`,()=>this.db.getRuleHostEvidenceRow(p)),p));for(let p of[r,...i])if(p.sessionId!==n.sessionId)throw uE("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${p.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],a={projectDir:t.projectDir,redactionNotes:o},s=this.buildSelectedCase(r,"negative",a),c=i.map(p=>this.buildSelectedCase(p,"positive",a)),u={sourceNegativeCase:s,ownerDesiredOutcome:t.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...i.map(p=>`tool_call:${p.id}`)].slice(0,Oqn),redactionNotes:o},l=uA(u);if(!l.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${l.errors.join("; ")} (ERR-069 fail loud)`);return u}buildSelectedCase(t,n,r){let{projectDir:i,redactionNotes:o}=r,a=Mqn(t,n,n==="negative"?"block":"allow"),s=Qqn(a.params,i);o.push(...s.notes);let c=IZ(`context history read for session=${t.sessionId} before id=${t.id}`,()=>this.db.getRuleHostContextRowsBefore(t.sessionId,t.id,Dqn)),u=_L(c.rows,c.truncated,{projectDir:i,toolSemantics:this.toolSemantics}),l=Bd(t.toolName,s.redacted,i,{canonicalKind:this.toolSemantics.resolve(t.toolName)}),p={version:2,history:u,facts:ev(u,l.normalizedPath||null,null)};return{...a,params:s.redacted,ruleContext:p}}};import tgo from"better-sqlite3";w0();var cgo=2*1024*1024;var ggo=1024*1024;var ygo=1024*1024;var Hqn=4*1024*1024;var kgo=1440*60*1e3;import jqn from"better-sqlite3";import{existsSync as Gqn}from"fs";import{join as qqn}from"path";function Rvt(e){return qqn(e,".state","trajectory.db")}var IL=class extends Error{dbPath;constructor(t,n){super(`Trajectory database unavailable at ${t} (${n})`),this.name="TrajectoryDbUnavailableError",this.dbPath=t}};function Tvt(e){let t=Rvt(e);if(!Gqn(t))throw new IL(t,"database file does not exist");try{return new jqn(t,{readonly:!0})}catch(n){let r=n instanceof Error?n.message:String(n);throw new IL(t,`cannot be opened: ${r}`)}}function Kqn(e,t){if(t instanceof IL||t instanceof Error&&t.message.startsWith("Sample not found"))throw t;let n=t instanceof Error?t.message:String(t);throw new IL(e,`query failed: ${n}`)}function eCe(e,t){let n=Tvt(e);try{let i=n.prepare("SELECT MAX(turn_index) AS max_turn FROM user_turns WHERE session_id = ?").get(t)?.max_turn;return typeof i=="number"&&Number.isFinite(i)?i+1:1}catch(r){Kqn(Rvt(e),r)}finally{n.close()}}var vZ=["before_prompt_build","before_tool_call","after_tool_call"],vL=class extends Error{reason;nextAction;constructor(t,n){super(`${t}: ${n}`),this.reason=t,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function zqn(e,t){switch(e.kind){case"before_prompt_build":return t.beforePromptBuild;case"before_tool_call":return t.beforeToolCall;case"after_tool_call":return t.afterToolCall;default:throw new vL("unsupported_host_event",`Only ${vZ.join(", ")} are supported by the MVP host runtime`)}}function uS(e){return typeof e=="string"&&e.trim().length>0}function Dvt(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function Yqn(e){return!uS(e.context.workspaceDir)||!Dvt(e.context.workspaceDir)||!uS(e.context.sessionId)||!uS(e.source)?!1:e.kind==="before_tool_call"||e.kind==="after_tool_call"?uS(e.context.toolName):!0}function Ovt(e){return e===void 0||uS(e)}function Jqn(e,t){if(t.warnings!==void 0&&(!Array.isArray(t.warnings)||!t.warnings.every(uS))||t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null||Array.isArray(t.metadata))||!uS(t.source)||!Ovt(t.reason)||!Ovt(t.additionalContext))return!1;let n=t.reason!==void 0,r=t.modifiedInput!==void 0,i=t.additionalContext!==void 0;switch(e.kind){case"before_prompt_build":return(t.decision==="allow"||t.decision==="modify")&&!n&&!r;case"before_tool_call":return t.decision==="observe"?!1:t.decision==="deny"?n&&!r&&!i:n?!1:!r||t.decision==="modify";case"after_tool_call":return t.decision==="observe"&&!n&&!r&&!i;default:return!1}}function Xqn(e){return{async dispatch(t){if(!SSe(t)||!Yqn(t))throw new vL("invalid_host_event","Decode and validate the host event before dispatch");let n=await zqn(t,e)(t);if(!CSe(n)||!Jqn(t,n))throw new vL("invalid_handler_result",`Handler for ${t.kind} must return a valid HostEventResult`);if(n.source!==t.source)throw new vL("lineage_mismatch",`Handler result source must match event source ${t.source}`);return n},async health(t){return t.trim().length===0?{ok:!1,workspaceDir:t,routes:vZ,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:Dvt(t)?{ok:!0,workspaceDir:t,routes:vZ}:{ok:!1,workspaceDir:t,routes:vZ,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function Pvt(e={}){let t=kIt({...e.hostKind?{hostKind:e.hostKind}:{},...e.projectDir?{projectDir:e.projectDir}:{},...e.ruleContextProvider?{ruleContextProvider:e.ruleContextProvider}:{},...e.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:e.ruleInputEnrichmentProvider}:{},...e.ruleImplementationRuntime?{implementationRuntime:e.ruleImplementationRuntime}:{},...e.toolSemantics?{toolSemantics:e.toolSemantics}:{}});return Xqn({afterToolCall:e.afterToolCall??DIt({...e.painEnrichmentProvider?{painEnrichmentProvider:e.painEnrichmentProvider}:{},...e.painDatabaseFactory?{painDatabaseFactory:e.painDatabaseFactory}:{},...e.hostKind?{hostKind:e.hostKind}:{},...e.projectDir?{projectDir:e.projectDir}:{},...e.events?{events:e.events}:{}}),beforeToolCall:e.beforeToolCall??t,async beforePromptBuild(n){let r;if(e.roundKeyProvider)try{let l=await e.roundKeyProvider(n);typeof l=="number"&&Number.isInteger(l)&&l>=1&&(r=l)}catch{r=void 0}let i=e.hostKind==="openclaw"||e.hostKind==="codex"||e.hostKind==="workbuddy"?e.hostKind:void 0,o=i===void 0?void 0:FW(Lr(n.context.workspaceDir).effective.config.promptBudget,i),a,s;if(e.adaptivePriorityProvider)try{a=await e.adaptivePriorityProvider(n),a&&(typeof a.artifactId!="string"||!a.artifactId.trim()||typeof a.activationId!="string"||!a.activationId.trim()||a.additiveOnly!==void 0&&typeof a.additiveOnly!="boolean"||a.deadlineAt!==void 0&&!Number.isFinite(a.deadlineAt))&&(a=void 0),(a?.signal?.aborted||a?.deadlineAt!==void 0&&Date.now()>=a.deadlineAt)&&(s=a,a=void 0)}catch{a=void 0}let c=await PSe({workspaceDir:n.context.workspaceDir,...r!==void 0?{roundKey:r}:{},...a?{adaptivePriority:{artifactId:a.artifactId,activationId:a.activationId},...a.additiveOnly===!0?{additiveOnly:!0}:{},...a.signal?{signal:a.signal}:{},...a.deadlineAt!==void 0?{deadlineAt:a.deadlineAt}:{},...a.hookInvocationId?{hookInvocationId:a.hookInvocationId}:{}}:{},promptBudget:mv({...o!==void 0?{operatorDeclared:{contextWindowTokens:o}}:{},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:r_e()})});s?.hookInvocationId&&(c.adaptivePacking={status:"unavailable",reason:"deadline",targetActivationId:s.activationId,targetArtifactId:s.artifactId,hookInvocationId:s.hookInvocationId,displacedActivationIds:[]});let u=[];try{e.events?.recordRuntimeActivationsInjected({sessionId:n.context.sessionId,workspaceDir:n.context.workspaceDir,principleIds:c.principleIds,activationIds:c.activationIds,artifactIds:c.artifactIds,injectedCount:c.principleIds.length,skippedWarnings:c.warnings,injectedCharCount:c.additionalContext.length,budget:c.budget,...e.hostKind==="openclaw"||e.hostKind==="codex"||e.hostKind==="workbuddy"?{hostKind:e.hostKind}:{},eventId:Vqn(),...c.truncated!==void 0?{v2Truncated:c.truncated}:{},...n.context.turnId!==void 0?{runId:n.context.turnId}:{},...c.budgetPolicyVersion!==void 0?{budgetPolicyVersion:c.budgetPolicyVersion}:{},...c.budgetCapacitySource!==void 0?{budgetCapacitySource:c.budgetCapacitySource}:{},...c.budgetCapacityStatus!==void 0?{budgetCapacityStatus:c.budgetCapacityStatus}:{},...c.budgetContextWindowTokens!=null?{budgetContextWindowTokens:c.budgetContextWindowTokens}:{},...c.budgetFallbackReason!==void 0?{budgetFallbackReason:c.budgetFallbackReason}:{},...c.selectionPolicy!==void 0?{selectionPolicy:c.selectionPolicy}:{},...c.eligibleCount!==void 0?{eligibleCount:c.eligibleCount}:{},...c.rotationStartIndex!==void 0?{rotationStartIndex:c.rotationStartIndex}:{},...c.droppedActivationIds!==void 0&&c.droppedActivationIds.length>0?{droppedActivationIds:c.droppedActivationIds}:{},...c.oversizedActivationIds!==void 0&&c.oversizedActivationIds.length>0?{oversizedActivationIds:c.oversizedActivationIds}:{}})}catch(l){u.push(`receipt_event_write_failed:${l instanceof Error?l.message.slice(0,200):String(l).slice(0,200)}`)}if(e.beforePromptBuild){let l=await e.beforePromptBuild(n,c);return u.length===0?l:{...l,warnings:[...l.warnings??[],...u]}}return{decision:c.additionalContext.length>0?"modify":"allow",source:n.source,...c.additionalContext.length>0?{additionalContext:c.additionalContext}:{},...u.length>0?{warnings:u}:{}}}})}function jy(e){return{source:e.source}}function lS(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,maxTokens:null,baseUrl:null}}function Zqn(e){return au.some(t=>t===e)}function EL(e,t,n,r){let i=Lr(e);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...jy(i),...lS(),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[t]?.enabled)return{enabled:!1,readiness:"disabled",...jy(i),...lS(),reason:`${t} is disabled in .pd/config.yaml`,nextAction:`Enable it in .pd/config.yaml \u2014 in the existing "features:" block set ${t}: {enabled: true} (one flat key, not nested)`};if(!Zqn(n))return{enabled:!1,readiness:"needs_setup",...jy(i),...lS(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${au.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...jy(i),...lS(),reason:`${t} 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 ${t}: {enabled: false}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,u=o.runtimeProfiles[c];if(!u)return{enabled:!0,readiness:"needs_setup",...jy(i),...lS(),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",...jy(i),...lS(),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",...jy(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",...jy(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",...jy(i),...lS(),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`}}import*as Wd from"fs";import*as Fl from"path";var Lvt="pd.mcp-binding.v1",Nvt="openclaw";function e8n(e,t,n){return{schemaVersion:Lvt,host:Nvt,workspaceDir:e,runtimeDir:t,serverEntry:n,versions:{mcpServer:t8n(n)}}}function t8n(e){try{let t=JSON.parse(Wd.readFileSync(Fl.join(Fl.dirname(e),"..","package.json"),"utf8"));return typeof t.version=="string"?t.version:"unknown"}catch{return"unknown"}}function Mvt(e){return Fl.join(Fl.resolve(e),".pd","runtime")}function n8n(e){return Fl.join(Mvt(e),"pd-mcp-server","dist","index.js")}function Bvt(e){let t=Fl.join(e,"mcp-binding.json");try{return Wd.existsSync(t)?(Wd.rmSync(t,{force:!0}),{ok:!0,removed:!0}):{ok:!0,removed:!1}}catch(n){return{ok:!1,removed:!1,reason:`remove_failed:${n instanceof Error?n.message.slice(0,120):String(n).slice(0,120)}`}}}function r8n(e,t){let n=Fl.join(Fl.dirname(e),`.${Fl.basename(e)}.${process.pid}.tmp`);try{Wd.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
2237
|
+
`).get(s.sourceKind,s.sourceLocator,s.observationKey);if(!yL(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=h=>typeof h=="string"&&/^sha256:[a-f0-9]{64}$/.test(h);if(!yL(l)||typeof l.activationId!="string"||!f(l.sourceSnapshotDigest)||!yL(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}:{}},g={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:g}}catch{return null}finally{try{c?.close()}catch{}}}return{appendObservationBatch:r,evidenceScopeIdFor:t,resolveInterventionContentRef:n,resolveActivationOccurrenceRef:i,existingObservationRefs:o}}var ZSe=null;function a$(){return ZSe||(ZSe=Sqn()),ZSe}DC();w0();var Cqn=new Set(["success","failure","blocked"]);function kqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Rqn(e){return typeof e=="string"&&Cqn.has(e)}function s$(e){return{status:"unavailable",unavailableReason:e,truncated:!1,calls:[]}}function _L(e,t,n){let{projectDir:r,toolSemantics:i}=n,o=[];for(let a of e){let{toolName:s}=a;if(typeof s!="string"||s.length===0)return s$(`row id=${a.id}: tool_name must be a non-empty string`);let{outcome:c}=a;if(!Rqn(c))return s$(`row id=${a.id}: outcome "${a.outcome}" is not a valid RuleToolOutcome`);let u=a.paramsJson;if(typeof u!="string")return s$(`row id=${a.id}: params_json must be a string`);let l;try{l=JSON.parse(u)}catch{return s$(`row id=${a.id}: params_json is not valid JSON`)}if(!kqn(l))return s$(`row id=${a.id}: params_json must parse to a non-array object`);let p=i.resolve(s),{normalizedPath:f}=Bd(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:t,calls:o}}var Tqn=3,Oqn=5,Dqn=100,kvt=new Set(["__proto__","constructor","prototype"]);function IZ(e,t){try{return t()}catch(n){let r=n instanceof Error?n.message:String(n);throw uE("evidence_source_error",`[BehaviorExamplePackAssembler] trajectory store ${e} failed (evidence source error, SPEC-PD-IAER-001 \xA76.2): ${r}`)}}function Pqn(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Lqn(e){for(let t of Object.keys(e))if(kvt.has(t))return!1;return!0}function Nqn(e){if(!Number.isSafeInteger(e.sourceNegativeToolCallId)||e.sourceNegativeToolCallId<=0)throw new Error("[BehaviorExamplePackAssembler] sourceNegativeToolCallId must be a positive integer");if(!Array.isArray(e.positiveToolCallIds)||e.positiveToolCallIds.length===0||e.positiveToolCallIds.length>Tqn)throw new Error("[BehaviorExamplePackAssembler] positiveToolCallIds must contain 1 to at most 3 IDs");let t=[e.sourceNegativeToolCallId,...e.positiveToolCallIds];if(t.some(n=>!Number.isSafeInteger(n)||n<=0)||new Set(t).size!==t.length)throw new Error("[BehaviorExamplePackAssembler] selected tool call IDs must be unique positive integers")}function Cvt(e,t){if(!e)throw uE("tool_call_not_found",`[BehaviorExamplePackAssembler] selected tool call id=${t} not found`);return e}function Mqn(e,t,n){if(typeof e.toolName!="string"||e.toolName.length===0)throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: toolName must be a non-empty string (rc-9 fail loud)`);if(typeof e.paramsJson!="string")throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must be a string (rc-9 fail loud)`);let r;try{r=JSON.parse(e.paramsJson)}catch{throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson is not valid JSON (rc-9 fail loud)`)}if(!Pqn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must parse to a non-array object (rc-9 fail loud)`);if(!Lqn(r))throw new Error(`[BehaviorExamplePackAssembler] row id=${e.id}: paramsJson must not carry prototype-pollution keys (ERR-076, rc-9 fail loud)`);return{caseId:`case-${t}-${e.id}`,kind:t,toolName:e.toolName,params:r,expectedDecision:n}}function Bqn(e){return e.startsWith("/")||/^[A-Za-z]:[\\/]/.test(e)}var Fqn=[/AKIA[0-9A-Z]{16}/,/[A-Za-z0-9+/]{40,}/];function Uqn(e){if(e.length<20)return!1;for(let t of Fqn)if(t.test(e))return!0;return!1}function Qqn(e,t){let n=[],r={};for(let i of Object.keys(e)){if(kvt.has(i))continue;let o=e[i];if(typeof o!="string"){r[i]=o;continue}if(Bqn(o)&&!o.startsWith(t)){r[i]="<redacted:absolute-path>",n.push(`redacted absolute path in field "${i}" (outside project tree)`);continue}if(Uqn(o)){r[i]="<redacted:secret>",n.push(`redacted possible secret in field "${i}"`);continue}r[i]=o}return{redacted:r,notes:n}}var c$=class{db;toolSemantics;constructor(t){this.db=t.source,this.toolSemantics=t.toolSemantics}assemble(t){let n=IZ(`pain lineage read for canonical_pain_id="${t.sourcePainId}"`,()=>this.db.getPainEventByCanonicalId(t.sourcePainId));if(!n)throw uE("pain_not_found",`[BehaviorExamplePackAssembler] pain event not found for canonical_pain_id="${t.sourcePainId}" (ERR-069 fail loud)`);Nqn(t);let r=Cvt(IZ(`evidence row read for id=${t.sourceNegativeToolCallId}`,()=>this.db.getRuleHostEvidenceRow(t.sourceNegativeToolCallId)),t.sourceNegativeToolCallId),i=t.positiveToolCallIds.map(p=>Cvt(IZ(`evidence row read for id=${p}`,()=>this.db.getRuleHostEvidenceRow(p)),p));for(let p of[r,...i])if(p.sessionId!==n.sessionId)throw uE("session_mismatch",`[BehaviorExamplePackAssembler] selected tool call ${p.id} session mismatch; all examples must belong to pain session ${n.sessionId}`);let o=[],a={projectDir:t.projectDir,redactionNotes:o},s=this.buildSelectedCase(r,"negative",a),c=i.map(p=>this.buildSelectedCase(p,"positive",a)),u={sourceNegativeCase:s,ownerDesiredOutcome:t.ownerDesiredOutcome,positiveCounterexamples:c,evidenceRefs:[`pain:${n.id}`,`tool_call:${r.id}`,...i.map(p=>`tool_call:${p.id}`)].slice(0,Oqn),redactionNotes:o},l=uA(u);if(!l.valid)throw new Error(`[BehaviorExamplePackAssembler] assembled pack failed validateBehaviorExamplePack: ${l.errors.join("; ")} (ERR-069 fail loud)`);return u}buildSelectedCase(t,n,r){let{projectDir:i,redactionNotes:o}=r,a=Mqn(t,n,n==="negative"?"block":"allow"),s=Qqn(a.params,i);o.push(...s.notes);let c=IZ(`context history read for session=${t.sessionId} before id=${t.id}`,()=>this.db.getRuleHostContextRowsBefore(t.sessionId,t.id,Dqn)),u=_L(c.rows,c.truncated,{projectDir:i,toolSemantics:this.toolSemantics}),l=Bd(t.toolName,s.redacted,i,{canonicalKind:this.toolSemantics.resolve(t.toolName)}),p={version:2,history:u,facts:ev(u,l.normalizedPath||null,null)};return{...a,params:s.redacted,ruleContext:p}}};import ugo from"better-sqlite3";w0();var ggo=2*1024*1024;var wgo=1024*1024;var Sgo=1024*1024;var Hqn=4*1024*1024;var Mgo=1440*60*1e3;import jqn from"better-sqlite3";import{existsSync as Gqn}from"fs";import{join as qqn}from"path";function Rvt(e){return qqn(e,".state","trajectory.db")}var IL=class extends Error{dbPath;constructor(t,n){super(`Trajectory database unavailable at ${t} (${n})`),this.name="TrajectoryDbUnavailableError",this.dbPath=t}};function Tvt(e){let t=Rvt(e);if(!Gqn(t))throw new IL(t,"database file does not exist");try{return new jqn(t,{readonly:!0})}catch(n){let r=n instanceof Error?n.message:String(n);throw new IL(t,`cannot be opened: ${r}`)}}function Kqn(e,t){if(t instanceof IL||t instanceof Error&&t.message.startsWith("Sample not found"))throw t;let n=t instanceof Error?t.message:String(t);throw new IL(e,`query failed: ${n}`)}function eCe(e,t){let n=Tvt(e);try{let i=n.prepare("SELECT MAX(turn_index) AS max_turn FROM user_turns WHERE session_id = ?").get(t)?.max_turn;return typeof i=="number"&&Number.isFinite(i)?i+1:1}catch(r){Kqn(Rvt(e),r)}finally{n.close()}}var vZ=["before_prompt_build","before_tool_call","after_tool_call"],vL=class extends Error{reason;nextAction;constructor(t,n){super(`${t}: ${n}`),this.reason=t,this.nextAction=n,this.name="HostRuntimeDispatchError"}};function zqn(e,t){switch(e.kind){case"before_prompt_build":return t.beforePromptBuild;case"before_tool_call":return t.beforeToolCall;case"after_tool_call":return t.afterToolCall;default:throw new vL("unsupported_host_event",`Only ${vZ.join(", ")} are supported by the MVP host runtime`)}}function uS(e){return typeof e=="string"&&e.trim().length>0}function Dvt(e){return e.startsWith("/")||e.startsWith("\\\\")||/^[A-Za-z]:[\\/]/.test(e)}function Yqn(e){return!uS(e.context.workspaceDir)||!Dvt(e.context.workspaceDir)||!uS(e.context.sessionId)||!uS(e.source)?!1:e.kind==="before_tool_call"||e.kind==="after_tool_call"?uS(e.context.toolName):!0}function Ovt(e){return e===void 0||uS(e)}function Jqn(e,t){if(t.warnings!==void 0&&(!Array.isArray(t.warnings)||!t.warnings.every(uS))||t.metadata!==void 0&&(typeof t.metadata!="object"||t.metadata===null||Array.isArray(t.metadata))||!uS(t.source)||!Ovt(t.reason)||!Ovt(t.additionalContext))return!1;let n=t.reason!==void 0,r=t.modifiedInput!==void 0,i=t.additionalContext!==void 0;switch(e.kind){case"before_prompt_build":return(t.decision==="allow"||t.decision==="modify")&&!n&&!r;case"before_tool_call":return t.decision==="observe"?!1:t.decision==="deny"?n&&!r&&!i:n?!1:!r||t.decision==="modify";case"after_tool_call":return t.decision==="observe"&&!n&&!r&&!i;default:return!1}}function Xqn(e){return{async dispatch(t){if(!SSe(t)||!Yqn(t))throw new vL("invalid_host_event","Decode and validate the host event before dispatch");let n=await zqn(t,e)(t);if(!CSe(n)||!Jqn(t,n))throw new vL("invalid_handler_result",`Handler for ${t.kind} must return a valid HostEventResult`);if(n.source!==t.source)throw new vL("lineage_mismatch",`Handler result source must match event source ${t.source}`);return n},async health(t){return t.trim().length===0?{ok:!1,workspaceDir:t,routes:vZ,reason:"workspace_dir_missing",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}:Dvt(t)?{ok:!0,workspaceDir:t,routes:vZ}:{ok:!1,workspaceDir:t,routes:vZ,reason:"workspace_dir_invalid",nextAction:"Resolve an absolute workspace directory before probing host runtime health"}}}}function Pvt(e={}){let t=kIt({...e.hostKind?{hostKind:e.hostKind}:{},...e.projectDir?{projectDir:e.projectDir}:{},...e.ruleContextProvider?{ruleContextProvider:e.ruleContextProvider}:{},...e.ruleInputEnrichmentProvider?{ruleInputEnrichmentProvider:e.ruleInputEnrichmentProvider}:{},...e.ruleImplementationRuntime?{implementationRuntime:e.ruleImplementationRuntime}:{},...e.toolSemantics?{toolSemantics:e.toolSemantics}:{}});return Xqn({afterToolCall:e.afterToolCall??DIt({...e.painEnrichmentProvider?{painEnrichmentProvider:e.painEnrichmentProvider}:{},...e.painDatabaseFactory?{painDatabaseFactory:e.painDatabaseFactory}:{},...e.hostKind?{hostKind:e.hostKind}:{},...e.projectDir?{projectDir:e.projectDir}:{},...e.events?{events:e.events}:{}}),beforeToolCall:e.beforeToolCall??t,async beforePromptBuild(n){let r;if(e.roundKeyProvider)try{let l=await e.roundKeyProvider(n);typeof l=="number"&&Number.isInteger(l)&&l>=1&&(r=l)}catch{r=void 0}let i=e.hostKind==="openclaw"||e.hostKind==="codex"||e.hostKind==="workbuddy"?e.hostKind:void 0,o=i===void 0?void 0:FW(Lr(n.context.workspaceDir).effective.config.promptBudget,i),a,s;if(e.adaptivePriorityProvider)try{a=await e.adaptivePriorityProvider(n),a&&(typeof a.artifactId!="string"||!a.artifactId.trim()||typeof a.activationId!="string"||!a.activationId.trim()||a.additiveOnly!==void 0&&typeof a.additiveOnly!="boolean"||a.deadlineAt!==void 0&&!Number.isFinite(a.deadlineAt))&&(a=void 0),(a?.signal?.aborted||a?.deadlineAt!==void 0&&Date.now()>=a.deadlineAt)&&(s=a,a=void 0)}catch{a=void 0}let c=await PSe({workspaceDir:n.context.workspaceDir,...r!==void 0?{roundKey:r}:{},...a?{adaptivePriority:{artifactId:a.artifactId,activationId:a.activationId},...a.additiveOnly===!0?{additiveOnly:!0}:{},...a.signal?{signal:a.signal}:{},...a.deadlineAt!==void 0?{deadlineAt:a.deadlineAt}:{},...a.hookInvocationId?{hookInvocationId:a.hookInvocationId}:{}}:{},promptBudget:mv({...o!==void 0?{operatorDeclared:{contextWindowTokens:o}}:{},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:r_e()})});s?.hookInvocationId&&(c.adaptivePacking={status:"unavailable",reason:"deadline",targetActivationId:s.activationId,targetArtifactId:s.artifactId,hookInvocationId:s.hookInvocationId,displacedActivationIds:[]});let u=[];try{e.events?.recordRuntimeActivationsInjected({sessionId:n.context.sessionId,workspaceDir:n.context.workspaceDir,principleIds:c.principleIds,activationIds:c.activationIds,artifactIds:c.artifactIds,injectedCount:c.principleIds.length,skippedWarnings:c.warnings,injectedCharCount:c.additionalContext.length,budget:c.budget,...e.hostKind==="openclaw"||e.hostKind==="codex"||e.hostKind==="workbuddy"?{hostKind:e.hostKind}:{},eventId:Vqn(),...c.truncated!==void 0?{v2Truncated:c.truncated}:{},...n.context.turnId!==void 0?{runId:n.context.turnId}:{},...c.budgetPolicyVersion!==void 0?{budgetPolicyVersion:c.budgetPolicyVersion}:{},...c.budgetCapacitySource!==void 0?{budgetCapacitySource:c.budgetCapacitySource}:{},...c.budgetCapacityStatus!==void 0?{budgetCapacityStatus:c.budgetCapacityStatus}:{},...c.budgetContextWindowTokens!=null?{budgetContextWindowTokens:c.budgetContextWindowTokens}:{},...c.budgetFallbackReason!==void 0?{budgetFallbackReason:c.budgetFallbackReason}:{},...c.selectionPolicy!==void 0?{selectionPolicy:c.selectionPolicy}:{},...c.eligibleCount!==void 0?{eligibleCount:c.eligibleCount}:{},...c.rotationStartIndex!==void 0?{rotationStartIndex:c.rotationStartIndex}:{},...c.droppedActivationIds!==void 0&&c.droppedActivationIds.length>0?{droppedActivationIds:c.droppedActivationIds}:{},...c.oversizedActivationIds!==void 0&&c.oversizedActivationIds.length>0?{oversizedActivationIds:c.oversizedActivationIds}:{}})}catch(l){u.push(`receipt_event_write_failed:${l instanceof Error?l.message.slice(0,200):String(l).slice(0,200)}`)}if(e.beforePromptBuild){let l=await e.beforePromptBuild(n,c);return u.length===0?l:{...l,warnings:[...l.warnings??[],...u]}}return{decision:c.additionalContext.length>0?"modify":"allow",source:n.source,...c.additionalContext.length>0?{additionalContext:c.additionalContext}:{},...u.length>0?{warnings:u}:{}}}})}function jy(e){return{source:e.source}}function lS(){return{runtimeProfileId:null,runtimeProfileType:null,apiKeyEnv:null,apiKeyPresent:!1,provider:null,model:null,timeoutMs:null,maxTokens:null,baseUrl:null}}function Zqn(e){return au.some(t=>t===e)}function EL(e,t,n,r){let i=Lr(e);if(!i.ok)return{enabled:!1,readiness:"config_malformed",...jy(i),...lS(),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[t]?.enabled)return{enabled:!1,readiness:"disabled",...jy(i),...lS(),reason:`${t} is disabled in .pd/config.yaml`,nextAction:`Enable it in .pd/config.yaml \u2014 in the existing "features:" block set ${t}: {enabled: true} (one flat key, not nested)`};if(!Zqn(n))return{enabled:!1,readiness:"needs_setup",...jy(i),...lS(),reason:`Unknown agent name '${n}'`,nextAction:`Use one of the known agent names: ${au.join(", ")}`};let s=o.internalAgents.agents[n];if(!s?.enabled)return{enabled:!1,readiness:"disabled",...jy(i),...lS(),reason:`${t} 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 ${t}: {enabled: false}`};let c=s.runtimeProfile??o.internalAgents.defaultRuntime,u=o.runtimeProfiles[c];if(!u)return{enabled:!0,readiness:"needs_setup",...jy(i),...lS(),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",...jy(i),...lS(),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",...jy(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",...jy(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",...jy(i),...lS(),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`}}import*as Wd from"fs";import*as Fl from"path";var Lvt="pd.mcp-binding.v1",Nvt="openclaw";function e8n(e,t,n){return{schemaVersion:Lvt,host:Nvt,workspaceDir:e,runtimeDir:t,serverEntry:n,versions:{mcpServer:t8n(n)}}}function t8n(e){try{let t=JSON.parse(Wd.readFileSync(Fl.join(Fl.dirname(e),"..","package.json"),"utf8"));return typeof t.version=="string"?t.version:"unknown"}catch{return"unknown"}}function Mvt(e){return Fl.join(Fl.resolve(e),".pd","runtime")}function n8n(e){return Fl.join(Mvt(e),"pd-mcp-server","dist","index.js")}function Bvt(e){let t=Fl.join(e,"mcp-binding.json");try{return Wd.existsSync(t)?(Wd.rmSync(t,{force:!0}),{ok:!0,removed:!0}):{ok:!0,removed:!1}}catch(n){return{ok:!1,removed:!1,reason:`remove_failed:${n instanceof Error?n.message.slice(0,120):String(n).slice(0,120)}`}}}function r8n(e,t){let n=Fl.join(Fl.dirname(e),`.${Fl.basename(e)}.${process.pid}.tmp`);try{Wd.writeFileSync(n,JSON.stringify(t,null,2)+`
|
|
2238
2238
|
`,"utf8"),Wd.renameSync(n,e)}catch(r){try{Wd.rmSync(n,{force:!0})}catch{}throw r}}function Fvt(e,t,n){try{let r=Mvt(n),i=n8n(n),o=Fl.join(t,"mcp-binding.json");if(typeof e!="string"||e.length===0)return{ok:!1,reason:"workspace_unresolved"};if(!Wd.existsSync(i))return{ok:!1,reason:"mcp_server_component_missing",serverEntry:i};let a=null;try{a=JSON.parse(Wd.readFileSync(o,"utf8"))}catch{}let s=e8n(e,r,i),c=s.versions.mcpServer,u=a!==null&&typeof a=="object"&&!Array.isArray(a)?a.versions:void 0,l=u!==null&&typeof u=="object"&&!Array.isArray(u)?u.mcpServer:void 0;return a!==null&&typeof a=="object"&&!Array.isArray(a)&&a.schemaVersion===Lvt&&a.host===Nvt&&a.workspaceDir===e&&a.runtimeDir===r&&a.serverEntry===i&&l===c?{ok:!0,written:!1,serverEntry:i}:(r8n(o,s),{ok:!0,written:!0,serverEntry:i})}catch(r){return{ok:!1,reason:`write_failed:${r instanceof Error?r.message.slice(0,120):String(r).slice(0,120)}`}}}function Uvt(e,t){let n=wvt({...t!==void 0?{logger:t}:{}});bvt(n,e,t)}import{existsSync as zvt,readFileSync as l8n,writeFileSync as d8n,renameSync as p8n}from"fs";import{homedir as f8n}from"os";import*as Yvt from"path";import*as Uo from"fs";import*as Wvt from"path";var tCe=class extends Error{filePath;lockPath;constructor(t,n,r){super(t),this.name="LockAcquisitionError",this.filePath=n,this.lockPath=r}},$vt={maxRetries:50,baseRetryDelayMs:10,maxRetryDelayMs:500,lockStaleMs:1e4,lockSuffix:".lock"};function Hvt(e){try{return process.kill(e,0),!0}catch{return!1}}function Qvt(e,t){try{let n=Wvt.dirname(e);Uo.existsSync(n)||Uo.mkdirSync(n,{recursive:!0});let r=Uo.constants.O_WRONLY|Uo.constants.O_CREAT|Uo.constants.O_EXCL,i=Uo.openSync(e,r);return Uo.writeSync(i,String(t)),Uo.fsyncSync(i),Uo.closeSync(i),!0}catch(n){if(n.code==="EEXIST")return!1;throw n}}function u$(e){try{let t=Uo.readFileSync(e,"utf8"),n=parseInt(t.trim(),10);return Number.isNaN(n)?null:n}catch{return null}}function i8n(e,t){try{u$(e)===t&&Uo.unlinkSync(e)}catch{}}function o8n(e,t){try{let n=Uo.statSync(e),r=u$(e),i=Date.now()-n.mtimeMs>t,o=r===null||!Hvt(r);if(i||o)try{return Uo.unlinkSync(e),!0}catch{return!1}return!1}catch{return!1}}function jvt(e,t,n){let r=Math.min(t*Math.pow(2,e),n),i=r*.2*Math.random();return Math.floor(r+i)}function a8n(e){return new Promise(t=>setTimeout(t,e))}function s8n(e){let t=Date.now()+e;for(;Date.now()<t;);}function Gvt(e,t){let n=u$(t),r=n!==null?Hvt(n)?`alive (PID ${n})`:`dead (PID ${n})`:"unknown";return new tCe(`Failed to acquire lock for ${e}. Lock holder: ${r}.`,e,t)}function qvt(e,t,n){let r=e+t.lockSuffix;return Qvt(r,n)&&u$(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:(o8n(r,t.lockStaleMs),Qvt(r,n)&&u$(r)===n?{lockPath:r,pid:n,acquiredAt:Date.now()}:null)}function c8n(e,t={}){let n={...$vt,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=qvt(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=jvt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);s8n(a)}}throw Gvt(e,e+n.lockSuffix)}async function u8n(e,t={}){let n={...$vt,...t},{pid:r}=process;for(let i=0;i<n.maxRetries;i++){let o=qvt(e,n,r);if(o)return o;if(i<n.maxRetries-1){let a=jvt(i,n.baseRetryDelayMs,n.maxRetryDelayMs);await a8n(a)}}throw Gvt(e,e+n.lockSuffix)}function Kvt(e){i8n(e.lockPath,e.pid)}function Nu(e,t,n={}){let r=c8n(e,n);try{return t()}finally{Kvt(r)}}async function EZ(e,t,n={}){let r=await u8n(e,n);try{return await t()}finally{Kvt(r)}}function xZ(e,t){if(!e||typeof e!="object"||Array.isArray(e))return;let n=e.plugins;if(!n||typeof n!="object"||Array.isArray(n))return;let r=n.entries;if(!(!r||typeof r!="object"||Array.isArray(r)))return r[t]}var rCe="allowConversationAccess",nCe="openclaw config set plugins.entries.principles-disciple.hooks.allowConversationAccess true --strict-json";function d$(e){if(e==null||typeof e!="object"||Array.isArray(e))return{authorized:!1,reason:"pluginConfig is missing or invalid \u2014 conversation hooks cannot be registered",nextAction:nCe};let t=e;return typeof t.hooks!="object"||t.hooks===null||Array.isArray(t.hooks)?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:nCe}:t.hooks[rCe]!==!0?{authorized:!1,reason:"allowConversationAccess is not set to true",nextAction:nCe}:{authorized:!0}}var Vvt="principles-disciple";function m8n(){return Yvt.join(f8n(),".openclaw","openclaw.json")}function l$(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function h8n(e){if(!zvt(e))return null;try{let t=l8n(e,"utf8").replace(/^\uFEFF/,""),n=JSON.parse(t);return l$(n)?n:null}catch{return null}}function g8n(e,t){let n=e+".tmp."+Date.now();d8n(n,JSON.stringify(t,null,2),"utf8"),p8n(n,e)}function wZ(){let e=m8n();return zvt(e)?Nu(e,()=>{let t=h8n(e);if(!t)return!1;l$(t.plugins)||(t.plugins={});let n=t.plugins;l$(n.entries)||(n.entries={});let r=n.entries,i=r[Vvt],o=l$(i)?i:{enabled:!0};l$(o.hooks)||(o.hooks={});let a=o.hooks;return Object.hasOwn(a,rCe)?!1:(a.allowConversationAccess=!0,r[Vvt]=o,g8n(e,t),!0)}):!1}function iCe(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e.hooks;return!t||typeof t!="object"||Array.isArray(t)?!1:t[rCe]===!1}function A8n(e){return e.toLowerCase().startsWith("zh")?"zh":"en"}var y8n={"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\uFF08\u4F1A\u8BDD\u3001\u89C4\u5219\u8BCD\u5178\uFF09",en:"View system status (session, rule 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 uc(e,t){let n=A8n(t),r=y8n[e];return r&&(r[n]||r.en)||e}import*as dS from"path";var Gr=(...e)=>dS.posix.join(...e);function _8n(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function I8n(e,t){return _8n(e)?dS.win32.join(e,t):e.startsWith("/")?dS.posix.join(e,t):dS.join(e,t)}var fr={IDENTITY:".principles",MODELS:Gr(".principles","models"),STATE:".state",MEMORY:"memory",OKR:Gr("memory","okr"),LOGS:Gr("memory","logs"),SESSIONS:Gr(".state","sessions"),PAIN_SAMPLES:Gr("memory","pain"),LOCKS:Gr("memory",".locks"),IMPL_CODE_DIR:Gr(".state","principles","implementations")},bZ={PROFILE:Gr(fr.IDENTITY,"PROFILE.json"),PRINCIPLES:Gr(fr.IDENTITY,"PRINCIPLES.md"),THINKING_OS:Gr(fr.IDENTITY,"THINKING_OS.md"),DECISION_POLICY:Gr(fr.IDENTITY,"DECISION_POLICY.json"),MODELS_DIR:fr.MODELS,STATE_DIR:fr.STATE,WORKBOARD:Gr(fr.STATE,"WORKBOARD.json"),AGENT_SCORECARD:Gr(fr.STATE,"AGENT_SCORECARD.json"),PAIN_FLAG:Gr(fr.STATE,".pain_flag"),SYSTEM_CAPABILITIES:Gr(fr.STATE,"SYSTEM_CAPABILITIES.json"),PAIN_SETTINGS:Gr(fr.STATE,"pain_settings.json"),PAIN_CANDIDATES:Gr(fr.STATE,"pain_candidates.json"),TRAJECTORY_DB:Gr(fr.STATE,"trajectory.db"),TRAJECTORY_BLOBS_DIR:Gr(fr.STATE,"blobs"),EXPORTS_DIR:Gr(fr.STATE,"exports"),SESSION_DIR:fr.SESSIONS,DICTIONARY:Gr(fr.STATE,"pain_dictionary.json"),PRINCIPLE_BLACKLIST:Gr(fr.STATE,"principle_blacklist.json"),WORKFLOWS_YAML:Gr(fr.STATE,"workflows.yaml"),IMPL_CODE_DIR:fr.IMPL_CODE_DIR,MEMORY_MD:"MEMORY.md",HEARTBEAT:"HEARTBEAT.md",SYSTEM_LOG:Gr(fr.LOGS,"SYSTEM.log"),REFLECTION_LOG:Gr(fr.MEMORY,"reflection-log.md"),USER_CONTEXT:Gr(fr.MEMORY,"USER_CONTEXT.md"),OKR_DIR:fr.OKR,CURRENT_FOCUS:Gr(fr.OKR,"CURRENT_FOCUS.md"),WEEK_STATE:Gr(fr.OKR,"WEEK_STATE.json"),EVOLUTION_STREAM:Gr(fr.MEMORY,"evolution.jsonl"),EVOLUTION_LOCK:Gr(fr.LOCKS,"evolution")};function is(e,t){return I8n(e,bZ[t])}import*as Mu from"path";import*as kZ from"os";import*as pS from"fs";var v8n={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"},SZ=class extends Error{constructor(n,r,i){super(n,i);this.code=r;this.name="PdError",this.category=v8n[r]??"execution_failed"}code;category};var CZ=class extends SZ{constructor(t,n){super(`[PD:Path] Unknown path key: ${t}`,"PATH_RESOLUTION_ERROR",n),this.name="PathResolutionError"}};var p$=class extends SZ{constructor(t,n){super(`[PD:Sample] Correction sample not found: ${t}`,"SAMPLE_NOT_FOUND",n),this.name="SampleNotFoundError"}};import*as $d from"path";import*as xL from"fs";var Jvt=3,E8n=50;function Ut(e,t){let n=e+".tmp";xL.writeFileSync(n,t,"utf8");let r;for(let i=0;i<Jvt;i++)try{xL.renameSync(n,e);return}catch(o){r=o;let a=o.code;if(a==="EPERM"||a==="EBUSY"||a==="EACCES"){if(i<Jvt-1){let s=E8n*Math.pow(2,i),c=Date.now()+s,u=!1;for(;Date.now()<c;)if(!u&&Date.now()>=c-10){try{ie("fs").accessSync?.(n)}catch{}u=!0}}continue}break}try{xL.unlinkSync(n)}catch{}throw r}function Zvt(e,t){if(!e)return"";let n=t.includes("\\")||t.length>=2&&t[1]===":",r=e.includes("\\")||e.length>=2&&e[1]===":",i=e;n!==r&&r&&(i=`/mnt/${e.charAt(0).toLowerCase()}${e.slice(2).replace(/\\/g,"/")}`);let o=i.startsWith("/")&&!r,a=!n,s;if(n){let c=$d.resolve(t);if(o)s=i;else{let u=$d.isAbsolute(i)?i:$d.join(c,i);s=$d.relative(c,u)}}else if(a&&o){let c=t.replace(/\\/g,"/");s=$d.posix.relative(c,i)}else{let c=t.replace(/\\/g,"/"),u=$d.isAbsolute(i)?i:$d.posix.join(c,i.replace(/\\/g,"/"));s=$d.posix.relative(c,u)}return s=s.replace(/\\/g,"/"),s.startsWith("../")?i:s}function Xvt(e){let t=e.replace(/\\/g,"/");return t.endsWith("/")&&(t=t.slice(0,-1)),t}function eEt(e,t){if(!e||!t||t.length===0)return!1;let n=Xvt(e);for(let r of t){let i=Xvt(r);if(n.startsWith(i)&&(n===i||n.charAt(i.length)==="/"))return!0}return!1}function Qo(e){return e==null?"":Array.isArray(e)?e.join(" "):e}var x8n=".openclaw/workspace";var oCe="principles-disciple.json",w8n=[Mu.join(process.cwd(),oCe),Mu.join(kZ.homedir(),".openclaw",oCe),Mu.join(kZ.homedir(),".principles",oCe)];function b8n(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")}function S8n(e){return e.startsWith("/")}function wL(e){return b8n(e)?Mu.win32:S8n(e)?Mu.posix:Mu}function C8n(){for(let e of w8n)if(pS.existsSync(e))return e;return null}function tEt(){let e=C8n();if(!e)return null;try{let t=pS.readFileSync(e,"utf8"),n=JSON.parse(t);return console.log(`[PD:PathResolver] Loaded config from: ${e}`),n}catch(t){return console.warn(`[PD:PathResolver] Failed to load config from ${e}: ${String(t)}`),null}}var Hd=class e{static extensionRoot=null;workspaceDir=null;stateDir=null;logger;normalizeWorkspace;initialized=!1;static setExtensionRoot(t){if(!t||!t.trim())return;let n=t.trim(),r=wL(n);e.extensionRoot=r.normalize(n)}static getExtensionRoot(){return e.extensionRoot}constructor(t={}){if(this.logger=t.logger,this.normalizeWorkspace=t.normalizeWorkspace??!0,t.workspaceDir){let n=t.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(t,n){let i=`[PD:PathResolver] ${n}`;switch(process.env.DEBUG==="true"&&this.logger?.debug?.(i),t){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 t=process.env.PD_WORKSPACE_DIR;if(t&&t.trim())return this.log("info",`Using workspace from PD_WORKSPACE_DIR: ${t}`),t.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=tEt();if(r?.workspace)return this.log("info",`Using workspace from config file: ${r.workspace}`),r.workspace;let i=kZ.homedir(),o=Mu.join(i,x8n);return this.log("info",`Using default workspace: ${o}`),o}normalizePath(t){let n=wL(t),r=n===Mu?Mu.resolve(t):n.normalize(t);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(t){return this.normalizePath(t)}getWorkspaceDir(){if(this.initialized&&this.workspaceDir)return this.workspaceDir;let t=this.detectWorkspaceDir();if(this.normalizeWorkspace){let n=t;t=this.normalizePath(t),n!==t&&this.log("info",`Workspace path normalized: ${n} -> ${t}`)}return this.workspaceDir=t,this.initialized=!0,this.log("debug",`Final workspace directory: ${this.workspaceDir}`),this.workspaceDir}getStateDir(){if(this.stateDir)return this.stateDir;let t=process.env.PD_STATE_DIR;if(t&&t.trim())return this.stateDir=t.trim(),this.log("info",`Using state directory from PD_STATE_DIR: ${this.stateDir}`),this.stateDir;if(this.initialized&&this.workspaceDir){let o=wL(this.workspaceDir);return this.stateDir=o.join(this.workspaceDir,".state"),this.log("debug",`Using workspace-based state directory: ${this.stateDir}`),this.stateDir}let n=tEt();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=wL(r);return this.stateDir=i.join(r,".state"),this.log("debug",`Computed state directory: ${this.stateDir}`),this.stateDir}resolve(t){let n=this.getWorkspaceDir(),r=this.getStateDir(),i=wL(n),o=e.extensionRoot||Mu.resolve(process.cwd(),"packages","openclaw-plugin"),a=wL(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}[t];if(!p)throw this.log("warn",`Unknown path key: ${t}`),new CZ(t);return this.log("debug",`Resolved path for '${t}': ${p}`),p}ensureStateDir(){let t=this.getStateDir();pS.existsSync(t)||(this.log("info",`Creating state directory: ${t}`),pS.mkdirSync(t,{recursive:!0}))}static createFromHookContext(t){let n=new e;if(t?.workspaceDir){let r=String(t.workspaceDir);n.normalizeWorkspace&&(r=n.normalizePath(r)),n.workspaceDir=r,n.initialized=!0,n.log("info",`Created from hook context with workspace: ${r}`)}return t?.stateDir&&(n.stateDir=String(t.stateDir)),n}};function nEt(e,t){if(!e)return;let n=e.runtime.agent;if(n?.resolveAgentWorkspaceDir)try{return n.resolveAgentWorkspaceDir(e.config,t??"main")}catch{}let r=e.config?.workspaceDir;if(r&&r.trim())return r.trim();try{return new Hd().getWorkspaceDir()}catch{return}}import*as rEt from"os";import*as RZ from"path";function aCe(e){return typeof e!="string"||!e.trim()||!RZ.isAbsolute(e)?!1:process.platform!=="win32"?!0:/^[A-Za-z]:[\\/]/.test(e)||/^\\\\[^\\/]/.test(e)}function Ul(e){if(!e)return"workspaceDir is undefined/null";if(/^[A-Za-z]:\\?$/.test(e))return`workspaceDir is a drive root: "${e}"`;let t=RZ.resolve(e),n=rEt.homedir();if(t===n)return`workspaceDir equals home directory (${n}), likely missing context field`;if(t==="/"||t==="")return`workspaceDir is root or empty: "${t}"`;if(/^[A-Za-z]:\\?$/.test(t))return`workspaceDir is a drive root: "${t}"`;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(t))return`workspaceDir ${a}: "${t}"`;return null}import*as fS from"fs";import*as OZ from"path";var iEt={language:"zh",diagnostician:{context:{time_window_minutes:5,max_message_length:500,max_summary_length:3e3}},thresholds:{cognitive_paralysis_input:4e3,semantic_min_score:.7,promotion_count_threshold:3,promotion_similarity_threshold:.8},compression:{line_threshold:100,size_threshold_kb:15,interval_hours:24,keep_completed_tasks:3,max_working_memory_artifacts:10}},TZ=class{settings={...iEt};filePath;constructor(t){this.filePath=OZ.join(t,"pain_settings.json")}load(){if(fS.existsSync(this.filePath))try{let t=JSON.parse(fS.readFileSync(this.filePath,"utf8"));this.settings=this.deepMerge(iEt,t)}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 t=OZ.dirname(this.filePath);fS.existsSync(t)||fS.mkdirSync(t,{recursive:!0}),Ut(this.filePath,JSON.stringify(this.settings,null,2)),console.log(`[PD:Config] Settings saved to ${this.filePath}`)}catch(t){console.error(`[PD:Config] Failed to save settings: ${String(t)}`)}}deepMerge(t,n){let r={...t};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 t?r[i]=this.deepMerge(t[i],n[i]):Object.assign(r,{[i]:n[i]}):Object.assign(r,{[i]:n[i]}))}),r}get(t){let n=t.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 f$=null,oEt=null,aEt={get(e){return(!f$||oEt!==e)&&(f$=new TZ(e),f$.load(),oEt=e),f$},reset(){f$=null}};import*as lc from"fs";import*as m$ from"path";var sEt=7,sCe=class{logsDir;statsFile;logger;statsCache=new Map;eventBuffer=[];maxBufferSize=20;flushIntervalMs=3e4;flushTimer;currentEventsFile;currentDate;constructor(t,n){let r=td(t);this.logsDir=m$.join(r,"logs"),lc.existsSync(this.logsDir)||lc.mkdirSync(this.logsDir,{recursive:!0}),this.statsFile=m$.join(this.logsDir,"daily-stats.json"),this.logger=n,this.loadStats(),this.startFlushTimer()}getEventsFile(t){return m$.join(this.logsDir,`events_${t}.jsonl`)}getTodayStr(){return new Date().toISOString().split("T")[0]??""}ensureEventsFile(){let t=this.getTodayStr();return(this.currentDate!==t||!this.currentEventsFile)&&(this.currentDate=t,this.currentEventsFile=this.getEventsFile(t),this.cleanupOldEventFiles(t)),this.currentEventsFile}cleanupOldEventFiles(t){if(!(sEt<=0))try{let n=Date.now()-sEt*24*60*60*1e3,r=lc.readdirSync(this.logsDir);for(let i of r){if(!i.startsWith("events_")||!i.endsWith(".jsonl"))continue;let o=m$.join(this.logsDir,i);lc.statSync(o).mtimeMs<n&&lc.unlinkSync(o)}}catch(n){this.logger?.debug?.(`[PD] Event file cleanup failed (non-blocking): ${String(n)}`)}}recordToolCall(t,n){let r=n.error||n.exitCode!==void 0&&n.exitCode!==0?"failure":"success";this.record("tool_call",r,t,n)}recordPainSignal(t,n){this.record("pain_signal","detected",t,n)}recordRulePromotion(t){this.record("rule_promotion","promoted",void 0,t)}recordGovernanceAction(t,n){this.record("governance_action","approved",void 0,t),n?.flushImmediately&&this.flushEvents()}recordHookExecution(t,n){let r=t.error?"failure":"success";this.record("hook_execution",r,void 0,t),n?.flushImmediately&&this.flushEvents()}recordAdaptiveDelivery(t,n){let r=qX(n);if(!r.ok)throw new Error(`Invalid adaptive delivery record: ${r.errors.join("; ")}`);this.record("adaptive_delivery","written",t,n),this.flushEvents()}recordGateBlock(t,n){this.record("gate_block","blocked",t,n)}recordGateBypass(t,n){this.record("gate_bypass","bypassed",t,n)}recordEmpathyRollback(t,n){this.record("empathy_rollback","rolled_back",t,n)}recordError(t,n,r){this.record("error","failure",t,{message:n,...r})}recordWarn(t,n,r){this.record("warn","failure",t,{message:n,...r})}recordDiagnosisTask(t){this.record("diagnosis_task","written",void 0,t)}recordHeartbeatDiagnosis(t){this.record("heartbeat_diagnosis","injected",void 0,t)}recordDiagnosticianReport(t){let n={success:"completed",missing_json:"failure",incomplete_fields:"failure"};this.record("diagnostician_report",n[t.category],void 0,t)}recordPrincipleCandidate(t){this.record("principle_candidate","created",void 0,t)}recordRuleEnforced(t){this.record("rule_enforced","matched",void 0,t)}recordRuleHostEvaluated(t){this.record("rulehost_evaluated","evaluated",void 0,t)}recordRuleHostBlocked(t){this.record("rulehost_blocked","blocked",void 0,t)}recordRuleHostRequireApproval(t){this.record("rulehost_requireApproval","requireApproval",void 0,t)}recordRuleHostAutoCorrectProposed(t){this.record("rulehost_auto_correct_proposed","auto_correct",void 0,t)}recordRuleHostAutoCorrectApplied(t){this.record("rulehost_auto_correct_applied","auto_correct",void 0,t)}recordRuntimeActivationsInjected(t){this.record("runtime_v2_prompt_activations_injected","injected",t.sessionId,t)}recordPromptPresenceObserved(t){this.record("runtime_v2_prompt_presence_observed","injected",t.sessionId,t),this.flushEvents()}recordRuleHostUnhealthy(t){this.record("rulehost_unhealthy","failure",void 0,t)}recordRuleHostSkipped(t){this.record("rulehost_skipped","failure",void 0,t)}recordTrajectoryObservabilityFailure(t){this.record("trajectory_observability_failure","failure",t.sessionId,t)}redactEventData(t,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(t))return n;let i={};for(let[o,a]of Object.entries(n))if(typeof a=="string")i[o]=CE(a);else if(Array.isArray(a))i[o]=a.map(s=>{if(typeof s=="string")return CE(s);if(typeof s=="object"&&s!==null){let c={};for(let[u,l]of Object.entries(s))c[u]=typeof l=="string"?CE(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]=CE(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:t,originalSessionId:n.sessionId??null}}}record(t,n,r,i){let o=new Date,a=this.formatDate(o),s=this.redactEventData(t,i),c={ts:o.toISOString(),date:a,type:t,category:n,sessionId:r,data:s};this.eventBuffer.push(c),this.updateStats(c),this.eventBuffer.length>=this.maxBufferSize&&this.flushEvents()}formatDate(t){return t.toISOString().split("T")[0]??""}loadStats(){if(lc.existsSync(this.statsFile))try{let t=JSON.parse(lc.readFileSync(this.statsFile,"utf-8"));for(let n in t)this.statsCache.set(n,t[n])}catch(t){this.logger&&this.logger.error(`[PD] Failed to load daily-stats.json: ${String(t)}`)}}updateStats(t){let n=this.statsCache.get(t.date);if(n||(n=SC(t.date),this.statsCache.set(t.date,n)),t.type==="tool_call")n.tools.total++,t.category==="success"?n.tools.success++:n.tools.failure++;else if(t.type==="pain_signal"){let r=t.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(t.type==="hook_execution"){let r=t.data;if(n.hooks.total++,t.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++,t.category==="success"?i.success++:i.failure++)}}else if(t.type==="empathy_rollback"){let r=t.data;n.empathy.rollbackCount++,n.empathy.rolledBackScore+=r.originalScore||0}else if(t.type==="rule_promotion")n.evolution.rulesPromoted++;else if(t.type==="evolution_task")t.category==="completed"?n.evolution.tasksCompleted++:t.category==="enqueued"&&n.evolution.tasksEnqueued++;else if(t.type==="diagnosis_task")n.evolution.diagnosisTasksWritten++;else if(t.type==="heartbeat_diagnosis")n.evolution.heartbeatsInjected++;else if(t.type==="diagnostician_report"){let r=t.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 t.type==="principle_candidate"?n.evolution.principleCandidatesCreated++:t.type==="rule_enforced"?n.evolution.rulesEnforced++:t.type==="rulehost_evaluated"?n.evolution.rulehostEvaluated++:t.type==="rulehost_blocked"?n.evolution.rulehostBlocked++:t.type==="rulehost_requireApproval"?n.evolution.rulehostRequireApproval++:t.type==="rulehost_auto_correct_proposed"?n.evolution.rulehostAutoCorrectProposed++:t.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(t=>({...t,data:{...t.data}}))}getEventDedupKey(t){let n=typeof t.data?.eventId=="string"?String(t.data.eventId):null;if(n)return`${t.type}:${t.sessionId??"none"}:${n}`;let r=t.data??{};return[t.ts??"no-ts",t.type??"no-type",t.category??"no-category",t.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 t=this.ensureEventsFile();if(!lc.existsSync(t))return[];try{return lc.readFileSync(t,"utf-8").trim().split(`
|
|
2239
2239
|
`).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 t=new Map;for(let n of[...this.readPersistedEvents(),...this.getBufferedEvents()])t.set(this.getEventDedupKey(n),n);return[...t.values()].sort((n,r)=>n.ts.localeCompare(r.ts))}flushEvents(){if(this.eventBuffer.length===0)return;let t=this.ensureEventsFile(),n=this.eventBuffer.map(r=>JSON.stringify(r)).join(`
|
|
2240
2240
|
`)+`
|
|
@@ -2712,7 +2712,7 @@ Reason: ${t}
|
|
|
2712
2712
|
This action was blocked by a Rule Host principle.
|
|
2713
2713
|
If the blocked path is correct and safe, explain the reasoning to the owner
|
|
2714
2714
|
and ask for explicit confirmation to proceed.
|
|
2715
|
-
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}function ywt(e,t,n,r,i){if(n>3){i(`[PD_GATE] Failed to persist trajectory gate block after ${3} retries (reasonCode=trajectory_write_exhausted): ${t.toolName} ${t.filePath}`);return}setTimeout(()=>{let o=gwt(e,t,r);if(o==="written"){r(`[PD_GATE] Trajectory gate block persisted on retry ${n}`);return}o!=="skipped"&&ywt(e,t,n+1,r,i)},250*n).unref()}var Iee=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],Sv=["write","edit","apply_patch"],T$=["exec"],rke=[...T$],HL=["sessions_spawn"],_3n=[...Sv],I3n=[...Sv,...T$,...HL],v3n=[...Iee],xEo=new Set(Iee),wEo=new Set(Sv),bEo=new Set(rke),vee=new Set(T$),_wt=new Set(HL),SEo=new Set(_3n),CEo=new Set(I3n),kEo=new Set(v3n),ike=new Set([...Sv]);function oke(e,t){return e.map(n=>({rawToolName:n,canonicalKind:t}))}var ske=Object.freeze([...oke(T$,"execute"),...oke(Sv,"write"),...oke(HL,"agent")]),ake=GP(ske);if(!ake.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${ake.errors.join("; ")}`);var Km=ake.registry;var E3n=20;function x3n(e,t,n){return _L(e,t,{projectDir:n,toolSemantics:Km})}function Iwt(e,t,n,r,i=E3n){if(!e||typeof e!="string"||e.length===0)return Qa;try{let o=n.getRuleHostContextRows(e,i),a=x3n(o.rows,o.truncated,r),s=ev(a,t,null);return{version:2,history:a,facts:s}}catch{return b3n("query or assembly failed")}}function w3n(e){return{status:"unavailable",unavailableReason:e,truncated:!1,calls:[]}}function b3n(e){return{version:2,history:w3n(e),facts:{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null}}}function Ewt(e){return $re(e)&&(e.activationMode!=="shadow"||typeof e.activationId=="string"&&e.activationId.trim().length>0)}function S3n(e){let t=e?.evaluations;if(Array.isArray(t))for(let n of t){if(!Ewt(n)||n.activationMode!=="live")continue;let r=n.activationId;if(typeof r=="string"&&r.trim().length>0)return r}}function xwt(e,t){let n=t.logger||console,r=vee.has(e.toolName),i=ike.has(e.toolName),o=_wt.has(e.toolName);if(!t.workspaceDir||!i&&!r&&!o)return;let a=ft.fromHookContext(t),s=Bd(e.toolName,e.params??{},a.workspaceDir,{isBashTool:r,isWriteTool:i,canonicalKind:Km.resolve(e.toolName)}),c=s.normalizedPath;if(c!==null)try{let u=a.getRuleHost(n),l=cke(a,c,t.sessionId,n),p={action:s,workspace:{isRiskPath:!1},session:{sessionId:t.sessionId},evolution:{epTier:wwt()},derived:{estimatedLineChanges:aL({toolName:e.toolName,params:e.params??{}}),bashRisk:bwt(e)},context:l},f=typeof u.evaluateDetailed=="function"?u.evaluateDetailed(p):{liveDecision:u.evaluate(p),shadowDecisions:[],skippedActivations:[],liveRulesLoaded:0,evaluationStatus:"ok"},m=f.liveDecision,g=m?.decision??(f.evaluationStatus==="failed"?"evaluation_failed":f.liveRulesLoaded>0?"allow":"no_rules_armed"),h=g==="no_rules_armed"||g==="evaluation_failed"?"allow":g;if(GZ({workspaceDir:a.workspaceDir,activationId:f.liveDecisionActivationId,toolName:e.toolName,params:e.params??{},decision:h,matched:m?.matched??!1,logger:n})){n.warn?.(`[PD_GATE] RuleCode ${f.liveDecisionActivationId??"unknown"} safety-isolated; allowing current host call.`);return}for(let _ of f.shadowDecisions)try{dc.get(a.stateDir,n).recordRuleHostEvaluated({toolName:e.toolName,filePath:c,matched:_.matched,decision:_.decision,ruleId:_.ruleId,activationId:_.activationId,activationMode:"shadow",hostKind:"openclaw"})}catch(v){n?.warn?.(`[PD_GATE] Failed to record shadow rulehost_evaluated: ${String(v)}`)}try{dc.get(a.stateDir,n).recordRuleHostEvaluated({toolName:e.toolName,filePath:c,matched:m?.matched??!1,decision:g,ruleId:m?.ruleId,activationId:f.liveDecisionActivationId,activationMode:"live",hostKind:"openclaw"})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rulehost_evaluated: ${String(_)}`)}if(m?.decision==="block"){try{let _=dc.get(a.stateDir,n);_.recordRuleEnforced({ruleId:m.ruleId||"unknown",principleId:m.principleId||"unknown",enforcement:"block",toolName:e.toolName,filePath:c}),_.recordRuleHostBlocked({toolName:e.toolName,filePath:c,reason:m.reason,ruleId:m.ruleId})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rule_enforced/rulehost_blocked: ${String(_)}`)}try{if(jr(a.workspaceDir,"principle_receipt_ledger").enabled){let _=m.principleId??m.ruleId;_?iee(a.workspaceDir,{principleId:_,activationId:f.liveDecisionActivationId,ruleId:m.ruleId,channel:"code_tool_hook",level:"effect",kind:"rule_blocked",sessionId:t.sessionId,toolName:e.toolName,filePath:c,digest:m.reason})||n?.warn?.("[PD_GATE] Receipt ledger write failed (rule_blocked) \u2014 history degraded, block unaffected (rc-9)"):n?.warn?.("[PD_GATE] Receipt ledger row skipped (rule_blocked): decision carries no principleId/ruleId \u2014 effect evidence not captured (rc-9)")}}catch(_){n?.warn?.(`[PD_GATE] Receipt ledger write threw (rule_blocked): ${String(_)}`)}try{ree({workspaceDir:a.workspaceDir,sessionId:t.sessionId,...Eee(e),toolName:e.toolName,filePath:c,activationId:f.liveDecisionActivationId,principleId:m.principleId,ruleId:m.ruleId,reason:m.reason,decision:"block",logger:n})}catch(_){n?.warn?.(`[PD_GATE] Evidence recording threw (block decision unaffected): ${String(_)}`)}return Awt(a,{filePath:c,reason:m.reason,toolName:e.toolName,sessionId:t.sessionId,blockSource:"rule-host",ruleId:m.ruleId,principleId:m.principleId},n)}if(m?.decision==="requireApproval")try{let _=dc.get(a.stateDir,n);_.recordRuleEnforced({ruleId:m.ruleId||"unknown",principleId:m.principleId||"unknown",enforcement:"requireApproval",toolName:e.toolName,filePath:c}),_.recordRuleHostRequireApproval({toolName:e.toolName,filePath:c,reason:m.reason,ruleId:m.ruleId})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rule_enforced/rulehost_requireApproval: ${String(_)}`)}if(m?.decision==="auto_correct"&&m.correctionProposal){let _=m.correctionProposal,v;try{v=Uy(_)}catch(w){v={valid:!1,errors:[`Validator threw: ${String(w)}`]}}try{let w=dc.get(a.stateDir,n),b=Array.isArray(_.correctedFields)?_.correctedFields.map(k=>String(typeof k=="object"&&k!==null?k.field:k)):[];w.recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:m.reason,applicationMode:_.applicationMode==="live"?"live":"shadow",correctedFields:b,validationValid:v.valid})}catch(w){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_proposed: ${String(w)}`)}if(_.applicationMode==="live"&&v.valid){if(!e.params)return;let w={...e.params},b={},k=[];try{if(!Array.isArray(_.correctedFields))throw new Error("proposal.correctedFields is not an array");if(!_.proposedParams||typeof _.proposedParams!="object"||Array.isArray(_.proposedParams))throw new Error("proposal.proposedParams must be an object");let P=t.workspaceDir;if(typeof P=="string"&&P.trim().length>0){let B=Jwe(_.proposedParams,P);if(!B.valid)throw new Error(`Path boundary violation: ${B.reason}`)}else if(Object.keys(_.proposedParams).some(N=>typeof _.proposedParams[N]=="string"&&(N==="file_path"||N==="path"||N==="filePath")))throw new Error("Cannot apply live auto-correction with path fields: no trusted workspace directory available");for(let B of _.correctedFields){if(typeof B!="object"||B===null||typeof B.field!="string")throw new Error("correctedFields entry must be an object with a string field");let N=B.field;if(!Object.hasOwn(e.params,N))throw new Error(`Field '${N}' not found in event.params`);if(!Object.hasOwn(_.proposedParams,N))throw new Error(`Field '${N}' not found in proposal.proposedParams`)}for(let B of _.correctedFields)if(typeof B=="object"&&B!==null&&typeof B.field=="string"){let N=B.field,T=e.params[N],M=_.proposedParams[N];b[N]=M,k.push({field:N,original:T,applied:M})}Object.assign(e.params,b);try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectApplied({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:m.reason||_.correctedFields?.[0]?.reason||"auto-correct applied",correctedFields:k})}catch(B){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_applied: ${String(B)}`)}if(k.length>0){try{if(DEt(t.sessionId,a.workspaceDir),jr(a.workspaceDir,"principle_receipt_ledger").enabled){let B=_.principleId!=null?String(_.principleId):String(_.ruleId??"unknown");iee(a.workspaceDir,{principleId:B,activationId:f.liveDecisionActivationId,ruleId:String(_.ruleId??"unknown"),channel:"code_tool_hook",level:"effect",kind:"auto_correct_applied",sessionId:t.sessionId,toolName:e.toolName,filePath:c,digest:k.map(T=>`${T.field}: ${JSON.stringify(T.original)} -> ${JSON.stringify(T.applied)}`).join(", ").slice(0,200)})||n?.warn?.("[PD_GATE] Receipt ledger write failed (auto_correct_applied) \u2014 history degraded, correction unaffected (rc-9)")}}catch(B){n?.warn?.(`[PD_GATE] Receipt ledger write threw (auto_correct_applied): ${String(B)}`)}try{ree({workspaceDir:a.workspaceDir,sessionId:t.sessionId,...Eee(e),toolName:e.toolName,filePath:c,activationId:f.liveDecisionActivationId,principleId:_.principleId!=null?String(_.principleId):void 0,ruleId:String(_.ruleId??"unknown"),reason:m.reason,decision:"auto_correct",logger:n})}catch(B){n?.warn?.(`[PD_GATE] Evidence recording threw (correction unaffected): ${String(B)}`)}return{params:{...e.params}}}}catch(P){e.params&&Object.assign(e.params,w);let B=String(P);if(B.includes("Path boundary violation")||B.includes("no trusted workspace directory")){n?.warn?.(`[PD_GATE] Live auto-correction rejected \u2014 path out of bounds: ${B}`);try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:`Path boundary rejected: ${B}`,applicationMode:"shadow",correctedFields:Array.isArray(_.correctedFields)?_.correctedFields.map(M=>String(typeof M=="object"&&M!==null?M.field:M)):[],validationValid:!1})}catch(T){n?.warn?.(`[PD_GATE] Failed to record path rejection telemetry: ${String(T)}`)}}else n?.warn?.(`[PD_GATE] Failed to apply auto-correction, using original params: ${B}`)}}}else if(m?.decision==="auto_correct")try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:m.ruleId??"unknown",confidence:0,reason:m.reason??"auto_correct without correctionProposal",applicationMode:"shadow",correctedFields:[],validationValid:!1})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_proposed (no proposal): ${String(_)}`)}}catch(u){n.warn?.(`[PD_GATE:RULE_HOST] Host evaluation failed, allowing conservatively: ${String(u)}`)}}function Eee(e){let t=i=>{if(!Object.hasOwn(e,i))return;let o=e[i];return typeof o=="string"&&o.trim().length>0?o:void 0},n=t("toolUseId")??t("toolCallId"),r=t("runId");return{...n!==void 0?{toolCallId:n}:{},...r!==void 0?{runId:r}:{}}}function wwt(){return 1}function bwt(e){return vee.has(e.toolName)?xP(!0,e.params):"unknown"}function Swt(e){return{epTier:wwt(),bashRisk:bwt(e)}}function cke(e,t,n,r){let i;try{i=Lr(e.workspaceDir)}catch(s){r?.warn?.(`[PD_GATE] RuleContext v2: config load failed, skipping context assembly: ${String(s)}`);return}if(!i.ok){let s=i.errors.map(c=>c.reason).join("; ");r?.warn?.(`[PD_GATE] RuleContext v2: config load returned malformed result, skipping context assembly: ${s}`);return}if(Ai(i.effective).flags.rulecode_context_v2?.enabled)try{return Iwt(n,t,e.trajectory,e.workspaceDir)}catch(s){return r?.warn?.(`[PD_GATE] RuleContext v2: buildProductionRuleContext threw unexpectedly, using unavailable context: ${String(s)}`),Qa}}function Cwt(e,t,n){let r=t.logger??console;for(let m of n.warnings??[])r.warn?.(`[PD_GATE:RULE_HOST] ${m}`);let i=n.metadata?.evaluatedLiveRules;r.info?.(`[PD_GATE:RULE_HOST] shared production gate evaluated; liveRules=${typeof i=="number"?i:"unknown"} decision=${n.decision}`);let o=n.metadata,a=o?.ruleDecision;if(a==="auto_correct"||a==="requireApproval"){r.info?.(`[PD_GATE:RULE_HOST] shared result carries ruleDecision=${String(a)}; the legacy handler records the decision events`);return}let s=ft.fromHookContext(t),c=Bd(e.toolName,e.params??{},s.workspaceDir,{isBashTool:vee.has(e.toolName),isWriteTool:ike.has(e.toolName),canonicalKind:Km.resolve(e.toolName)}),u=typeof o?.ruleId=="string"?o.ruleId:void 0,l=typeof o?.principleId=="string"?o.principleId:void 0,p=S3n(o),f=n.reason??"RuleHost denied the tool call";if(c.normalizedPath===null){n.decision==="deny"&&vwt(s,{sessionId:t.sessionId,toolName:e.toolName,filePath:null,reason:f,ruleId:u,principleId:l,activationId:p,...Eee(e)},r);return}try{let m=dc.get(s.stateDir,r),g=o?.evaluations;if(Array.isArray(g)){let h=!1;for(let y of g){if(!Ewt(y)){r.warn?.("[PD_GATE:RULE_HOST] shared gate produced an invalid evaluation entry; the row was not persisted (rc-9)");continue}m.recordRuleHostEvaluated({toolName:y.toolName,filePath:y.filePath,matched:y.matched,decision:y.decision,...y.ruleId!==void 0?{ruleId:y.ruleId}:{},...y.activationId!==void 0?{activationId:y.activationId}:{},...y.activationMode!==void 0?{activationMode:y.activationMode}:{},...y.hostKind!==void 0?{hostKind:y.hostKind}:{hostKind:"openclaw"}}),h=!0}h||r.warn?.("[PD_GATE:RULE_HOST] shared gate evaluations array carried no valid entry; no rulehost_evaluated row persisted (rc-9)")}else m.recordRuleHostEvaluated({toolName:e.toolName,filePath:c.normalizedPath,matched:n.decision==="deny",decision:n.decision==="deny"?"block":"allow",ruleId:u,activationMode:"live",hostKind:"openclaw"});n.decision==="deny"&&(m.recordRuleEnforced({ruleId:u??"unknown",principleId:l??"unknown",enforcement:"block",toolName:e.toolName,filePath:c.normalizedPath}),m.recordRuleHostBlocked({toolName:e.toolName,filePath:c.normalizedPath,reason:f,ruleId:u}))}catch(m){r.warn?.(`[PD_GATE] Failed to record shared RuleHost result: ${String(m)}`)}n.decision==="deny"&&vwt(s,{sessionId:t.sessionId,toolName:e.toolName,filePath:c.normalizedPath,reason:f,ruleId:u,principleId:l,activationId:p,...Eee(e)},r)}function vwt(e,t,n){t.filePath===null&&n.warn?.("[PD_GATE] Shared-path deny accounted with unresolved target path (reasonCode=shared_deny_path_unresolved)");try{if(jr(e.workspaceDir,"principle_receipt_ledger").enabled){let r=t.principleId??t.ruleId;r?iee(e.workspaceDir,{principleId:r,activationId:t.activationId,ruleId:t.ruleId,channel:"code_tool_hook",level:"effect",kind:"rule_blocked",sessionId:t.sessionId,toolName:t.toolName,filePath:t.filePath??void 0,digest:t.reason})||n.warn?.("[PD_GATE] Receipt ledger write failed (rule_blocked, shared) \u2014 history degraded, block unaffected (rc-9)"):n.warn?.("[PD_GATE] Receipt ledger row skipped (rule_blocked, shared): decision carries no principleId/ruleId \u2014 effect evidence not captured (rc-9)")}}catch(r){n.warn?.(`[PD_GATE] Receipt ledger write threw (rule_blocked, shared): ${String(r)}`)}try{ree({workspaceDir:e.workspaceDir,sessionId:t.sessionId,...t.toolCallId!==void 0?{toolCallId:t.toolCallId}:{},...t.runId!==void 0?{runId:t.runId}:{},toolName:t.toolName,filePath:t.filePath??void 0,activationId:t.activationId,principleId:t.principleId,ruleId:t.ruleId,reason:t.reason,decision:"block",logger:n})}catch(r){n.warn?.(`[PD_GATE] Evidence recording threw (shared deny accounting continues): ${String(r)}`)}nke(e,{filePath:t.filePath,reason:t.reason,toolName:t.toolName,sessionId:t.sessionId,blockSource:"rule-host-shared",ruleId:t.ruleId,principleId:t.principleId},n)}import*as so from"fs";import*as Cv from"path";import*as uke from"readline";async function kwt(e,t){if(!t.workspaceDir||!e.messages||e.messages.length===0)return;let n=ft.fromHookContext(t),r=e.messages.filter(i=>{let o=i;return o.role==="assistant"&&typeof o.content=="string"&&(o.content.includes("error")||o.content.includes("fail")||o.content.includes("blocked"))});if(r.length>0){let i=n.resolve("MEMORY_MD"),o=`
|
|
2715
|
+
\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501`}function ywt(e,t,n,r,i){if(n>3){i(`[PD_GATE] Failed to persist trajectory gate block after ${3} retries (reasonCode=trajectory_write_exhausted): ${t.toolName} ${t.filePath}`);return}setTimeout(()=>{let o=gwt(e,t,r);if(o==="written"){r(`[PD_GATE] Trajectory gate block persisted on retry ${n}`);return}o!=="skipped"&&ywt(e,t,n+1,r,i)},250*n).unref()}var Iee=["read","read_file","read_many_files","image_read","search_file_content","grep","grep_search","list_directory","ls","glob","lsp_hover","lsp_goto_definition","lsp_find_references","web_fetch","web_search","ref_search_documentation","ref_read_url","resolve-library-id","get-library-docs","memory_recall","save_memory","todo_read","todo_write","ask_user","ask_user_question","pd-status","report"],Sv=["write","edit","apply_patch"],T$=["exec"],rke=[...T$],HL=["sessions_spawn"],_3n=[...Sv],I3n=[...Sv,...T$,...HL],v3n=[...Iee],OEo=new Set(Iee),DEo=new Set(Sv),PEo=new Set(rke),vee=new Set(T$),_wt=new Set(HL),LEo=new Set(_3n),NEo=new Set(I3n),MEo=new Set(v3n),ike=new Set([...Sv]);function oke(e,t){return e.map(n=>({rawToolName:n,canonicalKind:t}))}var ske=Object.freeze([...oke(T$,"execute"),...oke(Sv,"write"),...oke(HL,"agent")]),ake=GP(ske);if(!ake.ok)throw new Error(`[PD] OpenClaw tool semantic declaration is invalid: ${ake.errors.join("; ")}`);var Km=ake.registry;var E3n=20;function x3n(e,t,n){return _L(e,t,{projectDir:n,toolSemantics:Km})}function Iwt(e,t,n,r,i=E3n){if(!e||typeof e!="string"||e.length===0)return Qa;try{let o=n.getRuleHostContextRows(e,i),a=x3n(o.rows,o.truncated,r),s=ev(a,t,null);return{version:2,history:a,facts:s}}catch{return b3n("query or assembly failed")}}function w3n(e){return{status:"unavailable",unavailableReason:e,truncated:!1,calls:[]}}function b3n(e){return{version:2,history:w3n(e),facts:{priorReadOfTarget:"unknown",readCount:null,writeCount:null,uniqueWritePathCount:null,sameActionBlockCount:null}}}function Ewt(e){return $re(e)&&(e.activationMode!=="shadow"||typeof e.activationId=="string"&&e.activationId.trim().length>0)}function S3n(e){let t=e?.evaluations;if(Array.isArray(t))for(let n of t){if(!Ewt(n)||n.activationMode!=="live")continue;let r=n.activationId;if(typeof r=="string"&&r.trim().length>0)return r}}function xwt(e,t){let n=t.logger||console,r=vee.has(e.toolName),i=ike.has(e.toolName),o=_wt.has(e.toolName);if(!t.workspaceDir||!i&&!r&&!o)return;let a=ft.fromHookContext(t),s=Bd(e.toolName,e.params??{},a.workspaceDir,{isBashTool:r,isWriteTool:i,canonicalKind:Km.resolve(e.toolName)}),c=s.normalizedPath;if(c!==null)try{let u=a.getRuleHost(n),l=cke(a,c,t.sessionId,n),p={action:s,workspace:{isRiskPath:!1},session:{sessionId:t.sessionId},evolution:{epTier:wwt()},derived:{estimatedLineChanges:aL({toolName:e.toolName,params:e.params??{}}),bashRisk:bwt(e)},context:l},f=typeof u.evaluateDetailed=="function"?u.evaluateDetailed(p):{liveDecision:u.evaluate(p),shadowDecisions:[],skippedActivations:[],liveRulesLoaded:0,evaluationStatus:"ok"},m=f.liveDecision,g=m?.decision??(f.evaluationStatus==="failed"?"evaluation_failed":f.liveRulesLoaded>0?"allow":"no_rules_armed"),h=g==="no_rules_armed"||g==="evaluation_failed"?"allow":g;if(GZ({workspaceDir:a.workspaceDir,activationId:f.liveDecisionActivationId,toolName:e.toolName,params:e.params??{},decision:h,matched:m?.matched??!1,logger:n})){n.warn?.(`[PD_GATE] RuleCode ${f.liveDecisionActivationId??"unknown"} safety-isolated; allowing current host call.`);return}for(let _ of f.shadowDecisions)try{dc.get(a.stateDir,n).recordRuleHostEvaluated({toolName:e.toolName,filePath:c,matched:_.matched,decision:_.decision,ruleId:_.ruleId,activationId:_.activationId,activationMode:"shadow",hostKind:"openclaw"})}catch(v){n?.warn?.(`[PD_GATE] Failed to record shadow rulehost_evaluated: ${String(v)}`)}try{dc.get(a.stateDir,n).recordRuleHostEvaluated({toolName:e.toolName,filePath:c,matched:m?.matched??!1,decision:g,ruleId:m?.ruleId,activationId:f.liveDecisionActivationId,activationMode:"live",hostKind:"openclaw"})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rulehost_evaluated: ${String(_)}`)}if(m?.decision==="block"){try{let _=dc.get(a.stateDir,n);_.recordRuleEnforced({ruleId:m.ruleId||"unknown",principleId:m.principleId||"unknown",enforcement:"block",toolName:e.toolName,filePath:c}),_.recordRuleHostBlocked({toolName:e.toolName,filePath:c,reason:m.reason,ruleId:m.ruleId})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rule_enforced/rulehost_blocked: ${String(_)}`)}try{if(jr(a.workspaceDir,"principle_receipt_ledger").enabled){let _=m.principleId??m.ruleId;_?iee(a.workspaceDir,{principleId:_,activationId:f.liveDecisionActivationId,ruleId:m.ruleId,channel:"code_tool_hook",level:"effect",kind:"rule_blocked",sessionId:t.sessionId,toolName:e.toolName,filePath:c,digest:m.reason})||n?.warn?.("[PD_GATE] Receipt ledger write failed (rule_blocked) \u2014 history degraded, block unaffected (rc-9)"):n?.warn?.("[PD_GATE] Receipt ledger row skipped (rule_blocked): decision carries no principleId/ruleId \u2014 effect evidence not captured (rc-9)")}}catch(_){n?.warn?.(`[PD_GATE] Receipt ledger write threw (rule_blocked): ${String(_)}`)}try{ree({workspaceDir:a.workspaceDir,sessionId:t.sessionId,...Eee(e),toolName:e.toolName,filePath:c,activationId:f.liveDecisionActivationId,principleId:m.principleId,ruleId:m.ruleId,reason:m.reason,decision:"block",logger:n})}catch(_){n?.warn?.(`[PD_GATE] Evidence recording threw (block decision unaffected): ${String(_)}`)}return Awt(a,{filePath:c,reason:m.reason,toolName:e.toolName,sessionId:t.sessionId,blockSource:"rule-host",ruleId:m.ruleId,principleId:m.principleId},n)}if(m?.decision==="requireApproval")try{let _=dc.get(a.stateDir,n);_.recordRuleEnforced({ruleId:m.ruleId||"unknown",principleId:m.principleId||"unknown",enforcement:"requireApproval",toolName:e.toolName,filePath:c}),_.recordRuleHostRequireApproval({toolName:e.toolName,filePath:c,reason:m.reason,ruleId:m.ruleId})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rule_enforced/rulehost_requireApproval: ${String(_)}`)}if(m?.decision==="auto_correct"&&m.correctionProposal){let _=m.correctionProposal,v;try{v=Uy(_)}catch(w){v={valid:!1,errors:[`Validator threw: ${String(w)}`]}}try{let w=dc.get(a.stateDir,n),b=Array.isArray(_.correctedFields)?_.correctedFields.map(k=>String(typeof k=="object"&&k!==null?k.field:k)):[];w.recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:m.reason,applicationMode:_.applicationMode==="live"?"live":"shadow",correctedFields:b,validationValid:v.valid})}catch(w){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_proposed: ${String(w)}`)}if(_.applicationMode==="live"&&v.valid){if(!e.params)return;let w={...e.params},b={},k=[];try{if(!Array.isArray(_.correctedFields))throw new Error("proposal.correctedFields is not an array");if(!_.proposedParams||typeof _.proposedParams!="object"||Array.isArray(_.proposedParams))throw new Error("proposal.proposedParams must be an object");let P=t.workspaceDir;if(typeof P=="string"&&P.trim().length>0){let B=Jwe(_.proposedParams,P);if(!B.valid)throw new Error(`Path boundary violation: ${B.reason}`)}else if(Object.keys(_.proposedParams).some(N=>typeof _.proposedParams[N]=="string"&&(N==="file_path"||N==="path"||N==="filePath")))throw new Error("Cannot apply live auto-correction with path fields: no trusted workspace directory available");for(let B of _.correctedFields){if(typeof B!="object"||B===null||typeof B.field!="string")throw new Error("correctedFields entry must be an object with a string field");let N=B.field;if(!Object.hasOwn(e.params,N))throw new Error(`Field '${N}' not found in event.params`);if(!Object.hasOwn(_.proposedParams,N))throw new Error(`Field '${N}' not found in proposal.proposedParams`)}for(let B of _.correctedFields)if(typeof B=="object"&&B!==null&&typeof B.field=="string"){let N=B.field,T=e.params[N],M=_.proposedParams[N];b[N]=M,k.push({field:N,original:T,applied:M})}Object.assign(e.params,b);try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectApplied({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:m.reason||_.correctedFields?.[0]?.reason||"auto-correct applied",correctedFields:k})}catch(B){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_applied: ${String(B)}`)}if(k.length>0){try{if(DEt(t.sessionId,a.workspaceDir),jr(a.workspaceDir,"principle_receipt_ledger").enabled){let B=_.principleId!=null?String(_.principleId):String(_.ruleId??"unknown");iee(a.workspaceDir,{principleId:B,activationId:f.liveDecisionActivationId,ruleId:String(_.ruleId??"unknown"),channel:"code_tool_hook",level:"effect",kind:"auto_correct_applied",sessionId:t.sessionId,toolName:e.toolName,filePath:c,digest:k.map(T=>`${T.field}: ${JSON.stringify(T.original)} -> ${JSON.stringify(T.applied)}`).join(", ").slice(0,200)})||n?.warn?.("[PD_GATE] Receipt ledger write failed (auto_correct_applied) \u2014 history degraded, correction unaffected (rc-9)")}}catch(B){n?.warn?.(`[PD_GATE] Receipt ledger write threw (auto_correct_applied): ${String(B)}`)}try{ree({workspaceDir:a.workspaceDir,sessionId:t.sessionId,...Eee(e),toolName:e.toolName,filePath:c,activationId:f.liveDecisionActivationId,principleId:_.principleId!=null?String(_.principleId):void 0,ruleId:String(_.ruleId??"unknown"),reason:m.reason,decision:"auto_correct",logger:n})}catch(B){n?.warn?.(`[PD_GATE] Evidence recording threw (correction unaffected): ${String(B)}`)}return{params:{...e.params}}}}catch(P){e.params&&Object.assign(e.params,w);let B=String(P);if(B.includes("Path boundary violation")||B.includes("no trusted workspace directory")){n?.warn?.(`[PD_GATE] Live auto-correction rejected \u2014 path out of bounds: ${B}`);try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:String(_.ruleId??"unknown"),principleId:_.principleId!=null?String(_.principleId):void 0,confidence:typeof _.confidence=="number"?_.confidence:0,reason:`Path boundary rejected: ${B}`,applicationMode:"shadow",correctedFields:Array.isArray(_.correctedFields)?_.correctedFields.map(M=>String(typeof M=="object"&&M!==null?M.field:M)):[],validationValid:!1})}catch(T){n?.warn?.(`[PD_GATE] Failed to record path rejection telemetry: ${String(T)}`)}}else n?.warn?.(`[PD_GATE] Failed to apply auto-correction, using original params: ${B}`)}}}else if(m?.decision==="auto_correct")try{dc.get(a.stateDir,n).recordRuleHostAutoCorrectProposed({toolName:e.toolName,filePath:c,ruleId:m.ruleId??"unknown",confidence:0,reason:m.reason??"auto_correct without correctionProposal",applicationMode:"shadow",correctedFields:[],validationValid:!1})}catch(_){n?.warn?.(`[PD_GATE] Failed to record rulehost_auto_correct_proposed (no proposal): ${String(_)}`)}}catch(u){n.warn?.(`[PD_GATE:RULE_HOST] Host evaluation failed, allowing conservatively: ${String(u)}`)}}function Eee(e){let t=i=>{if(!Object.hasOwn(e,i))return;let o=e[i];return typeof o=="string"&&o.trim().length>0?o:void 0},n=t("toolUseId")??t("toolCallId"),r=t("runId");return{...n!==void 0?{toolCallId:n}:{},...r!==void 0?{runId:r}:{}}}function wwt(){return 1}function bwt(e){return vee.has(e.toolName)?xP(!0,e.params):"unknown"}function Swt(e){return{epTier:wwt(),bashRisk:bwt(e)}}function cke(e,t,n,r){let i;try{i=Lr(e.workspaceDir)}catch(s){r?.warn?.(`[PD_GATE] RuleContext v2: config load failed, skipping context assembly: ${String(s)}`);return}if(!i.ok){let s=i.errors.map(c=>c.reason).join("; ");r?.warn?.(`[PD_GATE] RuleContext v2: config load returned malformed result, skipping context assembly: ${s}`);return}if(Ai(i.effective).flags.rulecode_context_v2?.enabled)try{return Iwt(n,t,e.trajectory,e.workspaceDir)}catch(s){return r?.warn?.(`[PD_GATE] RuleContext v2: buildProductionRuleContext threw unexpectedly, using unavailable context: ${String(s)}`),Qa}}function Cwt(e,t,n){let r=t.logger??console;for(let m of n.warnings??[])r.warn?.(`[PD_GATE:RULE_HOST] ${m}`);let i=n.metadata?.evaluatedLiveRules;r.info?.(`[PD_GATE:RULE_HOST] shared production gate evaluated; liveRules=${typeof i=="number"?i:"unknown"} decision=${n.decision}`);let o=n.metadata,a=o?.ruleDecision;if(a==="auto_correct"||a==="requireApproval"){r.info?.(`[PD_GATE:RULE_HOST] shared result carries ruleDecision=${String(a)}; the legacy handler records the decision events`);return}let s=ft.fromHookContext(t),c=Bd(e.toolName,e.params??{},s.workspaceDir,{isBashTool:vee.has(e.toolName),isWriteTool:ike.has(e.toolName),canonicalKind:Km.resolve(e.toolName)}),u=typeof o?.ruleId=="string"?o.ruleId:void 0,l=typeof o?.principleId=="string"?o.principleId:void 0,p=S3n(o),f=n.reason??"RuleHost denied the tool call";if(c.normalizedPath===null){n.decision==="deny"&&vwt(s,{sessionId:t.sessionId,toolName:e.toolName,filePath:null,reason:f,ruleId:u,principleId:l,activationId:p,...Eee(e)},r);return}try{let m=dc.get(s.stateDir,r),g=o?.evaluations;if(Array.isArray(g)){let h=!1;for(let y of g){if(!Ewt(y)){r.warn?.("[PD_GATE:RULE_HOST] shared gate produced an invalid evaluation entry; the row was not persisted (rc-9)");continue}m.recordRuleHostEvaluated({toolName:y.toolName,filePath:y.filePath,matched:y.matched,decision:y.decision,...y.ruleId!==void 0?{ruleId:y.ruleId}:{},...y.activationId!==void 0?{activationId:y.activationId}:{},...y.activationMode!==void 0?{activationMode:y.activationMode}:{},...y.hostKind!==void 0?{hostKind:y.hostKind}:{hostKind:"openclaw"}}),h=!0}h||r.warn?.("[PD_GATE:RULE_HOST] shared gate evaluations array carried no valid entry; no rulehost_evaluated row persisted (rc-9)")}else m.recordRuleHostEvaluated({toolName:e.toolName,filePath:c.normalizedPath,matched:n.decision==="deny",decision:n.decision==="deny"?"block":"allow",ruleId:u,activationMode:"live",hostKind:"openclaw"});n.decision==="deny"&&(m.recordRuleEnforced({ruleId:u??"unknown",principleId:l??"unknown",enforcement:"block",toolName:e.toolName,filePath:c.normalizedPath}),m.recordRuleHostBlocked({toolName:e.toolName,filePath:c.normalizedPath,reason:f,ruleId:u}))}catch(m){r.warn?.(`[PD_GATE] Failed to record shared RuleHost result: ${String(m)}`)}n.decision==="deny"&&vwt(s,{sessionId:t.sessionId,toolName:e.toolName,filePath:c.normalizedPath,reason:f,ruleId:u,principleId:l,activationId:p,...Eee(e)},r)}function vwt(e,t,n){t.filePath===null&&n.warn?.("[PD_GATE] Shared-path deny accounted with unresolved target path (reasonCode=shared_deny_path_unresolved)");try{if(jr(e.workspaceDir,"principle_receipt_ledger").enabled){let r=t.principleId??t.ruleId;r?iee(e.workspaceDir,{principleId:r,activationId:t.activationId,ruleId:t.ruleId,channel:"code_tool_hook",level:"effect",kind:"rule_blocked",sessionId:t.sessionId,toolName:t.toolName,filePath:t.filePath??void 0,digest:t.reason})||n.warn?.("[PD_GATE] Receipt ledger write failed (rule_blocked, shared) \u2014 history degraded, block unaffected (rc-9)"):n.warn?.("[PD_GATE] Receipt ledger row skipped (rule_blocked, shared): decision carries no principleId/ruleId \u2014 effect evidence not captured (rc-9)")}}catch(r){n.warn?.(`[PD_GATE] Receipt ledger write threw (rule_blocked, shared): ${String(r)}`)}try{ree({workspaceDir:e.workspaceDir,sessionId:t.sessionId,...t.toolCallId!==void 0?{toolCallId:t.toolCallId}:{},...t.runId!==void 0?{runId:t.runId}:{},toolName:t.toolName,filePath:t.filePath??void 0,activationId:t.activationId,principleId:t.principleId,ruleId:t.ruleId,reason:t.reason,decision:"block",logger:n})}catch(r){n.warn?.(`[PD_GATE] Evidence recording threw (shared deny accounting continues): ${String(r)}`)}nke(e,{filePath:t.filePath,reason:t.reason,toolName:t.toolName,sessionId:t.sessionId,blockSource:"rule-host-shared",ruleId:t.ruleId,principleId:t.principleId},n)}import*as so from"fs";import*as Cv from"path";import*as uke from"readline";async function kwt(e,t){if(!t.workspaceDir||!e.messages||e.messages.length===0)return;let n=ft.fromHookContext(t),r=e.messages.filter(i=>{let o=i;return o.role==="assistant"&&typeof o.content=="string"&&(o.content.includes("error")||o.content.includes("fail")||o.content.includes("blocked"))});if(r.length>0){let i=n.resolve("MEMORY_MD"),o=`
|
|
2716
2716
|
## [${new Date().toISOString()}] Session Reset Summary (Reason: ${e.reason??"Manual"})
|
|
2717
2717
|
- Encountered ${r.length} potential pain point(s) during this session.
|
|
2718
2718
|
- Action: These are informational notes only; Runtime V2 hooks capture pain evidence automatically. Review via pd-console (\`pd console open\`) if you want them turned into principle candidates.
|
|
@@ -3160,7 +3160,7 @@ Reason: ${o}`}):{text:a?`\u672A\u627E\u5230\u539F\u5219: ${r}`:`Principle not fo
|
|
|
3160
3160
|
${a.join(`
|
|
3161
3161
|
`)}`:`Pending correction samples:
|
|
3162
3162
|
${a.join(`
|
|
3163
|
-
`)}`}}var dzn=new Set(["add","update","remove"]),See=class e{stateDir;workspaceDir;logger;constructor(t,n,r){this.stateDir=t,this.workspaceDir=n,this.logger=r}applyResult(t){let n=bv.get(this.stateDir),r=t.updates??{};if(t.updated&&Object.keys(r).length>0)for(let[i,o]of Object.entries(r)){let a=i.trim().toLowerCase();if(a===""||dzn.has(a)){this.skip(i,o.action,`"${i}" is not a term (blank or action word)`);continue}let s=n.find(a);if(o.action!=="add"&&!s){this.skip(i,o.action,"not in store");continue}if(o.action==="remove"&&s!==void 0){if(s.source!=="llm"){this.skip(i,o.action,`${s.source} term is Owner-authored, not machine-removable`);continue}let c=s.truePositiveCount??0;if(c>0){this.skip(i,o.action,`term has ${c} confirmed correction(s); recent-window silence is not counter-evidence`);continue}}try{switch(o.action){case"add":{if(s){this.audit("ADD_SKIPPED",`"${a}" already exists as "${s.term}"`);break}if(a.includes(",")){this.skip(i,"add","joined cue of several terms, not one learnable term");break}let c=o.weight!==void 0?Math.max(.1,Math.min(.9,o.weight)):.5,u=n.add({term:a,weight:c,source:"llm"}),l=u.length>0?` evicted=[${u.map(p=>`"${p}"`).join(", ")}] (store at cap)`:"";this.audit("ADD",`term="${a}" weight=${c}${l}`);break}case"update":{if(o.weight===void 0)break;if(!n.updateWeight(a,o.weight)){this.skip(i,"update","not in store");break}this.audit("UPDATE",`term="${a}" weight=${o.weight}`);break}case"remove":{if(!n.remove(a)){this.skip(i,"remove","not in store");break}this.audit("REMOVE",`term="${a}"`);break}}}catch(c){this.logger?.warn?.(`[KeywordOptimizationService] ${o.action.toUpperCase()} failed for term="${a}": ${String(c)}`)}}else this.logger?.info?.("[KeywordOptimizationService] No store mutations to apply");if(t.fpAnalysisStatus==="completed"&&t.fpTerms&&t.fpTerms.length>0){let o=[...new Set(t.fpTerms.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0))].slice(0,20);for(let a of o)try{n.recordFalsePositive(a)?this.audit("FP_RECORDED",`term="${a}" (weight x0.8)`):this.skip(a,"fp","not in store")}catch(s){this.logger?.warn?.(`[KeywordOptimizationService] recordFalsePositive failed for term="${a}": ${String(s)}`)}}}audit(t,n){this.logger?.info?.(`[KeywordOptimizationService] ${t} ${n}`),ze.log(this.workspaceDir,"KEYWORD_LEARNING",`${t} ${n}`)}skip(t,n,r){this.logger?.warn?.(`[KeywordOptimizationService] ${n.toUpperCase()} skipped for term="${t}": ${r}`)}async buildTrajectoryHistory(t){let n=[],r=pc.get(this.workspaceDir);for(let i of t.slice(0,10)){try{let o=r.listUserTurnsForSession(i);for(let a of o){if(a.correctionDetected){let s=(a.correctionCue??"").trim(),u=s.startsWith("llm:")?[""]:s.split(",").map(l=>l.trim()).filter(l=>l!=="");for(let l of u.length>0?u:[""])if(n.push({sessionId:i,timestamp:a.createdAt??new Date().toISOString(),term:l,userMessage:a.rawExcerpt??""}),n.length>=50)break}if(n.length>=50)break}}catch(o){this.logger?.warn?.(`[KeywordOptimizationService] Failed to read trajectory for session ${i}: ${String(o)}`)}if(n.length>=50)break}return n}static _instances=new Map;static get(t,n,r){let i=`${t}::${n}`;return e._instances.has(i)||e._instances.set(i,new e(t,n,r)),e._instances.get(i)}static reset(){e._instances.clear()}};var Ky=null,gke=!1,Ake=!1,Cee=0,yke=new Set,pzn=900*1e3,fzn=1e4,mzn=20,hzn=10,sbt=40,cbt=400,gzn=20,Azn=5;async function yzn(e,t,n){let r=e.trajectory;if(!r?.listPendingSignalConfirmations)return 0;let i=r.listPendingSignalConfirmations(gzn);if(i.length===0)return 0;let o=mee(e,t);if(!o)return gf(e.stateDir,u=>{u.stage2BatchSkipped+=1}),t?.debug?.("[PD:CorrectionObserver] batch confirm skipped: signal classifier unavailable"),0;let a=_ee(e,t),s=0,c=(u,l)=>{let p=r.bumpSignalConfirmationAttempt(u);p>=Azn&&(r.markSignalConfirmationResult(u,"abandoned",`attempts exhausted (${p}): ${l}`),s++,ze.log(e.workspaceDir,"SIGNAL_CONFIRMATION_ABANDONED",`${u} after ${p} attempts`))};for(let u of i){if(n?.())break;try{let l=await a.confirmPendingSignal({sessionId:u.sessionId,userTurnRowid:u.userTurnRowid,occurrenceId:u.occurrenceId,excerpt:u.excerpt,terms:u.terms,termsVerified:u.termsVerified},o);if(l.disposition==="failed"){c(u.id,l.detail);continue}r.markSignalConfirmationResult(u.id,l.disposition,l.detail),s++,l.disposition==="confirmed"&&gf(e.stateDir,p=>{p.stage2Confirmed+=1,p.lastStage2SuccessAt=new Date().toISOString()}),ze.log(e.workspaceDir,"SIGNAL_CONFIRMATION_RESOLVED",`${u.id} -> ${l.disposition} (${l.detail.slice(0,80)})`)}catch(l){t?.warn?.(`[PD:CorrectionObserver] confirm failed for ${u.id}: ${String(l)}`),c(u.id,`threw: ${String(l)}`)}}return s}function _zn(e,t){try{let n=EL(e.workspaceDir,"correction_observer","correctionObserver",t);if(!n.enabled)return n.readiness==="config_malformed"?t?.warn?.(`[PD:CorrectionObserver] Config malformed: ${n.reason}. ${n.nextAction}`):t?.debug?.(`[PD:CorrectionObserver] ${n.reason}`),null;if(n.readiness==="needs_setup")return t?.info?.(`[PD:CorrectionObserver] ${n.reason}. ${n.nextAction}`),null;if(n.runtimeProfileType!=="pi-ai")return t?.warn?.(`[PD:CorrectionObserver] Runtime profile type '${String(n.runtimeProfileType)}' is not supported (ADR-0029: pi-ai only). Skipping.`),null;let r=new Dl({provider:n.provider??"anthropic",model:n.model??"anthropic/claude-3-5-sonnet",apiKeyEnv:n.apiKeyEnv??"ANTHROPIC_API_KEY",timeoutMs:n.timeoutMs??void 0,maxTokens:n.maxTokens??void 0,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return new $Q({runtimeAdapter:r},{timeoutMs:n.timeoutMs??void 0})}catch(n){return t?.warn?.(`[PD:CorrectionObserver] Failed to resolve CorrectionObserver: ${String(n)}`),null}}function kee(e,t){gf(e.stateDir,n=>{t?(n.observerLastSuccessAt=new Date().toISOString(),n.observerConsecutiveFailures=0):n.observerConsecutiveFailures+=1})}async function Izn(e,t,n){try{let r=await yzn(e,t,n);if(r>0&&t?.info?.(`[PD:CorrectionObserver] batch-confirmed ${r} pending signals`),n?.())return;gf(e.stateDir,w=>{w.pendingCount=e.trajectory?.countPendingSignalConfirmations?.()??w.pendingCount});let i=_zn(e,t);if(!i){t?.debug?.("[PD:CorrectionObserver] Observer not resolved. Skipping cycle."),kee(e,!0);return}t?.info?.("[PD:CorrectionObserver] Observer resolved. Initiating periodic optimization...");let o=pc.get(e.workspaceDir),a=o.listRecentSessions({limit:mzn}),s=a.map(w=>w.sessionId);if(s.length===0){t?.info?.("[PD:CorrectionObserver] No recent sessions found. Skipping correction optimization.");return}let c=Kxt(e.stateDir),u=a[0]?.updatedAt??null;if(r===0&&c?.observerLastSuccessAt&&u&&u<=c.observerLastSuccessAt){t?.debug?.(`[PD:CorrectionObserver] No new turns since ${c.observerLastSuccessAt}. Skipping optimization cycle.`),kee(e,!0);return}let l=[];for(let w of s.slice(0,hzn))try{let b=o.listUserTurnsForSession(w);for(let k of b)k.rawExcerpt&&l.push(k.rawExcerpt.length>cbt?`${k.rawExcerpt.slice(0,cbt)}\u2026`:k.rawExcerpt)}catch(b){t?.warn?.(`[PD:CorrectionObserver] Failed to load user turns for session ${w}: ${String(b)}`)}l.length>sbt&&l.splice(0,l.length-sbt);let f=bv.get(e.stateDir).getStore().keywords,m={totalKeywords:f.length,terms:f.map(w=>({term:w.term,weight:w.weight,truePositiveCount:w.truePositiveCount??0,falsePositiveCount:w.falsePositiveCount??0}))},g=See.get(e.stateDir,e.workspaceDir,t),h=await g.buildTrajectoryHistory(s),y={parentSessionId:"correction-observer-service",workspaceDir:e.workspaceDir,keywordStoreSummary:m,recentMessages:l,trajectoryHistory:h},_=new BW;_.register({agentId:"correction-observer",mode:"realtime",runner:i}),t?.info?.(`[PD:CorrectionObserver] Dispatching with ${h.length} trajectory events, ${l.length} recent messages.`);let v=await _.dispatch("correction-observer",y);if(t?.info?.(`[PD:CorrectionObserver] Completed: updated=${v.updated}, summary="${v.summary}"`),n?.())return;g.applyResult(v),kee(e,!0)}catch(r){let i=`Correction observer cycle failed: ${String(r)}`;t?.warn?.(`[PD:CorrectionObserver] ${i}`),ze.log(e.workspaceDir,"CORRECTION_OBSERVER_CYCLE_FAILED",i),n?.()||kee(e,!1)}}var _ke={id:"principles-correction-observer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n&&n.warn("[PD:CorrectionObserver] workspaceDir not found in service config. Correction observer disabled.");return}if(yke.has(t)){n&&n.info(`[PD:CorrectionObserver] Already started for workspace: ${t}. Skipping duplicate start.`);return}let r=EL(t,"correction_observer","correctionObserver",n),o=EL(t,"signal_collector","signalCollector",n).enabled;if(!r.enabled&&!o){n?.info?.(`[PD:CorrectionObserver] correction_observer disabled and signal_collector disabled \u2014 periodic cycle (batch confirmation + optimization) not started. ${r.nextAction}`);return}if(r.enabled&&r.readiness==="needs_setup"&&!o){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}r.enabled&&r.readiness!=="needs_setup"||n?.info?.(`[PD:CorrectionObserver] confirmation-consumer-only mode: batch-confirming persisted signal_confirmations every cycle; keyword optimization observer is ${r.enabled?"needs_setup":"disabled"}. ${r.nextAction}`),yke.add(t),gke=!1,Cee+=1;let s=Cee,c=ft.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:CorrectionObserver] Starting with workspaceDir=${c.workspaceDir}, stateDir=${c.stateDir}`);let u=pzn,l=()=>gke||s!==Cee;async function p(){if(!l()&&!Ake){Ake=!0;try{await Izn(c,n,l)}finally{Ake=!1}l()||(Ky=setTimeout(p,u),Ky.unref())}}Ky=setTimeout(()=>{p().catch(f=>{n&&n.error(`[PD:CorrectionObserver] Startup cycle failed: ${String(f)}`),!l()&&(Ky=setTimeout(p,u),Ky.unref())})},fzn),Ky.unref()},stop(e){gke=!0,Cee+=1,yke.clear(),Ky&&clearTimeout(Ky),Ky=null}};var Ree=class extends c${constructor(t){super({source:pc.get(t.workspaceDir),toolSemantics:Km})}};import vzn from"node:path";var Ezn=12e4,Ike=3e4,GL=new Map;function xzn(e){let t=GL.get(e);return t||(t={stopped:!1,timeoutId:null},GL.set(e,t)),t}function wzn(e){return`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`}function vke(e,t){try{let n=BSe(e,{version:1,hostKind:"openclaw",mappings:ske,declaredAt:new Date().toISOString()});n.ok||t.warn(`[PD:AutoConsumer] Failed to persist OpenClaw tool declaration: ${n.reason} \u2014 pd-cli reliability validation will not find it (rc-9)`)}catch(n){let r=n instanceof Error?n.message:String(n);t.warn(`[PD:AutoConsumer] Failed to persist OpenClaw tool declaration: ${r} \u2014 pd-cli reliability validation will not find it (rc-9)`)}}async function bzn(e,t){await GIt(e,{owner:"auto-consumer",logLabel:"AutoConsumer",logger:t,emitEvent:(n,r)=>ze.log(e,n,r),hostToolCatalog:{readOnlyTools:Iee,writeTools:[...Sv,...rke,...HL]},toolSemantics:Km,hostKinds:["openclaw"],behaviorEvidence:{assemble:n=>new Ree({workspaceDir:e,stateDir:vzn.join(e,".state")}).assemble({sourcePainId:n.sourcePainId,ownerDesiredOutcome:n.ownerDesiredOutcome,sourceNegativeToolCallId:n.sourceNegativeToolCallId,positiveToolCallIds:n.positiveToolCallIds,projectDir:e})}})}var Eke={id:"principles-internalization-auto-consumer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n.warn("[PD:AutoConsumer] No workspace directory, not starting.");return}let r=t,i=xzn(r);if(vke(r,n),!i.stopped&&i.timeoutId!==null){n.info(`[PD:AutoConsumer] Already started for workspace: ${r}`);return}let o=jr(r,USe,{info:u=>n.info(u),warn:u=>n.warn(u)});if(!o.enabled){let u=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:wzn(r),flagSource:o.source});ze.log(r,"INTERNALIZATION_CONSUMER_DISABLED",u),n.info(`[PD:AutoConsumer] NOT started for workspace: ${r}. Disabled (source: ${o.source}).`);return}i.stopped=!1;let a=Ezn;function s(){i.stopped||(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())}async function c(){if(!i.stopped){try{await bzn(r,n)}catch(u){let l=`Internalization consumer cycle failed: ${u instanceof Error?u.message:String(u)}`;n.error(`[PD:AutoConsumer] ${l}`),ze.log(r,"INTERNALIZATION_CONSUMER_CYCLE_FAILED",l)}s()}}i.timeoutId=setTimeout(()=>{c().catch(u=>{n.error(`[PD:AutoConsumer] Startup cycle failed: ${String(u)}`),!i.stopped&&(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())})},Ike),i.timeoutId?.unref(),ze.log(r,"INTERNALIZATION_CONSUMER_STARTED",JSON.stringify({intervalMs:a,initialDelayMs:Ike})),n.info(`[PD:AutoConsumer] Started for workspace: ${r} (interval: ${a}ms, initial delay: ${Ike}ms)`)},stop(e){let t=e?.workspaceDir;if(t){let n=GL.get(t);n&&(n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null),GL.delete(t)}else{for(let[,n]of GL)n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null;GL.clear()}}};var ubt={id:"principles-disciple-trajectory",start(e){e.workspaceDir&&ft.fromHookContext(e).trajectory},stop(e){e.workspaceDir&&pc.dispose(e.workspaceDir)}};import*as Oee from"fs";import*as gbt from"path";import*as Abt from"os";var lbt=[];import*as RS from"fs";import*as xke from"path";var dbt="pd_tasks.json";function pbt(e){return xke.join(e,".state",dbt)}function Szn(e){let t=xke.join(e,".state");RS.existsSync(t)||RS.mkdirSync(t,{recursive:!0})}function fbt(e){let t=pbt(e);if(!RS.existsSync(t))return[];try{let n=RS.readFileSync(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch(n){return console.warn(`[PD:TaskStore] Failed to parse ${dbt}: ${String(n)}`),[]}}async function mbt(e,t){let n=pbt(e);Szn(e),await EZ(n,async()=>{Ut(n,JSON.stringify(t,null,2))})}var Tee=gbt.join(Abt.homedir(),".openclaw","cron","jobs.json");function Czn(e){if(!Oee.existsSync(Tee))return e?.info?.("[PD:Reconciler] cron/jobs.json not found, starting with empty store"),{version:1,jobs:[]};try{let t=Oee.readFileSync(Tee,"utf-8"),n=JSON.parse(t);return e?.info?.(`[PD:Reconciler] Loaded cron/jobs.json: ${n.jobs.length} jobs`),n}catch(t){return e?.warn?.(`[PD:Reconciler] Failed to parse cron/jobs.json: ${String(t)}`),{version:1,jobs:[]}}}async function kzn(e){await EZ(Tee,async()=>{Ut(Tee,JSON.stringify(e,null,2))})}function Rzn(e,t){let n=[],r=new Map;for(let i of t)r.set(i.name,i);for(let i of e){let o=r.get(i.name);if(!o)i.enabled&&n.push({type:"CREATE",task:i});else{let a=o.metadata?.pdVersion;i.enabled?!a||a!==i.version?n.push({type:"UPDATE",task:i,job:o}):n.push({type:"SKIP",task:i,job:o}):n.push({type:"DISABLE",task:i,job:o})}}for(let i of t){if(!i.name.startsWith("PD "))continue;e.find(a=>a.name===i.name)||n.push({type:"ORPHAN",job:i})}return n}function hbt(e,t,n,r){return r?.info?.(`[PD:Reconciler] Building cron job: ${e.name} (id=${e.id}, interval=${e.schedule.everyMs}ms)`),{id:`pd-${e.id}-${t}`,name:e.name,agentId:e.agentId||"main",description:e.description,enabled:e.enabled,schedule:{kind:"every",everyMs:e.schedule.everyMs},sessionTarget:"isolated",wakeMode:"now",payload:{kind:"agentTurn",message:Tzn(e,n,r),lightContext:e.execution.lightContext??!0,timeoutSeconds:e.execution.timeoutSeconds??120,toolsAllow:e.execution.toolsAllow},delivery:{mode:e.delivery.mode},createdAtMs:t,updatedAtMs:t,state:{nextRunAtMs:t+e.schedule.everyMs},metadata:{pdVersion:e.version,pdTaskId:e.id}}}function Tzn(e,t,n){return e.description}async function ybt(e,t){let n=t?.dryRun??!1,r=t?.logger??console,i=Date.now(),o={created:[],updated:[],skipped:[],orphaned:[],errors:[]},a=fbt(e),s=new Map(a.map(f=>[f.id,f])),c=lbt.map(f=>{let m=s.get(f.id);return m?{...f,meta:{...f.meta,...m.meta}}:{...f,meta:{createdAtMs:i}}}),u=await Czn(r),l=Ozn(c,u,r),p=Rzn(l,u.jobs);for(let f of p)switch(f.type){case"CREATE":if(f.task){if(!n){let m=hbt(f.task,i,e,r);u.jobs.push(m),r.info?.(`[PD:Reconciler] Created job: ${f.task.name}`)}o.created.push(f.task.name)}break;case"UPDATE":if(f.task&&f.job){if(!n){let m=u.jobs.indexOf(f.job),g=hbt(f.task,i,e,r);g.id=f.job.id,g.state={...f.job.state,nextRunAtMs:void 0},u.jobs[m]=g,r.info?.(`[PD:Reconciler] Updated job: ${f.task.name}`)}o.updated.push(f.task.name)}break;case"DISABLE":if(f.job){if(!n){let m=u.jobs.indexOf(f.job);m>=0&&(u.jobs[m]={...f.job,enabled:!1,updatedAtMs:i})}r.warn?.(`[PD:Reconciler] Disabled job: ${f.job.name}`)}break;case"ORPHAN":f.job&&(r.warn?.(`[PD:Reconciler] Orphaned job (no declaration): ${f.job.name}`),o.orphaned.push(f.job.name));break;case"SKIP":f.task&&o.skipped.push(f.task.name);break}if(!n&&(o.created.length>0||o.updated.length>0)){await kzn(u),r.info?.(`[PD:Reconciler] Wrote cron/jobs.json: ${u.jobs.length} total jobs`);for(let f of u.jobs)f.name.startsWith("PD ")&&r.info?.(`[PD:Reconciler] PD job: name=${f.name}, enabled=${f.enabled}, schedule=${JSON.stringify(f.schedule)}, nextRun=${f.state.nextRunAtMs?new Date(f.state.nextRunAtMs).toISOString():"TBD"}`)}return!n&&c.length>0&&await mbt(e,c),o}function Ozn(e,t,n){let r=new Map(t.jobs.map(i=>[i.name,i]));return e.map(i=>{let o=r.get(i.name);if(!o)return i;let a=o.state.consecutiveErrors??0,s=o.state.lastError??"",c=s.includes("timed out")||s.includes("timeout");if(c&&a>0&&o.payload.kind==="agentTurn"){let l=o.payload.timeoutSeconds??120,p=Math.min(1800,l*2);p>l&&(o.payload.timeoutSeconds=p,o.state.consecutiveErrors=0,o.state.lastError=void 0,n.info?.(`[PD:Reconciler] Auto-increased timeout for '${i.name}': ${l}s \u2192 ${p}s (was ${a} consecutive timeouts)`))}let u=a>=3&&!c&&!i.meta?.autoDisabled;return a===0&&i.meta?.autoDisabled&&n.info?.(`[PD:Reconciler] Task '${i.id}' was previously auto-disabled but has 0 consecutive errors now`),u||i.meta||o.state.lastRunAtMs?{...i,meta:{...i.meta,...u?{autoDisabled:!0,autoDisabledAt:Date.now(),autoDisabledReason:`consecutiveErrors=${a}`}:{},...i.meta?{consecutiveFailCount:a}:{},...o.state.lastRunAtMs?{lastFailedAtMs:o.state.lastRunAtMs}:{}}}:i})}var _bt={id:"principles-disciple-task-manager",async start(e){let{workspaceDir:t}=e,n=e.logger??e.api?.logger;if(!t){n?.warn?.("[PD:TaskManager] No workspaceDir, skipping PD task reconciliation");return}n?.info?.("[PD:TaskManager] Starting PD task reconciliation...");try{let r=await ybt(t,{logger:n??console});n?.info?.(`[PD:TaskManager] Reconcile complete: +${r.created.length} ~${r.updated.length} =${r.skipped.length} orphan=${r.orphaned.length}`),r.created.length>0&&n?.info?.(`[PD:TaskManager] Created jobs: ${r.created.join(", ")}`),r.updated.length>0&&n?.info?.(`[PD:TaskManager] Updated jobs: ${r.updated.join(", ")}`),r.errors.length>0&&n?.warn?.(`[PD:TaskManager] Reconcile errors: ${r.errors.map(i=>i.message).join(", ")}`)}catch(r){n?.warn?.(`[PD:TaskManager] Reconcile failed: ${String(r)}`)}},stop(e){}};import*as Ti from"fs";import*as fc from"path";import{fileURLToPath as Dzn}from"url";var Pzn={name:"Principles Disciple Agent",version:"1.0.0"},Lzn="pd-core-guidance-v2",Ibt=new Set(["AGENTS.md","TOOLS.md"]);function Nzn(){return`pd-core-guidance-version: ${Lzn}`}function Mzn(e,t){return!Ibt.has(e)||t.includes(Nzn())?!1:!!(t.includes("pd_spawn_agent")||!t.includes("subagents")||!t.includes("sessions_spawn"))}function vbt(e,t,n="en"){try{let r=Dzn(import.meta.url),i=fc.dirname(r),o=fc.resolve(i,"..","..","templates","workspace");Ti.existsSync(o)&&(e.logger.info(`[PD] Syncing workspace templates: ${t}...`),wke(o,t,e));let a=fc.resolve(i,"..","..","templates","langs",n,"core");if(Ti.existsSync(a)||(a=fc.resolve(i,"..","..","templates","langs","zh","core")),Ti.existsSync(a)){e.logger.info(`[PD] Flattening ${n} core templates to workspace root...`);let p=Ti.readdirSync(a);for(let f of p){let m=fc.join(a,f),g=fc.join(t,f);if(!Ti.existsSync(g))Ti.copyFileSync(m,g),e.logger.info(`[PD] Initialized core file: ${f}`);else if(Ibt.has(f)){let h=Ti.readFileSync(g,"utf8");Mzn(f,h)&&e.logger.warn(`[PD] Outdated core guidance detected in ${f}. Review the latest template guidance for peer sessions, subagents, and sessions_spawn routing.`)}}}let s=fc.resolve(i,"..","..","templates","langs",n,"pain"),c=fc.join(t,fr.PAIN_SAMPLES);Ti.existsSync(s)&&(Ti.existsSync(c)||Ti.mkdirSync(c,{recursive:!0}),wke(s,c,e));let u=fc.join(t,fr.IDENTITY),l=fc.join(u,"PROFILE.json");Ti.existsSync(l)||(Ti.existsSync(u)||Ti.mkdirSync(u,{recursive:!0}),Ut(l,JSON.stringify(Pzn,null,2)),e.logger.info("[PD] Initialized PROFILE.json with identity metadata (contextInjection migrated to .pd/config.yaml)"))}catch(r){e.logger.error(`[PD] Failed to initialize workspace templates: ${String(r)}`)}}function wke(e,t,n){let r=Ti.readdirSync(e);for(let i of r){let o=fc.join(e,i),a=i==="okr"?fc.join("memory","okr"):i,s=fc.join(t,a);if(Ti.statSync(o).isDirectory())Ti.existsSync(s)||Ti.mkdirSync(s,{recursive:!0}),wke(o,s,n);else if(!Ti.existsSync(s)){let u=fc.dirname(s);Ti.existsSync(u)||Ti.mkdirSync(u,{recursive:!0}),Ti.copyFileSync(o,s),n.logger.info(`[PD] Copied: ${a}`)}}}var Kbo=uh.map(e=>({id:e.id,name:e.name,description:e.statement}));import*as mc from"fs";import*as $a from"path";function Ebt(e,t){try{let n=$a.join(t,"docs"),r=$a.join(t,"memory",".state"),i=[{legacy:$a.join(n,"PRINCIPLES.md"),newKey:"PRINCIPLES"},{legacy:$a.join(n,"THINKING_OS.md"),newKey:"THINKING_OS"},{legacy:$a.join(n,"DECISION_POLICY.json"),newKey:"DECISION_POLICY"},{legacy:$a.join(n,".pain_flag"),newKey:"PAIN_FLAG"},{legacy:$a.join(n,"SYSTEM_CAPABILITIES.json"),newKey:"SYSTEM_CAPABILITIES"},{legacy:$a.join(n,"SYSTEM.log"),newKey:"SYSTEM_LOG"},{legacy:$a.join(r,"pain_dictionary.json"),newKey:"DICTIONARY"},{legacy:$a.join(r,"pain_settings.json"),newKey:"PAIN_SETTINGS"},{legacy:$a.join(r,"pain_candidates.json"),newKey:"PAIN_CANDIDATES"},{legacy:$a.join(r,"sessions"),newKey:"SESSION_DIR"},{legacy:$a.join(r,"logs","events.jsonl"),newKey:"SYSTEM_LOG"}],o=0;for(let a of i)if(mc.existsSync(a.legacy)){let s=is(t,a.newKey),c=$a.dirname(s);if(mc.existsSync(c)||mc.mkdirSync(c,{recursive:!0}),mc.existsSync(s))e.logger?.warn?.(`[PD:Migration] Skipping ${$a.basename(a.legacy)}: already exists at destination.`);else try{mc.renameSync(a.legacy,s),e.logger.info(`[PD:Migration] Migrated ${$a.basename(a.legacy)} to ${s.replace(t,"")}`),o++}catch(u){e.logger.error(`[PD:Migration] Failed to rename ${a.legacy}: ${String(u)}`)}}if(o>0&&e.logger.info(`[PD:Migration] Successfully migrated ${o} files/folders to new architecture.`),mc.existsSync(r))try{let a=mc.readdirSync(r);if(a.length===0||a.length===1&&a[0]==="logs"){let s=$a.join(r,"logs");mc.existsSync(s)&&mc.readdirSync(s).length===0&&mc.rmdirSync(s),mc.readdirSync(r).length===0&&(mc.rmdirSync(r),e.logger.info("[PD:Migration] Cleaned up empty legacy state directory."))}}catch(a){e.logger.debug?.(`[PD:Migration] Failed to cleanup legacy state dir: ${String(a)}`)}}catch(n){e.logger.error(`[PD:Migration] Directory refactor migration failed: ${String(n)}`)}}function Bzn(e,t,n){return{workspaceDir:e,sessionId:t??"openclaw:session-unavailable",toolName:n}}function Fzn(e){let t={};return typeof e.modelProviderId=="string"&&e.modelProviderId.length>0&&(t.modelProviderId=e.modelProviderId),typeof e.modelId=="string"&&e.modelId.length>0&&(t.modelId=e.modelId),e.contextTokenBudget!==void 0&&(t.contextTokenBudget=e.contextTokenBudget),e.contextWindowSource!==void 0&&(t.contextWindowSource=e.contextWindowSource),Object.keys(t).length>0?t:void 0}function xbt(e){let t=new WeakMap,n=new WeakMap;function r(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error(`OpenClaw ${s.kind} dispatch is missing its native payload token`);let c=Object.hasOwn(s.rawPayload,"nativeToken")?Reflect.get(s.rawPayload,"nativeToken"):s.rawPayload;if(typeof c!="object"||c===null)throw new Error(`OpenClaw ${s.kind} dispatch has an invalid native payload token`);let u=t.get(c);if(!u||u.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} dispatch has a mismatched native payload`);return u}function i(s,c,u,l){let p={decision:u,source:s.source,...l?{reason:l}:{}};return n.set(p,c),p}let o=Pvt({toolSemantics:Km,...e.roundKeyProvider?{roundKeyProvider(s){let c=r(s);if(c.kind==="before_prompt_build")return e.roundKeyProvider?.(c.event,c.context)}}:{},adaptivePriorityProvider(s){let c=r(s);if(c.kind==="before_prompt_build")return e.adaptivePriorityProvider?.(c.event,c.context)},ruleContextProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule context request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule context request has an invalid native token");let u=t.get(c);if(!u||u.kind!=="before_tool_call")throw new Error("OpenClaw rule context request has a mismatched native payload");return e.ruleContextProvider?.(u.event,u.context,s)},ruleInputEnrichmentProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule enrichment request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule enrichment request has an invalid native token");let u=t.get(c);if(!u||u.kind!=="before_tool_call")throw new Error("OpenClaw rule enrichment request has a mismatched native payload");return e.ruleInputEnrichmentProvider?.(u.event,u.context,s)},async beforePromptBuild(s,c){let u=r(s);if(u.kind!=="before_prompt_build")throw new Error("OpenClaw prompt payload mismatch");let l=await e.beforePromptBuild(u.event,u.context,c);return i(s,{kind:u.kind,value:l},l?"modify":"allow")},painEnrichmentProvider(s){let c=r(s);if(c.kind!=="after_tool_call")throw new Error("OpenClaw pain payload mismatch");return e.painEnrichmentProvider?.(c.event,c.context)},hostKind:"openclaw"});async function a(s,c,u){let l={};t.set(l,s);let p=Fzn(s.context),f=s.kind==="after_tool_call"?s.event:void 0,m=f!==void 0?f.params:void 0,g=w=>typeof w=="object"&&w!==null&&!Array.isArray(w),h=g(m)?m:g(f?.toolArgs)?f.toolArgs:{},y={kind:s.kind,context:{...Bzn(c,u,s.kind==="before_prompt_build"?void 0:s.event.toolName),...f!==void 0?{toolInput:h,toolOutput:{error:f.error,result:f.result,durationMs:f.durationMs}}:{},...p!==void 0?{modelContext:p}:{}},rawPayload:s.kind==="before_tool_call"?{nativeToken:l,toolInput:{toolName:s.event.toolName,params:s.event.params??{}}}:{nativeToken:l},source:`openclaw:${s.kind}`},_=await o.dispatch(y),v=n.get(_);if(s.kind==="before_tool_call"&&!v){let w=e.onBeforeToolResult?.(s.event,s.context,_);return{kind:s.kind,value:_.decision==="deny"?{block:!0,blockReason:_.reason}:w}}if(s.kind==="after_tool_call"&&!v){let w=_.metadata,b=typeof w?.outcome=="string"?w.outcome:void 0,k=typeof w?.nextAction=="string"?w.nextAction:void 0;return{kind:s.kind,value:void 0,hostResult:{warnings:_.warnings??[],...b!==void 0?{outcome:b}:{},...k!==void 0?{nextAction:k}:{}}}}if(!v||v.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} result mapping is missing`);return v}return{runtime:o,async dispatchBeforePromptBuild(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_prompt_build requires workspaceDir");let u=await a({kind:"before_prompt_build",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="before_prompt_build")throw new Error("OpenClaw prompt result mismatch");return u.value},async dispatchBeforeToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_tool_call requires workspaceDir");let u=await a({kind:"before_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="before_tool_call")throw new Error("OpenClaw gate result mismatch");return u.value},async dispatchAfterToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw after_tool_call requires workspaceDir");let u=await a({kind:"after_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="after_tool_call")throw new Error("OpenClaw after_tool_call result mismatch");return u.hostResult??{warnings:[]}}}}var wbt=new Set;try{wZ()}catch{}function qSo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sbt(e,t,n){return jr(e,t,n)}function Qzn(e,t){let n=Sbt(e,"correction_observer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"correction_observer_disabled",nextAction:"set features.correction_observer.enabled=true in .pd/config.yaml to enable",featureFlag:"correction_observer",boundedContext:"correction_observer_service",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function Wzn(e,t){let n=Sbt(e,"internalization_auto_consumer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`,featureFlag:"internalization_auto_consumer",boundedContext:"internalization_auto_consumer",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function $zn(e){let t=e.resolver?e.resolver():Dxt(),n=t!==null&&Ul(t.workspaceDir)===null;if(t!==null&&n){let o=Fvt(t.workspaceDir,e.extensionRoot,e.homeDir);if(o.ok)return{status:o.written?"written":"unchanged",reason:`pd_workspace_explicit:${t.source}`,nextAction:o.written?"Restart the OpenClaw gateway so the pd-recall MCP server reads the new binding.":"No change: the binding already matches the declared PD workspace.",workspaceDir:t.workspaceDir,source:t.source};let a=o.reason==="mcp_server_component_missing";return{status:"unavailable",reason:o.reason??"mcp_binding_write_failed",nextAction:a?"Re-run the PD host setup so ~/.pd/runtime/pd-mcp-server is installed, then restart OpenClaw. pd-recall stays fail-closed until the binding exists.":`PD FAILED to write the binding for the declared workspace, so the previous mcp-binding.json (a DIFFERENT workspace) may still be on disk. The launcher refuses to start unless the binding matches the explicit declaration, so no other workspace is served \u2014 but fix the failure (check write access to ${e.extensionRoot}) and restart the OpenClaw gateway.`,workspaceDir:t.workspaceDir,source:t.source}}let r=Bvt(e.extensionRoot),i=t===null?"pd_workspace_not_explicit":"pd_workspace_declaration_invalid";return{status:r.ok?"invalidated":"unavailable",reason:r.ok?i:r.reason??"mcp_binding_remove_failed",nextAction:r.ok?'pd-recall MCP is fail-closed because the PD governance workspace is not explicitly configured; hooks keep their per-agent workspaces. Declare ONE PD workspace (set PD_WORKSPACE_DIR, or add {"workspace":"<absolute dir>"} to ~/.openclaw/principles-disciple.json), then restart the OpenClaw gateway.':`PD FAILED to remove the stale mcp-binding.json, so the old binding file is still on disk (the launcher separately refuses to start unless the binding matches the explicitly declared workspace). Delete ${Dee.join(e.extensionRoot,"mcp-binding.json")} manually, then declare ONE PD workspace and restart the OpenClaw gateway.`}}async function Hzn(e,t,n){let r=Date.now();if(!n)return;let i=t.workspaceDir,o=t.sessionId,a=(h,y)=>{if(!(!h||typeof h!="object"))return Object.getOwnPropertyDescriptor(h,y)?.value},s=a(e,"currentUserMessage"),c=a(e,"currentUserMessageId"),u=a(e,"requestId");if(!i||!o?.trim()||!WL(t.trigger)||qW(t.trigger,o))return;let l=JZ(a(n,"pluginConfig"),i,r);if(!l)return;if(!(typeof c=="string"&&c.trim().length>0||typeof u=="string"&&u.trim().length>0)){if(DL(l)){n.logger.warn('[PD:AA] controlled admission refused: {"reason":"principle_mapping_has_no_admission_identity"}');return}if(!tee())return;let h=Math.min(r+l.softTimeoutMs,l.expiresAtMs);if(h-Date.now()<=0)return;let y=Uzn(),_=rxt({event:e,workspaceDir:i,sessionId:o,runId:t.runId??null,mapping:l,hookInvocationId:y,now:r});if(_.status!=="claimed"){n.logger.warn(`[PD:AA] controlled admission refused: ${JSON.stringify({status:_.status,..._.status==="rejected"?{reason:_.reason,detail:_.detail}:{}})}`);return}return k$({...t,api:n},l,"shared",y),{artifactId:l.artifactId,activationId:l.activationId,hookInvocationId:y,signal:AbortSignal.timeout(Math.max(1,h-Date.now())),deadlineAt:h}}if(typeof s!="string"||ES(e,o).isAgentToAgent||s.split(/\r?\n/,1)[0]!=="[PD-AA:delivery-review:v1]")return;let m=Math.min(r+l.softTimeoutMs,l.expiresAtMs),g=m-Date.now();if(!(g<=0)){if(DL(l)){let h=await yIt({workspaceDir:i,principleId:l.principleId});if(!h.ok){n.logger.warn(`[PD:AA] principle resolution refused: ${JSON.stringify({reason:h.reason,principleId:l.principleId,warnings:h.warnings.length,nextAction:"the mapping target is not uniquely currently authorized; ordinary Native assembly continues"})}`);return}let y=m-Date.now();if(y<=0){n.logger.warn(`[PD:AA] principle resolution refused: ${JSON.stringify({reason:"deadline",principleId:l.principleId,nextAction:"the soft deadline expired during resolution; ordinary Native assembly continues"})}`);return}let _=k$({...t,api:n},{artifactId:h.artifactId,activationId:h.activationId},"shared");return GEt(_,h),{artifactId:h.artifactId,activationId:h.activationId,additiveOnly:!0,hookInvocationId:_,signal:AbortSignal.timeout(y),deadlineAt:m}}return{artifactId:l.artifactId,activationId:l.activationId,hookInvocationId:k$({...t,api:n},l,"shared"),signal:AbortSignal.timeout(g),deadlineAt:m}}}var jzn={name:"Principles Disciple",description:"Evolutionary programming agent framework with strategic guardrails and reflection loops.",register(e){e.logger.info(`Principles Disciple Plugin registered. (Path: ${e.rootDir??"(unknown)"})`),Hd.setExtensionRoot(e.rootDir??"."),setTimeout(()=>{try{let l=Hd.getExtensionRoot()??process.cwd(),p=$zn({extensionRoot:l,homeDir:bbt.homedir()});p.status==="written"?e.logger.info(`[PD:health] mcp-binding.json updated for the pd-recall MCP server (${p.reason}; restart the gateway to apply)`):p.status==="invalidated"?e.logger.warn(`[PD:health] mcp-binding.json removed: pd-recall MCP stays fail-closed (${p.reason}). nextAction: ${p.nextAction}`):p.status==="unavailable"&&e.logger.warn(`[PD:health] mcp-binding unavailable (${p.reason}). nextAction: ${p.nextAction}`)}catch(l){e.logger.warn(`[PD:health] mcp-binding update failed: ${String(l instanceof Error?l.message:l)}`)}let c=xZ(e.config,e.id),u=d$(c);if(!u.authorized&&iCe(c))e.logger.info("[PD:health] conversation hooks (llm_output / trajectory) disabled by explicit configuration \u2014 honoring Owner opt-out (allowConversationAccess=false). nextAction: set the flag to true or remove it to re-enable conversation capture.");else if(u.authorized)e.logger.info("[PD:health] conversation hooks (allowConversationAccess) OK");else{let l=!1;try{l=wZ()}catch(p){e.logger.warn(`[PD:health] auto-fix for allowConversationAccess failed: ${String(p instanceof Error?p.message:p)}`)}l?e.logger.info("[PD:health] allowConversationAccess auto-configured. Restart the gateway to activate conversation hooks."):e.logger.error(`[PD:health] conversation hooks (llm_output / trajectory) will be BLOCKED by OpenClaw.
|
|
3163
|
+
`)}`}}var dzn=new Set(["add","update","remove"]),See=class e{stateDir;workspaceDir;logger;constructor(t,n,r){this.stateDir=t,this.workspaceDir=n,this.logger=r}applyResult(t){let n=bv.get(this.stateDir),r=t.updates??{};if(t.updated&&Object.keys(r).length>0)for(let[i,o]of Object.entries(r)){let a=i.trim().toLowerCase();if(a===""||dzn.has(a)){this.skip(i,o.action,`"${i}" is not a term (blank or action word)`);continue}let s=n.find(a);if(o.action!=="add"&&!s){this.skip(i,o.action,"not in store");continue}if(o.action==="remove"&&s!==void 0){if(s.source!=="llm"){this.skip(i,o.action,`${s.source} term is Owner-authored, not machine-removable`);continue}let c=s.truePositiveCount??0;if(c>0){this.skip(i,o.action,`term has ${c} confirmed correction(s); recent-window silence is not counter-evidence`);continue}}try{switch(o.action){case"add":{if(s){this.audit("ADD_SKIPPED",`"${a}" already exists as "${s.term}"`);break}if(a.includes(",")){this.skip(i,"add","joined cue of several terms, not one learnable term");break}let c=o.weight!==void 0?Math.max(.1,Math.min(.9,o.weight)):.5,u=n.add({term:a,weight:c,source:"llm"}),l=u.length>0?` evicted=[${u.map(p=>`"${p}"`).join(", ")}] (store at cap)`:"";this.audit("ADD",`term="${a}" weight=${c}${l}`);break}case"update":{if(o.weight===void 0)break;if(!n.updateWeight(a,o.weight)){this.skip(i,"update","not in store");break}this.audit("UPDATE",`term="${a}" weight=${o.weight}`);break}case"remove":{if(!n.remove(a)){this.skip(i,"remove","not in store");break}this.audit("REMOVE",`term="${a}"`);break}}}catch(c){this.logger?.warn?.(`[KeywordOptimizationService] ${o.action.toUpperCase()} failed for term="${a}": ${String(c)}`)}}else this.logger?.info?.("[KeywordOptimizationService] No store mutations to apply");if(t.fpAnalysisStatus==="completed"&&t.fpTerms&&t.fpTerms.length>0){let o=[...new Set(t.fpTerms.map(a=>a.trim().toLowerCase()).filter(a=>a.length>0))].slice(0,20);for(let a of o)try{n.recordFalsePositive(a)?this.audit("FP_RECORDED",`term="${a}" (weight x0.8)`):this.skip(a,"fp","not in store")}catch(s){this.logger?.warn?.(`[KeywordOptimizationService] recordFalsePositive failed for term="${a}": ${String(s)}`)}}}audit(t,n){this.logger?.info?.(`[KeywordOptimizationService] ${t} ${n}`),ze.log(this.workspaceDir,"KEYWORD_LEARNING",`${t} ${n}`)}skip(t,n,r){this.logger?.warn?.(`[KeywordOptimizationService] ${n.toUpperCase()} skipped for term="${t}": ${r}`)}async buildTrajectoryHistory(t){let n=[],r=pc.get(this.workspaceDir);for(let i of t.slice(0,10)){try{let o=r.listUserTurnsForSession(i);for(let a of o){if(a.correctionDetected){let s=(a.correctionCue??"").trim(),u=s.startsWith("llm:")?[""]:s.split(",").map(l=>l.trim()).filter(l=>l!=="");for(let l of u.length>0?u:[""])if(n.push({sessionId:i,timestamp:a.createdAt??new Date().toISOString(),term:l,userMessage:a.rawExcerpt??""}),n.length>=50)break}if(n.length>=50)break}}catch(o){this.logger?.warn?.(`[KeywordOptimizationService] Failed to read trajectory for session ${i}: ${String(o)}`)}if(n.length>=50)break}return n}static _instances=new Map;static get(t,n,r){let i=`${t}::${n}`;return e._instances.has(i)||e._instances.set(i,new e(t,n,r)),e._instances.get(i)}static reset(){e._instances.clear()}};var Ky=null,gke=!1,Ake=!1,Cee=0,yke=new Set,pzn=900*1e3,fzn=1e4,mzn=20,hzn=10,sbt=40,cbt=400,gzn=20,Azn=5;async function yzn(e,t,n){let r=e.trajectory;if(!r?.listPendingSignalConfirmations)return 0;let i=r.listPendingSignalConfirmations(gzn);if(i.length===0)return 0;let o=mee(e,t);if(!o)return gf(e.stateDir,u=>{u.stage2BatchSkipped+=1}),t?.debug?.("[PD:CorrectionObserver] batch confirm skipped: signal classifier unavailable"),0;let a=_ee(e,t),s=0,c=(u,l)=>{let p=r.bumpSignalConfirmationAttempt(u);p>=Azn&&(r.markSignalConfirmationResult(u,"abandoned",`attempts exhausted (${p}): ${l}`),s++,ze.log(e.workspaceDir,"SIGNAL_CONFIRMATION_ABANDONED",`${u} after ${p} attempts`))};for(let u of i){if(n?.())break;try{let l=await a.confirmPendingSignal({sessionId:u.sessionId,userTurnRowid:u.userTurnRowid,occurrenceId:u.occurrenceId,excerpt:u.excerpt,terms:u.terms,termsVerified:u.termsVerified},o);if(l.disposition==="failed"){c(u.id,l.detail);continue}r.markSignalConfirmationResult(u.id,l.disposition,l.detail),s++,l.disposition==="confirmed"&&gf(e.stateDir,p=>{p.stage2Confirmed+=1,p.lastStage2SuccessAt=new Date().toISOString()}),ze.log(e.workspaceDir,"SIGNAL_CONFIRMATION_RESOLVED",`${u.id} -> ${l.disposition} (${l.detail.slice(0,80)})`)}catch(l){t?.warn?.(`[PD:CorrectionObserver] confirm failed for ${u.id}: ${String(l)}`),c(u.id,`threw: ${String(l)}`)}}return s}function _zn(e,t){try{let n=EL(e.workspaceDir,"correction_observer","correctionObserver",t);if(!n.enabled)return n.readiness==="config_malformed"?t?.warn?.(`[PD:CorrectionObserver] Config malformed: ${n.reason}. ${n.nextAction}`):t?.debug?.(`[PD:CorrectionObserver] ${n.reason}`),null;if(n.readiness==="needs_setup")return t?.info?.(`[PD:CorrectionObserver] ${n.reason}. ${n.nextAction}`),null;if(n.runtimeProfileType!=="pi-ai")return t?.warn?.(`[PD:CorrectionObserver] Runtime profile type '${String(n.runtimeProfileType)}' is not supported (ADR-0029: pi-ai only). Skipping.`),null;let r=new Dl({provider:n.provider??"anthropic",model:n.model??"anthropic/claude-3-5-sonnet",apiKeyEnv:n.apiKeyEnv??"ANTHROPIC_API_KEY",timeoutMs:n.timeoutMs??void 0,maxTokens:n.maxTokens??void 0,baseUrl:n.baseUrl??void 0,workspace:e.workspaceDir});return new $Q({runtimeAdapter:r},{timeoutMs:n.timeoutMs??void 0})}catch(n){return t?.warn?.(`[PD:CorrectionObserver] Failed to resolve CorrectionObserver: ${String(n)}`),null}}function kee(e,t){gf(e.stateDir,n=>{t?(n.observerLastSuccessAt=new Date().toISOString(),n.observerConsecutiveFailures=0):n.observerConsecutiveFailures+=1})}async function Izn(e,t,n){try{let r=await yzn(e,t,n);if(r>0&&t?.info?.(`[PD:CorrectionObserver] batch-confirmed ${r} pending signals`),n?.())return;gf(e.stateDir,w=>{w.pendingCount=e.trajectory?.countPendingSignalConfirmations?.()??w.pendingCount});let i=_zn(e,t);if(!i){t?.debug?.("[PD:CorrectionObserver] Observer not resolved. Skipping cycle."),kee(e,!0);return}t?.info?.("[PD:CorrectionObserver] Observer resolved. Initiating periodic optimization...");let o=pc.get(e.workspaceDir),a=o.listRecentSessions({limit:mzn}),s=a.map(w=>w.sessionId);if(s.length===0){t?.info?.("[PD:CorrectionObserver] No recent sessions found. Skipping correction optimization.");return}let c=Kxt(e.stateDir),u=a[0]?.updatedAt??null;if(r===0&&c?.observerLastSuccessAt&&u&&u<=c.observerLastSuccessAt){t?.debug?.(`[PD:CorrectionObserver] No new turns since ${c.observerLastSuccessAt}. Skipping optimization cycle.`),kee(e,!0);return}let l=[];for(let w of s.slice(0,hzn))try{let b=o.listUserTurnsForSession(w);for(let k of b)k.rawExcerpt&&l.push(k.rawExcerpt.length>cbt?`${k.rawExcerpt.slice(0,cbt)}\u2026`:k.rawExcerpt)}catch(b){t?.warn?.(`[PD:CorrectionObserver] Failed to load user turns for session ${w}: ${String(b)}`)}l.length>sbt&&l.splice(0,l.length-sbt);let f=bv.get(e.stateDir).getStore().keywords,m={totalKeywords:f.length,terms:f.map(w=>({term:w.term,weight:w.weight,truePositiveCount:w.truePositiveCount??0,falsePositiveCount:w.falsePositiveCount??0}))},g=See.get(e.stateDir,e.workspaceDir,t),h=await g.buildTrajectoryHistory(s),y={parentSessionId:"correction-observer-service",workspaceDir:e.workspaceDir,keywordStoreSummary:m,recentMessages:l,trajectoryHistory:h},_=new BW;_.register({agentId:"correction-observer",mode:"realtime",runner:i}),t?.info?.(`[PD:CorrectionObserver] Dispatching with ${h.length} trajectory events, ${l.length} recent messages.`);let v=await _.dispatch("correction-observer",y);if(t?.info?.(`[PD:CorrectionObserver] Completed: updated=${v.updated}, summary="${v.summary}"`),n?.())return;g.applyResult(v),kee(e,!0)}catch(r){let i=`Correction observer cycle failed: ${String(r)}`;t?.warn?.(`[PD:CorrectionObserver] ${i}`),ze.log(e.workspaceDir,"CORRECTION_OBSERVER_CYCLE_FAILED",i),n?.()||kee(e,!1)}}var _ke={id:"principles-correction-observer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n&&n.warn("[PD:CorrectionObserver] workspaceDir not found in service config. Correction observer disabled.");return}if(yke.has(t)){n&&n.info(`[PD:CorrectionObserver] Already started for workspace: ${t}. Skipping duplicate start.`);return}let r=EL(t,"correction_observer","correctionObserver",n),o=EL(t,"signal_collector","signalCollector",n).enabled;if(!r.enabled&&!o){n?.info?.(`[PD:CorrectionObserver] correction_observer disabled and signal_collector disabled \u2014 periodic cycle (batch confirmation + optimization) not started. ${r.nextAction}`);return}if(r.enabled&&r.readiness==="needs_setup"&&!o){n?.info?.(`[PD:CorrectionObserver] ${r.reason}. ${r.nextAction}`);return}r.enabled&&r.readiness!=="needs_setup"||n?.info?.(`[PD:CorrectionObserver] confirmation-consumer-only mode: batch-confirming persisted signal_confirmations every cycle; keyword optimization observer is ${r.enabled?"needs_setup":"disabled"}. ${r.nextAction}`),yke.add(t),gke=!1,Cee+=1;let s=Cee,c=ft.fromHookContext({workspaceDir:t,...e.config});n&&n.info(`[PD:CorrectionObserver] Starting with workspaceDir=${c.workspaceDir}, stateDir=${c.stateDir}`);let u=pzn,l=()=>gke||s!==Cee;async function p(){if(!l()&&!Ake){Ake=!0;try{await Izn(c,n,l)}finally{Ake=!1}l()||(Ky=setTimeout(p,u),Ky.unref())}}Ky=setTimeout(()=>{p().catch(f=>{n&&n.error(`[PD:CorrectionObserver] Startup cycle failed: ${String(f)}`),!l()&&(Ky=setTimeout(p,u),Ky.unref())})},fzn),Ky.unref()},stop(e){gke=!0,Cee+=1,yke.clear(),Ky&&clearTimeout(Ky),Ky=null}};var Ree=class extends c${constructor(t){super({source:pc.get(t.workspaceDir),toolSemantics:Km})}};import vzn from"node:path";var Ezn=12e4,Ike=3e4,GL=new Map;function xzn(e){let t=GL.get(e);return t||(t={stopped:!1,timeoutId:null},GL.set(e,t)),t}function wzn(e){return`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`}function vke(e,t){try{let n=BSe(e,{version:1,hostKind:"openclaw",mappings:ske,declaredAt:new Date().toISOString()});n.ok||t.warn(`[PD:AutoConsumer] Failed to persist OpenClaw tool declaration: ${n.reason} \u2014 pd-cli reliability validation will not find it (rc-9)`)}catch(n){let r=n instanceof Error?n.message:String(n);t.warn(`[PD:AutoConsumer] Failed to persist OpenClaw tool declaration: ${r} \u2014 pd-cli reliability validation will not find it (rc-9)`)}}async function bzn(e,t){await GIt(e,{owner:"auto-consumer",logLabel:"AutoConsumer",logger:t,emitEvent:(n,r)=>ze.log(e,n,r),hostToolCatalog:{readOnlyTools:Iee,writeTools:[...Sv,...rke,...HL]},toolSemantics:Km,hostKinds:["openclaw"],behaviorEvidence:{assemble:n=>new Ree({workspaceDir:e,stateDir:vzn.join(e,".state")}).assemble({sourcePainId:n.sourcePainId,ownerDesiredOutcome:n.ownerDesiredOutcome,sourceNegativeToolCallId:n.sourceNegativeToolCallId,positiveToolCallIds:n.positiveToolCallIds,projectDir:e})}})}var Eke={id:"principles-internalization-auto-consumer",start(e){let t=e?.workspaceDir,n=e?.logger||console;if(!t){n.warn("[PD:AutoConsumer] No workspace directory, not starting.");return}let r=t,i=xzn(r);if(vke(r,n),!i.stopped&&i.timeoutId!==null){n.info(`[PD:AutoConsumer] Already started for workspace: ${r}`);return}let o=jr(r,USe,{info:u=>n.info(u),warn:u=>n.warn(u)});if(!o.enabled){let u=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:wzn(r),flagSource:o.source});ze.log(r,"INTERNALIZATION_CONSUMER_DISABLED",u),n.info(`[PD:AutoConsumer] NOT started for workspace: ${r}. Disabled (source: ${o.source}).`);return}i.stopped=!1;let a=Ezn;function s(){i.stopped||(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())}async function c(){if(!i.stopped){try{await bzn(r,n)}catch(u){let l=`Internalization consumer cycle failed: ${u instanceof Error?u.message:String(u)}`;n.error(`[PD:AutoConsumer] ${l}`),ze.log(r,"INTERNALIZATION_CONSUMER_CYCLE_FAILED",l)}s()}}i.timeoutId=setTimeout(()=>{c().catch(u=>{n.error(`[PD:AutoConsumer] Startup cycle failed: ${String(u)}`),!i.stopped&&(i.timeoutId=setTimeout(c,a),i.timeoutId?.unref())})},Ike),i.timeoutId?.unref(),ze.log(r,"INTERNALIZATION_CONSUMER_STARTED",JSON.stringify({intervalMs:a,initialDelayMs:Ike})),n.info(`[PD:AutoConsumer] Started for workspace: ${r} (interval: ${a}ms, initial delay: ${Ike}ms)`)},stop(e){let t=e?.workspaceDir;if(t){let n=GL.get(t);n&&(n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null),GL.delete(t)}else{for(let[,n]of GL)n.stopped=!0,n.timeoutId&&clearTimeout(n.timeoutId),n.timeoutId=null;GL.clear()}}};var ubt={id:"principles-disciple-trajectory",start(e){e.workspaceDir&&ft.fromHookContext(e).trajectory},stop(e){e.workspaceDir&&pc.dispose(e.workspaceDir)}};import*as Oee from"fs";import*as gbt from"path";import*as Abt from"os";var lbt=[];import*as RS from"fs";import*as xke from"path";var dbt="pd_tasks.json";function pbt(e){return xke.join(e,".state",dbt)}function Szn(e){let t=xke.join(e,".state");RS.existsSync(t)||RS.mkdirSync(t,{recursive:!0})}function fbt(e){let t=pbt(e);if(!RS.existsSync(t))return[];try{let n=RS.readFileSync(t,"utf-8"),r=JSON.parse(n);return Array.isArray(r)?r:[]}catch(n){return console.warn(`[PD:TaskStore] Failed to parse ${dbt}: ${String(n)}`),[]}}async function mbt(e,t){let n=pbt(e);Szn(e),await EZ(n,async()=>{Ut(n,JSON.stringify(t,null,2))})}var Tee=gbt.join(Abt.homedir(),".openclaw","cron","jobs.json");function Czn(e){if(!Oee.existsSync(Tee))return e?.info?.("[PD:Reconciler] cron/jobs.json not found, starting with empty store"),{version:1,jobs:[]};try{let t=Oee.readFileSync(Tee,"utf-8"),n=JSON.parse(t);return e?.info?.(`[PD:Reconciler] Loaded cron/jobs.json: ${n.jobs.length} jobs`),n}catch(t){return e?.warn?.(`[PD:Reconciler] Failed to parse cron/jobs.json: ${String(t)}`),{version:1,jobs:[]}}}async function kzn(e){await EZ(Tee,async()=>{Ut(Tee,JSON.stringify(e,null,2))})}function Rzn(e,t){let n=[],r=new Map;for(let i of t)r.set(i.name,i);for(let i of e){let o=r.get(i.name);if(!o)i.enabled&&n.push({type:"CREATE",task:i});else{let a=o.metadata?.pdVersion;i.enabled?!a||a!==i.version?n.push({type:"UPDATE",task:i,job:o}):n.push({type:"SKIP",task:i,job:o}):n.push({type:"DISABLE",task:i,job:o})}}for(let i of t){if(!i.name.startsWith("PD "))continue;e.find(a=>a.name===i.name)||n.push({type:"ORPHAN",job:i})}return n}function hbt(e,t,n,r){return r?.info?.(`[PD:Reconciler] Building cron job: ${e.name} (id=${e.id}, interval=${e.schedule.everyMs}ms)`),{id:`pd-${e.id}-${t}`,name:e.name,agentId:e.agentId||"main",description:e.description,enabled:e.enabled,schedule:{kind:"every",everyMs:e.schedule.everyMs},sessionTarget:"isolated",wakeMode:"now",payload:{kind:"agentTurn",message:Tzn(e,n,r),lightContext:e.execution.lightContext??!0,timeoutSeconds:e.execution.timeoutSeconds??120,toolsAllow:e.execution.toolsAllow},delivery:{mode:e.delivery.mode},createdAtMs:t,updatedAtMs:t,state:{nextRunAtMs:t+e.schedule.everyMs},metadata:{pdVersion:e.version,pdTaskId:e.id}}}function Tzn(e,t,n){return e.description}async function ybt(e,t){let n=t?.dryRun??!1,r=t?.logger??console,i=Date.now(),o={created:[],updated:[],skipped:[],orphaned:[],errors:[]},a=fbt(e),s=new Map(a.map(f=>[f.id,f])),c=lbt.map(f=>{let m=s.get(f.id);return m?{...f,meta:{...f.meta,...m.meta}}:{...f,meta:{createdAtMs:i}}}),u=await Czn(r),l=Ozn(c,u,r),p=Rzn(l,u.jobs);for(let f of p)switch(f.type){case"CREATE":if(f.task){if(!n){let m=hbt(f.task,i,e,r);u.jobs.push(m),r.info?.(`[PD:Reconciler] Created job: ${f.task.name}`)}o.created.push(f.task.name)}break;case"UPDATE":if(f.task&&f.job){if(!n){let m=u.jobs.indexOf(f.job),g=hbt(f.task,i,e,r);g.id=f.job.id,g.state={...f.job.state,nextRunAtMs:void 0},u.jobs[m]=g,r.info?.(`[PD:Reconciler] Updated job: ${f.task.name}`)}o.updated.push(f.task.name)}break;case"DISABLE":if(f.job){if(!n){let m=u.jobs.indexOf(f.job);m>=0&&(u.jobs[m]={...f.job,enabled:!1,updatedAtMs:i})}r.warn?.(`[PD:Reconciler] Disabled job: ${f.job.name}`)}break;case"ORPHAN":f.job&&(r.warn?.(`[PD:Reconciler] Orphaned job (no declaration): ${f.job.name}`),o.orphaned.push(f.job.name));break;case"SKIP":f.task&&o.skipped.push(f.task.name);break}if(!n&&(o.created.length>0||o.updated.length>0)){await kzn(u),r.info?.(`[PD:Reconciler] Wrote cron/jobs.json: ${u.jobs.length} total jobs`);for(let f of u.jobs)f.name.startsWith("PD ")&&r.info?.(`[PD:Reconciler] PD job: name=${f.name}, enabled=${f.enabled}, schedule=${JSON.stringify(f.schedule)}, nextRun=${f.state.nextRunAtMs?new Date(f.state.nextRunAtMs).toISOString():"TBD"}`)}return!n&&c.length>0&&await mbt(e,c),o}function Ozn(e,t,n){let r=new Map(t.jobs.map(i=>[i.name,i]));return e.map(i=>{let o=r.get(i.name);if(!o)return i;let a=o.state.consecutiveErrors??0,s=o.state.lastError??"",c=s.includes("timed out")||s.includes("timeout");if(c&&a>0&&o.payload.kind==="agentTurn"){let l=o.payload.timeoutSeconds??120,p=Math.min(1800,l*2);p>l&&(o.payload.timeoutSeconds=p,o.state.consecutiveErrors=0,o.state.lastError=void 0,n.info?.(`[PD:Reconciler] Auto-increased timeout for '${i.name}': ${l}s \u2192 ${p}s (was ${a} consecutive timeouts)`))}let u=a>=3&&!c&&!i.meta?.autoDisabled;return a===0&&i.meta?.autoDisabled&&n.info?.(`[PD:Reconciler] Task '${i.id}' was previously auto-disabled but has 0 consecutive errors now`),u||i.meta||o.state.lastRunAtMs?{...i,meta:{...i.meta,...u?{autoDisabled:!0,autoDisabledAt:Date.now(),autoDisabledReason:`consecutiveErrors=${a}`}:{},...i.meta?{consecutiveFailCount:a}:{},...o.state.lastRunAtMs?{lastFailedAtMs:o.state.lastRunAtMs}:{}}}:i})}var _bt={id:"principles-disciple-task-manager",async start(e){let{workspaceDir:t}=e,n=e.logger??e.api?.logger;if(!t){n?.warn?.("[PD:TaskManager] No workspaceDir, skipping PD task reconciliation");return}n?.info?.("[PD:TaskManager] Starting PD task reconciliation...");try{let r=await ybt(t,{logger:n??console});n?.info?.(`[PD:TaskManager] Reconcile complete: +${r.created.length} ~${r.updated.length} =${r.skipped.length} orphan=${r.orphaned.length}`),r.created.length>0&&n?.info?.(`[PD:TaskManager] Created jobs: ${r.created.join(", ")}`),r.updated.length>0&&n?.info?.(`[PD:TaskManager] Updated jobs: ${r.updated.join(", ")}`),r.errors.length>0&&n?.warn?.(`[PD:TaskManager] Reconcile errors: ${r.errors.map(i=>i.message).join(", ")}`)}catch(r){n?.warn?.(`[PD:TaskManager] Reconcile failed: ${String(r)}`)}},stop(e){}};import*as Ti from"fs";import*as fc from"path";import{fileURLToPath as Dzn}from"url";var Pzn={name:"Principles Disciple Agent",version:"1.0.0"},Lzn="pd-core-guidance-v2",Ibt=new Set(["AGENTS.md","TOOLS.md"]);function Nzn(){return`pd-core-guidance-version: ${Lzn}`}function Mzn(e,t){return!Ibt.has(e)||t.includes(Nzn())?!1:!!(t.includes("pd_spawn_agent")||!t.includes("subagents")||!t.includes("sessions_spawn"))}function vbt(e,t,n="en"){try{let r=Dzn(import.meta.url),i=fc.dirname(r),o=fc.resolve(i,"..","..","templates","workspace");Ti.existsSync(o)&&(e.logger.info(`[PD] Syncing workspace templates: ${t}...`),wke(o,t,e));let a=fc.resolve(i,"..","..","templates","langs",n,"core");if(Ti.existsSync(a)||(a=fc.resolve(i,"..","..","templates","langs","zh","core")),Ti.existsSync(a)){e.logger.info(`[PD] Flattening ${n} core templates to workspace root...`);let p=Ti.readdirSync(a);for(let f of p){let m=fc.join(a,f),g=fc.join(t,f);if(!Ti.existsSync(g))Ti.copyFileSync(m,g),e.logger.info(`[PD] Initialized core file: ${f}`);else if(Ibt.has(f)){let h=Ti.readFileSync(g,"utf8");Mzn(f,h)&&e.logger.warn(`[PD] Outdated core guidance detected in ${f}. Review the latest template guidance for peer sessions, subagents, and sessions_spawn routing.`)}}}let s=fc.resolve(i,"..","..","templates","langs",n,"pain"),c=fc.join(t,fr.PAIN_SAMPLES);Ti.existsSync(s)&&(Ti.existsSync(c)||Ti.mkdirSync(c,{recursive:!0}),wke(s,c,e));let u=fc.join(t,fr.IDENTITY),l=fc.join(u,"PROFILE.json");Ti.existsSync(l)||(Ti.existsSync(u)||Ti.mkdirSync(u,{recursive:!0}),Ut(l,JSON.stringify(Pzn,null,2)),e.logger.info("[PD] Initialized PROFILE.json with identity metadata (contextInjection migrated to .pd/config.yaml)"))}catch(r){e.logger.error(`[PD] Failed to initialize workspace templates: ${String(r)}`)}}function wke(e,t,n){let r=Ti.readdirSync(e);for(let i of r){let o=fc.join(e,i),a=i==="okr"?fc.join("memory","okr"):i,s=fc.join(t,a);if(Ti.statSync(o).isDirectory())Ti.existsSync(s)||Ti.mkdirSync(s,{recursive:!0}),wke(o,s,n);else if(!Ti.existsSync(s)){let u=fc.dirname(s);Ti.existsSync(u)||Ti.mkdirSync(u,{recursive:!0}),Ti.copyFileSync(o,s),n.logger.info(`[PD] Copied: ${a}`)}}}var tSo=uh.map(e=>({id:e.id,name:e.name,description:e.statement}));import*as mc from"fs";import*as $a from"path";function Ebt(e,t){try{let n=$a.join(t,"docs"),r=$a.join(t,"memory",".state"),i=[{legacy:$a.join(n,"PRINCIPLES.md"),newKey:"PRINCIPLES"},{legacy:$a.join(n,"THINKING_OS.md"),newKey:"THINKING_OS"},{legacy:$a.join(n,"DECISION_POLICY.json"),newKey:"DECISION_POLICY"},{legacy:$a.join(n,".pain_flag"),newKey:"PAIN_FLAG"},{legacy:$a.join(n,"SYSTEM_CAPABILITIES.json"),newKey:"SYSTEM_CAPABILITIES"},{legacy:$a.join(n,"SYSTEM.log"),newKey:"SYSTEM_LOG"},{legacy:$a.join(r,"pain_dictionary.json"),newKey:"DICTIONARY"},{legacy:$a.join(r,"pain_settings.json"),newKey:"PAIN_SETTINGS"},{legacy:$a.join(r,"pain_candidates.json"),newKey:"PAIN_CANDIDATES"},{legacy:$a.join(r,"sessions"),newKey:"SESSION_DIR"},{legacy:$a.join(r,"logs","events.jsonl"),newKey:"SYSTEM_LOG"}],o=0;for(let a of i)if(mc.existsSync(a.legacy)){let s=is(t,a.newKey),c=$a.dirname(s);if(mc.existsSync(c)||mc.mkdirSync(c,{recursive:!0}),mc.existsSync(s))e.logger?.warn?.(`[PD:Migration] Skipping ${$a.basename(a.legacy)}: already exists at destination.`);else try{mc.renameSync(a.legacy,s),e.logger.info(`[PD:Migration] Migrated ${$a.basename(a.legacy)} to ${s.replace(t,"")}`),o++}catch(u){e.logger.error(`[PD:Migration] Failed to rename ${a.legacy}: ${String(u)}`)}}if(o>0&&e.logger.info(`[PD:Migration] Successfully migrated ${o} files/folders to new architecture.`),mc.existsSync(r))try{let a=mc.readdirSync(r);if(a.length===0||a.length===1&&a[0]==="logs"){let s=$a.join(r,"logs");mc.existsSync(s)&&mc.readdirSync(s).length===0&&mc.rmdirSync(s),mc.readdirSync(r).length===0&&(mc.rmdirSync(r),e.logger.info("[PD:Migration] Cleaned up empty legacy state directory."))}}catch(a){e.logger.debug?.(`[PD:Migration] Failed to cleanup legacy state dir: ${String(a)}`)}}catch(n){e.logger.error(`[PD:Migration] Directory refactor migration failed: ${String(n)}`)}}function Bzn(e,t,n){return{workspaceDir:e,sessionId:t??"openclaw:session-unavailable",toolName:n}}function Fzn(e){let t={};return typeof e.modelProviderId=="string"&&e.modelProviderId.length>0&&(t.modelProviderId=e.modelProviderId),typeof e.modelId=="string"&&e.modelId.length>0&&(t.modelId=e.modelId),e.contextTokenBudget!==void 0&&(t.contextTokenBudget=e.contextTokenBudget),e.contextWindowSource!==void 0&&(t.contextWindowSource=e.contextWindowSource),Object.keys(t).length>0?t:void 0}function xbt(e){let t=new WeakMap,n=new WeakMap;function r(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error(`OpenClaw ${s.kind} dispatch is missing its native payload token`);let c=Object.hasOwn(s.rawPayload,"nativeToken")?Reflect.get(s.rawPayload,"nativeToken"):s.rawPayload;if(typeof c!="object"||c===null)throw new Error(`OpenClaw ${s.kind} dispatch has an invalid native payload token`);let u=t.get(c);if(!u||u.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} dispatch has a mismatched native payload`);return u}function i(s,c,u,l){let p={decision:u,source:s.source,...l?{reason:l}:{}};return n.set(p,c),p}let o=Pvt({toolSemantics:Km,...e.roundKeyProvider?{roundKeyProvider(s){let c=r(s);if(c.kind==="before_prompt_build")return e.roundKeyProvider?.(c.event,c.context)}}:{},adaptivePriorityProvider(s){let c=r(s);if(c.kind==="before_prompt_build")return e.adaptivePriorityProvider?.(c.event,c.context)},ruleContextProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule context request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule context request has an invalid native token");let u=t.get(c);if(!u||u.kind!=="before_tool_call")throw new Error("OpenClaw rule context request has a mismatched native payload");return e.ruleContextProvider?.(u.event,u.context,s)},ruleInputEnrichmentProvider(s){if(typeof s.rawPayload!="object"||s.rawPayload===null)throw new Error("OpenClaw rule enrichment request is missing its native payload");let c=Reflect.get(s.rawPayload,"nativeToken");if(typeof c!="object"||c===null)throw new Error("OpenClaw rule enrichment request has an invalid native token");let u=t.get(c);if(!u||u.kind!=="before_tool_call")throw new Error("OpenClaw rule enrichment request has a mismatched native payload");return e.ruleInputEnrichmentProvider?.(u.event,u.context,s)},async beforePromptBuild(s,c){let u=r(s);if(u.kind!=="before_prompt_build")throw new Error("OpenClaw prompt payload mismatch");let l=await e.beforePromptBuild(u.event,u.context,c);return i(s,{kind:u.kind,value:l},l?"modify":"allow")},painEnrichmentProvider(s){let c=r(s);if(c.kind!=="after_tool_call")throw new Error("OpenClaw pain payload mismatch");return e.painEnrichmentProvider?.(c.event,c.context)},hostKind:"openclaw"});async function a(s,c,u){let l={};t.set(l,s);let p=Fzn(s.context),f=s.kind==="after_tool_call"?s.event:void 0,m=f!==void 0?f.params:void 0,g=w=>typeof w=="object"&&w!==null&&!Array.isArray(w),h=g(m)?m:g(f?.toolArgs)?f.toolArgs:{},y={kind:s.kind,context:{...Bzn(c,u,s.kind==="before_prompt_build"?void 0:s.event.toolName),...f!==void 0?{toolInput:h,toolOutput:{error:f.error,result:f.result,durationMs:f.durationMs}}:{},...p!==void 0?{modelContext:p}:{}},rawPayload:s.kind==="before_tool_call"?{nativeToken:l,toolInput:{toolName:s.event.toolName,params:s.event.params??{}}}:{nativeToken:l},source:`openclaw:${s.kind}`},_=await o.dispatch(y),v=n.get(_);if(s.kind==="before_tool_call"&&!v){let w=e.onBeforeToolResult?.(s.event,s.context,_);return{kind:s.kind,value:_.decision==="deny"?{block:!0,blockReason:_.reason}:w}}if(s.kind==="after_tool_call"&&!v){let w=_.metadata,b=typeof w?.outcome=="string"?w.outcome:void 0,k=typeof w?.nextAction=="string"?w.nextAction:void 0;return{kind:s.kind,value:void 0,hostResult:{warnings:_.warnings??[],...b!==void 0?{outcome:b}:{},...k!==void 0?{nextAction:k}:{}}}}if(!v||v.kind!==s.kind)throw new Error(`OpenClaw ${s.kind} result mapping is missing`);return v}return{runtime:o,async dispatchBeforePromptBuild(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_prompt_build requires workspaceDir");let u=await a({kind:"before_prompt_build",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="before_prompt_build")throw new Error("OpenClaw prompt result mismatch");return u.value},async dispatchBeforeToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw before_tool_call requires workspaceDir");let u=await a({kind:"before_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="before_tool_call")throw new Error("OpenClaw gate result mismatch");return u.value},async dispatchAfterToolCall(s,c){if(!c.workspaceDir)throw new Error("OpenClaw after_tool_call requires workspaceDir");let u=await a({kind:"after_tool_call",event:s,context:c},c.workspaceDir,c.sessionId);if(u.kind!=="after_tool_call")throw new Error("OpenClaw after_tool_call result mismatch");return u.hostResult??{warnings:[]}}}}var wbt=new Set;try{wZ()}catch{}function eCo(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Sbt(e,t,n){return jr(e,t,n)}function Qzn(e,t){let n=Sbt(e,"correction_observer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"correction_observer_disabled",nextAction:"set features.correction_observer.enabled=true in .pd/config.yaml to enable",featureFlag:"correction_observer",boundedContext:"correction_observer_service",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function Wzn(e,t){let n=Sbt(e,"internalization_auto_consumer",t);if(n.enabled)return{shouldStart:!0,flagSource:n.source,disabledInfo:null};let r=JSON.stringify({reason:"internalization_auto_consumer_disabled",nextAction:`pd runtime internalization run-once --workspace "${e}" --runner dreamer --runtime config --json`,featureFlag:"internalization_auto_consumer",boundedContext:"internalization_auto_consumer",flagSource:n.source});return{shouldStart:!1,flagSource:n.source,disabledInfo:r}}function $zn(e){let t=e.resolver?e.resolver():Dxt(),n=t!==null&&Ul(t.workspaceDir)===null;if(t!==null&&n){let o=Fvt(t.workspaceDir,e.extensionRoot,e.homeDir);if(o.ok)return{status:o.written?"written":"unchanged",reason:`pd_workspace_explicit:${t.source}`,nextAction:o.written?"Restart the OpenClaw gateway so the pd-recall MCP server reads the new binding.":"No change: the binding already matches the declared PD workspace.",workspaceDir:t.workspaceDir,source:t.source};let a=o.reason==="mcp_server_component_missing";return{status:"unavailable",reason:o.reason??"mcp_binding_write_failed",nextAction:a?"Re-run the PD host setup so ~/.pd/runtime/pd-mcp-server is installed, then restart OpenClaw. pd-recall stays fail-closed until the binding exists.":`PD FAILED to write the binding for the declared workspace, so the previous mcp-binding.json (a DIFFERENT workspace) may still be on disk. The launcher refuses to start unless the binding matches the explicit declaration, so no other workspace is served \u2014 but fix the failure (check write access to ${e.extensionRoot}) and restart the OpenClaw gateway.`,workspaceDir:t.workspaceDir,source:t.source}}let r=Bvt(e.extensionRoot),i=t===null?"pd_workspace_not_explicit":"pd_workspace_declaration_invalid";return{status:r.ok?"invalidated":"unavailable",reason:r.ok?i:r.reason??"mcp_binding_remove_failed",nextAction:r.ok?'pd-recall MCP is fail-closed because the PD governance workspace is not explicitly configured; hooks keep their per-agent workspaces. Declare ONE PD workspace (set PD_WORKSPACE_DIR, or add {"workspace":"<absolute dir>"} to ~/.openclaw/principles-disciple.json), then restart the OpenClaw gateway.':`PD FAILED to remove the stale mcp-binding.json, so the old binding file is still on disk (the launcher separately refuses to start unless the binding matches the explicitly declared workspace). Delete ${Dee.join(e.extensionRoot,"mcp-binding.json")} manually, then declare ONE PD workspace and restart the OpenClaw gateway.`}}async function Hzn(e,t,n){let r=Date.now();if(!n)return;let i=t.workspaceDir,o=t.sessionId,a=(h,y)=>{if(!(!h||typeof h!="object"))return Object.getOwnPropertyDescriptor(h,y)?.value},s=a(e,"currentUserMessage"),c=a(e,"currentUserMessageId"),u=a(e,"requestId");if(!i||!o?.trim()||!WL(t.trigger)||qW(t.trigger,o))return;let l=JZ(a(n,"pluginConfig"),i,r);if(!l)return;if(!(typeof c=="string"&&c.trim().length>0||typeof u=="string"&&u.trim().length>0)){if(DL(l)){n.logger.warn('[PD:AA] controlled admission refused: {"reason":"principle_mapping_has_no_admission_identity"}');return}if(!tee())return;let h=Math.min(r+l.softTimeoutMs,l.expiresAtMs);if(h-Date.now()<=0)return;let y=Uzn(),_=rxt({event:e,workspaceDir:i,sessionId:o,runId:t.runId??null,mapping:l,hookInvocationId:y,now:r});if(_.status!=="claimed"){n.logger.warn(`[PD:AA] controlled admission refused: ${JSON.stringify({status:_.status,..._.status==="rejected"?{reason:_.reason,detail:_.detail}:{}})}`);return}return k$({...t,api:n},l,"shared",y),{artifactId:l.artifactId,activationId:l.activationId,hookInvocationId:y,signal:AbortSignal.timeout(Math.max(1,h-Date.now())),deadlineAt:h}}if(typeof s!="string"||ES(e,o).isAgentToAgent||s.split(/\r?\n/,1)[0]!=="[PD-AA:delivery-review:v1]")return;let m=Math.min(r+l.softTimeoutMs,l.expiresAtMs),g=m-Date.now();if(!(g<=0)){if(DL(l)){let h=await yIt({workspaceDir:i,principleId:l.principleId});if(!h.ok){n.logger.warn(`[PD:AA] principle resolution refused: ${JSON.stringify({reason:h.reason,principleId:l.principleId,warnings:h.warnings.length,nextAction:"the mapping target is not uniquely currently authorized; ordinary Native assembly continues"})}`);return}let y=m-Date.now();if(y<=0){n.logger.warn(`[PD:AA] principle resolution refused: ${JSON.stringify({reason:"deadline",principleId:l.principleId,nextAction:"the soft deadline expired during resolution; ordinary Native assembly continues"})}`);return}let _=k$({...t,api:n},{artifactId:h.artifactId,activationId:h.activationId},"shared");return GEt(_,h),{artifactId:h.artifactId,activationId:h.activationId,additiveOnly:!0,hookInvocationId:_,signal:AbortSignal.timeout(y),deadlineAt:m}}return{artifactId:l.artifactId,activationId:l.activationId,hookInvocationId:k$({...t,api:n},l,"shared"),signal:AbortSignal.timeout(g),deadlineAt:m}}}var jzn={name:"Principles Disciple",description:"Evolutionary programming agent framework with strategic guardrails and reflection loops.",register(e){e.logger.info(`Principles Disciple Plugin registered. (Path: ${e.rootDir??"(unknown)"})`),Hd.setExtensionRoot(e.rootDir??"."),setTimeout(()=>{try{let l=Hd.getExtensionRoot()??process.cwd(),p=$zn({extensionRoot:l,homeDir:bbt.homedir()});p.status==="written"?e.logger.info(`[PD:health] mcp-binding.json updated for the pd-recall MCP server (${p.reason}; restart the gateway to apply)`):p.status==="invalidated"?e.logger.warn(`[PD:health] mcp-binding.json removed: pd-recall MCP stays fail-closed (${p.reason}). nextAction: ${p.nextAction}`):p.status==="unavailable"&&e.logger.warn(`[PD:health] mcp-binding unavailable (${p.reason}). nextAction: ${p.nextAction}`)}catch(l){e.logger.warn(`[PD:health] mcp-binding update failed: ${String(l instanceof Error?l.message:l)}`)}let c=xZ(e.config,e.id),u=d$(c);if(!u.authorized&&iCe(c))e.logger.info("[PD:health] conversation hooks (llm_output / trajectory) disabled by explicit configuration \u2014 honoring Owner opt-out (allowConversationAccess=false). nextAction: set the flag to true or remove it to re-enable conversation capture.");else if(u.authorized)e.logger.info("[PD:health] conversation hooks (allowConversationAccess) OK");else{let l=!1;try{l=wZ()}catch(p){e.logger.warn(`[PD:health] auto-fix for allowConversationAccess failed: ${String(p instanceof Error?p.message:p)}`)}l?e.logger.info("[PD:health] allowConversationAccess auto-configured. Restart the gateway to activate conversation hooks."):e.logger.error(`[PD:health] conversation hooks (llm_output / trajectory) will be BLOCKED by OpenClaw.
|
|
3164
3164
|
reason: ${u.reason}
|
|
3165
3165
|
nextAction: ${u.nextAction}`)}},1e3).unref();let n=jJ();if(!n.passed)for(let c of n.violations)e.logger.error(`[PD:surface-guard] VIOLATION: ${c}`);e.logger.info(`[PD:surface-guard] Core surfaces: ${n.enabledCoreSurfaces.join(", ")}`),e.logger.info(`[PD:surface-guard] Disabled non-core surfaces: ${n.disabledNonCoreSurfaces.length}`);for(let c of n.warnings)e.logger.warn(`[PD:surface-guard] ${c}`);let r=yxt(e),i=e.pluginConfig?.language||"zh",o=xbt({roundKeyProvider:(c,u)=>lwt(c,{...u,api:e}),adaptivePriorityProvider:(c,u)=>Hzn(c,u,e),beforePromptBuild:async(c,u,l)=>dwt(c,{...u,api:e},l),ruleContextProvider:(c,u,l)=>cke(ft.fromHookContext({...u,workspaceDir:u.workspaceDir}),l.targetPath,u.sessionId,e.logger),ruleInputEnrichmentProvider:c=>Swt(c),onBeforeToolResult:(c,u,l)=>{if(!u.workspaceDir){e.logger.warn("[PD_GATE:RULE_HOST] shared result mapping skipped: workspaceDir missing; nextAction=inspect OpenClaw hook context");return}Cwt(c,{...u,workspaceDir:u.workspaceDir,logger:e.logger},l);let p=l.metadata?.ruleDecision;if(p==="auto_correct"||p==="requireApproval")return xwt(c,{...u,workspaceDir:u.workspaceDir,pluginConfig:e.pluginConfig??{},logger:e.logger})},painEnrichmentProvider:(c,u)=>Gxt(c,{...u,workspaceDir:u.workspaceDir??"",pluginConfig:e.pluginConfig??{}})});r.register("hook:before_prompt_build","before_prompt_build",df("hook:before_prompt_build",e.logger,async(c,u)=>{let l=Bg(u,e,"before_prompt_build");if(!l.ok){e.logger.error(`[PD:before_prompt_build] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped \u2014 no mutation will occur. NextAction: ${l.nextAction}`);return}let p=l.workspaceDir;l.consistencyWarning&&e.logger.warn(`[PD:before_prompt_build] ${l.consistencyWarning}`);try{if(!wbt.has(p)){wbt.add(p),Ebt(e,p),vbt(e,p,i),ze.log(p,"SYSTEM_BOOT",`Principles Disciple online. Language: ${i}`);let g=Qzn(p,e.logger);g.shouldStart?(_ke.start({config:e.config,workspaceDir:p,stateDir:Dee.join(p,".state"),logger:e.logger}),e.logger.info(`[PD] CorrectionObserver started for workspace: ${p} (flag source: ${g.flagSource})`)):(e.logger.info(`[PD] CorrectionObserver NOT started for workspace: ${p}. ${g.disabledInfo}`),ze.log(p,"CORRECTION_OBSERVER_DISABLED",g.disabledInfo??"")),vke(p,e.logger);let h=Wzn(p,e.logger);h.shouldStart?(Eke.start({config:e.config,workspaceDir:p,stateDir:Dee.join(p,".state"),logger:e.logger}),e.logger.info(`[PD] InternalizationAutoConsumer started for workspace: ${p} (flag source: ${h.flagSource})`)):(e.logger.info(`[PD] InternalizationAutoConsumer NOT started for workspace: ${p}. ${h.disabledInfo}`),ze.log(p,"INTERNALIZATION_CONSUMER_DISABLED",h.disabledInfo??"")),Uvt(p,e.logger)}let f={...u,workspaceDir:p},m=await o.dispatchBeforePromptBuild(c,f);return ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"before_prompt_build",sessionId:u.sessionId}),m}catch(f){ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"before_prompt_build",sessionId:u.sessionId,error:String(f)}),e.logger.error(`[PD] Error in before_prompt_build: ${String(f)}`)}})),r.register("hook:before_tool_call","before_tool_call",df("hook:before_tool_call",e.logger,(c,u)=>{let l=Bg(u,e,"before_tool_call");if(!l.ok){e.logger.error(`[PD:before_tool_call] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped \u2014 security gate bypassed. NextAction: ${l.nextAction}`);return}let p=l.workspaceDir;l.consistencyWarning&&e.logger.warn(`[PD:before_tool_call] ${l.consistencyWarning}`);try{let f=e.pluginConfig??{},{logger:m}=e,g={...u,workspaceDir:p,pluginConfig:f,logger:m};return o.dispatchBeforeToolCall(c,g).then(h=>(ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"before_tool_call"},{flushImmediately:!0}),h)).catch(h=>{let y=h instanceof Error?h.message.slice(0,500):Ud(h).slice(0,500);ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"before_tool_call",error:y},{flushImmediately:!0}),e.logger.error(`[PD] Error in before_tool_call: ${y}`)})}catch(f){ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"before_tool_call",error:String(f)},{flushImmediately:!0}),e.logger.error(`[PD] Error in before_tool_call: ${String(f)}`)}})),r.register("hook:after_tool_call","after_tool_call",df("hook:after_tool_call",e.logger,(c,u)=>{let l=Bg(u,e,"after_tool_call");if(!l.ok){e.logger.error(`[PD:after_tool_call] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped \u2014 pain detection bypassed. NextAction: ${l.nextAction}`);return}let p=l.workspaceDir;l.consistencyWarning&&e.logger.warn(`[PD:after_tool_call] ${l.consistencyWarning}`);try{let f=e.pluginConfig??{},m={...u,workspaceDir:p,pluginConfig:f};if(c.toolName==="pain"||c.toolName==="skill:pain"){jxt(c,m,e),ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"after_tool_call"},{flushImmediately:!0});return}return ft.fromHookContext({workspaceDir:p,logger:e.logger}).trajectory,o.dispatchAfterToolCall(c,m).then(g=>{let h=g?.warnings??[];if(g?.outcome==="unavailable"||h.length>0){let y=`after_tool_call evidence degraded: ${h.join("; ")}${g?.nextAction?` nextAction=${g.nextAction}`:""}`;e.logger.warn(`[PD:after_tool_call] ${y}`),ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"after_tool_call",error:y.slice(0,500)},{flushImmediately:!0});return}ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"after_tool_call"},{flushImmediately:!0})}).catch(g=>{let h=g instanceof Error?g.message.slice(0,500):Ud(g).slice(0,500);ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"after_tool_call",error:h},{flushImmediately:!0}),e.logger.error(`[PD:SignalCollector] Error in after_tool_call: ${h}`)})}catch(f){ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"after_tool_call",error:String(f)},{flushImmediately:!0}),e.logger.error(`[PD:SignalCollector] Error in after_tool_call: ${String(f)}`)}}),{timeoutMs:1e4}),r.register("hook:llm_output","llm_output",df("hook:llm_output",e.logger,(c,u)=>{let l=Bg(u,e,"llm_output");if(!l.ok){e.logger.error(`[PD:llm_output] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped \u2014 LLM analysis bypassed. NextAction: ${l.nextAction}`);return}let p=l.workspaceDir;l.consistencyWarning&&e.logger.warn(`[PD:llm_output] ${l.consistencyWarning}`);try{Dwt(c,{...u,workspaceDir:p,logger:e.logger}),ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"llm_output",sessionId:u.sessionId})}catch(f){ft.fromHookContext({workspaceDir:p}).eventLog.recordHookExecution({hook:"llm_output",sessionId:u.sessionId,error:String(f)}),e.logger.error(`[PD] Error in llm_output: ${String(f)}`)}}),{timeoutMs:1e4});let a=Lwt({logger:e.logger,getEventLog:c=>ft.fromHookContext({workspaceDir:c}).eventLog});r.register(a.surfaceId,a.event,df("hook:llm_input_presence",e.logger,(c,u)=>{let l=Bg(u,e,"llm_input");if(!l.ok){e.logger.warn(`[PD:llm_input] workspaceDir resolution failed. reason=${l.reason} sessionId=${u.sessionId??"(missing)"}. Presence observation skipped.`);return}l.consistencyWarning&&e.logger.warn(`[PD:llm_input] ${l.consistencyWarning}`),a.onResolved(c,u,l.workspaceDir)})),r.register("hook:before_reset","before_reset",df("hook:before_reset",e.logger,(c,u)=>{let l=Bg(u,e,"before_reset");if(!l.ok){e.logger.error(`[PD:before_reset] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped. NextAction: ${l.nextAction}`);return}return l.consistencyWarning&&e.logger.warn(`[PD:before_reset] ${l.consistencyWarning}`),kwt(c,{...u,workspaceDir:l.workspaceDir})})),r.register("hook:before_compaction","before_compaction",df("hook:before_compaction",e.logger,(c,u)=>{let l=Bg(u,e,"before_compaction");if(!l.ok){e.logger.error(`[PD:before_compaction] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped. NextAction: ${l.nextAction}`);return}return l.consistencyWarning&&e.logger.warn(`[PD:before_compaction] ${l.consistencyWarning}`),Rwt(c,{...u,workspaceDir:l.workspaceDir})})),r.register("hook:after_compaction","after_compaction",df("hook:after_compaction",e.logger,(c,u)=>{let l=Bg(u,e,"after_compaction");if(!l.ok){e.logger.error(`[PD:after_compaction] workspaceDir resolution failed. reason=${l.reason} agentId=${u.agentId??"(missing)"} sessionId=${u.sessionId??"(missing)"}. Hook skipped. NextAction: ${l.nextAction}`);return}return l.consistencyWarning&&e.logger.warn(`[PD:after_compaction] ${l.consistencyWarning}`),Twt(c,{...u,workspaceDir:l.workspaceDir})})),r.register("hook:before_message_write","before_message_write",df("hook:before_message_write",e.logger,(c,u)=>{let l=Bg(u,e,"before_message_write");if(!l.ok){e.logger.warn(`[PD:before_message_write] workspaceDir resolution failed: ${l.reason}`);return}try{Bwt(c,{...u,workspaceDir:l.workspaceDir,pluginConfig:xZ(e.config,e.id)})}catch(p){e.logger.warn(`[PD:before_message_write] error: ${String(p)}`)}})),fxt(r.snapshot());try{let c=Ub("service:correction-observer",_ke,e.logger);c&&e.registerService(c);let u=Ub("service:trajectory",ubt,e.logger);u&&e.registerService(u);let l=Ub("service:pd-task",_bt,e.logger);l&&e.registerService(l);let p=Ub("service:internalization-auto-consumer",Eke,e.logger);p&&e.registerService(p)}catch(c){e.logger.error(`[PD] Failed to register services: ${String(c)}`)}let s=(c,u,l,p,f)=>{let m={name:c,description:l,handler:p,...f?.acceptsArgs?{acceptsArgs:!0}:{}};e.registerCommand(m),u&&e.registerCommand({...m,name:u,description:`${l} (alias of /${c})`})};s("pd-init","pdi",uc("pd-init",i),c=>Fwt(c)),s("pd-bootstrap","pdb",uc("pd-bootstrap",i),c=>Qwt(c)),s("pd-research","pdr",uc("pd-research",i),c=>Wwt(c)),s("pd-help","pdh",uc("pd-help",i),()=>i==="zh"?{text:`
|
|
3166
3166
|
\u{1F4D6} **Principles Disciple \u547D\u4EE4\u5927\u5168**
|
|
@@ -3262,7 +3262,7 @@ ${a.join(`
|
|
|
3262
3262
|
| \`/pd-help\` | Show this help |
|
|
3263
3263
|
|
|
3264
3264
|
\u{1F4A1} Full documentation: https://principles-disciple.dev/docs/slash-commands
|
|
3265
|
-
`.trim()}),e.registerCommand({name:"pd-status",description:uc("pd-status",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),$wt(c)}catch(u){return e.logger.error(`[PD] Command /pd-status failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-pain",description:uc("pd-pain",i),acceptsArgs:!0,handler:async c=>{try{let u=qd(e,c);return c.workspaceDir=u,c.config&&(c.config.workspaceDir=u),await Hwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-pain failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-context",description:uc("pd-context",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),qwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-context failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-focus",description:uc("pd-focus",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Kwt(c,e)}catch(u){return e.logger.error(`[PD] Command /pd-focus failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-principle-rollback",description:uc("pd-principle-rollback",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),ibt(c)}catch(u){return e.logger.error(`[PD] Command /pd-principle-rollback failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-rollback",description:uc("pd-rollback",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Vwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-rollback failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-export",description:uc("pd-export",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),obt(c)}catch(u){return e.logger.error(`[PD] Command /pd-export failed: ${String(u)}`),{text:i==="zh"?"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Export failed. Check logs."}}}}),e.registerCommand({name:"pd-samples",description:uc("pd-samples",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),abt(c)}catch(u){return e.logger.error(`[PD] Command /pd-samples failed: ${String(u)}`),{text:i==="zh"?"\u6837\u672C\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Samples command failed. Check logs."}}}}),e.registerCommand({name:"pd-promote-impl",description:uc("pd-promote-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Ywt(c)}catch(u){return e.logger.error(`[PD] Command /pd-promote-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-disable-impl",description:uc("pd-disable-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Xwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-disable-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-archive-impl",description:uc("pd-archive-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),tbt(c)}catch(u){return e.logger.error(`[PD] Command /pd-archive-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-rollback-impl",description:uc("pd-rollback-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),rbt(c)}catch(u){return e.logger.error(`[PD] Command /pd-rollback-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}})}};var
|
|
3265
|
+
`.trim()}),e.registerCommand({name:"pd-status",description:uc("pd-status",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),$wt(c)}catch(u){return e.logger.error(`[PD] Command /pd-status failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-pain",description:uc("pd-pain",i),acceptsArgs:!0,handler:async c=>{try{let u=qd(e,c);return c.workspaceDir=u,c.config&&(c.config.workspaceDir=u),await Hwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-pain failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-context",description:uc("pd-context",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),qwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-context failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-focus",description:uc("pd-focus",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Kwt(c,e)}catch(u){return e.logger.error(`[PD] Command /pd-focus failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-principle-rollback",description:uc("pd-principle-rollback",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),ibt(c)}catch(u){return e.logger.error(`[PD] Command /pd-principle-rollback failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-rollback",description:uc("pd-rollback",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Vwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-rollback failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-export",description:uc("pd-export",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),obt(c)}catch(u){return e.logger.error(`[PD] Command /pd-export failed: ${String(u)}`),{text:i==="zh"?"\u5BFC\u51FA\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Export failed. Check logs."}}}}),e.registerCommand({name:"pd-samples",description:uc("pd-samples",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),abt(c)}catch(u){return e.logger.error(`[PD] Command /pd-samples failed: ${String(u)}`),{text:i==="zh"?"\u6837\u672C\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Samples command failed. Check logs."}}}}),e.registerCommand({name:"pd-promote-impl",description:uc("pd-promote-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Ywt(c)}catch(u){return e.logger.error(`[PD] Command /pd-promote-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-disable-impl",description:uc("pd-disable-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),Xwt(c)}catch(u){return e.logger.error(`[PD] Command /pd-disable-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-archive-impl",description:uc("pd-archive-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),tbt(c)}catch(u){return e.logger.error(`[PD] Command /pd-archive-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}}),e.registerCommand({name:"pd-rollback-impl",description:uc("pd-rollback-impl",i),acceptsArgs:!0,handler:c=>{try{let u=qd(e,c);return c.config&&(c.config.workspaceDir=u),rbt(c)}catch(u){return e.logger.error(`[PD] Command /pd-rollback-impl failed: ${String(u)}`),{text:i==="zh"?"\u547D\u4EE4\u6267\u884C\u5931\u8D25\uFF0C\u8BF7\u68C0\u67E5\u65E5\u5FD7\u3002":"Command failed. Check logs."}}}})}};var tCo=jzn;export{rs as PrincipleTreeLedgerAdapter,d$ as checkConversationAccessConfig,tCo as default,wZ as ensureConversationAccessInConfig,xZ as getPluginEntry,N8n as initTrajectorySchema,iCe as isExplicitConversationAccessOptOut,eCo as isRecord,Sbt as loadFeatureFlagFromWorkspace,Hzn as resolveAdaptivePriorityForHook,Qzn as shouldStartCorrectionObserver,Wzn as shouldStartInternalizationAutoConsumer,$zn as syncMcpBindingFromExplicitWorkspace};
|
|
3266
3266
|
/*! Bundled license information:
|
|
3267
3267
|
|
|
3268
3268
|
web-streams-polyfill/dist/ponyfill.es2018.js:
|