@herjarsa/omo-meta-governor 0.4.0 → 0.5.0

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/config.d.ts CHANGED
@@ -47,6 +47,13 @@ export interface MetaGovernorPluginConfig {
47
47
  maxHistoryMessages?: number;
48
48
  minActionForMessage?: "warn" | "escalate" | "stop";
49
49
  };
50
+ /** Sisyphus protocol enforcement config. */
51
+ protocolEnforcement?: {
52
+ enabled?: boolean;
53
+ path?: string;
54
+ injectIntoSystem?: boolean;
55
+ auditToolCalls?: boolean;
56
+ };
50
57
  }
51
58
  /**
52
59
  * Project the full MetaGovernorPluginConfig into OrchestratorConfig.
package/dist/index.d.ts CHANGED
@@ -31,3 +31,5 @@ export { aggregateRead } from "./memory-aggregator";
31
31
  export { recordRecovery, type RecoveryOutcome } from "./post-repair-recorder";
32
32
  export { storeDecision, takeDecision, hasDecision, takeAnyDecision, clearAll, } from "./decision-store";
33
33
  export type { Decision, DecisionContext, DecisionHandlerConfig, DecisionHandlerInput, DecisionHandlerOutput, Deviation, Evidence, EvidenceContribution, InterventionConfig, InterventionMode, LearnFromOutcomeInput, LearnFromOutcomeOutput, MemoryRead, MemoryBackends, AgentmemoryWriteBackend, MetaGovernorInput, MetaGovernorOutput, OrchestratorConfig, ScoringConfig, ScoringResult, SlotMemory, TokenPredictorConfig, TokenPredictorInput, TokenPredictorOutput, ClosedLoopConfig, } from "./types";
34
+ export { loadProtocol, buildSystemInjection, auditToolCall, DEFAULT_PROTOCOL_PATH, } from "./protocol-enforcer";
35
+ export type { ProtocolViolation, ProtocolEnforcementSessionState } from "./types";
package/dist/index.js CHANGED
@@ -1,5 +1,7 @@
1
- var p={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function k(J,K){let Q=performance.now(),Z={...p.limits,...J.limits},$={...p.timeouts,...J.timeouts},[X,q,j]=await Promise.allSettled([KJ(J,K.agentmemory,Z,$.agentmemoryMs),QJ(J,K.magicContext,Z,$.magicContextMs),XJ(J,K.boulderState,Z,$.boulderStateMs)]),N=[],V={},B=X.status==="fulfilled"?X.value:(O(N,V,"agentmemory",L(X.reason)),M.agentmemory),z=q.status==="fulfilled"?q.value:(O(N,V,"magicContext",L(q.reason)),M.magicContext),W=j.status==="fulfilled"?j.value:(O(N,V,"boulderState",L(j.reason)),M.boulderState);return{query:J.query,timestampISO:new Date().toISOString(),agentmemory:B,magicContext:z,boulderState:W,degradedSources:N,durationMs:performance.now()-Q,errorMessages:V}}async function KJ(J,K,Q,Z){let $=await y(K.smartSearch({query:J.query,limit:Q.maxLessons}),Z,"agentmemory");return{available:!0,lessons:ZJ($.lessons).slice(0,Q.maxLessons).map((q)=>({id:q.id,title:q.title,advice:"info",confidence:q.confidence,concepts:q.concepts}))}}async function QJ(J,K,Q,Z){return{available:!0,slots:(await y(K.slotList({directory:J.directory}),Z,"magicContext")).filter((X)=>X.label.startsWith("meta_governor:")||$J(X,J.query)).sort((X,q)=>X.label.localeCompare(q.label)).slice(0,Q.maxSlots).map((X)=>({label:X.label,content:X.content}))}}async function XJ(J,K,Q,Z){let $=await y(K.boulderRead({directory:J.directory,sessionID:J.sessionID,query:J.query}),Z,"boulderState");return{available:!0,tasks:$.sort((q,j)=>q.priority-j.priority||j.updatedAtMs-q.updatedAtMs).slice(0,Q.maxTasks).map((q)=>({id:q.id,status:q.status,title:q.title})),planProgress:qJ($)}}function ZJ(J){return[...J].sort((K,Q)=>Q.confidence-K.confidence)}function $J(J,K){let Q=K.toLowerCase();return J.label.toLowerCase().includes(Q)||J.content.toLowerCase().includes(Q)}function qJ(J){if(J.length===0)return 0;return J.filter((Q)=>Q.status==="done").length/J.length}function L(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;return"unknown error"}function O(J,K,Q,Z){J.push(Q),K[Q]=Z}var M={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function y(J,K,Q){return new Promise((Z,$)=>{let X=setTimeout(()=>$(Error(`${Q} timeout after ${K}ms`)),K);J.then((q)=>{clearTimeout(X),Z(q)},(q)=>{clearTimeout(X),$(q)})})}function jJ(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function l(J){if(J.length===0)return 0;return J.reduce((Q,Z)=>Q+Z,0)/J.length}function zJ(J,K){let Q=0;for(let Z=J.length-1;Z>=0;Z--)if(J[Z]>=K)Q++;else break;return Q}function NJ(J,K,Q,Z){let $=K-J;if($<=0)return Z;if(Q<=0)return null;let X=Math.floor($/Q);if(X<=0)return Z;let q=X*2;return new Date(new Date(Z).getTime()+q*1000).toISOString()}function x(J){let{currentUsage:K,modelLimit:Q,recentTurnTokens:Z,timestampISO:$,config:X}=J,q=Z.slice(-X.windowSize),j=l(q),N=Q-K,V=Q>0?K/Q:1,B=Math.min(0.95,0.3+q.length/X.windowSize*0.65),z="no-action",W="within normal parameters";if(V>=X.switchModelUsageThreshold)z="switch-model",W=`context usage ${(V*100).toFixed(1)}% exceeds switch threshold ${(X.switchModelUsageThreshold*100).toFixed(1)}%`;if(V>=X.compactUsageThreshold||j>=X.compactBurnRateThreshold){if(z==="no-action")z="compact-now",W=V>=X.compactUsageThreshold?`context usage ${(V*100).toFixed(1)}% exceeds compact threshold ${(X.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${j.toFixed(0)} tokens/turn exceeds threshold ${X.compactBurnRateThreshold}`}let Y=zJ(q,X.compactBurnRateThreshold);if(Y>=X.delegateConsecutiveHighBurn&&z==="no-action")z="delegate-to-subagent",W=`${Y} consecutive high-burn turns (threshold: ${X.delegateConsecutiveHighBurn})`;let F=NJ(K,Q,j,$);return{currentUsage:K,burnRate:j,budgetLeft:N,willOverflowAt:F,recommendation:z,confidence:B,modelLimit:Q,windowRemaining:Math.max(0,Math.floor(N/Math.max(j,1))),input:{...J},computedAtISO:$,turnsAnalyzed:q.length}}var H={"oracle-verified":0.25,"no-progress-detector":0.2,"deviation-detector":0.2,"iteration-budget":0.15,"lesson-recall":0.1,"token-predictor":0.1},_=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function VJ(J){let K=[];K.push({source:"oracle-verified",rawScore:J.oracleVerified?0.6:0,weight:H["oracle-verified"],weightedScore:J.oracleVerified?0.6*H["oracle-verified"]:0,description:J.oracleVerified?"Oracle verification passed":"No Oracle verification"}),K.push({source:"no-progress-detector",rawScore:J.noProgress?-0.8:0,weight:H["no-progress-detector"],weightedScore:J.noProgress?-0.8*H["no-progress-detector"]:0,description:J.noProgress?"No progress detected in last turn":"Progress detected"});let Q=WJ(J.deviations);K.push({source:"deviation-detector",rawScore:Q,weight:H["deviation-detector"],weightedScore:Q*H["deviation-detector"],description:J.deviations.length>0?`${J.deviations.length} deviation(s) detected (worst: ${J.deviations[0].severity})`:"No deviations detected"});let Z=BJ(J.iterationRatio);K.push({source:"iteration-budget",rawScore:Z,weight:H["iteration-budget"],weightedScore:Z*H["iteration-budget"],description:`Iteration ratio: ${J.iterationRatio.toFixed(2)} (${J.ambient.iteration}/${J.ambient.maxIterations})`});let $=YJ(J.lessonsRelevant);return K.push({source:"lesson-recall",rawScore:$,weight:H["lesson-recall"],weightedScore:$*H["lesson-recall"],description:J.lessonsRelevant.length>0?`${J.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${HJ(J.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),K}function WJ(J){if(J.length===0)return 0;let K={grave:-0.9,media:-0.5,leve:-0.2},Q=0;for(let $ of J){let X=K[$.severity]??-0.3;if(X<Q)Q=X}let Z=Math.min(J.length*0.05,0.2);return Math.max(Q-Z,-1)}function BJ(J){if(J<=0.5)return-J*0.6;return-0.3-(J-0.5)*1}function YJ(J){if(J.length===0)return 0;let K=0;for(let Q of J)K+=({continue:0.3,info:0,warn:-0.3,stop:-0.7}[Q.advice]??0)*Q.confidence;return Math.max(Math.min(K/J.length,1),-1)}function HJ(J){if(J.length===0)return 0;return J.reduce((K,Q)=>K+Q.confidence,0)/J.length}function FJ(J,K){if(J>=K.continueThreshold)return"continue";if(J<=-K.stopThreshold)return"stop";if(J<=-K.escalateThreshold)return"escalate";if(J<=-K.warnThreshold)return"warn";return"continue"}function GJ(J,K){if(!J.oracleVerified)return"oracle";if(J.deviations.some((Q)=>Q.severity==="grave"))return"user";return K.defaultEscalationTarget}function u(J,K,Q,Z){if(Z)return`Paralysis detected: forced continue despite score ${J.toFixed(3)} (too many consecutive stops)`;let $=[...Q].sort((V,B)=>V.weightedScore-B.weightedScore),X=$[0],q=$[$.length-1],j=[];if(X.weightedScore<0)j.push(`primary concern: ${X.description}`);if(q.weightedScore>0)j.push(`positive signal: ${q.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[K]} (score: ${J.toFixed(3)}): ${j.join("; ")||"balanced signals"}`}function C(J,K){let Q={..._(),...K},Z=VJ(J),$=Z.reduce((z,W)=>z+W.weightedScore,0),X=Math.max(Math.min($,1),-1),q=J.slotMemory.consecutiveStops>=Q.paralysisThreshold&&X<=-Q.warnThreshold,j=q?"continue":FJ(X,Q),N=[];if(j!=="continue"||Math.abs(X)<Q.continueThreshold){for(let z of Z)if(Math.abs(z.weightedScore)>0.01)N.push({source:z.source,value:z.description,confidence:Math.abs(z.rawScore),weight:z.weight});if(N.length===0&&j!=="continue")N.push({source:"ambient",value:u(X,j,Z,q),confidence:0.5,weight:0.1})}let V=j==="escalate"?GJ(J,Q):null;return{decision:{action:j,score:X,reasoning:u(X,j,Z,q),evidence:N,shouldEscalateTo:V},contributions:Z,rawScore:X,paralysisOverride:q,computedAtISO:new Date().toISOString()}}var w=()=>({enabled:!0,maxHistoryPerSession:50,forceContinueAfterStops:3,warnMessageTemplate:"[MetaGovernor] Score {score}: {reasoning}. Evidence: {evidenceCount} signal(s).",escalateMessageTemplate:"[MetaGovernor] Escalating to {target}: {reasoning}",stopMessageTemplate:"[MetaGovernor] STOP — {reasoning}. Evidence: {evidenceCount} signal(s)."});function A(J,K){let Q=J;for(let[Z,$]of Object.entries(K))Q=Q.replaceAll(`{${Z}}`,$);return Q}function PJ(J){return J.length}function E(J,K){let Q={...w(),...K};if(!Q.enabled)return{action:"continue",message:null,historyEntry:{decision:J.scoringResult.decision,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:"Decision handler disabled — pass-through continue"}};let Z=J.scoringResult.decision,$=Z.score,X=Z.reasoning,q=PJ(Z.evidence),j=Z.shouldEscalateTo??Q.defaultEscalationTarget??"oracle";if(J.scoringResult.paralysisOverride)return{action:"continue",message:A(Q.warnMessageTemplate,{score:$.toFixed(3),reasoning:`Paralysis detected — forced continue. ${X}`,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:`Paralysis override: ${X}`}};switch(Z.action){case"continue":return{action:"continue",message:null,historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}};case"warn":return{action:"warn",message:A(Q.warnMessageTemplate,{score:$.toFixed(3),reasoning:X,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}};case"escalate":return{action:"escalate",message:A(Q.escalateMessageTemplate,{target:j,reasoning:X}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:`Escalate to ${j}: ${X}`}};case"stop":return{action:"stop",message:A(Q.stopMessageTemplate,{reasoning:X,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}}}}function UJ(J,K){if(J.length<=K)return{trimmed:[...J],dropped:0};let Q=J.length-K;return{trimmed:J.slice(-K),dropped:Q}}function _J(J){let K=0;for(let Q=J.length-1;Q>=0;Q--)if(J[Q].action==="stop")K++;else break;return K}var d={leve:0,media:1,grave:2};function AJ(J,K,Q){let Z=`${J}-${K}-${Q}`.split("").reduce(($,X)=>($<<5)-$+X.charCodeAt(0)|0,0);return`D-${Math.abs(Z).toString(36)}`}function a(J,K){let Q=d[K]??0;return J.some((Z)=>(d[Z.severity]??0)>=Q)}function wJ(J){let K=new Set;for(let Q of J)K.add(Q.category),K.add(Q.severity);return[...K]}function LJ(J,K){let Q=K.map((Z)=>`[${Z.severity}] ${Z.category}: ${Z.detail}`).join("; ");return`Action "${J.action}" (score ${J.score.toFixed(2)}) after deviations: ${Q}. Reasoning: ${J.reasoning}`}async function R(J,K){let{decision:Q,config:Z,sessionID:$,directory:X,filesChanged:q}=J,j=new Date().toISOString();if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};if(Q.evidence.length===0&&Q.action==="continue")return{lessonSaved:null,decisionSaved:null,reason:"no deviations to learn from"};let N=null,V=null;if(Z.saveDecisions){let W={id:AJ($,Q.action,j),timestampISO:j,action:Q.action,score:Q.score,reasoning:Q.reasoning,sessionID:$,directory:X,deviations:Q.evidence.filter((Y)=>Y.source==="deviation-detector").map((Y)=>({severity:"media",category:Y.source,detail:Y.value}))};try{await K.saveMemory({content:`Decision: ${Q.action} (score ${Q.score.toFixed(2)}). ${Q.reasoning}`,concepts:["meta-governor","decision",Q.action],type:"fact",files:[...q]}),V=W}catch{}}let B=Q.evidence.filter((W)=>W.source==="deviation-detector").map((W)=>({severity:"media",category:W.source,detail:W.value}));if(a(B,Z.minSeverityToLearn)){let W=wJ(B),Y=LJ(Q,B);try{N={id:(await K.saveLesson({content:Y,context:`session:${$} dir:${X}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(Q.score))),tags:W})).id,title:`${Q.action} after ${B[0]?.category??"deviation"}`,content:Y,type:"pattern",concepts:W,confidence:Math.max(0.3,Math.min(0.8,Math.abs(Q.score))),files:[...q],sessionID:$}}catch{}}let z=[];if(V)z.push("decision saved");if(N)z.push("lesson saved");if(!V&&!N)if(!a(B,Z.minSeverityToLearn))z.push("severity below threshold");else z.push("no saveable content");return{lessonSaved:N,decisionSaved:V,reason:z.join("; ")||"no action taken"}}function G(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var c=()=>({enabled:!0,memory:{enabled:!0,query:"",timeoutMs:3000},tokenPredictor:{},scoring:{},decision:{},closedLoop:{},intervention:{mode:"silent",includeDecisionHistory:!0,maxHistoryMessages:5,minActionForMessage:"warn"}}),I={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},OJ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},MJ={action:"continue",message:null,historyEntry:{decision:{action:"continue",score:0,reasoning:"no decision made",evidence:[],shouldEscalateTo:null},action:"continue",timestampISO:new Date().toISOString(),sessionID:"",reasoning:"no decision made"}};function s(J,K=I){let Q=J.maxIterations>0?J.iteration/J.maxIterations:0,Z={...OJ,consecutiveStops:J.consecutiveStops??0};return{oracleVerified:J.oracleVerified,noProgress:J.noProgress,deviations:J.deviations,iterationRatio:Q,lessonsRelevant:K.agentmemory.lessons,slotMemory:Z,ambient:{sessionID:J.sessionID,directory:".",mode:"simple",agentName:J.agentName??"unknown",iteration:J.iteration,maxIterations:J.maxIterations}}}async function T(J,K={}){let Q={...c(),...K};if(!Q.enabled)return{memoryRead:I,tokenPrediction:r(J),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:MJ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=I;if(Q.memory.enabled)try{let V={agentmemory:J.backends.agentmemory,magicContext:J.backends.magicContext,boulderState:J.backends.boulderState};Z=await k({directory:".",sessionID:J.sessionID,query:Q.memory.query||J.toolName},V)}catch{}let $;try{$=x({currentUsage:J.recentTurnTokens.reduce((V,B)=>V+B,0),modelLimit:J.modelLimit??K.modelOverride?.modelLimit??200000,recentTurnTokens:J.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:J.providerID??"",modelID:J.modelID??"",config:Q.tokenPredictor})}catch{$=r(J)}let X=C(s(J,Z),Q.scoring),q={sessionID:J.sessionID,scoringResult:X},j=E(q,Q.decision),N=null;try{if(Q.closedLoop.enabled!==!1)N=await R({decision:j.historyEntry.decision,memoryRead:Z,config:{...G(),...Q.closedLoop},sessionID:J.sessionID,directory:".",filesChanged:[]},J.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:$,scoringResult:X,decision:j,lessonSaved:N,decisionHistory:[j.historyEntry],skipped:!1}}function r(J){let K=J.recentTurnTokens.reduce((Q,Z)=>Q+Z,0);return{burnRate:0,budgetLeft:200000,currentUsage:K,modelLimit:200000,willOverflowAt:null,recommendation:"no-action",confidence:1,windowRemaining:200000,input:{currentUsage:K,modelLimit:200000,recentTurnTokens:J.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:J.providerID??"",modelID:J.modelID??"",config:{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}},computedAtISO:new Date().toISOString(),turnsAnalyzed:J.recentTurnTokens.length}}function D(J){let K={enabled:!1,...J},Q=_(),Z=w(),$=G();return{enabled:K.enabled===!0,memory:{enabled:!0,query:K.memory?.query??"meta_governor_context",timeoutMs:K.memory?.agentmemoryTimeoutMs??2000},tokenPredictor:{compactBurnRateThreshold:K.tokenPredictor?.compactBurnRateThreshold??500,compactUsageThreshold:K.tokenPredictor?.compactUsageThreshold??0.85,switchModelUsageThreshold:K.tokenPredictor?.switchModelUsageThreshold??0.95,delegateConsecutiveHighBurn:K.tokenPredictor?.delegateConsecutiveHighBurn??5},scoring:{...Q,...K.scoring?.continueThreshold!==void 0?{continueThreshold:K.scoring.continueThreshold}:{},...K.scoring?.warnThreshold!==void 0?{warnThreshold:K.scoring.warnThreshold}:{},...K.scoring?.escalateThreshold!==void 0?{escalateThreshold:K.scoring.escalateThreshold}:{},...K.scoring?.stopThreshold!==void 0?{stopThreshold:K.scoring.stopThreshold}:{}},closedLoop:{...$,...K.closedLoop?.saveDecisions!==void 0?{saveDecisions:K.closedLoop.saveDecisions}:{}},decision:{...Z,...K.decision?.maxHistoryPerSession!==void 0?{maxHistoryPerSession:K.decision.maxHistoryPerSession}:{},...K.decision?.forceContinueAfterStops!==void 0?{forceContinueAfterStops:K.decision.forceContinueAfterStops}:{}},modelOverride:K.modelOverride?{providerID:K.modelOverride.providerID,modelID:K.modelOverride.modelID,modelLimit:K.modelOverride.modelLimit,temperature:K.modelOverride.temperature??0.2,topP:K.modelOverride.topP??1,maxTokens:K.modelOverride.maxTokens??2048,reasoning:K.modelOverride.reasoning??!1,verbosity:K.modelOverride.verbosity??"minimal"}:void 0,intervention:{mode:K.intervention?.mode??"silent",includeDecisionHistory:K.intervention?.includeDecisionHistory??!0,maxHistoryMessages:K.intervention?.maxHistoryMessages??5,minActionForMessage:K.intervention?.minActionForMessage??"warn"}}}function kJ(J){return J?.enabled===!0}var P=new Map;function b(J,K){P.set(J,K)}function h(J){let K=P.get(J);if(K!==void 0)P.delete(J);return K}function yJ(J){return P.has(J)}function S(){for(let[J,K]of P)return P.delete(J),K;return}function xJ(){P.clear()}var t={continue:0,warn:1,escalate:2,stop:3};function v(J,K){return t[J]>=t[K]}var n=0;function f(){return n++,`mg-${Date.now()}-${n}`}function m(J={}){return async(Q,Z)=>{let $=Z?.meta_governor??{},X=D($);if(!X.enabled)return{};let q=()=>X.modelOverride?.providerID??J.providerID?.(),j=()=>X.modelOverride?.modelID??J.modelID?.(),N=()=>X.modelOverride?.modelLimit??200000,V=q()??"unknown",B=j()??"unknown";return{"tool.execute.after":async(z,W)=>{if(!X.enabled)return;let Y={sessionID:z.sessionID,toolName:z.tool,toolOutput:W.output,iteration:0,maxIterations:10,oracleVerified:!1,noProgress:!1,filesChanged:0,recentTurnTokens:[],deviations:[],backends:J.backends??{agentmemory:{smartSearch:async()=>({lessons:[],crystals:[]})},magicContext:{slotList:async()=>[]},boulderState:{boulderRead:async()=>[]}},writeBackend:J.writeBackend??{saveMemory:async()=>({id:""}),saveLesson:async()=>({id:""})},config:X,...q()?{providerID:q()}:{},...j()?{modelID:j()}:{},modelLimit:N()};try{let F=await T(Y);if(X.intervention.mode!=="silent"){let U=F.decision;if(U.action!=="continue"&&v(U.action,X.intervention.minActionForMessage))b(z.sessionID,U)}}catch(F){if(typeof console<"u"&&X.modelOverride?.verbosity!=="silent")console.error("[meta-governor] orchestrator error:",F)}},"experimental.chat.messages.transform":async(z,W)=>{if(!X.enabled)return;if(X.intervention.mode!=="message")return;let Y=S();if(!Y)return;if(Y.action==="continue")return;if(!Y.message)return;if(!v(Y.action,X.intervention.minActionForMessage))return;let F=f(),U=f(),g="intervention",e={id:f(),sessionID:g,role:"user",time:{created:Date.now()},agent:"meta-governor",model:{providerID:V,modelID:B}},JJ={id:U,sessionID:g,messageID:F,type:"text",text:Y.message,synthetic:!0};W.messages.unshift({info:e,parts:[JJ]})},"experimental.chat.system.transform":async(z,W)=>{if(!X.enabled)return;if(X.intervention.mode!=="system")return;if(!z.sessionID)return;let Y=h(z.sessionID);if(!Y)return;if(Y.action==="continue")return;if(!Y.message)return;if(!v(Y.action,X.intervention.minActionForMessage))return;W.system.push(`
2
- [MetaGovernor Intervention]`,Y.message,"---")}}}}function CJ(J){let K={severity:J.success?"leve":"grave",category:`recovery:${J.fixStrategy}`,detail:`${J.errorCode}: ${J.context??"no context"}`};return{action:J.success?"continue":"warn",score:J.success?0.5:-0.5,reasoning:`Recovery ${J.success?"succeeded":"failed"}: ${J.fixStrategy} for ${J.errorCode}`,evidence:[{source:"deviation-detector",value:K.detail,confidence:1,weight:J.success?0.3:0.8}],shouldEscalateTo:J.success?null:"oracle"}}var i={leve:0,media:1,grave:2};function o(J,K){let Q=i[K]??0;return J.some((Z)=>(i[Z.severity]??0)>=Q)}async function EJ(J,K,Q){if(!K)return null;let Z=Q?.config??G(),$=CJ(J);if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};let X=[{severity:J.success?"leve":"grave",category:`recovery:${J.fixStrategy}`,detail:`${J.errorCode}: ${J.context??"no context"}`}],q=null,j=null;if(Z.saveDecisions){let V={id:`D-${Math.abs(`${J.sessionID}-${$.action}-${Date.now()}`.split("").reduce((B,z)=>(B<<5)-B+z.charCodeAt(0)|0,0)).toString(36)}`,timestampISO:new Date().toISOString(),action:$.action,score:$.score,reasoning:$.reasoning,sessionID:J.sessionID,directory:J.directory,deviations:X.map((B)=>({severity:B.severity,category:B.category,detail:B.detail}))};try{await K.saveMemory({content:`Decision: ${$.action} (score ${$.score.toFixed(2)}). ${$.reasoning}`,concepts:["meta-governor","decision",$.action,...X.map((B)=>B.category)],type:"fact",files:[...J.filesChanged??[]]}),j=V}catch{}}if(o(X,Z.minSeverityToLearn)){let V=[...new Set(X.flatMap((W)=>[W.category,W.severity]))],B=X.map((W)=>`[${W.severity}] ${W.category}: ${W.detail}`).join("; "),z=`Action "${$.action}" (score ${$.score.toFixed(2)}) after deviations: ${B}. Reasoning: ${$.reasoning}`;try{q={id:(await K.saveLesson({content:z,context:`session:${J.sessionID} dir:${J.directory}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),tags:V})).id,title:`${$.action} after ${X[0]?.category??"recovery"}`,content:z,type:"pattern",concepts:V,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),files:[...J.filesChanged??[]],sessionID:J.sessionID}}catch{}}let N=[];if(j)N.push("decision saved");if(q)N.push("lesson saved");else if(!o(X,Z.minSeverityToLearn))N.push("severity below threshold");if(!j&&!q&&!N.length)N.push("no saveable content");return{lessonSaved:q,decisionSaved:j,reason:N.join("; ")||"no action taken"}}var RJ={id:"omo-meta-governor",server:m()},KK=RJ;export{UJ as trimHistory,h as takeDecision,S as takeAnyDecision,b as storeDecision,C as score,T as runMetaGovernor,EJ as recordRecovery,x as predict,R as observeAndLearn,D as loadOrchestratorConfig,kJ as isMetaGovernorEnabled,yJ as hasDecision,E as handleDecision,jJ as defaultTokenPredictorConfig,_ as defaultScoringConfig,c as defaultOrchestratorConfig,w as defaultDecisionHandlerConfig,G as defaultClosedLoopConfig,KK as default,m as createMetaGovernorPlugin,_J as countConsecutiveStops,xJ as clearAll,l as calculateBurnRate,s as buildDecisionContext,k as aggregateRead};
1
+ var c={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function R(J,K){let Q=performance.now(),Z={...c.limits,...J.limits},$={...c.timeouts,...J.timeouts},[X,q,z]=await Promise.allSettled([zJ(J,K.agentmemory,Z,$.agentmemoryMs),VJ(J,K.magicContext,Z,$.magicContextMs),WJ(J,K.boulderState,Z,$.boulderStateMs)]),V=[],W={},Y=X.status==="fulfilled"?X.value:(C(V,W,"agentmemory",y(X.reason)),E.agentmemory),B=q.status==="fulfilled"?q.value:(C(V,W,"magicContext",y(q.reason)),E.magicContext),j=z.status==="fulfilled"?z.value:(C(V,W,"boulderState",y(z.reason)),E.boulderState);return{query:J.query,timestampISO:new Date().toISOString(),agentmemory:Y,magicContext:B,boulderState:j,degradedSources:V,durationMs:performance.now()-Q,errorMessages:W}}async function zJ(J,K,Q,Z){let $=await D(K.smartSearch({query:J.query,limit:Q.maxLessons}),Z,"agentmemory");return{available:!0,lessons:jJ($.lessons).slice(0,Q.maxLessons).map((q)=>({id:q.id,title:q.title,advice:"info",confidence:q.confidence,concepts:q.concepts}))}}async function VJ(J,K,Q,Z){return{available:!0,slots:(await D(K.slotList({directory:J.directory}),Z,"magicContext")).filter((X)=>X.label.startsWith("meta_governor:")||BJ(X,J.query)).sort((X,q)=>X.label.localeCompare(q.label)).slice(0,Q.maxSlots).map((X)=>({label:X.label,content:X.content}))}}async function WJ(J,K,Q,Z){let $=await D(K.boulderRead({directory:J.directory,sessionID:J.sessionID,query:J.query}),Z,"boulderState");return{available:!0,tasks:$.sort((q,z)=>q.priority-z.priority||z.updatedAtMs-q.updatedAtMs).slice(0,Q.maxTasks).map((q)=>({id:q.id,status:q.status,title:q.title})),planProgress:YJ($)}}function jJ(J){return[...J].sort((K,Q)=>Q.confidence-K.confidence)}function BJ(J,K){let Q=K.toLowerCase();return J.label.toLowerCase().includes(Q)||J.content.toLowerCase().includes(Q)}function YJ(J){if(J.length===0)return 0;return J.filter((Q)=>Q.status==="done").length/J.length}function y(J){if(J instanceof Error)return J.message;if(typeof J==="string")return J;return"unknown error"}function C(J,K,Q,Z){J.push(Q),K[Q]=Z}var E={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function D(J,K,Q){return new Promise((Z,$)=>{let X=setTimeout(()=>$(Error(`${Q} timeout after ${K}ms`)),K);J.then((q)=>{clearTimeout(X),Z(q)},(q)=>{clearTimeout(X),$(q)})})}function GJ(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function s(J){if(J.length===0)return 0;return J.reduce((Q,Z)=>Q+Z,0)/J.length}function HJ(J,K){let Q=0;for(let Z=J.length-1;Z>=0;Z--)if(J[Z]>=K)Q++;else break;return Q}function FJ(J,K,Q,Z){let $=K-J;if($<=0)return Z;if(Q<=0)return null;let X=Math.floor($/Q);if(X<=0)return Z;let q=X*2;return new Date(new Date(Z).getTime()+q*1000).toISOString()}function b(J){let{currentUsage:K,modelLimit:Q,recentTurnTokens:Z,timestampISO:$,config:X}=J,q=Z.slice(-X.windowSize),z=s(q),V=Q-K,W=Q>0?K/Q:1,Y=Math.min(0.95,0.3+q.length/X.windowSize*0.65),B="no-action",j="within normal parameters";if(W>=X.switchModelUsageThreshold)B="switch-model",j=`context usage ${(W*100).toFixed(1)}% exceeds switch threshold ${(X.switchModelUsageThreshold*100).toFixed(1)}%`;if(W>=X.compactUsageThreshold||z>=X.compactBurnRateThreshold){if(B==="no-action")B="compact-now",j=W>=X.compactUsageThreshold?`context usage ${(W*100).toFixed(1)}% exceeds compact threshold ${(X.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${z.toFixed(0)} tokens/turn exceeds threshold ${X.compactBurnRateThreshold}`}let F=HJ(q,X.compactBurnRateThreshold);if(F>=X.delegateConsecutiveHighBurn&&B==="no-action")B="delegate-to-subagent",j=`${F} consecutive high-burn turns (threshold: ${X.delegateConsecutiveHighBurn})`;let H=FJ(K,Q,z,$);return{currentUsage:K,burnRate:z,budgetLeft:V,willOverflowAt:H,recommendation:B,confidence:Y,modelLimit:Q,windowRemaining:Math.max(0,Math.floor(V/Math.max(z,1))),input:{...J},computedAtISO:$,turnsAnalyzed:q.length}}var P={"oracle-verified":0.25,"no-progress-detector":0.2,"deviation-detector":0.2,"iteration-budget":0.15,"lesson-recall":0.1,"token-predictor":0.1},L=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function UJ(J){let K=[];K.push({source:"oracle-verified",rawScore:J.oracleVerified?0.6:0,weight:P["oracle-verified"],weightedScore:J.oracleVerified?0.6*P["oracle-verified"]:0,description:J.oracleVerified?"Oracle verification passed":"No Oracle verification"}),K.push({source:"no-progress-detector",rawScore:J.noProgress?-0.8:0,weight:P["no-progress-detector"],weightedScore:J.noProgress?-0.8*P["no-progress-detector"]:0,description:J.noProgress?"No progress detected in last turn":"Progress detected"});let Q=PJ(J.deviations);K.push({source:"deviation-detector",rawScore:Q,weight:P["deviation-detector"],weightedScore:Q*P["deviation-detector"],description:J.deviations.length>0?`${J.deviations.length} deviation(s) detected (worst: ${J.deviations[0].severity})`:"No deviations detected"});let Z=NJ(J.iterationRatio);K.push({source:"iteration-budget",rawScore:Z,weight:P["iteration-budget"],weightedScore:Z*P["iteration-budget"],description:`Iteration ratio: ${J.iterationRatio.toFixed(2)} (${J.ambient.iteration}/${J.ambient.maxIterations})`});let $=wJ(J.lessonsRelevant);return K.push({source:"lesson-recall",rawScore:$,weight:P["lesson-recall"],weightedScore:$*P["lesson-recall"],description:J.lessonsRelevant.length>0?`${J.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${AJ(J.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),K}function PJ(J){if(J.length===0)return 0;let K={grave:-0.9,media:-0.5,leve:-0.2},Q=0;for(let $ of J){let X=K[$.severity]??-0.3;if(X<Q)Q=X}let Z=Math.min(J.length*0.05,0.2);return Math.max(Q-Z,-1)}function NJ(J){if(J<=0.5)return-J*0.6;return-0.3-(J-0.5)*1}function wJ(J){if(J.length===0)return 0;let K=0;for(let Q of J)K+=({continue:0.3,info:0,warn:-0.3,stop:-0.7}[Q.advice]??0)*Q.confidence;return Math.max(Math.min(K/J.length,1),-1)}function AJ(J){if(J.length===0)return 0;return J.reduce((K,Q)=>K+Q.confidence,0)/J.length}function _J(J,K){if(J>=K.continueThreshold)return"continue";if(J<=-K.stopThreshold)return"stop";if(J<=-K.escalateThreshold)return"escalate";if(J<=-K.warnThreshold)return"warn";return"continue"}function LJ(J,K){if(!J.oracleVerified)return"oracle";if(J.deviations.some((Q)=>Q.severity==="grave"))return"user";return K.defaultEscalationTarget}function n(J,K,Q,Z){if(Z)return`Paralysis detected: forced continue despite score ${J.toFixed(3)} (too many consecutive stops)`;let $=[...Q].sort((W,Y)=>W.weightedScore-Y.weightedScore),X=$[0],q=$[$.length-1],z=[];if(X.weightedScore<0)z.push(`primary concern: ${X.description}`);if(q.weightedScore>0)z.push(`positive signal: ${q.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[K]} (score: ${J.toFixed(3)}): ${z.join("; ")||"balanced signals"}`}function x(J,K){let Q={...L(),...K},Z=UJ(J),$=Z.reduce((B,j)=>B+j.weightedScore,0),X=Math.max(Math.min($,1),-1),q=J.slotMemory.consecutiveStops>=Q.paralysisThreshold&&X<=-Q.warnThreshold,z=q?"continue":_J(X,Q),V=[];if(z!=="continue"||Math.abs(X)<Q.continueThreshold){for(let B of Z)if(Math.abs(B.weightedScore)>0.01)V.push({source:B.source,value:B.description,confidence:Math.abs(B.rawScore),weight:B.weight});if(V.length===0&&z!=="continue")V.push({source:"ambient",value:n(X,z,Z,q),confidence:0.5,weight:0.1})}let W=z==="escalate"?LJ(J,Q):null;return{decision:{action:z,score:X,reasoning:n(X,z,Z,q),evidence:V,shouldEscalateTo:W},contributions:Z,rawScore:X,paralysisOverride:q,computedAtISO:new Date().toISOString()}}var M=()=>({enabled:!0,maxHistoryPerSession:50,forceContinueAfterStops:3,warnMessageTemplate:"[MetaGovernor] Score {score}: {reasoning}. Evidence: {evidenceCount} signal(s).",escalateMessageTemplate:"[MetaGovernor] Escalating to {target}: {reasoning}",stopMessageTemplate:"[MetaGovernor] STOP — {reasoning}. Evidence: {evidenceCount} signal(s)."});function O(J,K){let Q=J;for(let[Z,$]of Object.entries(K))Q=Q.replaceAll(`{${Z}}`,$);return Q}function OJ(J){return J.length}function I(J,K){let Q={...M(),...K};if(!Q.enabled)return{action:"continue",message:null,historyEntry:{decision:J.scoringResult.decision,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:"Decision handler disabled — pass-through continue"}};let Z=J.scoringResult.decision,$=Z.score,X=Z.reasoning,q=OJ(Z.evidence),z=Z.shouldEscalateTo??Q.defaultEscalationTarget??"oracle";if(J.scoringResult.paralysisOverride)return{action:"continue",message:O(Q.warnMessageTemplate,{score:$.toFixed(3),reasoning:`Paralysis detected — forced continue. ${X}`,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:`Paralysis override: ${X}`}};switch(Z.action){case"continue":return{action:"continue",message:null,historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}};case"warn":return{action:"warn",message:O(Q.warnMessageTemplate,{score:$.toFixed(3),reasoning:X,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}};case"escalate":return{action:"escalate",message:O(Q.escalateMessageTemplate,{target:z,reasoning:X}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:`Escalate to ${z}: ${X}`}};case"stop":return{action:"stop",message:O(Q.stopMessageTemplate,{reasoning:X,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:J.sessionID,reasoning:X}}}}function MJ(J,K){if(J.length<=K)return{trimmed:[...J],dropped:0};let Q=J.length-K;return{trimmed:J.slice(-K),dropped:Q}}function kJ(J){let K=0;for(let Q=J.length-1;Q>=0;Q--)if(J[Q].action==="stop")K++;else break;return K}var i={leve:0,media:1,grave:2};function yJ(J,K,Q){let Z=`${J}-${K}-${Q}`.split("").reduce(($,X)=>($<<5)-$+X.charCodeAt(0)|0,0);return`D-${Math.abs(Z).toString(36)}`}function t(J,K){let Q=i[K]??0;return J.some((Z)=>(i[Z.severity]??0)>=Q)}function CJ(J){let K=new Set;for(let Q of J)K.add(Q.category),K.add(Q.severity);return[...K]}function EJ(J,K){let Q=K.map((Z)=>`[${Z.severity}] ${Z.category}: ${Z.detail}`).join("; ");return`Action "${J.action}" (score ${J.score.toFixed(2)}) after deviations: ${Q}. Reasoning: ${J.reasoning}`}async function h(J,K){let{decision:Q,config:Z,sessionID:$,directory:X,filesChanged:q}=J,z=new Date().toISOString();if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};if(Q.evidence.length===0&&Q.action==="continue")return{lessonSaved:null,decisionSaved:null,reason:"no deviations to learn from"};let V=null,W=null;if(Z.saveDecisions){let j={id:yJ($,Q.action,z),timestampISO:z,action:Q.action,score:Q.score,reasoning:Q.reasoning,sessionID:$,directory:X,deviations:Q.evidence.filter((F)=>F.source==="deviation-detector").map((F)=>({severity:"media",category:F.source,detail:F.value}))};try{await K.saveMemory({content:`Decision: ${Q.action} (score ${Q.score.toFixed(2)}). ${Q.reasoning}`,concepts:["meta-governor","decision",Q.action],type:"fact",files:[...q]}),W=j}catch{}}let Y=Q.evidence.filter((j)=>j.source==="deviation-detector").map((j)=>({severity:"media",category:j.source,detail:j.value}));if(t(Y,Z.minSeverityToLearn)){let j=CJ(Y),F=EJ(Q,Y);try{V={id:(await K.saveLesson({content:F,context:`session:${$} dir:${X}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(Q.score))),tags:j})).id,title:`${Q.action} after ${Y[0]?.category??"deviation"}`,content:F,type:"pattern",concepts:j,confidence:Math.max(0.3,Math.min(0.8,Math.abs(Q.score))),files:[...q],sessionID:$}}catch{}}let B=[];if(W)B.push("decision saved");if(V)B.push("lesson saved");if(!W&&!V)if(!t(Y,Z.minSeverityToLearn))B.push("severity below threshold");else B.push("no saveable content");return{lessonSaved:V,decisionSaved:W,reason:B.join("; ")||"no action taken"}}function N(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var e=()=>({enabled:!0,memory:{enabled:!0,query:"",timeoutMs:3000},tokenPredictor:{},scoring:{},decision:{},closedLoop:{},intervention:{mode:"silent",includeDecisionHistory:!0,maxHistoryMessages:5,minActionForMessage:"warn"},protocolEnforcement:{enabled:!1,path:void 0,injectIntoSystem:!1,auditToolCalls:!1}}),S={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},RJ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},DJ={action:"continue",message:null,historyEntry:{decision:{action:"continue",score:0,reasoning:"no decision made",evidence:[],shouldEscalateTo:null},action:"continue",timestampISO:new Date().toISOString(),sessionID:"",reasoning:"no decision made"}};function JJ(J,K=S){let Q=J.maxIterations>0?J.iteration/J.maxIterations:0,Z={...RJ,consecutiveStops:J.consecutiveStops??0};return{oracleVerified:J.oracleVerified,noProgress:J.noProgress,deviations:J.deviations,iterationRatio:Q,lessonsRelevant:K.agentmemory.lessons,slotMemory:Z,ambient:{sessionID:J.sessionID,directory:".",mode:"simple",agentName:J.agentName??"unknown",iteration:J.iteration,maxIterations:J.maxIterations}}}async function T(J,K={}){let Q={...e(),...K};if(!Q.enabled)return{memoryRead:S,tokenPrediction:o(J),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:DJ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=S;if(Q.memory.enabled)try{let W={agentmemory:J.backends.agentmemory,magicContext:J.backends.magicContext,boulderState:J.backends.boulderState};Z=await R({directory:".",sessionID:J.sessionID,query:Q.memory.query||J.toolName},W)}catch{}let $;try{$=b({currentUsage:J.recentTurnTokens.reduce((W,Y)=>W+Y,0),modelLimit:J.modelLimit??K.modelOverride?.modelLimit??200000,recentTurnTokens:J.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:J.providerID??"",modelID:J.modelID??"",config:Q.tokenPredictor})}catch{$=o(J)}let X=x(JJ(J,Z),Q.scoring),q={sessionID:J.sessionID,scoringResult:X},z=I(q,Q.decision),V=null;try{if(Q.closedLoop.enabled!==!1)V=await h({decision:z.historyEntry.decision,memoryRead:Z,config:{...N(),...Q.closedLoop},sessionID:J.sessionID,directory:".",filesChanged:[]},J.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:$,scoringResult:X,decision:z,lessonSaved:V,decisionHistory:[z.historyEntry],skipped:!1}}function o(J){let K=J.recentTurnTokens.reduce((Q,Z)=>Q+Z,0);return{burnRate:0,budgetLeft:200000,currentUsage:K,modelLimit:200000,willOverflowAt:null,recommendation:"no-action",confidence:1,windowRemaining:200000,input:{currentUsage:K,modelLimit:200000,recentTurnTokens:J.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:J.providerID??"",modelID:J.modelID??"",config:{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}},computedAtISO:new Date().toISOString(),turnsAnalyzed:J.recentTurnTokens.length}}function v(J){let K={enabled:!1,...J},Q=L(),Z=M(),$=N();return{enabled:K.enabled===!0,memory:{enabled:!0,query:K.memory?.query??"meta_governor_context",timeoutMs:K.memory?.agentmemoryTimeoutMs??2000},tokenPredictor:{compactBurnRateThreshold:K.tokenPredictor?.compactBurnRateThreshold??500,compactUsageThreshold:K.tokenPredictor?.compactUsageThreshold??0.85,switchModelUsageThreshold:K.tokenPredictor?.switchModelUsageThreshold??0.95,delegateConsecutiveHighBurn:K.tokenPredictor?.delegateConsecutiveHighBurn??5},scoring:{...Q,...K.scoring?.continueThreshold!==void 0?{continueThreshold:K.scoring.continueThreshold}:{},...K.scoring?.warnThreshold!==void 0?{warnThreshold:K.scoring.warnThreshold}:{},...K.scoring?.escalateThreshold!==void 0?{escalateThreshold:K.scoring.escalateThreshold}:{},...K.scoring?.stopThreshold!==void 0?{stopThreshold:K.scoring.stopThreshold}:{}},closedLoop:{...$,...K.closedLoop?.saveDecisions!==void 0?{saveDecisions:K.closedLoop.saveDecisions}:{}},decision:{...Z,...K.decision?.maxHistoryPerSession!==void 0?{maxHistoryPerSession:K.decision.maxHistoryPerSession}:{},...K.decision?.forceContinueAfterStops!==void 0?{forceContinueAfterStops:K.decision.forceContinueAfterStops}:{}},modelOverride:K.modelOverride?{providerID:K.modelOverride.providerID,modelID:K.modelOverride.modelID,modelLimit:K.modelOverride.modelLimit,temperature:K.modelOverride.temperature??0.2,topP:K.modelOverride.topP??1,maxTokens:K.modelOverride.maxTokens??2048,reasoning:K.modelOverride.reasoning??!1,verbosity:K.modelOverride.verbosity??"minimal"}:void 0,intervention:{mode:K.intervention?.mode??"silent",includeDecisionHistory:K.intervention?.includeDecisionHistory??!0,maxHistoryMessages:K.intervention?.maxHistoryMessages??5,minActionForMessage:K.intervention?.minActionForMessage??"warn"},protocolEnforcement:{enabled:K.protocolEnforcement?.enabled??!1,path:K.protocolEnforcement?.path,injectIntoSystem:K.protocolEnforcement?.injectIntoSystem??!1,auditToolCalls:K.protocolEnforcement?.auditToolCalls??!1}}}function bJ(J){return J?.enabled===!0}var w=new Map;function f(J,K){w.set(J,K)}function g(J){let K=w.get(J);if(K!==void 0)w.delete(J);return K}function xJ(J){return w.has(J)}function p(){for(let[J,K]of w)return w.delete(J),K;return}function IJ(){w.clear()}import{readFile as hJ}from"node:fs/promises";import{resolve as SJ}from"node:path";import{homedir as TJ}from"node:os";var k=SJ(TJ(),".config","opencode","sisyphus-mandatory","sisyphus-mandatory.md");async function m(J){return await hJ(J??k,"utf-8")}function l(J){let K=["","## Sisyphus Protocol Enforcement","","You MUST follow these Sisyphus protocol rules:","","1. **Pre-response Memory Check**: Before any action, read `<project-memory>` and `<session-history-since>` blocks in context. Cite `<memory id>` for any fact used from memory. Do not ask questions whose answers are in those blocks.","","2. **Codebase Graph First**: Before using grep/glob/read for architecture or symbol queries, check whether `.codegraph/` or `graphify-out/` exists. If so, use codegraph/graphify tools first. Fall back to AFT (aft_zoom, aft_outline), then grep/read only as last resort.","","3. **Tool Routing Table**: Match common intents to the correct tool:",' - "we did this before" / "you should know" → `agentmemory_memory_recall`',' - "the usual" / "as configured" → `ctx_memory(action="list")`'," - Starting a task that resembles a previous one → `agentmemory_memory_smart_search`",' - "what changed" / "history" → `ctx_search`'," - Before asking the user a clarifying question → `agentmemory_memory_recall` first",""];if(/\boracle\b/i.test(J))K.push("4. **Post-task Oracle Verification**: If files touched >= 3 OR any INVOKE trigger matches, invoke Oracle with the exact format:",' `task(subagent_type="oracle", run_in_background=false, prompt="Verify: ...")`'," - INVOKE triggers: created 1+ new file, modified abstraction, touched security/auth paths, modified DB/persistence, modified CI/CD, added/removed dependency, modified perf-critical path, todo had 2+ completed items."," - SKIP only when: files touched <= 2, no new file, no dependency change, single-step task, change is typo/comment/rename only."," - Verdict: PASS → done. FAIL/CONDITIONAL → fix and re-invoke. Max 3 invocations."," - Cost: Max 3 oracle invocations per task. Skip rate: Must NOT skip Oracle on 2+ file change.","");return K.push("5. **Parallel Query Rule**: Fire independent tool queries in the same turn. Do NOT serialize independent memory/context queries.","","6. **Empty-Result Escalation**: On empty `agentmemory_memory_recall`, fire `agentmemory_memory_smart_search` + `ctx_search` + `agentmemory_memory_export` before asking the user.","","7. **Hard Rules (No Exceptions)**:"," - Do NOT ask 'where is X?' if memory or session record already contains it."," - Do NOT claim 'I don't know' before firing at least 2 different recall tools."," - Do NOT re-issue clarifying questions whose answer is in `<project-memory>` or `<session-history-since>`."," - Do NOT use grep/find when aft_outline would answer the structure question."," - Do NOT duplicate a memory in both `agentmemory_memory_save` and `ctx_memory` — pick ONE.","","8. **Self-Check Before Responding**:"," - Verify you read `<project-memory>` and `<session-history-since>` blocks."," - Verify you cited `<memory id>` for any fact used from memory."," - Verify you did not ask a question whose answer is in those blocks."," - For multi-file changes, verify Oracle was invoked."," - For codebase exploration, verify codegraph/graphify was tried before grep/read.",""),K.join(`
2
+ `)}function vJ(J,K,Q){let Z=[];if((J==="grep"||J==="glob")&&(Q.hasCodegraphDir||Q.hasGraphifyDir)){let q=Q.hasCodegraphDir?".codegraph":"graphify-out";Z.push({rule:"codebase-graph-first",tool:J,severity:"media",detail:`Used ${J} when ${q} exists — should use codegraph/graphify first for architecture and symbol queries.`})}if(Q.emptyRecall&&!Q.escalationAttempted){if(J.startsWith("question")||J==="ask")Z.push({rule:"empty-result-escalation",tool:J,severity:"grave",detail:"Memory recall returned empty but agent did not fire smart_search + ctx_search + export before asking the user. Steps 1-3 of empty-result escalation protocol are mandatory."})}let $=["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"];if(!Q.memoryToolsUsed.some((q)=>$.some((z)=>q.startsWith(z)))&&(J.startsWith("question")||J==="ask"))Z.push({rule:"memory-first",tool:J,severity:"grave",detail:"Asked a question without first querying memory (agentmemory or ctx_memory). Must fire agentmemory_memory_recall or ctx_memory before asking the user."});if(Q.filesChanged>=3&&!Q.oracleInvoked){if(J!=="task"||!K||typeof K!=="object"||!("subagent_type"in K))Z.push({rule:"oracle-verification",tool:J,severity:"media",detail:`Files changed (${Q.filesChanged}) >= 3 but Oracle was not invoked. The POST-TASK ORACLE VERIFICATION protocol requires Oracle invocation on multi-file changes.`})}return Z}var KJ={continue:0,warn:1,escalate:2,stop:3};function u(J,K){return KJ[J]>=KJ[K]}var QJ=0;function d(){return QJ++,`mg-${Date.now()}-${QJ}`}function a(J={}){return async(Q,Z)=>{let $=Z?.meta_governor??{},X=v($);if(!X.enabled)return{};let q=()=>X.modelOverride?.providerID??J.providerID?.(),z=()=>X.modelOverride?.modelID??J.modelID?.(),V=()=>X.modelOverride?.modelLimit??200000,W=q()??"unknown",Y=z()??"unknown",B,j;if(X.protocolEnforcement.enabled||X.protocolEnforcement.injectIntoSystem){let H=X.protocolEnforcement.path??k;m(H).then((G)=>{B=G,j=l(G)}).catch((G)=>{if(typeof console<"u"&&X.modelOverride?.verbosity!=="silent")console.warn("[meta-governor] could not load protocol:",G instanceof Error?G.message:G)})}let F=new Map;return{"tool.execute.before":async(H)=>{if(!X.enabled)return;if(!X.protocolEnforcement.auditToolCalls)return;if(!H.sessionID)return;let G=F.get(H.sessionID);if(!G)G={memoryToolsUsed:[],hasCodegraphDir:!1,hasGraphifyDir:!1,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1},F.set(H.sessionID,G);if(j)console.log("[meta-governor] protocol loaded, system injection ready")},"tool.execute.after":async(H,G)=>{if(!X.enabled)return;let U={sessionID:H.sessionID,toolName:H.tool,toolOutput:G.output,iteration:0,maxIterations:10,oracleVerified:!1,noProgress:!1,filesChanged:0,recentTurnTokens:[],deviations:[],backends:J.backends??{agentmemory:{smartSearch:async()=>({lessons:[],crystals:[]})},magicContext:{slotList:async()=>[]},boulderState:{boulderRead:async()=>[]}},writeBackend:J.writeBackend??{saveMemory:async()=>({id:""}),saveLesson:async()=>({id:""})},config:X,...q()?{providerID:q()}:{},...z()?{modelID:z()}:{},modelLimit:V()};try{let A=await T(U);if(X.intervention.mode!=="silent"){let _=A.decision;if(_.action!=="continue"&&u(_.action,X.intervention.minActionForMessage))f(H.sessionID,_)}}catch(A){if(typeof console<"u"&&X.modelOverride?.verbosity!=="silent")console.error("[meta-governor] orchestrator error:",A)}},"experimental.chat.messages.transform":async(H,G)=>{if(!X.enabled)return;if(X.intervention.mode!=="message")return;let U=p();if(!U)return;if(U.action==="continue")return;if(!U.message)return;if(!u(U.action,X.intervention.minActionForMessage))return;let A=d(),_=d(),r="intervention",$J={id:d(),sessionID:r,role:"user",time:{created:Date.now()},agent:"meta-governor",model:{providerID:W,modelID:Y}},qJ={id:_,sessionID:r,messageID:A,type:"text",text:U.message,synthetic:!0};G.messages.unshift({info:$J,parts:[qJ]})},"experimental.chat.system.transform":async(H,G)=>{if(!X.enabled)return;if(X.protocolEnforcement.injectIntoSystem&&j)G.system.push(`
3
+ ### ⚙ Sisyphus Protocol Enforcement`,j,"---");if(X.intervention.mode==="system"&&H.sessionID){let U=g(H.sessionID);if(U&&U.action!=="continue"&&U.message){if(u(U.action,X.intervention.minActionForMessage))G.system.push(`
4
+ [MetaGovernor Intervention]`,U.message,"---")}}}}}}function fJ(J){let K={severity:J.success?"leve":"grave",category:`recovery:${J.fixStrategy}`,detail:`${J.errorCode}: ${J.context??"no context"}`};return{action:J.success?"continue":"warn",score:J.success?0.5:-0.5,reasoning:`Recovery ${J.success?"succeeded":"failed"}: ${J.fixStrategy} for ${J.errorCode}`,evidence:[{source:"deviation-detector",value:K.detail,confidence:1,weight:J.success?0.3:0.8}],shouldEscalateTo:J.success?null:"oracle"}}var XJ={leve:0,media:1,grave:2};function ZJ(J,K){let Q=XJ[K]??0;return J.some((Z)=>(XJ[Z.severity]??0)>=Q)}async function gJ(J,K,Q){if(!K)return null;let Z=Q?.config??N(),$=fJ(J);if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};let X=[{severity:J.success?"leve":"grave",category:`recovery:${J.fixStrategy}`,detail:`${J.errorCode}: ${J.context??"no context"}`}],q=null,z=null;if(Z.saveDecisions){let W={id:`D-${Math.abs(`${J.sessionID}-${$.action}-${Date.now()}`.split("").reduce((Y,B)=>(Y<<5)-Y+B.charCodeAt(0)|0,0)).toString(36)}`,timestampISO:new Date().toISOString(),action:$.action,score:$.score,reasoning:$.reasoning,sessionID:J.sessionID,directory:J.directory,deviations:X.map((Y)=>({severity:Y.severity,category:Y.category,detail:Y.detail}))};try{await K.saveMemory({content:`Decision: ${$.action} (score ${$.score.toFixed(2)}). ${$.reasoning}`,concepts:["meta-governor","decision",$.action,...X.map((Y)=>Y.category)],type:"fact",files:[...J.filesChanged??[]]}),z=W}catch{}}if(ZJ(X,Z.minSeverityToLearn)){let W=[...new Set(X.flatMap((j)=>[j.category,j.severity]))],Y=X.map((j)=>`[${j.severity}] ${j.category}: ${j.detail}`).join("; "),B=`Action "${$.action}" (score ${$.score.toFixed(2)}) after deviations: ${Y}. Reasoning: ${$.reasoning}`;try{q={id:(await K.saveLesson({content:B,context:`session:${J.sessionID} dir:${J.directory}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),tags:W})).id,title:`${$.action} after ${X[0]?.category??"recovery"}`,content:B,type:"pattern",concepts:W,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),files:[...J.filesChanged??[]],sessionID:J.sessionID}}catch{}}let V=[];if(z)V.push("decision saved");if(q)V.push("lesson saved");else if(!ZJ(X,Z.minSeverityToLearn))V.push("severity below threshold");if(!z&&!q&&!V.length)V.push("no saveable content");return{lessonSaved:q,decisionSaved:z,reason:V.join("; ")||"no action taken"}}var pJ={id:"omo-meta-governor",server:a()},PK=pJ;export{MJ as trimHistory,g as takeDecision,p as takeAnyDecision,f as storeDecision,x as score,T as runMetaGovernor,gJ as recordRecovery,b as predict,h as observeAndLearn,m as loadProtocol,v as loadOrchestratorConfig,bJ as isMetaGovernorEnabled,xJ as hasDecision,I as handleDecision,GJ as defaultTokenPredictorConfig,L as defaultScoringConfig,e as defaultOrchestratorConfig,M as defaultDecisionHandlerConfig,N as defaultClosedLoopConfig,PK as default,a as createMetaGovernorPlugin,kJ as countConsecutiveStops,IJ as clearAll,s as calculateBurnRate,l as buildSystemInjection,JJ as buildDecisionContext,vJ as auditToolCall,R as aggregateRead,k as DEFAULT_PROTOCOL_PATH};
3
5
 
4
- //# debugId=E670D00FFE84675964756E2164756E21
6
+ //# debugId=8F1D42E49502FCD664756E2164756E21
5
7
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,20 +1,21 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/memory-aggregator.ts", "../src/token-predictor.ts", "../src/scoring-engine.ts", "../src/decision-handler.ts", "../src/closed-loop-learning.ts", "../src/orchestrator.ts", "../src/config.ts", "../src/decision-store.ts", "../src/plugin.ts", "../src/post-repair-recorder.ts", "../src/index.ts"],
3
+ "sources": ["../src/memory-aggregator.ts", "../src/token-predictor.ts", "../src/scoring-engine.ts", "../src/decision-handler.ts", "../src/closed-loop-learning.ts", "../src/orchestrator.ts", "../src/config.ts", "../src/decision-store.ts", "../src/protocol-enforcer.ts", "../src/plugin.ts", "../src/post-repair-recorder.ts", "../src/index.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * Cross-system memory aggregator for MetaGovernor.\n *\n * PR 2 of 8. Reads from all three memory systems (agentmemory, magic-context,\n * boulder-state) in parallel and returns a `MemoryRead` that conforms to the\n * PR 1 contract (types.ts).\n *\n * Design choices:\n * - Parallel reads with per-source timeouts. No sequential I/O.\n * - Graceful degrade: a failing source does NOT fail the whole read.\n * It populates `degradedSources[]` (string tags per the contract) and\n * the caller (`score()`) can decide the policy.\n * - Lessons are sorted by confidence DESC. Slots by label. Tasks by priority\n * ASC then recency DESC.\n * - Result is bounded: respects `limits`.\n * - Per-source error messages are stored separately (`errorMessages`) for\n * debugging but NOT in the contract type (the contract only has the string tags).\n *\n * Future PRs that wire this:\n * - PR 3 (closed-loop): calls `aggregateRead()` from `observeErrorAndLearn`\n * and `preflightCheck`.\n * - PR 5 (score): calls `aggregateRead()` to build `lessonsRelevant` slice\n * of `DecisionContext`.\n * - PR 6 (post-repair): calls `aggregateRead()` after a fix to verify.\n *\n * Internal raw types (Lesson, Crystal, Slot, BoulderTask) are defined here\n * as private interfaces representing what each backend actually returns.\n * The aggregator maps them to the contract types from types.ts.\n */\n\nimport type {\n MemoryRead,\n MemorySource,\n RelevantLesson,\n} from \"./types\";\n\n// ---------------------------------------------------------------------------\n// Raw backend types (private to this module — NOT exported to the contract)\n\ninterface RawLesson {\n readonly id: string;\n readonly title: string;\n readonly content: string;\n readonly type: string;\n readonly concepts: readonly string[];\n readonly confidence: number;\n readonly files: readonly string[];\n}\n\ninterface RawCrystal {\n readonly id: string;\n readonly title: string;\n readonly content: string;\n readonly type: string;\n readonly concepts: readonly string[];\n readonly confidence: number;\n readonly files: readonly string[];\n}\n\ninterface RawSlot {\n readonly label: string;\n readonly content: string;\n readonly pinned?: boolean;\n readonly scope?: string;\n readonly sizeLimit?: number;\n readonly updatedAt?: number;\n}\n\ninterface RawBoulderTask {\n readonly id: string;\n readonly title: string;\n readonly priority: number;\n readonly status: string;\n readonly description: string;\n readonly createdAtMs: number;\n readonly updatedAtMs: number;\n}\n\n// ---------------------------------------------------------------------------\n// Backend ports (interfaces). Implementations are injected; tests use fakes.\n\nexport interface AgentmemoryBackend {\n smartSearch(input: { query: string; limit?: number }): Promise<{ lessons: RawLesson[]; crystals: RawCrystal[] }>;\n}\n\nexport interface MagicContextBackend {\n slotList(input: { directory?: string; labelPrefix?: string }): Promise<RawSlot[]>;\n}\n\nexport interface BoulderStateBackend {\n boulderRead(input: { directory: string; sessionID: string; query?: string }): Promise<RawBoulderTask[]>;\n}\n\n// ---------------------------------------------------------------------------\n// Aggregate read input\n\nexport interface AggregateReadInput {\n /** Working directory. Scopes the read. */\n readonly directory: string;\n /** Session ID. Used for boulder-state keying. */\n readonly sessionID: string;\n /** Natural-language query. Passed to agentmemory (semantic) and boulder. */\n readonly query: string;\n /** Result-size bounds. */\n readonly limits?: {\n readonly maxLessons?: number;\n readonly maxSlots?: number;\n readonly maxTasks?: number;\n };\n /** Per-source timeout in ms. Default 2000 for agentmemory (network), 1000 for local. */\n readonly timeouts?: {\n readonly agentmemoryMs?: number;\n readonly magicContextMs?: number;\n readonly boulderStateMs?: number;\n };\n}\n\n// ---------------------------------------------------------------------------\n// Extended result (conforms to MemoryRead + adds metadata for debugging)\n\nexport interface AggregateReadResult extends MemoryRead {\n /** Wall-clock duration of the whole read, in ms. */\n readonly durationMs: number;\n /** Per-source error messages (for debugging; not in the contract type). */\n readonly errorMessages: Partial<Record<MemorySource, string>>;\n}\n\n// ---------------------------------------------------------------------------\n// Backends\n\nexport interface Backends {\n agentmemory: AgentmemoryBackend;\n magicContext: MagicContextBackend;\n boulderState: BoulderStateBackend;\n}\n\nconst DEFAULTS = {\n limits: { maxLessons: 10, maxSlots: 20, maxTasks: 10 },\n timeouts: { agentmemoryMs: 2000, magicContextMs: 1000, boulderStateMs: 1000 },\n} as const;\n\n/**\n * Read from all three memory systems in parallel. Never throws — a failing\n * source populates `degradedSources` and the read still returns a valid result.\n */\nexport async function aggregateRead(\n input: AggregateReadInput,\n backends: Backends,\n): Promise<AggregateReadResult> {\n const start = performance.now();\n const limits = { ...DEFAULTS.limits, ...input.limits };\n const timeouts = { ...DEFAULTS.timeouts, ...input.timeouts };\n\n const [agentResult, magicResult, boulderResult] = await Promise.allSettled([\n readAgentmemory(input, backends.agentmemory, limits, timeouts.agentmemoryMs),\n readMagicContext(input, backends.magicContext, limits, timeouts.magicContextMs),\n readBoulderState(input, backends.boulderState, limits, timeouts.boulderStateMs),\n ]);\n\n const degradedSources: MemorySource[] = [];\n const errorMessages: Partial<Record<MemorySource, string>> = {};\n\n const agentmemory = agentResult.status === \"fulfilled\"\n ? agentResult.value\n : (pushDegraded(degradedSources, errorMessages, \"agentmemory\", errorMessage(agentResult.reason)), DEGRADED.agentmemory);\n\n const magicContext = magicResult.status === \"fulfilled\"\n ? magicResult.value\n : (pushDegraded(degradedSources, errorMessages, \"magicContext\", errorMessage(magicResult.reason)), DEGRADED.magicContext);\n\n const boulderState = boulderResult.status === \"fulfilled\"\n ? boulderResult.value\n : (pushDegraded(degradedSources, errorMessages, \"boulderState\", errorMessage(boulderResult.reason)), DEGRADED.boulderState);\n\n return {\n query: input.query,\n timestampISO: new Date().toISOString(),\n agentmemory,\n magicContext,\n boulderState,\n degradedSources,\n durationMs: performance.now() - start,\n errorMessages,\n };\n}\n\n// ---------------------------------------------------------------------------\n// Source readers\n\nasync function readAgentmemory(\n input: AggregateReadInput,\n backend: AgentmemoryBackend,\n limits: Required<NonNullable<AggregateReadInput[\"limits\"]>>,\n timeoutMs: number,\n): Promise<MemoryRead[\"agentmemory\"]> {\n const search = await withTimeout(\n backend.smartSearch({ query: input.query, limit: limits.maxLessons }),\n timeoutMs,\n \"agentmemory\",\n );\n\n const lessons: RelevantLesson[] = sortByConfidence(search.lessons)\n .slice(0, limits.maxLessons)\n .map((l) => ({\n id: l.id,\n title: l.title,\n advice: \"info\" as const,\n confidence: l.confidence,\n concepts: l.concepts,\n }));\n\n return {\n available: true,\n lessons,\n };\n}\n\nasync function readMagicContext(\n input: AggregateReadInput,\n backend: MagicContextBackend,\n limits: Required<NonNullable<AggregateReadInput[\"limits\"]>>,\n timeoutMs: number,\n): Promise<MemoryRead[\"magicContext\"]> {\n const slots = await withTimeout(\n backend.slotList({ directory: input.directory }),\n timeoutMs,\n \"magicContext\",\n );\n\n return {\n available: true,\n slots: slots\n .filter((s) => s.label.startsWith(\"meta_governor:\") || isRelevant(s, input.query))\n .sort((a, b) => a.label.localeCompare(b.label))\n .slice(0, limits.maxSlots)\n .map((s) => ({ label: s.label, content: s.content })),\n };\n}\n\nasync function readBoulderState(\n input: AggregateReadInput,\n backend: BoulderStateBackend,\n limits: Required<NonNullable<AggregateReadInput[\"limits\"]>>,\n timeoutMs: number,\n): Promise<MemoryRead[\"boulderState\"]> {\n const tasks = await withTimeout(\n backend.boulderRead({ directory: input.directory, sessionID: input.sessionID, query: input.query }),\n timeoutMs,\n \"boulderState\",\n );\n\n const sorted = tasks\n .sort((a, b) => a.priority - b.priority || b.updatedAtMs - a.updatedAtMs)\n .slice(0, limits.maxTasks);\n\n return {\n available: true,\n tasks: sorted.map((t) => ({ id: t.id, status: t.status, title: t.title })),\n planProgress: computePlanProgress(tasks),\n };\n}\n\n// ---------------------------------------------------------------------------\n// Helpers\n\nfunction sortByConfidence(lessons: RawLesson[]): RawLesson[] {\n return [...lessons].sort((a, b) => b.confidence - a.confidence);\n}\n\nfunction isRelevant(slot: RawSlot, query: string): boolean {\n const q = query.toLowerCase();\n return slot.label.toLowerCase().includes(q) || slot.content.toLowerCase().includes(q);\n}\n\nfunction computePlanProgress(tasks: RawBoulderTask[]): number {\n if (tasks.length === 0) return 0;\n const done = tasks.filter((t) => t.status === \"done\").length;\n return done / tasks.length;\n}\n\nfunction errorMessage(err: unknown): string {\n if (err instanceof Error) return err.message;\n if (typeof err === \"string\") return err;\n return \"unknown error\";\n}\n\nfunction pushDegraded(\n list: MemorySource[],\n errorMessages: Partial<Record<MemorySource, string>>,\n source: MemorySource,\n reason: string,\n): void {\n list.push(source);\n errorMessages[source] = reason;\n}\n\n// Typed fallback values for degraded sources.\n// These match the contract types exactly — pushDegraded is side-effect only.\nconst DEGRADED = {\n agentmemory: { available: false, lessons: [] } as const satisfies MemoryRead[\"agentmemory\"],\n magicContext: { available: false, slots: [] } as const satisfies MemoryRead[\"magicContext\"],\n boulderState: { available: false, tasks: [], planProgress: 0 } as const satisfies MemoryRead[\"boulderState\"],\n} as const;\n\nasync function withTimeout<T>(p: Promise<T>, ms: number, label: string): Promise<T> {\n return new Promise((resolve, reject) => {\n const t = setTimeout(() => reject(new Error(`${label} timeout after ${ms}ms`)), ms);\n p.then(\n (v) => { clearTimeout(t); resolve(v); },\n (e) => { clearTimeout(t); reject(e); },\n );\n });\n}\n",
6
6
  "/**\n * Token Predictor for MetaGovernor.\n *\n * PR 4 of 8. Computes token burn rate from recent turn metrics and recommends\n * preemptive actions (compact, switch model, delegate) before context window\n * exhaustion.\n *\n * Design:\n * - Pure function with no I/O — takes input, returns prediction.\n * - Configurable thresholds via TokenPredictorConfig.\n * - Burn rate = avg tokens/turn over sliding window.\n * - Overflow prediction: budgetLeft / burnRate = turns left.\n * - Recommendations layered: compact-now > switch-model > delegate > no-action.\n */\n\nimport type {\n TokenPredictorConfig,\n TokenPredictorInput,\n TokenPredictorOutput,\n} from \"./types\"\n\n/**\n * Default configuration for the token predictor.\n */\nexport function defaultTokenPredictorConfig(): TokenPredictorConfig {\n return {\n compactBurnRateThreshold: 500,\n compactUsageThreshold: 0.85,\n switchModelUsageThreshold: 0.95,\n delegateConsecutiveHighBurn: 5,\n windowSize: 10,\n }\n}\n\n/**\n * Calculate burn rate (avg tokens/turn) from recent turn tokens.\n * Returns 0 if no turns provided.\n */\nexport function calculateBurnRate(recentTurnTokens: readonly number[]): number {\n if (recentTurnTokens.length === 0) return 0\n const sum = recentTurnTokens.reduce((a, b) => a + b, 0)\n return sum / recentTurnTokens.length\n}\n\n/**\n * Count consecutive high-burn turns from the end of the window.\n */\nfunction countConsecutiveHighBurn(\n recentTurnTokens: readonly number[],\n threshold: number\n): number {\n let count = 0\n for (let i = recentTurnTokens.length - 1; i >= 0; i--) {\n if (recentTurnTokens[i] >= threshold) {\n count++\n } else {\n break\n }\n }\n return count\n}\n\n/**\n * Determine when overflow will occur based on burn rate and budget.\n * Returns ISO timestamp or null if no overflow expected.\n */\nfunction predictOverflowTime(\n currentUsage: number,\n modelLimit: number,\n burnRate: number,\n timestampISO: string\n): string | null {\n const budgetLeft = modelLimit - currentUsage\n if (budgetLeft <= 0) return timestampISO\n if (burnRate <= 0) return null\n\n const turnsLeft = Math.floor(budgetLeft / burnRate)\n if (turnsLeft <= 0) return timestampISO\n\n // Estimate ~2 seconds per turn as baseline\n const secondsLeft = turnsLeft * 2\n const overflowDate = new Date(\n new Date(timestampISO).getTime() + secondsLeft * 1000\n )\n return overflowDate.toISOString()\n}\n\n/**\n * Core prediction function. Analyzes recent turn tokens and recommends\n * an action to prevent context window exhaustion.\n */\nexport function predict(input: TokenPredictorInput): TokenPredictorOutput {\n const { currentUsage, modelLimit, recentTurnTokens, timestampISO, config } =\n input\n\n // Use at most windowSize recent turns\n const windowTokens = recentTurnTokens.slice(-config.windowSize)\n const burnRate = calculateBurnRate(windowTokens)\n const budgetLeft = modelLimit - currentUsage\n const usageRatio = modelLimit > 0 ? currentUsage / modelLimit : 1\n\n // Calculate confidence: more turns = higher confidence\n const confidence = Math.min(0.95, 0.3 + (windowTokens.length / config.windowSize) * 0.65)\n\n // Determine recommendation\n let recommendation: TokenPredictorOutput[\"recommendation\"] = \"no-action\"\n let reason = \"within normal parameters\"\n\n // Layer 1: Critical — context nearly full\n if (usageRatio >= config.switchModelUsageThreshold) {\n recommendation = \"switch-model\"\n reason = `context usage ${(usageRatio * 100).toFixed(1)}% exceeds switch threshold ${(config.switchModelUsageThreshold * 100).toFixed(1)}%`\n }\n\n // Layer 2: High burn rate or usage above compact threshold\n if (\n usageRatio >= config.compactUsageThreshold ||\n burnRate >= config.compactBurnRateThreshold\n ) {\n if (recommendation === \"no-action\") {\n recommendation = \"compact-now\"\n reason =\n usageRatio >= config.compactUsageThreshold\n ? `context usage ${(usageRatio * 100).toFixed(1)}% exceeds compact threshold ${(config.compactUsageThreshold * 100).toFixed(1)}%`\n : `burn rate ${burnRate.toFixed(0)} tokens/turn exceeds threshold ${config.compactBurnRateThreshold}`\n }\n }\n\n // Layer 3: Sustained high burn → delegate\n const consecutiveHighBurn = countConsecutiveHighBurn(\n windowTokens,\n config.compactBurnRateThreshold\n )\n if (\n consecutiveHighBurn >= config.delegateConsecutiveHighBurn &&\n recommendation === \"no-action\"\n ) {\n recommendation = \"delegate-to-subagent\"\n reason = `${consecutiveHighBurn} consecutive high-burn turns (threshold: ${config.delegateConsecutiveHighBurn})`\n }\n\n const willOverflowAt = predictOverflowTime(\n currentUsage,\n modelLimit,\n burnRate,\n timestampISO\n )\n\n return {\n currentUsage,\n burnRate,\n budgetLeft,\n willOverflowAt,\n recommendation,\n confidence,\n modelLimit,\n windowRemaining: Math.max(0, Math.floor(budgetLeft / Math.max(burnRate, 1))),\n input: { ...input },\n computedAtISO: timestampISO,\n turnsAnalyzed: windowTokens.length,\n }\n}\n",
7
7
  "/**\n * MetaGovernor Scoring Engine — PR 5 of 8.\n *\n * The core decision engine. Takes a DecisionContext (built from signals\n * gathered by the memory-aggregator, token-predictor, and hooks) and\n * produces a Decision via weighted evidence scoring.\n *\n * Architecture invariants:\n * - Pure function: no side effects, no I/O, no MCP calls\n * - Deterministic: same input → same output (no randomness)\n * - All thresholds configurable via ScoringConfig\n * - Paralysis prevention: N consecutive stops → force continue with warning\n * - Cite-or-abstain: evidence required when action !== \"continue\" silently\n *\n * Score ranges (default thresholds):\n * >= +0.3 → continue silently\n * [-0.3, +0.3] → continue with log\n * [-0.6, -0.3] → warn\n * [-0.8, -0.6] → escalate\n * < -0.8 → stop\n */\n\nimport type {\n DecisionContext,\n Decision,\n Evidence,\n EvidenceContribution,\n ScoringConfig,\n ScoringResult,\n RelevantLesson,\n} from \"./types\"\n\n// ─── Default weights ───────────────────────────────────────────────\n\n/** Default weights for each evidence source (must sum to ~1.0). */\nconst DEFAULT_WEIGHTS: Record<string, number> = {\n \"oracle-verified\": 0.25,\n \"no-progress-detector\": 0.20,\n \"deviation-detector\": 0.20,\n \"iteration-budget\": 0.15,\n \"lesson-recall\": 0.10,\n \"token-predictor\": 0.10,\n}\n\n// ─── Default config ────────────────────────────────────────────────\n\nexport const defaultScoringConfig = (): ScoringConfig => ({\n continueThreshold: 0.3,\n warnThreshold: 0.3,\n escalateThreshold: 0.6,\n stopThreshold: 0.8,\n paralysisThreshold: 3,\n defaultEscalationTarget: \"oracle\",\n})\n\n// ─── Signal scoring ────────────────────────────────────────────────\n\n/**\n * Score each signal source independently. Returns raw scores in [-1, +1].\n * Each score represents how POSITIVE (or negative) that signal is.\n */\nfunction scoreSignals(ctx: DecisionContext): EvidenceContribution[] {\n const contributions: EvidenceContribution[] = []\n\n // 1. Oracle verified: +0.6 (strongly positive)\n contributions.push({\n source: \"oracle-verified\",\n rawScore: ctx.oracleVerified ? 0.6 : 0,\n weight: DEFAULT_WEIGHTS[\"oracle-verified\"],\n weightedScore: ctx.oracleVerified ? 0.6 * DEFAULT_WEIGHTS[\"oracle-verified\"] : 0,\n description: ctx.oracleVerified\n ? \"Oracle verification passed\"\n : \"No Oracle verification\",\n })\n\n // 2. No progress: -0.8 (strongly negative)\n contributions.push({\n source: \"no-progress-detector\",\n rawScore: ctx.noProgress ? -0.8 : 0,\n weight: DEFAULT_WEIGHTS[\"no-progress-detector\"],\n weightedScore: ctx.noProgress ? -0.8 * DEFAULT_WEIGHTS[\"no-progress-detector\"] : 0,\n description: ctx.noProgress\n ? \"No progress detected in last turn\"\n : \"Progress detected\",\n })\n\n // 3. Deviations: severity-weighted\n const deviationScore = scoreDeviations(ctx.deviations)\n contributions.push({\n source: \"deviation-detector\",\n rawScore: deviationScore,\n weight: DEFAULT_WEIGHTS[\"deviation-detector\"],\n weightedScore: deviationScore * DEFAULT_WEIGHTS[\"deviation-detector\"],\n description: ctx.deviations.length > 0\n ? `${ctx.deviations.length} deviation(s) detected (worst: ${ctx.deviations[0]!.severity})`\n : \"No deviations detected\",\n })\n\n // 4. Iteration budget: approaching limit → negative\n const iterationScore = scoreIterationBudget(ctx.iterationRatio)\n contributions.push({\n source: \"iteration-budget\",\n rawScore: iterationScore,\n weight: DEFAULT_WEIGHTS[\"iteration-budget\"],\n weightedScore: iterationScore * DEFAULT_WEIGHTS[\"iteration-budget\"],\n description: `Iteration ratio: ${ctx.iterationRatio.toFixed(2)} (${ctx.ambient.iteration}/${ctx.ambient.maxIterations})`,\n })\n\n // 5. Lessons: advice-weighted\n const lessonScore = scoreLessons(ctx.lessonsRelevant)\n contributions.push({\n source: \"lesson-recall\",\n rawScore: lessonScore,\n weight: DEFAULT_WEIGHTS[\"lesson-recall\"],\n weightedScore: lessonScore * DEFAULT_WEIGHTS[\"lesson-recall\"],\n description: ctx.lessonsRelevant.length > 0\n ? `${ctx.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${avgConfidence(ctx.lessonsRelevant).toFixed(2)})`\n : \"No relevant lessons\",\n })\n\n return contributions\n}\n\nfunction scoreDeviations(deviations: readonly { severity: string }[]): number {\n if (deviations.length === 0) return 0\n\n // Score based on worst deviation severity\n const severityMap: Record<string, number> = {\n grave: -0.9,\n media: -0.5,\n leve: -0.2,\n }\n\n let worst = 0\n for (const d of deviations) {\n const s = severityMap[d.severity] ?? -0.3\n if (s < worst) worst = s\n }\n\n // Multiple deviations amplify slightly (capped at -1)\n const amplification = Math.min(deviations.length * 0.05, 0.2)\n return Math.max(worst - amplification, -1)\n}\n\nfunction scoreIterationBudget(ratio: number): number {\n // Linear ramp: 0.0 → 0.0, 0.5 → -0.3, 1.0 → -0.8\n if (ratio <= 0.5) return -ratio * 0.6\n return -0.3 - (ratio - 0.5) * 1.0\n}\n\nfunction scoreLessons(lessons: readonly RelevantLesson[]): number {\n if (lessons.length === 0) return 0\n\n let totalScore = 0\n for (const lesson of lessons) {\n const adviceScore: Record<string, number> = {\n continue: 0.3,\n info: 0.0,\n warn: -0.3,\n stop: -0.7,\n }\n totalScore += (adviceScore[lesson.advice] ?? 0) * lesson.confidence\n }\n\n // Average and clamp\n return Math.max(Math.min(totalScore / lessons.length, 1), -1)\n}\n\nfunction avgConfidence(lessons: readonly RelevantLesson[]): number {\n if (lessons.length === 0) return 0\n return lessons.reduce((sum, l) => sum + l.confidence, 0) / lessons.length\n}\n\n// ─── Action mapping ────────────────────────────────────────────────\n\nfunction mapScoreToAction(\n score: number,\n config: ScoringConfig,\n): Decision[\"action\"] {\n if (score >= config.continueThreshold) return \"continue\"\n if (score <= -config.stopThreshold) return \"stop\"\n if (score <= -config.escalateThreshold) return \"escalate\"\n if (score <= -config.warnThreshold) return \"warn\"\n return \"continue\"\n}\n\nfunction selectEscalationTarget(\n ctx: DecisionContext,\n config: ScoringConfig,\n): \"oracle\" | \"user\" | null {\n // Oracle first if it hasn't been consulted yet in this cycle\n if (!ctx.oracleVerified) return \"oracle\"\n // If oracle already verified and we still have issues, escalate to user\n if (ctx.deviations.some((d) => d.severity === \"grave\")) return \"user\"\n return config.defaultEscalationTarget\n}\n\nfunction buildReasoning(\n score: number,\n action: Decision[\"action\"],\n contributions: EvidenceContribution[],\n paralysisOverride: boolean,\n): string {\n if (paralysisOverride) {\n return `Paralysis detected: forced continue despite score ${score.toFixed(3)} (too many consecutive stops)`\n }\n\n // Find the strongest positive and negative contributions\n const sorted = [...contributions].sort((a, b) => a.weightedScore - b.weightedScore)\n const worst = sorted[0]!\n const best = sorted[sorted.length - 1]!\n\n const parts: string[] = []\n if (worst.weightedScore < 0) {\n parts.push(`primary concern: ${worst.description}`)\n }\n if (best.weightedScore > 0) {\n parts.push(`positive signal: ${best.description}`)\n }\n\n const actionLabel: Record<string, string> = {\n continue: \"Continue\",\n warn: \"Warn\",\n escalate: \"Escalate\",\n stop: \"Stop\",\n }\n\n return `${actionLabel[action]} (score: ${score.toFixed(3)}): ${parts.join(\"; \") || \"balanced signals\"}`\n}\n\n// ─── Public API ────────────────────────────────────────────────────\n\n/**\n * Core scoring function. Pure, deterministic, no side effects.\n *\n * @param ctx - DecisionContext assembled from all signal sources\n * @param config - Scoring thresholds (defaults if omitted)\n * @returns ScoringResult with Decision, evidence breakdown, and metadata\n */\nexport function score(\n ctx: DecisionContext,\n config?: Partial<ScoringConfig>,\n): ScoringResult {\n const resolvedConfig = { ...defaultScoringConfig(), ...config }\n\n // 1. Compute per-signal contributions\n const contributions = scoreSignals(ctx)\n\n // 2. Sum weighted scores → raw score in [-1, +1]\n const rawScore = contributions.reduce((sum, c) => sum + c.weightedScore, 0)\n const clampedScore = Math.max(Math.min(rawScore, 1), -1)\n\n // 3. Check paralysis (3 consecutive stops → force continue)\n const paralysisOverride =\n ctx.slotMemory.consecutiveStops >= resolvedConfig.paralysisThreshold &&\n clampedScore <= -resolvedConfig.warnThreshold\n\n // 4. Map score to action\n const action = paralysisOverride\n ? \"continue\"\n : mapScoreToAction(clampedScore, resolvedConfig)\n\n // 5. Build evidence array (cite-or-abstain)\n const evidence: Evidence[] = []\n if (action !== \"continue\" || Math.abs(clampedScore) < resolvedConfig.continueThreshold) {\n // Non-silent actions require at least 1 evidence unit\n for (const c of contributions) {\n if (Math.abs(c.weightedScore) > 0.01) {\n evidence.push({\n source: c.source,\n value: c.description,\n confidence: Math.abs(c.rawScore),\n weight: c.weight,\n })\n }\n }\n // Ensure at least 1 evidence for non-continue actions\n if (evidence.length === 0 && action !== \"continue\") {\n evidence.push({\n source: \"ambient\",\n value: buildReasoning(clampedScore, action, contributions, paralysisOverride),\n confidence: 0.5,\n weight: 0.1,\n })\n }\n }\n\n // 6. Select escalation target\n const shouldEscalateTo =\n action === \"escalate\" ? selectEscalationTarget(ctx, resolvedConfig) : null\n\n // 7. Build decision\n const decision: Decision = {\n action,\n score: clampedScore,\n reasoning: buildReasoning(clampedScore, action, contributions, paralysisOverride),\n evidence,\n shouldEscalateTo,\n }\n\n return {\n decision,\n contributions,\n rawScore: clampedScore,\n paralysisOverride,\n computedAtISO: new Date().toISOString(),\n }\n}\n",
8
8
  "/**\n * MetaGovernor Decision Handler — PR 6 of 8.\n *\n * Takes a ScoringResult from the scoring engine and dispatches to the\n * appropriate action: continue, warn, escalate, or stop. This is the\n * \"executor\" that translates scoring decisions into concrete outcomes.\n *\n * Architecture invariants:\n * - Pure dispatch: no I/O, no MCP calls, no side effects\n * - DI pattern: backends injected via DecisionHandlerConfig\n * - Audit trail: every decision + outcome recorded in DecisionHistory\n * - Configurable: all thresholds and behaviors overridable\n */\n\nimport type {\n Decision,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n DecisionHandlerOutput,\n ScoringResult,\n Evidence,\n Deviation,\n} from \"./types\"\n\n// ─── Default config ────────────────────────────────────────────────\n\nexport const defaultDecisionHandlerConfig = (): DecisionHandlerConfig => ({\n enabled: true,\n maxHistoryPerSession: 50,\n forceContinueAfterStops: 3,\n warnMessageTemplate:\n \"[MetaGovernor] Score {score}: {reasoning}. Evidence: {evidenceCount} signal(s).\",\n escalateMessageTemplate:\n \"[MetaGovernor] Escalating to {target}: {reasoning}\",\n stopMessageTemplate:\n \"[MetaGovernor] STOP — {reasoning}. Evidence: {evidenceCount} signal(s).\",\n})\n\n// ─── Helpers ────────────────────────────────────────────────────────\n\nfunction formatMessage(template: string, vars: Record<string, string>): string {\n let result = template\n for (const [key, value] of Object.entries(vars)) {\n result = result.replaceAll(`{${key}}`, value)\n }\n return result\n}\n\nfunction evidenceCount(evidence: readonly Evidence[]): number {\n return evidence.length\n}\n\n// ─── Public API ────────────────────────────────────────────────────\n\n/**\n * Core decision handler. Takes a ScoringResult and dispatches to the\n * appropriate action. Pure function — no side effects.\n *\n * @param input - ScoringResult + session context\n * @param config - Handler configuration\n * @returns DecisionHandlerOutput with action taken + message + history entry\n */\nexport function handleDecision(\n input: DecisionHandlerInput,\n config?: Partial<DecisionHandlerConfig>,\n): DecisionHandlerOutput {\n const resolvedConfig = { ...defaultDecisionHandlerConfig(), ...config }\n\n // Disabled = pass-through: always continue\n if (!resolvedConfig.enabled) {\n return {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision: input.scoringResult.decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: \"Decision handler disabled — pass-through continue\",\n },\n }\n }\n\n const decision = input.scoringResult.decision\n const score = decision.score\n const reasoning = decision.reasoning\n const evCount = evidenceCount(decision.evidence)\n const target = decision.shouldEscalateTo ?? resolvedConfig.defaultEscalationTarget ?? \"oracle\"\n\n // Paralysis override: force continue with warning\n if (input.scoringResult.paralysisOverride) {\n const message = formatMessage(\n resolvedConfig.warnMessageTemplate,\n {\n score: score.toFixed(3),\n reasoning: `Paralysis detected — forced continue. ${reasoning}`,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"continue\",\n message,\n historyEntry: {\n decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: `Paralysis override: ${reasoning}`,\n },\n }\n }\n\n // Dispatch by action\n switch (decision.action) {\n case \"continue\": {\n return {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n\n case \"warn\": {\n const message = formatMessage(\n resolvedConfig.warnMessageTemplate,\n {\n score: score.toFixed(3),\n reasoning,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"warn\",\n message,\n historyEntry: {\n decision,\n action: \"warn\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n\n case \"escalate\": {\n const message = formatMessage(\n resolvedConfig.escalateMessageTemplate,\n {\n target,\n reasoning,\n },\n )\n\n return {\n action: \"escalate\",\n message,\n historyEntry: {\n decision,\n action: \"escalate\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: `Escalate to ${target}: ${reasoning}`,\n },\n }\n }\n\n case \"stop\": {\n const message = formatMessage(\n resolvedConfig.stopMessageTemplate,\n {\n reasoning,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"stop\",\n message,\n historyEntry: {\n decision,\n action: \"stop\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n }\n}\n\n/**\n * Trim history to max size. Returns trimmed array + entries dropped count.\n */\nexport function trimHistory(\n history: readonly DecisionHandlerOutput[\"historyEntry\"][],\n maxSize: number,\n): { trimmed: DecisionHandlerOutput[\"historyEntry\"][]; dropped: number } {\n if (history.length <= maxSize) {\n return { trimmed: [...history], dropped: 0 }\n }\n const dropped = history.length - maxSize\n return { trimmed: history.slice(-maxSize), dropped }\n}\n\n/**\n * Count consecutive stops in history (most recent first).\n */\nexport function countConsecutiveStops(\n history: readonly DecisionHandlerOutput[\"historyEntry\"][],\n): number {\n let count = 0\n for (let i = history.length - 1; i >= 0; i--) {\n if (history[i]!.action === \"stop\") {\n count++\n } else {\n break\n }\n }\n return count\n}\n",
9
9
  "/**\n * Closed-loop learning for MetaGovernor.\n *\n * PR 3 of 8. After every repair/action cycle, observeAndLearn() decides\n * whether to persist a lesson or decision record to agentmemory. Future\n * sessions retrieve these via aggregateRead() (PR 2) and factor them into\n * scoring (PR 5).\n *\n * Design:\n * - Pure function with DI backend (no side effects without backend).\n * - config.enabled=false → returns no-op with reason.\n * - Severity threshold: minSeverityToLearn filters what gets saved.\n * - Session cap: maxLessonsPerSession prevents flooding.\n * - Lessons go to agentmemory_memory_save (type: \"pattern\").\n * - Decisions go to agentmemory_memory_save (type: \"fact\").\n * - No file I/O, no MCP calls — just decision logic + DI write.\n */\n\nimport type {\n AgentmemoryWriteBackend,\n ClosedLoopConfig,\n Decision,\n Deviation,\n LearnFromOutcomeInput,\n LearnFromOutcomeOutput,\n LessonLearned,\n MemoryDecision,\n MemoryRead,\n} from \"./types\"\n\n/** Severity ordering for threshold comparison. */\nconst SEVERITY_ORDER: Record<string, number> = {\n leve: 0,\n media: 1,\n grave: 2,\n}\n\n/**\n * Generate a deterministic lesson ID from session + timestamp.\n */\nfunction generateLessonId(sessionID: string, timestamp: string): string {\n const hash = `${sessionID}-${timestamp}`.split(\"\").reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)\n return `L-${Math.abs(hash).toString(36)}`\n}\n\n/**\n * Generate a deterministic decision ID from session + action + timestamp.\n */\nfunction generateDecisionId(sessionID: string, action: string, timestamp: string): string {\n const hash = `${sessionID}-${action}-${timestamp}`.split(\"\").reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)\n return `D-${Math.abs(hash).toString(36)}`\n}\n\n/**\n * Check if the decision's severity meets the threshold.\n */\nfunction severityMeetsThreshold(\n deviations: readonly Deviation[],\n threshold: ClosedLoopConfig[\"minSeverityToLearn\"]\n): boolean {\n const minOrder = SEVERITY_ORDER[threshold] ?? 0\n return deviations.some((d) => (SEVERITY_ORDER[d.severity] ?? 0) >= minOrder)\n}\n\n/**\n * Extract concepts from deviations for the lesson.\n */\nfunction extractConcepts(deviations: readonly Deviation[]): string[] {\n const concepts = new Set<string>()\n for (const d of deviations) {\n concepts.add(d.category)\n concepts.add(d.severity)\n }\n return [...concepts]\n}\n\n/**\n * Build the lesson content string from a decision and its deviations.\n */\nfunction buildLessonContent(decision: Decision, deviations: readonly Deviation[]): string {\n const deviationSummary = deviations\n .map((d) => `[${d.severity}] ${d.category}: ${d.detail}`)\n .join(\"; \")\n return `Action \"${decision.action}\" (score ${decision.score.toFixed(2)}) after deviations: ${deviationSummary}. Reasoning: ${decision.reasoning}`\n}\n\n/**\n * Core learning function. Decides whether to save a lesson and/or decision\n * to agentmemory based on the outcome of a repair/action cycle.\n *\n * Returns LearnFromOutcomeOutput describing what was saved (or why nothing was saved).\n */\nexport async function observeAndLearn(\n input: LearnFromOutcomeInput,\n backend: AgentmemoryWriteBackend\n): Promise<LearnFromOutcomeOutput> {\n const { decision, config, sessionID, directory, filesChanged } = input\n const now = new Date().toISOString()\n\n // Config disabled → no-op\n if (!config.enabled) {\n return { lessonSaved: null, decisionSaved: null, reason: \"closed-loop learning disabled\" }\n }\n\n // No deviations → nothing to learn from\n if (decision.evidence.length === 0 && decision.action === \"continue\") {\n return { lessonSaved: null, decisionSaved: null, reason: \"no deviations to learn from\" }\n }\n\n let lessonSaved: LessonLearned | null = null\n let decisionSaved: MemoryDecision | null = null\n\n // Save decision record if enabled\n if (config.saveDecisions) {\n const decisionRecord: MemoryDecision = {\n id: generateDecisionId(sessionID, decision.action, now),\n timestampISO: now,\n action: decision.action,\n score: decision.score,\n reasoning: decision.reasoning,\n sessionID,\n directory,\n deviations: decision.evidence\n .filter((e) => e.source === \"deviation-detector\")\n .map((e) => ({\n severity: \"media\" as const,\n category: e.source,\n detail: e.value,\n })),\n }\n\n try {\n await backend.saveMemory({\n content: `Decision: ${decision.action} (score ${decision.score.toFixed(2)}). ${decision.reasoning}`,\n concepts: [\"meta-governor\", \"decision\", decision.action],\n type: \"fact\",\n files: [...filesChanged],\n })\n decisionSaved = decisionRecord\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Save lesson if deviations meet severity threshold\n const deviationsFromEvidence = decision.evidence\n .filter((e) => e.source === \"deviation-detector\")\n .map<Deviation>((e) => ({\n severity: \"media\",\n category: e.source,\n detail: e.value,\n }))\n\n if (severityMeetsThreshold(deviationsFromEvidence, config.minSeverityToLearn)) {\n const concepts = extractConcepts(deviationsFromEvidence)\n const content = buildLessonContent(decision, deviationsFromEvidence)\n\n try {\n const result = await backend.saveLesson({\n content,\n context: `session:${sessionID} dir:${directory}`,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n tags: concepts,\n })\n\n lessonSaved = {\n id: result.id,\n title: `${decision.action} after ${deviationsFromEvidence[0]?.category ?? \"deviation\"}`,\n content,\n type: \"pattern\",\n concepts,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n files: [...filesChanged],\n sessionID,\n }\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Determine reason\n const reasons: string[] = []\n if (decisionSaved) reasons.push(\"decision saved\")\n if (lessonSaved) reasons.push(\"lesson saved\")\n if (!decisionSaved && !lessonSaved) {\n if (!severityMeetsThreshold(deviationsFromEvidence, config.minSeverityToLearn)) {\n reasons.push(\"severity below threshold\")\n } else {\n reasons.push(\"no saveable content\")\n }\n }\n\n return {\n lessonSaved,\n decisionSaved,\n reason: reasons.join(\"; \") || \"no action taken\",\n }\n}\n\n/**\n * Helper: create a default ClosedLoopConfig.\n */\nexport function defaultClosedLoopConfig(): ClosedLoopConfig {\n return {\n enabled: true,\n minSeverityToLearn: \"media\",\n maxLessonsPerSession: 20,\n saveDecisions: true,\n }\n}\n\nexport { SEVERITY_ORDER }\n",
10
- "/**\n * MetaGovernor Orchestrator — PR 7 of 8.\n *\n * Unified pipeline integrating all 6 prior modules:\n * - Memory Aggregator (PR 2): parallel reads from 3 memory systems\n * - Token Predictor (PR 4): burn rate + context pressure estimation\n * - Scoring Engine (PR 5): weighted evidence scoring → action decision\n * - Decision Handler (PR 6): dispatch + history tracking + force-continue\n * - Closed-Loop Learning (PR 3): lesson persistence for future sessions\n *\n * Architecture:\n * - Pure pipeline: input → memory → predict → score → decide → learn → output\n * - Each stage is independently testable and DI-friendly\n * - Graceful degradation: if any module throws, returns partial output with skipped=true\n */\n\nimport { aggregateRead } from \"./memory-aggregator\"\nimport type { Backends } from \"./memory-aggregator\"\nimport { predict } from \"./token-predictor\"\nimport { score } from \"./scoring-engine\"\nimport { handleDecision } from \"./decision-handler\"\nimport { observeAndLearn, defaultClosedLoopConfig } from \"./closed-loop-learning\"\n\nimport type {\n AgentmemoryWriteBackend,\n DecisionContext,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n MemoryRead,\n MetaGovernorInput,\n MetaGovernorOutput,\n OrchestratorConfig,\n ScoringConfig,\n SlotMemory,\n TokenPredictorConfig,\n TokenPredictorOutput,\n} from \"./types\"\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nexport const defaultOrchestratorConfig = (): OrchestratorConfig => ({\n enabled: true,\n memory: { enabled: true, query: \"\", timeoutMs: 3000 },\n tokenPredictor: {},\n scoring: {},\n decision: {},\n closedLoop: {},\n intervention: {\n mode: \"silent\" as const,\n includeDecisionHistory: true,\n maxHistoryMessages: 5,\n minActionForMessage: \"warn\" as const,\n },\n})\n\nconst EMPTY_MEMORY_READ: MemoryRead = {\n query: \"\",\n timestampISO: new Date().toISOString(),\n agentmemory: { available: false, lessons: [] },\n magicContext: { available: false, slots: [] },\n boulderState: { available: false, tasks: [], planProgress: 0 },\n degradedSources: [\"agentmemory\", \"magicContext\", \"boulderState\"],\n}\n\nconst EMPTY_SLOT_MEMORY: SlotMemory = {\n consecutiveStops: 0,\n consecutiveContinues: 0,\n lastUpdatedISO: new Date().toISOString(),\n}\n\nconst NO_OP_DECISION: MetaGovernorOutput[\"decision\"] = {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision: {\n action: \"continue\",\n score: 0,\n reasoning: \"no decision made\",\n evidence: [],\n shouldEscalateTo: null,\n },\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: \"\",\n reasoning: \"no decision made\",\n },\n}\n\n\n/**\n * Build a DecisionContext from orchestrator input + memory read.\n * Exported for direct testing.\n */\nexport function buildDecisionContext(\n input: MetaGovernorInput,\n memoryRead: MemoryRead = EMPTY_MEMORY_READ,\n): DecisionContext {\n const iterationRatio =\n input.maxIterations > 0 ? input.iteration / input.maxIterations : 0\n\n const slotMemory: SlotMemory = {\n ...EMPTY_SLOT_MEMORY,\n consecutiveStops: input.consecutiveStops ?? 0,\n }\n\n return {\n oracleVerified: input.oracleVerified,\n noProgress: input.noProgress,\n deviations: input.deviations,\n iterationRatio,\n lessonsRelevant: memoryRead.agentmemory.lessons,\n slotMemory,\n ambient: {\n sessionID: input.sessionID,\n directory: \".\",\n mode: \"simple\",\n agentName: input.agentName ?? \"unknown\",\n iteration: input.iteration,\n maxIterations: input.maxIterations,\n },\n }\n}\n\n// ─── Orchestrator ──────────────────────────────────────────────\n\n/**\n * Run the full MetaGovernor pipeline.\n *\n * 1. Read memory via aggregator\n * 2. Predict token pressure (skipped if no usage data)\n * 3. Build DecisionContext + score\n * 4. Dispatch decision\n * 5. Learn from outcome\n * 6. Return unified output\n */\nexport async function runMetaGovernor(\n input: MetaGovernorInput,\n config: Partial<OrchestratorConfig> = {},\n): Promise<MetaGovernorOutput> {\n const mergedConfig: OrchestratorConfig = {\n ...defaultOrchestratorConfig(),\n ...config,\n }\n\n if (!mergedConfig.enabled) {\n return {\n memoryRead: EMPTY_MEMORY_READ,\n tokenPrediction: createNoopPrediction(input),\n scoringResult: {\n decision: {\n action: \"continue\",\n score: 0,\n reasoning: \"MetaGovernor disabled\",\n evidence: [],\n shouldEscalateTo: null,\n },\n contributions: [],\n rawScore: 0,\n paralysisOverride: false,\n computedAtISO: new Date().toISOString(),\n },\n decision: NO_OP_DECISION,\n lessonSaved: null,\n decisionHistory: [],\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n // Step 1: Memory read\n let memoryRead: MemoryRead = EMPTY_MEMORY_READ\n if (mergedConfig.memory.enabled) {\n try {\n const backends: Backends = {\n agentmemory: input.backends.agentmemory as Backends[\"agentmemory\"],\n magicContext: input.backends.magicContext as Backends[\"magicContext\"],\n boulderState: input.backends.boulderState,\n }\n memoryRead = await aggregateRead(\n {\n directory: \".\",\n sessionID: input.sessionID,\n query: mergedConfig.memory.query || input.toolName,\n },\n backends,\n )\n } catch {\n // Graceful degradation — memoryRead stays at EMPTY_MEMORY_READ\n }\n }\n\n // Step 2: Token prediction (sync)\n let tokenPrediction: TokenPredictorOutput\n try {\n tokenPrediction = predict({\n currentUsage: input.recentTurnTokens.reduce((a, b) => a + b, 0),\n modelLimit: input.modelLimit ?? config.modelOverride?.modelLimit ?? 200_000,\n recentTurnTokens: input.recentTurnTokens,\n timestampISO: new Date().toISOString(),\n providerID: input.providerID ?? \"\",\n modelID: input.modelID ?? \"\",\n config: mergedConfig.tokenPredictor as TokenPredictorConfig,\n })\n } catch {\n tokenPrediction = createNoopPrediction(input)\n }\n\n\n const scoringResult = score(\n buildDecisionContext(input, memoryRead),\n mergedConfig.scoring as Partial<ScoringConfig>,\n )\n\n\n // Step 4: Decision\n const decisionInput: DecisionHandlerInput = {\n sessionID: input.sessionID,\n scoringResult,\n }\n\n const decision = handleDecision(\n decisionInput,\n mergedConfig.decision as DecisionHandlerConfig,\n )\n\n // Step 5: Learn from outcome\n let lessonSaved: MetaGovernorOutput[\"lessonSaved\"] = null\n try {\n const learnConfig = mergedConfig.closedLoop\n if (learnConfig.enabled !== false) {\n lessonSaved = await observeAndLearn(\n {\n decision: decision.historyEntry.decision,\n memoryRead,\n config: { ...defaultClosedLoopConfig(), ...mergedConfig.closedLoop },\n sessionID: input.sessionID,\n directory: \".\",\n filesChanged: [],\n },\n input.writeBackend,\n )\n }\n } catch {\n // Graceful degradation — lessonSaved stays null\n }\n\n return {\n memoryRead,\n tokenPrediction,\n scoringResult,\n decision,\n lessonSaved,\n decisionHistory: [decision.historyEntry],\n skipped: false,\n }\n}\n\nfunction createNoopPrediction(\n input: MetaGovernorInput,\n): TokenPredictorOutput {\n const totalTokens = input.recentTurnTokens.reduce((a, b) => a + b, 0)\n return {\n burnRate: 0,\n budgetLeft: 200_000,\n currentUsage: totalTokens,\n modelLimit: 200_000,\n willOverflowAt: null,\n recommendation: \"no-action\" as const,\n confidence: 1,\n windowRemaining: 200_000,\n input: {\n currentUsage: totalTokens,\n modelLimit: 200_000,\n recentTurnTokens: input.recentTurnTokens,\n timestampISO: new Date().toISOString(),\n providerID: input.providerID ?? \"\",\n modelID: input.modelID ?? \"\",\n config: {\n compactBurnRateThreshold: 500,\n compactUsageThreshold: 0.85,\n switchModelUsageThreshold: 0.95,\n delegateConsecutiveHighBurn: 5,\n windowSize: 10,\n },\n },\n computedAtISO: new Date().toISOString(),\n turnsAnalyzed: input.recentTurnTokens.length,\n }\n}\n",
11
- "import type { InterventionConfig, ModelOverrideConfig, OrchestratorConfig } from \"./types\"\nimport { defaultScoringConfig } from \"./scoring-engine\"\nimport { defaultDecisionHandlerConfig } from \"./decision-handler\"\nimport { defaultClosedLoopConfig } from \"./closed-loop-learning\"\n\n/**\n * MetaGovernor config schema exposed to users.\n * This is a Zod-free config interface since Zod parsing is optional\n * in the standalone plugin — the user provides JSON, we coerce with defaults.\n */\nexport interface MetaGovernorPluginConfig {\n /** Master feature flag — must be true to run the orchestrator. */\n enabled?: boolean\n\n /** Decision handler (PR 6) */\n decision?: {\n maxHistoryPerSession?: number\n forceContinueAfterStops?: number\n }\n\n /** Memory aggregator (PR 2) */\n memory?: {\n agentmemoryTimeoutMs?: number\n magicContextTimeoutMs?: number\n boulderStateTimeoutMs?: number\n query?: string\n }\n\n /** Token predictor (PR 4) */\n tokenPredictor?: {\n compactBurnRateThreshold?: number\n compactUsageThreshold?: number\n switchModelUsageThreshold?: number\n delegateConsecutiveHighBurn?: number\n }\n\n /** Scoring engine (PR 5) */\n scoring?: {\n continueThreshold?: number\n warnThreshold?: number\n escalateThreshold?: number\n stopThreshold?: number\n }\n\n /** Closed-loop learning (PR 3) */\n closedLoop?: {\n saveDecisions?: boolean\n saveLessons?: boolean\n }\n\n /** Model override for MetaGovernor internal LLM usage. */\n modelOverride?: ModelOverrideConfig\n\n /** Intervention config for visible decision injection. */\n intervention?: {\n mode?: \"silent\" | \"message\" | \"system\"\n includeDecisionHistory?: boolean\n maxHistoryMessages?: number\n minActionForMessage?: \"warn\" | \"escalate\" | \"stop\"\n }\n}\n\n/**\n * Project the full MetaGovernorPluginConfig into OrchestratorConfig.\n * Missing sub-configs fall back to module defaults.\n */\nexport function loadOrchestratorConfig(\n pluginConfig: Partial<MetaGovernorPluginConfig> | undefined,\n): OrchestratorConfig {\n const full: MetaGovernorPluginConfig = {\n enabled: false,\n ...pluginConfig,\n }\n\n const baseScoring = defaultScoringConfig()\n const baseDecision = defaultDecisionHandlerConfig()\n const baseClosedLoop = defaultClosedLoopConfig()\n\n return {\n enabled: full.enabled === true,\n memory: {\n enabled: true,\n query: full.memory?.query ?? \"meta_governor_context\",\n timeoutMs: full.memory?.agentmemoryTimeoutMs ?? 2000,\n },\n tokenPredictor: {\n compactBurnRateThreshold:\n full.tokenPredictor?.compactBurnRateThreshold ?? 500,\n compactUsageThreshold:\n full.tokenPredictor?.compactUsageThreshold ?? 0.85,\n switchModelUsageThreshold:\n full.tokenPredictor?.switchModelUsageThreshold ?? 0.95,\n delegateConsecutiveHighBurn:\n full.tokenPredictor?.delegateConsecutiveHighBurn ?? 5,\n },\n scoring: {\n ...baseScoring,\n ...(full.scoring?.continueThreshold !== undefined\n ? { continueThreshold: full.scoring.continueThreshold }\n : {}),\n ...(full.scoring?.warnThreshold !== undefined\n ? { warnThreshold: full.scoring.warnThreshold }\n : {}),\n ...(full.scoring?.escalateThreshold !== undefined\n ? { escalateThreshold: full.scoring.escalateThreshold }\n : {}),\n ...(full.scoring?.stopThreshold !== undefined\n ? { stopThreshold: full.scoring.stopThreshold }\n : {}),\n },\n closedLoop: {\n ...baseClosedLoop,\n ...(full.closedLoop?.saveDecisions !== undefined\n ? { saveDecisions: full.closedLoop.saveDecisions }\n : {}),\n },\n decision: {\n ...baseDecision,\n ...(full.decision?.maxHistoryPerSession !== undefined\n ? { maxHistoryPerSession: full.decision.maxHistoryPerSession }\n : {}),\n ...(full.decision?.forceContinueAfterStops !== undefined\n ? { forceContinueAfterStops: full.decision.forceContinueAfterStops }\n : {}),\n },\n modelOverride: full.modelOverride\n ? {\n providerID: full.modelOverride.providerID,\n modelID: full.modelOverride.modelID,\n modelLimit: full.modelOverride.modelLimit,\n temperature: full.modelOverride.temperature ?? 0.2,\n topP: full.modelOverride.topP ?? 1,\n maxTokens: full.modelOverride.maxTokens ?? 2048,\n reasoning: full.modelOverride.reasoning ?? false,\n verbosity: full.modelOverride.verbosity ?? \"minimal\",\n }\n : undefined,\n intervention: {\n mode: full.intervention?.mode ?? \"silent\",\n includeDecisionHistory: full.intervention?.includeDecisionHistory ?? true,\n maxHistoryMessages: full.intervention?.maxHistoryMessages ?? 5,\n minActionForMessage: full.intervention?.minActionForMessage ?? \"warn\",\n } as InterventionConfig,\n }\n}\n\n/**\n * Check whether the MetaGovernor is enabled. Returns false if config is undefined.\n */\nexport function isMetaGovernorEnabled(\n config: MetaGovernorPluginConfig | undefined,\n): boolean {\n return config?.enabled === true\n}\n",
10
+ "/**\n * MetaGovernor Orchestrator — PR 7 of 8.\n *\n * Unified pipeline integrating all 6 prior modules:\n * - Memory Aggregator (PR 2): parallel reads from 3 memory systems\n * - Token Predictor (PR 4): burn rate + context pressure estimation\n * - Scoring Engine (PR 5): weighted evidence scoring → action decision\n * - Decision Handler (PR 6): dispatch + history tracking + force-continue\n * - Closed-Loop Learning (PR 3): lesson persistence for future sessions\n *\n * Architecture:\n * - Pure pipeline: input → memory → predict → score → decide → learn → output\n * - Each stage is independently testable and DI-friendly\n * - Graceful degradation: if any module throws, returns partial output with skipped=true\n */\n\nimport { aggregateRead } from \"./memory-aggregator\"\nimport type { Backends } from \"./memory-aggregator\"\nimport { predict } from \"./token-predictor\"\nimport { score } from \"./scoring-engine\"\nimport { handleDecision } from \"./decision-handler\"\nimport { observeAndLearn, defaultClosedLoopConfig } from \"./closed-loop-learning\"\n\nimport type {\n AgentmemoryWriteBackend,\n DecisionContext,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n MemoryRead,\n MetaGovernorInput,\n MetaGovernorOutput,\n OrchestratorConfig,\n ScoringConfig,\n SlotMemory,\n TokenPredictorConfig,\n TokenPredictorOutput,\n} from \"./types\"\n\n// ─── Defaults ────────────────────────────────────────────────────\n\nexport const defaultOrchestratorConfig = (): OrchestratorConfig => ({\n enabled: true,\n memory: { enabled: true, query: \"\", timeoutMs: 3000 },\n tokenPredictor: {},\n scoring: {},\n decision: {},\n closedLoop: {},\n intervention: {\n mode: \"silent\" as const,\n includeDecisionHistory: true,\n maxHistoryMessages: 5,\n minActionForMessage: \"warn\" as const,\n },\n protocolEnforcement: {\n enabled: false,\n path: undefined,\n injectIntoSystem: false,\n auditToolCalls: false,\n },\n})\n\nconst EMPTY_MEMORY_READ: MemoryRead = {\n query: \"\",\n timestampISO: new Date().toISOString(),\n agentmemory: { available: false, lessons: [] },\n magicContext: { available: false, slots: [] },\n boulderState: { available: false, tasks: [], planProgress: 0 },\n degradedSources: [\"agentmemory\", \"magicContext\", \"boulderState\"],\n}\n\nconst EMPTY_SLOT_MEMORY: SlotMemory = {\n consecutiveStops: 0,\n consecutiveContinues: 0,\n lastUpdatedISO: new Date().toISOString(),\n}\n\nconst NO_OP_DECISION: MetaGovernorOutput[\"decision\"] = {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision: {\n action: \"continue\",\n score: 0,\n reasoning: \"no decision made\",\n evidence: [],\n shouldEscalateTo: null,\n },\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: \"\",\n reasoning: \"no decision made\",\n },\n}\n\n\n/**\n * Build a DecisionContext from orchestrator input + memory read.\n * Exported for direct testing.\n */\nexport function buildDecisionContext(\n input: MetaGovernorInput,\n memoryRead: MemoryRead = EMPTY_MEMORY_READ,\n): DecisionContext {\n const iterationRatio =\n input.maxIterations > 0 ? input.iteration / input.maxIterations : 0\n\n const slotMemory: SlotMemory = {\n ...EMPTY_SLOT_MEMORY,\n consecutiveStops: input.consecutiveStops ?? 0,\n }\n\n return {\n oracleVerified: input.oracleVerified,\n noProgress: input.noProgress,\n deviations: input.deviations,\n iterationRatio,\n lessonsRelevant: memoryRead.agentmemory.lessons,\n slotMemory,\n ambient: {\n sessionID: input.sessionID,\n directory: \".\",\n mode: \"simple\",\n agentName: input.agentName ?? \"unknown\",\n iteration: input.iteration,\n maxIterations: input.maxIterations,\n },\n }\n}\n\n// ─── Orchestrator ──────────────────────────────────────────────\n\n/**\n * Run the full MetaGovernor pipeline.\n *\n * 1. Read memory via aggregator\n * 2. Predict token pressure (skipped if no usage data)\n * 3. Build DecisionContext + score\n * 4. Dispatch decision\n * 5. Learn from outcome\n * 6. Return unified output\n */\nexport async function runMetaGovernor(\n input: MetaGovernorInput,\n config: Partial<OrchestratorConfig> = {},\n): Promise<MetaGovernorOutput> {\n const mergedConfig: OrchestratorConfig = {\n ...defaultOrchestratorConfig(),\n ...config,\n }\n\n if (!mergedConfig.enabled) {\n return {\n memoryRead: EMPTY_MEMORY_READ,\n tokenPrediction: createNoopPrediction(input),\n scoringResult: {\n decision: {\n action: \"continue\",\n score: 0,\n reasoning: \"MetaGovernor disabled\",\n evidence: [],\n shouldEscalateTo: null,\n },\n contributions: [],\n rawScore: 0,\n paralysisOverride: false,\n computedAtISO: new Date().toISOString(),\n },\n decision: NO_OP_DECISION,\n lessonSaved: null,\n decisionHistory: [],\n skipped: true,\n skipReason: \"disabled\",\n }\n }\n\n // Step 1: Memory read\n let memoryRead: MemoryRead = EMPTY_MEMORY_READ\n if (mergedConfig.memory.enabled) {\n try {\n const backends: Backends = {\n agentmemory: input.backends.agentmemory as Backends[\"agentmemory\"],\n magicContext: input.backends.magicContext as Backends[\"magicContext\"],\n boulderState: input.backends.boulderState,\n }\n memoryRead = await aggregateRead(\n {\n directory: \".\",\n sessionID: input.sessionID,\n query: mergedConfig.memory.query || input.toolName,\n },\n backends,\n )\n } catch {\n // Graceful degradation — memoryRead stays at EMPTY_MEMORY_READ\n }\n }\n\n // Step 2: Token prediction (sync)\n let tokenPrediction: TokenPredictorOutput\n try {\n tokenPrediction = predict({\n currentUsage: input.recentTurnTokens.reduce((a, b) => a + b, 0),\n modelLimit: input.modelLimit ?? config.modelOverride?.modelLimit ?? 200_000,\n recentTurnTokens: input.recentTurnTokens,\n timestampISO: new Date().toISOString(),\n providerID: input.providerID ?? \"\",\n modelID: input.modelID ?? \"\",\n config: mergedConfig.tokenPredictor as TokenPredictorConfig,\n })\n } catch {\n tokenPrediction = createNoopPrediction(input)\n }\n\n\n const scoringResult = score(\n buildDecisionContext(input, memoryRead),\n mergedConfig.scoring as Partial<ScoringConfig>,\n )\n\n\n // Step 4: Decision\n const decisionInput: DecisionHandlerInput = {\n sessionID: input.sessionID,\n scoringResult,\n }\n\n const decision = handleDecision(\n decisionInput,\n mergedConfig.decision as DecisionHandlerConfig,\n )\n\n // Step 5: Learn from outcome\n let lessonSaved: MetaGovernorOutput[\"lessonSaved\"] = null\n try {\n const learnConfig = mergedConfig.closedLoop\n if (learnConfig.enabled !== false) {\n lessonSaved = await observeAndLearn(\n {\n decision: decision.historyEntry.decision,\n memoryRead,\n config: { ...defaultClosedLoopConfig(), ...mergedConfig.closedLoop },\n sessionID: input.sessionID,\n directory: \".\",\n filesChanged: [],\n },\n input.writeBackend,\n )\n }\n } catch {\n // Graceful degradation — lessonSaved stays null\n }\n\n return {\n memoryRead,\n tokenPrediction,\n scoringResult,\n decision,\n lessonSaved,\n decisionHistory: [decision.historyEntry],\n skipped: false,\n }\n}\n\nfunction createNoopPrediction(\n input: MetaGovernorInput,\n): TokenPredictorOutput {\n const totalTokens = input.recentTurnTokens.reduce((a, b) => a + b, 0)\n return {\n burnRate: 0,\n budgetLeft: 200_000,\n currentUsage: totalTokens,\n modelLimit: 200_000,\n willOverflowAt: null,\n recommendation: \"no-action\" as const,\n confidence: 1,\n windowRemaining: 200_000,\n input: {\n currentUsage: totalTokens,\n modelLimit: 200_000,\n recentTurnTokens: input.recentTurnTokens,\n timestampISO: new Date().toISOString(),\n providerID: input.providerID ?? \"\",\n modelID: input.modelID ?? \"\",\n config: {\n compactBurnRateThreshold: 500,\n compactUsageThreshold: 0.85,\n switchModelUsageThreshold: 0.95,\n delegateConsecutiveHighBurn: 5,\n windowSize: 10,\n },\n },\n computedAtISO: new Date().toISOString(),\n turnsAnalyzed: input.recentTurnTokens.length,\n }\n}\n",
11
+ "import type { InterventionConfig, ModelOverrideConfig, OrchestratorConfig, ProtocolEnforcementConfig } from \"./types\"\nimport { defaultScoringConfig } from \"./scoring-engine\"\nimport { defaultDecisionHandlerConfig } from \"./decision-handler\"\nimport { defaultClosedLoopConfig } from \"./closed-loop-learning\"\n\n/**\n * MetaGovernor config schema exposed to users.\n * This is a Zod-free config interface since Zod parsing is optional\n * in the standalone plugin — the user provides JSON, we coerce with defaults.\n */\nexport interface MetaGovernorPluginConfig {\n /** Master feature flag — must be true to run the orchestrator. */\n enabled?: boolean\n\n /** Decision handler (PR 6) */\n decision?: {\n maxHistoryPerSession?: number\n forceContinueAfterStops?: number\n }\n\n /** Memory aggregator (PR 2) */\n memory?: {\n agentmemoryTimeoutMs?: number\n magicContextTimeoutMs?: number\n boulderStateTimeoutMs?: number\n query?: string\n }\n\n /** Token predictor (PR 4) */\n tokenPredictor?: {\n compactBurnRateThreshold?: number\n compactUsageThreshold?: number\n switchModelUsageThreshold?: number\n delegateConsecutiveHighBurn?: number\n }\n\n /** Scoring engine (PR 5) */\n scoring?: {\n continueThreshold?: number\n warnThreshold?: number\n escalateThreshold?: number\n stopThreshold?: number\n }\n\n /** Closed-loop learning (PR 3) */\n closedLoop?: {\n saveDecisions?: boolean\n saveLessons?: boolean\n }\n\n /** Model override for MetaGovernor internal LLM usage. */\n modelOverride?: ModelOverrideConfig\n\n /** Intervention config for visible decision injection. */\n intervention?: {\n mode?: \"silent\" | \"message\" | \"system\"\n includeDecisionHistory?: boolean\n maxHistoryMessages?: number\n minActionForMessage?: \"warn\" | \"escalate\" | \"stop\"\n }\n\n /** Sisyphus protocol enforcement config. */\n protocolEnforcement?: {\n enabled?: boolean\n path?: string\n injectIntoSystem?: boolean\n auditToolCalls?: boolean\n }\n}\n\n/**\n * Project the full MetaGovernorPluginConfig into OrchestratorConfig.\n * Missing sub-configs fall back to module defaults.\n */\nexport function loadOrchestratorConfig(\n pluginConfig: Partial<MetaGovernorPluginConfig> | undefined,\n): OrchestratorConfig {\n const full: MetaGovernorPluginConfig = {\n enabled: false,\n ...pluginConfig,\n }\n\n const baseScoring = defaultScoringConfig()\n const baseDecision = defaultDecisionHandlerConfig()\n const baseClosedLoop = defaultClosedLoopConfig()\n\n return {\n enabled: full.enabled === true,\n memory: {\n enabled: true,\n query: full.memory?.query ?? \"meta_governor_context\",\n timeoutMs: full.memory?.agentmemoryTimeoutMs ?? 2000,\n },\n tokenPredictor: {\n compactBurnRateThreshold:\n full.tokenPredictor?.compactBurnRateThreshold ?? 500,\n compactUsageThreshold:\n full.tokenPredictor?.compactUsageThreshold ?? 0.85,\n switchModelUsageThreshold:\n full.tokenPredictor?.switchModelUsageThreshold ?? 0.95,\n delegateConsecutiveHighBurn:\n full.tokenPredictor?.delegateConsecutiveHighBurn ?? 5,\n },\n scoring: {\n ...baseScoring,\n ...(full.scoring?.continueThreshold !== undefined\n ? { continueThreshold: full.scoring.continueThreshold }\n : {}),\n ...(full.scoring?.warnThreshold !== undefined\n ? { warnThreshold: full.scoring.warnThreshold }\n : {}),\n ...(full.scoring?.escalateThreshold !== undefined\n ? { escalateThreshold: full.scoring.escalateThreshold }\n : {}),\n ...(full.scoring?.stopThreshold !== undefined\n ? { stopThreshold: full.scoring.stopThreshold }\n : {}),\n },\n closedLoop: {\n ...baseClosedLoop,\n ...(full.closedLoop?.saveDecisions !== undefined\n ? { saveDecisions: full.closedLoop.saveDecisions }\n : {}),\n },\n decision: {\n ...baseDecision,\n ...(full.decision?.maxHistoryPerSession !== undefined\n ? { maxHistoryPerSession: full.decision.maxHistoryPerSession }\n : {}),\n ...(full.decision?.forceContinueAfterStops !== undefined\n ? { forceContinueAfterStops: full.decision.forceContinueAfterStops }\n : {}),\n },\n modelOverride: full.modelOverride\n ? {\n providerID: full.modelOverride.providerID,\n modelID: full.modelOverride.modelID,\n modelLimit: full.modelOverride.modelLimit,\n temperature: full.modelOverride.temperature ?? 0.2,\n topP: full.modelOverride.topP ?? 1,\n maxTokens: full.modelOverride.maxTokens ?? 2048,\n reasoning: full.modelOverride.reasoning ?? false,\n verbosity: full.modelOverride.verbosity ?? \"minimal\",\n }\n : undefined,\n intervention: {\n mode: full.intervention?.mode ?? \"silent\",\n includeDecisionHistory: full.intervention?.includeDecisionHistory ?? true,\n maxHistoryMessages: full.intervention?.maxHistoryMessages ?? 5,\n minActionForMessage: full.intervention?.minActionForMessage ?? \"warn\",\n } as InterventionConfig,\n protocolEnforcement: {\n enabled: full.protocolEnforcement?.enabled ?? false,\n path: full.protocolEnforcement?.path,\n injectIntoSystem: full.protocolEnforcement?.injectIntoSystem ?? false,\n auditToolCalls: full.protocolEnforcement?.auditToolCalls ?? false,\n } as ProtocolEnforcementConfig,\n }\n}\n\n/**\n * Check whether the MetaGovernor is enabled. Returns false if config is undefined.\n */\nexport function isMetaGovernorEnabled(\n config: MetaGovernorPluginConfig | undefined,\n): boolean {\n return config?.enabled === true\n}\n",
12
12
  "/**\n * MetaGovernor decision store — in-memory Map for intervention feature.\n *\n * Stores decisions produced by tool.execute.after so they can be\n * consumed by experimental.chat.messages.transform and\n * experimental.chat.system.transform hooks.\n *\n * The store is keyed by sessionID. For hooks that receive a sessionID\n * (system.transform), use takeDecision(sessionID). For hooks that\n * receive no sessionID (messages.transform), use takeAnyDecision().\n */\nimport type { DecisionHandlerOutput } from \"./types\"\n\nconst store = new Map<string, DecisionHandlerOutput>()\n\n/**\n * Store a decision for a session.\n * Overwrites any previous pending decision for the same session.\n */\nexport function storeDecision(sessionID: string, decision: DecisionHandlerOutput): void {\n store.set(sessionID, decision)\n}\n\n/**\n * Take (retrieve and remove) the pending decision for a session.\n * Returns undefined if no decision is pending.\n */\nexport function takeDecision(sessionID: string): DecisionHandlerOutput | undefined {\n const decision = store.get(sessionID)\n if (decision !== undefined) {\n store.delete(sessionID)\n }\n return decision\n}\n\n/**\n * Check whether a session has a pending decision without consuming it.\n */\nexport function hasDecision(sessionID: string): boolean {\n return store.has(sessionID)\n}\n\n/**\n * Take any pending decision across all sessions.\n * Useful for hooks that do not receive a sessionID.\n * Returns the first pending decision found, or undefined if none.\n */\nexport function takeAnyDecision(): DecisionHandlerOutput | undefined {\n for (const [sessionID, decision] of store) {\n store.delete(sessionID)\n return decision\n }\n return undefined\n}\n\n/**\n * Clear all stored decisions. Useful in tests or when a session ends.\n */\nexport function clearAll(): void {\n store.clear()\n}\n",
13
- "import type { Hooks, Plugin, PluginInput, PluginOptions } from \"@opencode-ai/plugin\"\nimport type { UserMessage, TextPart } from \"@opencode-ai/sdk\"\nimport type {\n AgentmemoryWriteBackend,\n DecisionHandlerOutput,\n MemoryBackends,\n MetaGovernorInput,\n\n} from \"./types\"\nimport { runMetaGovernor } from \"./orchestrator\"\nimport { loadOrchestratorConfig, type MetaGovernorPluginConfig } from \"./config\"\nimport { storeDecision, takeAnyDecision, takeDecision } from \"./decision-store\"\n\n/**\n * Dependencies required by the MetaGovernor plugin.\n * All are optional features degrade gracefully when backends are unavailable.\n */\nexport interface MetaGovernorPluginDeps {\n /** Backends for reading memory (agentmemory, magic-context, boulder-state). Optional degrades gracefully. */\n backends?: MemoryBackends\n /** Backend for writing lessons/decisions back to agentmemory. Optional degrades gracefully. */\n writeBackend?: AgentmemoryWriteBackend\n /** Provider ID for the current session (for token predictor). */\n providerID?: () => string | undefined\n /** Model ID for the current session (for token predictor). */\n modelID?: () => string | undefined\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────\n\nconst ACTION_SEVERITY: Record<string, number> = {\n continue: 0,\n warn: 1,\n escalate: 2,\n stop: 3,\n}\n\n/**\n * Check if the given action meets or exceeds the minimum severity threshold.\n */\nfunction meetsMinAction(\n action: DecisionHandlerOutput[\"action\"],\n minAction: \"warn\" | \"escalate\" | \"stop\",\n): boolean {\n return ACTION_SEVERITY[action] >= ACTION_SEVERITY[minAction]\n}\n\nlet idCounter = 0\nfunction generateID(): string {\n idCounter++\n return `mg-${Date.now()}-${idCounter}`\n}\n\n// ─── Plugin factory ─────────────────────────────────────────────\n\n/**\n * Create a MetaGovernor plugin that registers:\n * 1. `tool.execute.after` runs the orchestrator pipeline\n * 2. `experimental.chat.messages.transform` injects decisions as synthetic user messages\n * 3. `experimental.chat.system.transform` appends decision guidance to system prompt\n */\nexport function createMetaGovernorPlugin(\n deps: MetaGovernorPluginDeps = {},\n): Plugin {\n const plugin: Plugin = async (\n _input: PluginInput,\n options?: PluginOptions,\n ): Promise<Hooks> => {\n // 1. Load config from plugin options (PluginOptions = Record<string, unknown>)\n const rawConfig = ((options?.meta_governor as MetaGovernorPluginConfig) ?? {})\n const config = loadOrchestratorConfig(rawConfig)\n\n // 2. If disabled, return empty hooks\n if (!config.enabled) {\n return {}\n }\n\n // 3. Helper to resolve model settings from override or session\n const getProviderID = (): string | undefined =>\n config.modelOverride?.providerID ?? deps.providerID?.()\n const getModelID = (): string | undefined =>\n config.modelOverride?.modelID ?? deps.modelID?.()\n const getModelLimit = (): number =>\n config.modelOverride?.modelLimit ?? 200_000\n\n const providerID = getProviderID() ?? \"unknown\"\n const modelID = getModelID() ?? \"unknown\"\n\n return {\n // ── Tool execute after ────────────────────────────────────\n \"tool.execute.after\": async (\n toolInput: { tool: string; sessionID: string; callID: string },\n toolOutput: { title: string; output: string; metadata: unknown },\n ): Promise<void> => {\n if (!config.enabled) return\n\n // Build the orchestrator input from available signals\n const orchestratorInput: MetaGovernorInput = {\n sessionID: toolInput.sessionID,\n toolName: toolInput.tool,\n toolOutput: toolOutput.output,\n iteration: 0,\n maxIterations: 10,\n oracleVerified: false,\n noProgress: false,\n filesChanged: 0,\n recentTurnTokens: [],\n deviations: [],\n backends: deps.backends ?? {\n agentmemory: {\n smartSearch: async () => ({ lessons: [], crystals: [] }),\n },\n magicContext: {\n slotList: async () => [],\n },\n boulderState: {\n boulderRead: async () => [],\n },\n },\n writeBackend: deps.writeBackend ?? {\n saveMemory: async () => ({ id: \"\" }),\n saveLesson: async () => ({ id: \"\" }),\n },\n config,\n ...(getProviderID() ? { providerID: getProviderID() } : {}),\n ...(getModelID() ? { modelID: getModelID() } : {}),\n modelLimit: getModelLimit(),\n }\n\n // Run the orchestrator\n try {\n const output = await runMetaGovernor(orchestratorInput)\n\n // 4. Store decision for intervention if applicable\n if (config.intervention.mode !== \"silent\") {\n const decision = output.decision\n if (\n decision.action !== \"continue\" &&\n meetsMinAction(decision.action, config.intervention.minActionForMessage)\n ) {\n storeDecision(toolInput.sessionID, decision)\n }\n }\n } catch (err) {\n // MetaGovernor must NEVER break a tool call.\n if (typeof console !== \"undefined\" && config.modelOverride?.verbosity !== \"silent\") {\n console.error(\"[meta-governor] orchestrator error:\", err)\n }\n }\n },\n\n // ── Messages transform (injects decision as synthetic user message) ──\n \"experimental.chat.messages.transform\": async (\n _input: {},\n output: {\n messages: Array<{ info: unknown; parts: unknown[] }>\n },\n ): Promise<void> => {\n if (!config.enabled) return\n if (config.intervention.mode !== \"message\") return\n\n const decision = takeAnyDecision()\n if (!decision) return\n if (decision.action === \"continue\") return\n if (!decision.message) return\n if (!meetsMinAction(decision.action, config.intervention.minActionForMessage)) return\n\n const messageID = generateID()\n const partID = generateID()\n const sessionID = \"intervention\"\n\n const syntheticUserMessage: UserMessage = {\n id: generateID(),\n sessionID,\n role: \"user\",\n time: { created: Date.now() },\n agent: \"meta-governor\",\n model: { providerID, modelID },\n }\n\n const syntheticPart: TextPart = {\n id: partID,\n sessionID,\n messageID,\n type: \"text\",\n text: decision.message,\n synthetic: true,\n }\n\n output.messages.unshift({\n info: syntheticUserMessage,\n parts: [syntheticPart],\n })\n },\n\n // ── System transform (appends decision guidance to system prompt) ──\n \"experimental.chat.system.transform\": async (\n transformInput: { sessionID?: string },\n output: { system: string[] },\n ): Promise<void> => {\n if (!config.enabled) return\n if (config.intervention.mode !== \"system\") return\n if (!transformInput.sessionID) return\n\n const decision = takeDecision(transformInput.sessionID)\n if (!decision) return\n if (decision.action === \"continue\") return\n if (!decision.message) return\n if (!meetsMinAction(decision.action, config.intervention.minActionForMessage)) return\n\n output.system.push(\n \"\\n[MetaGovernor Intervention]\",\n decision.message,\n \"---\",\n )\n },\n }\n }\n\n return plugin\n}\n",
13
+ "/**\n * Sisyphus Protocol Enforcer — standalone module for the MetaGovernor plugin.\n *\n * Reads the Sisyphus-mandatory protocol from disk, injects a condensed\n * version into the system prompt, and audits tool calls for protocol\n * violations using heuristic detection (no NLP).\n *\n * Public surface:\n * - loadProtocol(path?): Promise<string> — reads the protocol markdown\n * - buildSystemInjection(protocolText): string — condenses for system prompt\n * - auditToolCall(toolName, args, context): ProtocolViolation[] — heuristic audit\n */\nimport { readFile } from \"node:fs/promises\"\nimport { resolve } from \"node:path\"\nimport { homedir } from \"node:os\"\nimport type { ProtocolViolation } from \"./types\"\n\n// ─── Default protocol path ───────────────────────────────────────\n\nexport const DEFAULT_PROTOCOL_PATH = resolve(\n homedir(),\n \".config\",\n \"opencode\",\n \"sisyphus-mandatory\",\n \"sisyphus-mandatory.md\",\n)\n\n// ─── loadProtocol ────────────────────────────────────────────────\n\n/**\n * Read the Sisyphus protocol markdown from disk.\n * Falls back to the default path (~/.config/opencode/sisyphus-mandatory/sisyphus-mandatory.md)\n * when no path is provided.\n */\nexport async function loadProtocol(path?: string): Promise<string> {\n const resolvedPath = path ?? DEFAULT_PROTOCOL_PATH\n return await readFile(resolvedPath, \"utf-8\")\n}\n\n// ─── buildSystemInjection ───────────────────────────────────────\n\n/**\n * Build a condensed system-prompt injection from the full protocol text.\n * Extracts key rules from the known sections of the protocol file.\n * Returns a markdown string that can be appended to the system prompt.\n */\nexport function buildSystemInjection(_protocolText: string): string {\n const lines: string[] = [\n \"\",\n \"## Sisyphus Protocol Enforcement\",\n \"\",\n \"You MUST follow these Sisyphus protocol rules:\",\n \"\",\n \"1. **Pre-response Memory Check**: Before any action, read `<project-memory>` and `<session-history-since>` blocks in context. Cite `<memory id>` for any fact used from memory. Do not ask questions whose answers are in those blocks.\",\n \"\",\n \"2. **Codebase Graph First**: Before using grep/glob/read for architecture or symbol queries, check whether `.codegraph/` or `graphify-out/` exists. If so, use codegraph/graphify tools first. Fall back to AFT (aft_zoom, aft_outline), then grep/read only as last resort.\",\n \"\",\n \"3. **Tool Routing Table**: Match common intents to the correct tool:\",\n ' - \"we did this before\" / \"you should know\" → `agentmemory_memory_recall`',\n ' - \"the usual\" / \"as configured\" `ctx_memory(action=\"list\")`',\n \" - Starting a task that resembles a previous one → `agentmemory_memory_smart_search`\",\n ' - \"what changed\" / \"history\" → `ctx_search`',\n \" - Before asking the user a clarifying question → `agentmemory_memory_recall` first\",\n \"\",\n ]\n\n // Detect sections in the protocol text to decide which rules to emit\n if (/\\boracle\\b/i.test(_protocolText)) {\n lines.push(\n \"4. **Post-task Oracle Verification**: If files touched >= 3 OR any INVOKE trigger matches, invoke Oracle with the exact format:\",\n ' `task(subagent_type=\"oracle\", run_in_background=false, prompt=\"Verify: ...\")`',\n \" - INVOKE triggers: created 1+ new file, modified abstraction, touched security/auth paths, modified DB/persistence, modified CI/CD, added/removed dependency, modified perf-critical path, todo had 2+ completed items.\",\n \" - SKIP only when: files touched <= 2, no new file, no dependency change, single-step task, change is typo/comment/rename only.\",\n \" - Verdict: PASS → done. FAIL/CONDITIONAL → fix and re-invoke. Max 3 invocations.\",\n \" - Cost: Max 3 oracle invocations per task. Skip rate: Must NOT skip Oracle on 2+ file change.\",\n \"\",\n )\n }\n\n lines.push(\n \"5. **Parallel Query Rule**: Fire independent tool queries in the same turn. Do NOT serialize independent memory/context queries.\",\n \"\",\n \"6. **Empty-Result Escalation**: On empty `agentmemory_memory_recall`, fire `agentmemory_memory_smart_search` + `ctx_search` + `agentmemory_memory_export` before asking the user.\",\n \"\",\n \"7. **Hard Rules (No Exceptions)**:\",\n \" - Do NOT ask 'where is X?' if memory or session record already contains it.\",\n \" - Do NOT claim 'I don't know' before firing at least 2 different recall tools.\",\n \" - Do NOT re-issue clarifying questions whose answer is in `<project-memory>` or `<session-history-since>`.\",\n \" - Do NOT use grep/find when aft_outline would answer the structure question.\",\n \" - Do NOT duplicate a memory in both `agentmemory_memory_save` and `ctx_memory` — pick ONE.\",\n \"\",\n \"8. **Self-Check Before Responding**:\",\n \" - Verify you read `<project-memory>` and `<session-history-since>` blocks.\",\n \" - Verify you cited `<memory id>` for any fact used from memory.\",\n \" - Verify you did not ask a question whose answer is in those blocks.\",\n \" - For multi-file changes, verify Oracle was invoked.\",\n \" - For codebase exploration, verify codegraph/graphify was tried before grep/read.\",\n \"\",\n )\n\n return lines.join(\"\\n\")\n}\n\n// ─── auditToolCall ───────────────────────────────────────────────\n\n/**\n * Audit a single tool call for Sisyphus protocol violations.\n *\n * Uses heuristic detection (no NLP):\n * 1. If grep/glob/read is used when codegraph or graphify exists → \"media\" violation\n * 2. If the agent asks a question without prior memory tool use \"grave\" violation\n * 3. If the agent is about to ask the user something memory could answer → \"media\" violation\n * 4. If an \"undo\" or \"revert\" is used without prior checkpoint \"leve\" violation\n *\n * @param toolName The name of the tool being called\n * @param _args The tool arguments (unused in current heuristics but reserved)\n * @param context Session-level context for cross-call state awareness\n * @returns Array of protocol violations (empty if none detected)\n */\nexport function auditToolCall(\n toolName: string,\n _args: unknown,\n context: {\n /** Whether any memory tools have been used in this session */\n memoryToolsUsed: readonly string[]\n /** Whether .codegraph/ directory exists in the project */\n hasCodegraphDir: boolean\n /** Whether graphify-out/ directory exists in the project */\n hasGraphifyDir: boolean\n /** Whether Oracle has been invoked in this session */\n oracleInvoked: boolean\n /** Number of files changed so far in this session */\n filesChanged: number\n /** Whether any memory recall tool returned empty results */\n emptyRecall: boolean\n /** Whether any ctx_search or smart_search was attempted after empty recall */\n escalationAttempted: boolean\n },\n): ProtocolViolation[] {\n const violations: ProtocolViolation[] = []\n\n // Rule 0.5: Codebase Graph First\n // grep/glob/read for architecture/symbol queries should use codegraph/graphify first\n if (\n (toolName === \"grep\" || toolName === \"glob\") &&\n (context.hasCodegraphDir || context.hasGraphifyDir)\n ) {\n const graphType = context.hasCodegraphDir ? \".codegraph\" : \"graphify-out\"\n violations.push({\n rule: \"codebase-graph-first\",\n tool: toolName,\n severity: \"media\",\n detail: `Used ${toolName} when ${graphType} exists should use codegraph/graphify first for architecture and symbol queries.`,\n })\n }\n\n // Rule Step 3: Empty-result escalation\n // After empty memory_recall, the agent must try smart_search + ctx_search before asking\n if (context.emptyRecall && !context.escalationAttempted) {\n if (toolName.startsWith(\"question\") || toolName === \"ask\") {\n violations.push({\n rule: \"empty-result-escalation\",\n tool: toolName,\n severity: \"grave\",\n detail:\n \"Memory recall returned empty but agent did not fire smart_search + ctx_search + export before asking the user. Steps 1-3 of empty-result escalation protocol are mandatory.\",\n })\n }\n }\n\n // Rule Step 1: Memory tools should be used before asking questions\n const memoryToolPatterns = [\"agentmemory_memory_recall\", \"agentmemory_memory_smart_search\", \"agentmemory_memory_save\", \"ctx_memory\", \"ctx_search\", \"ctx_note\"]\n const hasUsedMemory = context.memoryToolsUsed.some((t) =>\n memoryToolPatterns.some((p) => t.startsWith(p)),\n )\n\n if (!hasUsedMemory && (toolName.startsWith(\"question\") || toolName === \"ask\")) {\n violations.push({\n rule: \"memory-first\",\n tool: toolName,\n severity: \"grave\",\n detail:\n \"Asked a question without first querying memory (agentmemory or ctx_memory). Must fire agentmemory_memory_recall or ctx_memory before asking the user.\",\n })\n }\n\n // Oracle rule: after multi-file changes (3+), check if oracle was invoked\n if (context.filesChanged >= 3 && !context.oracleInvoked) {\n // We detect this on any tool call after files have changed\n // Only flag once per session - let the caller decide\n // For now, flag as media so the orchestrator can escalate\n if (toolName !== \"task\" || !_args || typeof _args !== \"object\" || !(\"subagent_type\" in (_args as Record<string, unknown>))) {\n violations.push({\n rule: \"oracle-verification\",\n tool: toolName,\n severity: \"media\",\n detail:\n `Files changed (${context.filesChanged}) >= 3 but Oracle was not invoked. The POST-TASK ORACLE VERIFICATION protocol requires Oracle invocation on multi-file changes.`,\n })\n }\n }\n\n return violations\n}\n",
14
+ "import type { Hooks, Plugin, PluginInput, PluginOptions } from \"@opencode-ai/plugin\"\nimport type { UserMessage, TextPart } from \"@opencode-ai/sdk\"\nimport type {\n AgentmemoryWriteBackend,\n DecisionHandlerOutput,\n MemoryBackends,\n MetaGovernorInput,\n ProtocolViolation,\n} from \"./types\"\nimport { runMetaGovernor } from \"./orchestrator\"\nimport { loadOrchestratorConfig, type MetaGovernorPluginConfig } from \"./config\"\nimport { storeDecision, takeAnyDecision, takeDecision } from \"./decision-store\"\nimport {\n loadProtocol,\n buildSystemInjection,\n auditToolCall,\n DEFAULT_PROTOCOL_PATH,\n} from \"./protocol-enforcer\"\n\n/**\n * Dependencies required by the MetaGovernor plugin.\n * All are optional — features degrade gracefully when backends are unavailable.\n */\nexport interface MetaGovernorPluginDeps {\n /** Backends for reading memory (agentmemory, magic-context, boulder-state). Optional — degrades gracefully. */\n backends?: MemoryBackends\n /** Backend for writing lessons/decisions back to agentmemory. Optional — degrades gracefully. */\n writeBackend?: AgentmemoryWriteBackend\n /** Provider ID for the current session (for token predictor). */\n providerID?: () => string | undefined\n /** Model ID for the current session (for token predictor). */\n modelID?: () => string | undefined\n}\n\n// ─── Helpers ──────────────────────────────────────────────────────\n\nconst ACTION_SEVERITY: Record<string, number> = {\n continue: 0,\n warn: 1,\n escalate: 2,\n stop: 3,\n}\n\n/**\n * Check if the given action meets or exceeds the minimum severity threshold.\n */\nfunction meetsMinAction(\n action: DecisionHandlerOutput[\"action\"],\n minAction: \"warn\" | \"escalate\" | \"stop\",\n): boolean {\n return ACTION_SEVERITY[action] >= ACTION_SEVERITY[minAction]\n}\n\nlet idCounter = 0\nfunction generateID(): string {\n idCounter++\n return `mg-${Date.now()}-${idCounter}`\n}\n\n// ─── Plugin factory ─────────────────────────────────────────────\n\n/**\n * Create a MetaGovernor plugin that registers:\n * 1. `tool.execute.after` — runs the orchestrator pipeline\n * 2. `experimental.chat.messages.transform` — injects decisions as synthetic user messages\n * 3. `experimental.chat.system.transform` — appends decision guidance to system prompt\n */\nexport function createMetaGovernorPlugin(\n deps: MetaGovernorPluginDeps = {},\n): Plugin {\n const plugin: Plugin = async (\n _input: PluginInput,\n options?: PluginOptions,\n ): Promise<Hooks> => {\n // 1. Load config from plugin options (PluginOptions = Record<string, unknown>)\n const rawConfig = ((options?.meta_governor as MetaGovernorPluginConfig) ?? {})\n const config = loadOrchestratorConfig(rawConfig)\n\n // 2. If disabled, return empty hooks\n if (!config.enabled) {\n return {}\n }\n\n // 3. Helper to resolve model settings from override or session\n const getProviderID = (): string | undefined =>\n config.modelOverride?.providerID ?? deps.providerID?.()\n const getModelID = (): string | undefined =>\n config.modelOverride?.modelID ?? deps.modelID?.()\n const getModelLimit = (): number =>\n config.modelOverride?.modelLimit ?? 200_000\n\n const providerID = getProviderID() ?? \"unknown\"\n const modelID = getModelID() ?? \"unknown\"\n\n // 4. Load protocol text for enforcement (best-effort, cached once)\n let protocolText: string | undefined\n let systemInjection: string | undefined\n if (config.protocolEnforcement.enabled || config.protocolEnforcement.injectIntoSystem) {\n const protocolPath = config.protocolEnforcement.path ?? DEFAULT_PROTOCOL_PATH\n loadProtocol(protocolPath).then((text) => {\n protocolText = text\n systemInjection = buildSystemInjection(text)\n }).catch((err) => {\n if (typeof console !== \"undefined\" && config.modelOverride?.verbosity !== \"silent\") {\n console.warn(\"[meta-governor] could not load protocol:\", err instanceof Error ? err.message : err)\n }\n })\n }\n\n // 5. Per-session audit state (for tool.execute.before)\n type AuditState = {\n memoryToolsUsed: string[]\n hasCodegraphDir: boolean\n hasGraphifyDir: boolean\n oracleInvoked: boolean\n filesChanged: number\n emptyRecall: boolean\n escalationAttempted: boolean\n }\n const auditSessions = new Map<string, AuditState>()\n\n return {\n // ── Tool execute before (protocol audit) ────────────────────\n \"tool.execute.before\": async (\n toolInput: { tool: string; sessionID: string }\n ): Promise<void> => {\n if (!config.enabled) return\n if (!config.protocolEnforcement.auditToolCalls) return\n if (!toolInput.sessionID) return\n\n // Get or create audit state for this session\n let state = auditSessions.get(toolInput.sessionID)\n if (!state) {\n state = {\n memoryToolsUsed: [],\n hasCodegraphDir: false,\n hasGraphifyDir: false,\n oracleInvoked: false,\n filesChanged: 0,\n emptyRecall: false,\n escalationAttempted: false,\n }\n auditSessions.set(toolInput.sessionID, state)\n }\n\n if (systemInjection) {\n console.log(\"[meta-governor] protocol loaded, system injection ready\")\n }\n },\n \"tool.execute.after\": async (\n toolInput: { tool: string; sessionID: string; callID: string },\n toolOutput: { title: string; output: string; metadata: unknown },\n ): Promise<void> => {\n if (!config.enabled) return\n\n // Build the orchestrator input from available signals\n const orchestratorInput: MetaGovernorInput = {\n sessionID: toolInput.sessionID,\n toolName: toolInput.tool,\n toolOutput: toolOutput.output,\n iteration: 0,\n maxIterations: 10,\n oracleVerified: false,\n noProgress: false,\n filesChanged: 0,\n recentTurnTokens: [],\n deviations: [],\n backends: deps.backends ?? {\n agentmemory: {\n smartSearch: async () => ({ lessons: [], crystals: [] }),\n },\n magicContext: {\n slotList: async () => [],\n },\n boulderState: {\n boulderRead: async () => [],\n },\n },\n writeBackend: deps.writeBackend ?? {\n saveMemory: async () => ({ id: \"\" }),\n saveLesson: async () => ({ id: \"\" }),\n },\n config,\n ...(getProviderID() ? { providerID: getProviderID() } : {}),\n ...(getModelID() ? { modelID: getModelID() } : {}),\n modelLimit: getModelLimit(),\n }\n\n // Run the orchestrator\n try {\n const output = await runMetaGovernor(orchestratorInput)\n\n // 4. Store decision for intervention if applicable\n if (config.intervention.mode !== \"silent\") {\n const decision = output.decision\n if (\n decision.action !== \"continue\" &&\n meetsMinAction(decision.action, config.intervention.minActionForMessage)\n ) {\n storeDecision(toolInput.sessionID, decision)\n }\n }\n } catch (err) {\n // MetaGovernor must NEVER break a tool call.\n if (typeof console !== \"undefined\" && config.modelOverride?.verbosity !== \"silent\") {\n console.error(\"[meta-governor] orchestrator error:\", err)\n }\n }\n },\n\n // ── Messages transform (injects decision as synthetic user message) ──\n \"experimental.chat.messages.transform\": async (\n _input: {},\n output: {\n messages: Array<{ info: unknown; parts: unknown[] }>\n },\n ): Promise<void> => {\n if (!config.enabled) return\n if (config.intervention.mode !== \"message\") return\n\n const decision = takeAnyDecision()\n if (!decision) return\n if (decision.action === \"continue\") return\n if (!decision.message) return\n if (!meetsMinAction(decision.action, config.intervention.minActionForMessage)) return\n\n const messageID = generateID()\n const partID = generateID()\n const sessionID = \"intervention\"\n\n const syntheticUserMessage: UserMessage = {\n id: generateID(),\n sessionID,\n role: \"user\",\n time: { created: Date.now() },\n agent: \"meta-governor\",\n model: { providerID, modelID },\n }\n\n const syntheticPart: TextPart = {\n id: partID,\n sessionID,\n messageID,\n type: \"text\",\n text: decision.message,\n synthetic: true,\n }\n\n output.messages.unshift({\n info: syntheticUserMessage,\n parts: [syntheticPart],\n })\n },\n\n // ── System transform (injects protocol text + decision guidance) ──\n \"experimental.chat.system.transform\": async (\n transformInput: { sessionID?: string },\n output: { system: string[] },\n ): Promise<void> => {\n if (!config.enabled) return\n\n // 1. Inject Sisyphus protocol text into system prompt\n if (config.protocolEnforcement.injectIntoSystem && systemInjection) {\n output.system.push(\n \"\\n### ⚙ Sisyphus Protocol Enforcement\",\n systemInjection,\n \"---\",\n )\n }\n\n // 2. Inject decision guidance for \"system\" intervention mode\n if (config.intervention.mode === \"system\" && transformInput.sessionID) {\n const decision = takeDecision(transformInput.sessionID)\n if (decision && decision.action !== \"continue\" && decision.message) {\n if (meetsMinAction(decision.action, config.intervention.minActionForMessage)) {\n output.system.push(\n \"\\n[MetaGovernor Intervention]\",\n decision.message,\n \"---\",\n )\n }\n }\n }\n },\n }\n }\n\n return plugin\n}\n",
14
15
  "/**\n * Post-Repair Recorder for MetaGovernor — PR 9 of 9.\n *\n * After each recovery hook repairs an error, this module records the\n * outcome into agentmemory. This ensures the MetaGovernor learns from\n * recovery attempts across sessions.\n *\n * Architecture invariants:\n * - DI: AgentmemoryWriteBackend injected via function parameter.\n * - No-op when backend is null (graceful degradation).\n * - Bypasses observeAndLearn() to preserve custom severity/category.\n * - Success → leve deviation (low severity, lesson saved for pattern).\n * - Failure → grave deviation (high severity, lesson saved as bug).\n */\n\nimport type {\n AgentmemoryWriteBackend,\n ClosedLoopConfig,\n Decision,\n Deviation,\n LearnFromOutcomeOutput,\n LessonLearned,\n MemoryDecision,\n} from \"./types\"\nimport { defaultClosedLoopConfig } from \"./closed-loop-learning\"\n\n/**\n * Outcome of a recovery hook repair attempt.\n */\nexport interface RecoveryOutcome {\n /** Error code or category (e.g. \"TOOL_TIMEOUT\", \"JSON_PARSE_ERROR\"). */\n readonly errorCode: string\n /** Recovery strategy used (e.g. \"retry\", \"fallback\", \"compact\"). */\n readonly fixStrategy: string\n /** Whether the repair succeeded. */\n readonly success: boolean\n /** Session ID where the repair happened. */\n readonly sessionID: string\n /** Directory context. */\n readonly directory: string\n /** Files changed during the repair, if any. */\n readonly filesChanged?: readonly string[]\n /** Additional context about the error. */\n readonly context?: string\n}\n\n/**\n * Build a Decision from a recovery outcome.\n *\n * Success → positive score, \"continue\" action.\n * Failure → negative score, \"warn\" action with escalation to oracle.\n */\nfunction buildDecisionFromRecovery(outcome: RecoveryOutcome): Decision {\n const deviation: Deviation = {\n severity: outcome.success ? \"leve\" : \"grave\",\n category: `recovery:${outcome.fixStrategy}`,\n detail: `${outcome.errorCode}: ${outcome.context ?? \"no context\"}`,\n }\n\n return {\n action: outcome.success ? \"continue\" : \"warn\",\n score: outcome.success ? 0.5 : -0.5,\n reasoning: `Recovery ${outcome.success ? \"succeeded\" : \"failed\"}: ${outcome.fixStrategy} for ${outcome.errorCode}`,\n evidence: [\n {\n source: \"deviation-detector\",\n value: deviation.detail,\n confidence: 1,\n weight: outcome.success ? 0.3 : 0.8,\n },\n ],\n shouldEscalateTo: outcome.success ? null : \"oracle\",\n }\n}\n\n/** Severity ordering for threshold comparison. */\nconst SEVERITY_ORDER: Record<string, number> = {\n leve: 0,\n media: 1,\n grave: 2,\n}\n\n/**\n * Check if any deviation meets the severity threshold.\n */\nfunction severityMeetsThreshold(\n deviations: readonly Deviation[],\n threshold: ClosedLoopConfig[\"minSeverityToLearn\"],\n): boolean {\n const minOrder = SEVERITY_ORDER[threshold] ?? 0\n return deviations.some((d) => (SEVERITY_ORDER[d.severity] ?? 0) >= minOrder)\n}\n\n/**\n * Record a recovery outcome to agentmemory.\n *\n * This bypasses observeAndLearn() to preserve custom severity and category\n * from the recovery outcome (observeAndLearn hardcodes severity: \"media\").\n *\n * When `writeBackend` is null, this is a silent no-op.\n */\nexport async function recordRecovery(\n outcome: RecoveryOutcome,\n writeBackend: AgentmemoryWriteBackend | null,\n options?: {\n config?: ClosedLoopConfig\n },\n): Promise<LearnFromOutcomeOutput | null> {\n if (!writeBackend) {\n return null\n }\n\n const config = options?.config ?? defaultClosedLoopConfig()\n const decision = buildDecisionFromRecovery(outcome)\n\n // Config disabled → no-op\n if (!config.enabled) {\n return { lessonSaved: null, decisionSaved: null, reason: \"closed-loop learning disabled\" }\n }\n\n // Build deviations with custom severity/category (bypass observeAndLearn)\n const deviations: Deviation[] = [{\n severity: outcome.success ? \"leve\" : \"grave\",\n category: `recovery:${outcome.fixStrategy}`,\n detail: `${outcome.errorCode}: ${outcome.context ?? \"no context\"}`,\n }]\n\n let lessonSaved: LessonLearned | null = null\n let decisionSaved: MemoryDecision | null = null\n\n // Save decision record if enabled\n if (config.saveDecisions) {\n const decisionRecord: MemoryDecision = {\n id: `D-${Math.abs(`${outcome.sessionID}-${decision.action}-${Date.now()}`.split(\"\").reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)).toString(36)}`,\n timestampISO: new Date().toISOString(),\n action: decision.action,\n score: decision.score,\n reasoning: decision.reasoning,\n sessionID: outcome.sessionID,\n directory: outcome.directory,\n deviations: deviations.map((d) => ({\n severity: d.severity,\n category: d.category,\n detail: d.detail,\n })),\n }\n\n try {\n await writeBackend.saveMemory({\n content: `Decision: ${decision.action} (score ${decision.score.toFixed(2)}). ${decision.reasoning}`,\n concepts: [\"meta-governor\", \"decision\", decision.action, ...deviations.map((d) => d.category)],\n type: \"fact\",\n files: [...(outcome.filesChanged ?? [])],\n })\n decisionSaved = decisionRecord\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Save lesson if deviations meet severity threshold\n if (severityMeetsThreshold(deviations, config.minSeverityToLearn)) {\n const concepts = [...new Set(deviations.flatMap((d) => [d.category, d.severity]))]\n const deviationSummary = deviations\n .map((d) => `[${d.severity}] ${d.category}: ${d.detail}`)\n .join(\"; \")\n const content = `Action \"${decision.action}\" (score ${decision.score.toFixed(2)}) after deviations: ${deviationSummary}. Reasoning: ${decision.reasoning}`\n\n try {\n const result = await writeBackend.saveLesson({\n content,\n context: `session:${outcome.sessionID} dir:${outcome.directory}`,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n tags: concepts,\n })\n\n lessonSaved = {\n id: result.id,\n title: `${decision.action} after ${deviations[0]?.category ?? \"recovery\"}`,\n content,\n type: \"pattern\",\n concepts,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n files: [...(outcome.filesChanged ?? [])],\n sessionID: outcome.sessionID,\n }\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Determine reason\n const reasons: string[] = []\n if (decisionSaved) reasons.push(\"decision saved\")\n if (lessonSaved) {\n reasons.push(\"lesson saved\")\n } else if (!severityMeetsThreshold(deviations, config.minSeverityToLearn)) {\n reasons.push(\"severity below threshold\")\n }\n if (!decisionSaved && !lessonSaved && !reasons.length) {\n reasons.push(\"no saveable content\")\n }\n\n return {\n lessonSaved,\n decisionSaved,\n reason: reasons.join(\"; \") || \"no action taken\",\n }\n}\n\nexport { defaultClosedLoopConfig }\n",
15
- "import type { PluginModule } from \"@opencode-ai/plugin\"\nimport { createMetaGovernorPlugin } from \"./plugin\"\n\n/**\n * @sisyphuslabs/omo-meta-governor — Self-judging agent orchestration layer.\n *\n * Default export is an OpenCode PluginModule that registers a\n * `tool.execute.after` hook. The MetaGovernor reads session signals,\n * scores them against weighted evidence, and dispatches decisions.\n *\n * Install:\n * npm install @sisyphuslabs/omo-meta-governor\n *\n * Configure:\n * ```jsonc\n * {\n * \"meta_governor\": {\n * \"enabled\": true\n * }\n * }\n * ```\n */\nconst pluginModule: PluginModule = {\n id: \"omo-meta-governor\",\n server: createMetaGovernorPlugin(),\n}\n\nexport default pluginModule\n\nexport {\n createMetaGovernorPlugin,\n type MetaGovernorPluginDeps,\n} from \"./plugin\"\n\nexport {\n runMetaGovernor,\n buildDecisionContext,\n defaultOrchestratorConfig,\n} from \"./orchestrator\"\nexport {\n loadOrchestratorConfig,\n isMetaGovernorEnabled,\n type MetaGovernorPluginConfig,\n} from \"./config\"\n\n// Core module re-exports\nexport { score, defaultScoringConfig } from \"./scoring-engine\"\nexport { predict, defaultTokenPredictorConfig, calculateBurnRate } from \"./token-predictor\"\nexport { handleDecision, defaultDecisionHandlerConfig, trimHistory, countConsecutiveStops } from \"./decision-handler\"\nexport { observeAndLearn, defaultClosedLoopConfig } from \"./closed-loop-learning\"\nexport { aggregateRead } from \"./memory-aggregator\"\nexport { recordRecovery, type RecoveryOutcome } from \"./post-repair-recorder\"\nexport {\n storeDecision,\n takeDecision,\n hasDecision,\n takeAnyDecision,\n clearAll,\n} from \"./decision-store\"\n\n// Types\nexport type {\n Decision,\n DecisionContext,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n DecisionHandlerOutput,\n Deviation,\n Evidence,\n EvidenceContribution,\n InterventionConfig,\n InterventionMode,\n LearnFromOutcomeInput,\n LearnFromOutcomeOutput,\n MemoryRead,\n MemoryBackends,\n AgentmemoryWriteBackend,\n MetaGovernorInput,\n MetaGovernorOutput,\n OrchestratorConfig,\n ScoringConfig,\n ScoringResult,\n SlotMemory,\n TokenPredictorConfig,\n TokenPredictorInput,\n TokenPredictorOutput,\n ClosedLoopConfig,\n} from \"./types\"\n"
16
+ "import type { PluginModule } from \"@opencode-ai/plugin\"\nimport { createMetaGovernorPlugin } from \"./plugin\"\n\n/**\n * @sisyphuslabs/omo-meta-governor — Self-judging agent orchestration layer.\n *\n * Default export is an OpenCode PluginModule that registers a\n * `tool.execute.after` hook. The MetaGovernor reads session signals,\n * scores them against weighted evidence, and dispatches decisions.\n *\n * Install:\n * npm install @sisyphuslabs/omo-meta-governor\n *\n * Configure:\n * ```jsonc\n * {\n * \"meta_governor\": {\n * \"enabled\": true\n * }\n * }\n * ```\n */\nconst pluginModule: PluginModule = {\n id: \"omo-meta-governor\",\n server: createMetaGovernorPlugin(),\n}\n\nexport default pluginModule\n\nexport {\n createMetaGovernorPlugin,\n type MetaGovernorPluginDeps,\n} from \"./plugin\"\n\nexport {\n runMetaGovernor,\n buildDecisionContext,\n defaultOrchestratorConfig,\n} from \"./orchestrator\"\nexport {\n loadOrchestratorConfig,\n isMetaGovernorEnabled,\n type MetaGovernorPluginConfig,\n} from \"./config\"\n\n// Core module re-exports\nexport { score, defaultScoringConfig } from \"./scoring-engine\"\nexport { predict, defaultTokenPredictorConfig, calculateBurnRate } from \"./token-predictor\"\nexport { handleDecision, defaultDecisionHandlerConfig, trimHistory, countConsecutiveStops } from \"./decision-handler\"\nexport { observeAndLearn, defaultClosedLoopConfig } from \"./closed-loop-learning\"\nexport { aggregateRead } from \"./memory-aggregator\"\nexport { recordRecovery, type RecoveryOutcome } from \"./post-repair-recorder\"\nexport {\n storeDecision,\n takeDecision,\n hasDecision,\n takeAnyDecision,\n clearAll,\n} from \"./decision-store\"\n\n// Types\nexport type {\n Decision,\n DecisionContext,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n DecisionHandlerOutput,\n Deviation,\n Evidence,\n EvidenceContribution,\n InterventionConfig,\n InterventionMode,\n LearnFromOutcomeInput,\n LearnFromOutcomeOutput,\n MemoryRead,\n MemoryBackends,\n AgentmemoryWriteBackend,\n MetaGovernorInput,\n MetaGovernorOutput,\n OrchestratorConfig,\n ScoringConfig,\n ScoringResult,\n SlotMemory,\n TokenPredictorConfig,\n TokenPredictorInput,\n TokenPredictorOutput,\n ClosedLoopConfig,\n} from \"./types\"\n// Protocol enforcer\nexport {\n loadProtocol,\n buildSystemInjection,\n auditToolCall,\n DEFAULT_PROTOCOL_PATH,\n} from \"./protocol-enforcer\"\nexport type { ProtocolViolation, ProtocolEnforcementSessionState } from \"./types\"\n"
16
17
  ],
17
- "mappings": "AAwIA,IAAM,EAAW,CACf,OAAQ,CAAE,WAAY,GAAI,SAAU,GAAI,SAAU,EAAG,EACrD,SAAU,CAAE,cAAe,KAAM,eAAgB,KAAM,eAAgB,IAAK,CAC9E,EAMA,eAAsB,CAAa,CACjC,EACA,EAC8B,CAC9B,IAAM,EAAQ,YAAY,IAAI,EACxB,EAAS,IAAK,EAAS,UAA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GAAe,CAAC,EAAQ,OAC7C,EAAQ,KAAK,qBAAqB,EAGpC,MAAO,CACL,cACA,gBACA,OAAQ,EAAQ,KAAK,IAAI,GAAK,iBAChC,ECzLF,IAAM,GAA6B,CACjC,GAAI,oBACJ,OAAQ,EAAyB,CACnC,EAEe",
19
+ "debugId": "8F1D42E49502FCD664756E2164756E21",
19
20
  "names": []
20
21
  }
@@ -0,0 +1,44 @@
1
+ import type { ProtocolViolation } from "./types";
2
+ export declare const DEFAULT_PROTOCOL_PATH: string;
3
+ /**
4
+ * Read the Sisyphus protocol markdown from disk.
5
+ * Falls back to the default path (~/.config/opencode/sisyphus-mandatory/sisyphus-mandatory.md)
6
+ * when no path is provided.
7
+ */
8
+ export declare function loadProtocol(path?: string): Promise<string>;
9
+ /**
10
+ * Build a condensed system-prompt injection from the full protocol text.
11
+ * Extracts key rules from the known sections of the protocol file.
12
+ * Returns a markdown string that can be appended to the system prompt.
13
+ */
14
+ export declare function buildSystemInjection(_protocolText: string): string;
15
+ /**
16
+ * Audit a single tool call for Sisyphus protocol violations.
17
+ *
18
+ * Uses heuristic detection (no NLP):
19
+ * 1. If grep/glob/read is used when codegraph or graphify exists → "media" violation
20
+ * 2. If the agent asks a question without prior memory tool use → "grave" violation
21
+ * 3. If the agent is about to ask the user something memory could answer → "media" violation
22
+ * 4. If an "undo" or "revert" is used without prior checkpoint → "leve" violation
23
+ *
24
+ * @param toolName The name of the tool being called
25
+ * @param _args The tool arguments (unused in current heuristics but reserved)
26
+ * @param context Session-level context for cross-call state awareness
27
+ * @returns Array of protocol violations (empty if none detected)
28
+ */
29
+ export declare function auditToolCall(toolName: string, _args: unknown, context: {
30
+ /** Whether any memory tools have been used in this session */
31
+ memoryToolsUsed: readonly string[];
32
+ /** Whether .codegraph/ directory exists in the project */
33
+ hasCodegraphDir: boolean;
34
+ /** Whether graphify-out/ directory exists in the project */
35
+ hasGraphifyDir: boolean;
36
+ /** Whether Oracle has been invoked in this session */
37
+ oracleInvoked: boolean;
38
+ /** Number of files changed so far in this session */
39
+ filesChanged: number;
40
+ /** Whether any memory recall tool returned empty results */
41
+ emptyRecall: boolean;
42
+ /** Whether any ctx_search or smart_search was attempted after empty recall */
43
+ escalationAttempted: boolean;
44
+ }): ProtocolViolation[];
package/dist/types.d.ts CHANGED
@@ -90,6 +90,16 @@ export interface Deviation {
90
90
  readonly detail: string;
91
91
  readonly filePath?: string;
92
92
  }
93
+ /**
94
+ * A protocol violation detected by the Sisyphus protocol enforcer.
95
+ * Severity reuses the 3-level taxonomy from Deviation for consistency.
96
+ */
97
+ export interface ProtocolViolation {
98
+ readonly rule: string;
99
+ readonly tool: string;
100
+ readonly severity: "leve" | "media" | "grave";
101
+ readonly detail: string;
102
+ }
93
103
  /**
94
104
  * A lesson retrieved from agentmemory.lesson_recall. Confidence is the
95
105
  * stored confidence in the memory store, not the relevance to this query.
@@ -351,6 +361,21 @@ export interface InterventionConfig {
351
361
  /** Max number of recent decision history entries to include. */
352
362
  readonly maxHistoryMessages: number;
353
363
  }
364
+ /**
365
+ * Configuration for Sisyphus protocol enforcement.
366
+ * Controls whether the protocol is injected into the system prompt
367
+ * and whether tool calls are audited for protocol violations.
368
+ */
369
+ export interface ProtocolEnforcementConfig {
370
+ /** Master switch for protocol enforcement. */
371
+ readonly enabled: boolean;
372
+ /** Path to protocol markdown. Defaults to ~/.config/opencode/sisyphus-mandatory/sisyphus-mandatory.md */
373
+ readonly path?: string;
374
+ /** Whether to inject protocol rules into the system prompt. */
375
+ readonly injectIntoSystem: boolean;
376
+ /** Whether to audit tool calls for protocol violations. */
377
+ readonly auditToolCalls: boolean;
378
+ }
354
379
  export interface TokenPredictorConfig {
355
380
  /** Burn rate threshold (tokens/sec) above which to recommend compact-now. Default: 500. */
356
381
  readonly compactBurnRateThreshold: number;
@@ -476,6 +501,8 @@ export interface OrchestratorConfig {
476
501
  readonly modelOverride?: ModelOverrideConfig;
477
502
  /** Intervention config for injecting decisions into agent context. */
478
503
  readonly intervention: InterventionConfig;
504
+ /** Protocol enforcement config for Sisyphus protocol injection and auditing. */
505
+ readonly protocolEnforcement: ProtocolEnforcementConfig;
479
506
  }
480
507
  /**
481
508
  * Input to runMetaGovernor(). All signals the orchestrator needs to
@@ -516,3 +543,10 @@ export interface MetaGovernorOutput {
516
543
  readonly skipped: boolean;
517
544
  readonly skipReason?: string;
518
545
  }
546
+ export interface ProtocolEnforcementSessionState {
547
+ readonly memoryToolsUsed: readonly string[];
548
+ readonly hasCodegraphDir: boolean;
549
+ readonly hasGraphifyDir: boolean;
550
+ readonly oracleInvoked: boolean;
551
+ readonly filesChanged: number;
552
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herjarsa/omo-meta-governor",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "Self-judging agent orchestration layer for OpenCode. Reads memory, scores sessions, dispatches decisions.",
6
6
  "exports": {
@@ -33,6 +33,7 @@
33
33
  "url": "https://github.com/herjarsa/omo-meta-governor.git"
34
34
  },
35
35
  "devDependencies": {
36
- "@opencode-ai/plugin": "^1.17.4"
36
+ "@opencode-ai/plugin": "^1.17.4",
37
+ "@types/node": "^25.9.3"
37
38
  }
38
39
  }