This repository was archived by the owner on Jun 8, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsymphony-loop.ts
More file actions
1404 lines (1267 loc) · 44.3 KB
/
Copy pathsymphony-loop.ts
File metadata and controls
1404 lines (1267 loc) · 44.3 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
import { execSync, spawn } from "node:child_process";
import crypto from "node:crypto";
import { closeSync, existsSync, openSync, readFileSync, readdirSync } from "node:fs";
import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import type {
OperationDispatcher,
OperationRequestContext,
} from "../operation-dispatcher.js";
import { assertPathAllowed, DirectoryNotAllowedError } from "../security.js";
import { findPluginScript } from "./plugin-cache.js";
import {
expandHome,
resolveWorktreeParentDir,
} from "./symphony-utils.js";
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
type LoopCommand = "PLAN" | "EXECUTE" | "REQUEST_CHANGES" | "DECOMPOSE";
const VALID_COMMANDS = new Set<LoopCommand>(["PLAN", "EXECUTE", "REQUEST_CHANGES", "DECOMPOSE"]);
interface LoopArtifact {
id?: string;
type: string;
title?: string;
content: string;
}
interface LoopRepo {
fullName: string;
branch: string;
}
interface LoopCommitter {
name: string;
email: string;
}
interface LoopRequestBody {
loopId: string;
command: LoopCommand;
closedLoopAuthToken: string;
apiBaseUrl: string;
artifacts: LoopArtifact[];
repo?: LoopRepo;
committer?: LoopCommitter;
artifactSlug?: string;
parentLoopId?: string;
parentBranchName?: string;
parentSessionId?: string;
prompt?: string;
}
/** Track running loop processes for cancellation and to prevent GC of ChildProcess. */
interface RunningLoop {
pid: number;
child: ReturnType<typeof spawn>;
}
const runningLoops = new Map<string, RunningLoop>();
function loopLog(loopId: string, ...args: unknown[]): void {
const short = loopId.slice(0, 8);
const ts = new Date().toISOString().slice(11, 23);
console.log(`[symphony-loop][${ts}][${short}]`, ...args);
}
function loopError(loopId: string, ...args: unknown[]): void {
const short = loopId.slice(0, 8);
const ts = new Date().toISOString().slice(11, 23);
console.error(`[symphony-loop][${ts}][${short}]`, ...args);
}
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function json(
context: OperationRequestContext,
status: number,
payload: unknown
): void {
context.response.statusCode = status;
context.response.setHeader("content-type", "application/json");
context.response.end(JSON.stringify(payload));
}
function parseJsonBody(
context: OperationRequestContext
): Record<string, unknown> | null {
if (!context.body.trim()) {
return null;
}
try {
return JSON.parse(context.body) as Record<string, unknown>;
} catch {
return null;
}
}
function shellEscape(value: string): string {
return "'" + value.replaceAll("'", String.raw`'\''`) + "'";
}
/**
* Find the stream_formatter.py script from the code plugin.
* Falls back to null if not installed — caller should degrade gracefully.
*/
function findStreamFormatter(): string | null {
const cacheRoot = path.join(os.homedir(), ".claude", "plugins", "cache", "closedloop-ai", "code");
try {
const versions = readdirSync(cacheRoot)
.filter((e: string) => /^\d+\.\d+\.\d+/.test(e))
.sort((a: string, b: string) => {
const pa = a.split(".").map(Number);
const pb = b.split(".").map(Number);
for (let i = 0; i < 3; i++) {
const diff = (pb[i] ?? 0) - (pa[i] ?? 0);
if (diff !== 0) { return diff; }
}
return 0;
});
for (const v of versions) {
const p = path.join(cacheRoot, v, "tools", "python", "stream_formatter.py");
if (existsSync(p)) { return p; }
}
} catch {
// Plugin not installed
}
return null;
}
/**
* Build a bash pipeline command that runs claude with stream-json output,
* filters JSON lines, tees to a jsonl log, and formats for human reading.
* Falls back to raw claude if formatter is not available.
*/
function buildClaudePipeline(
claudeArgs: string[],
claudeWorkDir: string,
stdinFile?: string
): { cmd: string; args: string[] } {
const formatter = findStreamFormatter();
const stderrFile = path.join(claudeWorkDir, "claude-stderr.log");
const jsonlFile = path.join(claudeWorkDir, "claude-output.jsonl");
// Build the claude command with properly escaped args
const escapedArgs = claudeArgs.map(shellEscape).join(" ");
const claudeCmd = stdinFile
? `claude ${escapedArgs} < ${shellEscape(stdinFile)}`
: `claude ${escapedArgs}`;
if (formatter) {
// Full pipeline matching run-loop.sh:
// claude ... 2>stderr | grep JSON | tee jsonl | formatter
const pipeline = [
`${claudeCmd} 2>${shellEscape(stderrFile)}`,
"grep --line-buffered '^{'",
`tee -a ${shellEscape(jsonlFile)}`,
`python3 ${shellEscape(formatter)}`,
].join(" | ");
return { cmd: "bash", args: ["-c", pipeline] };
}
// No formatter — run claude directly (raw stream-json to stdout)
if (stdinFile) {
return { cmd: "bash", args: ["-c", claudeCmd] };
}
return { cmd: "claude", args: claudeArgs };
}
/**
* Validate apiBaseUrl to prevent SSRF to private/metadata/loopback endpoints.
* Uses deny-by-default for IP literals: extracts the IPv4 address (including
* from IPv4-mapped IPv6 like ::ffff:127.0.0.1) and checks it against
* private/reserved ranges. Non-IP hostnames are allowed except "localhost".
*/
function validateApiBaseUrl(url: string): boolean {
let parsed: URL;
try {
parsed = new URL(url);
} catch {
return false;
}
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
return false;
}
// WHATWG URL parser strips brackets from IPv6, so hostname is e.g. "::1"
const hostname = parsed.hostname;
if (hostname === "localhost") {
return false;
}
// Extract IPv4 for range checking. Handles plain IPv4, IPv4-mapped IPv6
// (::ffff:1.2.3.4), and IPv4-compatible IPv6 (::1.2.3.4).
const ipv4 = extractIPv4(hostname);
if (ipv4) {
return !isPrivateIPv4(ipv4);
}
// Pure IPv6 (not IPv4-mapped): block loopback (::1) and all-zeros (::)
if (hostname.includes(":")) {
const normalized = hostname.replace(/^\[|]$/g, "");
if (normalized === "::1" || normalized === "::" || normalized === "0:0:0:0:0:0:0:0" || normalized === "0:0:0:0:0:0:0:1") {
return false;
}
// Block any remaining IPv6 with embedded IPv4-mapped prefix
if (/^::ffff:/i.test(normalized) || /^0{0,4}:0{0,4}:0{0,4}:0{0,4}:0{0,4}:ffff:/i.test(normalized)) {
return false;
}
// Block ULA (fc00::/7) and link-local (fe80::/10)
if (/^f[cd]/i.test(normalized) || /^fe[89ab]/i.test(normalized)) {
return false;
}
}
return true;
}
/** Extract the IPv4 dotted-quad from a hostname, handling IPv4-mapped IPv6. */
function extractIPv4(hostname: string): string | null {
// Plain IPv4
if (/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(hostname)) {
return hostname;
}
// IPv4-mapped IPv6: "::ffff:1.2.3.4" or "[::ffff:1.2.3.4]"
const stripped = hostname.replace(/^\[|]$/g, "");
const mapped = /::ffff:(\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})$/i.exec(stripped);
if (mapped) {
return mapped[1];
}
return null;
}
/** Check if an IPv4 dotted-quad is in a private/reserved range. */
function isPrivateIPv4(ip: string): boolean {
const parts = ip.split(".").map(Number);
if (parts.length !== 4 || parts.some((p) => Number.isNaN(p) || p < 0 || p > 255)) {
return true; // Malformed → treat as private (deny)
}
const [a, b] = parts;
return (
a === 0 || // 0.0.0.0/8
a === 10 || // 10.0.0.0/8
a === 127 || // 127.0.0.0/8 (loopback)
(a === 169 && b === 254) || // 169.254.0.0/16 (link-local / cloud metadata)
(a === 172 && b >= 16 && b <= 31) || // 172.16.0.0/12
(a === 192 && b === 168) // 192.168.0.0/16
);
}
/** Find the local repo path for a given fullName (e.g. "org/repo"). */
function findLocalRepo(
fullName: string,
allowedDirs: string[]
): string | null {
const repoName = fullName.split("/").pop();
if (!repoName) {
return null;
}
for (const dir of allowedDirs) {
const expanded = expandHome(dir);
// Check if the directory itself is the repo
if (path.basename(expanded) === repoName && existsSync(expanded)) {
return expanded;
}
// Check subdirectory
const candidate = path.join(expanded, repoName);
if (existsSync(candidate)) {
return candidate;
}
}
return null;
}
/**
* Resolve worktree directory for a loop.
* Uses full untruncated stable ID for directory naming.
*/
function resolveLoopWorktreeDir(
expandedRepoPath: string,
stableId: string
): string {
const repoName = path.basename(expandedRepoPath);
return path.join(
resolveWorktreeParentDir(expandedRepoPath),
`${repoName}-loop-${stableId}`
);
}
/**
* Slugify a loop ID for worktree/branch naming.
* Matches ECS harness convention: lowercase, non-alnum to dashes, max 50 chars.
*/
function slugifyLoopId(loopId: string): string {
return loopId
.toLowerCase()
.replace(/[^a-z0-9-]/g, "-")
.slice(0, 50);
}
/**
* Pick the stable ID for worktree/branch naming.
* Uses loopId (matching ECS harness branch/run-dir naming).
*/
function pickStableId(body: LoopRequestBody): string {
return slugifyLoopId(body.loopId);
}
// ---------------------------------------------------------------------------
// API communication (events + artifact upload)
// ---------------------------------------------------------------------------
async function postLoopEvent(
apiBaseUrl: string,
loopId: string,
token: string,
eventBody: Record<string, unknown>
): Promise<void> {
const url = `${apiBaseUrl}/loops/${loopId}/events`;
// Auto-inject timestamp on every event (matches ECS harness reportEvent())
const payload: Record<string, unknown> = {
...eventBody,
timestamp: eventBody.timestamp ?? new Date().toISOString(),
};
loopLog(loopId, `POST event: ${payload.type}`, url);
try {
const resp = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json",
"x-loop-event-nonce": crypto.randomUUID(),
},
body: JSON.stringify(payload),
});
if (!resp.ok) {
const text = await resp.text().catch(() => "");
loopError(loopId, `Event POST failed: ${resp.status} ${resp.statusText}`, text);
} else {
loopLog(loopId, `Event POST success: ${resp.status}`);
}
} catch (err) {
loopError(loopId, "Failed to post event:", err);
}
}
async function uploadArtifacts(
apiBaseUrl: string,
loopId: string,
token: string,
body: Record<string, unknown>
): Promise<void> {
const url = `${apiBaseUrl}/loops/${loopId}/upload-artifacts`;
loopLog(loopId, "Uploading artifacts...", url);
try {
const resp = await fetch(url, {
method: "POST",
headers: {
"Authorization": `Bearer ${token}`,
"Content-Type": "application/json",
},
body: JSON.stringify(body),
});
if (!resp.ok) {
const text = await resp.text().catch(() => "");
loopError(loopId, `Upload failed: ${resp.status} ${resp.statusText}`, text);
} else {
loopLog(loopId, `Upload success: ${resp.status}`);
}
} catch (err) {
loopError(loopId, "Failed to upload artifacts:", err);
}
}
// ---------------------------------------------------------------------------
// Worktree management
// ---------------------------------------------------------------------------
async function ensureWorktree(
expandedRepoPath: string,
worktreeDir: string,
branchName: string,
baseBranch: string
): Promise<void> {
if (existsSync(worktreeDir)) {
return;
}
await fs.mkdir(path.dirname(worktreeDir), { recursive: true });
try {
execSync("git fetch origin", {
cwd: expandedRepoPath,
stdio: "pipe",
timeout: 30_000,
});
} catch {
// non-fatal
}
// Resolve base ref
let baseRef = `origin/${baseBranch}`;
try {
execSync(`git rev-parse --verify ${shellEscape(baseRef)}`, {
cwd: expandedRepoPath,
stdio: "pipe",
timeout: 10_000,
});
} catch {
baseRef = baseBranch;
}
execSync(
`git worktree add -B ${shellEscape(branchName)} ${shellEscape(worktreeDir)} ${shellEscape(baseRef)}`,
{
cwd: expandedRepoPath,
stdio: "pipe",
timeout: 30_000,
}
);
}
/** Find existing worktree for a branch name. */
function findWorktreeForBranch(
expandedRepoPath: string,
branchName: string
): string | null {
try {
const output = execSync("git worktree list --porcelain", {
cwd: expandedRepoPath,
encoding: "utf-8",
stdio: "pipe",
timeout: 10_000,
});
let currentWorktree: string | null = null;
for (const line of output.split("\n")) {
if (line.startsWith("worktree ")) {
currentWorktree = line.slice("worktree ".length);
}
if (line.startsWith("branch ") && line.endsWith(`/${branchName}`)) {
return currentWorktree;
}
}
} catch {
// fall through
}
return null;
}
// findExistingLoopWorktree was removed — it greedy-matched ANY loop worktree
// from ANY prior loop, causing new PLAN loops to reuse stale worktrees.
// PLAN always creates a fresh worktree. EXECUTE/REQUEST_CHANGES reuse via
// findWorktreeForBranch(parentBranchName) which matches the specific parent.
// ---------------------------------------------------------------------------
// Per-command artifact writing
// ---------------------------------------------------------------------------
/**
* Write PRD for PLAN command.
* Matches ECS harness writePrdFile(): prompt first, then PRD artifact, then FEATURE.
*/
async function writeArtifactsForPlan(
claudeWorkDir: string,
artifacts: LoopArtifact[],
prompt?: string
): Promise<void> {
// Priority: explicit prompt > PRD artifact > FEATURE artifact (matches harness)
let prdContent = prompt ?? null;
if (!prdContent) {
const prdArtifact = artifacts.find((a) => a.type === "PRD" || a.type === "prd");
const featureArtifact = prdArtifact
? null
: artifacts.find((a) => a.type === "FEATURE" || a.type === "artifact");
const source = prdArtifact ?? featureArtifact;
if (source?.content) {
prdContent = source.content;
}
}
if (prdContent) {
await fs.writeFile(path.join(claudeWorkDir, "prd.md"), prdContent);
}
}
async function writeArtifactsForExecuteOrAmend(
claudeWorkDir: string,
artifacts: LoopArtifact[],
prompt?: string
): Promise<void> {
for (const artifact of artifacts) {
if (artifact.type === "IMPLEMENTATION_PLAN" || artifact.type === "plan") {
// Sync plan content like ECS harness's syncPlanFromContextPack():
// If plan.json already exists (from parent PLAN loop), update only the
// .content field — preserving tasks, openQuestions, metadata, etc.
// This picks up manual edits the user made in the Liveblocks editor.
const planJsonPath = path.join(claudeWorkDir, "plan.json");
if (existsSync(planJsonPath)) {
try {
const existing = JSON.parse(readFileSync(planJsonPath, "utf-8")) as Record<string, unknown>;
existing.content = artifact.content;
await fs.writeFile(planJsonPath, JSON.stringify(existing, null, 2));
} catch {
// If existing plan.json is corrupt, overwrite entirely
await fs.writeFile(planJsonPath, artifact.content);
}
} else {
// No existing plan.json — write the content as-is.
// If it's valid JSON, write directly. Otherwise wrap it.
try {
JSON.parse(artifact.content);
await fs.writeFile(planJsonPath, artifact.content);
} catch {
await fs.writeFile(
planJsonPath,
JSON.stringify({ content: artifact.content }, null, 2)
);
}
}
} else if (artifact.type === "prd" || artifact.type === "artifact" || artifact.type === "PRD" || artifact.type === "FEATURE") {
await fs.writeFile(path.join(claudeWorkDir, "prd.md"), artifact.content);
}
}
if (prompt) {
await fs.writeFile(path.join(claudeWorkDir, "prompt.md"), prompt);
}
}
async function writeArtifactsForDecompose(
tmpDir: string,
artifacts: LoopArtifact[],
prompt?: string
): Promise<void> {
// Same priority as writeArtifactsForPlan: prompt > PRD > FEATURE
let prdContent = prompt ?? null;
if (!prdContent) {
const prdArtifact = artifacts.find((a) => a.type === "PRD" || a.type === "prd");
const featureArtifact = prdArtifact
? null
: artifacts.find((a) => a.type === "FEATURE" || a.type === "artifact");
const source = prdArtifact ?? featureArtifact;
if (source?.content) {
prdContent = source.content;
}
}
if (prdContent) {
await fs.writeFile(path.join(tmpDir, "prd.md"), prdContent);
}
}
// ---------------------------------------------------------------------------
// Per-command output reading
// ---------------------------------------------------------------------------
function readJsonFile(filePath: string): unknown | null {
try {
if (!existsSync(filePath)) {
return null;
}
return JSON.parse(readFileSync(filePath, "utf-8"));
} catch {
return null;
}
}
function readTextFile(filePath: string): string | null {
try {
if (!existsSync(filePath)) {
return null;
}
return readFileSync(filePath, "utf-8");
} catch {
return null;
}
}
function readPlanOutputs(claudeWorkDir: string): Record<string, unknown> {
const plan = readJsonFile(path.join(claudeWorkDir, "plan.json"));
const openQuestions = readTextFile(
path.join(claudeWorkDir, "open-questions.md")
);
const judges = readJsonFile(path.join(claudeWorkDir, "judges.json"));
return {
plan: plan ?? undefined,
openQuestions: openQuestions ?? undefined,
judges: judges ?? undefined,
};
}
function readExecuteOutputs(claudeWorkDir: string): Record<string, unknown> {
const executionResult = readJsonFile(
path.join(claudeWorkDir, "execution-result.json")
);
const codeJudges = readJsonFile(
path.join(claudeWorkDir, "code-judges.json")
);
return {
executionResult: executionResult ?? undefined,
codeJudges: codeJudges ?? undefined,
};
}
function readDecomposeOutputs(workDir: string): Record<string, unknown> {
const features = readJsonFile(path.join(workDir, "features.json"));
return { features: features ?? undefined };
}
/** Parse token usage from claude-output.jsonl (JSONL stream output). */
function parseTokenUsage(claudeWorkDir: string): { input: number; output: number } {
const totals = { input: 0, output: 0 };
const outputFile = path.join(claudeWorkDir, "claude-output.jsonl");
if (!existsSync(outputFile)) {
return totals;
}
try {
const content = readFileSync(outputFile, "utf-8");
for (const line of content.split("\n")) {
if (!line.trim()) {
continue;
}
try {
const entry = JSON.parse(line) as Record<string, unknown>;
if (entry.type === "assistant") {
const message = entry.message as Record<string, unknown> | undefined;
const usage = message?.usage as Record<string, number> | undefined;
if (usage) {
totals.input +=
(usage.input_tokens ?? 0) +
(usage.cache_creation_input_tokens ?? 0) +
(usage.cache_read_input_tokens ?? 0);
totals.output += usage.output_tokens ?? 0;
}
}
} catch {
// skip malformed lines
}
}
} catch {
// file read error
}
return totals;
}
// ---------------------------------------------------------------------------
// Git operations (EXECUTE only)
// ---------------------------------------------------------------------------
function executeGitOperations(
worktreeDir: string,
committer: LoopCommitter | undefined,
baseBranch: string
): { prUrl: string; prNumber: number; branchName: string; commitSha: string } | null {
const env: Record<string, string> = { ...process.env } as Record<string, string>;
if (committer) {
env.GIT_AUTHOR_NAME = committer.name;
env.GIT_AUTHOR_EMAIL = committer.email;
env.GIT_COMMITTER_NAME = committer.name;
env.GIT_COMMITTER_EMAIL = committer.email;
}
// Check for changes
try {
const status = execSync("git status --porcelain", {
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
timeout: 10_000,
}).trim();
if (!status) {
return null; // No changes
}
} catch {
return null;
}
// Stage, commit, push
try {
execSync("git add -A", {
cwd: worktreeDir,
stdio: "pipe",
env,
timeout: 10_000,
});
execSync('git commit -m "Symphony: implement plan"', {
cwd: worktreeDir,
stdio: "pipe",
env,
timeout: 30_000,
});
const branchName = execSync("git rev-parse --abbrev-ref HEAD", {
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
timeout: 10_000,
}).trim();
execSync(`git push -u origin ${shellEscape(branchName)}`, {
cwd: worktreeDir,
stdio: "pipe",
env,
timeout: 60_000,
});
const commitSha = execSync("git rev-parse HEAD", {
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
timeout: 10_000,
}).trim();
// Check for existing PR before creating (handles retries gracefully)
let prUrl: string;
let prNumber: number;
try {
const existingPr = execSync(
`gh pr view --json url,number ${shellEscape(branchName)}`,
{
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
env,
timeout: 15_000,
}
).trim();
const parsed = JSON.parse(existingPr) as { url: string; number: number };
prUrl = parsed.url;
prNumber = parsed.number;
} catch {
// No existing PR — create one
const prOutput = execSync(
`gh pr create --title "Symphony: implement plan" --body "Automated PR from Symphony loop" --base ${shellEscape(baseBranch)}`,
{
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
env,
timeout: 30_000,
}
).trim();
prUrl = prOutput;
const prNumberMatch = /\/pull\/(\d+)/.exec(prUrl);
prNumber = prNumberMatch ? Number.parseInt(prNumberMatch[1], 10) : 0;
}
return { prUrl, prNumber, branchName, commitSha };
} catch (err) {
console.error("[symphony-loop] Git operations failed:", err);
return null;
}
}
// ---------------------------------------------------------------------------
// Process completion handler (async, runs after spawn)
// ---------------------------------------------------------------------------
async function handleProcessCompletion(
exitCode: number,
body: LoopRequestBody,
worktreeDir: string | null,
claudeWorkDir: string
): Promise<void> {
const { loopId, command, closedLoopAuthToken, apiBaseUrl, committer } = body;
loopLog(loopId, `Process exited with code ${exitCode}, command=${command}`);
runningLoops.delete(loopId);
if (exitCode !== 0) {
loopError(loopId, `Process failed with exit code ${exitCode}`);
// Error shape matches ECS harness: top-level code/message, not nested error object
await postLoopEvent(apiBaseUrl, loopId, closedLoopAuthToken, {
type: "error",
code: "PROCESS_FAILED",
message: `Process exited with code ${exitCode}`,
loopId,
});
return;
}
// Read outputs per command
let artifacts: Record<string, unknown> = {};
const metadata: Record<string, unknown> = {};
if (command === "PLAN" || command === "REQUEST_CHANGES") {
artifacts = readPlanOutputs(claudeWorkDir);
} else if (command === "EXECUTE") {
artifacts = readExecuteOutputs(claudeWorkDir);
// Git operations for EXECUTE
if (worktreeDir) {
const baseBranch = body.repo?.branch ?? "main";
const gitResult = executeGitOperations(
worktreeDir,
committer,
baseBranch
);
if (gitResult) {
// Merge git info into execution result
const execResult =
(artifacts.executionResult as Record<string, unknown>) ?? {};
execResult.pr_url = gitResult.prUrl;
execResult.pr_number = gitResult.prNumber;
execResult.branch_name = gitResult.branchName;
execResult.commit_sha = gitResult.commitSha;
execResult.has_changes = true;
execResult.base_branch = baseBranch;
artifacts.executionResult = execResult;
metadata.branchName = gitResult.branchName;
}
}
} else if (command === "DECOMPOSE") {
artifacts = readDecomposeOutputs(claudeWorkDir);
}
// Read session ID if available
const sessionFile = path.join(claudeWorkDir, "session-id.txt");
const sessionId = readTextFile(sessionFile);
if (sessionId) {
metadata.sessionId = sessionId.trim();
}
// Upload artifacts
loopLog(loopId, "Artifact keys:", Object.keys(artifacts));
await uploadArtifacts(apiBaseUrl, loopId, closedLoopAuthToken, {
artifacts,
metadata,
});
// Parse token usage from claude output
const tokensUsed = parseTokenUsage(claudeWorkDir);
loopLog(loopId, `Tokens used: input=${tokensUsed.input}, output=${tokensUsed.output}`);
// Post completed event — shape matches ECS harness reportFinalStatus()
const result: Record<string, unknown> = {
exitCode,
subtype: command.toLowerCase(),
};
if (command === "EXECUTE" && artifacts.executionResult) {
const execResult = artifacts.executionResult as Record<string, unknown>;
result.prUrl = execResult.pr_url;
result.prNumber = execResult.pr_number;
result.branchName = execResult.branch_name;
result.has_changes = execResult.has_changes ?? false;
}
// Include worktree branch name for all commands that use a worktree.
// The server persists this on the loop record for display/debugging.
if (worktreeDir && !result.branchName) {
try {
const branch = execSync("git rev-parse --abbrev-ref HEAD", {
cwd: worktreeDir,
encoding: "utf-8",
stdio: "pipe",
timeout: 5_000,
}).trim();
if (branch) {
result.branchName = branch;
}
} catch {
// Non-critical — worktree may already be cleaned up
}
}
// sessionId inside result (matches harness)
if (metadata.sessionId) {
result.sessionId = metadata.sessionId;
}
const completedEvent: Record<string, unknown> = {
type: "completed",
result,
tokensUsed,
loopId,
};
loopLog(loopId, "Posting completed event...");
await postLoopEvent(apiBaseUrl, loopId, closedLoopAuthToken, completedEvent);
loopLog(loopId, "Loop completed successfully");
// Clean up DECOMPOSE temp directory after all reads and uploads are complete
if (command === "DECOMPOSE") {
fs.rm(claudeWorkDir, { recursive: true, force: true }).catch(() => {});
}
}
// ---------------------------------------------------------------------------
// Main route handler
// ---------------------------------------------------------------------------
async function handleLoopRequest(
context: OperationRequestContext,
getAllowedDirectories: () => string[]
): Promise<void> {
const rawBody = parseJsonBody(context);
if (!rawBody) {
json(context, 400, { error: "Invalid JSON body" });
return;
}
const body = rawBody as unknown as LoopRequestBody;
if (!body.loopId || !body.command || !body.closedLoopAuthToken || !body.apiBaseUrl) {
json(context, 400, {
error: "Missing required fields: loopId, command, closedLoopAuthToken, apiBaseUrl",
});
return;
}
if (!VALID_COMMANDS.has(body.command)) {
json(context, 400, { error: `Invalid command: ${body.command}` });
return;
}
if (!/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/i.test(body.loopId)) {
json(context, 400, { error: "loopId must be a valid UUID" });
return;
}
if (!Array.isArray(body.artifacts)) {
json(context, 400, { error: "artifacts must be an array" });
return;
}
if (!validateApiBaseUrl(body.apiBaseUrl)) {
json(context, 400, {
error: "Invalid apiBaseUrl: must be a valid http(s) URL to a non-private host",
});
return;
}
if (runningLoops.has(body.loopId)) {
json(context, 409, { error: "Loop is already running on this machine" });
return;
}
// Claim the loopId immediately to prevent concurrent requests from racing
// past the has() check. Replaced with real entry after spawn succeeds.
runningLoops.set(body.loopId, { pid: -1, child: null as unknown as ReturnType<typeof spawn> });
loopLog(body.loopId, `Received ${body.command} request, repo=${body.repo?.fullName ?? "none"}, stableId=${pickStableId(body)}, parentSessionId=${body.parentSessionId ?? "none"}`);
let spawnedSuccessfully = false;
try {
const allowedDirs = getAllowedDirectories();
let expandedRepoPath: string | null = null;
if (body.repo?.fullName) {
expandedRepoPath = findLocalRepo(body.repo.fullName, allowedDirs);
if (!expandedRepoPath) {
json(context, 404, {
error: `Repository not found locally: ${body.repo.fullName}`,
});
return;
}
try {
assertPathAllowed(expandedRepoPath, allowedDirs);
} catch (err) {
if (err instanceof DirectoryNotAllowedError) {
json(context, 403, { error: "Repository path not allowed" });
return;
}
throw err;
}
}
let worktreeDir: string | null = null;
let claudeWorkDir: string;
if (body.command === "DECOMPOSE") {
// DECOMPOSE: use temp dir, no worktree needed
const tmpDir = path.join(
os.tmpdir(),
`symphony-decompose-${body.loopId.slice(0, 8)}`
);
await fs.mkdir(tmpDir, { recursive: true });
claudeWorkDir = tmpDir;
await writeArtifactsForDecompose(claudeWorkDir, body.artifacts, body.prompt);
} else if (!expandedRepoPath) {
json(context, 400, {
error: "Repository required for PLAN, EXECUTE, and REQUEST_CHANGES commands",
});
return;
} else if (body.command === "PLAN" || body.command === "EXECUTE" || body.command === "REQUEST_CHANGES") {
// Worktree keyed by artifact slug (e.g., symphony/PLAN-5).
// PLAN always creates fresh; EXECUTE/REQUEST_CHANGES reuse.
// Sanitize slug the same way we sanitize loopId to prevent path traversal.