-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAgentEngine.ts
More file actions
1489 lines (1346 loc) · 56.4 KB
/
Copy pathAgentEngine.ts
File metadata and controls
1489 lines (1346 loc) · 56.4 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
// AgentEngine.ts
//
// Phase 5: the bounded asynchronous state machine that connects inference,
// persistent workspace memory, fuzzy diff application, verification, and Git-backed
// recovery. The engine contains policy; the injected modules contain mechanisms.
import { stat, readFile, readdir } from 'node:fs/promises';
import { isAbsolute, relative, resolve, join } from 'node:path';
import { InferenceGateway } from './InferenceGateway';
import { WorkspaceMemory, type WorkspaceContext } from './WorkspaceMemory';
import {
ToolchainBridge,
type SubprocessResult,
type RollbackResult
} from './ToolchainBridge';
export type AgentAction = 'write_code' | 'run_tests' | 'done';
export type AdapterRole = 'orchestrator' | 'coder';
export enum AgentEngineState {
IDLE = 'idle',
ORCHESTRATING = 'orchestrating',
CHECKPOINTING = 'checkpointing',
CODING = 'coding',
VERIFYING = 'verifying',
DEBUGGING = 'debugging',
COMMITTING = 'committing',
ROLLING_BACK = 'rolling_back',
COMPLETED = 'completed',
PAUSED = 'paused',
FAILED = 'failed'
}
export interface OrchestratorDecision {
action: AgentAction;
targetFile?: string;
/** Shell-like user notation parsed into a shell-free executable and args. */
command?: string;
}
export interface VerificationCommand {
executable: string;
args: string[];
display: string;
}
export interface AdapterIds {
orchestrator: string;
coder: string;
}
export interface AgentEngineEvent {
timestamp: string;
state: AgentEngineState;
iteration: number;
message: string;
details?: Readonly<Record<string, unknown>>;
}
export interface AgentEngineOptions {
/** Total orchestrator turns before the autonomous run pauses. Default: 20. */
maxIterations?: number;
/** Maximum Coder/verification attempts in one checkpoint. Default: 3. */
maxRetries?: number;
/** Hard process timeout used for compiler/test commands. Default: 120 seconds. */
verificationTimeoutMs?: number;
/** Used when the Orchestrator omits its optional command field. */
defaultVerificationCommand?: string;
adapterIds?: Partial<AdapterIds>;
/** llama.cpp context capacity. Rule 1 caps this at 4,096. */
contextWindowTokens?: number;
/** Reserved so token approximation error cannot touch the hard context edge. */
promptSafetyTokens?: number;
/** Defensive read limit for a source file included in a Coder prompt. */
maxTargetFileBytes?: number;
/** Maximum diagnostic characters persisted or sent back to the model. */
maxDiagnosticChars?: number;
/** Optional non-throwing state/event observer. */
onEvent?: (event: AgentEngineEvent) => void;
}
export interface AgentRunResult {
status: 'completed' | 'paused' | 'iteration_limit' | 'failed';
state: AgentEngineState;
iterations: number;
lastDecision?: OrchestratorDecision;
error?: string;
rollback?: RollbackResult;
}
interface PromptSection {
label: string;
content: string;
/** Lower values are truncated before higher-value sections. */
trimPriority: number;
keep: 'head' | 'tail' | 'both';
}
interface VerificationDebugResult {
passed: boolean;
process: SubprocessResult;
failureSummary?: string;
}
interface CodeActionResult {
success: boolean;
paused: boolean;
error?: string;
rollback?: RollbackResult;
}
const DEFAULT_ADAPTERS: AdapterIds = {
orchestrator: 'orchestrator_v1',
coder: 'coder_v1'
};
const DEFAULT_MAX_ITERATIONS = 20;
const DEFAULT_MAX_RETRIES = 3;
const DEFAULT_VERIFICATION_TIMEOUT_MS = 120_000;
const DEFAULT_CONTEXT_WINDOW_TOKENS = 4_096;
const DEFAULT_PROMPT_SAFETY_TOKENS = 64;
const DEFAULT_MAX_TARGET_FILE_BYTES = 2 * 1024 * 1024;
const DEFAULT_MAX_DIAGNOSTIC_CHARS = 8_000;
const APPROXIMATE_CHARACTERS_PER_TOKEN = 2.2;
const ORCHESTRATOR_MAX_OUTPUT_TOKENS = 256;
const CODER_MAX_OUTPUT_TOKENS = 2048;
/** Strict GBNF for the Orchestrator's fixed-order JSON object. */
const ORCHESTRATOR_GBNF = String.raw`
root ::= "{" ws "\"action\"" ws ":" ws ( write-code-node | run-tests-node | done-node ) ws "}"
write-code-node ::= "\"write_code\"" target-field command-field?
run-tests-node ::= "\"run_tests\"" command-field?
done-node ::= "\"done\""
target-field ::= ws "," ws "\"targetFile\"" ws ":" ws json-string
command-field ::= ws "," ws "\"command\"" ws ":" ws json-string
json-string ::= "\"" json-char* "\""
json-char ::= [^"\\\x00-\x1F] | "\\" (["\\/bfnrt] | "u" hex hex hex hex)
hex ::= [0-9a-fA-F]
ws ::= [ \t\n\r]*
`.trim();
/** Coder output is JSON-wrapped so even the diff is grammar-constrained (Rule 2). */
const CODER_GBNF = String.raw`
root ::= "{" ws "\"diff\"" ws ":" ws json-string ws "}"
json-string ::= "\"" json-char* "\""
json-char ::= [^"\\\x00-\x1F] | "\\" (["\\/bfnrt] | "u" hex hex hex hex)
hex ::= [0-9a-fA-F]
ws ::= [ \t\n\r]*
`.trim();
const SCAFFOLD_GBNF = String.raw`
root ::= "{" ws "\"code\"" ws ":" ws json-string ws "," ws "\"explanation\"" ws ":" ws "\"success\"" ws "}"
json-string ::= "\"" json-char* "\""
json-char ::= [^"\\\x00-\x1F] | "\\" (["\\/bfnrt] | "u" hex hex hex hex)
hex ::= [0-9a-fA-F]
ws ::= [ \t\n\r]*
`.trim();
const EVALUATOR_GBNF = String.raw`
root ::= "{" ws "\"isComplete\"" ws ":" ws boolean "," ws "\"reasoning\"" ws ":" ws json-string "}"
boolean ::= "true" | "false"
json-string ::= "\"" json-char* "\""
json-char ::= [^"\\\x00-\x1F] | "\\" (["\\/bfnrt] | "u" hex hex hex hex)
hex ::= [0-9a-fA-F]
ws ::= [ \t\n\r]*
`.trim();
class EngineAbortError extends Error {
public constructor() {
super('AgentEngine run was aborted.');
this.name = 'EngineAbortError';
}
}
/**
* Central autonomous driver. A single instance cannot run concurrently; this keeps
* its retry counter, active Git checkpoint, and LoRA state deterministic.
*/
export class AgentEngine {
private readonly gateway: InferenceGateway;
private readonly memory: WorkspaceMemory;
private readonly toolchain: ToolchainBridge;
private readonly maxIterations: number;
private readonly maxRetries: number;
private readonly verificationTimeoutMs: number;
private readonly defaultVerificationCommand: string;
private readonly adapters: AdapterIds;
private readonly contextWindowTokens: number;
private readonly promptSafetyTokens: number;
private readonly maxTargetFileBytes: number;
private readonly maxDiagnosticChars: number;
private readonly onEvent?: (event: AgentEngineEvent) => void;
private state = AgentEngineState.IDLE;
private running = false;
private currentIteration = 0;
private runSequence = 0;
public constructor(
gateway: InferenceGateway,
memory: WorkspaceMemory,
toolchain: ToolchainBridge,
options: AgentEngineOptions = {}
) {
this.gateway = gateway;
this.memory = memory;
this.toolchain = toolchain;
this.maxIterations = options.maxIterations ?? DEFAULT_MAX_ITERATIONS;
this.maxRetries = options.maxRetries ?? DEFAULT_MAX_RETRIES;
this.verificationTimeoutMs =
options.verificationTimeoutMs ?? DEFAULT_VERIFICATION_TIMEOUT_MS;
this.defaultVerificationCommand =
options.defaultVerificationCommand ?? 'npm test';
this.adapters = { ...DEFAULT_ADAPTERS, ...options.adapterIds };
this.contextWindowTokens =
options.contextWindowTokens ?? DEFAULT_CONTEXT_WINDOW_TOKENS;
this.promptSafetyTokens =
options.promptSafetyTokens ?? DEFAULT_PROMPT_SAFETY_TOKENS;
this.maxTargetFileBytes =
options.maxTargetFileBytes ?? DEFAULT_MAX_TARGET_FILE_BYTES;
this.maxDiagnosticChars =
options.maxDiagnosticChars ?? DEFAULT_MAX_DIAGNOSTIC_CHARS;
this.onEvent = options.onEvent;
this.assertPositiveInteger(this.maxIterations, 'maxIterations');
this.assertPositiveInteger(this.maxRetries, 'maxRetries');
this.assertPositiveInteger(this.verificationTimeoutMs, 'verificationTimeoutMs');
this.assertPositiveInteger(this.contextWindowTokens, 'contextWindowTokens');
this.assertPositiveInteger(this.promptSafetyTokens, 'promptSafetyTokens');
this.assertPositiveInteger(this.maxTargetFileBytes, 'maxTargetFileBytes');
this.assertPositiveInteger(this.maxDiagnosticChars, 'maxDiagnosticChars');
if (this.contextWindowTokens > DEFAULT_CONTEXT_WINDOW_TOKENS) {
throw new RangeError('contextWindowTokens cannot exceed Rule 1 limit of 4,096.');
}
if (
this.promptSafetyTokens + CODER_MAX_OUTPUT_TOKENS >=
this.contextWindowTokens
) {
throw new RangeError('Context window is too small for the Coder output reserve.');
}
if (new Set(Object.values(this.adapters)).size !== 2) {
throw new Error('Orchestrator and Coder adapter IDs must be unique.');
}
for (const [role, id] of Object.entries(this.adapters)) {
if (typeof id !== 'string' || id.trim().length === 0) {
throw new TypeError(`${role} adapter ID must be a non-empty string.`);
}
}
// A mismatch would let memory edits and Git operations address different
// directories, defeating the rollback boundary.
if (
this.normalizePath(this.memory.workspaceRoot) !==
this.normalizePath(this.toolchain.workspaceRoot)
) {
throw new Error(
'WorkspaceMemory and ToolchainBridge must use the same workspaceRoot.'
);
}
// Validate the default command during construction rather than halfway
// through an autonomous run.
this.parseCommandLine(this.defaultVerificationCommand);
}
public getState(): AgentEngineState {
return this.state;
}
/**
* Runs the bounded autonomous loop. All terminal paths resolve to a structured
* result; a concurrent second run is rejected because it would race Git state.
*/
public async run(signal?: AbortSignal): Promise<AgentRunResult> {
if (this.running) {
throw new Error('AgentEngine is already running.');
}
this.running = true;
this.currentIteration = 0;
this.runSequence += 1;
this.transition(AgentEngineState.IDLE, 'Starting bounded agent run.');
let lastDecision: OrchestratorDecision | undefined;
try {
for (let iteration = 1; iteration <= this.maxIterations; iteration += 1) {
this.currentIteration = iteration;
this.assertNotAborted(signal);
const isComplete = await this.evaluateCompletion();
if (isComplete) {
this.transition(
AgentEngineState.COMPLETED,
'Evaluator reported that the objective is complete.'
);
await this.memory.writeKnownBugs('');
const currentProject = await this.memory.readProject();
const objectiveMatch = currentProject.match(/^(Objective:\s*.*)(?:\r?\n|$)/i);
const objectiveLine = objectiveMatch ? objectiveMatch[1] : 'Objective: Unspecified';
await this.memory.writeProject(`${objectiveLine}\nCurrent Status: Ready for next objective.\n`);
return {
status: 'completed',
state: this.state,
iterations: iteration - 1,
lastDecision
};
}
lastDecision = await this.executeOrchestrator(iteration, signal);
this.emit('Orchestrator selected the next action.', {
action: lastDecision.action,
targetFile: lastDecision.targetFile,
command: lastDecision.command
});
if (lastDecision.action === 'done') {
this.transition(
AgentEngineState.COMPLETED,
'Orchestrator reported that the objective is complete.'
);
await this.memory.writeKnownBugs('');
const currentProject = await this.memory.readProject();
const objectiveMatch = currentProject.match(/^(Objective:\s*.*)(?:\r?\n|$)/i);
const objectiveLine = objectiveMatch ? objectiveMatch[1] : 'Objective: Unspecified';
await this.memory.writeProject(`${objectiveLine}\nCurrent Status: Ready for next objective.\n`);
return {
status: 'completed',
state: this.state,
iterations: iteration,
lastDecision
};
}
if (lastDecision.action === 'run_tests') {
const command = this.resolveVerificationCommand(lastDecision.command);
const outcome = await this.verifyAndDebug({
command,
iteration,
attempt: 1,
targetFile: undefined,
signal,
persistFailureWithinCheckpoint: false
});
if (!outcome.passed) {
// There is no edit checkpoint to roll back for a standalone
// test. Persist the diagnosis and pause rather than repeatedly
// rerunning an unchanged failing command.
await this.appendKnownBug(
this.formatBugEntry(
'Standalone verification failed',
command,
outcome.process,
1
)
);
this.transition(
AgentEngineState.PAUSED,
'Standalone verification failed; human or Coder action is required.'
);
return {
status: 'paused',
state: this.state,
iterations: iteration,
lastDecision,
error: outcome.failureSummary
};
}
continue;
}
const codeResult = await this.executeCodeAction(
lastDecision,
iteration,
signal
);
if (!codeResult.success) {
this.transition(
codeResult.paused ? AgentEngineState.PAUSED : AgentEngineState.FAILED,
codeResult.error ?? 'Code action did not complete.'
);
return {
status: codeResult.paused ? 'paused' : 'failed',
state: this.state,
iterations: iteration,
lastDecision,
error: codeResult.error,
rollback: codeResult.rollback
};
}
}
this.transition(
AgentEngineState.PAUSED,
`Maximum iteration count (${this.maxIterations}) reached.`
);
return {
status: 'iteration_limit',
state: this.state,
iterations: this.maxIterations,
...(lastDecision === undefined ? {} : { lastDecision })
};
} catch (error) {
const originalMessage = this.errorMessage(error);
const rollback = await this.rollbackAfterUnexpectedFailure(originalMessage);
const aborted = error instanceof EngineAbortError;
this.transition(
aborted ? AgentEngineState.PAUSED : AgentEngineState.FAILED,
aborted ? 'Agent run aborted safely.' : `Fatal engine error: ${originalMessage}`
);
return {
status: aborted ? 'paused' : 'failed',
state: this.state,
iterations: this.currentIteration,
...(lastDecision === undefined ? {} : { lastDecision }),
error: originalMessage,
...(rollback === undefined ? {} : { rollback })
};
} finally {
this.running = false;
}
}
/** Reads state, activates the Orchestrator LoRA, and parses grammar-bound JSON. */
private async executeOrchestrator(
iteration: number,
signal?: AbortSignal
): Promise<OrchestratorDecision> {
this.transition(AgentEngineState.ORCHESTRATING, 'Requesting the next action.');
this.assertNotAborted(signal);
await this.activateAdapter('orchestrator');
const context = await this.memory.buildContext();
const instruction = [
'ROLE: Orchestrator.',
`RUN_SEQUENCE: ${this.runSequence}; ITERATION: ${iteration}.`,
'Choose exactly one next action from write_code, run_tests, or done.',
'For write_code, provide targetFile (e.g. "index.ts" or a comma-separated list like "math.ts, main.ts" to edit multiple files) and optionally a verification command (e.g. npx tsc --noEmit).',
'For run_tests, optionally provide command. A command is executable plus arguments, never shell syntax.',
'CRITICAL: The command property is ONLY for running tests or type-checking (e.g. tsc, jest). NEVER write shell commands like echo, cat, or redirect operators (> or >>) to create or edit files. File edits must be left entirely to the Coder.',
'Use done only when the project objective is demonstrably complete.',
'Return exactly one JSON object in this property order:',
'{"action":"write_code|run_tests|done","targetFile":"optional","command":"optional"}',
'Do not include Markdown, commentary, or additional properties.'
].join('\r\n');
const prompt = this.buildBoundedPrompt(
instruction,
this.memorySections(context),
ORCHESTRATOR_MAX_OUTPUT_TOKENS
);
const raw = await this.gateway.requestCompletion({
prompt,
max_tokens: ORCHESTRATOR_MAX_OUTPUT_TOKENS,
temperature: 0,
seed: 0,
grammar: ORCHESTRATOR_GBNF
});
this.assertNotAborted(signal);
return this.parseOrchestratorDecision(raw);
}
/**
* Orchestrator-Evaluator pattern: Fast evaluator step to check if the objective is met.
*/
private async evaluateCompletion(): Promise<boolean> {
try {
const projectMarkdown = await this.memory.readProject();
const files = await this.toolchain.getTrackedFiles();
let codebaseContent = '';
for (const file of files) {
const target = await this.readTargetFile(file);
if (target.exists) {
codebaseContent += `### File: ${file}\n\`\`\`\n${target.content}\n\`\`\`\n\n`;
}
}
// Use the base model by disabling all LoRA adapters
await this.gateway.swapLoRA([
{ id: this.adapters.orchestrator, scale: 0 },
{ id: this.adapters.coder, scale: 0 }
]);
const instruction = [
'ROLE: Evaluator.',
'Review the Objective, the Current Status, and the actual workspace files.',
'Has the overarching objective been fully and correctly implemented in the code?',
'Return exactly {"isComplete": true|false, "reasoning": "<short reasoning>"}',
'Do not include Markdown fences or additional properties.'
].join('\r\n');
const buster = `\r\n\r\n[CacheBust: ${Math.random().toString(36).substring(7)}]`;
const sections: PromptSection[] = [
{ label: 'PROJECT STATE', content: projectMarkdown + buster, trimPriority: 2, keep: 'both' },
{ label: 'WORKSPACE FILES', content: (codebaseContent || '(no workspace files written yet)') + buster, trimPriority: 1, keep: 'head' }
];
const prompt = this.buildBoundedPrompt(instruction, sections, 512);
const rawResponse = await this.gateway.requestCompletion({
prompt,
max_tokens: 512,
temperature: 0,
seed: 0,
grammar: EVALUATOR_GBNF
});
try {
const parsed = this.parseJsonObject(rawResponse, 'Evaluator');
if (typeof parsed.isComplete === 'boolean') {
return parsed.isComplete;
}
} catch (err) {
// The base model may ramble in the reasoning field and get truncated,
// causing an unterminated JSON string. Fallback to string matching:
if (rawResponse.includes('"isComplete": true') || rawResponse.includes('"isComplete":true')) {
return true;
}
if (rawResponse.includes('"isComplete": false') || rawResponse.includes('"isComplete":false')) {
return false;
}
}
return false;
} catch (error) {
console.error('[Evaluator] Error evaluating completion:', error);
return false;
}
}
/**
* Owns one checkpointed Coder transaction, including debugger-guided retries.
* Every attempt edits the same transaction; exhausting attempts rolls all of
* them back to the exact pre-edit parent.
*/
private async executeCodeAction(
decision: OrchestratorDecision,
iteration: number,
signal?: AbortSignal
): Promise<CodeActionResult> {
if (decision.targetFile === undefined) {
throw new Error('write_code action is missing targetFile.');
}
const targetFiles = decision.targetFile.split(',').map(file => this.validateTargetPath(file.trim()));
const command = this.resolveVerificationCommand(decision.command);
let lastFailure = 'Coder attempts exhausted.';
for (let attempt = 1; attempt <= this.maxRetries; attempt += 1) {
this.assertNotAborted(signal);
if (this.toolchain.getActiveCheckpoint() === null) {
this.transition(
AgentEngineState.CHECKPOINTING,
`Creating pre-edit checkpoint for multi-file edit: ${targetFiles.join(', ')}.`
);
await this.toolchain.createGitCheckpoint();
}
let coderFailed = false;
try {
for (const targetFile of targetFiles) {
await this.executeCoder(
targetFile,
iteration,
attempt,
signal
);
}
} catch (error) {
console.error("❌ CODER FAILED WITH ERROR:", error instanceof Error ? error.stack : error);
if (error instanceof EngineAbortError) {
throw error;
}
lastFailure = `Coder/applyDiff failure: ${this.errorMessage(error)}`;
// Roll back changes made during this failed attempt
await this.toolchain.executeRollback();
await this.appendKnownBug(
this.formatInternalFailureEntry(
'Coder or diff application failed',
targetFiles.join(', '),
lastFailure,
attempt
)
);
await this.commitDiagnostics();
if (attempt < this.maxRetries) {
continue;
}
coderFailed = true;
break;
}
if (coderFailed) {
break;
}
let verification = await this.verifyAndDebug({
command,
iteration,
attempt,
targetFile: undefined,
signal,
persistFailureWithinCheckpoint: true
});
if (!verification.passed) {
// Try Self-Healing missing package dependencies!
const errorText = (verification.process.stdout || '') + '\n' + (verification.process.stderr || '');
const healed = await this.healDependencies(errorText);
if (healed) {
// Try immediately re-verifying
verification = await this.verifyAndDebug({
command,
iteration,
attempt,
targetFile: undefined,
signal,
persistFailureWithinCheckpoint: false
});
}
}
if (verification.passed) {
await this.updateProjectAfterSuccess(targetFiles, command, attempt);
this.transition(
AgentEngineState.COMMITTING,
`Committing verified changes for ${targetFiles.join(', ')}.`
);
await this.toolchain.commitCheckpointedChanges(
this.buildVerifiedCommitMessage(targetFiles)
);
this.emit('Code transaction verified and committed.', {
targetFiles,
attempts: attempt,
command: command.display
});
return { success: true, paused: false };
}
lastFailure = verification.failureSummary ?? 'Verification failed.';
}
this.transition(
AgentEngineState.ROLLING_BACK,
`Retry limit (${this.maxRetries}) exhausted; restoring checkpoint.`
);
const rollback = await this.toolchain.executeRollback();
// Retry-level logs were inside the rolled-back transaction. Re-add one
// concise critical record afterward so the next run remembers the failure.
await this.appendKnownBug(
this.formatCriticalRollbackEntry(targetFiles, command, lastFailure, rollback)
);
return {
success: false,
paused: true,
error: lastFailure,
rollback
};
}
/** Activates Coder, requests a constrained diff or scaffold, validates it, and applies it. */
private async executeCoder(
targetFile: string,
iteration: number,
attempt: number,
signal?: AbortSignal
): Promise<void> {
this.transition(
AgentEngineState.CODING,
`Generating code for ${targetFile} (attempt ${attempt}/${this.maxRetries}).`
);
await this.activateAdapter('coder');
const context = await this.memory.buildContext();
const target = await this.readTargetFile(targetFile);
const isNewFile = !target.exists;
const targetLineCount = isNewFile ? 0 : this.countLines(target.content);
const useScaffold = isNewFile || targetLineCount <= 100;
const instruction = useScaffold ? [
'ROLE: Coder.',
`RUN_SEQUENCE: ${this.runSequence}; ITERATION: ${iteration}; ATTEMPT: ${attempt}.`,
`TARGET_FILE: ${targetFile}`,
'CRITICAL: Implement the target file cleanly and concisely as described in the objective. Avoid comments, boilerplate, or explanations inside the code. Do NOT write stubs.',
'Generate the complete, raw file contents for this file.',
'Return exactly {"code":"<JSON-escaped file string>", "explanation":"success"}',
'Do not include Markdown fences or additional properties.'
].join('\r\n') : [
'ROLE: Coder.',
`RUN_SEQUENCE: ${this.runSequence}; ITERATION: ${iteration}; ATTEMPT: ${attempt}.`,
`TARGET_FILE: ${targetFile}`,
'CRITICAL: Implement the objective for target file. Keep the edit concise and clean. Avoid comments or stubs.',
'Generate one valid Unified Diff for only TARGET_FILE.',
'Delta generation is mandatory. Do not rewrite an entire file longer than 100 lines.',
'Keep unchanged context lines in each hunk. Never emit shell commands.',
'Return exactly {"diff":"<JSON-escaped unified diff>"}.',
'Do not include Markdown fences or additional properties.'
].join('\r\n');
const sections = this.memorySections(context);
const workspaceFiles = await this.getWorkspaceFilesContent(targetFile);
if (workspaceFiles.length > 0) {
sections.push({
label: 'WORKSPACE FILES',
content: workspaceFiles,
trimPriority: 3,
keep: 'both'
});
}
if (!isNewFile) {
sections.push({
label: `CURRENT TARGET (${targetLineCount} lines)`,
content: target.content,
trimPriority: 4,
keep: 'both'
});
}
const prompt = this.buildBoundedPrompt(
instruction,
sections,
CODER_MAX_OUTPUT_TOKENS
);
console.log("DEBUG [executeCoder] prompt:", prompt);
const raw = await this.gateway.requestCompletion({
prompt,
max_tokens: CODER_MAX_OUTPUT_TOKENS,
temperature: 0,
seed: 0,
grammar: useScaffold ? SCAFFOLD_GBNF : CODER_GBNF
});
console.log("DEBUG [executeCoder] raw response:", raw);
this.assertNotAborted(signal);
if (useScaffold) {
const payload = JSON.parse(raw);
const result = await this.toolchain.runCheckpointedEdit(() =>
isNewFile
? this.memory.writeNewFile(targetFile, payload.code)
: this.memory.overwriteFile(targetFile, payload.code)
);
this.emit(isNewFile ? 'New file scaffolded inside active checkpoint.' : 'File overwritten inside active checkpoint.', {
targetFile
});
} else {
const diff = this.parseCoderDiff(raw);
this.enforceDeltaOnly(diff, targetLineCount);
const result = await this.toolchain.runCheckpointedEdit(() =>
this.memory.applyDiff(targetFile, diff)
);
if (!result.changed) {
throw new Error('Coder diff was a no-op; refusing to treat it as progress.');
}
this.emit('Unified Diff applied inside active checkpoint.', {
targetFile,
hunks: result.hunksApplied,
fuzzyScores: result.matchScores
});
}
}
/** Runs one verification and, on failure, obtains deterministic debugger advice. */
private async verifyAndDebug(options: {
command: VerificationCommand;
iteration: number;
attempt: number;
targetFile?: string;
signal?: AbortSignal;
persistFailureWithinCheckpoint: boolean;
}): Promise<VerificationDebugResult> {
this.transition(
AgentEngineState.VERIFYING,
`Running verification: ${options.command.display}`
);
this.assertNotAborted(options.signal);
const processResult = await this.toolchain.runSubprocess(
options.command.executable,
options.command.args,
this.verificationTimeoutMs
);
this.assertNotAborted(options.signal);
if (this.processPassed(processResult)) {
this.emit('Verification passed.', {
command: options.command.display,
durationMs: processResult.durationMs
});
return { passed: true, process: processResult };
}
const failureSummary = this.describeProcessFailure(
options.command,
processResult
);
if (options.persistFailureWithinCheckpoint) {
await this.appendKnownBugWithinCheckpoint(
this.formatBugEntry(
'Verification failure',
options.command,
processResult,
options.attempt
)
);
}
return {
passed: false,
process: processResult,
failureSummary
};
}
private async getWorkspaceFilesContent(excludeFile?: string): Promise<string> {
const root = this.memory.workspaceRoot;
try {
const files = await readdir(root);
const parts: string[] = [];
for (const file of files) {
const fullPath = join(root, file);
const fileStat = await stat(fullPath);
if (fileStat.isFile()) {
const name = file.toLowerCase();
if (
name === excludeFile?.toLowerCase() ||
name === 'project.md' ||
name === 'architecture.md' ||
name === 'known_bugs.md' ||
name === 'package.json' ||
name === 'package-lock.json' ||
name === 'tsconfig.json' ||
name === '.gitignore' ||
name.endsWith('.log')
) {
continue;
}
try {
const content = await readFile(fullPath, 'utf8');
parts.push(`### ${file}\r\n\`\`\`typescript\r\n${content}\r\n\`\`\``);
} catch (err) {
// Ignore read errors
}
}
}
return parts.join('\r\n\r\n');
} catch (err) {
return '';
}
}
/**
* Resolves missing dependency compile/test errors by running npm install inside the sandbox.
*/
private async healDependencies(errorText: string): Promise<boolean> {
const regexes = [
/Cannot find module '([^'\s]+)'/i,
/Could not find a declaration file for module '([^'\s]+)'/i
];
let packageName: string | null = null;
let isTypesError = false;
for (const regex of regexes) {
const match = errorText.match(regex);
if (match && match[1]) {
packageName = match[1];
if (regex.source.includes('declaration file') || errorText.includes('corresponding type declarations')) {
isTypesError = true;
}
break;
}
}
if (!packageName) {
return false;
}
// Validate package name safety to prevent arbitrary argument flags
const safePackageRegex = /^@?[a-z0-9-_.]+(?:\/[a-z0-9-_.]+)?$/i;
if (!safePackageRegex.test(packageName)) {
console.warn(`[Self-Healing] Detected unsafe package name suggestion: "${packageName}". Skipping.`);
return false;
}
this.transition(
AgentEngineState.VERIFYING,
`[Self-Healing] Detected missing dependency: "${packageName}". Installing...`
);
try {
const installBase = await this.toolchain.runSubprocess('npm', ['install', packageName], 60000);
if (installBase.exitCode !== 0) {
console.error(`[Self-Healing] Failed to install package "${packageName}":`, installBase.stdout, installBase.stderr);
return false;
}
if (isTypesError && !packageName.startsWith('@types/')) {
const typesPackage = `@types/${packageName}`;
if (safePackageRegex.test(typesPackage)) {
this.transition(
AgentEngineState.VERIFYING,
`[Self-Healing] Installing type definitions: "${typesPackage}"...`
);
await this.toolchain.runSubprocess('npm', ['install', '-D', typesPackage], 60000);
}
}
this.transition(
AgentEngineState.VERIFYING,
`[Self-Healing] Successfully installed missing dependencies for "${packageName}".`
);
return true;
} catch (err) {
console.error('[Self-Healing] Error running npm install:', err);
return false;
}
}
private parseJsonObject(raw: string, role: string): Record<string, unknown> {
let value: unknown;
try {
value = JSON.parse(raw);
} catch (error) {
throw new Error(`${role} returned invalid JSON: ${this.errorMessage(error)}`, {
cause: error
});
}
if (value === null || typeof value !== 'object' || Array.isArray(value)) {
throw new Error(`${role} response must be a JSON object.`);
}
return value as Record<string, unknown>;
}
private rejectUnknownKeys(
value: Record<string, unknown>,
allowed: ReadonlySet<string>,
role: string
): void {
const unknown = Object.keys(value).filter((key) => !allowed.has(key));
if (unknown.length > 0) {
throw new Error(`${role} returned unknown properties: ${unknown.join(', ')}.`);
}
}
/**
* Enforces Rule 5 at runtime. A large file may receive a small diff, but a diff
* removing most of that file is rejected before it reaches WorkspaceMemory.
*/
private enforceDeltaOnly(diff: string, targetLineCount: number): void {
if (targetLineCount <= 100) {
return;
}
const lines = diff.replace(/\r\n/gu, '\n').split('\n');
let removed = 0;
let added = 0;
for (const line of lines) {
if (line.startsWith('--- ') || line.startsWith('+++ ')) {
continue;
}
if (line.startsWith('-')) {
removed += 1;
} else if (line.startsWith('+')) {
added += 1;
}
}
const rewriteThreshold = Math.ceil(targetLineCount * 0.8);
if (removed >= rewriteThreshold || (removed > 100 && added > 100)) {
throw new Error(
`Rule 5 violation: diff removes ${removed} and adds ${added} lines ` +
`for a ${targetLineCount}-line file.`
);
}
}
private resolveVerificationCommand(command?: string): VerificationCommand {
return this.parseCommandLine(command ?? this.defaultVerificationCommand);
}
/**
* Parses a deliberately small command-line notation without invoking a shell.
* Quotes only group arguments. Shell operators are rejected even though spawn's
* shell:false would pass them literally; this catches unsafe model intent early.