@herjarsa/omo-meta-governor 0.7.0 → 0.9.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.
@@ -0,0 +1 @@
1
+ export declare function logToFile(level: "info" | "warn" | "error", message: string, data?: unknown): void;
@@ -43,6 +43,20 @@ export declare function installCodegraph(projectDir: string, timeoutMs?: number)
43
43
  */
44
44
  export declare function installGraphify(timeoutMs?: number): Promise<InstallCode>;
45
45
  export declare function resetInitializedProjects(): void;
46
+ /**
47
+ * Track a new session for a project. Increments reference count.
48
+ * Returns the new count.
49
+ */
50
+ export declare function trackSession(projectDir: string): number;
51
+ /**
52
+ * Untrack a session for a project. Decrements reference count.
53
+ * When count drops to 0, all watch processes for that project
54
+ * are automatically stopped.
55
+ * Returns the remaining count.
56
+ */
57
+ export declare function untrackSession(projectDir: string): number;
58
+ /** Get active session count for a project. */
59
+ export declare function getSessionCount(projectDir: string): number;
46
60
  export interface ToolAvailability {
47
61
  /** Whether codegraph is available (via npx or node_modules) */
48
62
  codegraph: boolean;
@@ -57,6 +71,8 @@ export interface ToolAvailability {
57
71
  * Stop all active watch processes for a project.
58
72
  */
59
73
  export declare function stopWatches(projectDir?: string): void;
74
+ /** Check if watches are active for a project. */
75
+ export declare function hasActiveWatcher(projectDir: string, tool?: "codegraph" | "graphify"): boolean;
60
76
  export interface GraphSyncResult {
61
77
  /** Whether synchronization was attempted */
62
78
  attempted: boolean;
package/dist/index.d.ts CHANGED
@@ -20,7 +20,8 @@ import type { PluginModule } from "@opencode-ai/plugin";
20
20
  */
21
21
  declare const pluginModule: PluginModule;
22
22
  export default pluginModule;
23
- export { createMetaGovernorPlugin, type MetaGovernorPluginDeps, } from "./plugin";
23
+ export { createMetaGovernorPlugin, type MetaGovernorPluginDeps } from "./plugin";
24
+ export { logToFile } from "./file-logger";
24
25
  export { runMetaGovernor, buildDecisionContext, defaultOrchestratorConfig, } from "./orchestrator";
25
26
  export { loadOrchestratorConfig, isMetaGovernorEnabled, type MetaGovernorPluginConfig, } from "./config";
26
27
  export { score, defaultScoringConfig } from "./scoring-engine";
package/dist/index.js CHANGED
@@ -1,9 +1,23 @@
1
- import{createRequire as vK}from"node:module";var xK=Object.defineProperty;var yK=(K)=>K;function SK(K,Q){this[K]=yK.bind(null,Q)}var DK=(K,Q)=>{for(var X in Q)xK(K,X,{get:Q[X],enumerable:!0,configurable:!0,set:SK.bind(Q,X)})};var hK=(K,Q)=>()=>(K&&(Q=K(K=0)),Q);var qK=vK(import.meta.url);var kK={};DK(kK,{stripJsoncComments:()=>r,parseJsonc:()=>c,loadMetaGovernorConfig:()=>MK,loadJsoncFile:()=>I,getUserConfigPath:()=>s,getProjectConfigPath:()=>n,deepMerge:()=>O});import{readFile as AQ,access as wQ}from"node:fs/promises";import{resolve as OK}from"node:path";import{homedir as _Q}from"node:os";function r(K){let Q=[],X=0;while(X<K.length){let J=K[X];if(J==='"'||J==="'"){let $=J;Q.push($),X++;while(X<K.length){let q=K[X];if(Q.push(q),q==="\\"){if(X++,X<K.length)Q.push(K[X])}else if(q===$){X++;break}X++}continue}if(J==="/"&&X+1<K.length&&K[X+1]==="/"){X+=2;while(X<K.length&&K[X]!==`
2
- `)X++;continue}if(J==="/"&&X+1<K.length&&K[X+1]==="*"){X+=2;while(X<K.length){if(K[X]==="*"&&X+1<K.length&&K[X+1]==="/"){X+=2;break}X++}continue}Q.push(J),X++}let Z=Q.join("");for(let J=0;J<10;J++){let $=Z;if(Z=Z.replace(/,(\s*[\]}])/g,"$1"),Z===$)break}return Z}function c(K){try{let Q=r(K);return JSON.parse(Q)}catch{return}}function s(){return OK(_Q(),".config","opencode",PK)}function n(K){let Q=K??process.cwd();return OK(Q,".opencode",PK)}async function LQ(K){try{return await wQ(K),!0}catch{return!1}}async function I(K){if(!await LQ(K))return;try{let Q=await AQ(K,"utf-8");return c(Q)}catch{return}}function O(K,Q){let X={...K};for(let Z of Object.keys(Q)){let J=Q[Z],$=X[Z];if(J===void 0)continue;if(LK(J)&&LK($))X[Z]=O($,J);else X[Z]=J}return X}function LK(K){return typeof K==="object"&&K!==null&&!Array.isArray(K)}async function MK(K={}){let Q=[],X="defaults",Z={},J=s(),$=await I(J);if($)Z=O(Z,$),Q.push(`user:${J}`),X="user";let q=n(K.projectDir),z=await I(q);if(z)Z=O(Z,z),Q.push(`project:${q}`),X="project";if(K.cliOptions&&Object.keys(K.cliOptions).length>0)Z=O(Z,K.cliOptions),Q.push("cli:inline"),X="cli";return{config:Z,sources:Q,effectiveSource:X}}var PK="omo-meta-governor.jsonc";var t=()=>{};import{execSync as A,spawn as zK}from"node:child_process";import{access as fK,stat as mK}from"node:fs/promises";import{resolve as E}from"node:path";import{constants as gK}from"node:fs";async function pK(K,Q=60000){try{return A("npm i -D @colbymchenry/codegraph",{cwd:K,stdio:"ignore",timeout:Q}),"codegraph-installed"}catch{return"codegraph-install-failed"}}async function uK(K=60000){try{return A("pip install graphifyy --break-system-packages --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{try{return A("uv tool install graphifyy --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{return"graphify-install-failed"}}}var y=new Set;function lK(){y.clear()}async function VK(K){let Q=!1,X=!1,Z=await YK(E(K,".codegraph")),J=await YK(E(K,"graphify-out"));try{A("npx --yes codegraph --version",{stdio:"ignore",timeout:1e4}),Q=!0}catch{try{A("node node_modules/.bin/codegraph --version",{cwd:K,stdio:"ignore",timeout:5000}),Q=!0}catch{}}try{A("python3 -c 'import graphify; print(graphify.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{try{A("python3 -c 'import graphifyy; print(graphifyy.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{}}return{codegraph:Q,graphify:X,codegraphIndexExists:Z,graphifyIndexExists:J}}async function dK(K){let Q=E(K,".codegraph");await WK(Q);try{A("npx --yes codegraph init",{cwd:K,stdio:"ignore",timeout:60000})}catch{}}async function aK(K){let Q=E(K,"graphify-out");await WK(Q);try{A("python3 -m graphify . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{try{A("graphifyy . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{}}}var R=new Map;function BK(K,Q){let X=`${K}:${Q}`;if(R.has(X))return;try{let Z;if(Q==="codegraph")Z=zK("npx",["codegraph","watch"],{cwd:K,stdio:"ignore",detached:!0});else Z=zK("python3",["-m","graphify",".","--no-viz","--watch"],{cwd:K,stdio:"ignore",detached:!0});Z.unref(),R.set(X,{process:Z,tool:Q}),Z.on("exit",()=>{R.delete(X)})}catch{}}function rK(K){for(let[Q,X]of R)if(!K||Q.startsWith(K)){try{X.process.kill()}catch{}R.delete(Q)}}async function S(K={enabled:!0,watch:!1,autoInstall:!0,installTimeoutMs:60000}){let Q=[],X=K.projectDir??process.cwd();if(!K.enabled)return{attempted:!1,codes:["disabled"],availability:{codegraph:!1,graphify:!1,codegraphIndexExists:!1,graphifyIndexExists:!1},alreadyInitialized:!1};if(y.has(X)){let J=await VK(X);return{attempted:!1,codes:J.codegraphIndexExists?["codegraph-already-exists"]:[],availability:J,alreadyInitialized:!0}}y.add(X);let Z;try{Z=await VK(X)}catch{return{attempted:!1,codes:["error"],availability:{codegraph:!1,graphify:!1,codegraphIndexExists:!1,graphifyIndexExists:!1},alreadyInitialized:!1}}if(K.autoInstall!==!1){if(!Z.codegraph){let J=await pK(X,K.installTimeoutMs??60000);if(Q.push(J),J==="codegraph-installed")Z.codegraph=!0}if(!Z.graphify){let J=await uK(K.installTimeoutMs??60000);if(Q.push(J),J==="graphify-installed")Z.graphify=!0}}else{if(!Z.codegraph)Q.push("codegraph-install-skipped");if(!Z.graphify)Q.push("graphify-install-skipped")}if(Z.codegraph)if(!Z.codegraphIndexExists)try{await dK(X),Q.push("codegraph-initialized")}catch{Q.push("error")}else Q.push("codegraph-already-exists");else Q.push("codegraph-unavailable");if(Z.graphify)if(!Z.graphifyIndexExists)try{await aK(X),Q.push("graphify-initialized")}catch{Q.push("error")}else Q.push("graphify-already-exists");else Q.push("graphify-unavailable");if(K.watch){if(Z.codegraph)BK(X,"codegraph"),Q.push("watch-started-codegraph");if(Z.graphify)BK(X,"graphify"),Q.push("watch-started-graphify")}return{attempted:!0,codes:Q,availability:Z,alreadyInitialized:!1}}async function YK(K){try{return(await mK(K)).isDirectory()}catch{return!1}}async function WK(K){try{await fK(K,gK.F_OK)}catch{let{mkdir:Q}=await import("node:fs/promises");await Q(K,{recursive:!0})}}var HK={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function f(K,Q){let X=performance.now(),Z={...HK.limits,...K.limits},J={...HK.timeouts,...K.timeouts},[$,q,z]=await Promise.allSettled([cK(K,Q.agentmemory,Z,J.agentmemoryMs),sK(K,Q.magicContext,Z,J.magicContextMs),nK(K,Q.boulderState,Z,J.boulderStateMs)]),V=[],B={},W=$.status==="fulfilled"?$.value:(h(V,B,"agentmemory",D($.reason)),v.agentmemory),Y=q.status==="fulfilled"?q.value:(h(V,B,"magicContext",D(q.reason)),v.magicContext),H=z.status==="fulfilled"?z.value:(h(V,B,"boulderState",D(z.reason)),v.boulderState);return{query:K.query,timestampISO:new Date().toISOString(),agentmemory:W,magicContext:Y,boulderState:H,degradedSources:V,durationMs:performance.now()-X,errorMessages:B}}async function cK(K,Q,X,Z){let J=await m(Q.smartSearch({query:K.query,limit:X.maxLessons}),Z,"agentmemory");return{available:!0,lessons:tK(J.lessons).slice(0,X.maxLessons).map((q)=>({id:q.id,title:q.title,advice:"info",confidence:q.confidence,concepts:q.concepts}))}}async function sK(K,Q,X,Z){return{available:!0,slots:(await m(Q.slotList({directory:K.directory}),Z,"magicContext")).filter(($)=>$.label.startsWith("meta_governor:")||iK($,K.query)).sort(($,q)=>$.label.localeCompare(q.label)).slice(0,X.maxSlots).map(($)=>({label:$.label,content:$.content}))}}async function nK(K,Q,X,Z){let J=await m(Q.boulderRead({directory:K.directory,sessionID:K.sessionID,query:K.query}),Z,"boulderState");return{available:!0,tasks:J.sort((q,z)=>q.priority-z.priority||z.updatedAtMs-q.updatedAtMs).slice(0,X.maxTasks).map((q)=>({id:q.id,status:q.status,title:q.title})),planProgress:oK(J)}}function tK(K){return[...K].sort((Q,X)=>X.confidence-Q.confidence)}function iK(K,Q){let X=Q.toLowerCase();return K.label.toLowerCase().includes(X)||K.content.toLowerCase().includes(X)}function oK(K){if(K.length===0)return 0;return K.filter((X)=>X.status==="done").length/K.length}function D(K){if(K instanceof Error)return K.message;if(typeof K==="string")return K;return"unknown error"}function h(K,Q,X,Z){K.push(X),Q[X]=Z}var v={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function m(K,Q,X){return new Promise((Z,J)=>{let $=setTimeout(()=>J(Error(`${X} timeout after ${Q}ms`)),Q);K.then((q)=>{clearTimeout($),Z(q)},(q)=>{clearTimeout($),J(q)})})}function eK(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function GK(K){if(K.length===0)return 0;return K.reduce((X,Z)=>X+Z,0)/K.length}function KQ(K,Q){let X=0;for(let Z=K.length-1;Z>=0;Z--)if(K[Z]>=Q)X++;else break;return X}function QQ(K,Q,X,Z){let J=Q-K;if(J<=0)return Z;if(X<=0)return null;let $=Math.floor(J/X);if($<=0)return Z;let q=$*2;return new Date(new Date(Z).getTime()+q*1000).toISOString()}function g(K){let{currentUsage:Q,modelLimit:X,recentTurnTokens:Z,timestampISO:J,config:$}=K,q=Z.slice(-$.windowSize),z=GK(q),V=X-Q,B=X>0?Q/X:1,W=Math.min(0.95,0.3+q.length/$.windowSize*0.65),Y="no-action",H="within normal parameters";if(B>=$.switchModelUsageThreshold)Y="switch-model",H=`context usage ${(B*100).toFixed(1)}% exceeds switch threshold ${($.switchModelUsageThreshold*100).toFixed(1)}%`;if(B>=$.compactUsageThreshold||z>=$.compactBurnRateThreshold){if(Y==="no-action")Y="compact-now",H=B>=$.compactUsageThreshold?`context usage ${(B*100).toFixed(1)}% exceeds compact threshold ${($.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${z.toFixed(0)} tokens/turn exceeds threshold ${$.compactBurnRateThreshold}`}let U=KQ(q,$.compactBurnRateThreshold);if(U>=$.delegateConsecutiveHighBurn&&Y==="no-action")Y="delegate-to-subagent",H=`${U} consecutive high-burn turns (threshold: ${$.delegateConsecutiveHighBurn})`;let P=QQ(Q,X,z,J);return{currentUsage:Q,burnRate:z,budgetLeft:V,willOverflowAt:P,recommendation:Y,confidence:W,modelLimit:X,windowRemaining:Math.max(0,Math.floor(V/Math.max(z,1))),input:{...K},computedAtISO:J,turnsAnalyzed:q.length}}var w={"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},C=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function XQ(K){let Q=[];Q.push({source:"oracle-verified",rawScore:K.oracleVerified?0.6:0,weight:w["oracle-verified"],weightedScore:K.oracleVerified?0.6*w["oracle-verified"]:0,description:K.oracleVerified?"Oracle verification passed":"No Oracle verification"}),Q.push({source:"no-progress-detector",rawScore:K.noProgress?-0.8:0,weight:w["no-progress-detector"],weightedScore:K.noProgress?-0.8*w["no-progress-detector"]:0,description:K.noProgress?"No progress detected in last turn":"Progress detected"});let X=ZQ(K.deviations);Q.push({source:"deviation-detector",rawScore:X,weight:w["deviation-detector"],weightedScore:X*w["deviation-detector"],description:K.deviations.length>0?`${K.deviations.length} deviation(s) detected (worst: ${K.deviations[0].severity})`:"No deviations detected"});let Z=$Q(K.iterationRatio);Q.push({source:"iteration-budget",rawScore:Z,weight:w["iteration-budget"],weightedScore:Z*w["iteration-budget"],description:`Iteration ratio: ${K.iterationRatio.toFixed(2)} (${K.ambient.iteration}/${K.ambient.maxIterations})`});let J=JQ(K.lessonsRelevant);return Q.push({source:"lesson-recall",rawScore:J,weight:w["lesson-recall"],weightedScore:J*w["lesson-recall"],description:K.lessonsRelevant.length>0?`${K.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${qQ(K.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),Q}function ZQ(K){if(K.length===0)return 0;let Q={grave:-0.9,media:-0.5,leve:-0.2},X=0;for(let J of K){let $=Q[J.severity]??-0.3;if($<X)X=$}let Z=Math.min(K.length*0.05,0.2);return Math.max(X-Z,-1)}function $Q(K){if(K<=0.5)return-K*0.6;return-0.3-(K-0.5)*1}function JQ(K){if(K.length===0)return 0;let Q=0;for(let X of K)Q+=({continue:0.3,info:0,warn:-0.3,stop:-0.7}[X.advice]??0)*X.confidence;return Math.max(Math.min(Q/K.length,1),-1)}function qQ(K){if(K.length===0)return 0;return K.reduce((Q,X)=>Q+X.confidence,0)/K.length}function zQ(K,Q){if(K>=Q.continueThreshold)return"continue";if(K<=-Q.stopThreshold)return"stop";if(K<=-Q.escalateThreshold)return"escalate";if(K<=-Q.warnThreshold)return"warn";return"continue"}function VQ(K,Q){if(!K.oracleVerified)return"oracle";if(K.deviations.some((X)=>X.severity==="grave"))return"user";return Q.defaultEscalationTarget}function UK(K,Q,X,Z){if(Z)return`Paralysis detected: forced continue despite score ${K.toFixed(3)} (too many consecutive stops)`;let J=[...X].sort((B,W)=>B.weightedScore-W.weightedScore),$=J[0],q=J[J.length-1],z=[];if($.weightedScore<0)z.push(`primary concern: ${$.description}`);if(q.weightedScore>0)z.push(`positive signal: ${q.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[Q]} (score: ${K.toFixed(3)}): ${z.join("; ")||"balanced signals"}`}function p(K,Q){let X={...C(),...Q},Z=XQ(K),J=Z.reduce((Y,H)=>Y+H.weightedScore,0),$=Math.max(Math.min(J,1),-1),q=K.slotMemory.consecutiveStops>=X.paralysisThreshold&&$<=-X.warnThreshold,z=q?"continue":zQ($,X),V=[];if(z!=="continue"||Math.abs($)<X.continueThreshold){for(let Y of Z)if(Math.abs(Y.weightedScore)>0.01)V.push({source:Y.source,value:Y.description,confidence:Math.abs(Y.rawScore),weight:Y.weight});if(V.length===0&&z!=="continue")V.push({source:"ambient",value:UK($,z,Z,q),confidence:0.5,weight:0.1})}let B=z==="escalate"?VQ(K,X):null;return{decision:{action:z,score:$,reasoning:UK($,z,Z,q),evidence:V,shouldEscalateTo:B},contributions:Z,rawScore:$,paralysisOverride:q,computedAtISO:new Date().toISOString()}}var j=()=>({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 T(K,Q){let X=K;for(let[Z,J]of Object.entries(Q))X=X.replaceAll(`{${Z}}`,J);return X}function BQ(K){return K.length}function u(K,Q){let X={...j(),...Q};if(!X.enabled)return{action:"continue",message:null,historyEntry:{decision:K.scoringResult.decision,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:"Decision handler disabled — pass-through continue"}};let Z=K.scoringResult.decision,J=Z.score,$=Z.reasoning,q=BQ(Z.evidence),z=Z.shouldEscalateTo??X.defaultEscalationTarget??"oracle";if(K.scoringResult.paralysisOverride)return{action:"continue",message:T(X.warnMessageTemplate,{score:J.toFixed(3),reasoning:`Paralysis detected — forced continue. ${$}`,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Paralysis override: ${$}`}};switch(Z.action){case"continue":return{action:"continue",message:null,historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:$}};case"warn":return{action:"warn",message:T(X.warnMessageTemplate,{score:J.toFixed(3),reasoning:$,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:$}};case"escalate":return{action:"escalate",message:T(X.escalateMessageTemplate,{target:z,reasoning:$}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Escalate to ${z}: ${$}`}};case"stop":return{action:"stop",message:T(X.stopMessageTemplate,{reasoning:$,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:$}}}}function YQ(K,Q){if(K.length<=Q)return{trimmed:[...K],dropped:0};let X=K.length-Q;return{trimmed:K.slice(-Q),dropped:X}}function WQ(K){let Q=0;for(let X=K.length-1;X>=0;X--)if(K[X].action==="stop")Q++;else break;return Q}var FK={leve:0,media:1,grave:2};function HQ(K,Q,X){let Z=`${K}-${Q}-${X}`.split("").reduce((J,$)=>(J<<5)-J+$.charCodeAt(0)|0,0);return`D-${Math.abs(Z).toString(36)}`}function NK(K,Q){let X=FK[Q]??0;return K.some((Z)=>(FK[Z.severity]??0)>=X)}function GQ(K){let Q=new Set;for(let X of K)Q.add(X.category),Q.add(X.severity);return[...Q]}function UQ(K,Q){let X=Q.map((Z)=>`[${Z.severity}] ${Z.category}: ${Z.detail}`).join("; ");return`Action "${K.action}" (score ${K.score.toFixed(2)}) after deviations: ${X}. Reasoning: ${K.reasoning}`}async function l(K,Q){let{decision:X,config:Z,sessionID:J,directory:$,filesChanged:q}=K,z=new Date().toISOString();if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};if(X.evidence.length===0&&X.action==="continue")return{lessonSaved:null,decisionSaved:null,reason:"no deviations to learn from"};let V=null,B=null;if(Z.saveDecisions){let H={id:HQ(J,X.action,z),timestampISO:z,action:X.action,score:X.score,reasoning:X.reasoning,sessionID:J,directory:$,deviations:X.evidence.filter((U)=>U.source==="deviation-detector").map((U)=>({severity:"media",category:U.source,detail:U.value}))};try{await Q.saveMemory({content:`Decision: ${X.action} (score ${X.score.toFixed(2)}). ${X.reasoning}`,concepts:["meta-governor","decision",X.action],type:"fact",files:[...q]}),B=H}catch{}}let W=X.evidence.filter((H)=>H.source==="deviation-detector").map((H)=>({severity:"media",category:H.source,detail:H.value}));if(NK(W,Z.minSeverityToLearn)){let H=GQ(W),U=UQ(X,W);try{V={id:(await Q.saveLesson({content:U,context:`session:${J} dir:${$}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),tags:H})).id,title:`${X.action} after ${W[0]?.category??"deviation"}`,content:U,type:"pattern",concepts:H,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),files:[...q],sessionID:J}}catch{}}let Y=[];if(B)Y.push("decision saved");if(V)Y.push("lesson saved");if(!B&&!V)if(!NK(W,Z.minSeverityToLearn))Y.push("severity below threshold");else Y.push("no saveable content");return{lessonSaved:V,decisionSaved:B,reason:Y.join("; ")||"no action taken"}}function _(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var wK=()=>({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}}),d={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},FQ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},NQ={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 _K(K,Q=d){let X=K.maxIterations>0?K.iteration/K.maxIterations:0,Z={...FQ,consecutiveStops:K.consecutiveStops??0};return{oracleVerified:K.oracleVerified,noProgress:K.noProgress,deviations:K.deviations,iterationRatio:X,lessonsRelevant:Q.agentmemory.lessons,slotMemory:Z,ambient:{sessionID:K.sessionID,directory:".",mode:"simple",agentName:K.agentName??"unknown",iteration:K.iteration,maxIterations:K.maxIterations}}}async function a(K,Q={}){let X={...wK(),...Q};if(!X.enabled)return{memoryRead:d,tokenPrediction:AK(K),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:NQ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=d;if(X.memory.enabled)try{let B={agentmemory:K.backends.agentmemory,magicContext:K.backends.magicContext,boulderState:K.backends.boulderState};Z=await f({directory:".",sessionID:K.sessionID,query:X.memory.query||K.toolName},B)}catch{}let J;try{J=g({currentUsage:K.recentTurnTokens.reduce((B,W)=>B+W,0),modelLimit:K.modelLimit??Q.modelOverride?.modelLimit??200000,recentTurnTokens:K.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:K.providerID??"",modelID:K.modelID??"",config:X.tokenPredictor})}catch{J=AK(K)}let $=p(_K(K,Z),X.scoring),q={sessionID:K.sessionID,scoringResult:$},z=u(q,X.decision),V=null;try{if(X.closedLoop.enabled!==!1)V=await l({decision:z.historyEntry.decision,memoryRead:Z,config:{..._(),...X.closedLoop},sessionID:K.sessionID,directory:".",filesChanged:[]},K.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:J,scoringResult:$,decision:z,lessonSaved:V,decisionHistory:[z.historyEntry],skipped:!1}}function AK(K){let Q=K.recentTurnTokens.reduce((X,Z)=>X+Z,0);return{burnRate:0,budgetLeft:200000,currentUsage:Q,modelLimit:200000,willOverflowAt:null,recommendation:"no-action",confidence:1,windowRemaining:200000,input:{currentUsage:Q,modelLimit:200000,recentTurnTokens:K.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:K.providerID??"",modelID:K.modelID??"",config:{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}},computedAtISO:new Date().toISOString(),turnsAnalyzed:K.recentTurnTokens.length}}function b(K){let Q={enabled:!1,...K},X=C(),Z=j(),J=_();return{enabled:Q.enabled===!0,memory:{enabled:!0,query:Q.memory?.query??"meta_governor_context",timeoutMs:Q.memory?.agentmemoryTimeoutMs??2000},tokenPredictor:{compactBurnRateThreshold:Q.tokenPredictor?.compactBurnRateThreshold??500,compactUsageThreshold:Q.tokenPredictor?.compactUsageThreshold??0.85,switchModelUsageThreshold:Q.tokenPredictor?.switchModelUsageThreshold??0.95,delegateConsecutiveHighBurn:Q.tokenPredictor?.delegateConsecutiveHighBurn??5},scoring:{...X,...Q.scoring?.continueThreshold!==void 0?{continueThreshold:Q.scoring.continueThreshold}:{},...Q.scoring?.warnThreshold!==void 0?{warnThreshold:Q.scoring.warnThreshold}:{},...Q.scoring?.escalateThreshold!==void 0?{escalateThreshold:Q.scoring.escalateThreshold}:{},...Q.scoring?.stopThreshold!==void 0?{stopThreshold:Q.scoring.stopThreshold}:{}},closedLoop:{...J,...Q.closedLoop?.saveDecisions!==void 0?{saveDecisions:Q.closedLoop.saveDecisions}:{}},decision:{...Z,...Q.decision?.maxHistoryPerSession!==void 0?{maxHistoryPerSession:Q.decision.maxHistoryPerSession}:{},...Q.decision?.forceContinueAfterStops!==void 0?{forceContinueAfterStops:Q.decision.forceContinueAfterStops}:{}},modelOverride:Q.modelOverride?{providerID:Q.modelOverride.providerID,modelID:Q.modelOverride.modelID,modelLimit:Q.modelOverride.modelLimit,temperature:Q.modelOverride.temperature??0.2,topP:Q.modelOverride.topP??1,maxTokens:Q.modelOverride.maxTokens??2048,reasoning:Q.modelOverride.reasoning??!1,verbosity:Q.modelOverride.verbosity??"minimal"}:void 0,intervention:{mode:Q.intervention?.mode??"silent",includeDecisionHistory:Q.intervention?.includeDecisionHistory??!0,maxHistoryMessages:Q.intervention?.maxHistoryMessages??5,minActionForMessage:Q.intervention?.minActionForMessage??"warn"},protocolEnforcement:{enabled:Q.protocolEnforcement?.enabled??!1,path:Q.protocolEnforcement?.path,injectIntoSystem:Q.protocolEnforcement?.injectIntoSystem??!1,auditToolCalls:Q.protocolEnforcement?.auditToolCalls??!1}}}function OQ(K){return K?.enabled===!0}async function PQ(K={}){let{loadMetaGovernorConfig:Q}=await Promise.resolve().then(() => (t(),kK)),X=await Q(K);return b(X.config)}var L=new Map;function i(K,Q){L.set(K,Q)}function o(K){let Q=L.get(K);if(Q!==void 0)L.delete(K);return Q}function MQ(K){return L.has(K)}function e(){for(let[K,Q]of L)return L.delete(K),Q;return}function kQ(){L.clear()}import{readFile as RQ}from"node:fs/promises";import{resolve as EQ}from"node:path";import{homedir as CQ}from"node:os";var x=EQ(CQ(),".config","opencode","sisyphus-mandatory","sisyphus-mandatory.md");async function KK(K){return await RQ(K??x,"utf-8")}function QK(K){let Q=["","## 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(K))Q.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 Q.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.",""),Q.join(`
3
- `)}function TQ(K,Q,X){let Z=[];if((K==="grep"||K==="glob")&&(X.hasCodegraphDir||X.hasGraphifyDir)){let q=X.hasCodegraphDir?".codegraph":"graphify-out";Z.push({rule:"codebase-graph-first",tool:K,severity:"media",detail:`Used ${K} when ${q} exists — should use codegraph/graphify first for architecture and symbol queries.`})}if(X.emptyRecall&&!X.escalationAttempted){if(K.startsWith("question")||K==="ask")Z.push({rule:"empty-result-escalation",tool:K,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 J=["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"];if(!X.memoryToolsUsed.some((q)=>J.some((z)=>q.startsWith(z)))&&(K.startsWith("question")||K==="ask"))Z.push({rule:"memory-first",tool:K,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(X.filesChanged>=3&&!X.oracleInvoked){if(K!=="task"||!Q||typeof Q!=="object"||!("subagent_type"in Q))Z.push({rule:"oracle-verification",tool:K,severity:"media",detail:`Files changed (${X.filesChanged}) >= 3 but Oracle was not invoked. The POST-TASK ORACLE VERIFICATION protocol requires Oracle invocation on multi-file changes.`})}return Z}var RK={continue:0,warn:1,escalate:2,stop:3};function XK(K,Q){return RK[K]>=RK[Q]}var EK=0;function ZK(){return EK++,`mg-${Date.now()}-${EK}`}function $K(K={}){return async(X,Z)=>{let J=Z?.meta_governor??{},$=b(J);if(!$.enabled)return{};let q={enabled:J?.graphSync?.enabled??!0,watch:J?.graphSync?.watch??!1,autoInstall:J?.graphSync?.autoInstall??!0,installTimeoutMs:J?.graphSync?.installTimeoutMs??60000};S(q).catch(()=>{});let z=()=>$.modelOverride?.providerID??K.providerID?.(),V=()=>$.modelOverride?.modelID??K.modelID?.(),B=()=>$.modelOverride?.modelLimit??200000,W=z()??"unknown",Y=V()??"unknown",H,U;if($.protocolEnforcement.enabled||$.protocolEnforcement.injectIntoSystem){let F=$.protocolEnforcement.path??x;KK(F).then((G)=>{H=G,U=QK(G)}).catch((G)=>{if(typeof console<"u"&&$.modelOverride?.verbosity!=="silent")console.warn("[meta-governor] could not load protocol:",G instanceof Error?G.message:G)})}let P=new Map;return{"tool.execute.before":async(F)=>{if(!$.enabled)return;if(!$.protocolEnforcement.auditToolCalls)return;if(!F.sessionID)return;let G=P.get(F.sessionID);if(!G)G={memoryToolsUsed:[],hasCodegraphDir:!1,hasGraphifyDir:!1,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1},P.set(F.sessionID,G);if(U)console.log("[meta-governor] protocol loaded, system injection ready")},"tool.execute.after":async(F,G)=>{if(!$.enabled)return;let N={sessionID:F.sessionID,toolName:F.tool,toolOutput:G.output,iteration:0,maxIterations:10,oracleVerified:!1,noProgress:!1,filesChanged:0,recentTurnTokens:[],deviations:[],backends:K.backends??{agentmemory:{smartSearch:async()=>({lessons:[],crystals:[]})},magicContext:{slotList:async()=>[]},boulderState:{boulderRead:async()=>[]}},writeBackend:K.writeBackend??{saveMemory:async()=>({id:""}),saveLesson:async()=>({id:""})},config:$,...z()?{providerID:z()}:{},...V()?{modelID:V()}:{},modelLimit:B()};try{let M=await a(N);if($.intervention.mode!=="silent"){let k=M.decision;if(k.action!=="continue"&&XK(k.action,$.intervention.minActionForMessage))i(F.sessionID,k)}}catch(M){if(typeof console<"u"&&$.modelOverride?.verbosity!=="silent")console.error("[meta-governor] orchestrator error:",M)}},"experimental.chat.messages.transform":async(F,G)=>{if(!$.enabled)return;if($.intervention.mode!=="message")return;let N=e();if(!N)return;if(N.action==="continue")return;if(!N.message)return;if(!XK(N.action,$.intervention.minActionForMessage))return;let M=ZK(),k=ZK(),JK="intervention",IK={id:ZK(),sessionID:JK,role:"user",time:{created:Date.now()},agent:"meta-governor",model:{providerID:W,modelID:Y}},bK={id:k,sessionID:JK,messageID:M,type:"text",text:N.message,synthetic:!0};G.messages.unshift({info:IK,parts:[bK]})},"experimental.chat.system.transform":async(F,G)=>{if(!$.enabled)return;if($.protocolEnforcement.injectIntoSystem&&U)G.system.push(`
4
- ### Sisyphus Protocol Enforcement`,U,"---");if($.intervention.mode==="system"&&F.sessionID){let N=o(F.sessionID);if(N&&N.action!=="continue"&&N.message){if(XK(N.action,$.intervention.minActionForMessage))G.system.push(`
5
- [MetaGovernor Intervention]`,N.message,"---")}}}}}}function jQ(K){let Q={severity:K.success?"leve":"grave",category:`recovery:${K.fixStrategy}`,detail:`${K.errorCode}: ${K.context??"no context"}`};return{action:K.success?"continue":"warn",score:K.success?0.5:-0.5,reasoning:`Recovery ${K.success?"succeeded":"failed"}: ${K.fixStrategy} for ${K.errorCode}`,evidence:[{source:"deviation-detector",value:Q.detail,confidence:1,weight:K.success?0.3:0.8}],shouldEscalateTo:K.success?null:"oracle"}}var CK={leve:0,media:1,grave:2};function TK(K,Q){let X=CK[Q]??0;return K.some((Z)=>(CK[Z.severity]??0)>=X)}async function IQ(K,Q,X){if(!Q)return null;let Z=X?.config??_(),J=jQ(K);if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};let $=[{severity:K.success?"leve":"grave",category:`recovery:${K.fixStrategy}`,detail:`${K.errorCode}: ${K.context??"no context"}`}],q=null,z=null;if(Z.saveDecisions){let B={id:`D-${Math.abs(`${K.sessionID}-${J.action}-${Date.now()}`.split("").reduce((W,Y)=>(W<<5)-W+Y.charCodeAt(0)|0,0)).toString(36)}`,timestampISO:new Date().toISOString(),action:J.action,score:J.score,reasoning:J.reasoning,sessionID:K.sessionID,directory:K.directory,deviations:$.map((W)=>({severity:W.severity,category:W.category,detail:W.detail}))};try{await Q.saveMemory({content:`Decision: ${J.action} (score ${J.score.toFixed(2)}). ${J.reasoning}`,concepts:["meta-governor","decision",J.action,...$.map((W)=>W.category)],type:"fact",files:[...K.filesChanged??[]]}),z=B}catch{}}if(TK($,Z.minSeverityToLearn)){let B=[...new Set($.flatMap((H)=>[H.category,H.severity]))],W=$.map((H)=>`[${H.severity}] ${H.category}: ${H.detail}`).join("; "),Y=`Action "${J.action}" (score ${J.score.toFixed(2)}) after deviations: ${W}. Reasoning: ${J.reasoning}`;try{q={id:(await Q.saveLesson({content:Y,context:`session:${K.sessionID} dir:${K.directory}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(J.score))),tags:B})).id,title:`${J.action} after ${$[0]?.category??"recovery"}`,content:Y,type:"pattern",concepts:B,confidence:Math.max(0.3,Math.min(0.8,Math.abs(J.score))),files:[...K.filesChanged??[]],sessionID:K.sessionID}}catch{}}let V=[];if(z)V.push("decision saved");if(q)V.push("lesson saved");else if(!TK($,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"}}t();function jK(){return{$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/herjarsa/omo-meta-governor/main/assets/omo-meta-governor.schema.json",title:"omo-meta-governor",description:"Configuration schema for @herjarsa/omo-meta-governor — Self-judging agent orchestration layer for OpenCode.",type:"object",additionalProperties:!1,properties:{$schema:{type:"string",description:"JSON Schema reference for IDE autocompletion."},enabled:{type:"boolean",description:"Master feature flag — must be true to run the orchestrator.",default:!1},decision:{type:"object",description:"Decision handler configuration.",additionalProperties:!1,properties:{maxHistoryPerSession:{type:"integer",description:"Maximum history entries per session before oldest are trimmed.",default:50,minimum:1},forceContinueAfterStops:{type:"integer",description:"How many consecutive stops before forcing continue.",default:3,minimum:1}}},memory:{type:"object",description:"Memory aggregator configuration.",additionalProperties:!1,properties:{agentmemoryTimeoutMs:{type:"integer",description:"Timeout for agentmemory queries in milliseconds.",default:2000,minimum:100},magicContextTimeoutMs:{type:"integer",description:"Timeout for magic-context queries in milliseconds.",default:1000,minimum:100},boulderStateTimeoutMs:{type:"integer",description:"Timeout for boulder-state queries in milliseconds.",default:1000,minimum:100},query:{type:"string",description:"Natural-language query for memory recall.",default:"meta_governor_context"}}},tokenPredictor:{type:"object",description:"Token predictor configuration.",additionalProperties:!1,properties:{compactBurnRateThreshold:{type:"integer",description:"Burn rate threshold (tokens/turn) above which to recommend compact-now.",default:500,minimum:0},compactUsageThreshold:{type:"number",description:"Context usage ratio (0..1) above which to recommend compact-now.",default:0.85,minimum:0,maximum:1},switchModelUsageThreshold:{type:"number",description:"Context usage ratio above which to recommend switch-model.",default:0.95,minimum:0,maximum:1},delegateConsecutiveHighBurn:{type:"integer",description:"Max consecutive high-burn turns before recommending delegate.",default:5,minimum:1}}},scoring:{type:"object",description:"Scoring engine configuration.",additionalProperties:!1,properties:{continueThreshold:{type:"number",description:"Score >= this -> continue silently.",default:0.3,minimum:0,maximum:1},warnThreshold:{type:"number",description:"Score <= -warnThreshold -> warn.",default:0.3,minimum:0,maximum:1},escalateThreshold:{type:"number",description:"Score <= -escalateThreshold -> escalate.",default:0.6,minimum:0,maximum:1},stopThreshold:{type:"number",description:"Score <= -stopThreshold -> stop.",default:0.8,minimum:0,maximum:1}}},closedLoop:{type:"object",description:"Closed-loop learning configuration.",additionalProperties:!1,properties:{saveDecisions:{type:"boolean",description:"Whether to save decision records.",default:!0},saveLessons:{type:"boolean",description:"Whether to save lessons.",default:!0}}},modelOverride:{type:"object",description:"Model override for MetaGovernor internal LLM usage.",additionalProperties:!1,properties:{providerID:{type:"string",description:"Provider ID (e.g. 'openai', 'anthropic')."},modelID:{type:"string",description:"Model ID (e.g. 'gpt-4o-mini', 'claude-sonnet-4-20250514')."},modelLimit:{type:"integer",description:"Context window size for token predictor.",minimum:1000},temperature:{type:"number",description:"Sampling temperature. Default: 0.2.",default:0.2,minimum:0,maximum:2},topP:{type:"number",description:"Top-p nucleus sampling. Default: 1.",default:1,minimum:0,maximum:1},maxTokens:{type:"integer",description:"Max output tokens for internal reasoning.",default:2048,minimum:1},reasoning:{type:"boolean",description:"Enable extended reasoning / thinking mode.",default:!1},verbosity:{type:"string",description:"Verbosity level for internal logging.",enum:["silent","minimal","verbose"],default:"minimal"}}},intervention:{type:"object",description:"Intervention config for visible decision injection.",additionalProperties:!1,properties:{mode:{type:"string",description:"How to inject: 'silent', 'message', or 'system'.",enum:["silent","message","system"],default:"silent"},includeDecisionHistory:{type:"boolean",description:"Whether to include recent decision history.",default:!0},maxHistoryMessages:{type:"integer",description:"Max history entries when includeDecisionHistory is true.",default:5,minimum:1},minActionForMessage:{type:"string",description:"Minimum action: 'warn' (all non-continue), 'escalate', or 'stop'.",enum:["warn","escalate","stop"],default:"warn"}}},protocolEnforcement:{type:"object",description:"Sisyphus protocol enforcement config.",additionalProperties:!1,properties:{enabled:{type:"boolean",description:"Master switch for protocol enforcement.",default:!1},path:{type:"string",description:"Path to protocol markdown file."},injectIntoSystem:{type:"boolean",description:"Whether to inject protocol rules into the system prompt.",default:!1},auditToolCalls:{type:"boolean",description:"Whether to audit tool calls for protocol violations.",default:!1}}},graphSync:{type:"object",description:"Graph synchronization (auto-init codegraph/graphify).",additionalProperties:!1,properties:{enabled:{type:"boolean",description:"Enable auto-initialization of codegraph and graphify.",default:!0},watch:{type:"boolean",description:"Enable watch mode (re-index on file changes).",default:!1}}}},definitions:{verbosity:{type:"string",enum:["silent","minimal","verbose"],description:"Verbosity level."},interventionMode:{type:"string",enum:["silent","message","system"],description:"Intervention injection mode."},minAction:{type:"string",enum:["warn","escalate","stop"],description:"Minimum action threshold."}}}}async function bQ(K){let Q=jK(),{writeFile:X}=await import("node:fs/promises");await X(K,JSON.stringify(Q,null,2)+`
6
- `,"utf-8")}var xQ={id:"omo-meta-governor",server:$K()},PX=xQ;export{bQ as writeSchemaFile,YQ as trimHistory,o as takeDecision,e as takeAnyDecision,r as stripJsoncComments,i as storeDecision,rK as stopWatches,p as score,a as runMetaGovernor,S as runGraphSync,lK as resetInitializedProjects,IQ as recordRecovery,g as predict,c as parseJsonc,l as observeAndLearn,KK as loadProtocol,PQ as loadOrchestratorConfigFromSources,b as loadOrchestratorConfig,MK as loadMetaGovernorConfig,I as loadJsoncFile,OQ as isMetaGovernorEnabled,MQ as hasDecision,u as handleDecision,s as getUserConfigPath,n as getProjectConfigPath,jK as generateSchema,eK as defaultTokenPredictorConfig,C as defaultScoringConfig,wK as defaultOrchestratorConfig,j as defaultDecisionHandlerConfig,_ as defaultClosedLoopConfig,PX as default,O as deepMerge,$K as createMetaGovernorPlugin,WQ as countConsecutiveStops,kQ as clearAll,GK as calculateBurnRate,QK as buildSystemInjection,_K as buildDecisionContext,TQ as auditToolCall,f as aggregateRead,x as DEFAULT_PROTOCOL_PATH};
1
+ import{createRequire as uK}from"node:module";var fK=Object.defineProperty;var mK=(K)=>K;function gK(K,Q){this[K]=mK.bind(null,Q)}var pK=(K,Q)=>{for(var X in Q)fK(K,X,{get:Q[X],enumerable:!0,configurable:!0,set:gK.bind(Q,X)})};var dK=(K,Q)=>()=>(K&&(Q=K(K=0)),Q);var WK=uK(import.meta.url);var CK={};pK(CK,{stripJsoncComments:()=>o,parseJsonc:()=>e,loadMetaGovernorConfig:()=>yK,loadJsoncFile:()=>h,getUserConfigPath:()=>KK,getProjectConfigPath:()=>QK,deepMerge:()=>T});import{readFile as RQ,access as kQ}from"node:fs/promises";import{resolve as bK}from"node:path";import{homedir as NQ}from"node:os";function o(K){let Q=[],X=0;while(X<K.length){let $=K[X];if($==='"'||$==="'"){let J=$;Q.push(J),X++;while(X<K.length){let z=K[X];if(Q.push(z),z==="\\"){if(X++,X<K.length)Q.push(K[X])}else if(z===J){X++;break}X++}continue}if($==="/"&&X+1<K.length&&K[X+1]==="/"){X+=2;while(X<K.length&&K[X]!==`
2
+ `)X++;continue}if($==="/"&&X+1<K.length&&K[X+1]==="*"){X+=2;while(X<K.length){if(K[X]==="*"&&X+1<K.length&&K[X+1]==="/"){X+=2;break}X++}continue}Q.push($),X++}let Z=Q.join("");for(let $=0;$<10;$++){let J=Z;if(Z=Z.replace(/,(\s*[\]}])/g,"$1"),Z===J)break}return Z}function e(K){try{let Q=o(K);return JSON.parse(Q)}catch{return}}function KK(){return bK(NQ(),".config","opencode",jK)}function QK(K){let Q=K??process.cwd();return bK(Q,".opencode",jK)}async function EQ(K){try{return await kQ(K),!0}catch{return!1}}async function h(K){if(!await EQ(K))return;try{let Q=await RQ(K,"utf-8");return e(Q)}catch{return}}function T(K,Q){let X={...K};for(let Z of Object.keys(Q)){let $=Q[Z],J=X[Z];if($===void 0)continue;if(TK($)&&TK(J))X[Z]=T(J,$);else X[Z]=$}return X}function TK(K){return typeof K==="object"&&K!==null&&!Array.isArray(K)}async function yK(K={}){let Q=[],X="defaults",Z={},$=KK(),J=await h($);if(J)Z=T(Z,J),Q.push(`user:${$}`),X="user";let z=QK(K.projectDir),q=await h(z);if(q)Z=T(Z,q),Q.push(`project:${z}`),X="project";if(K.cliOptions&&Object.keys(K.cliOptions).length>0)Z=T(Z,K.cliOptions),Q.push("cli:inline"),X="cli";return{config:Z,sources:Q,effectiveSource:X}}var jK="omo-meta-governor.jsonc";var XK=()=>{};import{execSync as P,spawn as HK}from"node:child_process";import{access as lK,stat as aK}from"node:fs/promises";import{resolve as x}from"node:path";import{constants as cK}from"node:fs";async function rK(K,Q=60000){try{return P("npm i -D @colbymchenry/codegraph",{cwd:K,stdio:"ignore",timeout:Q}),"codegraph-installed"}catch{return"codegraph-install-failed"}}async function nK(K=60000){try{return P("pip install graphifyy --break-system-packages --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{try{return P("uv tool install graphifyy --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{return"graphify-install-failed"}}}var m=new Set;function sK(){m.clear()}var UK=new Map;function wK(K){let X=(UK.get(K)??0)+1;return UK.set(K,X),X}async function GK(K){let Q=!1,X=!1,Z=await _K(x(K,".codegraph")),$=await _K(x(K,"graphify-out"));try{P("npx --yes codegraph --version",{stdio:"ignore",timeout:1e4}),Q=!0}catch{try{P("node node_modules/.bin/codegraph --version",{cwd:K,stdio:"ignore",timeout:5000}),Q=!0}catch{}}try{P("python3 -c 'import graphify; print(graphify.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{try{P("python3 -c 'import graphifyy; print(graphifyy.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{}}return{codegraph:Q,graphify:X,codegraphIndexExists:Z,graphifyIndexExists:$}}async function iK(K){let Q=x(K,".codegraph");await AK(Q);try{P("npx --yes codegraph init",{cwd:K,stdio:"ignore",timeout:60000})}catch{}}async function tK(K){let Q=x(K,"graphify-out");await AK(Q);try{P("python3 -m graphify . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{try{P("graphifyy . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{}}}var b=new Map;function FK(K,Q){let X=`${K}:${Q}`;if(b.has(X))return;try{let Z;if(Q==="codegraph")Z=HK("node",["-e",`
3
+ const {execSync} = require("child_process");
4
+ const run = () => {
5
+ try { execSync("npx codegraph update 2>/dev/null", {cwd: ${JSON.stringify(K)}, stdio: "ignore"}); }
6
+ catch(e) { /* best effort */ }
7
+ };
8
+ run();
9
+ setInterval(run, 30_000);
10
+ `],{stdio:"ignore",detached:!0});else Z=HK("python3",["-m","graphify",".","--no-viz","--watch"],{cwd:K,stdio:"ignore",detached:!0});Z.unref(),b.set(X,{process:Z,tool:Q}),Z.on("exit",()=>{b.delete(X)})}catch{}}function oK(K){for(let[Q,X]of b)if(!K||Q.startsWith(K)){try{X.process.kill("SIGTERM")}catch{}setTimeout(()=>{try{X.process.kill("SIGKILL")}catch{}},2000).unref(),b.delete(Q)}}async function g(K={enabled:!0,watch:!1,autoInstall:!0,installTimeoutMs:60000}){let Q=[],X=K.projectDir??process.cwd();if(!K.enabled)return{attempted:!1,codes:["disabled"],availability:{codegraph:!1,graphify:!1,codegraphIndexExists:!1,graphifyIndexExists:!1},alreadyInitialized:!1};if(m.has(X)){let $=await GK(X);return{attempted:!1,codes:$.codegraphIndexExists?["codegraph-already-exists"]:[],availability:$,alreadyInitialized:!0}}m.add(X);let Z;try{Z=await GK(X)}catch{return{attempted:!1,codes:["error"],availability:{codegraph:!1,graphify:!1,codegraphIndexExists:!1,graphifyIndexExists:!1},alreadyInitialized:!1}}if(K.autoInstall!==!1){if(!Z.codegraph){let $=await rK(X,K.installTimeoutMs??60000);if(Q.push($),$==="codegraph-installed")Z.codegraph=!0}if(!Z.graphify){let $=await nK(K.installTimeoutMs??60000);if(Q.push($),$==="graphify-installed")Z.graphify=!0}}else{if(!Z.codegraph)Q.push("codegraph-install-skipped");if(!Z.graphify)Q.push("graphify-install-skipped")}if(Z.codegraph)if(!Z.codegraphIndexExists)try{await iK(X),Q.push("codegraph-initialized")}catch{Q.push("error")}else Q.push("codegraph-already-exists");else Q.push("codegraph-unavailable");if(Z.graphify)if(!Z.graphifyIndexExists)try{await tK(X),Q.push("graphify-initialized")}catch{Q.push("error")}else Q.push("graphify-already-exists");else Q.push("graphify-unavailable");if(K.watch){if(Z.codegraph)FK(X,"codegraph"),Q.push("watch-started-codegraph");if(Z.graphify)FK(X,"graphify"),Q.push("watch-started-graphify")}return{attempted:!0,codes:Q,availability:Z,alreadyInitialized:!1}}async function _K(K){try{return(await aK(K)).isDirectory()}catch{return!1}}async function AK(K){try{await lK(K,cK.F_OK)}catch{let{mkdir:Q}=await import("node:fs/promises");await Q(K,{recursive:!0})}}var LK={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function l(K,Q){let X=performance.now(),Z={...LK.limits,...K.limits},$={...LK.timeouts,...K.timeouts},[J,z,q]=await Promise.allSettled([eK(K,Q.agentmemory,Z,$.agentmemoryMs),KQ(K,Q.magicContext,Z,$.magicContextMs),QQ(K,Q.boulderState,Z,$.boulderStateMs)]),B=[],W={},H=J.status==="fulfilled"?J.value:(d(B,W,"agentmemory",p(J.reason)),u.agentmemory),U=z.status==="fulfilled"?z.value:(d(B,W,"magicContext",p(z.reason)),u.magicContext),G=q.status==="fulfilled"?q.value:(d(B,W,"boulderState",p(q.reason)),u.boulderState);return{query:K.query,timestampISO:new Date().toISOString(),agentmemory:H,magicContext:U,boulderState:G,degradedSources:B,durationMs:performance.now()-X,errorMessages:W}}async function eK(K,Q,X,Z){let $=await a(Q.smartSearch({query:K.query,limit:X.maxLessons}),Z,"agentmemory");return{available:!0,lessons:XQ($.lessons).slice(0,X.maxLessons).map((z)=>({id:z.id,title:z.title,advice:"info",confidence:z.confidence,concepts:z.concepts}))}}async function KQ(K,Q,X,Z){return{available:!0,slots:(await a(Q.slotList({directory:K.directory}),Z,"magicContext")).filter((J)=>J.label.startsWith("meta_governor:")||ZQ(J,K.query)).sort((J,z)=>J.label.localeCompare(z.label)).slice(0,X.maxSlots).map((J)=>({label:J.label,content:J.content}))}}async function QQ(K,Q,X,Z){let $=await a(Q.boulderRead({directory:K.directory,sessionID:K.sessionID,query:K.query}),Z,"boulderState");return{available:!0,tasks:$.sort((z,q)=>z.priority-q.priority||q.updatedAtMs-z.updatedAtMs).slice(0,X.maxTasks).map((z)=>({id:z.id,status:z.status,title:z.title})),planProgress:$Q($)}}function XQ(K){return[...K].sort((Q,X)=>X.confidence-Q.confidence)}function ZQ(K,Q){let X=Q.toLowerCase();return K.label.toLowerCase().includes(X)||K.content.toLowerCase().includes(X)}function $Q(K){if(K.length===0)return 0;return K.filter((X)=>X.status==="done").length/K.length}function p(K){if(K instanceof Error)return K.message;if(typeof K==="string")return K;return"unknown error"}function d(K,Q,X,Z){K.push(X),Q[X]=Z}var u={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function a(K,Q,X){return new Promise((Z,$)=>{let J=setTimeout(()=>$(Error(`${X} timeout after ${Q}ms`)),Q);K.then((z)=>{clearTimeout(J),Z(z)},(z)=>{clearTimeout(J),$(z)})})}function JQ(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function PK(K){if(K.length===0)return 0;return K.reduce((X,Z)=>X+Z,0)/K.length}function qQ(K,Q){let X=0;for(let Z=K.length-1;Z>=0;Z--)if(K[Z]>=Q)X++;else break;return X}function zQ(K,Q,X,Z){let $=Q-K;if($<=0)return Z;if(X<=0)return null;let J=Math.floor($/X);if(J<=0)return Z;let z=J*2;return new Date(new Date(Z).getTime()+z*1000).toISOString()}function c(K){let{currentUsage:Q,modelLimit:X,recentTurnTokens:Z,timestampISO:$,config:J}=K,z=Z.slice(-J.windowSize),q=PK(z),B=X-Q,W=X>0?Q/X:1,H=Math.min(0.95,0.3+z.length/J.windowSize*0.65),U="no-action",G="within normal parameters";if(W>=J.switchModelUsageThreshold)U="switch-model",G=`context usage ${(W*100).toFixed(1)}% exceeds switch threshold ${(J.switchModelUsageThreshold*100).toFixed(1)}%`;if(W>=J.compactUsageThreshold||q>=J.compactBurnRateThreshold){if(U==="no-action")U="compact-now",G=W>=J.compactUsageThreshold?`context usage ${(W*100).toFixed(1)}% exceeds compact threshold ${(J.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${q.toFixed(0)} tokens/turn exceeds threshold ${J.compactBurnRateThreshold}`}let w=qQ(z,J.compactBurnRateThreshold);if(w>=J.delegateConsecutiveHighBurn&&U==="no-action")U="delegate-to-subagent",G=`${w} consecutive high-burn turns (threshold: ${J.delegateConsecutiveHighBurn})`;let F=zQ(Q,X,q,$);return{currentUsage:Q,burnRate:q,budgetLeft:B,willOverflowAt:F,recommendation:U,confidence:H,modelLimit:X,windowRemaining:Math.max(0,Math.floor(B/Math.max(q,1))),input:{...K},computedAtISO:$,turnsAnalyzed:z.length}}var M={"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},I=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function BQ(K){let Q=[];Q.push({source:"oracle-verified",rawScore:K.oracleVerified?0.6:0,weight:M["oracle-verified"],weightedScore:K.oracleVerified?0.6*M["oracle-verified"]:0,description:K.oracleVerified?"Oracle verification passed":"No Oracle verification"}),Q.push({source:"no-progress-detector",rawScore:K.noProgress?-0.8:0,weight:M["no-progress-detector"],weightedScore:K.noProgress?-0.8*M["no-progress-detector"]:0,description:K.noProgress?"No progress detected in last turn":"Progress detected"});let X=YQ(K.deviations);Q.push({source:"deviation-detector",rawScore:X,weight:M["deviation-detector"],weightedScore:X*M["deviation-detector"],description:K.deviations.length>0?`${K.deviations.length} deviation(s) detected (worst: ${K.deviations[0].severity})`:"No deviations detected"});let Z=VQ(K.iterationRatio);Q.push({source:"iteration-budget",rawScore:Z,weight:M["iteration-budget"],weightedScore:Z*M["iteration-budget"],description:`Iteration ratio: ${K.iterationRatio.toFixed(2)} (${K.ambient.iteration}/${K.ambient.maxIterations})`});let $=WQ(K.lessonsRelevant);return Q.push({source:"lesson-recall",rawScore:$,weight:M["lesson-recall"],weightedScore:$*M["lesson-recall"],description:K.lessonsRelevant.length>0?`${K.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${HQ(K.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),Q}function YQ(K){if(K.length===0)return 0;let Q={grave:-0.9,media:-0.5,leve:-0.2},X=0;for(let $ of K){let J=Q[$.severity]??-0.3;if(J<X)X=J}let Z=Math.min(K.length*0.05,0.2);return Math.max(X-Z,-1)}function VQ(K){if(K<=0.5)return-K*0.6;return-0.3-(K-0.5)*1}function WQ(K){if(K.length===0)return 0;let Q=0;for(let X of K)Q+=({continue:0.3,info:0,warn:-0.3,stop:-0.7}[X.advice]??0)*X.confidence;return Math.max(Math.min(Q/K.length,1),-1)}function HQ(K){if(K.length===0)return 0;return K.reduce((Q,X)=>Q+X.confidence,0)/K.length}function UQ(K,Q){if(K>=Q.continueThreshold)return"continue";if(K<=-Q.stopThreshold)return"stop";if(K<=-Q.escalateThreshold)return"escalate";if(K<=-Q.warnThreshold)return"warn";return"continue"}function GQ(K,Q){if(!K.oracleVerified)return"oracle";if(K.deviations.some((X)=>X.severity==="grave"))return"user";return Q.defaultEscalationTarget}function MK(K,Q,X,Z){if(Z)return`Paralysis detected: forced continue despite score ${K.toFixed(3)} (too many consecutive stops)`;let $=[...X].sort((W,H)=>W.weightedScore-H.weightedScore),J=$[0],z=$[$.length-1],q=[];if(J.weightedScore<0)q.push(`primary concern: ${J.description}`);if(z.weightedScore>0)q.push(`positive signal: ${z.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[Q]} (score: ${K.toFixed(3)}): ${q.join("; ")||"balanced signals"}`}function r(K,Q){let X={...I(),...Q},Z=BQ(K),$=Z.reduce((U,G)=>U+G.weightedScore,0),J=Math.max(Math.min($,1),-1),z=K.slotMemory.consecutiveStops>=X.paralysisThreshold&&J<=-X.warnThreshold,q=z?"continue":UQ(J,X),B=[];if(q!=="continue"||Math.abs(J)<X.continueThreshold){for(let U of Z)if(Math.abs(U.weightedScore)>0.01)B.push({source:U.source,value:U.description,confidence:Math.abs(U.rawScore),weight:U.weight});if(B.length===0&&q!=="continue")B.push({source:"ambient",value:MK(J,q,Z,z),confidence:0.5,weight:0.1})}let W=q==="escalate"?GQ(K,X):null;return{decision:{action:q,score:J,reasoning:MK(J,q,Z,z),evidence:B,shouldEscalateTo:W},contributions:Z,rawScore:J,paralysisOverride:z,computedAtISO:new Date().toISOString()}}var S=()=>({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 D(K,Q){let X=K;for(let[Z,$]of Object.entries(Q))X=X.replaceAll(`{${Z}}`,$);return X}function FQ(K){return K.length}function n(K,Q){let X={...S(),...Q};if(!X.enabled)return{action:"continue",message:null,historyEntry:{decision:K.scoringResult.decision,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:"Decision handler disabled — pass-through continue"}};let Z=K.scoringResult.decision,$=Z.score,J=Z.reasoning,z=FQ(Z.evidence),q=Z.shouldEscalateTo??X.defaultEscalationTarget??"oracle";if(K.scoringResult.paralysisOverride)return{action:"continue",message:D(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:`Paralysis detected — forced continue. ${J}`,evidenceCount:String(z)}),historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Paralysis override: ${J}`}};switch(Z.action){case"continue":return{action:"continue",message:null,historyEntry:{decision:Z,action:"continue",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}};case"warn":return{action:"warn",message:D(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:J,evidenceCount:String(z)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}};case"escalate":return{action:"escalate",message:D(X.escalateMessageTemplate,{target:q,reasoning:J}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Escalate to ${q}: ${J}`}};case"stop":return{action:"stop",message:D(X.stopMessageTemplate,{reasoning:J,evidenceCount:String(z)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}}}}function _Q(K,Q){if(K.length<=Q)return{trimmed:[...K],dropped:0};let X=K.length-Q;return{trimmed:K.slice(-Q),dropped:X}}function wQ(K){let Q=0;for(let X=K.length-1;X>=0;X--)if(K[X].action==="stop")Q++;else break;return Q}var OK={leve:0,media:1,grave:2};function AQ(K,Q,X){let Z=`${K}-${Q}-${X}`.split("").reduce(($,J)=>($<<5)-$+J.charCodeAt(0)|0,0);return`D-${Math.abs(Z).toString(36)}`}function RK(K,Q){let X=OK[Q]??0;return K.some((Z)=>(OK[Z.severity]??0)>=X)}function LQ(K){let Q=new Set;for(let X of K)Q.add(X.category),Q.add(X.severity);return[...Q]}function PQ(K,Q){let X=Q.map((Z)=>`[${Z.severity}] ${Z.category}: ${Z.detail}`).join("; ");return`Action "${K.action}" (score ${K.score.toFixed(2)}) after deviations: ${X}. Reasoning: ${K.reasoning}`}async function s(K,Q){let{decision:X,config:Z,sessionID:$,directory:J,filesChanged:z}=K,q=new Date().toISOString();if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};if(X.evidence.length===0&&X.action==="continue")return{lessonSaved:null,decisionSaved:null,reason:"no deviations to learn from"};let B=null,W=null;if(Z.saveDecisions){let G={id:AQ($,X.action,q),timestampISO:q,action:X.action,score:X.score,reasoning:X.reasoning,sessionID:$,directory:J,deviations:X.evidence.filter((w)=>w.source==="deviation-detector").map((w)=>({severity:"media",category:w.source,detail:w.value}))};try{await Q.saveMemory({content:`Decision: ${X.action} (score ${X.score.toFixed(2)}). ${X.reasoning}`,concepts:["meta-governor","decision",X.action],type:"fact",files:[...z]}),W=G}catch{}}let H=X.evidence.filter((G)=>G.source==="deviation-detector").map((G)=>({severity:"media",category:G.source,detail:G.value}));if(RK(H,Z.minSeverityToLearn)){let G=LQ(H),w=PQ(X,H);try{B={id:(await Q.saveLesson({content:w,context:`session:${$} dir:${J}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),tags:G})).id,title:`${X.action} after ${H[0]?.category??"deviation"}`,content:w,type:"pattern",concepts:G,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),files:[...z],sessionID:$}}catch{}}let U=[];if(W)U.push("decision saved");if(B)U.push("lesson saved");if(!W&&!B)if(!RK(H,Z.minSeverityToLearn))U.push("severity below threshold");else U.push("no saveable content");return{lessonSaved:B,decisionSaved:W,reason:U.join("; ")||"no action taken"}}function k(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var NK=()=>({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}}),i={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},MQ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},OQ={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 EK(K,Q=i){let X=K.maxIterations>0?K.iteration/K.maxIterations:0,Z={...MQ,consecutiveStops:K.consecutiveStops??0};return{oracleVerified:K.oracleVerified,noProgress:K.noProgress,deviations:K.deviations,iterationRatio:X,lessonsRelevant:Q.agentmemory.lessons,slotMemory:Z,ambient:{sessionID:K.sessionID,directory:".",mode:"simple",agentName:K.agentName??"unknown",iteration:K.iteration,maxIterations:K.maxIterations}}}async function t(K,Q={}){let X={...NK(),...Q};if(!X.enabled)return{memoryRead:i,tokenPrediction:kK(K),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:OQ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=i;if(X.memory.enabled)try{let W={agentmemory:K.backends.agentmemory,magicContext:K.backends.magicContext,boulderState:K.backends.boulderState};Z=await l({directory:".",sessionID:K.sessionID,query:X.memory.query||K.toolName},W)}catch{}let $;try{$=c({currentUsage:K.recentTurnTokens.reduce((W,H)=>W+H,0),modelLimit:K.modelLimit??Q.modelOverride?.modelLimit??200000,recentTurnTokens:K.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:K.providerID??"",modelID:K.modelID??"",config:X.tokenPredictor})}catch{$=kK(K)}let J=r(EK(K,Z),X.scoring),z={sessionID:K.sessionID,scoringResult:J},q=n(z,X.decision),B=null;try{if(X.closedLoop.enabled!==!1)B=await s({decision:q.historyEntry.decision,memoryRead:Z,config:{...k(),...X.closedLoop},sessionID:K.sessionID,directory:".",filesChanged:[]},K.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:$,scoringResult:J,decision:q,lessonSaved:B,decisionHistory:[q.historyEntry],skipped:!1}}function kK(K){let Q=K.recentTurnTokens.reduce((X,Z)=>X+Z,0);return{burnRate:0,budgetLeft:200000,currentUsage:Q,modelLimit:200000,willOverflowAt:null,recommendation:"no-action",confidence:1,windowRemaining:200000,input:{currentUsage:Q,modelLimit:200000,recentTurnTokens:K.recentTurnTokens,timestampISO:new Date().toISOString(),providerID:K.providerID??"",modelID:K.modelID??"",config:{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}},computedAtISO:new Date().toISOString(),turnsAnalyzed:K.recentTurnTokens.length}}function v(K){let Q={enabled:!1,...K},X=I(),Z=S(),$=k();return{enabled:Q.enabled===!0,memory:{enabled:!0,query:Q.memory?.query??"meta_governor_context",timeoutMs:Q.memory?.agentmemoryTimeoutMs??2000},tokenPredictor:{compactBurnRateThreshold:Q.tokenPredictor?.compactBurnRateThreshold??500,compactUsageThreshold:Q.tokenPredictor?.compactUsageThreshold??0.85,switchModelUsageThreshold:Q.tokenPredictor?.switchModelUsageThreshold??0.95,delegateConsecutiveHighBurn:Q.tokenPredictor?.delegateConsecutiveHighBurn??5},scoring:{...X,...Q.scoring?.continueThreshold!==void 0?{continueThreshold:Q.scoring.continueThreshold}:{},...Q.scoring?.warnThreshold!==void 0?{warnThreshold:Q.scoring.warnThreshold}:{},...Q.scoring?.escalateThreshold!==void 0?{escalateThreshold:Q.scoring.escalateThreshold}:{},...Q.scoring?.stopThreshold!==void 0?{stopThreshold:Q.scoring.stopThreshold}:{}},closedLoop:{...$,...Q.closedLoop?.saveDecisions!==void 0?{saveDecisions:Q.closedLoop.saveDecisions}:{}},decision:{...Z,...Q.decision?.maxHistoryPerSession!==void 0?{maxHistoryPerSession:Q.decision.maxHistoryPerSession}:{},...Q.decision?.forceContinueAfterStops!==void 0?{forceContinueAfterStops:Q.decision.forceContinueAfterStops}:{}},modelOverride:Q.modelOverride?{providerID:Q.modelOverride.providerID,modelID:Q.modelOverride.modelID,modelLimit:Q.modelOverride.modelLimit,temperature:Q.modelOverride.temperature??0.2,topP:Q.modelOverride.topP??1,maxTokens:Q.modelOverride.maxTokens??2048,reasoning:Q.modelOverride.reasoning??!1,verbosity:Q.modelOverride.verbosity??"minimal"}:void 0,intervention:{mode:Q.intervention?.mode??"silent",includeDecisionHistory:Q.intervention?.includeDecisionHistory??!0,maxHistoryMessages:Q.intervention?.maxHistoryMessages??5,minActionForMessage:Q.intervention?.minActionForMessage??"warn"},protocolEnforcement:{enabled:Q.protocolEnforcement?.enabled??!1,path:Q.protocolEnforcement?.path,injectIntoSystem:Q.protocolEnforcement?.injectIntoSystem??!1,auditToolCalls:Q.protocolEnforcement?.auditToolCalls??!1}}}function TQ(K){return K?.enabled===!0}async function bQ(K={}){let{loadMetaGovernorConfig:Q}=await Promise.resolve().then(() => (XK(),CK)),X=await Q(K);return v(X.config)}var N=new Map;function ZK(K,Q){N.set(K,Q)}function $K(K){let Q=N.get(K);if(Q!==void 0)N.delete(K);return Q}function jQ(K){return N.has(K)}function JK(){for(let[K,Q]of N)return N.delete(K),Q;return}function yQ(){N.clear()}import{appendFileSync as CQ,mkdirSync as xQ}from"node:fs";import{resolve as IQ,dirname as DQ}from"node:path";import{homedir as SQ}from"node:os";var xK=IQ(SQ(),".config","opencode","meta-governor.log");function hQ(){try{xQ(DQ(xK),{recursive:!0})}catch{}}function j(K,Q,X){hQ();let Z=new Date().toISOString(),$=X!==void 0?` | ${JSON.stringify(X)}`:"",J=`[${Z}] [${K.toUpperCase()}] ${Q}${$}
11
+ `;try{CQ(xK,J)}catch{}if(K==="error")console.error(`[meta-governor] ${Q}`);else if(K==="warn")console.warn(`[meta-governor] ${Q}`);else console.log(`[meta-governor] ${Q}`)}import{readFile as vQ}from"node:fs/promises";import{resolve as fQ}from"node:path";import{homedir as mQ}from"node:os";var f=fQ(mQ(),".config","opencode","sisyphus-mandatory","sisyphus-mandatory.md");async function qK(K){return await vQ(K??f,"utf-8")}function zK(K){let Q=["","## 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"," - Working note for THIS session only → `ctx_note`"," - Save durable insight/decision/rule → `ctx_memory`",""];if(/\boracle\b/i.test(K))Q.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 Q.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."," - Do NOT suppress type errors with `as any`, `@ts-ignore`, or `@ts-expect-error`."," - Do NOT leave empty catch blocks `catch(e) {}`.",' - Do NOT start a fresh agent via `task()` when `task(task_id="ses_...")` (continuation) exists — use continuation IDs.'," - Do NOT batch-complete todos — mark each one `completed` immediately after finishing."," - Do NOT skip creating todos for multi-step tasks.","","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."," - After discovering something non-obvious, save it with `ctx_memory` so future sessions benefit.",""),Q.join(`
12
+ `)}function BK(K,Q,X){let Z=[],$=X.recentToolCalls??[],J=X.aftAvailable??!1,z=X.aftUsed??!1,q=X.recentWriteContents??[],B=X.memorySaved??!1,W=X.batchCompletions??0;if((K==="grep"||K==="glob")&&(X.hasCodegraphDir||X.hasGraphifyDir)){let F=X.hasCodegraphDir?".codegraph":"graphify-out";Z.push({rule:"codebase-graph-first",tool:K,severity:"media",detail:`Used ${K} when ${F} exists — should use codegraph/graphify first for architecture and symbol queries.`})}if((K==="read"||K==="grep")&&J&&!z)Z.push({rule:"aft-first",tool:K,severity:"media",detail:`AFT tools (aft_outline, aft_zoom) are available but were not tried before using ${K}. Use aft_outline for structure discovery, aft_zoom for symbol source, before falling back to grep/read.`});if(K==="grep"&&J&&!z&&!X.hasCodegraphDir&&!X.hasGraphifyDir)Z.push({rule:"grep-without-aft",tool:K,severity:"leve",detail:"Used grep before checking if aft_outline would answer the structure question. grep is a last resort after graph tools and AFT."});if(K==="task"&&Q&&typeof Q==="object"){let F=Q;if(!F.task_id&&typeof F.prompt==="string"&&$.length>3)Z.push({rule:"continuation-discipline",tool:K,severity:"leve",detail:`Started a new task() without task(task_id="ses_...") continuation ID. Use task_id to preserve the subagent's full context and save tokens.`})}let H=["write","edit","edit_block","desktop-commander_edit_block","desktop-commander_write_file"];if(H.includes(K)){let F=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??""),A=/@ts-ignore|@ts-expect-error/.test(F),V=/\bas any\b/.test(F);if(A&&V)Z.push({rule:"no-type-suppression",tool:K,severity:"grave",detail:"File write contains both @ts-ignore/@ts-expect-error AND 'as any' — double type suppression. "+"Both are forbidden by the Sisyphus protocol."});else if(A)Z.push({rule:"no-type-suppression",tool:K,severity:"media",detail:"File write contains @ts-ignore or @ts-expect-error — both are forbidden. "+"Fix the underlying type error instead."});else if(V)Z.push({rule:"no-type-suppression",tool:K,severity:"media",detail:"File write contains 'as any' — type suppression forbidden. "+"Use proper type narrowing instead."})}if(H.includes(K)){let F=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??"");if(/catch\s*\(\s*\w+\s*\)\s*\{\s*\}/.test(F))Z.push({rule:"no-empty-catch",tool:K,severity:"media",detail:"Empty catch block detected — `catch(e) {}` is forbidden. "+"Log the error or handle it gracefully."})}if(["grep","glob","read","aft_zoom","aft_outline","codegraph_explore","graphify query"].includes(K)&&$.length>=2){if(!$.slice(0,5).some((A)=>A.startsWith("ctx_memory"))&&!B)Z.push({rule:"save-discovery-to-memory",tool:K,severity:"leve",detail:`Used ${K} to discover code but ctx_memory was not used afterwards. Save non-obvious findings with ctx_memory so future sessions benefit.`})}if(W>0&&K!=="todowrite")Z.push({rule:"no-batch-todo-completion",tool:K,severity:"leve",detail:"Batch todo completion detected. Each todo must be marked `completed` immediately "+"after finishing — do not batch-complete multiple items."});if(K==="ctx_reduce"&&Q&&typeof Q==="object"){let F=Q.drop;if(typeof F==="string"&&/^\d+-\d+$/i.test(F.trim())){let[A,V]=F.trim().split("-").map(Number);if(!isNaN(A)&&!isNaN(V)&&V-A>10)Z.push({rule:"ctx-reduce-discipline",tool:K,severity:"leve",detail:`Dropped a large range (${F}) with ctx_reduce. The protocol requires reviewing each tag before dropping. Use smaller targeted drops instead of blanket ranges.`})}}if(X.emptyRecall&&!X.escalationAttempted){if(K.startsWith("question")||K==="ask")Z.push({rule:"empty-result-escalation",tool:K,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 G=["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"];if(!X.memoryToolsUsed.some((F)=>G.some((A)=>F.startsWith(A)))&&(K.startsWith("question")||K==="ask"))Z.push({rule:"memory-first",tool:K,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(X.filesChanged>=3&&!X.oracleInvoked){if(K!=="task"||!Q||typeof Q!=="object"||!("subagent_type"in Q))Z.push({rule:"oracle-verification",tool:K,severity:"media",detail:`Files changed (${X.filesChanged}) >= 3 but Oracle was not invoked. The POST-TASK ORACLE VERIFICATION protocol requires Oracle invocation on multi-file changes.`})}return Z}var IK={continue:0,warn:1,escalate:2,stop:3};function YK(K,Q){return IK[K]>=IK[Q]}function VK(K={},Q={}){if(K.graphSync?.enabled!==!1){let $=process.cwd();g({enabled:!0,watch:K.graphSync?.watch??!1,autoInstall:K.graphSync?.autoInstall??!0,installTimeoutMs:K.graphSync?.installTimeoutMs??60000,projectDir:$}).catch(()=>{}),wK($)}return async($,J)=>{let z={...K,...J?.meta_governor??{}},q=v(z);if(!q.enabled)return{};let B=()=>q.modelOverride?.providerID??Q.providerID?.(),W=()=>q.modelOverride?.modelID??Q.modelID?.(),H=()=>q.modelOverride?.modelLimit??200000,U=B()??"unknown",G=W()??"unknown",w;if(q.protocolEnforcement.enabled||q.protocolEnforcement.injectIntoSystem){let V=q.protocolEnforcement.path??f;qK(V).then((Y)=>{w=zK(Y)}).catch((Y)=>{if(typeof console<"u"&&q.modelOverride?.verbosity!=="silent")console.warn("[meta-governor] could not load protocol:",Y instanceof Error?Y.message:Y)})}let F=new Map,A=new Map;return{"tool.execute.before":async(V)=>{if(!q.enabled)return;if(!q.protocolEnforcement.auditToolCalls)return;if(!V.sessionID)return;let Y=F.get(V.sessionID);if(!Y)Y={memoryToolsUsed:[],hasCodegraphDir:!1,hasGraphifyDir:!1,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1,aftAvailable:!1,aftUsed:!1,recentToolCalls:[],recentWriteContents:[],memorySaved:!1,batchCompletions:0},F.set(V.sessionID,Y);if(w)console.log("[meta-governor] protocol loaded, system injection ready");let _=BK(V.tool,{},{memoryToolsUsed:Y.memoryToolsUsed,hasCodegraphDir:Y.hasCodegraphDir,hasGraphifyDir:Y.hasGraphifyDir,oracleInvoked:Y.oracleInvoked,filesChanged:Y.filesChanged,emptyRecall:Y.emptyRecall,escalationAttempted:Y.escalationAttempted,aftAvailable:Y.aftAvailable,aftUsed:Y.aftUsed,recentToolCalls:Y.recentToolCalls,recentWriteContents:Y.recentWriteContents,memorySaved:Y.memorySaved,batchCompletions:Y.batchCompletions});if(_.length>0){j("warn",`protocol violations on tool ${V.tool}`,_);let O=A.get(V.sessionID)??[];for(let L of _)O.push(`[${L.severity.toUpperCase()}] ${L.rule}: ${L.detail}`);A.set(V.sessionID,O)}else j("info",`audit OK on tool ${V.tool}`)},"tool.execute.after":async(V,Y)=>{if(!q.enabled)return;let _=F.get(V.sessionID);if(_){if(_.recentToolCalls=[V.tool].concat(_.recentToolCalls).slice(0,20),["write","edit","edit_block","desktop-commander_write_file","desktop-commander_edit_block"].includes(V.tool)){_.filesChanged++;let R=(Y.output??"").slice(0,500);_.recentWriteContents=[R].concat(_.recentWriteContents).slice(0,3)}if(["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"].some((R)=>V.tool.startsWith(R))&&!_.memoryToolsUsed.includes(V.tool))_.memoryToolsUsed.push(V.tool);if(V.tool.startsWith("ctx_memory")){let R=Y.output??"";if(R.includes("saved")||R.includes("written"))_.memorySaved=!0}if(V.tool.startsWith("aft_zoom")||V.tool.startsWith("aft_outline"))_.aftUsed=!0;if(V.tool==="task"&&(Y.output??"").includes("subagent_type=oracle"))_.oracleInvoked=!0;let C=(Y.output??"").toLowerCase();if(V.tool.includes("recall")&&(C.includes("returned empty")||C.includes("no results")))_.emptyRecall=!0;if(V.tool==="todowrite"&&(Y.output??"").includes("completed")){if(((Y.output??"").match(/"status":"completed"/g)??[]).length>=3)_.batchCompletions++}}let O={sessionID:V.sessionID,toolName:V.tool,toolOutput:Y.output,iteration:0,maxIterations:10,oracleVerified:!1,noProgress:!1,filesChanged:0,recentTurnTokens:[],deviations:[],backends:Q.backends??{agentmemory:{smartSearch:async()=>({lessons:[],crystals:[]})},magicContext:{slotList:async()=>[]},boulderState:{boulderRead:async()=>[]}},writeBackend:Q.writeBackend??{saveMemory:async()=>({id:""}),saveLesson:async()=>({id:""})},config:q,...B()?{providerID:B()}:{},...W()?{modelID:W()}:{},modelLimit:H()};try{let L=await t(O);if(q.intervention.mode!=="silent"){let E=L.decision;if(E.action!=="continue"&&YK(E.action,q.intervention.minActionForMessage))ZK(V.sessionID,E)}}catch{}},"experimental.chat.messages.transform":async(V,Y)=>{if(!q.enabled)return;if(q.intervention.mode!=="message")return;let O=Y.messages[Y.messages.length-1]?.info?.sessionID;if(O&&A.has(O)){let y=A.get(O);if(y.length>0){let C=`[META-GOVERNOR PROTOCOL VIOLATIONS - YOU MUST COMPLY]
7
13
 
8
- //# debugId=4C126AF415E75E0064756E2164756E21
14
+ ${y.map((R,vK)=>`${vK+1}. ${R}`).join(`
15
+ `)}
16
+
17
+ Remember: use codegraph/graphify for architecture queries, do not grep without trying AFT/codegraph first, no @ts-ignore/as-any, no empty catch, check memory before asking.`;Y.messages.push({info:{role:"user",agent:"meta-governor",synthetic:!0},parts:[{type:"text",text:C,synthetic:!0}]}),A.delete(O),j("info",`injected ${y.length} violation(s) to model`)}}let L=JK();if(!L)return;if(L.action==="continue")return;if(!L.message)return;if(!YK(L.action,q.intervention.minActionForMessage))return;let E={type:"text",text:`[MetaGovernor] ${L.message}`,synthetic:!0};Y.messages.push({info:{role:"user",agent:"meta-governor"},parts:[E]})},"experimental.chat.system.transform":async(V,Y)=>{if(!q.enabled)return;if(q.protocolEnforcement.injectIntoSystem&&w)Y.system.push(`
18
+ ### Sisyphus Protocol Enforcement`,w,"---");if(q.intervention.mode==="system"&&V.sessionID){let _=$K(V.sessionID);if(_&&_.action!=="continue"&&_.message){if(YK(_.action,q.intervention.minActionForMessage))Y.system.push(`
19
+ [MetaGovernor Intervention]`,_.message,"---")}}}}}}function gQ(K){let Q={severity:K.success?"leve":"grave",category:`recovery:${K.fixStrategy}`,detail:`${K.errorCode}: ${K.context??"no context"}`};return{action:K.success?"continue":"warn",score:K.success?0.5:-0.5,reasoning:`Recovery ${K.success?"succeeded":"failed"}: ${K.fixStrategy} for ${K.errorCode}`,evidence:[{source:"deviation-detector",value:Q.detail,confidence:1,weight:K.success?0.3:0.8}],shouldEscalateTo:K.success?null:"oracle"}}var DK={leve:0,media:1,grave:2};function SK(K,Q){let X=DK[Q]??0;return K.some((Z)=>(DK[Z.severity]??0)>=X)}async function pQ(K,Q,X){if(!Q)return null;let Z=X?.config??k(),$=gQ(K);if(!Z.enabled)return{lessonSaved:null,decisionSaved:null,reason:"closed-loop learning disabled"};let J=[{severity:K.success?"leve":"grave",category:`recovery:${K.fixStrategy}`,detail:`${K.errorCode}: ${K.context??"no context"}`}],z=null,q=null;if(Z.saveDecisions){let W={id:`D-${Math.abs(`${K.sessionID}-${$.action}-${Date.now()}`.split("").reduce((H,U)=>(H<<5)-H+U.charCodeAt(0)|0,0)).toString(36)}`,timestampISO:new Date().toISOString(),action:$.action,score:$.score,reasoning:$.reasoning,sessionID:K.sessionID,directory:K.directory,deviations:J.map((H)=>({severity:H.severity,category:H.category,detail:H.detail}))};try{await Q.saveMemory({content:`Decision: ${$.action} (score ${$.score.toFixed(2)}). ${$.reasoning}`,concepts:["meta-governor","decision",$.action,...J.map((H)=>H.category)],type:"fact",files:[...K.filesChanged??[]]}),q=W}catch{}}if(SK(J,Z.minSeverityToLearn)){let W=[...new Set(J.flatMap((G)=>[G.category,G.severity]))],H=J.map((G)=>`[${G.severity}] ${G.category}: ${G.detail}`).join("; "),U=`Action "${$.action}" (score ${$.score.toFixed(2)}) after deviations: ${H}. Reasoning: ${$.reasoning}`;try{z={id:(await Q.saveLesson({content:U,context:`session:${K.sessionID} dir:${K.directory}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),tags:W})).id,title:`${$.action} after ${J[0]?.category??"recovery"}`,content:U,type:"pattern",concepts:W,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),files:[...K.filesChanged??[]],sessionID:K.sessionID}}catch{}}let B=[];if(q)B.push("decision saved");if(z)B.push("lesson saved");else if(!SK(J,Z.minSeverityToLearn))B.push("severity below threshold");if(!q&&!z&&!B.length)B.push("no saveable content");return{lessonSaved:z,decisionSaved:q,reason:B.join("; ")||"no action taken"}}XK();function hK(){return{$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/herjarsa/omo-meta-governor/main/assets/omo-meta-governor.schema.json",title:"omo-meta-governor",description:"Configuration schema for @herjarsa/omo-meta-governor — Self-judging agent orchestration layer for OpenCode.",type:"object",additionalProperties:!1,properties:{$schema:{type:"string",description:"JSON Schema reference for IDE autocompletion."},enabled:{type:"boolean",description:"Master feature flag — must be true to run the orchestrator.",default:!1},decision:{type:"object",description:"Decision handler configuration.",additionalProperties:!1,properties:{maxHistoryPerSession:{type:"integer",description:"Maximum history entries per session before oldest are trimmed.",default:50,minimum:1},forceContinueAfterStops:{type:"integer",description:"How many consecutive stops before forcing continue.",default:3,minimum:1}}},memory:{type:"object",description:"Memory aggregator configuration.",additionalProperties:!1,properties:{agentmemoryTimeoutMs:{type:"integer",description:"Timeout for agentmemory queries in milliseconds.",default:2000,minimum:100},magicContextTimeoutMs:{type:"integer",description:"Timeout for magic-context queries in milliseconds.",default:1000,minimum:100},boulderStateTimeoutMs:{type:"integer",description:"Timeout for boulder-state queries in milliseconds.",default:1000,minimum:100},query:{type:"string",description:"Natural-language query for memory recall.",default:"meta_governor_context"}}},tokenPredictor:{type:"object",description:"Token predictor configuration.",additionalProperties:!1,properties:{compactBurnRateThreshold:{type:"integer",description:"Burn rate threshold (tokens/turn) above which to recommend compact-now.",default:500,minimum:0},compactUsageThreshold:{type:"number",description:"Context usage ratio (0..1) above which to recommend compact-now.",default:0.85,minimum:0,maximum:1},switchModelUsageThreshold:{type:"number",description:"Context usage ratio above which to recommend switch-model.",default:0.95,minimum:0,maximum:1},delegateConsecutiveHighBurn:{type:"integer",description:"Max consecutive high-burn turns before recommending delegate.",default:5,minimum:1}}},scoring:{type:"object",description:"Scoring engine configuration.",additionalProperties:!1,properties:{continueThreshold:{type:"number",description:"Score >= this -> continue silently.",default:0.3,minimum:0,maximum:1},warnThreshold:{type:"number",description:"Score <= -warnThreshold -> warn.",default:0.3,minimum:0,maximum:1},escalateThreshold:{type:"number",description:"Score <= -escalateThreshold -> escalate.",default:0.6,minimum:0,maximum:1},stopThreshold:{type:"number",description:"Score <= -stopThreshold -> stop.",default:0.8,minimum:0,maximum:1}}},closedLoop:{type:"object",description:"Closed-loop learning configuration.",additionalProperties:!1,properties:{saveDecisions:{type:"boolean",description:"Whether to save decision records.",default:!0},saveLessons:{type:"boolean",description:"Whether to save lessons.",default:!0}}},modelOverride:{type:"object",description:"Model override for MetaGovernor internal LLM usage.",additionalProperties:!1,properties:{providerID:{type:"string",description:"Provider ID (e.g. 'openai', 'anthropic')."},modelID:{type:"string",description:"Model ID (e.g. 'gpt-4o-mini', 'claude-sonnet-4-20250514')."},modelLimit:{type:"integer",description:"Context window size for token predictor.",minimum:1000},temperature:{type:"number",description:"Sampling temperature. Default: 0.2.",default:0.2,minimum:0,maximum:2},topP:{type:"number",description:"Top-p nucleus sampling. Default: 1.",default:1,minimum:0,maximum:1},maxTokens:{type:"integer",description:"Max output tokens for internal reasoning.",default:2048,minimum:1},reasoning:{type:"boolean",description:"Enable extended reasoning / thinking mode.",default:!1},verbosity:{type:"string",description:"Verbosity level for internal logging.",enum:["silent","minimal","verbose"],default:"minimal"}}},intervention:{type:"object",description:"Intervention config for visible decision injection.",additionalProperties:!1,properties:{mode:{type:"string",description:"How to inject: 'silent', 'message', or 'system'.",enum:["silent","message","system"],default:"silent"},includeDecisionHistory:{type:"boolean",description:"Whether to include recent decision history.",default:!0},maxHistoryMessages:{type:"integer",description:"Max history entries when includeDecisionHistory is true.",default:5,minimum:1},minActionForMessage:{type:"string",description:"Minimum action: 'warn' (all non-continue), 'escalate', or 'stop'.",enum:["warn","escalate","stop"],default:"warn"}}},protocolEnforcement:{type:"object",description:"Sisyphus protocol enforcement config.",additionalProperties:!1,properties:{enabled:{type:"boolean",description:"Master switch for protocol enforcement.",default:!1},path:{type:"string",description:"Path to protocol markdown file."},injectIntoSystem:{type:"boolean",description:"Whether to inject protocol rules into the system prompt.",default:!1},auditToolCalls:{type:"boolean",description:"Whether to audit tool calls for protocol violations.",default:!1}}},graphSync:{type:"object",description:"Graph synchronization (auto-init codegraph/graphify).",additionalProperties:!1,properties:{enabled:{type:"boolean",description:"Enable auto-initialization of codegraph and graphify.",default:!0},watch:{type:"boolean",description:"Enable watch mode (re-index on file changes).",default:!1}}}},definitions:{verbosity:{type:"string",enum:["silent","minimal","verbose"],description:"Verbosity level."},interventionMode:{type:"string",enum:["silent","message","system"],description:"Intervention injection mode."},minAction:{type:"string",enum:["warn","escalate","stop"],description:"Minimum action threshold."}}}}async function dQ(K){let Q=hK(),{writeFile:X}=await import("node:fs/promises");await X(K,JSON.stringify(Q,null,2)+`
20
+ `,"utf-8")}var uQ={id:"omo-meta-governor",server:VK()},fX=uQ;export{dQ as writeSchemaFile,_Q as trimHistory,$K as takeDecision,JK as takeAnyDecision,o as stripJsoncComments,ZK as storeDecision,oK as stopWatches,r as score,t as runMetaGovernor,g as runGraphSync,sK as resetInitializedProjects,pQ as recordRecovery,c as predict,e as parseJsonc,s as observeAndLearn,j as logToFile,qK as loadProtocol,bQ as loadOrchestratorConfigFromSources,v as loadOrchestratorConfig,yK as loadMetaGovernorConfig,h as loadJsoncFile,TQ as isMetaGovernorEnabled,jQ as hasDecision,n as handleDecision,KK as getUserConfigPath,QK as getProjectConfigPath,hK as generateSchema,JQ as defaultTokenPredictorConfig,I as defaultScoringConfig,NK as defaultOrchestratorConfig,S as defaultDecisionHandlerConfig,k as defaultClosedLoopConfig,fX as default,T as deepMerge,VK as createMetaGovernorPlugin,wQ as countConsecutiveStops,yQ as clearAll,PK as calculateBurnRate,zK as buildSystemInjection,EK as buildDecisionContext,BK as auditToolCall,l as aggregateRead,f as DEFAULT_PROTOCOL_PATH};
21
+
22
+ //# debugId=3FE6584FA205492964756E2164756E21
9
23
  //# sourceMappingURL=index.js.map
package/dist/index.js.map CHANGED
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "version": 3,
3
- "sources": ["../src/config-file.ts", "../src/graph-sync.ts", "../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", "../src/generate-schema.ts"],
3
+ "sources": ["../src/config-file.ts", "../src/graph-sync.ts", "../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/file-logger.ts", "../src/protocol-enforcer.ts", "../src/plugin.ts", "../src/post-repair-recorder.ts", "../src/index.ts", "../src/generate-schema.ts"],
4
4
  "sourcesContent": [
5
5
  "/**\n * JSONC config file loader for omo-meta-governor.\n *\n * Loads `omo-meta-governor.jsonc` from three layers (closer wins):\n * 1. CLI inline options (opts object) — highest priority\n * 2. Project config: `.opencode/omo-meta-governor.jsonc`\n * 3. User config: `~/.config/opencode/omo-meta-governor.jsonc`\n * 4. Defaults — lowest priority\n *\n * JSONC support: comments (//, /* * /) and trailing commas are stripped\n * before parsing. The raw JSON object is then projected into\n * `MetaGovernorPluginConfig` via `loadOrchestratorConfig()`.\n */\n\nimport { readFile, access } from \"node:fs/promises\"\nimport { resolve, join } from \"node:path\"\nimport { homedir } from \"node:os\"\nimport type { MetaGovernorPluginConfig } from \"./config\"\n\n// ─── File name ─────────────────────────────────────────────────────\n\nconst CONFIG_FILE_NAME = \"omo-meta-governor.jsonc\"\n\n// ─── JSONC parsing ─────────────────────────────────────────────────\n\n/**\n * Strip JSONC comments (single-line // style and multi-line bracket style)\n * and trailing commas from a JSONC string so it can be parsed by JSON.parse.\n *\n * Handles:\n * - // single-line comments\n * - /asterisk ... asterisk/ multi-line comments\n * - Trailing commas before ] or }\n * - Strings containing comments (preserved)\n */\nexport function stripJsoncComments(jsonc: string): string {\n const result: string[] = []\n let i = 0\n\n while (i < jsonc.length) {\n const ch = jsonc[i]!\n\n // Detect string literal\n if (ch === '\"' || ch === \"'\") {\n const quote = ch\n result.push(quote)\n i++\n while (i < jsonc.length) {\n const c = jsonc[i]!\n result.push(c)\n if (c === '\\\\') {\n i++\n if (i < jsonc.length) {\n result.push(jsonc[i]!)\n }\n } else if (c === quote) {\n i++\n break\n }\n i++\n }\n continue\n }\n\n // Single-line comment\n if (ch === '/' && i + 1 < jsonc.length && jsonc[i + 1] === '/') {\n i += 2\n while (i < jsonc.length && jsonc[i] !== '\\n') {\n i++\n }\n continue\n }\n\n // Multi-line comment\n if (ch === '/' && i + 1 < jsonc.length && jsonc[i + 1] === '*') {\n i += 2\n while (i < jsonc.length) {\n if (jsonc[i] === '*' && i + 1 < jsonc.length && jsonc[i + 1] === '/') {\n i += 2\n break\n }\n i++\n }\n continue\n }\n\n result.push(ch)\n i++\n }\n\n // Strip trailing commas before ] or }\n let cleaned = result.join(\"\")\n // Handle multiple passes for nested structures\n for (let pass = 0; pass < 10; pass++) {\n const before = cleaned\n cleaned = cleaned.replace(/,(\\s*[\\]}])/g, \"$1\")\n if (cleaned === before) break\n }\n\n return cleaned\n}\n\n/**\n * Parse a JSONC string into a JavaScript object.\n * Returns undefined on parse failure.\n */\nexport function parseJsonc<T = Record<string, unknown>>(jsonc: string): T | undefined {\n try {\n const cleaned = stripJsoncComments(jsonc)\n return JSON.parse(cleaned) as T\n } catch {\n return undefined\n }\n}\n\n// ─── Config paths ──────────────────────────────────────────────────\n\n/**\n * Get the user-level config file path.\n */\nexport function getUserConfigPath(): string {\n return resolve(homedir(), \".config\", \"opencode\", CONFIG_FILE_NAME)\n}\n\n/**\n * Get the project-level config file path for a given project directory.\n */\nexport function getProjectConfigPath(projectDir?: string): string {\n const base = projectDir ?? process.cwd()\n return resolve(base, \".opencode\", CONFIG_FILE_NAME)\n}\n\n// ─── File existence check ──────────────────────────────────────────\n\nasync function fileExists(filePath: string): Promise<boolean> {\n try {\n await access(filePath)\n return true\n } catch {\n return false\n }\n}\n\n// ─── Load single config file ───────────────────────────────────────\n\n/**\n * Read and parse a single JSONC config file.\n * Returns undefined if the file does not exist or is unparseable.\n */\nexport async function loadJsoncFile<T = Record<string, unknown>>(\n filePath: string,\n): Promise<T | undefined> {\n if (!(await fileExists(filePath))) return undefined\n try {\n const content = await readFile(filePath, \"utf-8\")\n return parseJsonc<T>(content)\n } catch {\n return undefined\n }\n}\n\n// ─── Merge two configs (deep merge, second wins) ───────────────────\n\n/**\n * Deep-merge two config objects. Arrays are replaced (not concatenated).\n * The `source` values win when both exist.\n * Mutually recursive with mergeArrays=false for sub-objects.\n */\nexport function deepMerge<T extends Record<string, unknown>>(\n target: T,\n source: Partial<T>,\n): T {\n const result = { ...target } as Record<string, unknown>\n\n for (const key of Object.keys(source)) {\n const srcVal = source[key as keyof typeof source]\n const tgtVal = result[key]\n\n if (srcVal === undefined) continue\n\n if (\n isPlainObject(srcVal) &&\n isPlainObject(tgtVal)\n ) {\n result[key] = deepMerge(tgtVal as Record<string, unknown>, srcVal as Record<string, unknown>)\n } else {\n result[key] = srcVal\n }\n }\n\n return result as T\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value)\n}\n\n// ─── Full config loading pipeline ──────────────────────────────────\n\nexport interface ConfigFileSources {\n /** CLI inline options (highest priority) */\n cliOptions?: Partial<MetaGovernorPluginConfig>\n /** Project directory for project-level config lookup */\n projectDir?: string\n}\n\nexport interface ConfigFileResult {\n /** The merged MetaGovernorPluginConfig */\n config: Partial<MetaGovernorPluginConfig>\n /** Which source files were loaded */\n sources: string[]\n /** Which source was the effective highest-priority non-empty source */\n effectiveSource: \"cli\" | \"project\" | \"user\" | \"defaults\"\n}\n\n/**\n * Load the MetaGovernor config from all available sources with priority:\n * CLI inline > project `.opencode/omo-meta-governor.jsonc` >\n * user `~/.config/opencode/omo-meta-governor.jsonc` > defaults\n *\n * Higher-priority sources override lower-priority ones.\n */\nexport async function loadMetaGovernorConfig(\n sources: ConfigFileSources = {},\n): Promise<ConfigFileResult> {\n const loadedSources: string[] = []\n let effectiveSource: ConfigFileResult[\"effectiveSource\"] = \"defaults\"\n\n // Start with empty config (defaults applied later by loadOrchestratorConfig)\n let merged: Partial<MetaGovernorPluginConfig> = {}\n\n // 1. User config (lowest file priority)\n const userPath = getUserConfigPath()\n const userConfig = await loadJsoncFile<Partial<MetaGovernorPluginConfig>>(userPath)\n if (userConfig) {\n merged = deepMerge(merged, userConfig)\n loadedSources.push(`user:${userPath}`)\n effectiveSource = \"user\"\n }\n\n // 2. Project config (medium file priority)\n const projectPath = getProjectConfigPath(sources.projectDir)\n const projectConfig = await loadJsoncFile<Partial<MetaGovernorPluginConfig>>(projectPath)\n if (projectConfig) {\n merged = deepMerge(merged, projectConfig)\n loadedSources.push(`project:${projectPath}`)\n effectiveSource = \"project\"\n }\n\n // 3. CLI inline options (highest priority)\n if (sources.cliOptions && Object.keys(sources.cliOptions).length > 0) {\n merged = deepMerge(merged, sources.cliOptions)\n loadedSources.push(\"cli:inline\")\n effectiveSource = \"cli\"\n }\n\n return {\n config: merged,\n sources: loadedSources,\n effectiveSource,\n }\n}\n",
6
- "/**\n * graphSync — Auto-initialize codegraph and graphify for a project.\n *\n * On first session in a project, checks whether:\n * - `npx codegraph` is available on PATH (or node_modules)\n * - `graphify` / `graphifyy` is available as a Python package\n *\n * If a tool is available but the project has no index yet, runs the\n * initialization automatically. With `--watch` mode, spawns a background\n * process that re-indexes on file changes.\n *\n * Architecture invariants:\n * - Never blocks the session — init runs async, best-effort\n * - Never throws — all errors are silently caught and logged\n * - Tracks session init once per project via an in-memory Set\n */\n\nimport { execSync, spawn } from \"node:child_process\"\nimport { access, stat } from \"node:fs/promises\"\nimport { resolve } from \"node:path\"\nimport { constants } from \"node:fs\"\n\n// ─── GraphSync config ──────────────────────────────────────────────\n\nexport interface GraphSyncConfig {\n /** Enable auto-initialization. Default: true */\n enabled: boolean\n /** Enable watch mode (re-index on file changes). Default: false */\n watch: boolean\n /** Project directory to initialize in. Default: cwd */\n projectDir?: string\n /**\n * Auto-install missing backends. Default: true.\n * - codegraph: installed via `npm i -D @colbymchenry/codegraph` in the project\n * - graphify: installed via `pip install graphifyy --break-system-packages` (or `uv tool install graphifyy`)\n */\n autoInstall: boolean\n /** Max ms to wait for each install. Default: 60_000 */\n installTimeoutMs: number\n}\n\n// ─── Install codes ────────────────────────────────────────────────\n\nexport type InstallCode =\n | \"codegraph-installed\"\n | \"codegraph-install-failed\"\n | \"codegraph-install-skipped\"\n | \"graphify-installed\"\n | \"graphify-install-failed\"\n | \"graphify-install-skipped\"\n\n/**\n * Install codegraph via `npm i -D @colbymchenry/codegraph`.\n * Best-effort, never throws.\n */\nexport async function installCodegraph(\n projectDir: string,\n timeoutMs: number = 60_000,\n): Promise<InstallCode> {\n try {\n execSync(\"npm i -D @colbymchenry/codegraph\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"codegraph-installed\"\n } catch {\n return \"codegraph-install-failed\"\n }\n}\n\n/**\n * Install graphify via `pip install graphifyy --break-system-packages`.\n * Falls back to `uv tool install graphifyy`.\n * Best-effort, never throws.\n */\nexport async function installGraphify(\n timeoutMs: number = 60_000,\n): Promise<InstallCode> {\n try {\n execSync(\"pip install graphifyy --break-system-packages --quiet\", {\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"graphify-installed\"\n } catch {\n try {\n execSync(\"uv tool install graphifyy --quiet\", {\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"graphify-installed\"\n } catch {\n return \"graphify-install-failed\"\n }\n }\n}\n\n// ─── Graph sync state ──────────────────────────────────────────────\n\nconst initializedProjects = new Set<string>()\n\nexport function resetInitializedProjects(): void {\n initializedProjects.clear()\n}\n\n// ─── Tool detection ────────────────────────────────────────────────\n\nexport interface ToolAvailability {\n /** Whether codegraph is available (via npx or node_modules) */\n codegraph: boolean\n /** Whether graphify/graphifyy is available (via pip) */\n graphify: boolean\n /** Whether .codegraph/ directory already exists in the project */\n codegraphIndexExists: boolean\n /** Whether graphify-out/ directory already exists in the project */\n graphifyIndexExists: boolean\n}\n\n/**\n * Check which graph tools are available and whether indexes already exist.\n */\nasync function checkToolAvailability(projectDir: string): Promise<ToolAvailability> {\n let codegraph = false\n let graphify = false\n const codegraphIndexExists = await dirExists(resolve(projectDir, \".codegraph\"))\n const graphifyIndexExists = await dirExists(resolve(projectDir, \"graphify-out\"))\n\n try {\n execSync(\"npx --yes codegraph --version\", {\n stdio: \"ignore\",\n timeout: 10_000,\n })\n codegraph = true\n } catch {\n try {\n execSync(\"node node_modules/.bin/codegraph --version\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 5_000,\n })\n codegraph = true\n } catch {\n // Not available\n }\n }\n\n try {\n execSync(\"python3 -c 'import graphify; print(graphify.__version__)'\", {\n stdio: \"ignore\",\n timeout: 5_000,\n })\n graphify = true\n } catch {\n try {\n execSync(\"python3 -c 'import graphifyy; print(graphifyy.__version__)'\", {\n stdio: \"ignore\",\n timeout: 5_000,\n })\n graphify = true\n } catch {\n // Not available\n }\n }\n\n return { codegraph, graphify, codegraphIndexExists, graphifyIndexExists }\n}\n\n// ─── Initialization ────────────────────────────────────────────────\n\nasync function initCodegraph(projectDir: string): Promise<void> {\n const codegraphDir = resolve(projectDir, \".codegraph\")\n await ensureDir(codegraphDir)\n\n try {\n execSync(\"npx --yes codegraph init\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 60_000,\n })\n } catch {\n // Best-effort\n }\n}\n\nasync function initGraphify(projectDir: string): Promise<void> {\n const graphifyOut = resolve(projectDir, \"graphify-out\")\n await ensureDir(graphifyOut)\n\n try {\n execSync(\"python3 -m graphify . --no-viz\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 120_000,\n })\n } catch {\n try {\n execSync(\"graphifyy . --no-viz\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 120_000,\n })\n } catch {\n // Best-effort\n }\n }\n}\n\n// ─── Watch mode ────────────────────────────────────────────────────\n\ninterface WatchProcess {\n process: ReturnType<typeof spawn>\n tool: \"codegraph\" | \"graphify\"\n}\n\nconst activeWatchProcesses = new Map<string, WatchProcess>()\n\nfunction startWatch(projectDir: string, tool: \"codegraph\" | \"graphify\"): void {\n const key = `${projectDir}:${tool}`\n if (activeWatchProcesses.has(key)) return\n\n try {\n let child: ReturnType<typeof spawn>\n\n if (tool === \"codegraph\") {\n child = spawn(\"npx\", [\"codegraph\", \"watch\"], {\n cwd: projectDir,\n stdio: \"ignore\",\n detached: true,\n })\n } else {\n child = spawn(\"python3\", [\"-m\", \"graphify\", \".\", \"--no-viz\", \"--watch\"], {\n cwd: projectDir,\n stdio: \"ignore\",\n detached: true,\n })\n }\n\n child.unref()\n activeWatchProcesses.set(key, { process: child, tool })\n\n child.on(\"exit\", () => {\n activeWatchProcesses.delete(key)\n })\n } catch {\n // Best-effort\n }\n}\n\n/**\n * Stop all active watch processes for a project.\n */\nexport function stopWatches(projectDir?: string): void {\n for (const [key, wp] of activeWatchProcesses) {\n if (!projectDir || key.startsWith(projectDir)) {\n try {\n wp.process.kill()\n } catch {\n // Already dead\n }\n activeWatchProcesses.delete(key)\n }\n }\n}\n\n// ─── Main API ──────────────────────────────────────────────────────\n\nexport interface GraphSyncResult {\n /** Whether synchronization was attempted */\n attempted: boolean\n /** Codes that describe the outcome */\n codes: GraphSyncCode[]\n /** Tool availability before init */\n availability: ToolAvailability\n /** Whether this project was already initialized this session */\n alreadyInitialized: boolean\n}\n\nexport type GraphSyncCode =\n | \"codegraph-initialized\"\n | \"codegraph-already-exists\"\n | \"codegraph-unavailable\"\n | \"codegraph-install-failed\"\n | \"codegraph-install-skipped\"\n | \"graphify-initialized\"\n | \"graphify-already-exists\"\n | \"graphify-unavailable\"\n | \"graphify-install-failed\"\n | \"graphify-install-skipped\"\n | \"watch-started-codegraph\"\n | \"watch-started-graphify\"\n | \"disabled\"\n | \"error\"\n\n/**\n * Run the graphSync pipeline. Best-effort, never throws.\n */\nexport async function runGraphSync(\n config: GraphSyncConfig = { enabled: true, watch: false, autoInstall: true, installTimeoutMs: 60_000 },\n): Promise<GraphSyncResult> {\n const codes: GraphSyncCode[] = []\n const projectDir = config.projectDir ?? process.cwd()\n\n if (!config.enabled) {\n return {\n attempted: false,\n codes: [\"disabled\"],\n availability: { codegraph: false, graphify: false, codegraphIndexExists: false, graphifyIndexExists: false },\n alreadyInitialized: false,\n }\n }\n\n // Skip if already initialized this session\n if (initializedProjects.has(projectDir)) {\n const avail = await checkToolAvailability(projectDir)\n return {\n attempted: false,\n codes: avail.codegraphIndexExists ? [\"codegraph-already-exists\"] : [],\n availability: avail,\n alreadyInitialized: true,\n }\n }\n\n initializedProjects.add(projectDir)\n\n let availability: ToolAvailability\n try {\n availability = await checkToolAvailability(projectDir)\n } catch {\n return {\n attempted: false,\n codes: [\"error\"],\n availability: { codegraph: false, graphify: false, codegraphIndexExists: false, graphifyIndexExists: false },\n alreadyInitialized: false,\n }\n }\n\n // Auto-install missing backends\n if (config.autoInstall !== false) {\n if (!availability.codegraph) {\n const result = await installCodegraph(projectDir, config.installTimeoutMs ?? 60_000)\n codes.push(result as GraphSyncCode)\n if (result === \"codegraph-installed\") {\n availability.codegraph = true\n }\n }\n if (!availability.graphify) {\n const result = await installGraphify(config.installTimeoutMs ?? 60_000)\n codes.push(result as GraphSyncCode)\n if (result === \"graphify-installed\") {\n availability.graphify = true\n }\n }\n } else {\n if (!availability.codegraph) codes.push(\"codegraph-install-skipped\")\n if (!availability.graphify) codes.push(\"graphify-install-skipped\")\n }\n // Codegraph init\n if (availability.codegraph) {\n if (!availability.codegraphIndexExists) {\n try {\n await initCodegraph(projectDir)\n codes.push(\"codegraph-initialized\")\n } catch {\n codes.push(\"error\")\n }\n } else {\n codes.push(\"codegraph-already-exists\")\n }\n } else {\n codes.push(\"codegraph-unavailable\")\n }\n\n // Graphify init\n if (availability.graphify) {\n if (!availability.graphifyIndexExists) {\n try {\n await initGraphify(projectDir)\n codes.push(\"graphify-initialized\")\n } catch {\n codes.push(\"error\")\n }\n } else {\n codes.push(\"graphify-already-exists\")\n }\n } else {\n codes.push(\"graphify-unavailable\")\n }\n\n // Watch mode\n if (config.watch) {\n if (availability.codegraph) {\n startWatch(projectDir, \"codegraph\")\n codes.push(\"watch-started-codegraph\")\n }\n if (availability.graphify) {\n startWatch(projectDir, \"graphify\")\n codes.push(\"watch-started-graphify\")\n }\n }\n\n return {\n attempted: true,\n codes,\n availability,\n alreadyInitialized: false,\n }\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────\n\nasync function dirExists(dirPath: string): Promise<boolean> {\n try {\n const st = await stat(dirPath)\n return st.isDirectory()\n } catch {\n return false\n }\n}\n\nasync function ensureDir(dirPath: string): Promise<void> {\n try {\n await access(dirPath, constants.F_OK)\n } catch {\n const { mkdir } = await import(\"node:fs/promises\")\n await mkdir(dirPath, { recursive: true })\n }\n}\n",
6
+ "/**\n * graphSync — Auto-initialize codegraph and graphify for a project.\n *\n * On first session in a project, checks whether:\n * - `npx codegraph` is available on PATH (or node_modules)\n * - `graphify` / `graphifyy` is available as a Python package\n *\n * If a tool is available but the project has no index yet, runs the\n * initialization automatically. With `--watch` mode, spawns a background\n * process that re-indexes on file changes.\n *\n * Architecture invariants:\n * - Never blocks the session — init runs async, best-effort\n * - Never throws — all errors are silently caught and logged\n * - Tracks session init once per project via an in-memory Set\n */\n\nimport { execSync, spawn } from \"node:child_process\"\nimport { access, stat } from \"node:fs/promises\"\nimport { resolve } from \"node:path\"\nimport { constants } from \"node:fs\"\n\n// ─── GraphSync config ──────────────────────────────────────────────\n\nexport interface GraphSyncConfig {\n /** Enable auto-initialization. Default: true */\n enabled: boolean\n /** Enable watch mode (re-index on file changes). Default: false */\n watch: boolean\n /** Project directory to initialize in. Default: cwd */\n projectDir?: string\n /**\n * Auto-install missing backends. Default: true.\n * - codegraph: installed via `npm i -D @colbymchenry/codegraph` in the project\n * - graphify: installed via `pip install graphifyy --break-system-packages` (or `uv tool install graphifyy`)\n */\n autoInstall: boolean\n /** Max ms to wait for each install. Default: 60_000 */\n installTimeoutMs: number\n}\n\n// ─── Install codes ────────────────────────────────────────────────\n\nexport type InstallCode =\n | \"codegraph-installed\"\n | \"codegraph-install-failed\"\n | \"codegraph-install-skipped\"\n | \"graphify-installed\"\n | \"graphify-install-failed\"\n | \"graphify-install-skipped\"\n\n/**\n * Install codegraph via `npm i -D @colbymchenry/codegraph`.\n * Best-effort, never throws.\n */\nexport async function installCodegraph(\n projectDir: string,\n timeoutMs: number = 60_000,\n): Promise<InstallCode> {\n try {\n execSync(\"npm i -D @colbymchenry/codegraph\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"codegraph-installed\"\n } catch {\n return \"codegraph-install-failed\"\n }\n}\n\n/**\n * Install graphify via `pip install graphifyy --break-system-packages`.\n * Falls back to `uv tool install graphifyy`.\n * Best-effort, never throws.\n */\nexport async function installGraphify(\n timeoutMs: number = 60_000,\n): Promise<InstallCode> {\n try {\n execSync(\"pip install graphifyy --break-system-packages --quiet\", {\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"graphify-installed\"\n } catch {\n try {\n execSync(\"uv tool install graphifyy --quiet\", {\n stdio: \"ignore\",\n timeout: timeoutMs,\n })\n return \"graphify-installed\"\n } catch {\n return \"graphify-install-failed\"\n }\n }\n}\n\n// ─── Graph sync state ──────────────────────────────────────────────\n\nconst initializedProjects = new Set<string>()\n\nexport function resetInitializedProjects(): void {\n initializedProjects.clear()\n}\n\n// ─── Session tracking (for watch lifecycle) ────────────────────────\n\nconst sessionCounts = new Map<string, number>()\n\n/**\n * Track a new session for a project. Increments reference count.\n * Returns the new count.\n */\nexport function trackSession(projectDir: string): number {\n const current = sessionCounts.get(projectDir) ?? 0\n const next = current + 1\n sessionCounts.set(projectDir, next)\n return next\n}\n\n/**\n * Untrack a session for a project. Decrements reference count.\n * When count drops to 0, all watch processes for that project\n * are automatically stopped.\n * Returns the remaining count.\n */\nexport function untrackSession(projectDir: string): number {\n const current = sessionCounts.get(projectDir) ?? 0\n const next = Math.max(0, current - 1)\n if (next === 0) {\n sessionCounts.delete(projectDir)\n // Auto-cleanup watches when last session exits\n stopWatches(projectDir)\n } else {\n sessionCounts.set(projectDir, next)\n }\n return next\n}\n\n/** Get active session count for a project. */\nexport function getSessionCount(projectDir: string): number {\n return sessionCounts.get(projectDir) ?? 0\n}\n\n// ─── Tool detection ────────────────────────────────────────────────\n\nexport interface ToolAvailability {\n /** Whether codegraph is available (via npx or node_modules) */\n codegraph: boolean\n /** Whether graphify/graphifyy is available (via pip) */\n graphify: boolean\n /** Whether .codegraph/ directory already exists in the project */\n codegraphIndexExists: boolean\n /** Whether graphify-out/ directory already exists in the project */\n graphifyIndexExists: boolean\n}\n\n/**\n * Check which graph tools are available and whether indexes already exist.\n */\nasync function checkToolAvailability(projectDir: string): Promise<ToolAvailability> {\n let codegraph = false\n let graphify = false\n const codegraphIndexExists = await dirExists(resolve(projectDir, \".codegraph\"))\n const graphifyIndexExists = await dirExists(resolve(projectDir, \"graphify-out\"))\n\n try {\n execSync(\"npx --yes codegraph --version\", {\n stdio: \"ignore\",\n timeout: 10_000,\n })\n codegraph = true\n } catch {\n try {\n execSync(\"node node_modules/.bin/codegraph --version\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 5_000,\n })\n codegraph = true\n } catch {\n // Not available\n }\n }\n\n try {\n execSync(\"python3 -c 'import graphify; print(graphify.__version__)'\", {\n stdio: \"ignore\",\n timeout: 5_000,\n })\n graphify = true\n } catch {\n try {\n execSync(\"python3 -c 'import graphifyy; print(graphifyy.__version__)'\", {\n stdio: \"ignore\",\n timeout: 5_000,\n })\n graphify = true\n } catch {\n // Not available\n }\n }\n\n return { codegraph, graphify, codegraphIndexExists, graphifyIndexExists }\n}\n\n// ─── Initialization ────────────────────────────────────────────────\n\nasync function initCodegraph(projectDir: string): Promise<void> {\n const codegraphDir = resolve(projectDir, \".codegraph\")\n await ensureDir(codegraphDir)\n\n try {\n execSync(\"npx --yes codegraph init\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 60_000,\n })\n } catch {\n // Best-effort\n }\n}\n\nasync function initGraphify(projectDir: string): Promise<void> {\n const graphifyOut = resolve(projectDir, \"graphify-out\")\n await ensureDir(graphifyOut)\n\n try {\n execSync(\"python3 -m graphify . --no-viz\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 120_000,\n })\n } catch {\n try {\n execSync(\"graphifyy . --no-viz\", {\n cwd: projectDir,\n stdio: \"ignore\",\n timeout: 120_000,\n })\n } catch {\n // Best-effort\n }\n }\n}\n\n// ─── Watch mode ────────────────────────────────────────────────────\n\ninterface WatchProcess {\n process: ReturnType<typeof spawn>\n tool: \"codegraph\" | \"graphify\"\n}\n\nconst activeWatchProcesses = new Map<string, WatchProcess>()\n\nfunction startWatch(projectDir: string, tool: \"codegraph\" | \"graphify\"): void {\n const key = `${projectDir}:${tool}`\n if (activeWatchProcesses.has(key)) return\n\n try {\n let child: ReturnType<typeof spawn>\n\n if (tool === \"codegraph\") {\n // codegraph has no built-in watch; use periodic update loop\n child = spawn(\n \"node\",\n [\n \"-e\",\n `\n const {execSync} = require(\"child_process\");\n const run = () => {\n try { execSync(\"npx codegraph update 2>/dev/null\", {cwd: ${JSON.stringify(projectDir)}, stdio: \"ignore\"}); }\n catch(e) { /* best effort */ }\n };\n run();\n setInterval(run, 30_000);\n `,\n ],\n {\n stdio: \"ignore\",\n detached: true,\n },\n )\n } else {\n child = spawn(\"python3\", [\"-m\", \"graphify\", \".\", \"--no-viz\", \"--watch\"], {\n cwd: projectDir,\n stdio: \"ignore\",\n detached: true,\n })\n }\n\n child.unref()\n activeWatchProcesses.set(key, { process: child, tool })\n\n child.on(\"exit\", () => {\n activeWatchProcesses.delete(key)\n })\n } catch {\n // Best-effort\n }\n}\n\n/**\n * Stop all active watch processes for a project.\n */\nexport function stopWatches(projectDir?: string): void {\n for (const [key, wp] of activeWatchProcesses) {\n if (!projectDir || key.startsWith(projectDir)) {\n try {\n wp.process.kill(\"SIGTERM\")\n } catch {\n // Already dead\n }\n setTimeout(() => {\n try { wp.process.kill(\"SIGKILL\") } catch { /* OK */ }\n }, 2_000).unref()\n activeWatchProcesses.delete(key)\n }\n }\n}\n\n/** Check if watches are active for a project. */\nexport function hasActiveWatcher(projectDir: string, tool?: \"codegraph\" | \"graphify\"): boolean {\n for (const key of activeWatchProcesses.keys()) {\n if (key.startsWith(projectDir)) {\n if (!tool || key.endsWith(tool)) return true\n }\n }\n return false\n}\n\n// ─── Main API ──────────────────────────────────────────────────────\n\nexport interface GraphSyncResult {\n /** Whether synchronization was attempted */\n attempted: boolean\n /** Codes that describe the outcome */\n codes: GraphSyncCode[]\n /** Tool availability before init */\n availability: ToolAvailability\n /** Whether this project was already initialized this session */\n alreadyInitialized: boolean\n}\n\nexport type GraphSyncCode =\n | \"codegraph-initialized\"\n | \"codegraph-already-exists\"\n | \"codegraph-unavailable\"\n | \"codegraph-install-failed\"\n | \"codegraph-install-skipped\"\n | \"graphify-initialized\"\n | \"graphify-already-exists\"\n | \"graphify-unavailable\"\n | \"graphify-install-failed\"\n | \"graphify-install-skipped\"\n | \"watch-started-codegraph\"\n | \"watch-started-graphify\"\n | \"disabled\"\n | \"error\"\n\n/**\n * Run the graphSync pipeline. Best-effort, never throws.\n */\nexport async function runGraphSync(\n config: GraphSyncConfig = { enabled: true, watch: false, autoInstall: true, installTimeoutMs: 60_000 },\n): Promise<GraphSyncResult> {\n const codes: GraphSyncCode[] = []\n const projectDir = config.projectDir ?? process.cwd()\n\n if (!config.enabled) {\n return {\n attempted: false,\n codes: [\"disabled\"],\n availability: { codegraph: false, graphify: false, codegraphIndexExists: false, graphifyIndexExists: false },\n alreadyInitialized: false,\n }\n }\n\n // Skip if already initialized this session\n if (initializedProjects.has(projectDir)) {\n const avail = await checkToolAvailability(projectDir)\n return {\n attempted: false,\n codes: avail.codegraphIndexExists ? [\"codegraph-already-exists\"] : [],\n availability: avail,\n alreadyInitialized: true,\n }\n }\n\n initializedProjects.add(projectDir)\n\n let availability: ToolAvailability\n try {\n availability = await checkToolAvailability(projectDir)\n } catch {\n return {\n attempted: false,\n codes: [\"error\"],\n availability: { codegraph: false, graphify: false, codegraphIndexExists: false, graphifyIndexExists: false },\n alreadyInitialized: false,\n }\n }\n\n // Auto-install missing backends\n if (config.autoInstall !== false) {\n if (!availability.codegraph) {\n const result = await installCodegraph(projectDir, config.installTimeoutMs ?? 60_000)\n codes.push(result as GraphSyncCode)\n if (result === \"codegraph-installed\") {\n availability.codegraph = true\n }\n }\n if (!availability.graphify) {\n const result = await installGraphify(config.installTimeoutMs ?? 60_000)\n codes.push(result as GraphSyncCode)\n if (result === \"graphify-installed\") {\n availability.graphify = true\n }\n }\n } else {\n if (!availability.codegraph) codes.push(\"codegraph-install-skipped\")\n if (!availability.graphify) codes.push(\"graphify-install-skipped\")\n }\n\n // Codegraph init\n if (availability.codegraph) {\n if (!availability.codegraphIndexExists) {\n try {\n await initCodegraph(projectDir)\n codes.push(\"codegraph-initialized\")\n } catch {\n codes.push(\"error\")\n }\n } else {\n codes.push(\"codegraph-already-exists\")\n }\n } else {\n codes.push(\"codegraph-unavailable\")\n }\n\n // Graphify init\n if (availability.graphify) {\n if (!availability.graphifyIndexExists) {\n try {\n await initGraphify(projectDir)\n codes.push(\"graphify-initialized\")\n } catch {\n codes.push(\"error\")\n }\n } else {\n codes.push(\"graphify-already-exists\")\n }\n } else {\n codes.push(\"graphify-unavailable\")\n }\n\n // Watch mode\n if (config.watch) {\n if (availability.codegraph) {\n startWatch(projectDir, \"codegraph\")\n codes.push(\"watch-started-codegraph\")\n }\n if (availability.graphify) {\n startWatch(projectDir, \"graphify\")\n codes.push(\"watch-started-graphify\")\n }\n }\n\n return {\n attempted: true,\n codes,\n availability,\n alreadyInitialized: false,\n }\n}\n\n// ─── Helpers ───────────────────────────────────────────────────────\n\nasync function dirExists(dirPath: string): Promise<boolean> {\n try {\n const st = await stat(dirPath)\n return st.isDirectory()\n } catch {\n return false\n }\n}\n\nasync function ensureDir(dirPath: string): Promise<void> {\n try {\n await access(dirPath, constants.F_OK)\n } catch {\n const { mkdir } = await import(\"node:fs/promises\")\n await mkdir(dirPath, { recursive: true })\n }\n}\n",
7
7
  "/**\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",
8
8
  "/**\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",
9
9
  "/**\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",
@@ -12,13 +12,14 @@
12
12
  "/**\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",
13
13
  "import type { InterventionConfig, ModelOverrideConfig, OrchestratorConfig, ProtocolEnforcementConfig } from \"./types\"\nimport { defaultScoringConfig } from \"./scoring-engine\"\nimport { defaultDecisionHandlerConfig } from \"./decision-handler\"\nimport { defaultClosedLoopConfig } from \"./closed-loop-learning\"\nimport type { ConfigFileSources, ConfigFileResult } from \"./config-file\"\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 /** Graph sync config for auto-initializing codegraph/graphify. */\ngraphSync?: {\nenabled?: boolean\n watch?: boolean\n autoInstall?: boolean\n installTimeoutMs?: number\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\n/**\n * Load orchestrator config from all available sources: config file (JSONC)\n * with priority: CLI inline > project config > user config > defaults.\n */\nexport async function loadOrchestratorConfigFromSources(\n sources: ConfigFileSources = {},\n): Promise<OrchestratorConfig> {\n const { loadMetaGovernorConfig } = await import(\"./config-file\")\n const result: ConfigFileResult = await loadMetaGovernorConfig(sources)\n return loadOrchestratorConfig(result.config)\n}\n",
14
14
  "/**\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",
15
- "/**\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",
16
- "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 { runGraphSync, type GraphSyncConfig } from \"./graph-sync\"\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 // 2a. Run graphSync (best-effort, non-blocking)\nconst graphSyncCfg: GraphSyncConfig = {\nenabled: rawConfig?.graphSync?.enabled ?? true,\n watch: rawConfig?.graphSync?.watch ?? false,\n autoInstall: rawConfig?.graphSync?.autoInstall ?? true,\n installTimeoutMs: rawConfig?.graphSync?.installTimeoutMs ?? 60_000,\n}\n runGraphSync(graphSyncCfg).catch(() => {})\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",
15
+ "import { appendFileSync, mkdirSync } from \"node:fs\"\nimport { resolve, dirname } from \"node:path\"\nimport { homedir } from \"node:os\"\n\n/**\n * Persistent file-based logger so the user can tail the plugin's activity.\n * Logs to ~/.config/opencode/meta-governor.log with rotation hints.\n */\nconst LOG_PATH = resolve(homedir(), \".config\", \"opencode\", \"meta-governor.log\")\n\nfunction ensureLogDir(): void {\n try {\n mkdirSync(dirname(LOG_PATH), { recursive: true })\n } catch {\n // ignore\n }\n}\n\nexport function logToFile(level: \"info\" | \"warn\" | \"error\", message: string, data?: unknown): void {\n ensureLogDir()\n const ts = new Date().toISOString()\n const dataStr = data !== undefined ? ` | ${JSON.stringify(data)}` : \"\"\n const line = `[${ts}] [${level.toUpperCase()}] ${message}${dataStr}\\n`\n try {\n appendFileSync(LOG_PATH, line)\n } catch {\n // ignore\n }\n // Also emit to console so journald captures it\n if (level === \"error\") {\n console.error(`[meta-governor] ${message}`)\n } else if (level === \"warn\") {\n console.warn(`[meta-governor] ${message}`)\n } else {\n console.log(`[meta-governor] ${message}`)\n }\n}\n",
16
+ "/**\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>\n * - buildSystemInjection(protocolText): string\n * - auditToolCall(toolName, args, context): ProtocolViolation[]\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\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\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 \" - Working note for THIS session only → `ctx_note`\",\n \" - Save durable insight/decision/rule → `ctx_memory`\",\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 \" - Do NOT suppress type errors with `as any`, `@ts-ignore`, or `@ts-expect-error`.\",\n \" - Do NOT leave empty catch blocks `catch(e) {}`.\",\n \" - Do NOT start a fresh agent via `task()` when `task(task_id=\\\"ses_...\\\")` (continuation) exists — use continuation IDs.\",\n \" - Do NOT batch-complete todos — mark each one `completed` immediately after finishing.\",\n \" - Do NOT skip creating todos for multi-step tasks.\",\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 \" - After discovering something non-obvious, save it with `ctx_memory` so future sessions benefit.\",\n \"\",\n )\n\n return lines.join(\"\\n\")\n}\n\n// ─── Audit context ────────────────────────────────────────────────\n\nexport interface AuditContext {\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/** Whether AFT tools (aft_zoom, aft_outline) are available */\n aftAvailable?: boolean\n/** Whether AFT tools have been used in this session */\n aftUsed?: boolean\n/** Tool names called in this session so far (latest first) */\n recentToolCalls?: readonly string[]\n/** File write/edit contents (last 3 for pattern detection) */\n recentWriteContents?: readonly string[]\n/** Whether ctx_memory save has been used to persist discoveries */\n memorySaved?: boolean\n/** Number of times todo was batch-completed in this session */\n batchCompletions?: number\n}\n\n// ─── auditToolCall ────────────────────────────────────────────────\n\nexport function auditToolCall(\n toolName: string,\n args: unknown,\n context: AuditContext,\n): ProtocolViolation[] {\n const violations: ProtocolViolation[] = []\n const recentToolCalls = context.recentToolCalls ?? []\n const aftAvailable = context.aftAvailable ?? false\n const aftUsed = context.aftUsed ?? false\n const recentWriteContents = context.recentWriteContents ?? []\n const memorySaved = context.memorySaved ?? false\n const batchCompletions = context.batchCompletions ?? 0\n // ── Rule 0.5: Codebase Graph First ──────────────────────────────\n // grep/glob/read for architecture/symbol queries should use codegraph/graphify/AFT 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: AFT First (before grep/read for structure queries) ──\n if (\n (toolName === \"read\" || toolName === \"grep\") &&\n aftAvailable &&\n !aftUsed\n ) {\n violations.push({\n rule: \"aft-first\",\n tool: toolName,\n severity: \"media\",\n detail:\n `AFT tools (aft_outline, aft_zoom) are available but were not tried before using ${toolName}. ` +\n \"Use aft_outline for structure discovery, aft_zoom for symbol source, before falling back to grep/read.\",\n })\n }\n\n // ── Rule: grep used when aft_outline would answer structure ─────\n if (toolName === \"grep\" && aftAvailable && !aftUsed && !context.hasCodegraphDir && !context.hasGraphifyDir) {\n violations.push({\n rule: \"grep-without-aft\",\n tool: toolName,\n severity: \"leve\",\n detail:\n \"Used grep before checking if aft_outline would answer the structure question. grep is a last resort after graph tools and AFT.\",\n })\n }\n\n // ── Rule: Continuation ID discipline ────────────────────────────\n // Starting fresh with task() instead of continuing via task(task_id=\"ses_...\")\n if (toolName === \"task\" && args && typeof args === \"object\") {\n const taskArgs = args as Record<string, unknown>\n // If task() has no task_id but has a prompt that resembles a follow-up\n if (!taskArgs.task_id && typeof taskArgs.prompt === \"string\" && recentToolCalls.length > 3) {\n // Heuristic: if we have more than 3 tool calls in this session and the agent\n // is starting a new task without continuation ID, flag it\n violations.push({\n rule: \"continuation-discipline\",\n tool: toolName,\n severity: \"leve\",\n detail:\n \"Started a new task() without task(task_id=\\\"ses_...\\\") continuation ID. \" +\n \"Use task_id to preserve the subagent's full context and save tokens.\",\n })\n }\n }\n\n // ── Rule: No type suppression patterns ─────────────────────────\n const writeTools = [\"write\", \"edit\", \"edit_block\", \"desktop-commander_edit_block\", \"desktop-commander_write_file\"]\n if (writeTools.includes(toolName)) {\n const content = typeof args === \"object\" && args !== null\n ? JSON.stringify(args)\n : String(args ?? \"\")\n\n const tsIgnore = /@ts-ignore|@ts-expect-error/.test(content)\n const anyCast = /\\bas any\\b/.test(content)\n\n if (tsIgnore && anyCast) {\n violations.push({\n rule: \"no-type-suppression\",\n tool: toolName,\n severity: \"grave\",\n detail:\n `File write contains both @ts-ignore/@ts-expect-error AND 'as any' — double type suppression. ` +\n `Both are forbidden by the Sisyphus protocol.`,\n })\n } else if (tsIgnore) {\n violations.push({\n rule: \"no-type-suppression\",\n tool: toolName,\n severity: \"media\",\n detail:\n `File write contains @ts-ignore or @ts-expect-error — both are forbidden. ` +\n `Fix the underlying type error instead.`,\n })\n } else if (anyCast) {\n violations.push({\n rule: \"no-type-suppression\",\n tool: toolName,\n severity: \"media\",\n detail:\n `File write contains 'as any' — type suppression forbidden. ` +\n `Use proper type narrowing instead.`,\n })\n }\n }\n\n // ── Rule: No empty catch blocks ────────────────────────────────\n if (writeTools.includes(toolName)) {\n const content = typeof args === \"object\" && args !== null\n ? JSON.stringify(args)\n : String(args ?? \"\")\n\n if (/catch\\s*\\(\\s*\\w+\\s*\\)\\s*\\{\\s*\\}/.test(content)) {\n violations.push({\n rule: \"no-empty-catch\",\n tool: toolName,\n severity: \"media\",\n detail:\n \"Empty catch block detected — `catch(e) {}` is forbidden. \" +\n \"Log the error or handle it gracefully.\",\n })\n }\n }\n\n // ── Rule: Memory discovery not saved ────────────────────────────\n // After reading/searching files, if ctx_memory wasn't used to save discoveries\n const discoveryTools = [\"grep\", \"glob\", \"read\", \"aft_zoom\", \"aft_outline\", \"codegraph_explore\", \"graphify query\"]\n if (discoveryTools.includes(toolName) && recentToolCalls.length >= 2) {\n // Check the last few tools for ctx_memory usage\n const lastFew = recentToolCalls.slice(0, 5)\n if (!lastFew.some((t) => t.startsWith(\"ctx_memory\")) && !memorySaved) {\n violations.push({\n rule: \"save-discovery-to-memory\",\n tool: toolName,\n severity: \"leve\",\n detail:\n `Used ${toolName} to discover code but ctx_memory was not used afterwards. ` +\n \"Save non-obvious findings with ctx_memory so future sessions benefit.\",\n })\n }\n }\n\n // ── Rule: Batch todo completion ─────────────────────────────────\n // Detected by caller passing batchCompletions info\n // The orchestrator/provider sets batchCompletions based on its own monitoring\n if (batchCompletions > 0 && toolName !== \"todowrite\") {\n violations.push({\n rule: \"no-batch-todo-completion\",\n tool: toolName,\n severity: \"leve\",\n detail:\n \"Batch todo completion detected. Each todo must be marked `completed` immediately \" +\n \"after finishing — do not batch-complete multiple items.\",\n })\n }\n\n // ── Rule: Session continuity (ctx_reduce discipline) ────────────\n if (toolName === \"ctx_reduce\" && args && typeof args === \"object\") {\n const dropArg = (args as Record<string, unknown>).drop\n if (typeof dropArg === \"string\" && /^\\d+-\\d+$/i.test(dropArg.trim())) {\n const [startStr, endStr] = dropArg.trim().split(\"-\").map(Number)\n if (!isNaN(startStr) && !isNaN(endStr) && (endStr - startStr) > 10) {\n violations.push({\n rule: \"ctx-reduce-discipline\",\n tool: toolName,\n severity: \"leve\",\n detail:\n `Dropped a large range (${dropArg}) with ctx_reduce. The protocol requires reviewing each tag before dropping. ` +\n `Use smaller targeted drops instead of blanket ranges.`,\n })\n }\n }\n }\n\n // ── Rule: Step 3: Empty-result escalation ───────────────────────\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 \" +\n \"before asking the user. Steps 1-3 of empty-result escalation protocol are mandatory.\",\n })\n }\n }\n\n // ── Rule: Memory first before asking questions ──────────────────\n const memoryToolPatterns = [\n \"agentmemory_memory_recall\", \"agentmemory_memory_smart_search\",\n \"agentmemory_memory_save\", \"ctx_memory\", \"ctx_search\", \"ctx_note\",\n ]\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). \" +\n \"Must fire agentmemory_memory_recall or ctx_memory before asking the user.\",\n })\n }\n\n // ── Oracle rule: after multi-file changes ───────────────────────\n if (context.filesChanged >= 3 && !context.oracleInvoked) {\n if (\n toolName !== \"task\" ||\n !args || typeof args !== \"object\" ||\n !(\"subagent_type\" in (args as Record<string, unknown>))\n ) {\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. ` +\n \"The POST-TASK ORACLE VERIFICATION protocol requires Oracle invocation on multi-file changes.\",\n })\n }\n }\n\n return violations\n}\n",
17
+ "import type { Hooks, Plugin, PluginInput, PluginOptions } from \"@opencode-ai/plugin\"\nimport type {\n AgentmemoryWriteBackend,\n DecisionHandlerOutput,\n MemoryBackends,\n MetaGovernorInput,\n} from \"./types\"\nimport { runGraphSync, trackSession, untrackSession } from \"./graph-sync\"\nimport { runMetaGovernor } from \"./orchestrator\"\nimport { loadOrchestratorConfig, type MetaGovernorPluginConfig } from \"./config\"\nimport { storeDecision, takeAnyDecision, takeDecision } from \"./decision-store\"\nimport { logToFile } from \"./file-logger\"\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?: MemoryBackends\n writeBackend?: AgentmemoryWriteBackend\n providerID?: () => string | undefined\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\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\nexport function createMetaGovernorPlugin(\n config: MetaGovernorPluginConfig = {},\n deps: MetaGovernorPluginDeps = {},\n): Plugin {\n // Initialise graphSync when the module loads (before any session)\n const graphSyncEnabled = config.graphSync?.enabled !== false\n if (graphSyncEnabled) {\n const cwd = process.cwd()\n runGraphSync({\n enabled: true,\n watch: config.graphSync?.watch ?? false,\n autoInstall: config.graphSync?.autoInstall ?? true,\n installTimeoutMs: config.graphSync?.installTimeoutMs ?? 60_000,\n projectDir: cwd,\n }).catch(() => {})\n trackSession(cwd)\n }\n\n const plugin: Plugin = async (\n _input: PluginInput,\n options?: PluginOptions,\n ): Promise<Hooks> => {\n // 1. Load config from plugin options\n const rawConfig = {\n ...config,\n ...((options?.meta_governor as MetaGovernorPluginConfig) ?? {}),\n }\n const mergedConfig = loadOrchestratorConfig(rawConfig)\n\n // 2. If disabled, return empty hooks\n if (!mergedConfig.enabled) {\n return {}\n }\n\n // 3. Resolve model settings from override or session\n const getProviderID = (): string | undefined =>\n mergedConfig.modelOverride?.providerID ?? deps.providerID?.()\n const getModelID = (): string | undefined =>\n mergedConfig.modelOverride?.modelID ?? deps.modelID?.()\n const getModelLimit = (): number =>\n mergedConfig.modelOverride?.modelLimit ?? 200_000\n\n const providerID = getProviderID() ?? \"unknown\"\n const modelID = getModelID() ?? \"unknown\"\n\n // 4. Load protocol text (best-effort, cached once)\n let systemInjection: string | undefined\n if (mergedConfig.protocolEnforcement.enabled || mergedConfig.protocolEnforcement.injectIntoSystem) {\n const protocolPath = mergedConfig.protocolEnforcement.path ?? DEFAULT_PROTOCOL_PATH\n loadProtocol(protocolPath).then((text) => {\n systemInjection = buildSystemInjection(text)\n }).catch((err) => {\n if (typeof console !== \"undefined\" && mergedConfig.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\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 aftAvailable: boolean\n aftUsed: boolean\n recentToolCalls: string[]\n recentWriteContents: string[]\n memorySaved: boolean\n batchCompletions: number\n }\n const auditSessions = new Map<string, AuditState>()\n\n // Pending protocol violations queue: key=sessionID, value=violations to surface to the model\n const pendingViolations = new Map<string, string[]>()\n return {\n // - Tool execute before (protocol audit)\n \"tool.execute.before\": async (\n toolInput: { tool: string; sessionID: string; callID: string },\n ): Promise<void> => {\n if (!mergedConfig.enabled) return\n if (!mergedConfig.protocolEnforcement.auditToolCalls) return\n if (!toolInput.sessionID) return\n\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 aftAvailable: false,\n aftUsed: false,\n recentToolCalls: [],\n recentWriteContents: [],\n memorySaved: false,\n batchCompletions: 0,\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 const violations = auditToolCall(toolInput.tool, {}, {\n memoryToolsUsed: state.memoryToolsUsed,\n hasCodegraphDir: state.hasCodegraphDir,\n hasGraphifyDir: state.hasGraphifyDir,\n oracleInvoked: state.oracleInvoked,\n filesChanged: state.filesChanged,\n emptyRecall: state.emptyRecall,\n escalationAttempted: state.escalationAttempted,\n aftAvailable: state.aftAvailable,\n aftUsed: state.aftUsed,\n recentToolCalls: state.recentToolCalls,\n recentWriteContents: state.recentWriteContents,\n memorySaved: state.memorySaved,\n batchCompletions: state.batchCompletions,\n })\n\n if (violations.length > 0) {\n // Log to file + console for visibility\n logToFile(\"warn\", `protocol violations on tool ${toolInput.tool}`, violations)\n // Queue violations so the next messages.transform surfaces them to the model\n const existing = pendingViolations.get(toolInput.sessionID) ?? []\n for (const v of violations) {\n existing.push(`[${v.severity.toUpperCase()}] ${v.rule}: ${v.detail}`)\n }\n pendingViolations.set(toolInput.sessionID, existing)\n } else {\n logToFile(\"info\", `audit OK on tool ${toolInput.tool}`)\n }\n },\n\n // - Tool execute after (orchestrator + audit state update)\n // - Tool execute after (orchestrator + audit state update)\n \"tool.execute.after\": async (\n toolInput: { tool: string; sessionID: string; callID: string; args: unknown },\n toolOutput: { title: string; output: string; metadata: unknown },\n ): Promise<void> => {\n if (!mergedConfig.enabled) return\n\n const sessionState = auditSessions.get(toolInput.sessionID)\n if (sessionState) {\n sessionState.recentToolCalls = [toolInput.tool].concat(\n sessionState.recentToolCalls,\n ).slice(0, 20)\n\n const writeTools = [\n \"write\", \"edit\", \"edit_block\",\n \"desktop-commander_write_file\", \"desktop-commander_edit_block\",\n ]\n if (writeTools.includes(toolInput.tool)) {\n sessionState.filesChanged++\n const content = (toolOutput.output ?? \"\").slice(0, 500)\n sessionState.recentWriteContents = [content].concat(\n sessionState.recentWriteContents,\n ).slice(0, 3)\n }\n\n const memoryTools = [\n \"agentmemory_memory_recall\", \"agentmemory_memory_smart_search\",\n \"agentmemory_memory_save\", \"ctx_memory\", \"ctx_search\", \"ctx_note\",\n ]\n const isMemoryTool = memoryTools.some((m) => toolInput.tool.startsWith(m))\n if (isMemoryTool && !sessionState.memoryToolsUsed.includes(toolInput.tool)) {\n sessionState.memoryToolsUsed.push(toolInput.tool)\n }\n\n if (toolInput.tool.startsWith(\"ctx_memory\")) {\n const out = toolOutput.output ?? \"\"\n if (out.includes(\"saved\") || out.includes(\"written\")) {\n sessionState.memorySaved = true\n }\n }\n\n if (toolInput.tool.startsWith(\"aft_zoom\") || toolInput.tool.startsWith(\"aft_outline\")) {\n sessionState.aftUsed = true\n }\n\n if (toolInput.tool === \"task\" && (toolOutput.output ?? \"\").includes(\"subagent_type=oracle\")) {\n sessionState.oracleInvoked = true\n }\n\n const outLower = (toolOutput.output ?? \"\").toLowerCase()\n if (toolInput.tool.includes(\"recall\") && (outLower.includes(\"returned empty\") || outLower.includes(\"no results\"))) {\n sessionState.emptyRecall = true\n }\n\n if (toolInput.tool === \"todowrite\" && (toolOutput.output ?? \"\").includes(\"completed\")) {\n const matches = (toolOutput.output ?? \"\").match(/\"status\":\"completed\"/g) ?? []\n if (matches.length >= 3) {\n sessionState.batchCompletions++\n }\n }\n }\n\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: { smartSearch: async () => ({ lessons: [], crystals: [] }) },\n magicContext: { slotList: async () => [] },\n boulderState: { boulderRead: async () => [] },\n },\n writeBackend: deps.writeBackend ?? {\n saveMemory: async () => ({ id: \"\" }),\n saveLesson: async () => ({ id: \"\" }),\n },\n config: mergedConfig,\n ...(getProviderID() ? { providerID: getProviderID() } : {}),\n ...(getModelID() ? { modelID: getModelID() } : {}),\n modelLimit: getModelLimit(),\n }\n\n try {\n const output = await runMetaGovernor(orchestratorInput)\n\n if (mergedConfig.intervention.mode !== \"silent\") {\n const decision = output.decision\n if (\n decision.action !== \"continue\" &&\n meetsMinAction(decision.action, mergedConfig.intervention.minActionForMessage)\n ) {\n storeDecision(toolInput.sessionID, decision)\n }\n }\n } catch {\n // MetaGovernor must NEVER break a tool call\n }\n },\n\n // - Messages transform (injects decisions + protocol violations as synthetic user messages)\n \"experimental.chat.messages.transform\": async (\n _input: {},\n output: { messages: Array<{ info: unknown; parts: unknown[] }> },\n ): Promise<void> => {\n if (!mergedConfig.enabled) return\n if (mergedConfig.intervention.mode !== \"message\") return\n\n // 1. Inject pending protocol violations so the model sees them\n const lastMsg = output.messages[output.messages.length - 1] as { info?: { sessionID?: string } } | undefined\n const violationSessionID = lastMsg?.info?.sessionID\n if (violationSessionID && pendingViolations.has(violationSessionID)) {\n const violations = pendingViolations.get(violationSessionID)!\n if (violations.length > 0) {\n const violationText = `[META-GOVERNOR PROTOCOL VIOLATIONS - YOU MUST COMPLY]\\n\\n${violations.map((v, i) => `${i + 1}. ${v}`).join(\"\\n\")}\\n\\nRemember: use codegraph/graphify for architecture queries, do not grep without trying AFT/codegraph first, no @ts-ignore/as-any, no empty catch, check memory before asking.`\n output.messages.push({\n info: { role: \"user\", agent: \"meta-governor\", synthetic: true },\n parts: [{ type: \"text\", text: violationText, synthetic: true }],\n })\n pendingViolations.delete(violationSessionID)\n logToFile(\"info\", `injected ${violations.length} violation(s) to model`)\n }\n }\n\n // 2. Inject MetaGovernor decision\n const decision = takeAnyDecision()\n if (!decision) return\n if (decision.action === \"continue\") return\n if (!decision.message) return\n if (!meetsMinAction(decision.action, mergedConfig.intervention.minActionForMessage)) return\n\n const textPart = {\n type: \"text\",\n text: `[MetaGovernor] ${decision.message}`,\n synthetic: true,\n }\n\n output.messages.push({\n info: { role: \"user\", agent: \"meta-governor\" },\n parts: [textPart],\n })\n },\n \"experimental.chat.system.transform\": async (\n transformInput: { sessionID?: string; model: unknown },\n output: { system: string[] },\n ): Promise<void> => {\n if (!mergedConfig.enabled) return\n\n if (mergedConfig.protocolEnforcement.injectIntoSystem && systemInjection) {\n output.system.push(\n \"\\n### Sisyphus Protocol Enforcement\",\n systemInjection,\n \"---\",\n )\n }\n\n if (mergedConfig.intervention.mode === \"system\" && transformInput.sessionID) {\n const decision = takeDecision(transformInput.sessionID)\n if (decision && decision.action !== \"continue\" && decision.message) {\n if (meetsMinAction(decision.action, mergedConfig.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",
17
18
  "/**\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",
18
- "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\"\n\n// Config-file loader + graphSync + schema generator\nexport {\n stripJsoncComments,\n parseJsonc,\n loadJsoncFile,\n deepMerge,\n loadMetaGovernorConfig,\n getUserConfigPath,\n getProjectConfigPath,\n type ConfigFileSources,\n type ConfigFileResult,\n} from \"./config-file\"\nexport {\n runGraphSync,\n stopWatches,\n resetInitializedProjects,\n type GraphSyncConfig,\n type GraphSyncResult,\n type GraphSyncCode,\n type ToolAvailability,\n} from \"./graph-sync\"\nexport { generateSchema, writeSchemaFile, type JsonSchema, type JsonSchemaProperty } from \"./generate-schema\"\nexport { loadOrchestratorConfigFromSources } from \"./config\"\n\nexport type { ProtocolViolation, ProtocolEnforcementSessionState } from \"./types\"\n",
19
+ "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 { createMetaGovernorPlugin, type MetaGovernorPluginDeps } from \"./plugin\"\nexport { logToFile } from \"./file-logger\"\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\"\n\n// Config-file loader + graphSync + schema generator\nexport {\n stripJsoncComments,\n parseJsonc,\n loadJsoncFile,\n deepMerge,\n loadMetaGovernorConfig,\n getUserConfigPath,\n getProjectConfigPath,\n type ConfigFileSources,\n type ConfigFileResult,\n} from \"./config-file\"\nexport {\n runGraphSync,\n stopWatches,\n resetInitializedProjects,\n type GraphSyncConfig,\n type GraphSyncResult,\n type GraphSyncCode,\n type ToolAvailability,\n} from \"./graph-sync\"\nexport { generateSchema, writeSchemaFile, type JsonSchema, type JsonSchemaProperty } from \"./generate-schema\"\nexport { loadOrchestratorConfigFromSources } from \"./config\"\n\nexport type { ProtocolViolation, ProtocolEnforcementSessionState } from \"./types\"\n",
19
20
  "/**\n * JSON Schema generator for omo-meta-governor.jsonc.\n *\n * Generates a JSON Schema (draft-07) from the MetaGovernorPluginConfig\n * interface definition. The schema is used for IDE autocompletion and\n * validation when editing the .jsonc config file.\n *\n * Usage:\n * import { generateSchema } from \"./generate-schema\"\n * const schema = generateSchema()\n * await Bun.write(\"assets/omo-meta-governor.schema.json\", JSON.stringify(schema, null, 2))\n */\n\nexport interface JsonSchema {\n $schema: string\n $id: string\n title: string\n description: string\n type: \"object\"\n properties: Record<string, JsonSchemaProperty>\n additionalProperties: boolean\n definitions?: Record<string, JsonSchemaProperty>\n}\n\nexport interface JsonSchemaProperty {\n type?: string | string[]\n description?: string\n default?: unknown\n properties?: Record<string, JsonSchemaProperty>\n items?: JsonSchemaProperty\n additionalProperties?: boolean\n required?: string[]\n enum?: string[]\n oneOf?: JsonSchemaProperty[]\n anyOf?: JsonSchemaProperty[]\n $ref?: string\n minimum?: number\n maximum?: number\n}\n\nconst ID_BASE = \"https://raw.githubusercontent.com/herjarsa/omo-meta-governor/main\"\n\n/**\n * Generate the full JSON Schema for the omo-meta-governor.jsonc config file.\n */\nexport function generateSchema(): JsonSchema {\n return {\n $schema: \"http://json-schema.org/draft-07/schema#\",\n $id: `${ID_BASE}/assets/omo-meta-governor.schema.json`,\n title: \"omo-meta-governor\",\n description: \"Configuration schema for @herjarsa/omo-meta-governor — Self-judging agent orchestration layer for OpenCode.\",\n type: \"object\",\n additionalProperties: false,\n properties: {\n $schema: {\n type: \"string\",\n description: \"JSON Schema reference for IDE autocompletion.\",\n },\n enabled: {\n type: \"boolean\",\n description: \"Master feature flag — must be true to run the orchestrator.\",\n default: false,\n },\n decision: {\n type: \"object\",\n description: \"Decision handler configuration.\",\n additionalProperties: false,\n properties: {\n maxHistoryPerSession: {\n type: \"integer\",\n description: \"Maximum history entries per session before oldest are trimmed.\",\n default: 50,\n minimum: 1,\n },\n forceContinueAfterStops: {\n type: \"integer\",\n description: \"How many consecutive stops before forcing continue.\",\n default: 3,\n minimum: 1,\n },\n },\n },\n memory: {\n type: \"object\",\n description: \"Memory aggregator configuration.\",\n additionalProperties: false,\n properties: {\n agentmemoryTimeoutMs: {\n type: \"integer\",\n description: \"Timeout for agentmemory queries in milliseconds.\",\n default: 2000,\n minimum: 100,\n },\n magicContextTimeoutMs: {\n type: \"integer\",\n description: \"Timeout for magic-context queries in milliseconds.\",\n default: 1000,\n minimum: 100,\n },\n boulderStateTimeoutMs: {\n type: \"integer\",\n description: \"Timeout for boulder-state queries in milliseconds.\",\n default: 1000,\n minimum: 100,\n },\n query: {\n type: \"string\",\n description: \"Natural-language query for memory recall.\",\n default: \"meta_governor_context\",\n },\n },\n },\n tokenPredictor: {\n type: \"object\",\n description: \"Token predictor configuration.\",\n additionalProperties: false,\n properties: {\n compactBurnRateThreshold: {\n type: \"integer\",\n description: \"Burn rate threshold (tokens/turn) above which to recommend compact-now.\",\n default: 500,\n minimum: 0,\n },\n compactUsageThreshold: {\n type: \"number\",\n description: \"Context usage ratio (0..1) above which to recommend compact-now.\",\n default: 0.85,\n minimum: 0,\n maximum: 1,\n },\n switchModelUsageThreshold: {\n type: \"number\",\n description: \"Context usage ratio above which to recommend switch-model.\",\n default: 0.95,\n minimum: 0,\n maximum: 1,\n },\n delegateConsecutiveHighBurn: {\n type: \"integer\",\n description: \"Max consecutive high-burn turns before recommending delegate.\",\n default: 5,\n minimum: 1,\n },\n },\n },\n scoring: {\n type: \"object\",\n description: \"Scoring engine configuration.\",\n additionalProperties: false,\n properties: {\n continueThreshold: {\n type: \"number\",\n description: \"Score >= this -> continue silently.\",\n default: 0.3,\n minimum: 0,\n maximum: 1,\n },\n warnThreshold: {\n type: \"number\",\n description: \"Score <= -warnThreshold -> warn.\",\n default: 0.3,\n minimum: 0,\n maximum: 1,\n },\n escalateThreshold: {\n type: \"number\",\n description: \"Score <= -escalateThreshold -> escalate.\",\n default: 0.6,\n minimum: 0,\n maximum: 1,\n },\n stopThreshold: {\n type: \"number\",\n description: \"Score <= -stopThreshold -> stop.\",\n default: 0.8,\n minimum: 0,\n maximum: 1,\n },\n },\n },\n closedLoop: {\n type: \"object\",\n description: \"Closed-loop learning configuration.\",\n additionalProperties: false,\n properties: {\n saveDecisions: {\n type: \"boolean\",\n description: \"Whether to save decision records.\",\n default: true,\n },\n saveLessons: {\n type: \"boolean\",\n description: \"Whether to save lessons.\",\n default: true,\n },\n },\n },\n modelOverride: {\n type: \"object\",\n description: \"Model override for MetaGovernor internal LLM usage.\",\n additionalProperties: false,\n properties: {\n providerID: {\n type: \"string\",\n description: \"Provider ID (e.g. 'openai', 'anthropic').\",\n },\n modelID: {\n type: \"string\",\n description: \"Model ID (e.g. 'gpt-4o-mini', 'claude-sonnet-4-20250514').\",\n },\n modelLimit: {\n type: \"integer\",\n description: \"Context window size for token predictor.\",\n minimum: 1000,\n },\n temperature: {\n type: \"number\",\n description: \"Sampling temperature. Default: 0.2.\",\n default: 0.2,\n minimum: 0,\n maximum: 2,\n },\n topP: {\n type: \"number\",\n description: \"Top-p nucleus sampling. Default: 1.\",\n default: 1,\n minimum: 0,\n maximum: 1,\n },\n maxTokens: {\n type: \"integer\",\n description: \"Max output tokens for internal reasoning.\",\n default: 2048,\n minimum: 1,\n },\n reasoning: {\n type: \"boolean\",\n description: \"Enable extended reasoning / thinking mode.\",\n default: false,\n },\n verbosity: {\n type: \"string\",\n description: \"Verbosity level for internal logging.\",\n enum: [\"silent\", \"minimal\", \"verbose\"],\n default: \"minimal\",\n },\n },\n },\n intervention: {\n type: \"object\",\n description: \"Intervention config for visible decision injection.\",\n additionalProperties: false,\n properties: {\n mode: {\n type: \"string\",\n description: \"How to inject: 'silent', 'message', or 'system'.\",\n enum: [\"silent\", \"message\", \"system\"],\n default: \"silent\",\n },\n includeDecisionHistory: {\n type: \"boolean\",\n description: \"Whether to include recent decision history.\",\n default: true,\n },\n maxHistoryMessages: {\n type: \"integer\",\n description: \"Max history entries when includeDecisionHistory is true.\",\n default: 5,\n minimum: 1,\n },\n minActionForMessage: {\n type: \"string\",\n description: \"Minimum action: 'warn' (all non-continue), 'escalate', or 'stop'.\",\n enum: [\"warn\", \"escalate\", \"stop\"],\n default: \"warn\",\n },\n },\n },\n protocolEnforcement: {\n type: \"object\",\n description: \"Sisyphus protocol enforcement config.\",\n additionalProperties: false,\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Master switch for protocol enforcement.\",\n default: false,\n },\n path: {\n type: \"string\",\n description: \"Path to protocol markdown file.\",\n },\n injectIntoSystem: {\n type: \"boolean\",\n description: \"Whether to inject protocol rules into the system prompt.\",\n default: false,\n },\n auditToolCalls: {\n type: \"boolean\",\n description: \"Whether to audit tool calls for protocol violations.\",\n default: false,\n },\n },\n },\n graphSync: {\n type: \"object\",\n description: \"Graph synchronization (auto-init codegraph/graphify).\",\n additionalProperties: false,\n properties: {\n enabled: {\n type: \"boolean\",\n description: \"Enable auto-initialization of codegraph and graphify.\",\n default: true,\n },\n watch: {\n type: \"boolean\",\n description: \"Enable watch mode (re-index on file changes).\",\n default: false,\n },\n },\n },\n },\n definitions: {\n verbosity: {\n type: \"string\",\n enum: [\"silent\", \"minimal\", \"verbose\"],\n description: \"Verbosity level.\",\n },\n interventionMode: {\n type: \"string\",\n enum: [\"silent\", \"message\", \"system\"],\n description: \"Intervention injection mode.\",\n },\n minAction: {\n type: \"string\",\n enum: [\"warn\", \"escalate\", \"stop\"],\n description: \"Minimum action threshold.\",\n },\n },\n }\n}\n\n/**\n * Write the schema to a file.\n */\nexport async function writeSchemaFile(outputPath: string): Promise<void> {\n const schema = generateSchema()\n const { writeFile } = await import(\"node:fs/promises\")\n await writeFile(outputPath, JSON.stringify(schema, null, 2) + \"\\n\", \"utf-8\")\n}\n"
20
21
  ],
21
- "mappings": "mdAcA,mBAAS,aAAU,0BACnB,kBAAS,mBACT,kBAAS,iBAmBF,SAAS,CAAkB,CAAC,EAAuB,CACxD,IAAM,EAAmB,CAAC,EACtB,EAAI,EAER,MAAO,EAAI,EAAM,OAAQ,CACvB,IAAM,EAAK,EAAM,GAGjB,GAAI,IAAO,KAAO,IAAO,IAAK,CAC5B,IAAM,EAAQ,EACd,EAAO,KAAK,CAAK,EACjB,IACA,MAAO,EAAI,EAAM,OAAQ,CACvB,IAAM,EAAI,EAAM,GAEhB,GADA,EAAO,KAAK,CAAC,EACT,IAAM,MAER,GADA,IACI,EAAI,EAAM,OACZ,EAAO,KAAK,EAAM,EAAG,EAElB,QAAI,IAAM,EAAO,CACtB,IACA,MAEF,IAEF,SAIF,GAAI,IAAO,KAAO,EAAI,EAAI,EAAM,QAAU,EAAM,EAAI,KAAO,IAAK,CAC9D,GAAK,EACL,MAAO,EAAI,EAAM,QAAU,EAAM,KAAO;AAAA,EACtC,IAEF,SAIF,GAAI,IAAO,KAAO,EAAI,EAAI,EAAM,QAAU,EAAM,EAAI,KAAO,IAAK,CAC9D,GAAK,EACL,MAAO,EAAI,EAAM,OAAQ,CACvB,GAAI,EAAM,KAAO,KAAO,EAAI,EAAI,EAAM,QAAU,EAAM,EAAI,KAAO,IAAK,CACpE,GAAK,EACL,MAEF,IAEF,SAGF,EAA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BAAuB,CACrB,KAAM,SACN,YAAa,mEACb,QAAS,KACT,QAAS,EACT,QAAS,CACX,EACA,0BAA2B,CACzB,KAAM,SACN,YAAa,6DACb,QAAS,KACT,QAAS,EACT,QAAS,CACX,EACA,4BAA6B,CAC3B,KAAM,UACN,YAAa,gEACb,QAAS,EACT,QAAS,CACX,CACF,CACF,EACA,QAAS,CACP,KAAM,SACN,YAAa,gCACb,qBAAsB,GACtB,WAAY,CACV,kBAAmB,CACjB,KAAM,SACN,YAAa,sCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,cAAe,CACb,KAAM,SACN,YAAa,mCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,kBAAmB,CACjB,KAAM,SACN,YAAa,2CACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,cAAe,CACb,KAAM,SACN,YAAa,mCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,CACF,CACF,EACA,WAAY,CACV,KAAM,SACN,YAAa,sCACb,qBAAsB,GACtB,WAAY,CACV,cAAe,CACb,KAAM,UACN,YAAa,oCACb,QAAS,EACX,EACA,YAAa,CACX,KAAM,UACN,YAAa,2BACb,QAAS,EACX,CACF,CACF,EACA,cAAe,CACb,KAAM,SACN,YAAa,sDACb,qBAAsB,GACtB,WAAY,CACV,WAAY,CACV,KAAM,SACN,YAAa,2CACf,EACA,QAAS,CACP,KAAM,SACN,YAAa,4DACf,EACA,WAAY,CACV,KAAM,UACN,YAAa,2CACb,QAAS,IACX,EACA,YAAa,CACX,KAAM,SACN,YAAa,sCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,KAAM,CACJ,KAAM,SACN,YAAa,sCACb,QAAS,EACT,QAAS,EACT,QAAS,CACX,EACA,UAAW,CACT,KAAM,UACN,YAAa,4CACb,QAAS,KACT,QAAS,CACX,EACA,UAAW,CACT,KAAM,UACN,YAAa,6CACb,QAAS,EACX,EACA,UAAW,CACT,KAAM,SACN,YAAa,wCACb,KAAM,CAAC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KAAM,UACN,YAAa,qDACb,QAAS,KACT,QAAS,GACX,EACA,MAAO,CACL,KAAM,SACN,YAAa,4CACb,QAAS,uBACX,CACF,CACF,EACA,eAAgB,CACd,KAAM,SACN,YAAa,iCACb,qBAAsB,GACtB,WAAY,CACV,yBAA0B,CACxB,KAAM,UACN,YAAa,0EACb,QAAS,IACT,QAAS,CACX,EACA,sBAAuB,CACrB,KAAM,SACN,YAAa,mEACb,QAAS,KACT,QAAS,EACT,QAAS,CACX,EACA,0BAA2B,CACzB,KAAM,SACN,YAAa,6DACb,QAAS,KACT,QAAS,EACT,QAAS,CACX,EACA,4BAA6B,CAC3B,KAAM,UACN,YAAa,gEACb,QAAS,EACT,QAAS,CACX,CACF,CACF,EACA,QAAS,CACP,KAAM,SACN,YAAa,gCACb,qBAAsB,GACtB,WAAY,CACV,kBAAmB,CACjB,KAAM,SACN,YAAa,sCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,cAAe,CACb,KAAM,SACN,YAAa,mCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,kBAAmB,CACjB,KAAM,SACN,YAAa,2CACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,cAAe,CACb,KAAM,SACN,YAAa,mCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,CACF,CACF,EACA,WAAY,CACV,KAAM,SACN,YAAa,sCACb,qBAAsB,GACtB,WAAY,CACV,cAAe,CACb,KAAM,UACN,YAAa,oCACb,QAAS,EACX,EACA,YAAa,CACX,KAAM,UACN,YAAa,2BACb,QAAS,EACX,CACF,CACF,EACA,cAAe,CACb,KAAM,SACN,YAAa,sDACb,qBAAsB,GACtB,WAAY,CACV,WAAY,CACV,KAAM,SACN,YAAa,2CACf,EACA,QAAS,CACP,KAAM,SACN,YAAa,4DACf,EACA,WAAY,CACV,KAAM,UACN,YAAa,2CACb,QAAS,IACX,EACA,YAAa,CACX,KAAM,SACN,YAAa,sCACb,QAAS,IACT,QAAS,EACT,QAAS,CACX,EACA,KAAM,CACJ,KAAM,SACN,YAAa,sCACb,QAAS,EACT,QAAS,EACT,QAAS,CACX,EACA,UAAW,CACT,KAAM,UACN,YAAa,4CACb,QAAS,KACT,QAAS,CACX,EACA,UAAW,CACT,KAAM,UACN,YAAa,6CACb,QAAS,EACX,EACA,UAAW,CACT,KAAM,SACN,YAAa,wCACb,KAAM,CAAC,SAAU,UAAW,SAAS,EACrC,QAAS,SACX,CACF,CACF,EACA,aAAc,CACZ,KAAM,SACN,YAAa,sDACb,qBAAsB,GACtB,WAAY,CACV,KAAM,CACJ,KAAM,SACN,YAAa,mDACb,KAAM,CAAC,SAAU,UAAW,QAAQ,EACpC,QAAS,QACX,EACA,uBAAwB,CACtB,KAAM,UACN,YAAa,8CACb,QAAS,EACX,EACA,mBAAoB,CAClB,KAAM,UACN,YAAa,2DACb,QAAS,EACT,QAAS,CACX,EACA,oBAAqB,CACnB,KAAM,SACN,YAAa,oEACb,KAAM,CAAC,OAAQ,WAAY,MAAM,EACjC,QAAS,MACX,CACF,CACF,EACA,oBAAqB,CACnB,KAAM,SACN,YAAa,wCACb,qBAAsB,GACtB,WAAY,CACV,QAAS,CACP,KAAM,UACN,YAAa,0CACb,QAAS,EACX,EACA,KAAM,CACJ,KAAM,SACN,YAAa,iCACf,EACA,iBAAkB,CAChB,KAAM,UACN,YAAa,2DACb,QAAS,EACX,EACA,eAAgB,CACd,KAAM,UACN,YAAa,uDACb,QAAS,EACX,CACF,CACF,EACA,UAAW,CACT,KAAM,SACN,YAAa,wDACb,qBAAsB,GACtB,WAAY,CACV,QAAS,CACP,KAAM,UACN,YAAa,wDACb,QAAS,EACX,EACA,MAAO,CACL,KAAM,UACN,YAAa,gDACb,QAAS,EACX,CACF,CACF,CACF,EACA,YAAa,CACX,UAAW,CACT,KAAM,SACN,KAAM,CAAC,SAAU,UAAW,SAAS,EACrC,YAAa,kBACf,EACA,iBAAkB,CAChB,KAAM,SACN,KAAM,CAAC,SAAU,UAAW,QAAQ,EACpC,YAAa,8BACf,EACA,UAAW,CACT,KAAM,SACN,KAAM,CAAC,OAAQ,WAAY,MAAM,EACjC,YAAa,2BACf,CACF,CACF,EAMF,eAAsB,EAAe,CAAC,EAAmC,CACvE,IAAM,EAAS,GAAe,GACtB,aAAc,KAAa,4BACnC,MAAM,EAAU,EAAY,KAAK,UAAU,EAAQ,KAAM,CAAC,EAAI;AAAA,EAAM,OAAO,EDtU7E,IAAM,GAA6B,CACjC,GAAI,oBACJ,OAAQ,GAAyB,CACnC,EAEe",
23
+ "debugId": "3FE6584FA205492964756E2164756E21",
23
24
  "names": []
24
25
  }
package/dist/plugin.d.ts CHANGED
@@ -1,23 +1,14 @@
1
1
  import type { Plugin } from "@opencode-ai/plugin";
2
2
  import type { AgentmemoryWriteBackend, MemoryBackends } from "./types";
3
+ import { type MetaGovernorPluginConfig } from "./config";
3
4
  /**
4
5
  * Dependencies required by the MetaGovernor plugin.
5
- * All are optional features degrade gracefully when backends are unavailable.
6
+ * All are optional - features degrade gracefully when backends are unavailable.
6
7
  */
7
8
  export interface MetaGovernorPluginDeps {
8
- /** Backends for reading memory (agentmemory, magic-context, boulder-state). Optional — degrades gracefully. */
9
9
  backends?: MemoryBackends;
10
- /** Backend for writing lessons/decisions back to agentmemory. Optional — degrades gracefully. */
11
10
  writeBackend?: AgentmemoryWriteBackend;
12
- /** Provider ID for the current session (for token predictor). */
13
11
  providerID?: () => string | undefined;
14
- /** Model ID for the current session (for token predictor). */
15
12
  modelID?: () => string | undefined;
16
13
  }
17
- /**
18
- * Create a MetaGovernor plugin that registers:
19
- * 1. `tool.execute.after` — runs the orchestrator pipeline
20
- * 2. `experimental.chat.messages.transform` — injects decisions as synthetic user messages
21
- * 3. `experimental.chat.system.transform` — appends decision guidance to system prompt
22
- */
23
- export declare function createMetaGovernorPlugin(deps?: MetaGovernorPluginDeps): Plugin;
14
+ export declare function createMetaGovernorPlugin(config?: MetaGovernorPluginConfig, deps?: MetaGovernorPluginDeps): Plugin;
@@ -1,32 +1,8 @@
1
1
  import type { ProtocolViolation } from "./types";
2
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
3
  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
4
  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: {
5
+ export interface AuditContext {
30
6
  /** Whether any memory tools have been used in this session */
31
7
  memoryToolsUsed: readonly string[];
32
8
  /** Whether .codegraph/ directory exists in the project */
@@ -41,4 +17,17 @@ export declare function auditToolCall(toolName: string, _args: unknown, context:
41
17
  emptyRecall: boolean;
42
18
  /** Whether any ctx_search or smart_search was attempted after empty recall */
43
19
  escalationAttempted: boolean;
44
- }): ProtocolViolation[];
20
+ /** Whether AFT tools (aft_zoom, aft_outline) are available */
21
+ aftAvailable?: boolean;
22
+ /** Whether AFT tools have been used in this session */
23
+ aftUsed?: boolean;
24
+ /** Tool names called in this session so far (latest first) */
25
+ recentToolCalls?: readonly string[];
26
+ /** File write/edit contents (last 3 for pattern detection) */
27
+ recentWriteContents?: readonly string[];
28
+ /** Whether ctx_memory save has been used to persist discoveries */
29
+ memorySaved?: boolean;
30
+ /** Number of times todo was batch-completed in this session */
31
+ batchCompletions?: number;
32
+ }
33
+ export declare function auditToolCall(toolName: string, args: unknown, context: AuditContext): ProtocolViolation[];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@herjarsa/omo-meta-governor",
3
- "version": "0.7.0",
3
+ "version": "0.9.0",
4
4
  "type": "module",
5
5
  "description": "Self-judging agent orchestration layer for OpenCode. Reads memory, scores sessions, dispatches decisions.",
6
6
  "exports": {