-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathreflection-3.ts
More file actions
1962 lines (1732 loc) · 71.9 KB
/
reflection-3.ts
File metadata and controls
1962 lines (1732 loc) · 71.9 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
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Reflection-3 Plugin for OpenCode
*
* Consolidated reflection layer that combines self-assessment with workflow checks.
* Uses a dynamic prompt (task + workflow requirements) unless reflection.md overrides it.
* Ensures tests/build/PR/CI checks are verified before completion.
*/
import type { Plugin } from "@opencode-ai/plugin"
import { readFile, writeFile, mkdir, stat, appendFile } from "fs/promises"
import { join } from "path"
import { homedir } from "os"
// Lazy Sentry helper — reports errors without crashing if @sentry/node is unavailable
async function reportError(err: unknown, context?: Record<string, string>): Promise<void> {
try {
const Sentry = await import("@sentry/node")
if (!Sentry.isInitialized()) return
Sentry.captureException(err, context ? { tags: context } : undefined)
} catch {}
}
const SELF_ASSESSMENT_MARKER = "## Reflection-3 Self-Assessment"
const FEEDBACK_MARKER = "## Reflection-3:"
const MAX_ATTEMPTS = 3
const JUDGE_BLOCKED_PATTERNS = [
/\bhaiku\b/i,
/\bmini\b/i,
/\bnano\b/i,
/\bflash\b/i,
/\bgpt-3\.5\b/i,
/\bllama-3\.1-8b\b/i,
/\bmixtral-8x7b\b/i,
]
const PLANNING_LOOP_MIN_TOOL_CALLS = 8
const PLANNING_LOOP_WRITE_RATIO_THRESHOLD = 0.1
const ACTION_LOOP_MIN_COMMANDS = 4
const ACTION_LOOP_REPETITION_THRESHOLD = 0.6
type TaskType = "coding" | "docs" | "research" | "ops" | "other"
type AgentMode = "plan" | "build" | "unknown"
type RoutingCategory = "backend" | "architecture" | "frontend" | "default"
interface WorkflowRequirements {
requiresTests: boolean
requiresBuild: boolean
requiresPR: boolean
requiresCI: boolean
requiresLocalTests: boolean
requiresLocalTestsEvidence: boolean
}
interface TaskContext extends WorkflowRequirements {
taskSummary: string
taskType: TaskType
agentMode: AgentMode
humanMessages: string[]
toolsSummary: string
detectedSignals: string[]
recentCommands: string[]
pushedToDefaultBranch: boolean
}
interface SelfAssessment {
task_summary?: string
task_type?: string
status?: "complete" | "in_progress" | "blocked" | "stuck" | "waiting_for_user"
confidence?: number
evidence?: {
tests?: {
ran?: boolean
results?: "pass" | "fail" | "unknown"
ran_after_changes?: boolean
commands?: string[]
skipped?: boolean
skip_reason?: string
}
build?: {
ran?: boolean
results?: "pass" | "fail" | "unknown"
}
pr?: {
created?: boolean
url?: string
ci_status?: "pass" | "fail" | "unknown"
checked?: boolean
}
}
remaining_work?: string[]
next_steps?: string[]
needs_user_action?: string[]
stuck?: boolean
alternate_approach?: string
}
interface ReflectionAnalysis {
complete: boolean
shouldContinue: boolean
reason: string
missing: string[]
nextActions: string[]
requiresHumanAction: boolean
severity: "NONE" | "LOW" | "MEDIUM" | "HIGH" | "BLOCKER"
}
interface RoutingConfig {
enabled: boolean
models: Record<RoutingCategory, string>
}
interface ModelSpecParts {
providerID: string
modelID: string
}
const DEFAULT_ROUTING_CONFIG: RoutingConfig = {
enabled: false,
models: {
backend: "",
architecture: "",
frontend: "",
default: ""
}
}
const JUDGE_RESPONSE_TIMEOUT = 120_000
const POLL_INTERVAL = 2_000
const ABORT_COOLDOWN = 10_000
const ABORT_RACE_DELAY = 1_500 // ms to wait for session.error to arrive before running reflection
const REFLECTION_CONFIG_PATH = join(homedir(), ".config", "opencode", "reflection.yaml")
// Debug logging — writes to .reflection/debug.log when REFLECTION_DEBUG=1.
// Never write to stdout/stderr — it corrupts the OpenCode TUI.
const REFLECTION_DEBUG = process.env.REFLECTION_DEBUG === "1"
// Module-level debug function, initially a no-op.
// Replaced with a file-backed logger once the plugin initializes with a directory.
let debug: (...args: any[]) => void = () => {}
function initDebugLogger(directory: string) {
if (!REFLECTION_DEBUG) return
const logPath = join(directory, ".reflection", "debug.log")
let dirEnsured = false
debug = (...args: any[]) => {
const msg = args.map(a => typeof a === "string" ? a : JSON.stringify(a)).join(" ")
const ts = new Date().toISOString()
const line = `[${ts}] [Reflection3] ${msg}\n`
// Fire-and-forget: do not await to avoid slowing down the plugin
;(async () => {
if (!dirEnsured) {
try { await mkdir(join(directory, ".reflection"), { recursive: true }) } catch {}
dirEnsured = true
}
try { await appendFile(logPath, line) } catch {}
})()
}
}
function isBlockedJudgeModel(modelSpec: string): boolean {
const normalized = modelSpec.toLowerCase()
return JUDGE_BLOCKED_PATTERNS.some((pattern) => pattern.test(normalized))
}
function stripJsonComments(input: string): string {
return input
.replace(/\/\*[^]*?\*\//g, "")
.replace(/(^|\s)\/\/.*$/gm, "$1")
}
async function loadPreferredModelSpec(directory: string): Promise<string | null> {
const candidates = [
join(directory, "opencode.json"),
join(directory, ".opencode", "opencode.json"),
join(homedir(), ".config", "opencode", "opencode.json"),
join(directory, "opencode.jsonc"),
join(directory, ".opencode", "opencode.jsonc"),
join(homedir(), ".config", "opencode", "opencode.jsonc"),
]
for (const path of candidates) {
try {
const content = await readFile(path, "utf-8")
const parsed = JSON.parse(stripJsonComments(content))
const model = parsed?.model
if (typeof model === "string" && model.trim()) {
return model.trim()
}
} catch {}
}
return null
}
async function loadReflectionPrompt(directory: string): Promise<string | null> {
const candidates = [".reflection.md", ".reflection.MD", "reflection.md", "reflection.MD"]
for (const name of candidates) {
try {
const reflectionPath = join(directory, name)
const customPrompt = await readFile(reflectionPath, "utf-8")
debug("Loaded custom prompt from", name)
return customPrompt.trim()
} catch {}
}
return null
}
function buildToolReflectionGuidanceSection(toolReflectionPrompt: string | null): string {
if (!toolReflectionPrompt) return ""
return `\n## Tool Reflection Guidance\n${toolReflectionPrompt.slice(0, 4000)}\n`
}
function resolveReflectionPrompt(
filePrompt: string | null,
toolReflectionPrompt: string | null,
defaultPrompt: string
): { prompt: string; source: "file" | "tool" | "default"; effectiveToolReflectionPrompt: string | null } {
if (filePrompt) {
return {
prompt: filePrompt,
source: "file",
effectiveToolReflectionPrompt: null
}
}
if (toolReflectionPrompt) {
return {
prompt: `${defaultPrompt}${buildToolReflectionGuidanceSection(toolReflectionPrompt)}`,
source: "tool",
effectiveToolReflectionPrompt: toolReflectionPrompt
}
}
return {
prompt: defaultPrompt,
source: "default",
effectiveToolReflectionPrompt: null
}
}
async function getAgentsFile(directory: string): Promise<string> {
for (const name of ["AGENTS.md", ".opencode/AGENTS.md", "agents.md"]) {
try {
const content = await readFile(join(directory, name), "utf-8")
return content
} catch {}
}
return ""
}
function getMessageSignature(msg: any): string {
if (msg.id) return msg.id
const role = msg.info?.role || "unknown"
const time = msg.info?.time?.start || 0
const textPart = msg.parts?.find((p: any) => p.type === "text")?.text?.slice(0, 20) || ""
return `${role}:${time}:${textPart}`
}
export function detectPlanningLoop(messages: any[]): {
detected: boolean
readCount: number
writeCount: number
totalTools: number
} {
if (!Array.isArray(messages)) {
return { detected: false, readCount: 0, writeCount: 0, totalTools: 0 }
}
let readCount = 0
let writeCount = 0
let totalTools = 0
for (const msg of messages) {
if (msg.info?.role !== "assistant") continue
for (const part of msg.parts || []) {
if (part.type !== "tool") continue
totalTools++
const toolName = (part.tool || "").toString().toLowerCase()
const input = part.state?.input || {}
if (["edit", "write", "apply_patch", "github_create_or_update_file", "github_push_files", "github_delete_file", "github_create_pull_request", "github_update_pull_request"].includes(toolName)) {
writeCount++
continue
}
if (toolName === "bash") {
const cmd = (input.command || input.cmd || "").toString()
if (/^\s*(npm|yarn|pnpm)\s+(run\s+)?(build|test|lint|fmt|format)\b/i.test(cmd) || /^\s*git\s+(add|commit|push|checkout|switch|merge|rebase)\b/i.test(cmd) || /^\s*(mkdir|rm|mv|cp)\b/i.test(cmd)) {
writeCount++
} else if (/^\s*git\s+(status|log|diff|show|branch|remote|tag)\b/i.test(cmd) || /^\s*(ls|cat|head|tail|find|grep|rg|wc|file)\b/i.test(cmd)) {
readCount++
}
continue
}
if (["read", "glob", "grep", "todowrite", "task", "webfetch", "knowledge-graph_search", "knowledge-graph_read", "knowledge-graph_open"].some((name) => toolName.startsWith(name)) || toolName.startsWith("context7_")) {
readCount++
}
}
}
const detected =
totalTools >= PLANNING_LOOP_MIN_TOOL_CALLS &&
(writeCount === 0 || writeCount / totalTools < PLANNING_LOOP_WRITE_RATIO_THRESHOLD)
return { detected, readCount, writeCount, totalTools }
}
export function shouldApplyPlanningLoop(taskType: TaskType, loopDetected: boolean): boolean {
if (!loopDetected) return false
return taskType === "coding"
}
/**
* Detects when the agent is repeating the same commands/actions without progress.
* Unlike detectPlanningLoop (read-heavy without writes), this catches action loops
* where the agent IS making write-like operations but repeating the same ones.
* Example: repeatedly re-deploying and re-running the same failing evaluation.
*/
export function detectActionLoop(messages: any[]): {
detected: boolean
repeatedCommands: string[]
totalCommands: number
} {
if (!Array.isArray(messages)) {
return { detected: false, repeatedCommands: [], totalCommands: 0 }
}
const commands: string[] = []
for (const msg of messages) {
if (msg.info?.role !== "assistant") continue
for (const part of msg.parts || []) {
if (part.type !== "tool") continue
const toolName = (part.tool || "").toString().toLowerCase()
const input = part.state?.input || {}
if (toolName === "bash") {
const cmd = (input.command || input.cmd || "").toString().trim()
if (cmd) {
// Normalize: collapse whitespace and remove trailing timestamps/IDs
const normalized = cmd.replace(/\s+/g, " ").replace(/\d{10,}/g, "TIMESTAMP").toLowerCase()
commands.push(normalized)
}
} else if (toolName !== "read" && toolName !== "glob" && toolName !== "grep" && toolName !== "todowrite") {
// Track non-read tool calls by name + key input params
const key = `${toolName}:${JSON.stringify(input).slice(0, 100)}`
commands.push(key)
}
}
}
if (commands.length < ACTION_LOOP_MIN_COMMANDS) {
return { detected: false, repeatedCommands: [], totalCommands: commands.length }
}
// Count occurrences of each command
const counts = new Map<string, number>()
for (const cmd of commands) {
counts.set(cmd, (counts.get(cmd) || 0) + 1)
}
// Find commands repeated 3+ times
const repeatedCommands: string[] = []
let repeatedCount = 0
for (const [cmd, count] of counts) {
if (count >= 3) {
repeatedCommands.push(cmd)
repeatedCount += count
}
}
// Loop detected if repeated commands make up a significant fraction
const detected = repeatedCommands.length > 0 && repeatedCount / commands.length >= ACTION_LOOP_REPETITION_THRESHOLD
return { detected, repeatedCommands, totalCommands: commands.length }
}
export function buildEscalatingFeedback(
attemptCount: number,
severity: string,
verdict: { feedback?: string; missing?: string[]; next_actions?: string[] } | undefined | null,
isPlanningLoop: boolean,
isActionLoop?: boolean
): string {
const safeVerdict = verdict ?? {}
const missingItems = Array.isArray(safeVerdict.missing) ? safeVerdict.missing : []
const nextActionItems = Array.isArray(safeVerdict.next_actions) ? safeVerdict.next_actions : []
const feedbackStr = safeVerdict.feedback || ""
if (isPlanningLoop) {
return `${FEEDBACK_MARKER} STOP: Planning Loop Detected
You have been reading files, checking git status, and creating todo lists without writing any code.
DO NOT:
- Run git status or git log again
- Create another todo list
- Read more files "for context"
- Say "let me get right to work" without actually working
DO NOW:
Pick the FIRST item from your existing todo list and implement it. Open a file with Edit or Write and make changes. If you don't know where to start, create the simplest possible file first.
Start coding NOW. No more planning.`
}
if (isActionLoop) {
return `${FEEDBACK_MARKER} STOP: Action Loop Detected (attempt ${attemptCount}/${MAX_ATTEMPTS})
You are repeating the same commands without making progress. Running the same deploy/test/build cycle again will produce the same result.
STOP and do ONE of these:
1. If the same test/eval keeps failing, analyze the failure output and fix the root cause before re-running.
2. If you cannot fix the root cause, explain what is blocking you and ask the user for help.
3. Try a completely different approach (e.g., test locally instead of via deployment).
Do NOT re-run the same command hoping for a different result.`
}
if (attemptCount <= 2) {
const missing = missingItems.length
? `\n### Missing\n${missingItems.map((m) => `- ${m}`).join("\n")}`
: ""
const nextActions = nextActionItems.length
? `\n### Next Actions\n${nextActionItems.map((a) => `- ${a}`).join("\n")}`
: ""
return `${FEEDBACK_MARKER} Task Incomplete (${severity})
${feedbackStr}
${missing}
${nextActions}
Please address these issues and continue.`
}
const missingBrief = missingItems.length
? `Still missing: ${missingItems.slice(0, 3).join(", ")}.`
: ""
return `${FEEDBACK_MARKER} Final Attempt (${attemptCount}/${MAX_ATTEMPTS})
${missingBrief}
You have been asked ${attemptCount} times to complete this task. This is your LAST chance before reflection stops.
If you cannot complete the remaining items:
- Explain clearly what is blocking you
- Set needs_user_action if you need user help
- Try a different approach instead of repeating the same steps
Do NOT re-read files or re-plan. Either implement the fix now or explain why you cannot.`
}
function getLastRelevantUserMessageId(messages: any[]): string | null {
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
if (msg.info?.role === "user") {
let isReflection = false
for (const part of msg.parts || []) {
if (part.type === "text" && part.text) {
if (part.text.includes(SELF_ASSESSMENT_MARKER) || part.text.includes(FEEDBACK_MARKER)) {
isReflection = true
break
}
}
}
if (!isReflection) return getMessageSignature(msg)
}
}
return null
}
function isJudgeSession(sessionId: string, messages: any[], judgeSessionIds: Set<string>): boolean {
if (judgeSessionIds.has(sessionId)) return true
for (const msg of messages) {
for (const part of msg.parts || []) {
if (part.type === "text" && (part.text?.includes("ANALYZE REFLECTION-3") || part.text?.includes("SELF-ASSESS REFLECTION-3") || part.text?.includes("REVIEW REFLECTION-3 COMPLETION"))) {
return true
}
}
}
return false
}
export function isPlanMode(messages: any[]): boolean {
if (!Array.isArray(messages)) return false
// Check system/developer messages for plan mode indicators
const hasSystemPlanMode = messages.some((m: any) =>
(m.info?.role === "system" || m.info?.role === "developer") &&
m.parts?.some((p: any) =>
p.type === "text" &&
p.text &&
(p.text.includes("Plan Mode") ||
p.text.includes("plan mode ACTIVE") ||
p.text.includes("plan mode is active") ||
p.text.includes("read-only mode") ||
p.text.includes("READ-ONLY phase"))
)
)
if (hasSystemPlanMode) return true
// OpenCode injects plan mode as <system-reminder> inside user message parts.
// Check ALL text parts of ALL messages for plan mode system-reminder patterns.
for (const msg of messages) {
for (const part of msg.parts || []) {
if (part.type === "text" && part.text) {
const text = part.text
if (
text.includes("<system-reminder>") &&
(/plan mode/i.test(text) || /READ-ONLY phase/i.test(text))
) {
return true
}
}
}
}
// Check the last non-reflection user message for plan-related keywords
for (let i = messages.length - 1; i >= 0; i--) {
const msg = messages[i]
if (msg.info?.role === "user") {
let isReflection = false
const texts: string[] = []
for (const part of msg.parts || []) {
if (part.type === "text" && part.text) {
if (part.text.includes(SELF_ASSESSMENT_MARKER)) {
isReflection = true
break
}
texts.push(part.text)
}
}
if (!isReflection && texts.length > 0) {
for (const text of texts) {
if (/plan mode/i.test(text)) return true
if (/\b(create|make|draft|generate|propose|write|update)\b.{1,30}\bplan\b/i.test(text)) return true
if (/^plan\b/i.test(text.trim())) return true
}
return false
}
}
}
return false
}
async function showToast(client: any, directory: string, message: string, variant: "info" | "success" | "warning" | "error" = "info") {
try {
await client.tui.publish({
query: { directory },
body: {
type: "tui.toast.show",
properties: { title: "Reflection", message, variant, duration: 5000 }
}
})
} catch {}
}
function parseModelListFromYaml(content: string): string[] {
const models: string[] = []
const lines = content.split(/\r?\n/)
let inModels = false
for (const rawLine of lines) {
const line = rawLine.trim()
if (!line || line.startsWith("#")) continue
if (/^models\s*:/i.test(line)) {
inModels = true
const inline = line.replace(/^models\s*:/i, "").trim()
if (inline.startsWith("[") && inline.endsWith("]")) {
const items = inline.slice(1, -1).split(",")
for (const item of items) {
const value = item.trim().replace(/^['"]|['"]$/g, "")
if (value) models.push(value)
}
inModels = false
}
continue
}
if (inModels) {
if (/^[\w-]+\s*:/.test(line)) {
inModels = false
continue
}
if (line.startsWith("-")) {
const value = line.replace(/^-\s*/, "").trim().replace(/^['"]|['"]$/g, "")
if (value) models.push(value)
}
}
}
return models
}
function parseRoutingFromYaml(content: string): RoutingConfig {
const config: RoutingConfig = { ...DEFAULT_ROUTING_CONFIG, models: { ...DEFAULT_ROUTING_CONFIG.models } }
const lines = content.split(/\r?\n/)
let inRouting = false
let inRoutingModels = false
for (const rawLine of lines) {
const line = rawLine.trim()
if (!line || line.startsWith("#")) continue
if (/^routing\s*:/i.test(line)) {
inRouting = true
continue
}
if (inRouting) {
// Exit routing section when we hit a top-level key
if (/^[a-zA-Z][\w-]*\s*:/.test(rawLine) && !rawLine.startsWith(" ") && !rawLine.startsWith("\t")) {
inRouting = false
inRoutingModels = false
continue
}
if (/^\s*enabled\s*:\s*(true|false)/i.test(rawLine)) {
config.enabled = /true/i.test(rawLine)
continue
}
if (/^\s*models\s*:/i.test(rawLine)) {
inRoutingModels = true
continue
}
if (inRoutingModels) {
// Exit models sub-section on a non-indented or non-model key
if (/^\s{2,}[\w-]+\s*:/.test(rawLine) || /^\s+[\w-]+\s*:/.test(rawLine)) {
const match = rawLine.match(/^\s+([\w-]+)\s*:\s*(.*)/)
if (match) {
const key = match[1].toLowerCase() as RoutingCategory
const value = match[2].trim().replace(/^['"]|['"]$/g, "")
if (key === "backend" || key === "architecture" || key === "frontend" || key === "default") {
config.models[key] = value
}
}
}
}
}
}
return config
}
function parseRoutingCategory(text: string | null | undefined): RoutingCategory | null {
if (typeof text !== "string") return null
const trimmed = text.trim()
if (!trimmed) return null
const jsonMatch = trimmed.match(/\{[\s\S]*\}/)
if (jsonMatch) {
try {
const parsed = JSON.parse(jsonMatch[0]) as { category?: string }
const value = (parsed.category || "").toLowerCase()
if (value === "backend" || value === "architecture" || value === "frontend" || value === "default") {
return value
}
} catch {}
}
const word = trimmed.split(/\s+/)[0]?.toLowerCase()
if (word === "backend" || word === "architecture" || word === "frontend" || word === "default") {
return word
}
return null
}
function parseModelSpec(modelSpec: string | null | undefined): ModelSpecParts | null {
if (typeof modelSpec !== "string") return null
const trimmed = modelSpec.trim()
if (!trimmed) return null
const parts = trimmed.split("/")
if (parts.length < 2) return null
const providerID = parts[0] || ""
const modelID = parts.slice(1).join("/") || ""
if (!providerID || !modelID) return null
return { providerID, modelID }
}
function getGitHubCopilotModelForRouting(modelSpec: string | null | undefined): string | null {
const parsed = parseModelSpec(modelSpec)
if (!parsed) return null
const providerID = parsed.providerID.toLowerCase()
const modelID = parsed.modelID.toLowerCase()
if (providerID === "github-copilot" || providerID === "github-copilot/free") {
if (modelID.includes("gpt-4.1") || modelID.includes("gpt-4o") || modelID.includes("gpt-4")) {
return "github-copilot/gpt-4.1"
}
}
return null
}
function getCrossReviewModelSpec(modelSpec: string | null | undefined): string | null {
const parsed = parseModelSpec(modelSpec)
if (!parsed) return null
const modelID = parsed.modelID.toLowerCase()
if (modelID === "claude-opus-4.6") return "github-copilot/gpt-5.2-codex"
if (modelID === "gpt-5.2-codex") return "github-copilot/claude-opus-4.6"
return null
}
async function classifyTaskForRoutingWithLLM(
client: any,
directory: string,
context: TaskContext,
judgeSessionIds: Set<string>
): Promise<RoutingCategory | null> {
const modelList = await loadReflectionModelList()
const preferredModel = await loadPreferredModelSpec(directory)
let attempts: string[] = []
if (modelList.length) {
attempts = modelList
} else if (preferredModel) {
const routingModel = getGitHubCopilotModelForRouting(preferredModel)
if (routingModel && !isBlockedJudgeModel(routingModel)) {
attempts = [routingModel]
} else if (!isBlockedJudgeModel(preferredModel)) {
attempts = [preferredModel]
}
}
if (attempts.length === 0) attempts = [""]
const prompt = `CLASSIFY TASK ROUTING\n\nYou are classifying a task into one routing category.\n\nTask summary:\n${context.taskSummary}\n\nTask type: ${context.taskType}\n\nRecent user messages:\n${context.humanMessages.slice(0, 4).join("\n\n")}\n\nChoose exactly one category from: backend, architecture, frontend, default.\nReturn JSON only:\n{\n "category": "backend|architecture|frontend|default"\n}`
for (const modelSpec of attempts) {
let classifierSession: any
try {
const { data } = await client.session.create({ query: { directory } })
classifierSession = data
} catch {
return null
}
if (!classifierSession?.id) return null
judgeSessionIds.add(classifierSession.id)
let response: string | null = null
try {
const modelParts = modelSpec ? modelSpec.split("/") : []
const providerID = modelParts[0] || ""
const modelID = modelParts.slice(1).join("/") || ""
const body: any = { parts: [{ type: "text", text: prompt }] }
if (providerID && modelID) body.model = { providerID, modelID }
await client.session.promptAsync({
path: { id: classifierSession.id },
body
})
response = await waitForResponse(client, classifierSession.id)
} catch (e) {
reportError(e, { plugin: "reflection-3", op: "routing-classifier" })
continue
} finally {
try {
await client.session.delete({ path: { id: classifierSession.id }, query: { directory } })
} catch {}
judgeSessionIds.delete(classifierSession.id)
}
const category = parseRoutingCategory(response)
if (category) return category
}
return null
}
async function loadRoutingConfig(): Promise<RoutingConfig> {
try {
const content = await readFile(REFLECTION_CONFIG_PATH, "utf-8")
return parseRoutingFromYaml(content)
} catch {
return { ...DEFAULT_ROUTING_CONFIG, models: { ...DEFAULT_ROUTING_CONFIG.models } }
}
}
function getRoutingModel(config: RoutingConfig, category: RoutingCategory | null): { providerID: string; modelID: string } | null {
if (!category) return null
if (!config.enabled) return null
const modelSpec = config.models[category] || config.models["default"] || ""
if (!modelSpec) return null
const parts = modelSpec.split("/")
const providerID = parts[0] || ""
const modelID = parts.slice(1).join("/") || ""
if (!providerID || !modelID) return null
return { providerID, modelID }
}
async function loadReflectionModelList(): Promise<string[]> {
try {
const content = await readFile(REFLECTION_CONFIG_PATH, "utf-8")
const models = parseModelListFromYaml(content)
const filtered = models.filter((model) => {
if (isBlockedJudgeModel(model)) {
debug("Blocked weak reflection model:", model)
return false
}
return true
})
if (filtered.length) debug("Loaded reflection model list:", JSON.stringify(filtered))
return filtered
} catch {
return []
}
}
async function ensureReflectionDir(directory: string): Promise<string> {
const reflectionDir = join(directory, ".reflection")
try {
await mkdir(reflectionDir, { recursive: true })
} catch {}
return reflectionDir
}
async function writeVerdictSignal(directory: string, sessionId: string, complete: boolean, severity: string): Promise<void> {
const reflectionDir = await ensureReflectionDir(directory)
const signalPath = join(reflectionDir, `verdict_${sessionId.slice(0, 8)}.json`)
const signal = {
sessionId: sessionId.slice(0, 8),
complete,
severity,
timestamp: Date.now()
}
try {
await writeFile(signalPath, JSON.stringify(signal))
debug("Wrote verdict signal:", signalPath)
} catch (e) {
debug("Failed to write verdict signal:", String(e))
reportError(e, { plugin: "reflection-3", op: "write-verdict-signal" })
}
}
async function saveReflectionData(directory: string, sessionId: string, data: any): Promise<void> {
const reflectionDir = await ensureReflectionDir(directory)
const filename = `${sessionId.slice(0, 8)}_${Date.now()}.json`
const filepath = join(reflectionDir, filename)
try {
await writeFile(filepath, JSON.stringify(data, null, 2))
} catch {}
}
async function waitForResponse(client: any, sessionId: string): Promise<string | null> {
const start = Date.now()
while (Date.now() - start < JUDGE_RESPONSE_TIMEOUT) {
await new Promise(r => setTimeout(r, POLL_INTERVAL))
try {
const { data } = await client.session.messages({ path: { id: sessionId } })
const messages = Array.isArray(data) ? data : []
const assistantMsg = [...messages].reverse().find((m: any) => m.info?.role === "assistant")
if (!(assistantMsg?.info?.time as any)?.completed) continue
for (const part of assistantMsg?.parts || []) {
if (part.type === "text" && part.text) return part.text
}
} catch {}
}
return null
}
function inferTaskType(text: string): TaskType {
const hasResearch = /research|investigate|analyze|compare|evaluate|study/i.test(text)
const hasCodingAction = /\bfix\b|implement|add|create|build|feature|refactor|improve|update/i.test(text)
const hasCodingSignal = /\bbug\b|\berror\b|\bregression\b/i.test(text)
const hasGitHubIssue = /github\.com\/[^\s/]+\/[^\s/]+\/issues\/\d+/i.test(text)
// When text contains both research AND coding-action keywords (e.g. "investigate and fix this bug"),
// or references a GitHub issue URL alongside research terms, prefer coding —
// these are almost always coding tasks even if the description says "investigate".
// Note: coding-signal words (bug, error, regression) alone don't override research,
// because "investigate performance regressions" is legitimate research.
if (hasResearch && (hasCodingAction || hasGitHubIssue)) return "coding"
if (hasResearch) return "research"
if (/docs?|readme|documentation/i.test(text)) return "docs"
// Ops detection: explicit ops terms and personal-assistant / browser-automation patterns
// Must be checked BEFORE coding to avoid "create filter" or "build entities" matching as coding
if (/deploy|release|infra|ops|oncall|incident|runbook/i.test(text)) return "ops"
if (/\bgmail\b|\bemail\b|\bfilter\b|\binbox\b|\bcalendar\b|\blinkedin\b|\brecruiter\b|\bbrowser\b/i.test(text)) return "ops"
if (/\bclean\s*up\b|\borganize\b|\bconfigure\b|\bsetup\b|\bset\s*up\b|\binstall\b/i.test(text)) return "ops"
if (hasCodingAction || hasCodingSignal) return "coding"
return "other"
}
async function hasPath(target: string): Promise<boolean> {
try {
await stat(target)
return true
} catch {
return false
}
}
async function getRepoSignals(directory: string): Promise<{ hasTestScript: boolean; hasBuildScript: boolean; hasTestsDir: boolean }>{
let hasTestScript = false
let hasBuildScript = false
const packagePath = join(directory, "package.json")
try {
const content = await readFile(packagePath, "utf-8")
const pkg = JSON.parse(content)
const scripts = pkg?.scripts || {}
hasTestScript = Boolean(scripts.test || scripts["test:ci"] || scripts["test:e2e"])
hasBuildScript = Boolean(scripts.build || scripts["build:prod"])
} catch {}
const hasTestsDir = (await hasPath(join(directory, "test"))) || (await hasPath(join(directory, "tests")))
return { hasTestScript, hasBuildScript, hasTestsDir }
}
function extractToolCommands(messages: any[]): string[] {
const commands: string[] = []
for (const msg of messages) {
for (const part of msg.parts || []) {
if (part.type === "tool" && part.tool === "bash") {
const command = part.state?.input?.command
if (typeof command === "string" && command.trim()) {
commands.push(command)
}
}
}
}
return commands
}
function detectSignals(humanText: string, commands: string[]): string[] {
const signals: string[] = []
if (/test|tests|pytest|jest|unit|e2e|integration/i.test(humanText)) signals.push("test-mention")
if (/build|compile|bundle|release/i.test(humanText)) signals.push("build-mention")
if (/pull request|\bPR\b|merge request/i.test(humanText)) signals.push("pr-mention")
if (/ci|checks|github actions/i.test(humanText)) signals.push("ci-mention")
if (commands.some(cmd => /\b(npm|pnpm|yarn)\s+test\b|pytest\b|go\s+test\b|cargo\s+test\b/i.test(cmd))) {
signals.push("test-command")
}
if (commands.some(cmd => /\b(npm|pnpm|yarn)\s+run\s+build\b|cargo\s+build\b|go\s+build\b/i.test(cmd))) {
signals.push("build-command")
}
if (commands.some(cmd => /\bgh\s+pr\b/i.test(cmd))) signals.push("gh-pr")
if (commands.some(cmd => /\bgh\s+issue\b/i.test(cmd))) signals.push("gh-issue")
if (commands.some(cmd => /\bgh\s+pr\s+create\b/i.test(cmd))) signals.push("gh-pr-create")
if (commands.some(cmd => /\bgh\s+pr\s+view\b/i.test(cmd))) signals.push("gh-pr-view")
if (commands.some(cmd => /\bgh\s+pr\s+status\b/i.test(cmd))) signals.push("gh-pr-status")
if (commands.some(cmd => /\bgh\s+pr\s+checks\b/i.test(cmd))) signals.push("gh-pr-checks")
if (commands.some(cmd => /\bgit\s+push\b/i.test(cmd))) signals.push("git-push")
return signals
}
function normalizeCommand(command: string): string {
return command.replace(/\s+/g, " ").trim()
}
function getRecentCommands(commands: string[], limit = 20): string[] {
return commands.map(normalizeCommand).slice(-limit)
}
function hasLocalTestCommand(commands: string[]): boolean {
return commands.some(cmd =>
/\bnpm\s+test\b/i.test(cmd) ||
/\bnpm\s+run\s+test\b/i.test(cmd) ||
/\bnpm\s+run\s+typecheck\b/i.test(cmd) ||
/\bpnpm\s+test\b/i.test(cmd) ||
/\byarn\s+test\b/i.test(cmd) ||
/\bpytest\b/i.test(cmd) ||
/\bgo\s+test\b/i.test(cmd) ||
/\bcargo\s+test\b/i.test(cmd)
)
}
function pushedToDefaultBranch(commands: string[]): boolean {
return commands.some(cmd =>
/\bgit\s+push\b.*\b(main|master)\b/i.test(cmd) ||
/\bgit\s+push\b.*\borigin\b\s+\b(main|master)\b/i.test(cmd) ||
/\bgit\s+push\b.*\bHEAD:(main|master)\b/i.test(cmd)
)
}
async function buildTaskContext(messages: any[], directory: string): Promise<TaskContext | null> {
if (!Array.isArray(messages)) return null
const humanMessages: string[] = []
let lastAssistantText = ""
for (const msg of messages) {
if (msg.info?.role === "user") {
for (const part of msg.parts || []) {
if (part.type === "text" && part.text) {
if (part.text.includes(SELF_ASSESSMENT_MARKER) || part.text.includes(FEEDBACK_MARKER)) continue
humanMessages.push(part.text)
break
}
}
}
if (msg.info?.role === "assistant") {
for (const part of msg.parts || []) {
if (part.type === "text" && part.text) {
lastAssistantText = part.text
}
}
}
}
if (humanMessages.length === 0) return null
const taskSummary = humanMessages.length === 1
? humanMessages[0]
: humanMessages.map((msg, i) => `[${i + 1}] ${msg}`).join("\n\n")