@herjarsa/omo-meta-governor 0.9.3 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +26 -5
- package/dist/config.d.ts +4 -0
- package/dist/index.js +11 -11
- package/dist/index.js.map +6 -6
- package/dist/types.d.ts +13 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,11 +38,28 @@ After every tool call, MetaGovernor:
|
|
|
38
38
|
|
|
39
39
|
See [docs/guide/meta-governor.md](docs/guide/meta-governor.md) for full docs.
|
|
40
40
|
|
|
41
|
-
## Intervention
|
|
41
|
+
## Intervention
|
|
42
42
|
|
|
43
43
|
MetaGovernor can inject its decisions into the active agent's context
|
|
44
44
|
so the agent is aware of governance warnings, escalations, or stop signals.
|
|
45
45
|
|
|
46
|
+
### v0.10.0 — Loop prevention
|
|
47
|
+
|
|
48
|
+
The plugin now self-disables intervention when the agent's task is verifiably
|
|
49
|
+
complete. This fixes the v0.3.0–v0.9.x bug where the plugin kept injecting
|
|
50
|
+
synthetic user messages indefinitely after the agent had finished.
|
|
51
|
+
|
|
52
|
+
Three mechanisms enforce the cap:
|
|
53
|
+
|
|
54
|
+
1. **`<promise>DONE</promise>` + Oracle verified** — the agent emits this signal
|
|
55
|
+
to mark the task complete. If Oracle has verified the work (the agent
|
|
56
|
+
invoked `task(subagent_type="oracle")` and got a PASS verdict), the plugin
|
|
57
|
+
disables intervention for that session.
|
|
58
|
+
2. **`maxInterventionsPerSession`** — hard cap (default `3`) on the number of
|
|
59
|
+
times a session can receive an injection. Once reached, no more injections.
|
|
60
|
+
3. **Cross-session scoping** — decisions are now scoped to the current
|
|
61
|
+
sessionID. The plugin no longer pulls decisions from unrelated sessions.
|
|
62
|
+
|
|
46
63
|
### Modes
|
|
47
64
|
|
|
48
65
|
| Mode | Mechanism | Effect |
|
|
@@ -61,20 +78,24 @@ so the agent is aware of governance warnings, escalations, or stop signals.
|
|
|
61
78
|
"mode": "message",
|
|
62
79
|
"includeDecisionHistory": true,
|
|
63
80
|
"maxHistoryMessages": 5,
|
|
64
|
-
"minActionForMessage": "
|
|
81
|
+
"minActionForMessage": "stop",
|
|
82
|
+
"maxInterventionsPerSession": 3,
|
|
83
|
+
"respectDoneSignal": true
|
|
65
84
|
}
|
|
66
85
|
}
|
|
67
86
|
}
|
|
68
|
-
|
|
69
87
|
```
|
|
70
88
|
|
|
89
|
+
### Fields
|
|
90
|
+
|
|
71
91
|
| Field | Default | Description |
|
|
72
92
|
|-------|---------|-------------|
|
|
73
93
|
| `mode` | `"silent"` | How to inject: `"silent"`, `"message"`, or `"system"` |
|
|
74
94
|
| `includeDecisionHistory` | `true` | Whether to include recent decision history |
|
|
75
95
|
| `maxHistoryMessages` | `5` | Max history entries when includeDecisionHistory is true |
|
|
76
|
-
| `minActionForMessage` | `"
|
|
77
|
-
|
|
96
|
+
| `minActionForMessage` | `"stop"` (v0.10.0) | Minimum action: `"warn"`, `"escalate"`, or `"stop"`. Default is now `"stop"` so warnings do not auto-trigger injection. Opt UP to `"warn"` explicitly. |
|
|
97
|
+
| `maxInterventionsPerSession` | `3` (v0.10.0) | Hard cap on injections per session. Once reached, no more injections until session restart. |
|
|
98
|
+
| `respectDoneSignal` | `true` (v0.10.0) | When true, the plugin stops injecting the moment the agent emits `<promise>DONE</promise>` AND Oracle has verified the work. |
|
|
78
99
|
### How it works
|
|
79
100
|
|
|
80
101
|
1. After every tool call, MetaGovernor runs the orchestrator pipeline.
|
package/dist/config.d.ts
CHANGED
|
@@ -47,6 +47,10 @@ export interface MetaGovernorPluginConfig {
|
|
|
47
47
|
includeDecisionHistory?: boolean;
|
|
48
48
|
maxHistoryMessages?: number;
|
|
49
49
|
minActionForMessage?: "warn" | "escalate" | "stop";
|
|
50
|
+
/** v0.10.0: rate-limit interventions to break instruction loops. */
|
|
51
|
+
maxInterventionsPerSession?: number;
|
|
52
|
+
/** v0.10.0: stop injecting after <promise>DONE</promise> + Oracle verified. */
|
|
53
|
+
respectDoneSignal?: boolean;
|
|
50
54
|
};
|
|
51
55
|
/** Sisyphus protocol enforcement config. */
|
|
52
56
|
protocolEnforcement?: {
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import{createRequire as
|
|
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
|
|
1
|
+
import{createRequire as sK}from"node:module";var lK=Object.defineProperty;var aK=(K)=>K;function cK(K,Q){this[K]=aK.bind(null,Q)}var rK=(K,Q)=>{for(var X in Q)lK(K,X,{get:Q[X],enumerable:!0,configurable:!0,set:cK.bind(Q,X)})};var nK=(K,Q)=>()=>(K&&(Q=K(K=0)),Q);var FK=sK(import.meta.url);var IK={};rK(IK,{stripJsoncComments:()=>ZK,parseJsonc:()=>$K,loadMetaGovernorConfig:()=>DK,loadJsoncFile:()=>g,getUserConfigPath:()=>JK,getProjectConfigPath:()=>qK,deepMerge:()=>x});import{readFile as jQ,access as yQ}from"node:fs/promises";import{resolve as CQ,join as xQ}from"node:path";import{homedir as DQ}from"node:os";function ZK(K){let Q=[],X=0;while(X<K.length){let $=K[X];if($==='"'||$==="'"){let J=$;Q.push(J),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===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 $K(K){try{let Q=ZK(K);return JSON.parse(Q)}catch{return}}function JK(){return CQ(DQ(),".config","opencode",xK)}function qK(K){let Q=K??process.cwd();return xQ(Q,".opencode",xK)}async function IQ(K){try{return await yQ(K),!0}catch{return!1}}async function g(K){if(!await IQ(K))return;try{let Q=await jQ(K,"utf-8");return $K(Q)}catch{return}}function x(K,Q){let X={...K};for(let Z of Object.keys(Q)){let $=Q[Z],J=X[Z];if($===void 0)continue;if(CK($)&&CK(J))X[Z]=x(J,$);else X[Z]=$}return X}function CK(K){return typeof K==="object"&&K!==null&&!Array.isArray(K)}async function DK(K={}){let Q=[],X="defaults",Z={},$=JK(),J=await g($);if(J)Z=x(Z,J),Q.push(`user:${$}`),X="user";let q=qK(K.projectDir),B=await g(q);if(B)Z=x(Z,B),Q.push(`project:${q}`),X="project";if(K.cliOptions&&Object.keys(K.cliOptions).length>0)Z=x(Z,K.cliOptions),Q.push("cli:inline"),X="cli";return{config:Z,sources:Q,effectiveSource:X}}var xK="omo-meta-governor.jsonc";var zK=()=>{};import{execSync as N,spawn as _K}from"node:child_process";import{access as iK,stat as tK}from"node:fs/promises";import{resolve as S}from"node:path";import{constants as oK}from"node:fs";async function eK(K,Q=60000){try{return N("npm i -D @colbymchenry/codegraph",{cwd:K,stdio:"ignore",timeout:Q}),"codegraph-installed"}catch{return"codegraph-install-failed"}}async function KQ(K=60000){try{return N("pip install graphifyy --break-system-packages --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{try{return N("uv tool install graphifyy --quiet",{stdio:"ignore",timeout:K}),"graphify-installed"}catch{return"graphify-install-failed"}}}var l=new Set;function QQ(){l.clear()}var wK=new Map;function MK(K){let X=(wK.get(K)??0)+1;return wK.set(K,X),X}async function AK(K){let Q=!1,X=!1,Z=await PK(S(K,".codegraph")),$=await PK(S(K,"graphify-out"));try{N("npx --yes codegraph --version",{stdio:"ignore",timeout:1e4}),Q=!0}catch{try{N("node node_modules/.bin/codegraph --version",{cwd:K,stdio:"ignore",timeout:5000}),Q=!0}catch{}}try{N("python3 -c 'import graphify; print(graphify.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{try{N("python3 -c 'import graphifyy; print(graphifyy.__version__)'",{stdio:"ignore",timeout:5000}),X=!0}catch{}}return{codegraph:Q,graphify:X,codegraphIndexExists:Z,graphifyIndexExists:$}}async function XQ(K){let Q=S(K,".codegraph");await OK(Q);try{N("npx --yes codegraph init",{cwd:K,stdio:"ignore",timeout:60000})}catch{}}async function ZQ(K){let Q=S(K,"graphify-out");await OK(Q);try{N("python3 -m graphify . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{try{N("graphifyy . --no-viz",{cwd:K,stdio:"ignore",timeout:120000})}catch{}}}var h=new Map;function LK(K,Q){let X=`${K}:${Q}`;if(h.has(X))return;try{let Z;if(Q==="codegraph")Z=_K("node",["-e",`
|
|
3
3
|
const {execSync} = require("child_process");
|
|
4
4
|
const run = () => {
|
|
5
5
|
try { execSync("npx codegraph update 2>/dev/null", {cwd: ${JSON.stringify(K)}, stdio: "ignore"}); }
|
|
@@ -7,17 +7,17 @@ import{createRequire as rK}from"node:module";var dK=Object.defineProperty;var uK
|
|
|
7
7
|
};
|
|
8
8
|
run();
|
|
9
9
|
setInterval(run, 30_000);
|
|
10
|
-
`],{stdio:"ignore",detached:!0});else Z=FK("python3",["-m","graphify",".","--no-viz","--watch"],{cwd:K,stdio:"ignore",detached:!0});Z.unref(),y.set(X,{process:Z,tool:Q}),Z.on("exit",()=>{y.delete(X)})}catch{}}function XQ(K){for(let[Q,X]of y)if(!K||Q.startsWith(K)){try{X.process.kill("SIGTERM")}catch{}setTimeout(()=>{try{X.process.kill("SIGKILL")}catch{}},2000).unref(),y.delete(Q)}}async function u(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(d.has(X)){let $=await wK(X);return{attempted:!1,codes:$.codegraphIndexExists?["codegraph-already-exists"]:[],availability:$,alreadyInitialized:!0}}d.add(X);let Z;try{Z=await wK(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 tK(X,K.installTimeoutMs??60000);if(Q.push($),$==="codegraph-installed")Z.codegraph=!0}if(!Z.graphify){let $=await oK(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 KQ(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 QQ(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)AK(X,"codegraph"),Q.push("watch-started-codegraph");if(Z.graphify)AK(X,"graphify"),Q.push("watch-started-graphify")}return{attempted:!0,codes:Q,availability:Z,alreadyInitialized:!1}}async function LK(K){try{return(await sK(K)).isDirectory()}catch{return!1}}async function MK(K){try{await nK(K,iK.F_OK)}catch{let{mkdir:Q}=await import("node:fs/promises");await Q(K,{recursive:!0})}}var OK={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function r(K,Q){let X=performance.now(),Z={...OK.limits,...K.limits},$={...OK.timeouts,...K.timeouts},[J,q,B]=await Promise.allSettled([ZQ(K,Q.agentmemory,Z,$.agentmemoryMs),$Q(K,Q.magicContext,Z,$.magicContextMs),JQ(K,Q.boulderState,Z,$.boulderStateMs)]),V=[],W={},z=J.status==="fulfilled"?J.value:(a(V,W,"agentmemory",l(J.reason)),c.agentmemory),U=q.status==="fulfilled"?q.value:(a(V,W,"magicContext",l(q.reason)),c.magicContext),H=B.status==="fulfilled"?B.value:(a(V,W,"boulderState",l(B.reason)),c.boulderState);return{query:K.query,timestampISO:new Date().toISOString(),agentmemory:z,magicContext:U,boulderState:H,degradedSources:V,durationMs:performance.now()-X,errorMessages:W}}async function ZQ(K,Q,X,Z){let $=await n(Q.smartSearch({query:K.query,limit:X.maxLessons}),Z,"agentmemory");return{available:!0,lessons:qQ($.lessons).slice(0,X.maxLessons).map((q)=>({id:q.id,title:q.title,advice:"info",confidence:q.confidence,concepts:q.concepts}))}}async function $Q(K,Q,X,Z){return{available:!0,slots:(await n(Q.slotList({directory:K.directory}),Z,"magicContext")).filter((J)=>J.label.startsWith("meta_governor:")||zQ(J,K.query)).sort((J,q)=>J.label.localeCompare(q.label)).slice(0,X.maxSlots).map((J)=>({label:J.label,content:J.content}))}}async function JQ(K,Q,X,Z){let $=await n(Q.boulderRead({directory:K.directory,sessionID:K.sessionID,query:K.query}),Z,"boulderState");return{available:!0,tasks:$.sort((q,B)=>q.priority-B.priority||B.updatedAtMs-q.updatedAtMs).slice(0,X.maxTasks).map((q)=>({id:q.id,status:q.status,title:q.title})),planProgress:BQ($)}}function qQ(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 BQ(K){if(K.length===0)return 0;return K.filter((X)=>X.status==="done").length/K.length}function l(K){if(K instanceof Error)return K.message;if(typeof K==="string")return K;return"unknown error"}function a(K,Q,X,Z){K.push(X),Q[X]=Z}var c={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function n(K,Q,X){return new Promise((Z,$)=>{let J=setTimeout(()=>$(Error(`${X} timeout after ${Q}ms`)),Q);K.then((q)=>{clearTimeout(J),Z(q)},(q)=>{clearTimeout(J),$(q)})})}function YQ(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function RK(K){if(K.length===0)return 0;return K.reduce((X,Z)=>X+Z,0)/K.length}function VQ(K,Q){let X=0;for(let Z=K.length-1;Z>=0;Z--)if(K[Z]>=Q)X++;else break;return X}function WQ(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 q=J*2;return new Date(new Date(Z).getTime()+q*1000).toISOString()}function s(K){let{currentUsage:Q,modelLimit:X,recentTurnTokens:Z,timestampISO:$,config:J}=K,q=Z.slice(-J.windowSize),B=RK(q),V=X-Q,W=X>0?Q/X:1,z=Math.min(0.95,0.3+q.length/J.windowSize*0.65),U="no-action",H="within normal parameters";if(W>=J.switchModelUsageThreshold)U="switch-model",H=`context usage ${(W*100).toFixed(1)}% exceeds switch threshold ${(J.switchModelUsageThreshold*100).toFixed(1)}%`;if(W>=J.compactUsageThreshold||B>=J.compactBurnRateThreshold){if(U==="no-action")U="compact-now",H=W>=J.compactUsageThreshold?`context usage ${(W*100).toFixed(1)}% exceeds compact threshold ${(J.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${B.toFixed(0)} tokens/turn exceeds threshold ${J.compactBurnRateThreshold}`}let w=VQ(q,J.compactBurnRateThreshold);if(w>=J.delegateConsecutiveHighBurn&&U==="no-action")U="delegate-to-subagent",H=`${w} consecutive high-burn turns (threshold: ${J.delegateConsecutiveHighBurn})`;let _=WQ(Q,X,B,$);return{currentUsage:Q,burnRate:B,budgetLeft:V,willOverflowAt:_,recommendation:U,confidence:z,modelLimit:X,windowRemaining:Math.max(0,Math.floor(V/Math.max(B,1))),input:{...K},computedAtISO:$,turnsAnalyzed:q.length}}var O={"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},S=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function UQ(K){let Q=[];Q.push({source:"oracle-verified",rawScore:K.oracleVerified?0.6:0,weight:O["oracle-verified"],weightedScore:K.oracleVerified?0.6*O["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:O["no-progress-detector"],weightedScore:K.noProgress?-0.8*O["no-progress-detector"]:0,description:K.noProgress?"No progress detected in last turn":"Progress detected"});let X=HQ(K.deviations);Q.push({source:"deviation-detector",rawScore:X,weight:O["deviation-detector"],weightedScore:X*O["deviation-detector"],description:K.deviations.length>0?`${K.deviations.length} deviation(s) detected (worst: ${K.deviations[0].severity})`:"No deviations detected"});let Z=GQ(K.iterationRatio);Q.push({source:"iteration-budget",rawScore:Z,weight:O["iteration-budget"],weightedScore:Z*O["iteration-budget"],description:`Iteration ratio: ${K.iterationRatio.toFixed(2)} (${K.ambient.iteration}/${K.ambient.maxIterations})`});let $=FQ(K.lessonsRelevant);return Q.push({source:"lesson-recall",rawScore:$,weight:O["lesson-recall"],weightedScore:$*O["lesson-recall"],description:K.lessonsRelevant.length>0?`${K.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${_Q(K.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),Q}function HQ(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 GQ(K){if(K<=0.5)return-K*0.6;return-0.3-(K-0.5)*1}function FQ(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 _Q(K){if(K.length===0)return 0;return K.reduce((Q,X)=>Q+X.confidence,0)/K.length}function wQ(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 AQ(K,Q){if(!K.oracleVerified)return"oracle";if(K.deviations.some((X)=>X.severity==="grave"))return"user";return Q.defaultEscalationTarget}function kK(K,Q,X,Z){if(Z)return`Paralysis detected: forced continue despite score ${K.toFixed(3)} (too many consecutive stops)`;let $=[...X].sort((W,z)=>W.weightedScore-z.weightedScore),J=$[0],q=$[$.length-1],B=[];if(J.weightedScore<0)B.push(`primary concern: ${J.description}`);if(q.weightedScore>0)B.push(`positive signal: ${q.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[Q]} (score: ${K.toFixed(3)}): ${B.join("; ")||"balanced signals"}`}function i(K,Q){let X={...S(),...Q},Z=UQ(K),$=Z.reduce((U,H)=>U+H.weightedScore,0),J=Math.max(Math.min($,1),-1),q=K.slotMemory.consecutiveStops>=X.paralysisThreshold&&J<=-X.warnThreshold,B=q?"continue":wQ(J,X),V=[];if(B!=="continue"||Math.abs(J)<X.continueThreshold){for(let U of Z)if(Math.abs(U.weightedScore)>0.01)V.push({source:U.source,value:U.description,confidence:Math.abs(U.rawScore),weight:U.weight});if(V.length===0&&B!=="continue")V.push({source:"ambient",value:kK(J,B,Z,q),confidence:0.5,weight:0.1})}let W=B==="escalate"?AQ(K,X):null;return{decision:{action:B,score:J,reasoning:kK(J,B,Z,q),evidence:V,shouldEscalateTo:W},contributions:Z,rawScore:J,paralysisOverride:q,computedAtISO:new Date().toISOString()}}var v=()=>({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 h(K,Q){let X=K;for(let[Z,$]of Object.entries(Q))X=X.replaceAll(`{${Z}}`,$);return X}function LQ(K){return K.length}function t(K,Q){let X={...v(),...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,q=LQ(Z.evidence),B=Z.shouldEscalateTo??X.defaultEscalationTarget??"oracle";if(K.scoringResult.paralysisOverride)return{action:"continue",message:h(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:`Paralysis detected — forced continue. ${J}`,evidenceCount:String(q)}),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:h(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:J,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}};case"escalate":return{action:"escalate",message:h(X.escalateMessageTemplate,{target:B,reasoning:J}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Escalate to ${B}: ${J}`}};case"stop":return{action:"stop",message:h(X.stopMessageTemplate,{reasoning:J,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}}}}function PQ(K,Q){if(K.length<=Q)return{trimmed:[...K],dropped:0};let X=K.length-Q;return{trimmed:K.slice(-Q),dropped:X}}function MQ(K){let Q=0;for(let X=K.length-1;X>=0;X--)if(K[X].action==="stop")Q++;else break;return Q}var NK={leve:0,media:1,grave:2};function OQ(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 EK(K,Q){let X=NK[Q]??0;return K.some((Z)=>(NK[Z.severity]??0)>=X)}function RQ(K){let Q=new Set;for(let X of K)Q.add(X.category),Q.add(X.severity);return[...Q]}function kQ(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 o(K,Q){let{decision:X,config:Z,sessionID:$,directory:J,filesChanged:q}=K,B=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,W=null;if(Z.saveDecisions){let H={id:OQ($,X.action,B),timestampISO:B,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:[...q]}),W=H}catch{}}let z=X.evidence.filter((H)=>H.source==="deviation-detector").map((H)=>({severity:"media",category:H.source,detail:H.value}));if(EK(z,Z.minSeverityToLearn)){let H=RQ(z),w=kQ(X,z);try{V={id:(await Q.saveLesson({content:w,context:`session:${$} dir:${J}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),tags:H})).id,title:`${X.action} after ${z[0]?.category??"deviation"}`,content:w,type:"pattern",concepts:H,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),files:[...q],sessionID:$}}catch{}}let U=[];if(W)U.push("decision saved");if(V)U.push("lesson saved");if(!W&&!V)if(!EK(z,Z.minSeverityToLearn))U.push("severity below threshold");else U.push("no saveable content");return{lessonSaved:V,decisionSaved:W,reason:U.join("; ")||"no action taken"}}function N(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var bK=()=>({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}}),e={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},NQ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},EQ={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 jK(K,Q=e){let X=K.maxIterations>0?K.iteration/K.maxIterations:0,Z={...NQ,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 KK(K,Q={}){let X={...bK(),...Q};if(!X.enabled)return{memoryRead:e,tokenPrediction:TK(K),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:EQ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=e;if(X.memory.enabled)try{let W={agentmemory:K.backends.agentmemory,magicContext:K.backends.magicContext,boulderState:K.backends.boulderState};Z=await r({directory:".",sessionID:K.sessionID,query:X.memory.query||K.toolName},W)}catch{}let $;try{$=s({currentUsage:K.recentTurnTokens.reduce((W,z)=>W+z,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{$=TK(K)}let J=i(jK(K,Z),X.scoring),q={sessionID:K.sessionID,scoringResult:J},B=t(q,X.decision),V=null;try{if(X.closedLoop.enabled!==!1)V=await o({decision:B.historyEntry.decision,memoryRead:Z,config:{...N(),...X.closedLoop},sessionID:K.sessionID,directory:".",filesChanged:[]},K.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:$,scoringResult:J,decision:B,lessonSaved:V,decisionHistory:[B.historyEntry],skipped:!1}}function TK(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 m(K){let Q={enabled:!1,...K},X=S(),Z=v(),$=N();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 yQ(K){return K?.enabled===!0}async function xQ(K={}){let{loadMetaGovernorConfig:Q}=await Promise.resolve().then(() => (JK(),DK)),X=await Q(K);return m(X.config)}var E=new Map;function qK(K,Q){E.set(K,Q)}function zK(K){let Q=E.get(K);if(Q!==void 0)E.delete(K);return Q}function IQ(K){return E.has(K)}function BK(){for(let[K,Q]of E)return E.delete(K),Q;return}function DQ(){E.clear()}import{appendFileSync as SQ,mkdirSync as hQ}from"node:fs";import{resolve as vQ,dirname as fQ}from"node:path";import{homedir as mQ}from"node:os";var SK=vQ(mQ(),".config","opencode","meta-governor.log");function gQ(){try{hQ(fQ(SK),{recursive:!0})}catch{}}function j(K,Q,X){gQ();let Z=new Date().toISOString(),$=X!==void 0?` | ${JSON.stringify(X)}`:"",J=`[${Z}] [${K.toUpperCase()}] ${Q}${$}
|
|
11
|
-
`;try{
|
|
12
|
-
`)}function WK(K,Q,X){let Z=[],$=X.recentToolCalls??[],J=X.aftAvailable??!1,q=X.aftUsed??!1,B=X.recentWriteContents??[],V=X.memorySaved??!1,W=X.batchCompletions??0;if((K==="grep"||K==="glob")&&(X.hasCodegraphDir||X.hasGraphifyDir)){let _=X.hasCodegraphDir?".codegraph":"graphify-out";Z.push({rule:"codebase-graph-first",tool:K,severity:"media",detail:`Used ${K} when ${_} exists — should use codegraph/graphify first for architecture and symbol queries.`})}if((K==="read"||K==="grep")&&J&&!q)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&&!q&&!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 _=Q;if(!_.task_id&&typeof _.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 z=["write","edit","edit_block","desktop-commander_edit_block","desktop-commander_write_file"];if(z.includes(K)){let _=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??""),L=/@ts-ignore|@ts-expect-error/.test(_),P=/\bas any\b/.test(_);if(L&&P)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(L)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(P)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(z.includes(K)){let _=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??"");if(/catch\s*\(\s*\w+\s*\)\s*\{\s*\}/.test(_))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((L)=>L.startsWith("ctx_memory"))&&!V)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 _=Q.drop;if(typeof _==="string"&&/^\d+-\d+$/i.test(_.trim())){let[L,P]=_.trim().split("-").map(Number);if(!isNaN(L)&&!isNaN(P)&&P-L>10)Z.push({rule:"ctx-reduce-discipline",tool:K,severity:"leve",detail:`Dropped a large range (${_}) 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 H=["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"];if(!X.memoryToolsUsed.some((_)=>H.some((L)=>_.startsWith(L)))&&(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 vK={continue:0,warn:1,escalate:2,stop:3};function UK(K,Q){return vK[K]>=vK[Q]}function HK(K={},Q={}){let X=process.cwd(),Z=(()=>{try{return hK(`${X}/.codegraph`).isDirectory()}catch{return!1}})(),$=(()=>{try{return hK(`${X}/graphify-out`).isDirectory()}catch{return!1}})();if(K.graphSync?.enabled!==!1)u({enabled:!0,watch:K.graphSync?.watch??!1,autoInstall:K.graphSync?.autoInstall??!0,installTimeoutMs:K.graphSync?.installTimeoutMs??60000,projectDir:X}).catch(()=>{}),PK(X);return j("info","MetaGovernor plugin loaded",{version:"0.9.3",cwd:X,projectHasCodegraph:Z,projectHasGraphify:$}),async(B,V)=>{let W={...K,...V?.meta_governor??{}},z=m(W);if(!z.enabled)return{};let U=()=>z.modelOverride?.providerID??Q.providerID?.(),H=()=>z.modelOverride?.modelID??Q.modelID?.(),w=()=>z.modelOverride?.modelLimit??200000,_=U()??"unknown",L=H()??"unknown",P;if(z.protocolEnforcement.enabled||z.protocolEnforcement.injectIntoSystem){let G=z.protocolEnforcement.path??g;YK(G).then((Y)=>{P=VK(Y)}).catch((Y)=>{if(typeof console<"u"&&z.modelOverride?.verbosity!=="silent")console.warn("[meta-governor] could not load protocol:",Y instanceof Error?Y.message:Y)})}let p=new Map,C=new Map;return{"tool.execute.before":async(G)=>{if(!z.enabled)return;if(!z.protocolEnforcement.auditToolCalls)return;if(!G.sessionID)return;let Y=p.get(G.sessionID);if(!Y)Y={memoryToolsUsed:[],hasCodegraphDir:Z,hasGraphifyDir:$,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1,aftAvailable:!1,aftUsed:!1,recentToolCalls:[],recentWriteContents:[],memorySaved:!1,batchCompletions:0},p.set(G.sessionID,Y);if(P)console.log("[meta-governor] protocol loaded, system injection ready");let F=WK(G.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(F.length>0){j("warn",`protocol violations on tool ${G.tool}`,F);let R=C.get(G.sessionID)??[];for(let A of F)R.push(`[${A.severity.toUpperCase()}] ${A.rule}: ${A.detail}`);C.set(G.sessionID,R)}else j("info",`audit OK on tool ${G.tool}`)},"tool.execute.after":async(G,Y)=>{if(!z.enabled)return;let F=p.get(G.sessionID);if(F){if(F.recentToolCalls=[G.tool].concat(F.recentToolCalls).slice(0,20),["write","edit","edit_block","desktop-commander_write_file","desktop-commander_edit_block"].includes(G.tool)){F.filesChanged++;let k=(Y.output??"").slice(0,500);F.recentWriteContents=[k].concat(F.recentWriteContents).slice(0,3)}if(["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"].some((k)=>G.tool.startsWith(k))&&!F.memoryToolsUsed.includes(G.tool))F.memoryToolsUsed.push(G.tool);if(G.tool.startsWith("ctx_memory")){let k=Y.output??"";if(k.includes("saved")||k.includes("written"))F.memorySaved=!0}if(G.tool.startsWith("aft_zoom")||G.tool.startsWith("aft_outline"))F.aftUsed=!0;if(G.tool==="task"&&(Y.output??"").includes("subagent_type=oracle"))F.oracleInvoked=!0;let I=(Y.output??"").toLowerCase();if(G.tool.includes("recall")&&(I.includes("returned empty")||I.includes("no results")))F.emptyRecall=!0;if(G.tool==="todowrite"&&(Y.output??"").includes("completed")){if(((Y.output??"").match(/"status":"completed"/g)??[]).length>=3)F.batchCompletions++}}let R={sessionID:G.sessionID,toolName:G.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:z,...U()?{providerID:U()}:{},...H()?{modelID:H()}:{},modelLimit:w()};try{let A=await KK(R);if(z.intervention.mode!=="silent"){let T=A.decision;if(T.action!=="continue"&&UK(T.action,z.intervention.minActionForMessage))qK(G.sessionID,T)}}catch{}},"experimental.chat.messages.transform":async(G,Y)=>{if(!z.enabled)return;if(z.intervention.mode!=="message")return;let R=Y.messages[Y.messages.length-1]?.info?.sessionID;if(R&&C.has(R)){let x=C.get(R);if(x.length>0){let I=`[META-GOVERNOR PROTOCOL VIOLATIONS - YOU MUST COMPLY]
|
|
10
|
+
`],{stdio:"ignore",detached:!0});else Z=_K("python3",["-m","graphify",".","--no-viz","--watch"],{cwd:K,stdio:"ignore",detached:!0});Z.unref(),h.set(X,{process:Z,tool:Q}),Z.on("exit",()=>{h.delete(X)})}catch{}}function $Q(K){for(let[Q,X]of h)if(!K||Q.startsWith(K)){try{X.process.kill("SIGTERM")}catch{}setTimeout(()=>{try{X.process.kill("SIGKILL")}catch{}},2000).unref(),h.delete(Q)}}async function a(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(l.has(X)){let $=await AK(X);return{attempted:!1,codes:$.codegraphIndexExists?["codegraph-already-exists"]:[],availability:$,alreadyInitialized:!0}}l.add(X);let Z;try{Z=await AK(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 eK(X,K.installTimeoutMs??60000);if(Q.push($),$==="codegraph-installed")Z.codegraph=!0}if(!Z.graphify){let $=await KQ(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 XQ(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 ZQ(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)LK(X,"codegraph"),Q.push("watch-started-codegraph");if(Z.graphify)LK(X,"graphify"),Q.push("watch-started-graphify")}return{attempted:!0,codes:Q,availability:Z,alreadyInitialized:!1}}async function PK(K){try{return(await tK(K)).isDirectory()}catch{return!1}}async function OK(K){try{await iK(K,oK.F_OK)}catch{let{mkdir:Q}=await import("node:fs/promises");await Q(K,{recursive:!0})}}var RK={limits:{maxLessons:10,maxSlots:20,maxTasks:10},timeouts:{agentmemoryMs:2000,magicContextMs:1000,boulderStateMs:1000}};async function s(K,Q){let X=performance.now(),Z={...RK.limits,...K.limits},$={...RK.timeouts,...K.timeouts},[J,q,B]=await Promise.allSettled([JQ(K,Q.agentmemory,Z,$.agentmemoryMs),qQ(K,Q.magicContext,Z,$.magicContextMs),zQ(K,Q.boulderState,Z,$.boulderStateMs)]),W=[],G={},z=J.status==="fulfilled"?J.value:(r(W,G,"agentmemory",c(J.reason)),n.agentmemory),H=q.status==="fulfilled"?q.value:(r(W,G,"magicContext",c(q.reason)),n.magicContext),F=B.status==="fulfilled"?B.value:(r(W,G,"boulderState",c(B.reason)),n.boulderState);return{query:K.query,timestampISO:new Date().toISOString(),agentmemory:z,magicContext:H,boulderState:F,degradedSources:W,durationMs:performance.now()-X,errorMessages:G}}async function JQ(K,Q,X,Z){let $=await i(Q.smartSearch({query:K.query,limit:X.maxLessons}),Z,"agentmemory");return{available:!0,lessons:BQ($.lessons).slice(0,X.maxLessons).map((q)=>({id:q.id,title:q.title,advice:"info",confidence:q.confidence,concepts:q.concepts}))}}async function qQ(K,Q,X,Z){return{available:!0,slots:(await i(Q.slotList({directory:K.directory}),Z,"magicContext")).filter((J)=>J.label.startsWith("meta_governor:")||YQ(J,K.query)).sort((J,q)=>J.label.localeCompare(q.label)).slice(0,X.maxSlots).map((J)=>({label:J.label,content:J.content}))}}async function zQ(K,Q,X,Z){let $=await i(Q.boulderRead({directory:K.directory,sessionID:K.sessionID,query:K.query}),Z,"boulderState");return{available:!0,tasks:$.sort((q,B)=>q.priority-B.priority||B.updatedAtMs-q.updatedAtMs).slice(0,X.maxTasks).map((q)=>({id:q.id,status:q.status,title:q.title})),planProgress:VQ($)}}function BQ(K){return[...K].sort((Q,X)=>X.confidence-Q.confidence)}function YQ(K,Q){let X=Q.toLowerCase();return K.label.toLowerCase().includes(X)||K.content.toLowerCase().includes(X)}function VQ(K){if(K.length===0)return 0;return K.filter((X)=>X.status==="done").length/K.length}function c(K){if(K instanceof Error)return K.message;if(typeof K==="string")return K;return"unknown error"}function r(K,Q,X,Z){K.push(X),Q[X]=Z}var n={agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0}};async function i(K,Q,X){return new Promise((Z,$)=>{let J=setTimeout(()=>$(Error(`${X} timeout after ${Q}ms`)),Q);K.then((q)=>{clearTimeout(J),Z(q)},(q)=>{clearTimeout(J),$(q)})})}function WQ(){return{compactBurnRateThreshold:500,compactUsageThreshold:0.85,switchModelUsageThreshold:0.95,delegateConsecutiveHighBurn:5,windowSize:10}}function NK(K){if(K.length===0)return 0;return K.reduce((X,Z)=>X+Z,0)/K.length}function UQ(K,Q){let X=0;for(let Z=K.length-1;Z>=0;Z--)if(K[Z]>=Q)X++;else break;return X}function GQ(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 q=J*2;return new Date(new Date(Z).getTime()+q*1000).toISOString()}function t(K){let{currentUsage:Q,modelLimit:X,recentTurnTokens:Z,timestampISO:$,config:J}=K,q=Z.slice(-J.windowSize),B=NK(q),W=X-Q,G=X>0?Q/X:1,z=Math.min(0.95,0.3+q.length/J.windowSize*0.65),H="no-action",F="within normal parameters";if(G>=J.switchModelUsageThreshold)H="switch-model",F=`context usage ${(G*100).toFixed(1)}% exceeds switch threshold ${(J.switchModelUsageThreshold*100).toFixed(1)}%`;if(G>=J.compactUsageThreshold||B>=J.compactBurnRateThreshold){if(H==="no-action")H="compact-now",F=G>=J.compactUsageThreshold?`context usage ${(G*100).toFixed(1)}% exceeds compact threshold ${(J.compactUsageThreshold*100).toFixed(1)}%`:`burn rate ${B.toFixed(0)} tokens/turn exceeds threshold ${J.compactBurnRateThreshold}`}let A=UQ(q,J.compactBurnRateThreshold);if(A>=J.delegateConsecutiveHighBurn&&H==="no-action")H="delegate-to-subagent",F=`${A} consecutive high-burn turns (threshold: ${J.delegateConsecutiveHighBurn})`;let _=GQ(Q,X,B,$);return{currentUsage:Q,burnRate:B,budgetLeft:W,willOverflowAt:_,recommendation:H,confidence:z,modelLimit:X,windowRemaining:Math.max(0,Math.floor(W/Math.max(B,1))),input:{...K},computedAtISO:$,turnsAnalyzed:q.length}}var E={"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},v=()=>({continueThreshold:0.3,warnThreshold:0.3,escalateThreshold:0.6,stopThreshold:0.8,paralysisThreshold:3,defaultEscalationTarget:"oracle"});function HQ(K){let Q=[];Q.push({source:"oracle-verified",rawScore:K.oracleVerified?0.6:0,weight:E["oracle-verified"],weightedScore:K.oracleVerified?0.6*E["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:E["no-progress-detector"],weightedScore:K.noProgress?-0.8*E["no-progress-detector"]:0,description:K.noProgress?"No progress detected in last turn":"Progress detected"});let X=FQ(K.deviations);Q.push({source:"deviation-detector",rawScore:X,weight:E["deviation-detector"],weightedScore:X*E["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:E["iteration-budget"],weightedScore:Z*E["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:E["lesson-recall"],weightedScore:$*E["lesson-recall"],description:K.lessonsRelevant.length>0?`${K.lessonsRelevant.length} relevant lesson(s) (avg confidence: ${AQ(K.lessonsRelevant).toFixed(2)})`:"No relevant lessons"}),Q}function FQ(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 _Q(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 AQ(K){if(K.length===0)return 0;return K.reduce((Q,X)=>Q+X.confidence,0)/K.length}function LQ(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 PQ(K,Q){if(!K.oracleVerified)return"oracle";if(K.deviations.some((X)=>X.severity==="grave"))return"user";return Q.defaultEscalationTarget}function EK(K,Q,X,Z){if(Z)return`Paralysis detected: forced continue despite score ${K.toFixed(3)} (too many consecutive stops)`;let $=[...X].sort((G,z)=>G.weightedScore-z.weightedScore),J=$[0],q=$[$.length-1],B=[];if(J.weightedScore<0)B.push(`primary concern: ${J.description}`);if(q.weightedScore>0)B.push(`positive signal: ${q.description}`);return`${{continue:"Continue",warn:"Warn",escalate:"Escalate",stop:"Stop"}[Q]} (score: ${K.toFixed(3)}): ${B.join("; ")||"balanced signals"}`}function o(K,Q){let X={...v(),...Q},Z=HQ(K),$=Z.reduce((H,F)=>H+F.weightedScore,0),J=Math.max(Math.min($,1),-1),q=K.slotMemory.consecutiveStops>=X.paralysisThreshold&&J<=-X.warnThreshold,B=q?"continue":LQ(J,X),W=[];if(B!=="continue"||Math.abs(J)<X.continueThreshold){for(let H of Z)if(Math.abs(H.weightedScore)>0.01)W.push({source:H.source,value:H.description,confidence:Math.abs(H.rawScore),weight:H.weight});if(W.length===0&&B!=="continue")W.push({source:"ambient",value:EK(J,B,Z,q),confidence:0.5,weight:0.1})}let G=B==="escalate"?PQ(K,X):null;return{decision:{action:B,score:J,reasoning:EK(J,B,Z,q),evidence:W,shouldEscalateTo:G},contributions:Z,rawScore:J,paralysisOverride:q,computedAtISO:new Date().toISOString()}}var m=()=>({enabled:!0,maxHistoryPerSession:50,forceContinueAfterStops:3,warnMessageTemplate:"[MetaGovernor] Score {score}: {reasoning}. Evidence: {evidenceCount} signal(s).",escalateMessageTemplate:"[MetaGovernor] Escalating to {target}: {reasoning}",stopMessageTemplate:"[MetaGovernor] STOP — {reasoning}. Evidence: {evidenceCount} signal(s)."});function f(K,Q){let X=K;for(let[Z,$]of Object.entries(Q))X=X.replaceAll(`{${Z}}`,$);return X}function MQ(K){return K.length}function e(K,Q){let X={...m(),...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,q=MQ(Z.evidence),B=Z.shouldEscalateTo??X.defaultEscalationTarget??"oracle";if(K.scoringResult.paralysisOverride)return{action:"continue",message:f(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:`Paralysis detected — forced continue. ${J}`,evidenceCount:String(q)}),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:f(X.warnMessageTemplate,{score:$.toFixed(3),reasoning:J,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"warn",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}};case"escalate":return{action:"escalate",message:f(X.escalateMessageTemplate,{target:B,reasoning:J}),historyEntry:{decision:Z,action:"escalate",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:`Escalate to ${B}: ${J}`}};case"stop":return{action:"stop",message:f(X.stopMessageTemplate,{reasoning:J,evidenceCount:String(q)}),historyEntry:{decision:Z,action:"stop",timestampISO:new Date().toISOString(),sessionID:K.sessionID,reasoning:J}}}}function OQ(K,Q){if(K.length<=Q)return{trimmed:[...K],dropped:0};let X=K.length-Q;return{trimmed:K.slice(-Q),dropped:X}}function RQ(K){let Q=0;for(let X=K.length-1;X>=0;X--)if(K[X].action==="stop")Q++;else break;return Q}var kK={leve:0,media:1,grave:2};function NQ(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 bK(K,Q){let X=kK[Q]??0;return K.some((Z)=>(kK[Z.severity]??0)>=X)}function EQ(K){let Q=new Set;for(let X of K)Q.add(X.category),Q.add(X.severity);return[...Q]}function kQ(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 KK(K,Q){let{decision:X,config:Z,sessionID:$,directory:J,filesChanged:q}=K,B=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 W=null,G=null;if(Z.saveDecisions){let F={id:NQ($,X.action,B),timestampISO:B,action:X.action,score:X.score,reasoning:X.reasoning,sessionID:$,directory:J,deviations:X.evidence.filter((A)=>A.source==="deviation-detector").map((A)=>({severity:"media",category:A.source,detail:A.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]}),G=F}catch{}}let z=X.evidence.filter((F)=>F.source==="deviation-detector").map((F)=>({severity:"media",category:F.source,detail:F.value}));if(bK(z,Z.minSeverityToLearn)){let F=EQ(z),A=kQ(X,z);try{W={id:(await Q.saveLesson({content:A,context:`session:${$} dir:${J}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),tags:F})).id,title:`${X.action} after ${z[0]?.category??"deviation"}`,content:A,type:"pattern",concepts:F,confidence:Math.max(0.3,Math.min(0.8,Math.abs(X.score))),files:[...q],sessionID:$}}catch{}}let H=[];if(G)H.push("decision saved");if(W)H.push("lesson saved");if(!G&&!W)if(!bK(z,Z.minSeverityToLearn))H.push("severity below threshold");else H.push("no saveable content");return{lessonSaved:W,decisionSaved:G,reason:H.join("; ")||"no action taken"}}function y(){return{enabled:!0,minSeverityToLearn:"media",maxLessonsPerSession:20,saveDecisions:!0}}var jK=()=>({enabled:!0,memory:{enabled:!0,query:"",timeoutMs:3000},tokenPredictor:{},scoring:{},decision:{},closedLoop:{},intervention:{mode:"silent",includeDecisionHistory:!0,maxHistoryMessages:5,minActionForMessage:"stop",maxInterventionsPerSession:3,respectDoneSignal:!0},protocolEnforcement:{enabled:!1,path:void 0,injectIntoSystem:!1,auditToolCalls:!1}}),QK={query:"",timestampISO:new Date().toISOString(),agentmemory:{available:!1,lessons:[]},magicContext:{available:!1,slots:[]},boulderState:{available:!1,tasks:[],planProgress:0},degradedSources:["agentmemory","magicContext","boulderState"]},bQ={consecutiveStops:0,consecutiveContinues:0,lastUpdatedISO:new Date().toISOString()},TQ={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 yK(K,Q=QK){let X=K.maxIterations>0?K.iteration/K.maxIterations:0,Z={...bQ,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 XK(K,Q={}){let X={...jK(),...Q};if(!X.enabled)return{memoryRead:QK,tokenPrediction:TK(K),scoringResult:{decision:{action:"continue",score:0,reasoning:"MetaGovernor disabled",evidence:[],shouldEscalateTo:null},contributions:[],rawScore:0,paralysisOverride:!1,computedAtISO:new Date().toISOString()},decision:TQ,lessonSaved:null,decisionHistory:[],skipped:!0,skipReason:"disabled"};let Z=QK;if(X.memory.enabled)try{let G={agentmemory:K.backends.agentmemory,magicContext:K.backends.magicContext,boulderState:K.backends.boulderState};Z=await s({directory:".",sessionID:K.sessionID,query:X.memory.query||K.toolName},G)}catch{}let $;try{$=t({currentUsage:K.recentTurnTokens.reduce((G,z)=>G+z,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{$=TK(K)}let J=o(yK(K,Z),X.scoring),q={sessionID:K.sessionID,scoringResult:J},B=e(q,X.decision),W=null;try{if(X.closedLoop.enabled!==!1)W=await KK({decision:B.historyEntry.decision,memoryRead:Z,config:{...y(),...X.closedLoop},sessionID:K.sessionID,directory:".",filesChanged:[]},K.writeBackend)}catch{}return{memoryRead:Z,tokenPrediction:$,scoringResult:J,decision:B,lessonSaved:W,decisionHistory:[B.historyEntry],skipped:!1}}function TK(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 p(K){let Q={enabled:!1,...K},X=v(),Z=m(),$=y();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??"stop",maxInterventionsPerSession:Q.intervention?.maxInterventionsPerSession??3,respectDoneSignal:Q.intervention?.respectDoneSignal??!0},protocolEnforcement:{enabled:Q.protocolEnforcement?.enabled??!1,path:Q.protocolEnforcement?.path,injectIntoSystem:Q.protocolEnforcement?.injectIntoSystem??!1,auditToolCalls:Q.protocolEnforcement?.auditToolCalls??!1}}}function hQ(K){return K?.enabled===!0}async function SQ(K={}){let{loadMetaGovernorConfig:Q}=await Promise.resolve().then(() => (zK(),IK)),X=await Q(K);return p(X.config)}var C=new Map;function BK(K,Q){C.set(K,Q)}function T(K){let Q=C.get(K);if(Q!==void 0)C.delete(K);return Q}function vQ(K){return C.has(K)}function fQ(){for(let[K,Q]of C)return C.delete(K),Q;return}function mQ(){C.clear()}import{appendFileSync as gQ,mkdirSync as pQ}from"node:fs";import{resolve as dQ,dirname as uQ}from"node:path";import{homedir as lQ}from"node:os";var hK=dQ(lQ(),".config","opencode","meta-governor.log");function aQ(){try{pQ(uQ(hK),{recursive:!0})}catch{}}function b(K,Q,X){aQ();let Z=new Date().toISOString(),$=X!==void 0?` | ${JSON.stringify(X)}`:"",J=`[${Z}] [${K.toUpperCase()}] ${Q}${$}
|
|
11
|
+
`;try{gQ(hK,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{statSync as SK}from"node:fs";import{readFile as cQ}from"node:fs/promises";import{resolve as rQ}from"node:path";import{homedir as nQ}from"node:os";var d=rQ(nQ(),".config","opencode","sisyphus-mandatory","sisyphus-mandatory.md");async function YK(K){return await cQ(K??d,"utf-8")}function VK(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 WK(K,Q,X){let Z=[],$=X.recentToolCalls??[],J=X.aftAvailable??!1,q=X.aftUsed??!1,B=X.recentWriteContents??[],W=X.memorySaved??!1,G=X.batchCompletions??0;if((K==="grep"||K==="glob")&&(X.hasCodegraphDir||X.hasGraphifyDir)){let _=X.hasCodegraphDir?".codegraph":"graphify-out";Z.push({rule:"codebase-graph-first",tool:K,severity:"media",detail:`Used ${K} when ${_} exists — should use codegraph/graphify first for architecture and symbol queries.`})}if((K==="read"||K==="grep")&&J&&!q)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&&!q&&!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 _=Q;if(!_.task_id&&typeof _.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 z=["write","edit","edit_block","desktop-commander_edit_block","desktop-commander_write_file"];if(z.includes(K)){let _=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??""),M=/@ts-ignore|@ts-expect-error/.test(_),O=/\bas any\b/.test(_);if(M&&O)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(M)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(O)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(z.includes(K)){let _=typeof Q==="object"&&Q!==null?JSON.stringify(Q):String(Q??"");if(/catch\s*\(\s*\w+\s*\)\s*\{\s*\}/.test(_))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((M)=>M.startsWith("ctx_memory"))&&!W)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(G>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 _=Q.drop;if(typeof _==="string"&&/^\d+-\d+$/i.test(_.trim())){let[M,O]=_.trim().split("-").map(Number);if(!isNaN(M)&&!isNaN(O)&&O-M>10)Z.push({rule:"ctx-reduce-discipline",tool:K,severity:"leve",detail:`Dropped a large range (${_}) 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 F=["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"];if(!X.memoryToolsUsed.some((_)=>F.some((M)=>_.startsWith(M)))&&(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 vK={continue:0,warn:1,escalate:2,stop:3};function UK(K,Q){return vK[K]>=vK[Q]}function GK(K={},Q={}){let X=process.cwd(),Z=(()=>{try{return SK(`${X}/.codegraph`).isDirectory()}catch{return!1}})(),$=(()=>{try{return SK(`${X}/graphify-out`).isDirectory()}catch{return!1}})();if(K.graphSync?.enabled!==!1)a({enabled:!0,watch:K.graphSync?.watch??!1,autoInstall:K.graphSync?.autoInstall??!0,installTimeoutMs:K.graphSync?.installTimeoutMs??60000,projectDir:X}).catch(()=>{}),MK(X);return b("info","MetaGovernor plugin loaded",{version:"0.10.0",cwd:X,projectHasCodegraph:Z,projectHasGraphify:$}),async(B,W)=>{let G={...K,...W?.meta_governor??{}},z=p(G);if(!z.enabled)return{};let H=()=>z.modelOverride?.providerID??Q.providerID?.(),F=()=>z.modelOverride?.modelID??Q.modelID?.(),A=()=>z.modelOverride?.modelLimit??200000,_=H()??"unknown",M=F()??"unknown",O;if(z.protocolEnforcement.enabled||z.protocolEnforcement.injectIntoSystem){let Y=z.protocolEnforcement.path??d;YK(Y).then((V)=>{O=VK(V)}).catch((V)=>{if(typeof console<"u"&&z.modelOverride?.verbosity!=="silent")console.warn("[meta-governor] could not load protocol:",V instanceof Error?V.message:V)})}let j=new Map,D=new Map;function HK(Y){if(typeof Y!=="string"||Y.length===0)return!1;return/<promise>\s*DONE!?\s*<\/promise>/i.test(Y)}return{"tool.execute.before":async(Y)=>{if(!z.enabled)return;if(!z.protocolEnforcement.auditToolCalls)return;if(!Y.sessionID)return;let V=j.get(Y.sessionID);if(!V)V={memoryToolsUsed:[],hasCodegraphDir:Z,hasGraphifyDir:$,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1,aftAvailable:!1,aftUsed:!1,recentToolCalls:[],recentWriteContents:[],memorySaved:!1,batchCompletions:0,taskDoneSignal:!1,interventionCount:0,interventionDisabled:!1},j.set(Y.sessionID,V);if(O)console.log("[meta-governor] protocol loaded, system injection ready");let U=WK(Y.tool,{},{memoryToolsUsed:V.memoryToolsUsed,hasCodegraphDir:V.hasCodegraphDir,hasGraphifyDir:V.hasGraphifyDir,oracleInvoked:V.oracleInvoked,filesChanged:V.filesChanged,emptyRecall:V.emptyRecall,escalationAttempted:V.escalationAttempted,aftAvailable:V.aftAvailable,aftUsed:V.aftUsed,recentToolCalls:V.recentToolCalls,recentWriteContents:V.recentWriteContents,memorySaved:V.memorySaved,batchCompletions:V.batchCompletions});if(U.length>0){b("warn",`protocol violations on tool ${Y.tool}`,U);let w=D.get(Y.sessionID)??[];for(let L of U)w.push(`[${L.severity.toUpperCase()}] ${L.rule}: ${L.detail}`);D.set(Y.sessionID,w)}else b("info",`audit OK on tool ${Y.tool}`)},"tool.execute.after":async(Y,V)=>{if(!z.enabled)return;let U=j.get(Y.sessionID);if(U){if(U.recentToolCalls=[Y.tool].concat(U.recentToolCalls).slice(0,20),["write","edit","edit_block","desktop-commander_write_file","desktop-commander_edit_block"].includes(Y.tool)){U.filesChanged++;let k=(V.output??"").slice(0,500);U.recentWriteContents=[k].concat(U.recentWriteContents).slice(0,3)}if(["agentmemory_memory_recall","agentmemory_memory_smart_search","agentmemory_memory_save","ctx_memory","ctx_search","ctx_note"].some((k)=>Y.tool.startsWith(k))&&!U.memoryToolsUsed.includes(Y.tool))U.memoryToolsUsed.push(Y.tool);if(Y.tool.startsWith("ctx_memory")){let k=V.output??"";if(k.includes("saved")||k.includes("written"))U.memorySaved=!0}if(Y.tool.startsWith("aft_zoom")||Y.tool.startsWith("aft_outline"))U.aftUsed=!0;if(Y.tool==="task"&&(V.output??"").includes("subagent_type=oracle"))U.oracleInvoked=!0;let I=(V.output??"").toLowerCase();if(Y.tool.includes("recall")&&(I.includes("returned empty")||I.includes("no results")))U.emptyRecall=!0;if(Y.tool==="todowrite"&&(V.output??"").includes("completed")){if(((V.output??"").match(/"status":"completed"/g)??[]).length>=3)U.batchCompletions++}if(!U.taskDoneSignal){if(HK(V.output)||HK(Y.args))U.taskDoneSignal=!0,b("info",`task_done_signal detected for session ${Y.sessionID}`)}}if(U?.interventionDisabled)return;let w={sessionID:Y.sessionID,toolName:Y.tool,toolOutput:V.output,iteration:0,maxIterations:10,oracleVerified:U?.oracleInvoked??!1,noProgress:!1,filesChanged:U?.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:z,...H()?{providerID:H()}:{},...F()?{modelID:F()}:{},modelLimit:A()};try{let L=await XK(w);if(z.intervention.mode!=="silent"&&U){let R=L.decision;if(z.intervention.respectDoneSignal&&U.taskDoneSignal&&U.oracleInvoked){U.interventionDisabled=!0,b("info",`task verified (DONE + Oracle): disabling intervention for session ${Y.sessionID}`),T(Y.sessionID);return}if(R.action!=="continue"&&UK(R.action,z.intervention.minActionForMessage)){let P=Math.max(0,z.intervention.maxInterventionsPerSession??0);if(P>0&&U.interventionCount>=P){U.interventionDisabled=!0,b("warn",`intervention cap (${P}) reached for session ${Y.sessionID}; disabling further intervention`),T(Y.sessionID);return}U.interventionCount++,BK(Y.sessionID,R)}}}catch{}},"experimental.chat.messages.transform":async(Y,V)=>{if(!z.enabled)return;if(z.intervention.mode!=="message")return;let w=V.messages[V.messages.length-1]?.info?.sessionID;if(!w)return;let L=j.get(w);if(L?.interventionDisabled){T(w);return}if(D.has(w)){let u=D.get(w);if(u.length>0){let pK=`[META-GOVERNOR PROTOCOL VIOLATIONS - YOU MUST COMPLY]
|
|
13
13
|
|
|
14
|
-
${
|
|
14
|
+
${u.map((dK,uK)=>`${uK+1}. ${dK}`).join(`
|
|
15
15
|
`)}
|
|
16
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.`;
|
|
18
|
-
### Sisyphus Protocol Enforcement`,
|
|
19
|
-
[MetaGovernor Intervention]`,
|
|
20
|
-
`,"utf-8")}var
|
|
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.`;V.messages.push({info:{role:"user",agent:"meta-governor",synthetic:!0},parts:[{type:"text",text:pK,synthetic:!0}]}),D.delete(w),b("info",`injected ${u.length} violation(s) to model`)}}let R=T(w);if(!R)return;if(R.action==="continue")return;if(!R.message)return;if(!UK(R.action,z.intervention.minActionForMessage))return;let P=L??j.get(w);if(!P)P={memoryToolsUsed:[],hasCodegraphDir:Z,hasGraphifyDir:$,oracleInvoked:!1,filesChanged:0,emptyRecall:!1,escalationAttempted:!1,aftAvailable:!1,aftUsed:!1,recentToolCalls:[],recentWriteContents:[],memorySaved:!1,batchCompletions:0,taskDoneSignal:!1,interventionCount:0,interventionDisabled:!1},j.set(w,P);let I=Math.max(0,z.intervention.maxInterventionsPerSession??0);if(I>0&&P.interventionCount>=I){P.interventionDisabled=!0;return}P.interventionCount++;let k={type:"text",text:`[MetaGovernor] ${R.message}`,synthetic:!0};V.messages.push({info:{role:"user",agent:"meta-governor"},parts:[k]})},"experimental.chat.system.transform":async(Y,V)=>{if(!z.enabled)return;if(z.protocolEnforcement.injectIntoSystem&&O)V.system.push(`
|
|
18
|
+
### Sisyphus Protocol Enforcement`,O,"---");if(z.intervention.mode==="system"&&Y.sessionID){let U=j.get(Y.sessionID);if(U?.interventionDisabled){T(Y.sessionID);return}let w=T(Y.sessionID);if(w&&w.action!=="continue"&&w.message){if(UK(w.action,z.intervention.minActionForMessage)){if(U){let L=Math.max(0,z.intervention.maxInterventionsPerSession??0);if(L>0&&U.interventionCount>=L){U.interventionDisabled=!0;return}U.interventionCount++}V.system.push(`
|
|
19
|
+
[MetaGovernor Intervention]`,w.message,"---")}}}}}}}function sQ(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 fK={leve:0,media:1,grave:2};function mK(K,Q){let X=fK[Q]??0;return K.some((Z)=>(fK[Z.severity]??0)>=X)}async function iQ(K,Q,X){if(!Q)return null;let Z=X?.config??y(),$=sQ(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"}`}],q=null,B=null;if(Z.saveDecisions){let G={id:`D-${Math.abs(`${K.sessionID}-${$.action}-${Date.now()}`.split("").reduce((z,H)=>(z<<5)-z+H.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((z)=>({severity:z.severity,category:z.category,detail:z.detail}))};try{await Q.saveMemory({content:`Decision: ${$.action} (score ${$.score.toFixed(2)}). ${$.reasoning}`,concepts:["meta-governor","decision",$.action,...J.map((z)=>z.category)],type:"fact",files:[...K.filesChanged??[]]}),B=G}catch{}}if(mK(J,Z.minSeverityToLearn)){let G=[...new Set(J.flatMap((F)=>[F.category,F.severity]))],z=J.map((F)=>`[${F.severity}] ${F.category}: ${F.detail}`).join("; "),H=`Action "${$.action}" (score ${$.score.toFixed(2)}) after deviations: ${z}. Reasoning: ${$.reasoning}`;try{q={id:(await Q.saveLesson({content:H,context:`session:${K.sessionID} dir:${K.directory}`,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),tags:G})).id,title:`${$.action} after ${J[0]?.category??"recovery"}`,content:H,type:"pattern",concepts:G,confidence:Math.max(0.3,Math.min(0.8,Math.abs($.score))),files:[...K.filesChanged??[]],sessionID:K.sessionID}}catch{}}let W=[];if(B)W.push("decision saved");if(q)W.push("lesson saved");else if(!mK(J,Z.minSeverityToLearn))W.push("severity below threshold");if(!B&&!q&&!W.length)W.push("no saveable content");return{lessonSaved:q,decisionSaved:B,reason:W.join("; ")||"no action taken"}}zK();function gK(){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 tQ(K){let Q=gK(),{writeFile:X}=await import("node:fs/promises");await X(K,JSON.stringify(Q,null,2)+`
|
|
20
|
+
`,"utf-8")}var oQ={id:"omo-meta-governor",server:GK()},rX=oQ;export{tQ as writeSchemaFile,OQ as trimHistory,T as takeDecision,fQ as takeAnyDecision,ZK as stripJsoncComments,BK as storeDecision,$Q as stopWatches,o as score,XK as runMetaGovernor,a as runGraphSync,QQ as resetInitializedProjects,iQ as recordRecovery,t as predict,$K as parseJsonc,KK as observeAndLearn,b as logToFile,YK as loadProtocol,SQ as loadOrchestratorConfigFromSources,p as loadOrchestratorConfig,DK as loadMetaGovernorConfig,g as loadJsoncFile,hQ as isMetaGovernorEnabled,vQ as hasDecision,e as handleDecision,JK as getUserConfigPath,qK as getProjectConfigPath,gK as generateSchema,WQ as defaultTokenPredictorConfig,v as defaultScoringConfig,jK as defaultOrchestratorConfig,m as defaultDecisionHandlerConfig,y as defaultClosedLoopConfig,rX as default,x as deepMerge,GK as createMetaGovernorPlugin,RQ as countConsecutiveStops,mQ as clearAll,NK as calculateBurnRate,VK as buildSystemInjection,yK as buildDecisionContext,WK as auditToolCall,s as aggregateRead,d as DEFAULT_PROTOCOL_PATH};
|
|
21
21
|
|
|
22
|
-
//# debugId=
|
|
22
|
+
//# debugId=24A1BC51E07F8C3E64756E2164756E21
|
|
23
23
|
//# sourceMappingURL=index.js.map
|
package/dist/index.js.map
CHANGED
|
@@ -2,24 +2,24 @@
|
|
|
2
2
|
"version": 3,
|
|
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/file-logger.ts", "../src/plugin.ts", "../src/protocol-enforcer.ts", "../src/post-repair-recorder.ts", "../src/index.ts", "../src/generate-schema.ts"],
|
|
4
4
|
"sourcesContent": [
|
|
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
|
|
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 join(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
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",
|
|
10
10
|
"/**\n * MetaGovernor Decision Handler — PR 6 of 8.\n *\n * Takes a ScoringResult from the scoring engine and dispatches to the\n * appropriate action: continue, warn, escalate, or stop. This is the\n * \"executor\" that translates scoring decisions into concrete outcomes.\n *\n * Architecture invariants:\n * - Pure dispatch: no I/O, no MCP calls, no side effects\n * - DI pattern: backends injected via DecisionHandlerConfig\n * - Audit trail: every decision + outcome recorded in DecisionHistory\n * - Configurable: all thresholds and behaviors overridable\n */\n\nimport type {\n Decision,\n DecisionHandlerConfig,\n DecisionHandlerInput,\n DecisionHandlerOutput,\n ScoringResult,\n Evidence,\n Deviation,\n} from \"./types\"\n\n// ─── Default config ────────────────────────────────────────────────\n\nexport const defaultDecisionHandlerConfig = (): DecisionHandlerConfig => ({\n enabled: true,\n maxHistoryPerSession: 50,\n forceContinueAfterStops: 3,\n warnMessageTemplate:\n \"[MetaGovernor] Score {score}: {reasoning}. Evidence: {evidenceCount} signal(s).\",\n escalateMessageTemplate:\n \"[MetaGovernor] Escalating to {target}: {reasoning}\",\n stopMessageTemplate:\n \"[MetaGovernor] STOP — {reasoning}. Evidence: {evidenceCount} signal(s).\",\n})\n\n// ─── Helpers ────────────────────────────────────────────────────────\n\nfunction formatMessage(template: string, vars: Record<string, string>): string {\n let result = template\n for (const [key, value] of Object.entries(vars)) {\n result = result.replaceAll(`{${key}}`, value)\n }\n return result\n}\n\nfunction evidenceCount(evidence: readonly Evidence[]): number {\n return evidence.length\n}\n\n// ─── Public API ────────────────────────────────────────────────────\n\n/**\n * Core decision handler. Takes a ScoringResult and dispatches to the\n * appropriate action. Pure function — no side effects.\n *\n * @param input - ScoringResult + session context\n * @param config - Handler configuration\n * @returns DecisionHandlerOutput with action taken + message + history entry\n */\nexport function handleDecision(\n input: DecisionHandlerInput,\n config?: Partial<DecisionHandlerConfig>,\n): DecisionHandlerOutput {\n const resolvedConfig = { ...defaultDecisionHandlerConfig(), ...config }\n\n // Disabled = pass-through: always continue\n if (!resolvedConfig.enabled) {\n return {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision: input.scoringResult.decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: \"Decision handler disabled — pass-through continue\",\n },\n }\n }\n\n const decision = input.scoringResult.decision\n const score = decision.score\n const reasoning = decision.reasoning\n const evCount = evidenceCount(decision.evidence)\n const target = decision.shouldEscalateTo ?? resolvedConfig.defaultEscalationTarget ?? \"oracle\"\n\n // Paralysis override: force continue with warning\n if (input.scoringResult.paralysisOverride) {\n const message = formatMessage(\n resolvedConfig.warnMessageTemplate,\n {\n score: score.toFixed(3),\n reasoning: `Paralysis detected — forced continue. ${reasoning}`,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"continue\",\n message,\n historyEntry: {\n decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: `Paralysis override: ${reasoning}`,\n },\n }\n }\n\n // Dispatch by action\n switch (decision.action) {\n case \"continue\": {\n return {\n action: \"continue\",\n message: null,\n historyEntry: {\n decision,\n action: \"continue\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n\n case \"warn\": {\n const message = formatMessage(\n resolvedConfig.warnMessageTemplate,\n {\n score: score.toFixed(3),\n reasoning,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"warn\",\n message,\n historyEntry: {\n decision,\n action: \"warn\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n\n case \"escalate\": {\n const message = formatMessage(\n resolvedConfig.escalateMessageTemplate,\n {\n target,\n reasoning,\n },\n )\n\n return {\n action: \"escalate\",\n message,\n historyEntry: {\n decision,\n action: \"escalate\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning: `Escalate to ${target}: ${reasoning}`,\n },\n }\n }\n\n case \"stop\": {\n const message = formatMessage(\n resolvedConfig.stopMessageTemplate,\n {\n reasoning,\n evidenceCount: String(evCount),\n },\n )\n\n return {\n action: \"stop\",\n message,\n historyEntry: {\n decision,\n action: \"stop\",\n timestampISO: new Date().toISOString(),\n sessionID: input.sessionID,\n reasoning,\n },\n }\n }\n }\n}\n\n/**\n * Trim history to max size. Returns trimmed array + entries dropped count.\n */\nexport function trimHistory(\n history: readonly DecisionHandlerOutput[\"historyEntry\"][],\n maxSize: number,\n): { trimmed: DecisionHandlerOutput[\"historyEntry\"][]; dropped: number } {\n if (history.length <= maxSize) {\n return { trimmed: [...history], dropped: 0 }\n }\n const dropped = history.length - maxSize\n return { trimmed: history.slice(-maxSize), dropped }\n}\n\n/**\n * Count consecutive stops in history (most recent first).\n */\nexport function countConsecutiveStops(\n history: readonly DecisionHandlerOutput[\"historyEntry\"][],\n): number {\n let count = 0\n for (let i = history.length - 1; i >= 0; i--) {\n if (history[i]!.action === \"stop\") {\n count++\n } else {\n break\n }\n }\n return count\n}\n",
|
|
11
11
|
"/**\n * Closed-loop learning for MetaGovernor.\n *\n * PR 3 of 8. After every repair/action cycle, observeAndLearn() decides\n * whether to persist a lesson or decision record to agentmemory. Future\n * sessions retrieve these via aggregateRead() (PR 2) and factor them into\n * scoring (PR 5).\n *\n * Design:\n * - Pure function with DI backend (no side effects without backend).\n * - config.enabled=false → returns no-op with reason.\n * - Severity threshold: minSeverityToLearn filters what gets saved.\n * - Session cap: maxLessonsPerSession prevents flooding.\n * - Lessons go to agentmemory_memory_save (type: \"pattern\").\n * - Decisions go to agentmemory_memory_save (type: \"fact\").\n * - No file I/O, no MCP calls — just decision logic + DI write.\n */\n\nimport type {\n AgentmemoryWriteBackend,\n ClosedLoopConfig,\n Decision,\n Deviation,\n LearnFromOutcomeInput,\n LearnFromOutcomeOutput,\n LessonLearned,\n MemoryDecision,\n MemoryRead,\n} from \"./types\"\n\n/** Severity ordering for threshold comparison. */\nconst SEVERITY_ORDER: Record<string, number> = {\n leve: 0,\n media: 1,\n grave: 2,\n}\n\n/**\n * Generate a deterministic lesson ID from session + timestamp.\n */\nfunction generateLessonId(sessionID: string, timestamp: string): string {\n const hash = `${sessionID}-${timestamp}`.split(\"\").reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)\n return `L-${Math.abs(hash).toString(36)}`\n}\n\n/**\n * Generate a deterministic decision ID from session + action + timestamp.\n */\nfunction generateDecisionId(sessionID: string, action: string, timestamp: string): string {\n const hash = `${sessionID}-${action}-${timestamp}`.split(\"\").reduce((a, c) => ((a << 5) - a + c.charCodeAt(0)) | 0, 0)\n return `D-${Math.abs(hash).toString(36)}`\n}\n\n/**\n * Check if the decision's severity meets the threshold.\n */\nfunction severityMeetsThreshold(\n deviations: readonly Deviation[],\n threshold: ClosedLoopConfig[\"minSeverityToLearn\"]\n): boolean {\n const minOrder = SEVERITY_ORDER[threshold] ?? 0\n return deviations.some((d) => (SEVERITY_ORDER[d.severity] ?? 0) >= minOrder)\n}\n\n/**\n * Extract concepts from deviations for the lesson.\n */\nfunction extractConcepts(deviations: readonly Deviation[]): string[] {\n const concepts = new Set<string>()\n for (const d of deviations) {\n concepts.add(d.category)\n concepts.add(d.severity)\n }\n return [...concepts]\n}\n\n/**\n * Build the lesson content string from a decision and its deviations.\n */\nfunction buildLessonContent(decision: Decision, deviations: readonly Deviation[]): string {\n const deviationSummary = deviations\n .map((d) => `[${d.severity}] ${d.category}: ${d.detail}`)\n .join(\"; \")\n return `Action \"${decision.action}\" (score ${decision.score.toFixed(2)}) after deviations: ${deviationSummary}. Reasoning: ${decision.reasoning}`\n}\n\n/**\n * Core learning function. Decides whether to save a lesson and/or decision\n * to agentmemory based on the outcome of a repair/action cycle.\n *\n * Returns LearnFromOutcomeOutput describing what was saved (or why nothing was saved).\n */\nexport async function observeAndLearn(\n input: LearnFromOutcomeInput,\n backend: AgentmemoryWriteBackend\n): Promise<LearnFromOutcomeOutput> {\n const { decision, config, sessionID, directory, filesChanged } = input\n const now = new Date().toISOString()\n\n // Config disabled → no-op\n if (!config.enabled) {\n return { lessonSaved: null, decisionSaved: null, reason: \"closed-loop learning disabled\" }\n }\n\n // No deviations → nothing to learn from\n if (decision.evidence.length === 0 && decision.action === \"continue\") {\n return { lessonSaved: null, decisionSaved: null, reason: \"no deviations to learn from\" }\n }\n\n let lessonSaved: LessonLearned | null = null\n let decisionSaved: MemoryDecision | null = null\n\n // Save decision record if enabled\n if (config.saveDecisions) {\n const decisionRecord: MemoryDecision = {\n id: generateDecisionId(sessionID, decision.action, now),\n timestampISO: now,\n action: decision.action,\n score: decision.score,\n reasoning: decision.reasoning,\n sessionID,\n directory,\n deviations: decision.evidence\n .filter((e) => e.source === \"deviation-detector\")\n .map((e) => ({\n severity: \"media\" as const,\n category: e.source,\n detail: e.value,\n })),\n }\n\n try {\n await backend.saveMemory({\n content: `Decision: ${decision.action} (score ${decision.score.toFixed(2)}). ${decision.reasoning}`,\n concepts: [\"meta-governor\", \"decision\", decision.action],\n type: \"fact\",\n files: [...filesChanged],\n })\n decisionSaved = decisionRecord\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Save lesson if deviations meet severity threshold\n const deviationsFromEvidence = decision.evidence\n .filter((e) => e.source === \"deviation-detector\")\n .map<Deviation>((e) => ({\n severity: \"media\",\n category: e.source,\n detail: e.value,\n }))\n\n if (severityMeetsThreshold(deviationsFromEvidence, config.minSeverityToLearn)) {\n const concepts = extractConcepts(deviationsFromEvidence)\n const content = buildLessonContent(decision, deviationsFromEvidence)\n\n try {\n const result = await backend.saveLesson({\n content,\n context: `session:${sessionID} dir:${directory}`,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n tags: concepts,\n })\n\n lessonSaved = {\n id: result.id,\n title: `${decision.action} after ${deviationsFromEvidence[0]?.category ?? \"deviation\"}`,\n content,\n type: \"pattern\",\n concepts,\n confidence: Math.max(0.3, Math.min(0.8, Math.abs(decision.score))),\n files: [...filesChanged],\n sessionID,\n }\n } catch {\n // Backend failure is non-fatal — degrade silently\n }\n }\n\n // Determine reason\n const reasons: string[] = []\n if (decisionSaved) reasons.push(\"decision saved\")\n if (lessonSaved) reasons.push(\"lesson saved\")\n if (!decisionSaved && !lessonSaved) {\n if (!severityMeetsThreshold(deviationsFromEvidence, config.minSeverityToLearn)) {\n reasons.push(\"severity below threshold\")\n } else {\n reasons.push(\"no saveable content\")\n }\n }\n\n return {\n lessonSaved,\n decisionSaved,\n reason: reasons.join(\"; \") || \"no action taken\",\n }\n}\n\n/**\n * Helper: create a default ClosedLoopConfig.\n */\nexport function defaultClosedLoopConfig(): ClosedLoopConfig {\n return {\n enabled: true,\n minSeverityToLearn: \"media\",\n maxLessonsPerSession: 20,\n saveDecisions: true,\n }\n}\n\nexport { SEVERITY_ORDER }\n",
|
|
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: \"
|
|
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
|
|
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 // v0.10.0: default is \"stop\" — warnings are advisory and must not auto-trigger\n // message injection (which would create new LLM turns and trap the agent\n // in an instruction loop). Users opt UP to \"warn\" explicitly.\n mode: \"silent\" as const,\n includeDecisionHistory: true,\n maxHistoryMessages: 5,\n minActionForMessage: \"stop\" as const,\n // v0.10.0: rate-limit interventions to break instruction loops.\n maxInterventionsPerSession: 3,\n // v0.10.0: stop injecting after the agent signals <promise>DONE</promise>\n // AND Oracle has verified the work.\n respectDoneSignal: true,\n },\n protocolEnforcement: {\nenabled: false,\npath: undefined,\ninjectIntoSystem: false,\nauditToolCalls: 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
|
+
"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 /** v0.10.0: rate-limit interventions to break instruction loops. */\n maxInterventionsPerSession?: number\n /** v0.10.0: stop injecting after <promise>DONE</promise> + Oracle verified. */\n respectDoneSignal?: boolean\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 // v0.10.0: default is \"stop\" — see orchestrator.ts for rationale.\n minActionForMessage: full.intervention?.minActionForMessage ?? \"stop\",\n // v0.10.0: rate-limit interventions to break instruction loops.\n maxInterventionsPerSession:\n full.intervention?.maxInterventionsPerSession ?? 3,\n // v0.10.0: stop injecting after the agent signals <promise>DONE</promise>\n // AND Oracle has verified the work.\n respectDoneSignal: full.intervention?.respectDoneSignal ?? true,\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
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
|
-
"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 { statSync } from \"node:fs\"\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 // Detect project graph directories at load time\n const cwd = process.cwd()\n const projectHasCodegraph = (() => {\n try { return statSync(`${cwd}/.codegraph`).isDirectory() } catch { return false }\n })()\n const projectHasGraphify = (() => {\n try { return statSync(`${cwd}/graphify-out`).isDirectory() } catch { return false }\n })()\n\n // Initialise graphSync when the module loads\n const graphSyncEnabled = config.graphSync?.enabled !== false\n if (graphSyncEnabled) {\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 // Log startup so the user can see the plugin is loaded\n logToFile(\"info\", \"MetaGovernor plugin loaded\", {\n version: \"0.9.3\",\n cwd,\n projectHasCodegraph,\n projectHasGraphify,\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: string) => {\n systemInjection = buildSystemInjection(text)\n }).catch((err: unknown) => {\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\n const pendingViolations = new Map<string, string[]>()\n\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: projectHasCodegraph,\n hasGraphifyDir: projectHasGraphify,\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 logToFile(\"warn\", `protocol violations on tool ${toolInput.tool}`, violations)\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\": 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: string) => 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\n // - System transform (protocol injection + system intervention mode)\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",
|
|
16
|
+
"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, takeDecision } from \"./decision-store\"\nimport { logToFile } from \"./file-logger\"\nimport { statSync } from \"node:fs\"\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 // Detect project graph directories at load time\n const cwd = process.cwd()\n const projectHasCodegraph = (() => {\n try { return statSync(`${cwd}/.codegraph`).isDirectory() } catch { return false }\n })()\n const projectHasGraphify = (() => {\n try { return statSync(`${cwd}/graphify-out`).isDirectory() } catch { return false }\n })()\n\n // Initialise graphSync when the module loads\n const graphSyncEnabled = config.graphSync?.enabled !== false\n if (graphSyncEnabled) {\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 // Log startup so the user can see the plugin is loaded\n logToFile(\"info\", \"MetaGovernor plugin loaded\", {\n version: \"0.10.0\",\n cwd,\n projectHasCodegraph,\n projectHasGraphify,\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: string) => {\n systemInjection = buildSystemInjection(text)\n }).catch((err: unknown) => {\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 (v0.10.0: adds DONE tracking + intervention cap)\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 taskDoneSignal: boolean\n interventionCount: number\n interventionDisabled: boolean\n }\n const auditSessions = new Map<string, AuditState>()\n\n // Pending protocol violations queue\n const pendingViolations = new Map<string, string[]>()\n\n // v0.10.0: detect `<promise>DONE</promise>` (with optional !) in any\n // tool output / agent output string. Sisyphus emits this to mark the\n // user's task as verifiably complete.\n function detectDoneSignal(text: string | undefined | null): boolean {\n if (typeof text !== \"string\" || text.length === 0) return false\n return /<promise>\\s*DONE!?\\s*<\\/promise>/i.test(text)\n }\n\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: projectHasCodegraph,\n hasGraphifyDir: projectHasGraphify,\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 taskDoneSignal: false,\n interventionCount: 0,\n interventionDisabled: 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 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 logToFile(\"warn\", `protocol violations on tool ${toolInput.tool}`, violations)\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\": 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: string) => 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 // v0.10.0: detect <promise>DONE</promise> in tool output\n if (!sessionState.taskDoneSignal) {\n if (\n detectDoneSignal(toolOutput.output) ||\n detectDoneSignal(toolInput.args as string | undefined)\n ) {\n sessionState.taskDoneSignal = true\n logToFile(\n \"info\",\n `task_done_signal detected for session ${toolInput.sessionID}`,\n )\n }\n }\n }\n\n // v0.10.0: hard break — if intervention already disabled, skip orchestrator\n if (sessionState?.interventionDisabled) {\n return\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: sessionState?.oracleInvoked ?? false,\n noProgress: false,\n filesChanged: sessionState?.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\" && sessionState) {\n const decision = output.decision\n\n // v0.10.0: DONE + Oracle verified → stop intervening\n if (\n mergedConfig.intervention.respectDoneSignal &&\n sessionState.taskDoneSignal &&\n sessionState.oracleInvoked\n ) {\n sessionState.interventionDisabled = true\n logToFile(\n \"info\",\n `task verified (DONE + Oracle): disabling intervention for session ${toolInput.sessionID}`,\n )\n takeDecision(toolInput.sessionID)\n return\n }\n\n if (\n decision.action !== \"continue\" &&\n meetsMinAction(\n decision.action,\n mergedConfig.intervention.minActionForMessage,\n )\n ) {\n // v0.10.0: rate-limit interventions\n const cap = Math.max(\n 0,\n mergedConfig.intervention.maxInterventionsPerSession ?? 0,\n )\n if (cap > 0 && sessionState.interventionCount >= cap) {\n sessionState.interventionDisabled = true\n logToFile(\n \"warn\",\n `intervention cap (${cap}) reached for session ${toolInput.sessionID}; disabling further intervention`,\n )\n takeDecision(toolInput.sessionID)\n return\n }\n sessionState.interventionCount++\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 // v0.10.0: derive current sessionID from the LAST message.\n // MUST scope decisions to the current session; never takeAnyDecision().\n // If we cannot derive a sessionID, the safe default is no injection.\n const lastMsg = output.messages[output.messages.length - 1] as\n | { info?: { sessionID?: string } }\n | undefined\n const currentSessionID = lastMsg?.info?.sessionID\n if (!currentSessionID) {\n return\n }\n\n // v0.10.0: respect per-session intervention disable\n const state = auditSessions.get(currentSessionID)\n if (state?.interventionDisabled) {\n takeDecision(currentSessionID)\n return\n }\n\n // 1. Inject pending protocol violations so the model sees them\n if (pendingViolations.has(currentSessionID)) {\n const violations = pendingViolations.get(currentSessionID)!\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(currentSessionID)\n logToFile(\"info\", `injected ${violations.length} violation(s) to model`)\n }\n }\n\n // 2. Inject MetaGovernor decision — SCOPED to current session\n const decision = takeDecision(currentSessionID)\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 // v0.10.0: defense-in-depth cap check before push.\n // State may not exist yet (no tool.execute.before ran); lazily create it.\n let curState = state ?? auditSessions.get(currentSessionID)\n if (!curState) {\n curState = {\n memoryToolsUsed: [],\n hasCodegraphDir: projectHasCodegraph,\n hasGraphifyDir: projectHasGraphify,\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 taskDoneSignal: false,\n interventionCount: 0,\n interventionDisabled: false,\n }\n auditSessions.set(currentSessionID, curState)\n }\n const cap = Math.max(\n 0,\n mergedConfig.intervention.maxInterventionsPerSession ?? 0,\n )\n if (cap > 0 && curState.interventionCount >= cap) {\n curState.interventionDisabled = true\n return\n }\n curState.interventionCount++\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\n // - System transform (protocol injection + system intervention mode)\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 // v0.10.0: also respect per-session intervention disable here\n const state = auditSessions.get(transformInput.sessionID)\n if (state?.interventionDisabled) {\n takeDecision(transformInput.sessionID)\n return\n }\n const decision = takeDecision(transformInput.sessionID)\n if (decision && decision.action !== \"continue\" && decision.message) {\n if (meetsMinAction(decision.action, mergedConfig.intervention.minActionForMessage)) {\n if (state) {\n const cap = Math.max(\n 0,\n mergedConfig.intervention.maxInterventionsPerSession ?? 0,\n )\n if (cap > 0 && state.interventionCount >= cap) {\n state.interventionDisabled = true\n return\n }\n state.interventionCount++\n }\n output.system.push(\n \"\\n[MetaGovernor Intervention]\",\n decision.message,\n \"---\",\n )\n }\n }\n }\n },\n }\n }\n\n return plugin\n}",
|
|
17
17
|
"/**\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",
|
|
18
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",
|
|
19
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",
|
|
20
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"
|
|
21
21
|
],
|
|
22
|
-
"mappings": "udAcA,mBAAS,aAAU,0BACnB,kBAAS,mBACT,kBAAS,iBAmBF,SAAS,EAAkB,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,EAAO,KAAK,CAAE,EACd,IAIF,IAAI,EAAU,EAAO,KAAK,EAAE,EAE5B,QAAS,E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,KAAM,SACN,YAAa,+CACf,EACA,QAAS,CACP,KAAM,UACN,YAAa,8DACb,QAAS,EACX,EACA,SAAU,CACR,KAAM,SACN,YAAa,kCACb,qBAAsB,GACtB,WAAY,CACV,qBAAsB,CACpB,KAAM,UACN,YAAa,iEACb,QAAS,GACT,QAAS,CACX,EACA,wBAAyB,CACvB,KAAM,UACN,YAAa,sDACb,QAAS,EACT,QAAS,CACX,CACF,CACF,EACA,OAAQ,CACN,KAAM,SACN,YAAa,mCACb,qBAAsB,GACtB,WAAY,CACV,qBAAsB,CACpB,KAAM,UACN,YAAa,mDACb,QAAS,KACT,QAAS,GACX,EACA,sBAAuB,CACrB,KAAM,UACN,YAAa,qDACb,QAAS,KACT,QAAS,GACX,EACA,sBAAuB,CACrB,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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,CACF,EACA,OAAQ,CACN,KAAM,SACN,YAAa,mCACb,qBAAsB,GACtB,WAAY,CACV,qBAAsB,CACpB,KAAM,UACN,YAAa,mDACb,QAAS,KACT,QAAS,GACX,EACA,sBAAuB,CACrB,KAAM,UACN,YAAa,qDACb,QAAS,KACT,QAAS,GACX,EACA,sBAAuB,CACrB,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": "24A1BC51E07F8C3E64756E2164756E21",
|
|
24
24
|
"names": []
|
|
25
25
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -360,6 +360,19 @@ export interface InterventionConfig {
|
|
|
360
360
|
readonly includeDecisionHistory: boolean;
|
|
361
361
|
/** Max number of recent decision history entries to include. */
|
|
362
362
|
readonly maxHistoryMessages: number;
|
|
363
|
+
/**
|
|
364
|
+
* Max number of times a single session may receive an intervention
|
|
365
|
+
* before the plugin auto-disables intervention for that session.
|
|
366
|
+
* v0.10.0: prevents infinite instruction loops. Default: 3.
|
|
367
|
+
*/
|
|
368
|
+
readonly maxInterventionsPerSession: number;
|
|
369
|
+
/**
|
|
370
|
+
* When true, the plugin stops injecting the moment the agent emits a
|
|
371
|
+
* `<promise>DONE</promise>` signal AND Oracle has verified the work.
|
|
372
|
+
* v0.10.0: prevents the plugin from continuing to "guide" the agent
|
|
373
|
+
* after the user's task is verifiably complete. Default: true.
|
|
374
|
+
*/
|
|
375
|
+
readonly respectDoneSignal: boolean;
|
|
363
376
|
}
|
|
364
377
|
/**
|
|
365
378
|
* Configuration for Sisyphus protocol enforcement.
|
package/package.json
CHANGED