This repository was archived by the owner on Aug 20, 2026. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathflow-next-ralph-guard.ts
More file actions
255 lines (224 loc) · 8.58 KB
/
Copy pathflow-next-ralph-guard.ts
File metadata and controls
255 lines (224 loc) · 8.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
import type { Hooks, PluginInput } from "@opencode-ai/plugin"
import fs from "fs"
import path from "path"
const STATE_DIR = "/tmp"
const DEFAULT_REVIEWER = "opencode-reviewer"
const RALPH_SYSTEM = [
"Ralph mode: unattended autonomous execution.",
"Never stop after a status-only message.",
"Always use tools to perform actions.",
"Do not ask questions.",
"If you cannot proceed, output exactly: <promise>RETRY</promise> and stop.",
].join(" ")
type CallInfo = {
tool: string
command?: string
subagent_type?: string
}
type State = {
chats_sent: number
chat_send_succeeded: boolean
opencode_review_succeeded: boolean
last_verdict?: string
flowctl_done_called: string[]
calls: Record<string, CallInfo>
}
function isRalph() {
return process.env.FLOW_RALPH === "1"
}
function statePath(sessionID: string) {
return path.join(STATE_DIR, `ralph-guard-${sessionID}.json`)
}
function loadState(sessionID: string): State {
const file = statePath(sessionID)
if (fs.existsSync(file)) {
try {
const raw = JSON.parse(fs.readFileSync(file, "utf8"))
return {
chats_sent: raw.chats_sent ?? 0,
chat_send_succeeded: raw.chat_send_succeeded ?? false,
opencode_review_succeeded: raw.opencode_review_succeeded ?? false,
last_verdict: raw.last_verdict,
flowctl_done_called: Array.isArray(raw.flowctl_done_called) ? raw.flowctl_done_called : [],
calls: raw.calls ?? {},
}
} catch {}
}
return {
chats_sent: 0,
chat_send_succeeded: false,
opencode_review_succeeded: false,
flowctl_done_called: [],
calls: {},
}
}
function saveState(sessionID: string, state: State) {
fs.writeFileSync(statePath(sessionID), JSON.stringify(state))
}
function block(message: string): never {
throw new Error(message)
}
function blockIfChatCommand(command: string) {
if (/(^|\s)\/?flow-next:/.test(command)) {
block("BLOCKED: Do not run /flow-next:* as a shell command. Use the skill/tool workflow instead.")
}
}
function blockIfQuestionText(text: string) {
const normalized = text.toLowerCase()
if (
normalized.includes("want me to proceed") ||
normalized.includes("should i proceed") ||
normalized.includes("should i continue") ||
normalized.includes("do you want me to proceed")
) {
block("BLOCKED: Ralph is unattended. Do not ask for confirmation.")
}
}
function isReceiptWrite(command: string, receiptPath: string) {
const dir = path.dirname(receiptPath)
return (
command.includes(receiptPath) ||
new RegExp(`>\\s*['\"]?${dir.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`).test(command) ||
/cat\s*>\s*.*receipt/i.test(command) ||
/receipts\/.*\.json/.test(command)
)
}
export default async function (_input: PluginInput): Promise<Hooks> {
const allowedReviewer = process.env.FLOW_RALPH_REVIEWER_AGENT || DEFAULT_REVIEWER
return {
"experimental.chat.system.transform": async (_input, output) => {
if (!isRalph()) return
output.system.push(RALPH_SYSTEM)
},
"tool.execute.before": async (input, output) => {
if (!isRalph()) return output
const sessionID = input.sessionID
const state = loadState(sessionID)
const callID = input.callID
if (input.tool === "bash") {
const command = String(output.args?.command ?? "")
blockIfChatCommand(command)
state.calls[callID] = { tool: "bash", command }
if (command.includes("chat-send")) {
if (/chat-send.*--json/.test(command)) {
block("BLOCKED: Do not use --json with chat-send. It suppresses the review text.")
}
if (command.includes("--new-chat") && state.chats_sent > 0) {
block("BLOCKED: Do not use --new-chat for re-reviews. Stay in the same chat.")
}
}
if (command.includes("rp-cli")) {
const isRpCheck =
/\bwhich\s+rp-cli\b/.test(command) ||
/\bcommand\s+-v\s+rp-cli\b/.test(command) ||
/-x\s+\/(opt\/homebrew|usr\/local)\/bin\/rp-cli\b/.test(command)
if (!isRpCheck) {
block("BLOCKED: Do not call rp-cli directly. Use flowctl rp wrappers.")
}
}
if (command.includes("setup-review")) {
if (!/--repo-root/.test(command)) {
block("BLOCKED: setup-review requires --repo-root.")
}
if (!/--summary/.test(command)) {
block("BLOCKED: setup-review requires --summary.")
}
}
if (command.includes("select-add")) {
if (!/--window/.test(command) || !/--tab/.test(command)) {
block("BLOCKED: select-add requires --window and --tab.")
}
}
if (/\bdone\b/.test(command) && (command.includes("flowctl") || command.includes("FLOWCTL"))) {
if (!/--help|-h/.test(command)) {
if (!/--evidence-json|--evidence/.test(command)) {
block("BLOCKED: flowctl done requires --evidence-json.")
}
if (!/--summary-file|--summary/.test(command)) {
block("BLOCKED: flowctl done requires --summary-file.")
}
}
}
const receiptPath = process.env.REVIEW_RECEIPT_PATH || ""
if (receiptPath && isReceiptWrite(command, receiptPath)) {
if (!state.chat_send_succeeded && !state.opencode_review_succeeded) {
block(
"BLOCKED: Cannot write receipt before review completes. Run review and receive verdict first.",
)
}
if (!/"id"\s*:/.test(command) && !/\'id\'\s*:/.test(command)) {
block("BLOCKED: Receipt JSON missing required id field. Copy the exact template.")
}
if (command.includes("impl_review")) {
const match =
command.match(/"id"\s*:\s*"([^"]+)"/) || command.match(/'id'\s*:\s*'([^']+)'/)
const taskId = match?.[1]
if (taskId && !state.flowctl_done_called.includes(taskId)) {
block(`BLOCKED: Cannot write impl receipt for ${taskId} - flowctl done was not called.`)
}
}
}
}
if (input.tool === "task") {
const subagent = String(output.args?.subagent_type ?? "")
state.calls[callID] = { tool: "task", subagent_type: subagent }
if (subagent !== allowedReviewer) {
block(
`BLOCKED: Ralph mode only allows task tool for reviewer '${allowedReviewer}'. ` +
"Use the skill tool (flow-next-opencode-plan-review / flow-next-opencode-work) and do NOT spawn generic tasks.",
)
}
}
saveState(sessionID, state)
return output
},
"tool.execute.after": async (input, output) => {
if (!isRalph()) return output
const sessionID = input.sessionID
const state = loadState(sessionID)
const callID = input.callID
const call = state.calls[callID]
const outputText = String(output.output ?? "")
blockIfQuestionText(outputText)
if (input.tool === "bash" && call?.command) {
const command = call.command
if (command.includes("chat-send")) {
const hasVerdict = /<verdict>(SHIP|NEEDS_WORK|MAJOR_RETHINK)<\/verdict>/.test(outputText)
const hasChat = outputText.includes("Chat Send") && !outputText.includes('"chat": null')
if (hasVerdict || hasChat) {
state.chats_sent = (state.chats_sent || 0) + 1
state.chat_send_succeeded = true
}
if (outputText.includes('"chat": null')) {
state.chat_send_succeeded = false
}
}
if (/\bdone\b/.test(command) && (command.includes("flowctl") || command.includes("FLOWCTL"))) {
const match = command.match(/\bdone\s+([a-zA-Z0-9][a-zA-Z0-9._-]*)/)
if (match) {
const taskId = match[1]
const exit = output.metadata?.exit
if (exit === 0) {
if (!state.flowctl_done_called.includes(taskId)) state.flowctl_done_called.push(taskId)
}
}
}
const receiptPath = process.env.REVIEW_RECEIPT_PATH || ""
if (receiptPath && command.includes(receiptPath) && command.includes(">")) {
state.chat_send_succeeded = false
state.opencode_review_succeeded = false
}
}
if (input.tool === "task" && call?.subagent_type === allowedReviewer) {
const verdict = outputText.match(/<verdict>(SHIP|NEEDS_WORK|MAJOR_RETHINK)<\/verdict>/)
if (verdict) {
state.opencode_review_succeeded = true
state.last_verdict = verdict[1]
}
}
delete state.calls[callID]
saveState(sessionID, state)
return output
},
}
}