InfiniaxAI commited on
Commit
568df62
Β·
verified Β·
1 Parent(s): 7a3459f

Create ARDR_stages.ts

Browse files
Files changed (1) hide show
  1. ARDR_stages.ts +578 -0
ARDR_stages.ts ADDED
@@ -0,0 +1,578 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { MODELS, colors } from "./ARDR_models";
2
+ import {
3
+ NexusTier,
4
+ ReasoningBudget,
5
+ TriStructurePack,
6
+ BranchOutput,
7
+ Scratchpad,
8
+ VerificationResult,
9
+ ARDRState,
10
+ BranchConfig
11
+ } from "./ARDR_types";
12
+ import { log, logSection, callModel, callModelStreaming, parseJsonFromResponse } from "./ARDR_utils";
13
+
14
+ export async function stage0_TaskProfiler(
15
+ prompt: string,
16
+ tier: NexusTier,
17
+ debug: boolean
18
+ ): Promise<ReasoningBudget> {
19
+ logSection("STAGE 0: Task Profiler & Budget Allocator");
20
+ log("Profiler", "Analyzing task complexity and allocating reasoning budget...", colors.cyan);
21
+
22
+ const systemPrompt = `You are a Task Profiler for an advanced AI reasoning system. Analyze the user's request and output a JSON object with:
23
+ - taskType: one of "code", "math", "writing", "reasoning", "world_knowledge", "multi_step", "data_analysis", "conversation"
24
+ - Use "conversation" for: greetings, casual chat, simple questions, introductions, emotional support, small talk
25
+ - Use other types only for actual tasks that need deep reasoning
26
+ - complexity: one of "low", "medium", "high", "extreme"
27
+ - riskScore: 0.0 to 1.0 (hallucination risk)
28
+ - allowedDepth: 1-3 (reasoning passes allowed)
29
+ - requiredBranches: array of needed branch types from ["logic", "pattern", "world", "code", "adversarial"]
30
+ - For "conversation" type, use empty array []
31
+
32
+ Be concise. Output ONLY valid JSON, no explanation.`;
33
+
34
+ const response = await callModel(MODELS.profiler, systemPrompt, `Analyze this task:\n\n${prompt}`);
35
+
36
+ let budget: ReasoningBudget;
37
+ const parsed = parseJsonFromResponse(response);
38
+
39
+ if (parsed) {
40
+ budget = {
41
+ taskType: parsed.taskType || "reasoning",
42
+ complexity: parsed.complexity || "medium",
43
+ riskScore: parsed.riskScore || 0.5,
44
+ allowedDepth: Math.min(parsed.allowedDepth || 2, tier === "max" ? 3 : tier === "high" ? 2 : 1),
45
+ branches: parsed.requiredBranches || ["logic", "world"],
46
+ chiefModel: tier === "max" ? MODELS.chiefMax : tier === "high" ? MODELS.chiefHigh : MODELS.chiefLow
47
+ };
48
+ } else {
49
+ budget = {
50
+ taskType: "reasoning",
51
+ complexity: "medium",
52
+ riskScore: 0.5,
53
+ allowedDepth: tier === "max" ? 3 : tier === "high" ? 2 : 1,
54
+ branches: ["logic", "world", "code"],
55
+ chiefModel: tier === "max" ? MODELS.chiefMax : tier === "high" ? MODELS.chiefHigh : MODELS.chiefLow
56
+ };
57
+ }
58
+
59
+ if (debug) {
60
+ console.log(`${colors.dim}Budget:${colors.reset}`, JSON.stringify(budget, null, 2));
61
+ }
62
+
63
+ log("Profiler", `Task: ${budget.taskType} | Complexity: ${budget.complexity} | Risk: ${budget.riskScore.toFixed(2)} | Depth: ${budget.allowedDepth}`, colors.green);
64
+ log("Profiler", `Branches: ${budget.branches.join(", ")}`, colors.green);
65
+
66
+ return budget;
67
+ }
68
+
69
+ export async function stageA_StructuredDecomposition(
70
+ prompt: string,
71
+ budget: ReasoningBudget,
72
+ debug: boolean
73
+ ): Promise<TriStructurePack> {
74
+ logSection("STAGE A: Structured Decomposition Layer");
75
+ log("Decomposer", "Creating Tri-Structure Pack...", colors.cyan);
76
+
77
+ const [symbolic, invariants, formal] = await Promise.all([
78
+ (async () => {
79
+ log("Symbolic", "Extracting entities, relations, and operations...", colors.yellow);
80
+ return await callModel(
81
+ MODELS.cheap,
82
+ `You are a Symbolic Abstractor. Convert the problem into symbolic form:
83
+ - Identify key entities/variables
84
+ - Extract relationships between them
85
+ - Define operations and transformations needed
86
+ - Express constraints in logical notation
87
+ Keep output under 400 tokens. Be precise and formal.`,
88
+ `Extract symbolic structure from:\n\n${prompt}`
89
+ );
90
+ })(),
91
+
92
+ (async () => {
93
+ log("Invariants", "Extracting core invariants and constraints...", colors.yellow);
94
+ return await callModel(
95
+ MODELS.cheap,
96
+ `You are an Invariant Reducer. Extract the core invariants:
97
+ - What must remain true throughout the solution?
98
+ - What are the hard constraints?
99
+ - What can be simplified or removed as noise?
100
+ - What dependencies exist between components?
101
+ Keep output under 400 tokens. Focus on what cannot change.`,
102
+ `Extract invariants from:\n\n${prompt}`
103
+ );
104
+ })(),
105
+
106
+ (async () => {
107
+ log("Formalizer", "Creating formal specification...", colors.yellow);
108
+ return await callModel(
109
+ MODELS.cheap,
110
+ `You are a Formalizer. Create a formal representation:
111
+ - For code: input/output contracts, algorithm sketch, data structures
112
+ - For math: equations, proofs outline, theorems to apply
113
+ - For writing: structure outline, key arguments, logical flow
114
+ - For reasoning: decision tree, evaluation criteria, success metrics
115
+ Keep output under 400 tokens. Use pseudo-code or formal notation.`,
116
+ `Formalize this problem:\n\n${prompt}`
117
+ );
118
+ })()
119
+ ]);
120
+
121
+ const triPack: TriStructurePack = { symbolic, invariants, formal };
122
+
123
+ if (debug) {
124
+ console.log(`\n${colors.dim}=== TRI-STRUCTURE PACK ===${colors.reset}`);
125
+ console.log(`${colors.cyan}[Symbolic]${colors.reset}\n${symbolic.slice(0, 500)}...`);
126
+ console.log(`${colors.cyan}[Invariants]${colors.reset}\n${invariants.slice(0, 500)}...`);
127
+ console.log(`${colors.cyan}[Formal]${colors.reset}\n${formal.slice(0, 500)}...`);
128
+ }
129
+
130
+ log("Decomposer", "Tri-Structure Pack complete", colors.green);
131
+ return triPack;
132
+ }
133
+
134
+ export async function stageB_DendriticBranches(
135
+ prompt: string,
136
+ triPack: TriStructurePack,
137
+ budget: ReasoningBudget,
138
+ scratchpad: Scratchpad,
139
+ debug: boolean
140
+ ): Promise<BranchOutput[]> {
141
+ logSection("STAGE B: Dendritic Branch Network");
142
+ log("Branches", `Activating ${budget.branches.length} specialized branches...`, colors.cyan);
143
+
144
+ const branchConfigs: Record<string, BranchConfig> = {
145
+ logic: {
146
+ model: MODELS.logic,
147
+ systemPrompt: `You are the Logic Branch of a reasoning network. Analyze using formal logic:
148
+ - Apply deductive reasoning
149
+ - Check for logical fallacies
150
+ - Build proof chains
151
+ - Identify necessary and sufficient conditions
152
+ Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`
153
+ },
154
+ pattern: {
155
+ model: MODELS.pattern,
156
+ systemPrompt: `You are the Pattern Branch of a reasoning network. Analyze patterns and structures:
157
+ - Identify recurring patterns
158
+ - Find analogies to known problems
159
+ - Detect spatial/temporal relationships
160
+ - Recognize transformations
161
+ Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`
162
+ },
163
+ world: {
164
+ model: MODELS.world,
165
+ systemPrompt: `You are the World Knowledge Branch of a reasoning network. Apply real-world knowledge:
166
+ - Verify factual claims
167
+ - Apply domain expertise
168
+ - Check temporal consistency
169
+ - Validate against known principles
170
+ Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`
171
+ },
172
+ code: {
173
+ model: MODELS.code,
174
+ systemPrompt: `You are the Code/Algorithm Branch of a reasoning network. Focus on implementation:
175
+ - Design algorithms
176
+ - Write code solutions
177
+ - Optimize for efficiency
178
+ - Handle edge cases
179
+ Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`
180
+ },
181
+ adversarial: {
182
+ model: MODELS.adversarial,
183
+ systemPrompt: `You are the Adversarial Branch of a reasoning network. Challenge everything:
184
+ - Find counterexamples
185
+ - Stress test assumptions
186
+ - Identify failure modes
187
+ - Attack weak arguments
188
+ Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`
189
+ }
190
+ };
191
+
192
+ const contextPack = `
193
+ === SYMBOLIC STRUCTURE ===
194
+ ${triPack.symbolic}
195
+
196
+ === INVARIANTS ===
197
+ ${triPack.invariants}
198
+
199
+ === FORMAL SPECIFICATION ===
200
+ ${triPack.formal}
201
+
202
+ === ORIGINAL QUERY ===
203
+ ${prompt}
204
+ `;
205
+
206
+ const branchPromises = budget.branches.map(async (branchName) => {
207
+ const config = branchConfigs[branchName];
208
+ if (!config) return null;
209
+
210
+ log(branchName.toUpperCase(), "Processing...", colors.yellow);
211
+
212
+ const response = await callModel(config.model, config.systemPrompt, contextPack, 800);
213
+
214
+ let output: BranchOutput;
215
+ const parsed = parseJsonFromResponse(response);
216
+
217
+ if (parsed) {
218
+ output = {
219
+ branchName,
220
+ hypotheses: parsed.hypotheses || [],
221
+ artifacts: parsed.artifacts || [],
222
+ notes: parsed.notes || "",
223
+ contradictions: parsed.contradictions || [],
224
+ confidence: parsed.confidence || 0.5
225
+ };
226
+ } else {
227
+ output = {
228
+ branchName,
229
+ hypotheses: [response.slice(0, 500)],
230
+ artifacts: [],
231
+ notes: response,
232
+ contradictions: [],
233
+ confidence: 0.5
234
+ };
235
+ }
236
+
237
+ scratchpad.entries.push({
238
+ branch: branchName,
239
+ timestamp: Date.now(),
240
+ content: output.notes,
241
+ type: "note"
242
+ });
243
+ output.hypotheses.forEach(h => {
244
+ scratchpad.entries.push({
245
+ branch: branchName,
246
+ timestamp: Date.now(),
247
+ content: h,
248
+ type: "hypothesis"
249
+ });
250
+ });
251
+
252
+ log(branchName.toUpperCase(), `Done (confidence: ${output.confidence.toFixed(2)})`, colors.green);
253
+ return output;
254
+ });
255
+
256
+ const results = await Promise.all(branchPromises);
257
+ const branchOutputs = results.filter((r): r is BranchOutput => r !== null);
258
+
259
+ if (debug) {
260
+ console.log(`\n${colors.dim}=== BRANCH OUTPUTS ===${colors.reset}`);
261
+ branchOutputs.forEach(b => {
262
+ console.log(`${colors.cyan}[${b.branchName}]${colors.reset} Confidence: ${b.confidence}, Hypotheses: ${b.hypotheses.length}`);
263
+ });
264
+ }
265
+
266
+ log("Branches", "Running micro-reflection on shared scratchpad...", colors.cyan);
267
+
268
+ return branchOutputs;
269
+ }
270
+
271
+ export async function stageC_Verification(
272
+ prompt: string,
273
+ triPack: TriStructurePack,
274
+ branchOutputs: BranchOutput[],
275
+ scratchpad: Scratchpad,
276
+ debug: boolean
277
+ ): Promise<VerificationResult> {
278
+ logSection("STAGE C: Verification Layer & Uncertainty Engine");
279
+ log("Verifier", "Attacking hypotheses and calculating uncertainty...", colors.cyan);
280
+
281
+ const allHypotheses = branchOutputs.flatMap(b => b.hypotheses.map(h => `[${b.branchName}] ${h}`));
282
+ const allContradictions = branchOutputs.flatMap(b => b.contradictions);
283
+
284
+ const verificationContext = `
285
+ === ORIGINAL QUERY ===
286
+ ${prompt}
287
+
288
+ === INVARIANTS ===
289
+ ${triPack.invariants}
290
+
291
+ === HYPOTHESES FROM BRANCHES ===
292
+ ${allHypotheses.map((h, i) => `${i + 1}. ${h}`).join("\n")}
293
+
294
+ === IDENTIFIED CONTRADICTIONS ===
295
+ ${allContradictions.join("\n") || "None identified"}
296
+
297
+ === SCRATCHPAD NOTES ===
298
+ ${scratchpad.entries.slice(-10).map(e => `[${e.branch}] ${e.content.slice(0, 200)}`).join("\n")}
299
+ `;
300
+
301
+ const [counterexampleResult, consistencyResult] = await Promise.all([
302
+ (async () => {
303
+ log("Counterexamples", "Generating counterexamples...", colors.yellow);
304
+ return await callModel(
305
+ MODELS.cheap,
306
+ `You are a Counterexample Generator. For each hypothesis, try to find a counterexample that disproves it.
307
+ Output JSON: { "counterexamples": ["counterexample1", ...], "failed_hypotheses": [1, 3, ...] }`,
308
+ verificationContext,
309
+ 600
310
+ );
311
+ })(),
312
+
313
+ (async () => {
314
+ log("Consistency", "Scoring consistency and coverage...", colors.yellow);
315
+ return await callModel(
316
+ MODELS.cheap,
317
+ `You are a Consistency Scorer. Evaluate the hypotheses:
318
+ - Check for internal contradictions
319
+ - Score coverage (are all aspects addressed?)
320
+ - Identify proven invariants
321
+ - Calculate overall uncertainty (0.0 = certain, 1.0 = highly uncertain)
322
+ Output JSON: { "branch_scores": {"logic": 0.8, "code": 0.6, ...}, "proven_invariants": [...], "weak_points": [...], "uncertainty": 0.5 }`,
323
+ verificationContext,
324
+ 600
325
+ );
326
+ })()
327
+ ]);
328
+
329
+ let counterexamples: string[] = [];
330
+ let branchScores = new Map<string, number>();
331
+ let provenInvariants: string[] = [];
332
+ let weakPoints: string[] = [];
333
+ let uncertaintyScore = 0.5;
334
+
335
+ const ceParsed = parseJsonFromResponse(counterexampleResult);
336
+ if (ceParsed) {
337
+ counterexamples = ceParsed.counterexamples || [];
338
+ }
339
+
340
+ const csParsed = parseJsonFromResponse(consistencyResult);
341
+ if (csParsed) {
342
+ if (csParsed.branch_scores) {
343
+ Object.entries(csParsed.branch_scores).forEach(([k, v]) => {
344
+ branchScores.set(k, v as number);
345
+ });
346
+ }
347
+ provenInvariants = csParsed.proven_invariants || [];
348
+ weakPoints = csParsed.weak_points || [];
349
+ uncertaintyScore = csParsed.uncertainty || 0.5;
350
+ }
351
+
352
+ const avgConfidence = branchOutputs.reduce((sum, b) => sum + b.confidence, 0) / branchOutputs.length;
353
+ uncertaintyScore = (uncertaintyScore + (1 - avgConfidence)) / 2;
354
+
355
+ const result: VerificationResult = {
356
+ branchScores,
357
+ counterexamples,
358
+ contradictions: allContradictions,
359
+ provenInvariants,
360
+ uncertaintyScore,
361
+ weakPoints
362
+ };
363
+
364
+ if (debug) {
365
+ console.log(`\n${colors.dim}=== VERIFICATION RESULT ===${colors.reset}`);
366
+ console.log(`Uncertainty: ${uncertaintyScore.toFixed(3)}`);
367
+ console.log(`Counterexamples: ${counterexamples.length}`);
368
+ console.log(`Weak points: ${weakPoints.join(", ") || "None"}`);
369
+ }
370
+
371
+ log("Verifier", `Uncertainty: ${uncertaintyScore.toFixed(3)} | Counterexamples: ${counterexamples.length} | Weak points: ${weakPoints.length}`,
372
+ uncertaintyScore > 0.6 ? colors.red : uncertaintyScore > 0.4 ? colors.yellow : colors.green);
373
+
374
+ return result;
375
+ }
376
+
377
+ export async function stageD_AdaptiveRecurrence(
378
+ prompt: string,
379
+ triPack: TriStructurePack,
380
+ branchOutputs: BranchOutput[],
381
+ scratchpad: Scratchpad,
382
+ verification: VerificationResult,
383
+ budget: ReasoningBudget,
384
+ recurrenceCount: number,
385
+ debug: boolean
386
+ ): Promise<{ shouldRecur: boolean; updatedBranches: BranchOutput[] }> {
387
+ logSection("STAGE D: Adaptive Recurrence Pass");
388
+
389
+ const UNCERTAINTY_THRESHOLD = 0.55;
390
+ const MIN_BRANCH_SCORE = 0.5;
391
+
392
+ if (verification.uncertaintyScore < UNCERTAINTY_THRESHOLD &&
393
+ verification.weakPoints.length === 0) {
394
+ log("Recurrence", "Uncertainty below threshold, skipping recurrence (fast path)", colors.green);
395
+ return { shouldRecur: false, updatedBranches: branchOutputs };
396
+ }
397
+
398
+ if (recurrenceCount >= budget.allowedDepth) {
399
+ log("Recurrence", `Max depth reached (${recurrenceCount}/${budget.allowedDepth}), proceeding to synthesis`, colors.yellow);
400
+ return { shouldRecur: false, updatedBranches: branchOutputs };
401
+ }
402
+
403
+ log("Recurrence", `Pass ${recurrenceCount + 1}/${budget.allowedDepth} - Targeting weak branches...`, colors.cyan);
404
+
405
+ const weakBranches = branchOutputs.filter(b => {
406
+ const score = verification.branchScores.get(b.branchName) || b.confidence;
407
+ return score < MIN_BRANCH_SCORE || verification.weakPoints.some(wp => wp.includes(b.branchName));
408
+ });
409
+
410
+ if (weakBranches.length === 0) {
411
+ log("Recurrence", "No weak branches identified, proceeding to synthesis", colors.green);
412
+ return { shouldRecur: false, updatedBranches: branchOutputs };
413
+ }
414
+
415
+ log("Recurrence", `Re-running ${weakBranches.length} weak branches: ${weakBranches.map(b => b.branchName).join(", ")}`, colors.yellow);
416
+
417
+ const instructionPrompt = `Based on these issues, generate specific improvement instructions for each weak branch:
418
+
419
+ Weak points: ${verification.weakPoints.join(", ")}
420
+ Counterexamples found: ${verification.counterexamples.slice(0, 3).join("; ")}
421
+ Branches to improve: ${weakBranches.map(b => b.branchName).join(", ")}
422
+
423
+ Output JSON: { "instructions": { "branchName": "specific instruction", ... } }`;
424
+
425
+ const instructionResult = await callModel(MODELS.cheap,
426
+ "You are a Reasoning Controller. Generate specific, targeted instructions for branches that need improvement.",
427
+ instructionPrompt, 400);
428
+
429
+ let instructions: Record<string, string> = {};
430
+ const parsed = parseJsonFromResponse(instructionResult);
431
+ if (parsed) {
432
+ instructions = parsed.instructions || {};
433
+ }
434
+
435
+ const updatedBranchPromises = branchOutputs.map(async (branch) => {
436
+ if (!weakBranches.find(wb => wb.branchName === branch.branchName)) {
437
+ return branch;
438
+ }
439
+
440
+ const instruction = instructions[branch.branchName] || "Re-analyze with more rigor";
441
+ log(branch.branchName.toUpperCase(), `Re-running: ${instruction.slice(0, 50)}...`, colors.magenta);
442
+
443
+ const refinedContext = `
444
+ PREVIOUS ANALYSIS: ${branch.notes}
445
+ COUNTEREXAMPLES TO ADDRESS: ${verification.counterexamples.slice(0, 2).join("; ")}
446
+ SPECIFIC INSTRUCTION: ${instruction}
447
+
448
+ ORIGINAL PROBLEM:
449
+ ${prompt}
450
+
451
+ Provide an improved analysis. Output JSON: { "hypotheses": [...], "artifacts": [...], "notes": "...", "contradictions": [...], "confidence": 0.0-1.0 }`;
452
+
453
+ const model = branch.branchName === "code" ? MODELS.code : MODELS.cheap;
454
+ const response = await callModel(model,
455
+ `You are the ${branch.branchName} reasoning branch. Improve your previous analysis based on the feedback.`,
456
+ refinedContext, 800);
457
+
458
+ const refined = parseJsonFromResponse(response);
459
+ if (refined) {
460
+ return {
461
+ branchName: branch.branchName,
462
+ hypotheses: refined.hypotheses || branch.hypotheses,
463
+ artifacts: refined.artifacts || branch.artifacts,
464
+ notes: refined.notes || response,
465
+ contradictions: refined.contradictions || [],
466
+ confidence: Math.min((refined.confidence || branch.confidence) + 0.1, 0.95)
467
+ };
468
+ }
469
+
470
+ return { ...branch, confidence: branch.confidence + 0.1 };
471
+ });
472
+
473
+ const updatedBranches = await Promise.all(updatedBranchPromises);
474
+ log("Recurrence", `Completed pass ${recurrenceCount + 1}`, colors.green);
475
+
476
+ return { shouldRecur: true, updatedBranches };
477
+ }
478
+
479
+ export async function stageFinal_GrandSynthesis(
480
+ prompt: string,
481
+ state: ARDRState,
482
+ debug: boolean
483
+ ): Promise<string> {
484
+ logSection("FINAL STAGE: Grand Synthesizer");
485
+
486
+ const tierLabel = state.tier === "max" ? "Max (Opus 4.5)" :
487
+ state.tier === "high" ? "High (Deepseek V3.2)" : "Low (Llama 3.3 70B)";
488
+ log("Synthesizer", `${tierLabel} synthesizing final response...`, colors.cyan);
489
+
490
+ const evidenceLedger = `
491
+ === EVIDENCE LEDGER ===
492
+
493
+ [Task Profile]
494
+ Type: ${state.budget.taskType}
495
+ Complexity: ${state.budget.complexity}
496
+ Risk Score: ${state.budget.riskScore}
497
+ Recurrence Passes: ${state.recurrenceCount}
498
+
499
+ [Structured Views]
500
+ Symbolic: ${state.triPack.symbolic.slice(0, 300)}...
501
+ Invariants: ${state.triPack.invariants.slice(0, 300)}...
502
+ Formal: ${state.triPack.formal.slice(0, 300)}...
503
+
504
+ [Branch Findings]
505
+ ${state.branchOutputs.map(b => `
506
+ [${b.branchName.toUpperCase()}] (confidence: ${b.confidence.toFixed(2)})
507
+ Hypotheses: ${b.hypotheses.slice(0, 3).join("; ")}
508
+ Key artifacts: ${b.artifacts.slice(0, 2).join("; ") || "None"}
509
+ `).join("\n")}
510
+
511
+ [Verification Results]
512
+ Uncertainty: ${state.verification.uncertaintyScore.toFixed(3)}
513
+ Proven Invariants: ${state.verification.provenInvariants.join(", ") || "None proven"}
514
+ Counterexamples Found: ${state.verification.counterexamples.length}
515
+ Remaining Weak Points: ${state.verification.weakPoints.join(", ") || "None"}
516
+ Contradictions Resolved: ${state.verification.contradictions.length}
517
+
518
+ [Scratchpad Highlights]
519
+ ${state.scratchpad.entries.slice(-5).map(e => `[${e.branch}] ${e.content.slice(0, 150)}`).join("\n")}
520
+ `;
521
+
522
+ const systemPrompt = `You are the ARDR Grand Synthesizer (${tierLabel}).
523
+
524
+ You have received clean, verified evidence from a multi-stage reasoning pipeline:
525
+ 1. A Task Profiler classified this problem
526
+ 2. A Decomposition Layer created structured views
527
+ 3. Multiple specialized branches reasoned in parallel with a shared scratchpad
528
+ 4. A Verification Layer attacked hypotheses and measured uncertainty
529
+ 5. Adaptive Recurrence refined weak points
530
+
531
+ Your job: Synthesize a final, coherent response that is:
532
+ - Comprehensive but concise
533
+ - Multi-proofed and contradiction-free
534
+ - Leveraging the best insights from each branch
535
+ - Honest about remaining uncertainties
536
+
537
+ For code tasks: Provide complete, working code
538
+ For writing tasks: Deliver polished, structured prose
539
+ For reasoning tasks: Show clear logical chains
540
+ For math tasks: Include formal proofs where appropriate
541
+
542
+ Do not mention the internal pipeline or stages. Respond directly to the user's query.`;
543
+
544
+ console.log(`\n${colors.bright}${colors.green}═══════════════════════════════════════════════════════════════${colors.reset}`);
545
+ console.log(`${colors.bright}${colors.green} ARDR RESPONSE ${colors.reset}`);
546
+ console.log(`${colors.bright}${colors.green}═══════════════════════════════════════════════════════════════${colors.reset}\n`);
547
+
548
+ const maxTokens = state.tier === "max" ? 8000 : state.tier === "high" ? 4000 : 2000;
549
+
550
+ const response = await callModelStreaming(
551
+ state.budget.chiefModel,
552
+ systemPrompt,
553
+ `${evidenceLedger}\n\n=== ORIGINAL USER QUERY ===\n${prompt}`,
554
+ maxTokens
555
+ );
556
+
557
+ return response;
558
+ }
559
+
560
+ export async function handleConversation(prompt: string, tier: NexusTier): Promise<string> {
561
+ console.log(`\n${colors.bright}${colors.green}═══════════════════════════════════════════════════════════════${colors.reset}`);
562
+ console.log(`${colors.bright}${colors.green} ARDR RESPONSE ${colors.reset}`);
563
+ console.log(`${colors.bright}${colors.green}═══════════════════════════════════════════════════════════════${colors.reset}\n`);
564
+
565
+ const chiefModel = tier === "max" ? MODELS.chiefMax : tier === "high" ? MODELS.chiefHigh : MODELS.chiefLow;
566
+
567
+ const systemPrompt = `You are ARDR, a friendly and capable AI assistant. You can help with:
568
+ - Casual conversation and chat
569
+ - Coding and programming tasks
570
+ - Writing and creative work
571
+ - Analysis and reasoning
572
+ - Answering questions
573
+
574
+ Be natural, warm, and helpful. Match the user's tone - if they're casual, be casual. If they need help with something, offer to assist.`;
575
+
576
+ const response = await callModelStreaming(chiefModel, systemPrompt, prompt, 1500);
577
+ return response;
578
+ }