principles-disciple 3.1.3 → 3.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/bundle.js CHANGED
@@ -1943,7 +1943,7 @@ CONSTRAINTS:
1943
1943
  `).run(n.decidedAt,n.subject.activationId,n.subject.artifactId),p=i.prepare(`
1944
1944
  UPDATE activation_control_states SET version = version + 1, updated_at = ?
1945
1945
  WHERE activation_id = ? AND enforcement = 'eligible' AND version = ?
1946
- `).run(n.decidedAt,n.subject.activationId,t.expectedControlVersion);if(l.changes!==1||p.changes!==1)throw new Error("Promotion state changed during atomic commit");return i.exec("COMMIT"),{activationId:n.subject.activationId,decisionId:n.decisionId,promotedAt:n.decidedAt}}catch(o){try{i.exec("ROLLBACK")}catch{}throw o}}};function _X(){return{consecutiveErrors:0,consecutiveBlocks:[],latestEligible:[]}}function IX(e,t){if(t.protectedCapabilityMatched)return{state:e,trip:"protected_capability_matched"};if(t.neutralProbeFailed)return{state:e,trip:"host_liveness_probe_failed"};if(t.healthFailure)return{state:e,trip:"runtime_health_failure"};let n=t.decision==="error"?e.consecutiveErrors+1:0,r=t.decision==="block"?[...e.consecutiveBlocks,{toolName:t.toolName}].slice(-5):[],i=[...e.latestEligible,{blocked:t.decision==="block",outsideApprovedScope:t.outsideApprovedScope}].slice(-20),o={consecutiveErrors:n,consecutiveBlocks:r,latestEligible:i};return n>=3?{state:o,trip:"three_consecutive_errors"}:r.length>=5&&new Set(r.map(a=>a.toolName)).size>=3?{state:o,trip:"broad_consecutive_blocking"}:i.length===20&&i.filter(a=>a.blocked&&a.outsideApprovedScope).length/20>.8?{state:o,trip:"outside_scope_block_ratio"}:{state:o,trip:null}}import{createHash as I5n,randomUUID as $Zi}from"node:crypto";function Pg(e){return`sha256:${I5n("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function Yb(e,t,n){if(typeof n!="string"||n.length===0)return{outcome:"no_binding"};let r=e.artifact_id,i=e.artifact_kind,o=e.source_task_id,a=e.source_principle_id,s=e.source_rule_id,c=e.lineage_artifact_ids,u=e.validation_status,l=e.created_at,p=e.updated_at;if(!(typeof r=="string"&&r.length>0&&typeof i=="string"&&typeof o=="string"&&(typeof a=="string"||a===null)&&(typeof s=="string"||s===null)&&typeof c=="string"&&typeof u=="string"&&typeof l=="string"&&typeof p=="string"))return{outcome:"unverifiable",error:"artifact row integrity does not allow digest re-verification"};let m;try{m=Pg(up({artifact_id:r,artifact_kind:i,source_task_id:o,source_principle_id:a,source_rule_id:s,lineage_artifact_ids:c,validation_status:u,content_json:t,created_at:l,updated_at:p}))}catch(g){return{outcome:"unverifiable",error:g instanceof Error?g.message:String(g)}}return m!==n?{outcome:"tampered",actualDigest:m}:{outcome:"verified"}}en();po();var G0t={schemaVersion:d.Union([d.Literal("approval-review"),d.Literal("approval-review-v1")]),approvalId:d.String({minLength:1}),artifactId:d.String({minLength:1}),channel:d.Union([d.Literal("prompt"),d.Literal("skill"),d.Literal("code_tool_hook"),d.Literal("defer_archive")])},q0t=d.Union([d.Object({...G0t,artifactState:d.Literal("present"),artifactDigest:d.String({pattern:"^sha256:[a-f0-9]{64}$"})},{additionalProperties:!1}),d.Object({...G0t,artifactState:d.Literal("missing")},{additionalProperties:!1})]);function K0t(e){return nt.Check(q0t,e)}function vX(e,t,n,r=!1){return!K0t(n)||n.approvalId!==e.approvalId||n.artifactId!==e.artifactId||n.channel!==e.channel?!1:n.artifactState==="missing"?r&&t===null:t!==null&&t.artifactId===e.artifactId&&Pg(t)===n.artifactDigest}function zP(){return{ok:!1,error:"stale_review",reason:"The approval material or target changed after review.",nextAction:"Reload this approval and review the current material before deciding again."}}function zbe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vbe(e){if(!zbe(e))return!1;let t=n=>e[n]===null||typeof e[n]=="string";if(typeof e.artifact_id!="string"||typeof e.artifact_kind!="string"||typeof e.source_task_id!="string"||!t("source_principle_id")||!t("source_rule_id")||typeof e.lineage_artifact_ids!="string"||typeof e.validation_status!="string"||typeof e.content_json!="string"||typeof e.created_at!="string"||typeof e.updated_at!="string")return!1;try{let n=JSON.parse(e.lineage_artifact_ids);return Array.isArray(n)&&n.every(r=>typeof r=="string")}catch{return!1}}function V0t(e){return e==="pending"||e==="approved"||e==="rejected"||e==="cancelled"}function YP(e,t){if(!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="string"?n:null}function Ml(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="string"?n:void 0}function v5n(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="number"?n:void 0}function DW(e){if(!zbe(e))return null;let t=YP(e,"approval_id"),n=YP(e,"artifact_id"),r=YP(e,"channel"),i=YP(e,"risk_level"),o=YP(e,"status"),a=YP(e,"requested_at");return!t||!n||!r||!i||!o||!a?null:{approvalId:t,artifactId:n,artifactDigest:Ml(e,"artifact_digest"),channel:r,riskLevel:i,status:o,confidence:v5n(e,"confidence"),requestedAt:a,decidedAt:Ml(e,"decided_at"),decidedBy:Ml(e,"decided_by"),decisionNote:Ml(e,"decision_note"),rejectionReason:Ml(e,"rejection_reason"),summary:Ml(e,"summary"),triggerReason:Ml(e,"trigger_reason"),confidenceExplanation:Ml(e,"confidence_explanation"),effectDescription:Ml(e,"effect_description"),rejectionEffect:Ml(e,"rejection_effect"),editedAt:Ml(e,"edited_at"),editedBy:Ml(e,"edited_by"),editReason:Ml(e,"edit_reason"),previousArtifactId:Ml(e,"previous_artifact_id")}}function EX(e){return{approvalId:e.approval_id,artifactId:e.artifact_id,artifactDigest:e.artifact_digest??void 0,channel:e.channel,riskLevel:e.risk_level,status:e.status,confidence:e.confidence??void 0,requestedAt:e.requested_at,decidedAt:e.decided_at??void 0,decidedBy:e.decided_by??void 0,decisionNote:e.decision_note??void 0,rejectionReason:e.rejection_reason??void 0,summary:e.summary??void 0,triggerReason:e.trigger_reason??void 0,confidenceExplanation:e.confidence_explanation??void 0,effectDescription:e.effect_description??void 0,rejectionEffect:e.rejection_effect??void 0,editedAt:e.edited_at??void 0,editedBy:e.edited_by??void 0,editReason:e.edit_reason??void 0,previousArtifactId:e.previous_artifact_id??void 0}}function E5n(e,t){return"apr_"+t+"_"+e}var Jb=class{connection;constructor(t){this.connection=t}async enqueue(t,n){let r=this.connection.getDb();if(!r.prepare("SELECT 1 FROM pi_artifacts WHERE artifact_id = ?").get(t.artifactId))throw new Error(`approvals.artifact_id references non-existent pi_artifact: ${t.artifactId}`);let o=E5n(t.artifactId,t.channel);r.prepare("INSERT OR IGNORE INTO approvals (approval_id, artifact_id, channel, risk_level, status, confidence, requested_at, summary, trigger_reason, confidence_explanation, effect_description, rejection_effect) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(o,t.artifactId,t.channel,t.riskLevel,"pending",t.confidence??null,n,t.summary??null,t.triggerReason??null,t.confidenceExplanation??null,t.effectDescription??null,t.rejectionEffect??null);let a=r.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(o);if(!a)throw new Error("ApprovalQueue enqueue failed: no row found for "+o);return EX(a)}async getById(t){let r=this.connection.getDb().prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t);return r?EX(r):null}async listPending(t){let n=this.connection.getDb(),r="SELECT * FROM approvals WHERE status = 'pending'",i=[];return t?.channel&&(r+=" AND channel = ?",i.push(t.channel)),t?.riskLevel&&(r+=" AND risk_level = ?",i.push(t.riskLevel)),n.prepare(r).all(...i).map(EX)}async listAll(t){let n=this.connection.getDb(),r=[],i=[];t?.status&&(r.push("status = ?"),i.push(t.status)),t?.channel&&(r.push("channel = ?"),i.push(t.channel));let o="SELECT * FROM approvals";r.length>0&&(o+=" WHERE "+r.join(" AND ")),o+=" ORDER BY requested_at DESC";let a=t?.page??1,s=t?.pageSize??0;if(s>0){let u=(a-1)*s;o+=" LIMIT ? OFFSET ?",i.push(s,u)}return n.prepare(o).all(...i).map(EX)}async countByStatus(){let n=this.connection.getDb().prepare("SELECT status, COUNT(*) as cnt FROM approvals GROUP BY status").all(),r={pending:0,approved:0,rejected:0,cancelled:0};for(let i of n)V0t(i.status)&&(r[i.status]=i.cnt);return r}async approve(t,n,r,i){let o=this.connection.getDb(),a=new Date().toISOString();o.exec("BEGIN IMMEDIATE");try{let s=o.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);if(s===void 0)return o.exec("COMMIT"),{ok:!1,error:"not_found"};if(!zbe(s)||typeof s.status!="string"||!V0t(s.status))throw new Error(`ApprovalQueue approve failed: malformed decision status for ${t}`);if(s.status!=="pending")return o.exec("COMMIT"),{ok:!1,error:"already_decided",status:s.status};let c=DW(o.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t));if(!c)throw new Error(`ApprovalQueue approve failed: malformed row for ${t}`);let u=o.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId);if(!Vbe(u)){if(i)return o.exec("COMMIT"),zP();throw new Error(`ApprovalQueue approve failed: current PI artifact snapshot is missing or malformed for ${c.artifactId}`)}if(i&&!vX(c,up(u),i))return o.exec("COMMIT"),zP();let l=Pg(up(u)),p=DW(o.prepare("UPDATE approvals SET status = 'approved', decided_at = ?, decided_by = ?, decision_note = ?, artifact_digest = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(a,n,r??null,l,t));if(!p)throw new Error(`ApprovalQueue approve failed: pending decision disappeared for ${t}`);return o.exec("COMMIT"),{ok:!0,record:p}}catch(s){try{o.exec("ROLLBACK")}catch{}throw s}}async reject(t,n,r,i){return i?this.guardedMutation({approvalId:t,guard:i,allowMissing:!0,mutate:()=>this.rejectUnchecked(t,n,r)}):this.rejectUnchecked(t,n,r)}rejectUnchecked(t,n,r){let i=this.connection.getDb(),o=new Date().toISOString(),a=DW(i.prepare("UPDATE approvals SET status = 'rejected', decided_at = ?, decided_by = ?, rejection_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(o,n,r,t));if(!a){let s=i.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return s?{ok:!1,error:"already_decided",status:s.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:a}}async resetToPending(t){let n=this.connection.getDb(),r=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return r?r.status!=="approved"?{ok:!1,error:"not_approved"}:(n.prepare("UPDATE approvals SET status = 'pending', decided_at = NULL, decided_by = NULL, decision_note = NULL, artifact_digest = NULL WHERE approval_id = ? AND status = 'approved'").run(t),{ok:!0}):{ok:!1,error:"not_found"}}async edit(t){return t.expectedReview?this.guardedMutation({approvalId:t.approvalId,guard:t.expectedReview,allowMissing:!1,mutate:()=>this.editUnchecked(t),newArtifactId:t.newArtifactId,expectedNewArtifactDigest:t.expectedNewArtifactDigest}):this.editUnchecked(t)}editUnchecked(t){let n=this.connection.getDb(),r=DW(n.prepare("UPDATE approvals SET previous_artifact_id = artifact_id, artifact_id = ?, artifact_digest = NULL, edited_at = ?, edited_by = ?, edit_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(t.newArtifactId,t.now,t.editedBy,t.editReason,t.approvalId));if(!r){let i=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t.approvalId);return i?{ok:!1,error:"already_decided",status:i.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:r}}guardedMutation(t){let{approvalId:n,guard:r,allowMissing:i,mutate:o,newArtifactId:a}=t,s=this.connection.getDb();s.exec("BEGIN IMMEDIATE");try{let c=DW(s.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(n)),u;if(!c)u={ok:!1,error:"not_found"};else if(c.status!=="pending")u={ok:!1,error:"already_decided",status:c.status};else{let l=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId),p=Vbe(l)?up(l):null;if(l!==void 0&&p===null||!vX(c,p,r,i))u=zP();else if(a!==void 0){let f=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(a);u=p!==null&&Vbe(f)&&f.validation_status==="validated"&&Pg(up(f))===t.expectedNewArtifactDigest&&Fm(up(f),p)?o():zP()}else u=o()}return s.exec("COMMIT"),u}catch(c){try{s.exec("ROLLBACK")}catch{}throw c}}};import{createHash as x5n}from"node:crypto";var Xb=4e3;function PW(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function w5n(e){try{return JSON.parse(e)}catch{return null}}function LW(e){return e.filter(t=>t.channel==="prompt"&&t.action==="prompt_activate"&&t.deactivatedAt===null)}function JP(e,t){if(!PW(e))return{ok:!1,warning:`artifact_query_unexpected: artifactId=${t.artifactId}; nextAction=check_pi_artifacts_table`};let n=Object.hasOwn(e,"artifact_id")&&typeof e.artifact_id=="string"&&e.artifact_id.length>0?e.artifact_id:null,r=Object.hasOwn(e,"artifact_kind")&&typeof e.artifact_kind=="string"?e.artifact_kind:null,i=Object.hasOwn(e,"content_json")&&typeof e.content_json=="string"?e.content_json:null,o=Object.hasOwn(e,"validation_status")&&typeof e.validation_status=="string"?e.validation_status:null;if(!n)return{ok:!1,warning:`artifact_not_found: artifactId=${t.artifactId} activationId=${t.activationId}; nextAction=verify_artifact_exists_or_remove_stale_activation`};if(r!=="principle")return{ok:!1,warning:`artifact_not_principle: artifactId=${n} kind=${r??"missing"}; nextAction=skip_non_principle_activations`};if(o!=="validated")return{ok:!1,warning:`artifact_not_validated: artifactId=${n} status=${o??"missing"}; nextAction=skip_unvalidated_artifacts`};if(i===null)return{ok:!1,warning:`artifact_missing_content_json: artifactId=${n}; nextAction=ensure_artifact_has_content_json`};let a=w5n(i);if(a===null)return{ok:!1,warning:`artifact_content_json_parse_error: artifactId=${t.artifactId} reason=invalid_json; nextAction=fix_artifact_content_json`};if(!PW(a))return{ok:!1,warning:`artifact_content_malformed: artifactId=${t.artifactId} reason=parsed_to_non_object; nextAction=fix_artifact_content_json`};let s=Object.hasOwn(a,"principleId")&&typeof a.principleId=="string"?a.principleId:void 0,c=Object.hasOwn(a,"text")&&typeof a.text=="string"?a.text:void 0,u=Object.hasOwn(a,"principleDraft")&&PW(a.principleDraft)?a.principleDraft:null,l=u&&Object.hasOwn(u,"title")&&typeof u.title=="string"?u.title:void 0,p=u&&Object.hasOwn(u,"statement")&&typeof u.statement=="string"?u.statement:void 0,f=s&&s.length>0?s:l,m=c&&c.length>0?c:p;return!f||f.length===0?{ok:!1,warning:`artifact_missing_principle_id: artifactId=${t.artifactId}; nextAction=ensure_artifact_has_principleId_or_principleDraft_title`}:!m||m.length===0?{ok:!1,warning:`artifact_missing_text: artifactId=${t.artifactId} principleId=${f}; nextAction=ensure_artifact_has_text_or_principleDraft_statement`}:{ok:!0,principle:{principleId:f,text:m,artifactContentSha256:x5n("sha256").update(i,"utf8").digest("hex"),artifactId:t.artifactId,activationId:t.activationId}}}function z0t(){return["","## \u3010ACTIVE BEHAVIOR DIRECTIVES\u3011","",'Active behavior directives are operating constraints learned from prior owner corrections. Each directive carries its authorization: authority="owner" (approved in the owner approval queue) or authority="system_policy" (auto-activated by low-risk policy).',"These directives are mandatory for this session unless they conflict with safety, security, or higher-priority system policy.","For ambiguous coding or file-changing tasks, follow these directives before using mutating tools.",""]}function Y0t(e,t){let n=e.authority==="owner"||e.authority==="system_policy"?` authority="${e.authority}"`:"";return[`<directive id="${t(e.principleId)}" source="runtime_v2_activation"${n}>`,`MANDATORY: ${t(e.text)}`,"Apply this as an active behavior constraint. Do not treat this as background context.","</directive>",""]}function J0t(e){return e?["Self-report (OWNER visibility): when a directive above actually changes what you do in this turn, append exactly ONE line at the end of your reply in this format:","\u{1F4CC} \u5E94\u7528\u4E86\u4F60\u7684\u539F\u5219\u300C<directive id>\u300D\uFF1A<\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u4F60\u8FD9\u6B21\u505A\u6CD5\u6709\u4F55\u4E0D\u540C>","Use the directive's exact id attribute. At most one line per directive per session. Omit the line entirely if no directive changed your behavior.",""]:[]}function X0t(){return["Note: These directives do not override safety, security, or core system policy."]}function NW(e,t){let n=t?.escapeFn??(i=>i),r=Y0t(e,n);return r.reduce((i,o)=>i+o.length,0)+r.length}function xX(e){let t=[...z0t(),...J0t(e?.selfReportInstruction===!0),...X0t()];return t.reduce((n,r)=>n+r.length,0)+t.length-1}function Lg(e,t,n){if(t.size===0)return"";let r=n?.escapeFn??(o=>o),i=[...z0t()];for(let o of e)t.has(o.principleId)&&i.push(...Y0t(o,r));return i.push(...J0t(n?.selfReportInstruction===!0)),i.push(...X0t()),i.join(`
1946
+ `).run(n.decidedAt,n.subject.activationId,t.expectedControlVersion);if(l.changes!==1||p.changes!==1)throw new Error("Promotion state changed during atomic commit");return i.exec("COMMIT"),{activationId:n.subject.activationId,decisionId:n.decisionId,promotedAt:n.decidedAt}}catch(o){try{i.exec("ROLLBACK")}catch{}throw o}}};function _X(){return{consecutiveErrors:0,consecutiveBlocks:[],latestEligible:[]}}function IX(e,t){if(t.protectedCapabilityMatched)return{state:e,trip:"protected_capability_matched"};if(t.neutralProbeFailed)return{state:e,trip:"host_liveness_probe_failed"};if(t.healthFailure)return{state:e,trip:"runtime_health_failure"};let n=t.decision==="error"?e.consecutiveErrors+1:0,r=t.decision==="block"?[...e.consecutiveBlocks,{toolName:t.toolName}].slice(-5):[],i=[...e.latestEligible,{blocked:t.decision==="block",outsideApprovedScope:t.outsideApprovedScope}].slice(-20),o={consecutiveErrors:n,consecutiveBlocks:r,latestEligible:i};return n>=3?{state:o,trip:"three_consecutive_errors"}:r.length>=5&&new Set(r.map(a=>a.toolName)).size>=3?{state:o,trip:"broad_consecutive_blocking"}:i.length===20&&i.filter(a=>a.blocked&&a.outsideApprovedScope).length/20>.8?{state:o,trip:"outside_scope_block_ratio"}:{state:o,trip:null}}import{createHash as I5n,randomUUID as $Zi}from"node:crypto";function Pg(e){return`sha256:${I5n("sha256").update(JSON.stringify(e),"utf8").digest("hex")}`}function Yb(e,t,n){if(typeof n!="string"||n.length===0)return{outcome:"no_binding"};let r=e.artifact_id,i=e.artifact_kind,o=e.source_task_id,a=e.source_principle_id,s=e.source_rule_id,c=e.lineage_artifact_ids,u=e.validation_status,l=e.created_at,p=e.updated_at;if(!(typeof r=="string"&&r.length>0&&typeof i=="string"&&typeof o=="string"&&(typeof a=="string"||a===null)&&(typeof s=="string"||s===null)&&typeof c=="string"&&typeof u=="string"&&typeof l=="string"&&typeof p=="string"))return{outcome:"unverifiable",error:"artifact row integrity does not allow digest re-verification"};let m;try{m=Pg(up({artifact_id:r,artifact_kind:i,source_task_id:o,source_principle_id:a,source_rule_id:s,lineage_artifact_ids:c,validation_status:u,content_json:t,created_at:l,updated_at:p}))}catch(g){return{outcome:"unverifiable",error:g instanceof Error?g.message:String(g)}}return m!==n?{outcome:"tampered",actualDigest:m}:{outcome:"verified"}}en();po();var G0t={schemaVersion:d.Union([d.Literal("approval-review"),d.Literal("approval-review-v1")]),approvalId:d.String({minLength:1}),artifactId:d.String({minLength:1}),channel:d.Union([d.Literal("prompt"),d.Literal("skill"),d.Literal("code_tool_hook"),d.Literal("defer_archive")])},q0t=d.Union([d.Object({...G0t,artifactState:d.Literal("present"),artifactDigest:d.String({pattern:"^sha256:[a-f0-9]{64}$"})},{additionalProperties:!1}),d.Object({...G0t,artifactState:d.Literal("missing")},{additionalProperties:!1})]);function K0t(e){return nt.Check(q0t,e)}function vX(e,t,n,r=!1){return!K0t(n)||n.approvalId!==e.approvalId||n.artifactId!==e.artifactId||n.channel!==e.channel?!1:n.artifactState==="missing"?r&&t===null:t!==null&&t.artifactId===e.artifactId&&Pg(t)===n.artifactDigest}function zP(){return{ok:!1,error:"stale_review",reason:"The approval material or target changed after review.",nextAction:"Reload this approval and review the current material before deciding again."}}function zbe(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function Vbe(e){if(!zbe(e))return!1;let t=n=>e[n]===null||typeof e[n]=="string";if(typeof e.artifact_id!="string"||typeof e.artifact_kind!="string"||typeof e.source_task_id!="string"||!t("source_principle_id")||!t("source_rule_id")||typeof e.lineage_artifact_ids!="string"||typeof e.validation_status!="string"||typeof e.content_json!="string"||typeof e.created_at!="string"||typeof e.updated_at!="string")return!1;try{let n=JSON.parse(e.lineage_artifact_ids);return Array.isArray(n)&&n.every(r=>typeof r=="string")}catch{return!1}}function V0t(e){return e==="pending"||e==="approved"||e==="rejected"||e==="cancelled"}function YP(e,t){if(!Object.hasOwn(e,t))return null;let n=e[t];return typeof n=="string"?n:null}function Ml(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="string"?n:void 0}function v5n(e,t){if(!Object.hasOwn(e,t))return;let n=e[t];if(n!==null)return typeof n=="number"?n:void 0}function DW(e){if(!zbe(e))return null;let t=YP(e,"approval_id"),n=YP(e,"artifact_id"),r=YP(e,"channel"),i=YP(e,"risk_level"),o=YP(e,"status"),a=YP(e,"requested_at");return!t||!n||!r||!i||!o||!a?null:{approvalId:t,artifactId:n,artifactDigest:Ml(e,"artifact_digest"),channel:r,riskLevel:i,status:o,confidence:v5n(e,"confidence"),requestedAt:a,decidedAt:Ml(e,"decided_at"),decidedBy:Ml(e,"decided_by"),decisionNote:Ml(e,"decision_note"),rejectionReason:Ml(e,"rejection_reason"),summary:Ml(e,"summary"),triggerReason:Ml(e,"trigger_reason"),confidenceExplanation:Ml(e,"confidence_explanation"),effectDescription:Ml(e,"effect_description"),rejectionEffect:Ml(e,"rejection_effect"),editedAt:Ml(e,"edited_at"),editedBy:Ml(e,"edited_by"),editReason:Ml(e,"edit_reason"),previousArtifactId:Ml(e,"previous_artifact_id")}}function EX(e){return{approvalId:e.approval_id,artifactId:e.artifact_id,artifactDigest:e.artifact_digest??void 0,channel:e.channel,riskLevel:e.risk_level,status:e.status,confidence:e.confidence??void 0,requestedAt:e.requested_at,decidedAt:e.decided_at??void 0,decidedBy:e.decided_by??void 0,decisionNote:e.decision_note??void 0,rejectionReason:e.rejection_reason??void 0,summary:e.summary??void 0,triggerReason:e.trigger_reason??void 0,confidenceExplanation:e.confidence_explanation??void 0,effectDescription:e.effect_description??void 0,rejectionEffect:e.rejection_effect??void 0,editedAt:e.edited_at??void 0,editedBy:e.edited_by??void 0,editReason:e.edit_reason??void 0,previousArtifactId:e.previous_artifact_id??void 0}}function E5n(e,t){return"apr_"+t+"_"+e}var Jb=class{connection;constructor(t){this.connection=t}async enqueue(t,n){let r=this.connection.getDb();if(!r.prepare("SELECT 1 FROM pi_artifacts WHERE artifact_id = ?").get(t.artifactId))throw new Error(`approvals.artifact_id references non-existent pi_artifact: ${t.artifactId}`);let o=E5n(t.artifactId,t.channel);r.prepare("INSERT OR IGNORE INTO approvals (approval_id, artifact_id, channel, risk_level, status, confidence, requested_at, summary, trigger_reason, confidence_explanation, effect_description, rejection_effect) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)").run(o,t.artifactId,t.channel,t.riskLevel,"pending",t.confidence??null,n,t.summary??null,t.triggerReason??null,t.confidenceExplanation??null,t.effectDescription??null,t.rejectionEffect??null);let a=r.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(o);if(!a)throw new Error("ApprovalQueue enqueue failed: no row found for "+o);return EX(a)}async getById(t){let r=this.connection.getDb().prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t);return r?EX(r):null}async listPending(t){let n=this.connection.getDb(),r="SELECT * FROM approvals WHERE status = 'pending'",i=[];return t?.channel&&(r+=" AND channel = ?",i.push(t.channel)),t?.riskLevel&&(r+=" AND risk_level = ?",i.push(t.riskLevel)),n.prepare(r).all(...i).map(EX)}async listAll(t){let n=this.connection.getDb(),r=[],i=[];t?.status&&(r.push("status = ?"),i.push(t.status)),t?.channel&&(r.push("channel = ?"),i.push(t.channel));let o="SELECT * FROM approvals";r.length>0&&(o+=" WHERE "+r.join(" AND ")),o+=" ORDER BY requested_at DESC";let a=t?.page??1,s=t?.pageSize??0;if(s>0){let u=(a-1)*s;o+=" LIMIT ? OFFSET ?",i.push(s,u)}return n.prepare(o).all(...i).map(EX)}async countByStatus(){let n=this.connection.getDb().prepare("SELECT status, COUNT(*) as cnt FROM approvals GROUP BY status").all(),r={pending:0,approved:0,rejected:0,cancelled:0};for(let i of n)V0t(i.status)&&(r[i.status]=i.cnt);return r}async approve(t,n,r,i){let o=this.connection.getDb(),a=new Date().toISOString();o.exec("BEGIN IMMEDIATE");try{let s=o.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);if(s===void 0)return o.exec("COMMIT"),{ok:!1,error:"not_found"};if(!zbe(s)||typeof s.status!="string"||!V0t(s.status))throw new Error(`ApprovalQueue approve failed: malformed decision status for ${t}`);if(s.status!=="pending")return o.exec("COMMIT"),{ok:!1,error:"already_decided",status:s.status};let c=DW(o.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(t));if(!c)throw new Error(`ApprovalQueue approve failed: malformed row for ${t}`);let u=o.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId);if(!Vbe(u)){if(i)return o.exec("COMMIT"),zP();throw new Error(`ApprovalQueue approve failed: current PI artifact snapshot is missing or malformed for ${c.artifactId}`)}if(i&&!vX(c,up(u),i))return o.exec("COMMIT"),zP();let l=Pg(up(u)),p=DW(o.prepare("UPDATE approvals SET status = 'approved', decided_at = ?, decided_by = ?, decision_note = ?, artifact_digest = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(a,n,r??null,l,t));if(!p)throw new Error(`ApprovalQueue approve failed: pending decision disappeared for ${t}`);return o.exec("COMMIT"),{ok:!0,record:p}}catch(s){try{o.exec("ROLLBACK")}catch{}throw s}}async reject(t,n,r,i){return i?this.guardedMutation({approvalId:t,guard:i,allowMissing:!0,mutate:()=>this.rejectUnchecked(t,n,r)}):this.rejectUnchecked(t,n,r)}rejectUnchecked(t,n,r){let i=this.connection.getDb(),o=new Date().toISOString(),a=DW(i.prepare("UPDATE approvals SET status = 'rejected', decided_at = ?, decided_by = ?, rejection_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(o,n,r,t));if(!a){let s=i.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return s?{ok:!1,error:"already_decided",status:s.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:a}}async resetToPending(t){let n=this.connection.getDb(),r=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t);return r?r.status!=="approved"?{ok:!1,error:"not_approved"}:(n.prepare("UPDATE approvals SET status = 'pending', decided_at = NULL, decided_by = NULL, decision_note = NULL, artifact_digest = NULL WHERE approval_id = ? AND status = 'approved'").run(t),{ok:!0}):{ok:!1,error:"not_found"}}async edit(t){return t.expectedReview?this.guardedMutation({approvalId:t.approvalId,guard:t.expectedReview,allowMissing:!1,mutate:()=>this.editUnchecked(t),newArtifactId:t.newArtifactId,expectedNewArtifactDigest:t.expectedNewArtifactDigest}):this.editUnchecked(t)}editUnchecked(t){let n=this.connection.getDb(),r=DW(n.prepare("UPDATE approvals SET previous_artifact_id = artifact_id, artifact_id = ?, artifact_digest = NULL, edited_at = ?, edited_by = ?, edit_reason = ? WHERE approval_id = ? AND status = 'pending' RETURNING *").get(t.newArtifactId,t.now,t.editedBy,t.editReason,t.approvalId));if(!r){let i=n.prepare("SELECT status FROM approvals WHERE approval_id = ?").get(t.approvalId);return i?{ok:!1,error:"already_decided",status:i.status}:{ok:!1,error:"not_found"}}return{ok:!0,record:r}}guardedMutation(t){let{approvalId:n,guard:r,allowMissing:i,mutate:o,newArtifactId:a}=t,s=this.connection.getDb();s.exec("BEGIN IMMEDIATE");try{let c=DW(s.prepare("SELECT * FROM approvals WHERE approval_id = ?").get(n)),u;if(!c)u={ok:!1,error:"not_found"};else if(c.status!=="pending")u={ok:!1,error:"already_decided",status:c.status};else{let l=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(c.artifactId),p=Vbe(l)?up(l):null;if(l!==void 0&&p===null||!vX(c,p,r,i))u=zP();else if(a!==void 0){let f=s.prepare("SELECT * FROM pi_artifacts WHERE artifact_id = ?").get(a);u=p!==null&&Vbe(f)&&f.validation_status==="validated"&&Pg(up(f))===t.expectedNewArtifactDigest&&Fm(up(f),p)?o():zP()}else u=o()}return s.exec("COMMIT"),u}catch(c){try{s.exec("ROLLBACK")}catch{}throw c}}};import{createHash as x5n}from"node:crypto";var Xb=4e3;function PW(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function w5n(e){try{return JSON.parse(e)}catch{return null}}function LW(e){return e.filter(t=>t.channel==="prompt"&&t.action==="prompt_activate"&&t.deactivatedAt===null)}function JP(e,t){if(!PW(e))return{ok:!1,warning:`artifact_query_unexpected: artifactId=${t.artifactId}; nextAction=check_pi_artifacts_table`};let n=Object.hasOwn(e,"artifact_id")&&typeof e.artifact_id=="string"&&e.artifact_id.length>0?e.artifact_id:null,r=Object.hasOwn(e,"artifact_kind")&&typeof e.artifact_kind=="string"?e.artifact_kind:null,i=Object.hasOwn(e,"content_json")&&typeof e.content_json=="string"?e.content_json:null,o=Object.hasOwn(e,"validation_status")&&typeof e.validation_status=="string"?e.validation_status:null;if(!n)return{ok:!1,warning:`artifact_not_found: artifactId=${t.artifactId} activationId=${t.activationId}; nextAction=verify_artifact_exists_or_remove_stale_activation`};if(r!=="principle")return{ok:!1,warning:`artifact_not_principle: artifactId=${n} kind=${r??"missing"}; nextAction=skip_non_principle_activations`};if(o!=="validated")return{ok:!1,warning:`artifact_not_validated: artifactId=${n} status=${o??"missing"}; nextAction=skip_unvalidated_artifacts`};if(i===null)return{ok:!1,warning:`artifact_missing_content_json: artifactId=${n}; nextAction=ensure_artifact_has_content_json`};let a=w5n(i);if(a===null)return{ok:!1,warning:`artifact_content_json_parse_error: artifactId=${t.artifactId} reason=invalid_json; nextAction=fix_artifact_content_json`};if(!PW(a))return{ok:!1,warning:`artifact_content_malformed: artifactId=${t.artifactId} reason=parsed_to_non_object; nextAction=fix_artifact_content_json`};let s=Object.hasOwn(a,"principleId")&&typeof a.principleId=="string"?a.principleId:void 0,c=Object.hasOwn(a,"text")&&typeof a.text=="string"?a.text:void 0,u=Object.hasOwn(a,"principleDraft")&&PW(a.principleDraft)?a.principleDraft:null,l=u&&Object.hasOwn(u,"title")&&typeof u.title=="string"?u.title:void 0,p=u&&Object.hasOwn(u,"statement")&&typeof u.statement=="string"?u.statement:void 0,f=s&&s.length>0?s:l,m=c&&c.length>0?c:p;return!f||f.length===0?{ok:!1,warning:`artifact_missing_principle_id: artifactId=${t.artifactId}; nextAction=ensure_artifact_has_principleId_or_principleDraft_title`}:!m||m.length===0?{ok:!1,warning:`artifact_missing_text: artifactId=${t.artifactId} principleId=${f}; nextAction=ensure_artifact_has_text_or_principleDraft_statement`}:{ok:!0,principle:{principleId:f,text:m,artifactContentSha256:x5n("sha256").update(i,"utf8").digest("hex"),artifactId:t.artifactId,activationId:t.activationId}}}function z0t(){return["","## \u3010ACTIVE BEHAVIOR DIRECTIVES\u3011","",'Active behavior directives are operating constraints learned from prior owner corrections. Each directive carries its authorization: authority="owner" (approved in the owner approval queue) or authority="system_policy" (auto-activated by low-risk policy).',"These directives are mandatory active behavior constraints for this session, not background context, unless they conflict with safety, security, or higher-priority system policy.","For ambiguous coding or file-changing tasks, follow these directives before using mutating tools.",""]}function Y0t(e,t){let n=e.authority==="owner"||e.authority==="system_policy"?` authority="${e.authority}"`:"";return[`<directive id="${t(e.principleId)}" source="runtime_v2_activation"${n}>`,`MANDATORY: ${t(e.text)}`,"</directive>",""]}function J0t(e){return e?["Self-report (OWNER visibility): when a directive above actually changes what you do in this turn, append exactly ONE line at the end of your reply in this format:","\u{1F4CC} \u5E94\u7528\u4E86\u4F60\u7684\u539F\u5219\u300C<directive id>\u300D\uFF1A<\u7528\u4E00\u53E5\u8BDD\u8BF4\u660E\u4F60\u8FD9\u6B21\u505A\u6CD5\u6709\u4F55\u4E0D\u540C>","Use the directive's exact id attribute. At most one line per directive per session. Omit the line entirely if no directive changed your behavior.",""]:[]}function X0t(){return["Note: These directives do not override safety, security, or core system policy."]}function NW(e,t){let n=t?.escapeFn??(i=>i),r=Y0t(e,n);return r.reduce((i,o)=>i+o.length,0)+r.length}function xX(e){let t=[...z0t(),...J0t(e?.selfReportInstruction===!0),...X0t()];return t.reduce((n,r)=>n+r.length,0)+t.length-1}function Lg(e,t,n){if(t.size===0)return"";let r=n?.escapeFn??(o=>o),i=[...z0t()];for(let o of e)t.has(o.principleId)&&i.push(...Y0t(o,r));return i.push(...J0t(n?.selfReportInstruction===!0)),i.push(...X0t()),i.join(`
1947
1947
  `)}var pv="model_aware",Xbe=4e3,Zbe=128e3,MW=1250,BW=32e3,XP=Xb,Z0t=7e3,e_t=XP+Z0t;function ZP(e){return e+Z0t}var eS=1024,tS=1e8,eSe=new Set(["model","modelsConfig","agentContextTokens"]);function fv(e){return typeof e=="number"&&Number.isInteger(e)&&e>=eS&&e<=tS}function Zb(e){if(!fv(e))return XP;let t=Math.floor(Xbe*e/Zbe);return Math.min(BW,Math.max(MW,t))}function Ybe(e){return{budgetChars:XP,capacitySource:"legacy_fallback",capacityStatus:"unknown",contextWindowTokens:null,policyVersion:pv,fallbackReason:e.reason,fallbackDetail:e.detail}}function Jbe(e){return typeof e=="string"&&e.length>0?e:void 0}function wX(e,t){let n=t.skipReason===null?"host_capacity_absent":t.skipReason,r=(l,p)=>Ybe({reason:t.skipReason??l,detail:`${n};${l}:${p}`}),i=e?.catalog,o=Jbe(e?.modelIdentity?.modelId),a=Jbe(e?.modelIdentity?.providerId);if(i===void 0)return t.skipReason===null&&o===void 0?Ybe({reason:"host_capacity_absent",detail:"host_capacity_absent;no-facts-at-all"}):r("catalog_unavailable","no-catalog-binding");if(o===void 0)return t.skipReason===null?Ybe({reason:"host_capacity_absent",detail:"host_capacity_absent;no-model-context"}):r("model_identity_absent","no-model-id");if(a!==void 0){let l=i.exact(a,o);return l===void 0?r("catalog_no_exact_match",`${a}/${o}`):fv(l.contextWindowTokens)?{budgetChars:Zb(l.contextWindowTokens),capacitySource:"pi_catalog_exact",capacityStatus:"confirmed",contextWindowTokens:l.contextWindowTokens,policyVersion:pv}:r("catalog_metadata_invalid",`${a}/${o}`)}let s=i.byModelId(o);if(s.length===0)return r("catalog_no_match_for_model_id",o);let[c]=s;return c===void 0||!s.every(l=>fv(l.contextWindowTokens))?r("catalog_metadata_invalid",o):s.every(l=>l.contextWindowTokens===c.contextWindowTokens)?{budgetChars:Zb(c.contextWindowTokens),capacitySource:"pi_catalog_model_id",capacityStatus:"confirmed",contextWindowTokens:c.contextWindowTokens,policyVersion:pv}:r("catalog_ambiguous_model_id",o)}function mv(e){let t=e?.operatorDeclared?.contextWindowTokens;if(t!==void 0&&fv(t))return{budgetChars:Zb(t),capacitySource:"operator_declared",capacityStatus:"confirmed",contextWindowTokens:t,policyVersion:pv};let n=e?.hostCapacity;if(n!==void 0){let r=n.contextTokenBudget!==void 0,i=n.contextWindowSource!==void 0;if(!r&&!i)return wX(e,{skipReason:null,detail:"host_capacity_absent"});let o=Jbe(n.contextWindowSource);if(!(o!==void 0&&eSe.has(o)))return wX(e,{skipReason:"host_capacity_source_untrusted",detail:`host_capacity_source_untrusted:${o??"absent"}`});if(!fv(n.contextTokenBudget))return wX(e,{skipReason:"host_capacity_invalid_value",detail:"host_capacity_invalid_value"});let s=n.contextTokenBudget;return{budgetChars:Zb(s),capacitySource:"host_effective_window",capacityStatus:"confirmed",contextWindowTokens:s,policyVersion:pv}}return wX(e,{skipReason:null,detail:"host_capacity_absent"})}import Qeo from"better-sqlite3";import Keo from"better-sqlite3";import eto from"better-sqlite3";en();function hv(e){if(!e||typeof e!="object")return!1;let t=e,n=["high","medium","low"];if(typeof t.confidence!="string"||!n.includes(t.confidence))return!1;let r=o=>Array.isArray(o)&&o.length>0&&o.every(a=>typeof a=="string"&&a.length>0),i=o=>Array.isArray(o)&&o.every(a=>Array.isArray(a)&&a.every(s=>typeof s=="string"));return r(t.applicabilityTags)&&r(t.positiveSignals)&&r(t.negativeSignals)&&i(t.toolSequenceHints)}var bX=d.Union([d.Literal("candidate"),d.Literal("probation"),d.Literal("active"),d.Literal("deprecated"),d.Literal("archived")]),rSe=d.Union([d.Literal("deterministic"),d.Literal("weak_heuristic"),d.Literal("manual_only")]);var iSe=d.Object({applicabilityTags:d.Array(d.String()),positiveSignals:d.Array(d.String()),negativeSignals:d.Array(d.String()),toolSequenceHints:d.Array(d.Array(d.String())),confidence:d.Union([d.Literal("high"),d.Literal("medium"),d.Literal("low")])}),n_t=d.Object({name:d.String(),type:d.Union([d.Literal("hook"),d.Literal("gate"),d.Literal("skill"),d.Literal("test"),d.Literal("prompt")]),triggerCondition:d.String(),enforcement:d.Union([d.Literal("block"),d.Literal("warn"),d.Literal("log")]),action:d.String(),implementationHint:d.Optional(d.String())}),r_t=d.Object({painPreventedCount:d.Number(),lastPainPreventedAt:d.Optional(d.String()),calculatedAt:d.String()}),V5n=d.Object({id:d.String(),version:d.Number(),text:d.String(),source:d.Object({painId:d.String(),painType:d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")]),timestamp:d.String()}),trigger:d.String(),action:d.String(),guardrails:d.Optional(d.Array(d.String())),contextTags:d.Array(d.String()),validation:d.Object({successCount:d.Number(),conflictCount:d.Number()}),status:bX,feedbackScore:d.Number(),usageCount:d.Number(),createdAt:d.String(),activatedAt:d.Optional(d.String()),deprecatedAt:d.Optional(d.String()),evaluability:rSe,detectorMetadata:d.Optional(iSe),abstractedPrinciple:d.Optional(d.String()),coreAxiomId:d.Optional(d.String()),priority:d.Optional(d.Union([d.Literal("P0"),d.Literal("P1"),d.Literal("P2")])),scope:d.Optional(d.Union([d.Literal("general"),d.Literal("domain")])),domain:d.Optional(d.String()),suggestedRules:d.Optional(d.Array(n_t)),valueMetrics:d.Optional(r_t)}),z5n=d.Union([d.Literal("pain_detected"),d.Literal("candidate_created"),d.Literal("principle_promoted"),d.Literal("principle_deprecated"),d.Literal("principle_rolled_back"),d.Literal("circuit_breaker_opened"),d.Literal("legacy_import")]),nSe=d.Object({painId:d.String(),painType:d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")]),source:d.String(),reason:d.String(),score:d.Optional(d.Number()),sessionId:d.Optional(d.String()),agentId:d.Optional(d.String()),taskId:d.Optional(d.String()),traceId:d.Optional(d.String()),provenance:d.Optional(d.Union([d.Literal("host_context_bound"),d.Literal("owner_reported_no_host_trace"),d.Literal("automatic_hook"),d.Literal("openclaw_context_bound")])),hostKind:d.Optional(d.Union([d.Literal("openclaw"),d.Literal("codex"),d.Literal("workbuddy")]))}),i_t=d.Object({painId:d.String(),principleId:d.String(),trigger:d.String(),action:d.String(),status:d.Literal("candidate"),painType:d.Optional(d.Union([d.Literal("tool_failure"),d.Literal("dispatch_error"),d.Literal("subagent_error"),d.Literal("user_frustration")])),evaluability:d.Optional(rSe),detectorMetadata:d.Optional(iSe),abstractedPrinciple:d.Optional(d.String()),coreAxiomId:d.Optional(d.String())}),o_t=d.Object({principleId:d.String(),from:bX,to:bX,reason:d.String(),successCount:d.Optional(d.Number())}),a_t=d.Object({principleId:d.String(),reason:d.String(),triggeredBy:d.Union([d.Literal("auto"),d.Literal("manual")])}),s_t=d.Object({principleId:d.String(),reason:d.String(),triggeredBy:d.Union([d.Literal("user_command"),d.Literal("auto_conflict")]),blacklistPattern:d.Optional(d.String()),relatedPainId:d.Optional(d.String())}),c_t=d.Object({taskId:d.String(),painId:d.String(),failCount:d.Number(),reason:d.String(),requireHuman:d.Boolean(),nextRetryAt:d.Optional(d.String())}),u_t=d.Object({sourceFile:d.String(),content:d.String(),contentHash:d.Optional(d.String())}),Y5n=d.Union([d.Object({ts:d.String(),type:d.Literal("pain_detected"),data:nSe}),d.Object({ts:d.String(),type:d.Literal("pain_recorded"),data:nSe}),d.Object({ts:d.String(),type:d.Literal("candidate_created"),data:i_t}),d.Object({ts:d.String(),type:d.Literal("principle_promoted"),data:o_t}),d.Object({ts:d.String(),type:d.Literal("principle_deprecated"),data:a_t}),d.Object({ts:d.String(),type:d.Literal("principle_rolled_back"),data:s_t}),d.Object({ts:d.String(),type:d.Literal("circuit_breaker_opened"),data:c_t}),d.Object({ts:d.String(),type:d.Literal("legacy_import"),data:u_t})]);en();var eL=200,tL=[{term:"\u4E0D\u662F\u8FD9\u4E2A",weight:.6,source:"seed",addedAt:""},{term:"\u4E0D\u5BF9",weight:.5,source:"seed",addedAt:""},{term:"\u9519\u4E86",weight:.5,source:"seed",addedAt:""},{term:"\u641E\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u7406\u89E3\u9519\u4E86",weight:.7,source:"seed",addedAt:""},{term:"\u4F60\u7406\u89E3\u9519\u4E86",weight:.8,source:"seed",addedAt:""},{term:"\u91CD\u65B0\u6765",weight:.6,source:"seed",addedAt:""},{term:"\u518D\u8BD5\u4E00\u6B21",weight:.4,source:"seed",addedAt:""},{term:"you are wrong",weight:.7,source:"seed",addedAt:""},{term:"wrong file",weight:.6,source:"seed",addedAt:""},{term:"not this",weight:.4,source:"seed",addedAt:""},{term:"redo",weight:.6,source:"seed",addedAt:""},{term:"try again",weight:.4,source:"seed",addedAt:""},{term:"again",weight:.3,source:"seed",addedAt:""},{term:"please redo",weight:.6,source:"seed",addedAt:""},{term:"please try again",weight:.5,source:"seed",addedAt:""}],l_t=d.Object({term:d.String(),weight:d.Number(),source:d.Union([d.Literal("seed"),d.Literal("llm"),d.Literal("user")]),addedAt:d.String(),hitCount:d.Optional(d.Number({minimum:0})),truePositiveCount:d.Optional(d.Number({minimum:0})),falsePositiveCount:d.Optional(d.Number({minimum:0})),lastHitAt:d.Optional(d.String())}),J5n=d.Object({keywords:d.Array(l_t),version:d.Integer({minimum:0}),lastOptimizedAt:d.String()});var FW=class{registry=new Map;register(t){this.registry.set(t.agentId,t)}async dispatch(t,n){let r=this.registry.get(t);if(!r)throw new Error(`Agent ${t} is not registered in AgentScheduler`);return r.runner.run(n)}getRegisteredAgents(){return Array.from(this.registry.values()).map(t=>({agentId:t.agentId,mode:t.mode}))}};function gv(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function Ng(e){return typeof e=="string"}function SX(e){return typeof e=="boolean"}function $m(e){return typeof e=="number"&&Number.isFinite(e)}function er(e,t){return{path:e,message:t}}function Gn(e,t){return Object.hasOwn(e,t)?e[t]:void 0}var gHn=new Set(["info","warning","error","fatal"]);function AHn(e,t){let n=[];return Gn(e,"gate")!==void 0&&n.push(er(`${t}.gate`,"deprecated: the built-in PLAN/confirm-first gate was removed (PRI-286); this key has no effect and can be deleted")),(Gn(e,"progressive_gate")!==void 0||Gn(e,"progressiveGate")!==void 0)&&n.push(er(`${t}.progressive_gate`,"deprecated: plan-approval gating was removed (PRI-286); this key has no effect and can be deleted")),Gn(e,"progressiveGate")!==void 0&&n.push(er(`${t}.progressiveGate`,"deprecated: plan-approval gating was removed (PRI-286); legacy camelCase alias, this key has no effect and can be deleted")),(Gn(e,"thinking_checkpoint")!==void 0||Gn(e,"thinkingCheckpoint")!==void 0)&&n.push(er(`${t}.thinking_checkpoint`,"deprecated: the thinking-checkpoint gate is retired; this key has no effect and can be deleted")),Gn(e,"thinkingCheckpoint")!==void 0&&n.push(er(`${t}.thinkingCheckpoint`,"deprecated: the thinking-checkpoint gate is retired; legacy camelCase alias, this key has no effect and can be deleted")),n}function yHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`tests must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"on_change");i!==void 0&&(Ng(i)&&HC.includes(i)?r.on_change=i:n.push(er(`${t}.on_change`,`must be one of: ${HC.join(", ")}`)));let o=Gn(e,"on_risk_change");o!==void 0&&(Ng(o)&&HC.includes(o)?r.on_risk_change=o:n.push(er(`${t}.on_risk_change`,`must be one of: ${HC.join(", ")}`)));let a=Gn(e,"commands");if(a!==void 0)if(gv(a)){let s={};for(let c of Object.keys(a)){let u=a[c];Ng(u)?s[c]=u:n.push(er(`${t}.commands.${c}`,"command value must be a string"))}r.commands=s}else n.push(er(`${t}.commands`,"must be an object (string\u2192string map)"));return{value:r,warnings:n}}function _Hn(e,t){let n=[];if(!gv(e))return n.push(er(t,`adaptive must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"spiral_boost");o!==void 0&&($m(o)?r.spiral_boost=o:n.push(er(`${t}.spiral_boost`,"must be a finite number")));let a=Gn(e,"min_threshold");a!==void 0&&($m(a)?r.min_threshold=a:n.push(er(`${t}.min_threshold`,"must be a finite number")));let s=Gn(e,"max_threshold");s!==void 0&&($m(s)?r.max_threshold=s:n.push(er(`${t}.max_threshold`,"must be a finite number")));let c=Gn(e,"backlog_trigger");c!==void 0&&($m(c)?r.backlog_trigger=c:n.push(er(`${t}.backlog_trigger`,"must be a finite number")));let u=Gn(e,"hard_failure_trigger");u!==void 0&&($m(u)?r.hard_failure_trigger=u:n.push(er(`${t}.hard_failure_trigger`,"must be a finite number")));let l=Gn(e,"low_recent_success_boost");l!==void 0&&($m(l)?r.low_recent_success_boost=l:n.push(er(`${t}.low_recent_success_boost`,"must be a finite number")));let p=Gn(e,"high_recent_pain_boost");return p!==void 0&&($m(p)?r.high_recent_pain_boost=p:n.push(er(`${t}.high_recent_pain_boost`,"must be a finite number"))),{value:r,warnings:n}}function IHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`pain must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"soft_capture_threshold");i!==void 0&&($m(i)?r.soft_capture_threshold=i:n.push(er(`${t}.soft_capture_threshold`,"must be a finite number")));let o=Gn(e,"adaptive");if(o!==void 0){let a=_Hn(o,`${t}.adaptive`);a.value&&(r.adaptive=a.value),n.push(...a.warnings)}return{value:r,warnings:n}}function vHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`lifecycle must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"heartbeat_stale_hours");return o!==void 0&&($m(o)?r.heartbeat_stale_hours=o:n.push(er(`${t}.heartbeat_stale_hours`,"must be a finite number"))),{value:r,warnings:n}}function EHn(e,t){let n=[];if(!gv(e))return n.push(er(t,`edit_verification must be an object, got ${typeof e}`)),{warnings:n};let r={},i=Gn(e,"enabled");i!==void 0&&(SX(i)?r.enabled=i:n.push(er(`${t}.enabled`,"must be boolean")));let o=Gn(e,"max_file_size_bytes");o!==void 0&&($m(o)&&o>=0?r.max_file_size_bytes=o:n.push(er(`${t}.max_file_size_bytes`,"must be a non-negative number")));let a=Gn(e,"fuzzy_match_enabled");a!==void 0&&(SX(a)?r.fuzzy_match_enabled=a:n.push(er(`${t}.fuzzy_match_enabled`,"must be boolean")));let s=Gn(e,"fuzzy_match_threshold");s!==void 0&&($m(s)&&s>0&&s<=1?r.fuzzy_match_threshold=s:n.push(er(`${t}.fuzzy_match_threshold`,"must be a number in (0, 1]")));let c=Gn(e,"skip_large_file_action");return c!==void 0&&(c==="warn"||c==="block"?r.skip_large_file_action=c:n.push(er(`${t}.skip_large_file_action`,'must be "warn" or "block"'))),{value:r,warnings:n}}function xHn(e,t){let n=[];if(!Array.isArray(e))return n.push(er(t,`custom_guards must be an array, got ${typeof e}`)),{warnings:n};let r=[];for(let i=0;i<e.length;i++){let o=e[i];if(!gv(o)){n.push(er(`${t}[${i}]`,"must be an object"));continue}let a=Gn(o,"pattern"),s=Gn(o,"message"),c=Gn(o,"severity");if(!Ng(a)||a.length===0){n.push(er(`${t}[${i}].pattern`,"must be a non-empty string"));continue}r.push({pattern:a,message:Ng(s)?s:"Custom guard triggered",severity:Ng(c)&&gHn.has(c.toLowerCase())?c.toLowerCase():"error"})}return{value:r,warnings:n}}function oSe(e,t="profile"){let n=[];if(!gv(e))return{ok:!1,errors:[er(t,`profile must be an object, got ${typeof e}`)]};let r={},i=Gn(e,"audit_level");i!==void 0&&(Ng(i)&&Qj.includes(i)?r.audit_level=i:n.push(er(`${t}.audit_level`,`must be one of: ${Qj.join(", ")}, got ${JSON.stringify(i)}`)));let o=Gn(e,"evolution_mode");o!==void 0&&(Ng(o)&&Wj.includes(o)?r.evolution_mode=o:n.push(er(`${t}.evolution_mode`,`must be one of: ${Wj.join(", ")}, got ${JSON.stringify(o)}`)));let a=Gn(e,"risk_paths");a!==void 0&&(Array.isArray(a)?r.risk_paths=a.filter(Ng):Ng(a)?r.risk_paths=[a]:n.push(er(`${t}.risk_paths`,"must be an array of strings or a single string"))),n.push(...AHn(e,t));let s=Gn(e,"tests");if(s!==void 0){let f=yHn(s,`${t}.tests`);f.value&&(r.tests=f.value),n.push(...f.warnings)}let c=Gn(e,"pain");if(c!==void 0){let f=IHn(c,`${t}.pain`);f.value&&(r.pain=f.value),n.push(...f.warnings)}let u=Gn(e,"lifecycle");if(u!==void 0){let f=vHn(u,`${t}.lifecycle`);f.value&&(r.lifecycle=f.value),n.push(...f.warnings)}let l=Gn(e,"edit_verification");if(l!==void 0){let f=EHn(l,`${t}.edit_verification`);f.value&&(r.edit_verification=f.value),n.push(...f.warnings)}let p=Gn(e,"custom_guards");if(p!==void 0){let f=xHn(p,`${t}.custom_guards`);f.value&&(r.custom_guards=f.value),n.push(...f.warnings)}return{ok:!0,value:r,warnings:n}}var x_t=new Set(["enabled","runtimeProfile","timeoutMs"]),w_t=new Set(["declaredContextWindowTokens","hosts"]);function sc(e){return e!=null&&typeof e=="object"&&!Array.isArray(e)}function ta(e){return typeof e=="string"}function aSe(e){return typeof e=="boolean"}function Bl(e){return typeof e=="number"&&Number.isFinite(e)}function je(e,t,n){return{path:e,reason:t,nextAction:n}}function bn(e,t){if(!Ea.has(t))return Object.hasOwn(e,t)?e[t]:void 0}function CX(e){return Bl(e)&&Number.isInteger(e)&&e>=eS&&e<=tS}function Wi(e){if(e===null)return"null";if(e===void 0)return"undefined";let t=typeof e;if(t==="string"){let n=e;return n.length>50?`"${n.slice(0,50)}\u2026"`:`"${n}"`}return t==="number"||t==="boolean"?String(e):Array.isArray(e)?`array(${e.length})`:t==="object"?"object":t}function wHn(e,t,n){let r=[];if(!sc(e))return{ok:!1,errors:[je(t,`feature '${n}' must be an object, got ${typeof e}`,`Fix feature '${n}' to be an object with category and enabled fields`)]};let i=bn(e,"category");i===void 0?r.push(je(`${t}.category`,`feature '${n}' missing required field 'category'`,`Add 'category' to feature '${n}' (one of: ${EE.join(", ")})`)):(!ta(i)||!EE.includes(i))&&r.push(je(`${t}.category`,`feature '${n}' category must be one of: ${EE.join(", ")}, got ${Wi(i)}`,`Change category of feature '${n}' to one of: ${EE.join(", ")}`));let o=bn(e,"enabled");o===void 0?r.push(je(`${t}.enabled`,`feature '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to feature '${n}'`)):aSe(o)||r.push(je(`${t}.enabled`,`feature '${n}' enabled must be boolean, got ${typeof o}`,`Change enabled of feature '${n}' to true or false`));let a=bn(e,"source");return a!==void 0&&(typeof a!="string"||!CM.includes(a))&&r.push(je(`${t}.source`,`feature '${n}' source must be one of: ${CM.join(", ")}, got ${Wi(a)}`,`Set source to one of: ${CM.join(", ")}, or remove it (legacy override)`)),r.length>0?{ok:!1,errors:r}:{ok:!0,value:{category:i,enabled:o,...a!==void 0&&typeof a=="string"&&CM.includes(a)?{source:a}:{}}}}function bHn(e,t,n){let r=[],i=bn(e,"provider");i!==void 0&&!ta(i)&&r.push(je(`${t}.provider`,`profile '${n}' provider must be a string, got ${typeof i}`,`Fix provider in profile '${n}'`));let o=bn(e,"model");o!==void 0&&!ta(o)&&r.push(je(`${t}.model`,`profile '${n}' model must be a string, got ${typeof o}`,`Fix model in profile '${n}'`));let a=bn(e,"source");a!==void 0&&!ta(a)&&r.push(je(`${t}.source`,`profile '${n}' source must be a string, got ${typeof a}`,`Fix source in profile '${n}'`));let s=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let u of s)Object.hasOwn(e,u)&&r.push(je(`${t}.${u}`,`profile '${n}' contains forbidden secret field '${u}'`,`Remove '${u}' from profile '${n}' \u2014 PD does not store provider credentials (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let c={type:"openclaw"};return ta(i)&&(c.provider=i),ta(o)&&(c.model=o),ta(a)&&(c.source=a),{ok:!0,value:c}}function SHn(e,t,n){let r=[],i=bn(e,"provider");i===void 0?r.push(je(`${t}.provider`,`profile '${n}' missing required field 'provider'`,`Add 'provider' to profile '${n}' (e.g. "anthropic", "openai")`)):ta(i)||r.push(je(`${t}.provider`,`profile '${n}' provider must be a string, got ${Wi(i)}`,`Fix provider in profile '${n}'`));let o=bn(e,"model");o===void 0?r.push(je(`${t}.model`,`profile '${n}' missing required field 'model'`,`Add 'model' to profile '${n}' (e.g. "claude-3-5-sonnet")`)):ta(o)||r.push(je(`${t}.model`,`profile '${n}' model must be a string, got ${Wi(o)}`,`Fix model in profile '${n}'`));let a=bn(e,"apiKeyEnv");a===void 0?r.push(je(`${t}.apiKeyEnv`,`profile '${n}' missing required field 'apiKeyEnv'`,`Add 'apiKeyEnv' to profile '${n}' (e.g. "ANTHROPIC_API_KEY")`)):ta(a)||r.push(je(`${t}.apiKeyEnv`,`profile '${n}' apiKeyEnv must be a string (env var name), got ${Wi(a)}`,`Fix apiKeyEnv in profile '${n}' to be an environment variable name`));let s=bn(e,"baseUrl");s!==void 0&&!ta(s)&&r.push(je(`${t}.baseUrl`,`profile '${n}' baseUrl must be a string, got ${typeof s}`,`Fix baseUrl in profile '${n}'`));let c=bn(e,"timeoutMs");c!==void 0&&!Bl(c)&&r.push(je(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be a finite number, got ${Wi(c)}`,`Fix timeoutMs in profile '${n}'`)),Bl(c)&&c<=0&&r.push(je(`${t}.timeoutMs`,`profile '${n}' timeoutMs must be positive, got ${c}`,`Set timeoutMs in profile '${n}' to a positive number`));let u=bn(e,"maxRetries");u!==void 0&&!Bl(u)&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be a finite number, got ${Wi(u)}`,`Fix maxRetries in profile '${n}'`)),Bl(u)&&u<0&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be non-negative, got ${u}`,`Set maxRetries in profile '${n}' to a non-negative integer`)),Bl(u)&&!Number.isInteger(u)&&r.push(je(`${t}.maxRetries`,`profile '${n}' maxRetries must be an integer, got ${u}`,`Set maxRetries in profile '${n}' to a non-negative integer`));let l=bn(e,"maxTokens");l!==void 0&&!Bl(l)&&r.push(je(`${t}.maxTokens`,`profile '${n}' maxTokens must be a finite number, got ${Wi(l)}`,`Fix maxTokens in profile '${n}'`)),Bl(l)&&l<=0&&r.push(je(`${t}.maxTokens`,`profile '${n}' maxTokens must be positive, got ${l}`,`Set maxTokens in profile '${n}' to a positive number`));let p=["minimal","low","medium","high","xhigh"],f=bn(e,"reasoning");f!==void 0&&f!==!1&&!(ta(f)&&p.includes(f))&&r.push(je(`${t}.reasoning`,`profile '${n}' reasoning must be one of: ${p.join(", ")} or false, got ${Wi(f)}`,`Fix reasoning in profile '${n}'`));let m=["apiKey","api_key","token","gatewayToken","gateway_token","secret","password","auth"];for(let h of m)Object.hasOwn(e,h)&&r.push(je(`${t}.${h}`,`profile '${n}' contains forbidden secret field '${h}'`,`Remove '${h}' from profile '${n}' \u2014 use 'apiKeyEnv' for env var name reference (ADR-0016 \xA72.2)`));if(r.length>0)return{ok:!1,errors:r};let g={type:"pi-ai",provider:i,model:o,apiKeyEnv:a};return ta(s)&&(g.baseUrl=s),Bl(c)&&(g.timeoutMs=c),Bl(u)&&(g.maxRetries=u),Bl(l)&&(g.maxTokens=l),f!==void 0&&(g.reasoning=f),{ok:!0,value:g}}function CHn(e,t,n){if(!sc(e))return{ok:!1,errors:[je(t,`profile '${n}' must be an object, got ${typeof e}`,`Fix profile '${n}' to be an object with type, provider, model fields`)]};for(let i of Ea)if(Object.hasOwn(e,i))return{ok:!1,errors:[je(`${t}.${i}`,`profile '${n}' contains dangerous key '${i}'`,`Remove '${i}' from profile '${n}'`)]};let r=bn(e,"type");return r===void 0?{ok:!1,errors:[je(`${t}.type`,`profile '${n}' missing required field 'type'`,`Add 'type' to profile '${n}' (one of: ${$C.join(", ")})`)]}:!ta(r)||!$C.includes(r)?{ok:!1,errors:[je(`${t}.type`,`profile '${n}' type must be one of: ${$C.join(", ")}, got ${Wi(r)}`,`Fix type in profile '${n}'`)]}:r==="openclaw"?bHn(e,t,n):SHn(e,t,n)}function kHn(e,t,n){let r=[];if(!sc(e))return{ok:!1,errors:[je(t,`agent '${n}' must be an object, got ${typeof e}`,`Fix agent '${n}' to be an object with enabled and optional runtimeProfile fields`)]};let i=bn(e,"enabled");i===void 0?r.push(je(`${t}.enabled`,`agent '${n}' missing required field 'enabled'`,`Add 'enabled' (boolean) to agent '${n}'`)):aSe(i)||r.push(je(`${t}.enabled`,`agent '${n}' enabled must be boolean, got ${typeof i}`,`Change enabled of agent '${n}' to true or false`));let o=bn(e,"runtimeProfile");if(o!==void 0&&!ta(o)&&r.push(je(`${t}.runtimeProfile`,`agent '${n}' runtimeProfile must be a string, got ${typeof o}`,`Fix runtimeProfile of agent '${n}' to a profile ID`)),r.length>0)return{ok:!1,errors:r};let a={enabled:i};return ta(o)&&(a.runtimeProfile=o),{ok:!0,value:a}}var b_t=new Set(["empathyObserver"]);function RHn(e,t){let n=[],r=[];if(!sc(e))return{ok:!1,errors:[je(t,`internalAgents must be an object, got ${typeof e}`,"Fix internalAgents to be an object with defaultRuntime and agents")]};let i=bn(e,"defaultRuntime");i===void 0?n.push(je(`${t}.defaultRuntime`,"missing required field defaultRuntime","Add defaultRuntime with a runtime profile ID")):(!ta(i)||i.length===0)&&n.push(je(`${t}.defaultRuntime`,`defaultRuntime must be a non-empty string, got ${Wi(i)}`,"Fix defaultRuntime to a valid runtime profile ID"));let o=bn(e,"agents"),a={};if(o===void 0)n.push(je(`${t}.agents`,"missing required field agents",`Add agents section with per-agent bindings: ${ou.join(", ")}`));else if(!sc(o))n.push(je(`${t}.agents`,`agents must be an object, got ${typeof o}`,"Fix agents to be an object mapping agent names to bindings"));else{for(let c of ou){let u=bn(o,c);if(u===void 0)continue;let l=kHn(u,`${t}.agents.${c}`,c);l.ok?a[c]=l.value:n.push(...l.errors)}for(let c of Object.keys(o))Ea.has(c)||b_t.has(c)||ou.includes(c)||n.push(je(`${t}.agents.${c}`,`unknown agent key '${c}'`,`Remove unknown agent '${c}' or use a known agent name: ${ou.join(", ")}`));for(let c of b_t)Object.hasOwn(o,c)&&r.push(`${t}.agents.${c} is a retired no-op (the agent had no runtime consumer and has been removed) and is now ignored \u2014 remove it from .pd/config.yaml`)}let s=new Set(["defaultRuntime","agents"]);for(let c of Object.keys(e))Ea.has(c)||s.has(c)||n.push(je(`${t}.${c}`,`unknown key '${c}' in internalAgents`,`Remove unknown key '${c}' from internalAgents`));return n.length>0?{ok:!1,errors:n}:{ok:!0,warnings:r,value:{defaultRuntime:i,agents:a}}}function THn(e,t){let n=[];if(!sc(e))return{ok:!1,errors:[je(t,`ui must be an object, got ${typeof e}`,"Fix ui to be an object with diagnostics settings")]};let r=bn(e,"diagnostics");if(!sc(r))return{ok:!1,errors:[je(`${t}.diagnostics`,`ui.diagnostics must be an object, got ${typeof r}`,"Fix ui.diagnostics to be an object with mode field")]};let i=bn(r,"mode");return i===void 0?n.push(je(`${t}.diagnostics.mode`,"missing required field mode",`Add mode to ui.diagnostics (one of: ${xE.join(", ")})`)):(!ta(i)||!xE.includes(i))&&n.push(je(`${t}.diagnostics.mode`,`mode must be one of: ${xE.join(", ")}, got ${Wi(i)}`,`Fix mode to one of: ${xE.join(", ")}`)),n.length>0?{ok:!1,errors:n}:{ok:!0,value:{diagnostics:{mode:i}}}}function OHn(e){return/^[A-Za-z]:[\\/]/.test(e)||e.startsWith("\\\\")||e.startsWith("/")}function DHn(e){return kM.some(t=>t===e)}function PHn(e,t){let n=[];if(!sc(e))return{ok:!1,errors:[je(t,`workspace must be an object, got ${typeof e}`,"Fix workspace to be an object with a default field")]};for(let s of Ea)if(Object.hasOwn(e,s))return{ok:!1,errors:[je(`${t}.${s}`,`workspace contains dangerous key '${s}'`,`Remove '${s}' from workspace`)]};let r=bn(e,"default");r===void 0?n.push(je(`${t}.default`,"workspace missing required field default","Add default path to workspace section (must be an absolute path)")):!ta(r)||r.length===0?n.push(je(`${t}.default`,`workspace.default must be a non-empty string, got ${Wi(r)}`,"Set workspace.default to an absolute directory path")):OHn(r)||n.push(je(`${t}.default`,`workspace.default must be an absolute path, got "${r}"`,'Use an absolute path like "D:\\.openclaw\\workspace" or "/home/user/.openclaw/workspace"'));let i=bn(e,"environment"),o;i!==void 0&&(ta(i)&&DHn(i)?o=i:n.push(je(`${t}.environment`,`workspace.environment must be one of ${kM.join("|")}, got ${Wi(i)}`,`Set workspace.environment to one of ${kM.join(", ")}, or remove the key to leave the environment unknown`)));let a=new Set(["default","environment"]);for(let s of Object.keys(e))Ea.has(s)||a.has(s)||n.push(je(`${t}.${s}`,`unknown key '${s}' in workspace`,`Remove unknown key '${s}' from workspace`));return n.length>0?{ok:!1,errors:n}:!ta(r)||r.length===0?{ok:!1,errors:[je(`${t}.default`,"workspace.default validation invariant failed","Re-validate the workspace section; this error indicates a validator bug \u2014 please report it")]}:{ok:!0,value:{default:r,...o!==void 0?{environment:o}:{}}}}function LHn(e,t){let n=[],r=[];if(!sc(e))return{ok:!1,errors:[je(t,"contextInjection must be an object","Fix contextInjection to be an object with optional thinkingOs and projectFocus fields")]};for(let c of Ea)if(Object.hasOwn(e,c))return{ok:!1,errors:[je(`${t}.${c}`,`contextInjection contains dangerous key '${c}'`,`Remove '${c}' from contextInjection`)]};let i={},o=bn(e,"thinkingOs");o!==void 0&&(aSe(o)?i.thinkingOs=o:n.push(je(`${t}.thinkingOs`,"contextInjection.thinkingOs must be a boolean","Set contextInjection.thinkingOs to true or false")));let a=bn(e,"projectFocus");a!==void 0&&(!ta(a)||!RM.includes(a)?n.push(je(`${t}.projectFocus`,`contextInjection.projectFocus must be one of: ${RM.join(", ")}, got ${Wi(a)}`,`Set contextInjection.projectFocus to one of: ${RM.join(", ")}`)):i.projectFocus=a);let s=new Set(["thinkingOs","projectFocus","evolutionContext"]);for(let c of Object.keys(e))Ea.has(c)||s.has(c)||n.push(je(`${t}.${c}`,`unknown key '${c}' in contextInjection`,`Remove unknown key '${c}' from contextInjection`));return Object.hasOwn(e,"evolutionContext")&&r.push(`${t}.evolutionContext is a retired no-op (no runtime consumer ever read it) and is now ignored \u2014 remove it from .pd/config.yaml`),n.length>0?{ok:!1,errors:n}:{ok:!0,value:i,warnings:r}}function kX(e){let t=[],n=[];if(e==null)return{ok:!1,errors:[je("","config is null or undefined","Provide a valid .pd/config.yaml file or use defaults")]};if(!sc(e))return{ok:!1,errors:[je("",`config root must be an object, got ${typeof e}`,"Fix .pd/config.yaml to be a YAML object")]};for(let R of Ea)Object.hasOwn(e,R)&&t.push(je(R,`root contains dangerous key '${R}'`,`Remove '${R}' from config root`));let r=bn(e,"version");r===void 0?t.push(je("version","missing required field version",`Add version: ${1} to config`)):(!Bl(r)||r!==1)&&t.push(je("version",`version must be ${1}, got ${Wi(r)}`,`Set version to ${1}`));let i=bn(e,"workspace"),o;if(i!==void 0){let R=PHn(i,"workspace");R.ok?o=R.value:t.push(...R.errors)}let a=bn(e,"features"),s={};if(a===void 0)t.push(je("features","missing required field features","Add features section with prompt, code_tool_hook, defer_archive entries"));else if(!sc(a))t.push(je("features",`features must be an object, got ${typeof a}`,"Fix features to be an object mapping flag names to {category, enabled}"));else for(let R of Object.keys(a)){if(Ea.has(R)){t.push(je(`features.${R}`,`dangerous key '${R}' rejected`,`Remove '${R}' from features`));continue}let M=wHn(a[R],`features.${R}`,R);M.ok?s[R]=M.value:t.push(...M.errors)}let c=bn(e,"runtimeProfiles"),u={};if(c===void 0)t.push(je("runtimeProfiles","missing required field runtimeProfiles","Add runtimeProfiles section with at least one profile"));else if(!sc(c))t.push(je("runtimeProfiles",`runtimeProfiles must be an object, got ${typeof c}`,"Fix runtimeProfiles to be an object mapping profile IDs to profile definitions"));else for(let R of Object.keys(c)){if(Ea.has(R)){t.push(je(`runtimeProfiles.${R}`,`dangerous key '${R}' rejected`,`Remove '${R}' from runtimeProfiles`));continue}let M=CHn(c[R],`runtimeProfiles.${R}`,R);M.ok?(u[R]=M.value,M.value.type==="openclaw"&&n.push(`runtime profile '${R}' uses the retired 'openclaw' backend (ADR-0029): PD no longer runs internal agents through a host CLI session, so agents bound to it report needs_setup until a pi-ai profile is configured`)):t.push(...M.errors)}let l=bn(e,"internalAgents"),p;if(l===void 0)t.push(je("internalAgents","missing required field internalAgents","Add internalAgents section with defaultRuntime"));else{let R=RHn(l,"internalAgents");R.ok?(p=R.value,n.push(...R.warnings)):t.push(...R.errors)}let f=bn(e,"ui"),m;if(f!==void 0){let R=THn(f,"ui");R.ok?m=R.value:t.push(...R.errors)}let g=bn(e,"profile"),h;if(g!==void 0){let R=oSe(g);if(R.ok)h=R.value;else for(let M of R.errors)t.push(je(M.path,M.message,"Fix profile section in .pd/config.yaml"))}let y=bn(e,"contextInjection"),I;if(y!==void 0){let R=LHn(y,"contextInjection");R.ok?(I=R.value,n.push(...R.warnings)):t.push(...R.errors)}let v=bn(e,"reuseEvaluation"),w;if(v!==void 0)if(!sc(v))t.push(je("reuseEvaluation",`reuseEvaluation must be an object, got ${Wi(v)}`,"Set reuseEvaluation to a mapping (e.g. reuseEvaluation: { enabled: true })"));else{for(let $ of Object.keys(v))x_t.has($)||t.push(je(`reuseEvaluation.${$}`,`unknown key '${$}' in reuseEvaluation`,`Remove '${$}'; only ${[...x_t].join(", ")} are supported`));let R=bn(v,"enabled");R!==void 0&&typeof R!="boolean"&&t.push(je("reuseEvaluation.enabled",`enabled must be a boolean, got ${Wi(R)}`,"Set reuseEvaluation.enabled to true or false"));let M=bn(v,"runtimeProfile");M!==void 0&&(typeof M!="string"||M.trim()==="")&&t.push(je("reuseEvaluation.runtimeProfile",`runtimeProfile must be a non-empty string, got ${Wi(M)}`,"Set reuseEvaluation.runtimeProfile to a runtimeProfiles id, or remove the key to fall back to internalAgents.defaultRuntime"));let H=bn(v,"timeoutMs");H!==void 0&&(!Bl(H)||!Number.isFinite(H)||H<=0)&&t.push(je("reuseEvaluation.timeoutMs",`timeoutMs must be a positive number of milliseconds, got ${Wi(H)}`,"Set reuseEvaluation.timeoutMs to a positive integer (e.g. 60000), or remove the key to use the profile timeout")),t.every($=>!$.path.startsWith("reuseEvaluation"))&&(w={enabled:R===void 0?!0:R,...typeof M=="string"&&M.trim()!==""?{runtimeProfile:M}:{},...Bl(H)&&H>0?{timeoutMs:H}:{}})}let b=bn(e,"promptBudget"),k;if(b!==void 0)if(!sc(b))t.push(je("promptBudget",`promptBudget must be an object, got ${Wi(b)}`,"Set promptBudget to a mapping (e.g. promptBudget: { declaredContextWindowTokens: 262144 })"));else{for(let H of Object.keys(b))w_t.has(H)||t.push(je(`promptBudget.${H}`,`unknown key '${H}' in promptBudget`,`Remove '${H}'; only ${[...w_t].join(", ")} are supported`));let R=bn(b,"declaredContextWindowTokens");R!==void 0&&!CX(R)&&t.push(je("promptBudget.declaredContextWindowTokens",`declaredContextWindowTokens must be an integer between ${eS} and ${tS}, got ${Wi(R)}`,"Set promptBudget.declaredContextWindowTokens to the model context window in tokens (e.g. 262144), or remove the key"));let M=bn(b,"hosts");if(M!==void 0)if(!sc(M))t.push(je("promptBudget.hosts",`hosts must be an object, got ${Wi(M)}`,`Set promptBudget.hosts to a mapping keyed by ${wE.join(", ")}`));else for(let[H,$]of Object.entries(M))wE.includes(H)?CX($)||t.push(je(`promptBudget.hosts.${H}`,`host window must be an integer between ${eS} and ${tS}, got ${Wi($)}`,`Set promptBudget.hosts.${H} to the model context window in tokens (e.g. 262144), or remove the key`)):t.push(je(`promptBudget.hosts.${H}`,`unknown host '${H}' in promptBudget.hosts`,`Only ${wE.join(", ")} are supported`));t.every(H=>!H.path.startsWith("promptBudget"))&&(k={...CX(R)?{declaredContextWindowTokens:R}:{},...sc(M)&&Object.keys(M).length>0?{hosts:Object.fromEntries(Object.entries(M).filter(([H,$])=>wE.includes(H)&&CX($)))}:{}})}let P=bn(e,"principles"),B;if(P!==void 0)if(!sc(P))t.push(je("principles",`principles must be an object, got ${Wi(P)}`,"Set principles to a mapping (e.g. principles: { outputLanguage: zh-CN })"));else{let R=Object.hasOwn(P,"outputLanguage")?P.outputLanguage:void 0;R===void 0?B={}:Mj(R)?B={outputLanguage:R}:t.push(je("principles.outputLanguage",`outputLanguage must be one of ${IE.join(", ")}, got ${Wi(R)}`,`Set principles.outputLanguage to one of: ${IE.join(", ")}`))}return t.length>0?{ok:!1,errors:t}:p?{ok:!0,value:{version:1,...o?{workspace:o}:{},features:s,runtimeProfiles:u,internalAgents:p,ui:m??{diagnostics:{mode:"simple"}},...B?{principles:B}:{},...w?{reuseEvaluation:w}:{},...k?{promptBudget:k}:{},...h?{profile:h}:{},...I?{contextInjection:I}:{}},warnings:n}:{ok:!1,errors:[je("internalAgents","internalAgents validation unexpectedly failed","Check internalAgents configuration")]}}var NHn={on_change:"smoke",on_risk_change:"unit",commands:{}},S_t={enabled:!0,spiral_boost:20,min_threshold:15,max_threshold:70,backlog_trigger:6,hard_failure_trigger:1,low_recent_success_boost:15,high_recent_pain_boost:10},MHn={soft_capture_threshold:30,adaptive:{...S_t}},BHn={enabled:!0,heartbeat_stale_hours:72},FHn={enabled:!0,max_file_size_bytes:10*1024*1024,fuzzy_match_enabled:!0,fuzzy_match_threshold:.8,skip_large_file_action:"warn"};var ao={audit_level:"medium",risk_paths:[],evolution_mode:"realtime",tests:{...NHn},pain:{soft_capture_threshold:MHn.soft_capture_threshold,adaptive:{...S_t}},lifecycle:{...BHn},edit_verification:{...FHn},custom_guards:[]};function RX(e){return e?{audit_level:e.audit_level??ao.audit_level,risk_paths:e.risk_paths??ao.risk_paths,evolution_mode:e.evolution_mode??ao.evolution_mode,tests:{on_change:e.tests?.on_change??ao.tests.on_change,on_risk_change:e.tests?.on_risk_change??ao.tests.on_risk_change,commands:{...ao.tests.commands,...e.tests?.commands??{}}},pain:{soft_capture_threshold:e.pain?.soft_capture_threshold??ao.pain.soft_capture_threshold,adaptive:{enabled:e.pain?.adaptive?.enabled??ao.pain.adaptive.enabled,spiral_boost:e.pain?.adaptive?.spiral_boost??ao.pain.adaptive.spiral_boost,min_threshold:e.pain?.adaptive?.min_threshold??ao.pain.adaptive.min_threshold,max_threshold:e.pain?.adaptive?.max_threshold??ao.pain.adaptive.max_threshold,backlog_trigger:e.pain?.adaptive?.backlog_trigger??ao.pain.adaptive.backlog_trigger,hard_failure_trigger:e.pain?.adaptive?.hard_failure_trigger??ao.pain.adaptive.hard_failure_trigger,low_recent_success_boost:e.pain?.adaptive?.low_recent_success_boost??ao.pain.adaptive.low_recent_success_boost,high_recent_pain_boost:e.pain?.adaptive?.high_recent_pain_boost??ao.pain.adaptive.high_recent_pain_boost}},lifecycle:{enabled:e.lifecycle?.enabled??ao.lifecycle.enabled,heartbeat_stale_hours:e.lifecycle?.heartbeat_stale_hours??ao.lifecycle.heartbeat_stale_hours},edit_verification:{enabled:e.edit_verification?.enabled??ao.edit_verification.enabled,max_file_size_bytes:e.edit_verification?.max_file_size_bytes??ao.edit_verification.max_file_size_bytes,fuzzy_match_enabled:e.edit_verification?.fuzzy_match_enabled??ao.edit_verification.fuzzy_match_enabled,fuzzy_match_threshold:e.edit_verification?.fuzzy_match_threshold??ao.edit_verification.fuzzy_match_threshold,skip_large_file_action:e.edit_verification?.skip_large_file_action??ao.edit_verification.skip_large_file_action},custom_guards:e.custom_guards??ao.custom_guards}:{...ao}}function C_t(e){return e?{thinkingOs:e.thinkingOs??DM.thinkingOs,projectFocus:e.projectFocus??DM.projectFocus}:{...DM}}function Av(e){if(e==null)return{config:Gj(),source:"defaults",warnings:[],featuresChangedFromDefault:[],resolvedProfile:RX({}),resolvedContextInjection:C_t(void 0)};let t=[],n=[],{normalized:r,warnings:i}=$j(e.features);t.push(...i);let o={};for(let[b,k]of Object.entries(O0))if(Object.hasOwn(r,b)){let P=r[b];if(!P){o[b]={...k};continue}if(k.category==="gone"){o[b]={...k},P.enabled&&(t.push(`feature '${b}': gone flag cannot be re-enabled`),n.push(b));continue}if(k.category==="core"&&!P.enabled){o[b]={category:P.category,enabled:!1,...P.source?{source:P.source}:{}},t.push(`feature '${b}': core flag explicitly disabled via config (emergency disable)`),n.push(b);continue}(P.category!==k.category||P.enabled!==k.enabled)&&n.push(b),o[b]={category:P.category,enabled:P.enabled,...P.source?{source:P.source}:{}}}else o[b]={...k};for(let b of Object.keys(r))Ea.has(b)||Object.hasOwn(o,b)||t.push(`feature '${b}': unknown flag ignored (not a registered capability)`);let a={};for(let[b,k]of Object.entries(e.runtimeProfiles))Ea.has(b)||(a[b]={...k});Object.hasOwn(a,bE)||(a[bE]={...jj},t.push(`runtime profile '${bE}' not found in config, using default`));let s=TM(),c={};for(let b of ou){let k=e.internalAgents.agents[b],P=s.agents[b];k!==void 0?c[b]={enabled:k.enabled,runtimeProfile:k.runtimeProfile??e.internalAgents.defaultRuntime}:c[b]={enabled:P.enabled,runtimeProfile:e.internalAgents.defaultRuntime}}for(let b of ou){let k=c[b];k&&k.enabled&&k.runtimeProfile&&!Object.hasOwn(a,k.runtimeProfile)&&t.push(`agent '${b}': runtime profile '${k.runtimeProfile}' not found in runtimeProfiles`)}let u=r.diagnostician_split_pipeline;if(u!==void 0&&u.enabled===!1&&c.diagnostician?.enabled===!0){c.diagnostician={enabled:!1,runtimeProfile:e.internalAgents.defaultRuntime};let b=u.source??"unknown";t.push(`PRI-638 cutover: legacy diagnostician_split_pipeline=false (source: ${b}) honored as internalAgents.agents.diagnostician.enabled=false to avoid silently enabling a previously-disabled LLM pipeline. Recovery: toggle Diagnostician ON in Console \u2192 Control Center (the writer retires the conflicting legacy override), or edit .pd/config.yaml to remove the legacy diagnostician_split_pipeline flag. A standalone internalAgents.agents.diagnostician.enabled=true is NOT sufficient while the legacy override remains false.`)}let l={defaultRuntime:e.internalAgents.defaultRuntime,agents:c},p=e.reuseEvaluation??{},f=p.runtimeProfile??e.internalAgents.defaultRuntime;(p.enabled??PM.enabled)&&!Object.hasOwn(a,f)&&t.push(`reuseEvaluation: runtime profile '${f}' not found in runtimeProfiles (the capability will not run until a configured profile is available)`);let g={enabled:p.enabled??PM.enabled,runtimeProfile:f,...p.timeoutMs!==void 0?{timeoutMs:p.timeoutMs}:{}},h=e.ui??{...OM},y=e.principles??{outputLanguage:void 0},I=RX(e.profile??{}),v=C_t(e.contextInjection);return{config:{version:1,...e.workspace?{workspace:e.workspace}:{},features:o,runtimeProfiles:a,internalAgents:l,ui:h,principles:y,reuseEvaluation:g,...e.promptBudget?{promptBudget:e.promptBudget}:{},...e.profile?{profile:e.profile}:{},...e.contextInjection?{contextInjection:e.contextInjection}:{}},source:"user_config",warnings:t,featuresChangedFromDefault:n,resolvedProfile:I,resolvedContextInjection:v}}function UW(e,t){return e?.hosts?.[t]??e?.declaredContextWindowTokens}var $Hn=new Set(["owner_reported","agent_on_owner_request","tool_failure","dispatch_error","provider_failure","rate_limit","rulehost_block","empathy_inferred","semantic","llm_paralysis","subagent_error","unknown"]);function TX(e){return typeof e=="string"&&$Hn.has(e)}var sSe=new Map([["owner_reported",{kind:"owner_reported",defaultDecision:"admit",reason:"Owner explicitly reported pain. Highest confidence signal.",nextAction:"none"}],["agent_on_owner_request",{kind:"agent_on_owner_request",defaultDecision:"admit",reason:"Agent recorded pain at owner request. Owner intent preserved.",nextAction:"none"}],["tool_failure",{kind:"tool_failure",defaultDecision:"evidence_only",reason:"Tool failure is a technical trajectory fact, never a behavioral-deviation Pain by itself (Phase A).",nextAction:"store_as_evidence_for_later_correlation"}],["dispatch_error",{kind:"dispatch_error",defaultDecision:"evidence_only",reason:"Dispatch/subagent routing error. Not a behavior pattern.",nextAction:"store_as_evidence_for_later_correlation"}],["provider_failure",{kind:"provider_failure",defaultDecision:"health_only",reason:"LLM provider failure. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry"}],["rate_limit",{kind:"rate_limit",defaultDecision:"health_only",reason:"LLM provider rate limit. Infrastructure health signal, not owner-relevant behavior.",nextAction:"record_in_health_telemetry"}],["rulehost_block",{kind:"rulehost_block",defaultDecision:"evidence_only",reason:"RuleHost block is a technical block fact. Correct blocks are not Owner pain; wrong blocks reach correction detection (Phase A).",nextAction:"store_as_evidence_for_later_correlation"}],["empathy_inferred",{kind:"empathy_inferred",defaultDecision:"owner_confirm",reason:"Empathy-inferred frustration. Never silently creates diagnosis (PRODUCT_IDENTITY: owner-governed).",nextAction:"request_owner_confirmation_before_diagnosis"}],["semantic",{kind:"semantic",defaultDecision:"evidence_only",reason:"Keyword/detection match. Not explicit owner pain. Needs accumulation.",nextAction:"store_as_evidence_for_later_correlation"}],["llm_paralysis",{kind:"llm_paralysis",defaultDecision:"evidence_only",reason:"Session health signal. Not sufficient for diagnosis on its own.",nextAction:"store_as_evidence_for_later_correlation"}],["subagent_error",{kind:"subagent_error",defaultDecision:"evidence_only",reason:"Subagent workflow failure. Not a behavior pattern by itself.",nextAction:"store_as_evidence_for_later_correlation"}],["unknown",{kind:"unknown",defaultDecision:"evidence_only",reason:"Unclassified source. Conservative default.",nextAction:"classify_source_kind_and_store_as_evidence"}]]);function nL(e){return sSe.get(e)}function OX(e){let t=TX(e.sourceKind)?e.sourceKind:"unknown",n=nL(t);return n?{decision:n.defaultDecision,sourceKind:t,reason:n.reason,nextAction:n.nextAction}:{decision:"evidence_only",sourceKind:"unknown",reason:`Source kind '${t}' not found in descriptor registry. Conservative default.`,nextAction:"classify_source_kind_and_store_as_evidence"}}function rL(e){let{isManualEntry:t,isGateBlock:n,isSubagentError:r,isRateLimit:i,toolName:o,failureSource:a,detectionSource:s,nonZeroExit:c,timedOut:u,toolNotFound:l}=e;if(t)return"owner_reported";if(n)return"rulehost_block";if(r)return"subagent_error";if(i===!0)return"rate_limit";if(i===!1)return"provider_failure";if(o==="pain"||o==="skill:pain")return e.provenance==="host_context_bound"?"agent_on_owner_request":"owner_reported";if(a)return a==="dispatch_error"?"dispatch_error":"tool_failure";if(l||(o!==void 0||c||u||l)&&(!o||o.trim()===""))return"dispatch_error";if(c||u)return"tool_failure";if(s){if(s==="llm_paralysis")return"llm_paralysis";if(s.startsWith("llm_"))return"semantic";if(s==="user_empathy")return"empathy_inferred"}return"unknown"}function HHn(e){if(!e)return"tool_failure";let t=String(e);return/\btool\s+(?:\S+\s+)?not\s+found\b/i.test(t)||/\bunknown\s+tool\b/i.test(t)?"dispatch_error":"tool_failure"}function iL(e){let{toolName:t,error:n,provenance:r}=e,i=typeof e.exitCode=="number"&&e.exitCode!==0,o;return!t||t.trim()===""?o="dispatch_error":o=HHn(n),!n&&!i&&(o=void 0),{observedAt:new Date().toISOString(),toolName:t,failureSource:o,nonZeroExit:i,provenance:r}}function QW(e){return{observedAt:new Date().toISOString(),isManualEntry:!0,sessionId:e.sessionId}}function k_t(e,t){let n=[];return e&&n.push(`kind=${e.kind}`),n.push(`score=${t.score}`),t.sessionId&&n.push(`session=${t.sessionId.slice(0,8)}`),n.join(", ")}function jHn(e){return{outcome:"refused",reason:e.validationError??"Input validation failed. Evidence is malformed or incomplete.",nextAction:"fix_input_and_retry_or_classify_as_unknown",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!1,decidedAt:new Date().toISOString(),operatorNote:`validationError=${e.validationError??"unknown"}`}}function GHn(e){return{outcome:"manual_owner_admitted",reason:"Owner explicit manual pain. Bypasses triage and cooldown. Highest confidence signal.",nextAction:"create_diagnostic_task",sourceKind:e.triageResult.sourceKind,triageDecision:e.triageResult.decision,shouldCreateDiagnosticTask:!0,decidedAt:new Date().toISOString(),operatorNote:`score=${e.score}, sessionId=${e.sessionId??"unknown"}`}}function qHn(e){let{triageResult:t}=e,n=nL(t.sourceKind),r=new Date().toISOString();switch(t.decision){case"admit":return e.isCooldownActive&&!e.cooldownBypassAllowed?{outcome:"cooldown_skipped",reason:`Admitted by triage but cooldown is active for source '${t.sourceKind}'. Cooldown prevents diagnosis to avoid duplicate tasks.`,nextAction:"wait_for_cooldown_or_manual_retrigger",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`cooldown_active=true, score=${e.score}`}:{outcome:"diagnosis_created",reason:t.reason,nextAction:t.nextAction==="none"?"proceed_with_diagnostic_task":t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!0,decidedAt:r,operatorNote:k_t(n,e)};case"evidence_only":return{outcome:"evidence_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:k_t(n,e)};case"health_only":return{outcome:"health_only",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`provider_signal, score=${e.score}`};case"owner_confirm":return{outcome:"owner_confirm_required",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`requires_confirmation, score=${e.score}`};case"reject":return{outcome:"refused",reason:t.reason,nextAction:t.nextAction,sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r,operatorNote:`rejected, score=${e.score}`};default:{let i=t.decision;return{outcome:"refused",reason:`Unhandled triage decision: ${String(t.decision)}. Conservative refusal.`,nextAction:"investigate_unknown_triage_decision",sourceKind:t.sourceKind,triageDecision:t.decision,shouldCreateDiagnosticTask:!1,decidedAt:r}}}}function DX(e){return e.isValid?e.isOwnerManual?GHn(e):qHn(e):jHn(e)}var R_t=[{key:"why",headerRegex:/^##\s+1\.\s*Why\s*$/im,label:"why",header:"## 1. Why"},{key:"desiredOutcome",headerRegex:/^##\s+2\.\s*Desired Outcome\s*$/im,label:"desiredOutcome",header:"## 2. Desired Outcome"},{key:"nonNegotiables",headerRegex:/^##\s+3\.\s*Non-negotiables\s*$/im,label:"nonNegotiables",header:"## 3. Non-negotiables"},{key:"stopEscalation",headerRegex:/^##\s+4\.\s*Stop\s*\/\s*Escalation\s*$/im,label:"stopEscalation",header:"## 4. Stop / Escalation"},{key:"currentStrategicFocus",headerRegex:/^##\s+5\.\s*Current Strategic Focus\s*$/im,label:"currentStrategicFocus",header:"## 5. Current Strategic Focus"}];function PX(e){let t={};for(let n of R_t){let r=n.headerRegex.exec(e);if(r===null)continue;let i=e.slice(r.index+r[0].length),o=/^##\s+/m.exec(i);t[n.key]=i.slice(0,o!==null?o.index:i.length).trim()}return t}function cSe(e){let t=[];for(let n of R_t){let i=Object.hasOwn(e,n.key)?e[n.key]:void 0;if(i===void 0){t.push({code:"missing_section",message:`Section "${n.label}" is missing from INTENT.md.`,section:n.label});continue}if(typeof i!="string"){t.push({code:"parse_failed",message:`Section "${n.label}" has a non-string value.`,section:n.label});continue}if(i.trim().length===0){t.push({code:"empty_section",message:`Section "${n.label}" is empty.`,section:n.label});continue}i.length<10&&t.push({code:"too_vague",message:`Section "${n.label}" is too short.`,section:n.label})}return t}function Hm(e){return`INTENT.${e}.md`}import{createHash as XHn}from"node:crypto";function LX(e){return`sha256:${XHn("sha256").update(e,"utf8").digest("hex")}`}function Du(e){return e.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&apos;")}var uSe=4e3,lSe=`
1948
1948
  ...[truncated: intent doc exceeds injection budget]`;function dSe(e){if(e==null)return"";let t=typeof e.rawIntentMd=="string"?e.rawIntentMd:"";if(t.trim().length===0)return"";let n=Du(t);if(n.length>uSe){let a=uSe-lSe.length;n=n.slice(0,Math.max(0,a))+lSe}let r=`<intent_anchor>
1949
1949
  This is the Owner-owned project intent.
@@ -2,7 +2,7 @@
2
2
  "id": "principles-disciple",
3
3
  "name": "Principles Disciple",
4
4
  "description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
5
- "version": "3.1.3",
5
+ "version": "3.1.4",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
@@ -2,7 +2,7 @@
2
2
  "id": "principles-disciple",
3
3
  "name": "Principles Disciple",
4
4
  "description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
5
- "version": "3.1.3",
5
+ "version": "3.1.4",
6
6
  "activation": {
7
7
  "onStartup": true,
8
8
  "onCapabilities": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "principles-disciple",
3
- "version": "3.1.3",
3
+ "version": "3.1.4",
4
4
  "description": "Principles Disciple is an AI Agent Governance System. Stop correcting the same AI behavior across sessions. Turn repeated Agent corrections into Owner-approved, observable, reversible behavior principles.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -76,8 +76,8 @@
76
76
  "compile-principles": "node scripts/compile-principles.mjs"
77
77
  },
78
78
  "devDependencies": {
79
- "@principles/core": "^6.0.0",
80
- "@principles/host-runtime": "^3.1.1",
79
+ "@principles/core": "^6.0.1",
80
+ "@principles/host-runtime": "^3.1.2",
81
81
  "@types/better-sqlite3": "^9.6.0",
82
82
  "@types/js-yaml": "^4.0.9",
83
83
  "@types/micromatch": "^4.0.10",
@@ -109,5 +109,5 @@
109
109
  "js-yaml": "^5.4.3",
110
110
  "micromatch": "^4.0.8"
111
111
  },
112
- "gitHead": "e7c7e6bba35aa7d691496cf126b195ea3a70fef9"
112
+ "gitHead": "4000adc495a7c146f4d9282c114d0d936d8e196a"
113
113
  }