@clagentic/console 1.0.0-beta.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CREDITS.md +3 -0
- package/LICENSE +21 -0
- package/README.md +250 -0
- package/bin/cli.js +2812 -0
- package/lib/agents-favorites.js +164 -0
- package/lib/agents.js +282 -0
- package/lib/ask-user-mcp-server.js +120 -0
- package/lib/browser-mcp-server.js +484 -0
- package/lib/build-user-env.js +63 -0
- package/lib/certs/fullchain.pem +47 -0
- package/lib/certs/privkey.pem +5 -0
- package/lib/cli-sessions.js +265 -0
- package/lib/codex-defaults.js +18 -0
- package/lib/config.js +332 -0
- package/lib/crisis-safety.js +60 -0
- package/lib/daemon-projects.js +164 -0
- package/lib/daemon.js +1602 -0
- package/lib/dm.js +128 -0
- package/lib/ipc.js +125 -0
- package/lib/ipv4-only.js +39 -0
- package/lib/mcp-local.js +385 -0
- package/lib/notes.js +141 -0
- package/lib/os-users.js +529 -0
- package/lib/pages.js +1325 -0
- package/lib/project-connection.js +302 -0
- package/lib/project-external-trigger.js +236 -0
- package/lib/project-file-watch.js +120 -0
- package/lib/project-filesystem.js +528 -0
- package/lib/project-http.js +753 -0
- package/lib/project-image.js +95 -0
- package/lib/project-knowledge.js +88 -0
- package/lib/project-loop.js +1304 -0
- package/lib/project-mcp.js +374 -0
- package/lib/project-memory.js +39 -0
- package/lib/project-notifications.js +262 -0
- package/lib/project-sessions.js +1581 -0
- package/lib/project-user-mention.js +193 -0
- package/lib/project-user-message.js +628 -0
- package/lib/project.js +1303 -0
- package/lib/public/app.js +1031 -0
- package/lib/public/apple-touch-icon.png +0 -0
- package/lib/public/claude-code-avatar.png +0 -0
- package/lib/public/codex-avatar.png +0 -0
- package/lib/public/console-icon.png +0 -0
- package/lib/public/css/admin.css +736 -0
- package/lib/public/css/agent-picker.css +119 -0
- package/lib/public/css/base.css +235 -0
- package/lib/public/css/channel-layout.css +441 -0
- package/lib/public/css/command-palette.css +559 -0
- package/lib/public/css/debate.css +1609 -0
- package/lib/public/css/diff.css +139 -0
- package/lib/public/css/filebrowser.css +1976 -0
- package/lib/public/css/highlight.css +144 -0
- package/lib/public/css/home-hub.css +545 -0
- package/lib/public/css/icon-strip.css +1856 -0
- package/lib/public/css/input.css +1349 -0
- package/lib/public/css/loop.css +1248 -0
- package/lib/public/css/mention.css +317 -0
- package/lib/public/css/menus.css +857 -0
- package/lib/public/css/messages.css +1833 -0
- package/lib/public/css/mobile-nav.css +1332 -0
- package/lib/public/css/notifications-center.css +296 -0
- package/lib/public/css/overlays.css +1273 -0
- package/lib/public/css/playbook.css +264 -0
- package/lib/public/css/profile.css +397 -0
- package/lib/public/css/rewind.css +671 -0
- package/lib/public/css/scheduler-modal.css +1495 -0
- package/lib/public/css/scheduler.css +1420 -0
- package/lib/public/css/server-settings.css +909 -0
- package/lib/public/css/session-search.css +159 -0
- package/lib/public/css/sidebar.css +2012 -0
- package/lib/public/css/skills.css +789 -0
- package/lib/public/css/sticky-notes.css +854 -0
- package/lib/public/css/stt.css +155 -0
- package/lib/public/css/title-bar.css +674 -0
- package/lib/public/css/tooltip.css +67 -0
- package/lib/public/css/user-settings.css +702 -0
- package/lib/public/emoji-data.json +1 -0
- package/lib/public/favicon-banded-32.png +0 -0
- package/lib/public/favicon-banded.png +0 -0
- package/lib/public/favicon-dark.svg +32 -0
- package/lib/public/favicon.svg +32 -0
- package/lib/public/icon-192.png +0 -0
- package/lib/public/icon-512.png +0 -0
- package/lib/public/icon-banded-76.png +0 -0
- package/lib/public/icon-banded-96.png +0 -0
- package/lib/public/icon-mono.svg +25 -0
- package/lib/public/icons/email/gmail.svg +7 -0
- package/lib/public/icons/email/outlook.svg +35 -0
- package/lib/public/icons/email/yahoo.svg +1 -0
- package/lib/public/index.html +1946 -0
- package/lib/public/manifest.json +27 -0
- package/lib/public/markdown-worker.js +43 -0
- package/lib/public/marked.min.js +6 -0
- package/lib/public/modules/admin.js +954 -0
- package/lib/public/modules/agent-picker.js +429 -0
- package/lib/public/modules/app-connection.js +216 -0
- package/lib/public/modules/app-cursors.js +492 -0
- package/lib/public/modules/app-dm.js +265 -0
- package/lib/public/modules/app-favicon.js +231 -0
- package/lib/public/modules/app-header.js +242 -0
- package/lib/public/modules/app-home-hub.js +432 -0
- package/lib/public/modules/app-loop-ui.js +691 -0
- package/lib/public/modules/app-loop-wizard.js +439 -0
- package/lib/public/modules/app-messages.js +1415 -0
- package/lib/public/modules/app-misc.js +463 -0
- package/lib/public/modules/app-notifications.js +651 -0
- package/lib/public/modules/app-panels.js +1061 -0
- package/lib/public/modules/app-projects.js +875 -0
- package/lib/public/modules/app-rate-limit.js +529 -0
- package/lib/public/modules/app-rendering.js +739 -0
- package/lib/public/modules/app-skills-install.js +285 -0
- package/lib/public/modules/avatar.js +36 -0
- package/lib/public/modules/command-palette.js +491 -0
- package/lib/public/modules/console-logo.js +162 -0
- package/lib/public/modules/context-sources.js +365 -0
- package/lib/public/modules/diff.js +412 -0
- package/lib/public/modules/dom-refs.js +21 -0
- package/lib/public/modules/emoji-picker.js +222 -0
- package/lib/public/modules/events.js +21 -0
- package/lib/public/modules/filebrowser.js +1966 -0
- package/lib/public/modules/fileicons.js +172 -0
- package/lib/public/modules/icons.js +80 -0
- package/lib/public/modules/input.js +1102 -0
- package/lib/public/modules/longpress.js +74 -0
- package/lib/public/modules/markdown.js +486 -0
- package/lib/public/modules/mcp-ui.js +295 -0
- package/lib/public/modules/mention.js +1093 -0
- package/lib/public/modules/notifications.js +613 -0
- package/lib/public/modules/playbook.js +578 -0
- package/lib/public/modules/profile.js +594 -0
- package/lib/public/modules/project-settings.js +849 -0
- package/lib/public/modules/project-switcher.js +375 -0
- package/lib/public/modules/qrcode.js +87 -0
- package/lib/public/modules/rewind.js +381 -0
- package/lib/public/modules/scheduler-config.js +1611 -0
- package/lib/public/modules/scheduler-history.js +131 -0
- package/lib/public/modules/scheduler.js +1689 -0
- package/lib/public/modules/server-settings.js +842 -0
- package/lib/public/modules/session-search.js +456 -0
- package/lib/public/modules/settings-defaults.js +253 -0
- package/lib/public/modules/sidebar-mobile.js +1425 -0
- package/lib/public/modules/sidebar-projects.js +2022 -0
- package/lib/public/modules/sidebar-sessions.js +1548 -0
- package/lib/public/modules/sidebar-users.js +449 -0
- package/lib/public/modules/sidebar.js +348 -0
- package/lib/public/modules/skills.js +793 -0
- package/lib/public/modules/state.js +3 -0
- package/lib/public/modules/sticky-notes.js +1221 -0
- package/lib/public/modules/store.js +34 -0
- package/lib/public/modules/stt.js +266 -0
- package/lib/public/modules/terminal.js +987 -0
- package/lib/public/modules/theme.js +812 -0
- package/lib/public/modules/tool-palette.js +562 -0
- package/lib/public/modules/tools.js +2285 -0
- package/lib/public/modules/tooltip.js +150 -0
- package/lib/public/modules/user-settings.js +544 -0
- package/lib/public/modules/utils.js +56 -0
- package/lib/public/modules/ws-ref.js +26 -0
- package/lib/public/style.css +34 -0
- package/lib/public/sw.js +159 -0
- package/lib/push.js +149 -0
- package/lib/scheduler.js +471 -0
- package/lib/sdk-bridge.js +1792 -0
- package/lib/sdk-message-processor.js +740 -0
- package/lib/sdk-message-queue.js +42 -0
- package/lib/sdk-skill-discovery.js +131 -0
- package/lib/sdk-worker.js +677 -0
- package/lib/server-admin.js +712 -0
- package/lib/server-auth.js +737 -0
- package/lib/server-dm.js +170 -0
- package/lib/server-palette.js +104 -0
- package/lib/server-settings.js +553 -0
- package/lib/server-skills.js +280 -0
- package/lib/server.js +1390 -0
- package/lib/session-search.js +693 -0
- package/lib/sessions.js +946 -0
- package/lib/smtp.js +221 -0
- package/lib/terminal-manager.js +219 -0
- package/lib/terminal.js +39 -0
- package/lib/themes/ayu-light.json +9 -0
- package/lib/themes/catppuccin-latte.json +9 -0
- package/lib/themes/catppuccin-mocha.json +9 -0
- package/lib/themes/clagentic-dark.json +10 -0
- package/lib/themes/clagentic-light.json +10 -0
- package/lib/themes/dracula.json +9 -0
- package/lib/themes/everforest-light.json +9 -0
- package/lib/themes/everforest.json +9 -0
- package/lib/themes/github-light.json +9 -0
- package/lib/themes/gruvbox-dark.json +9 -0
- package/lib/themes/gruvbox-light.json +9 -0
- package/lib/themes/monokai.json +9 -0
- package/lib/themes/nord-light.json +9 -0
- package/lib/themes/nord.json +9 -0
- package/lib/themes/one-dark.json +9 -0
- package/lib/themes/one-light.json +9 -0
- package/lib/themes/rose-pine-dawn.json +9 -0
- package/lib/themes/rose-pine.json +9 -0
- package/lib/themes/solarized-dark.json +9 -0
- package/lib/themes/solarized-light.json +9 -0
- package/lib/themes/tokyo-night-light.json +9 -0
- package/lib/themes/tokyo-night.json +9 -0
- package/lib/updater.js +124 -0
- package/lib/user-presence.js +92 -0
- package/lib/users-auth.js +146 -0
- package/lib/users-permissions.js +118 -0
- package/lib/users-preferences.js +254 -0
- package/lib/users.js +465 -0
- package/lib/utils.js +64 -0
- package/lib/worktree.js +134 -0
- package/lib/ws-schema.js +464 -0
- package/lib/yoke/adapters/claude-worker.js +759 -0
- package/lib/yoke/adapters/claude.js +1599 -0
- package/lib/yoke/adapters/codex.js +1559 -0
- package/lib/yoke/codex-app-server.js +352 -0
- package/lib/yoke/index.js +319 -0
- package/lib/yoke/instructions.js +61 -0
- package/lib/yoke/interface.js +98 -0
- package/lib/yoke/mcp-bridge-server.js +302 -0
- package/lib/yoke/package.json +7 -0
- package/package.json +72 -0
|
@@ -0,0 +1,1304 @@
|
|
|
1
|
+
var fs = require("fs");
|
|
2
|
+
var path = require("path");
|
|
3
|
+
var crypto = require("crypto");
|
|
4
|
+
var { execFileSync } = require("child_process");
|
|
5
|
+
var { createLoopRegistry } = require("./scheduler");
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Attach loop engine to a project context.
|
|
9
|
+
*
|
|
10
|
+
* ctx fields:
|
|
11
|
+
* cwd, slug, sm, sdk, send, sendTo, sendToSession, pushModule,
|
|
12
|
+
* getHubSchedules, getLinuxUserForSession, onProcessingChanged,
|
|
13
|
+
* hydrateImageRefs
|
|
14
|
+
*/
|
|
15
|
+
function attachLoop(ctx) {
|
|
16
|
+
var cwd = ctx.cwd;
|
|
17
|
+
var slug = ctx.slug;
|
|
18
|
+
var sm = ctx.sm;
|
|
19
|
+
var sdk = ctx.sdk;
|
|
20
|
+
var send = ctx.send;
|
|
21
|
+
var sendTo = ctx.sendTo;
|
|
22
|
+
var sendToSession = ctx.sendToSession;
|
|
23
|
+
var pushModule = ctx.pushModule;
|
|
24
|
+
var notificationsModule = ctx.notificationsModule;
|
|
25
|
+
var getHubSchedules = ctx.getHubSchedules;
|
|
26
|
+
var getLinuxUserForSession = ctx.getLinuxUserForSession;
|
|
27
|
+
var onProcessingChanged = ctx.onProcessingChanged;
|
|
28
|
+
var hydrateImageRefs = ctx.hydrateImageRefs;
|
|
29
|
+
|
|
30
|
+
// --- Ralph Loop state ---
|
|
31
|
+
var loopState = {
|
|
32
|
+
active: false,
|
|
33
|
+
phase: "idle", // idle | crafting | approval | executing | done
|
|
34
|
+
promptText: "",
|
|
35
|
+
judgeText: "",
|
|
36
|
+
iteration: 0,
|
|
37
|
+
maxIterations: 20,
|
|
38
|
+
baseCommit: null,
|
|
39
|
+
currentSessionId: null,
|
|
40
|
+
judgeSessionId: null,
|
|
41
|
+
results: [],
|
|
42
|
+
stopping: false,
|
|
43
|
+
wizardData: null,
|
|
44
|
+
craftingSessionId: null,
|
|
45
|
+
startedAt: null,
|
|
46
|
+
loopId: null,
|
|
47
|
+
loopFilesId: null,
|
|
48
|
+
};
|
|
49
|
+
|
|
50
|
+
function loopDir() {
|
|
51
|
+
var id = loopState.loopFilesId || loopState.loopId;
|
|
52
|
+
if (!id) return null;
|
|
53
|
+
return path.join(cwd, ".claude", "loops", id);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function generateLoopId() {
|
|
57
|
+
return "loop_" + Date.now() + "_" + crypto.randomBytes(3).toString("hex");
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Loop state persistence
|
|
61
|
+
var _loopConfig = require("./config");
|
|
62
|
+
var _loopUtils = require("./utils");
|
|
63
|
+
var _loopDir = path.join(_loopConfig.CONFIG_DIR, "loops");
|
|
64
|
+
var _loopEncodedCwd = _loopUtils.resolveEncodedFile(_loopDir, cwd, ".json");
|
|
65
|
+
var _loopStatePath = path.join(_loopDir, _loopEncodedCwd + ".json");
|
|
66
|
+
|
|
67
|
+
function saveLoopState() {
|
|
68
|
+
try {
|
|
69
|
+
fs.mkdirSync(_loopDir, { recursive: true });
|
|
70
|
+
var data = {
|
|
71
|
+
phase: loopState.phase,
|
|
72
|
+
active: loopState.active,
|
|
73
|
+
iteration: loopState.iteration,
|
|
74
|
+
maxIterations: loopState.maxIterations,
|
|
75
|
+
baseCommit: loopState.baseCommit,
|
|
76
|
+
results: loopState.results,
|
|
77
|
+
wizardData: loopState.wizardData,
|
|
78
|
+
startedAt: loopState.startedAt,
|
|
79
|
+
loopId: loopState.loopId,
|
|
80
|
+
loopFilesId: loopState.loopFilesId || null,
|
|
81
|
+
};
|
|
82
|
+
var tmpPath = _loopStatePath + ".tmp";
|
|
83
|
+
fs.writeFileSync(tmpPath, JSON.stringify(data, null, 2));
|
|
84
|
+
fs.renameSync(tmpPath, _loopStatePath);
|
|
85
|
+
} catch (e) {
|
|
86
|
+
console.error("[ralph-loop] Failed to save state:", e.message);
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function loadLoopState() {
|
|
91
|
+
try {
|
|
92
|
+
var raw = fs.readFileSync(_loopStatePath, "utf8");
|
|
93
|
+
var data = JSON.parse(raw);
|
|
94
|
+
loopState.phase = data.phase || "idle";
|
|
95
|
+
loopState.active = data.active || false;
|
|
96
|
+
loopState.iteration = data.iteration || 0;
|
|
97
|
+
loopState.maxIterations = data.maxIterations || 20;
|
|
98
|
+
loopState.baseCommit = data.baseCommit || null;
|
|
99
|
+
loopState.results = data.results || [];
|
|
100
|
+
loopState.wizardData = data.wizardData || null;
|
|
101
|
+
loopState.startedAt = data.startedAt || null;
|
|
102
|
+
loopState.loopId = data.loopId || null;
|
|
103
|
+
loopState.loopFilesId = data.loopFilesId || null;
|
|
104
|
+
// SDK sessions cannot survive daemon restart
|
|
105
|
+
loopState.currentSessionId = null;
|
|
106
|
+
loopState.judgeSessionId = null;
|
|
107
|
+
loopState.craftingSessionId = null;
|
|
108
|
+
loopState.stopping = false;
|
|
109
|
+
// If was executing, schedule resume after SDK is ready
|
|
110
|
+
if (loopState.phase === "executing" && loopState.active) {
|
|
111
|
+
loopState._needsResume = true;
|
|
112
|
+
}
|
|
113
|
+
// If was crafting, check if files exist and move to approval
|
|
114
|
+
if (loopState.phase === "crafting") {
|
|
115
|
+
var hasFiles = checkLoopFilesExist();
|
|
116
|
+
if (hasFiles) {
|
|
117
|
+
loopState.phase = "approval";
|
|
118
|
+
saveLoopState();
|
|
119
|
+
} else {
|
|
120
|
+
loopState.phase = "idle";
|
|
121
|
+
saveLoopState();
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
} catch (e) {
|
|
125
|
+
// No saved state, use defaults
|
|
126
|
+
}
|
|
127
|
+
// Recover orphaned loops: if idle but completed loop files exist in .claude/loops/
|
|
128
|
+
if (loopState.phase === "idle") {
|
|
129
|
+
var _loopsBase = path.join(cwd, ".claude", "loops");
|
|
130
|
+
try {
|
|
131
|
+
var _loopDirs = fs.readdirSync(_loopsBase).filter(function (d) {
|
|
132
|
+
return d.indexOf("loop_") === 0;
|
|
133
|
+
});
|
|
134
|
+
for (var _li = 0; _li < _loopDirs.length; _li++) {
|
|
135
|
+
var _ld = path.join(_loopsBase, _loopDirs[_li]);
|
|
136
|
+
try {
|
|
137
|
+
fs.accessSync(path.join(_ld, "PROMPT.md"));
|
|
138
|
+
fs.accessSync(path.join(_ld, "LOOP.json"));
|
|
139
|
+
var _loopCfg = JSON.parse(fs.readFileSync(path.join(_ld, "LOOP.json"), "utf8"));
|
|
140
|
+
var _isSimple = _loopCfg.loopMode === "simple";
|
|
141
|
+
if (!_isSimple) fs.accessSync(path.join(_ld, "JUDGE.md"));
|
|
142
|
+
// Found a completed loop — recover to approval phase
|
|
143
|
+
loopState.loopId = _loopDirs[_li];
|
|
144
|
+
loopState.phase = "approval";
|
|
145
|
+
loopState.maxIterations = _loopCfg.maxIterations || 20;
|
|
146
|
+
if (!loopState.wizardData) loopState.wizardData = {};
|
|
147
|
+
loopState.wizardData.loopMode = _loopCfg.loopMode || "judge";
|
|
148
|
+
saveLoopState();
|
|
149
|
+
console.log("[ralph-loop] Recovered orphaned loop: " + _loopDirs[_li]);
|
|
150
|
+
break;
|
|
151
|
+
} catch (e) {}
|
|
152
|
+
}
|
|
153
|
+
} catch (e) {}
|
|
154
|
+
}
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function clearLoopState() {
|
|
158
|
+
loopState.active = false;
|
|
159
|
+
loopState.phase = "idle";
|
|
160
|
+
loopState.promptText = "";
|
|
161
|
+
loopState.judgeText = "";
|
|
162
|
+
loopState.iteration = 0;
|
|
163
|
+
loopState.maxIterations = 20;
|
|
164
|
+
loopState.baseCommit = null;
|
|
165
|
+
loopState.currentSessionId = null;
|
|
166
|
+
loopState.judgeSessionId = null;
|
|
167
|
+
loopState.results = [];
|
|
168
|
+
loopState.stopping = false;
|
|
169
|
+
loopState.wizardData = null;
|
|
170
|
+
loopState.craftingSessionId = null;
|
|
171
|
+
loopState.startedAt = null;
|
|
172
|
+
loopState.loopId = null;
|
|
173
|
+
loopState.loopFilesId = null;
|
|
174
|
+
saveLoopState();
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
function checkLoopFilesExist() {
|
|
178
|
+
var dir = loopDir();
|
|
179
|
+
if (!dir) return false;
|
|
180
|
+
var hasPrompt = false;
|
|
181
|
+
var hasJudge = false;
|
|
182
|
+
try { fs.accessSync(path.join(dir, "PROMPT.md")); hasPrompt = true; } catch (e) {}
|
|
183
|
+
try { fs.accessSync(path.join(dir, "JUDGE.md")); hasJudge = true; } catch (e) {}
|
|
184
|
+
var isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
185
|
+
return isSimple ? hasPrompt : (hasPrompt && hasJudge);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// .claude/ directory watcher for PROMPT.md / JUDGE.md
|
|
189
|
+
var claudeDirWatcher = null;
|
|
190
|
+
var claudeDirDebounce = null;
|
|
191
|
+
|
|
192
|
+
function startClaudeDirWatch() {
|
|
193
|
+
if (claudeDirWatcher) return;
|
|
194
|
+
var watchDir = loopDir();
|
|
195
|
+
if (!watchDir) return;
|
|
196
|
+
try { fs.mkdirSync(watchDir, { recursive: true }); } catch (e) {}
|
|
197
|
+
try {
|
|
198
|
+
claudeDirWatcher = fs.watch(watchDir, function () {
|
|
199
|
+
if (claudeDirDebounce) clearTimeout(claudeDirDebounce);
|
|
200
|
+
claudeDirDebounce = setTimeout(function () {
|
|
201
|
+
broadcastLoopFilesStatus();
|
|
202
|
+
}, 300);
|
|
203
|
+
});
|
|
204
|
+
claudeDirWatcher.on("error", function () {});
|
|
205
|
+
} catch (e) {
|
|
206
|
+
console.error("[ralph-loop] Failed to watch .claude/:", e.message);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
function stopClaudeDirWatch() {
|
|
211
|
+
if (claudeDirWatcher) {
|
|
212
|
+
claudeDirWatcher.close();
|
|
213
|
+
claudeDirWatcher = null;
|
|
214
|
+
}
|
|
215
|
+
if (claudeDirDebounce) {
|
|
216
|
+
clearTimeout(claudeDirDebounce);
|
|
217
|
+
claudeDirDebounce = null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function broadcastLoopFilesStatus() {
|
|
222
|
+
var dir = loopDir();
|
|
223
|
+
var hasPrompt = false;
|
|
224
|
+
var hasJudge = false;
|
|
225
|
+
var hasLoopJson = false;
|
|
226
|
+
if (dir) {
|
|
227
|
+
try { fs.accessSync(path.join(dir, "PROMPT.md")); hasPrompt = true; } catch (e) {}
|
|
228
|
+
try { fs.accessSync(path.join(dir, "JUDGE.md")); hasJudge = true; } catch (e) {}
|
|
229
|
+
try { fs.accessSync(path.join(dir, "LOOP.json")); hasLoopJson = true; } catch (e) {}
|
|
230
|
+
}
|
|
231
|
+
var isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
232
|
+
var bothReady = isSimple ? hasPrompt : (hasPrompt && hasJudge);
|
|
233
|
+
send({
|
|
234
|
+
type: "ralph_files_status",
|
|
235
|
+
promptReady: hasPrompt,
|
|
236
|
+
judgeReady: hasJudge,
|
|
237
|
+
loopJsonReady: hasLoopJson,
|
|
238
|
+
bothReady: bothReady,
|
|
239
|
+
taskId: loopState.loopId,
|
|
240
|
+
});
|
|
241
|
+
// Auto-transition to approval phase when files are ready
|
|
242
|
+
if (bothReady && loopState.phase === "crafting") {
|
|
243
|
+
loopState.phase = "approval";
|
|
244
|
+
saveLoopState();
|
|
245
|
+
|
|
246
|
+
// Parse recommended title from crafting session conversation
|
|
247
|
+
if (loopState.craftingSessionId && loopState.loopId) {
|
|
248
|
+
var craftSess = sm.sessions.get(loopState.craftingSessionId);
|
|
249
|
+
if (craftSess && craftSess.history) {
|
|
250
|
+
for (var hi = craftSess.history.length - 1; hi >= 0; hi--) {
|
|
251
|
+
var entry = craftSess.history[hi];
|
|
252
|
+
var entryText = entry.text || "";
|
|
253
|
+
var titleMatch = entryText.match(/\[\[LOOP_TITLE:\s*(.+?)\]\]/);
|
|
254
|
+
if (titleMatch) {
|
|
255
|
+
var suggestedTitle = titleMatch[1].trim();
|
|
256
|
+
if (suggestedTitle) {
|
|
257
|
+
loopRegistry.updateRecord(loopState.loopId, { name: suggestedTitle });
|
|
258
|
+
}
|
|
259
|
+
break;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Load persisted state on startup
|
|
268
|
+
loadLoopState();
|
|
269
|
+
|
|
270
|
+
// --- Loop Registry (unified one-off + scheduled) ---
|
|
271
|
+
var activeRegistryId = null; // track which registry record triggered current loop
|
|
272
|
+
var pendingTriggers = []; // queue for deferred triggers when skipIfRunning=false
|
|
273
|
+
|
|
274
|
+
function triggerFromQueue(record) {
|
|
275
|
+
// For schedule records, resolve the linked task to get loop files
|
|
276
|
+
var loopFilesId = record.id;
|
|
277
|
+
if (record.source === "schedule") {
|
|
278
|
+
if (!record.linkedTaskId) {
|
|
279
|
+
console.error("[loop-registry] Schedule has no linked task: " + record.name);
|
|
280
|
+
return;
|
|
281
|
+
}
|
|
282
|
+
loopFilesId = record.linkedTaskId;
|
|
283
|
+
console.log("[loop-registry] Schedule triggered: " + record.name + " -> linked task " + loopFilesId);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Verify the loop directory and PROMPT.md exist
|
|
287
|
+
var recDir = path.join(cwd, ".claude", "loops", loopFilesId);
|
|
288
|
+
try {
|
|
289
|
+
fs.accessSync(path.join(recDir, "PROMPT.md"));
|
|
290
|
+
} catch (e) {
|
|
291
|
+
console.error("[loop-registry] PROMPT.md missing for " + loopFilesId);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
// Set the loopId to the schedule's own id (not the linked task) so sidebar groups correctly
|
|
295
|
+
loopState.loopId = record.id;
|
|
296
|
+
loopState.loopFilesId = loopFilesId;
|
|
297
|
+
// Restore loopMode from LOOP.json so simple loops work correctly on trigger
|
|
298
|
+
var _triggerCfg = {};
|
|
299
|
+
try { _triggerCfg = JSON.parse(fs.readFileSync(path.join(recDir, "LOOP.json"), "utf8")); } catch (e) {}
|
|
300
|
+
loopState.wizardData = { loopMode: _triggerCfg.loopMode || "judge" };
|
|
301
|
+
activeRegistryId = record.id;
|
|
302
|
+
console.log("[loop-registry] Auto-starting loop: " + record.name + " (" + loopState.loopId + ")");
|
|
303
|
+
send({ type: "schedule_run_started", recordId: record.id });
|
|
304
|
+
startLoop({ maxIterations: record.maxIterations, name: record.name });
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
var loopRegistry = createLoopRegistry({
|
|
308
|
+
cwd: cwd,
|
|
309
|
+
onTrigger: function (record) {
|
|
310
|
+
// Skip or queue trigger if a loop is already active
|
|
311
|
+
if (loopState.active || loopState.phase === "executing") {
|
|
312
|
+
if (record.skipIfRunning !== false) {
|
|
313
|
+
console.log("[loop-registry] Skipping trigger for " + record.name + " — loop already active (skipIfRunning)");
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
console.log("[loop-registry] Loop active, queuing trigger for " + record.name);
|
|
317
|
+
pendingTriggers.push(record);
|
|
318
|
+
return;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
triggerFromQueue(record);
|
|
322
|
+
},
|
|
323
|
+
onChange: function () {
|
|
324
|
+
send({ type: "loop_registry_updated", records: getHubSchedules() });
|
|
325
|
+
},
|
|
326
|
+
});
|
|
327
|
+
loopRegistry.load();
|
|
328
|
+
loopRegistry.startTimer();
|
|
329
|
+
|
|
330
|
+
// Wire loop info resolution for session list broadcasts
|
|
331
|
+
sm.setResolveLoopInfo(function (loopId) {
|
|
332
|
+
var rec = loopRegistry.getById(loopId);
|
|
333
|
+
if (!rec) return null;
|
|
334
|
+
return { name: rec.name || null, source: rec.source || null };
|
|
335
|
+
});
|
|
336
|
+
|
|
337
|
+
function startLoop(opts) {
|
|
338
|
+
var loopOpts = opts || {};
|
|
339
|
+
var dir = loopDir();
|
|
340
|
+
if (!dir) {
|
|
341
|
+
send({ type: "loop_error", text: "No loop directory. Run the wizard first." });
|
|
342
|
+
return;
|
|
343
|
+
}
|
|
344
|
+
var promptPath = path.join(dir, "PROMPT.md");
|
|
345
|
+
var judgePath = path.join(dir, "JUDGE.md");
|
|
346
|
+
var promptText, judgeText;
|
|
347
|
+
try {
|
|
348
|
+
promptText = fs.readFileSync(promptPath, "utf8");
|
|
349
|
+
} catch (e) {
|
|
350
|
+
send({ type: "loop_error", text: "Missing PROMPT.md in " + dir });
|
|
351
|
+
return;
|
|
352
|
+
}
|
|
353
|
+
try {
|
|
354
|
+
judgeText = fs.readFileSync(judgePath, "utf8");
|
|
355
|
+
} catch (e) {
|
|
356
|
+
judgeText = null;
|
|
357
|
+
}
|
|
358
|
+
|
|
359
|
+
var baseCommit;
|
|
360
|
+
try {
|
|
361
|
+
baseCommit = execFileSync("git", ["rev-parse", "HEAD"], {
|
|
362
|
+
cwd: cwd, encoding: "utf8", timeout: 5000,
|
|
363
|
+
}).trim();
|
|
364
|
+
} catch (e) {
|
|
365
|
+
send({ type: "loop_error", text: "Failed to get git HEAD: " + e.message });
|
|
366
|
+
return;
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// Read loop config from LOOP.json in loop directory
|
|
370
|
+
var loopConfig = {};
|
|
371
|
+
try {
|
|
372
|
+
loopConfig = JSON.parse(fs.readFileSync(path.join(dir, "LOOP.json"), "utf8"));
|
|
373
|
+
} catch (e) {}
|
|
374
|
+
|
|
375
|
+
var isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
376
|
+
loopState.active = true;
|
|
377
|
+
loopState.phase = "executing";
|
|
378
|
+
loopState.promptText = promptText;
|
|
379
|
+
loopState.judgeText = isSimple ? null : judgeText;
|
|
380
|
+
loopState.iteration = 0;
|
|
381
|
+
if (isSimple) {
|
|
382
|
+
loopState.maxIterations = (loopOpts.maxIterations >= 1 ? loopOpts.maxIterations : null) || loopConfig.maxIterations || 5;
|
|
383
|
+
} else {
|
|
384
|
+
loopState.maxIterations = judgeText ? ((loopOpts.maxIterations >= 1 ? loopOpts.maxIterations : null) || loopConfig.maxIterations || 20) : 1;
|
|
385
|
+
}
|
|
386
|
+
loopState.baseCommit = baseCommit;
|
|
387
|
+
loopState.currentSessionId = null;
|
|
388
|
+
loopState.judgeSessionId = null;
|
|
389
|
+
loopState.results = [];
|
|
390
|
+
loopState.stopping = false;
|
|
391
|
+
loopState.name = loopOpts.name || null;
|
|
392
|
+
loopState.settings = loopConfig.settings || null;
|
|
393
|
+
loopState.startedAt = Date.now();
|
|
394
|
+
saveLoopState();
|
|
395
|
+
|
|
396
|
+
stopClaudeDirWatch();
|
|
397
|
+
|
|
398
|
+
send({ type: "loop_started", maxIterations: loopState.maxIterations, name: loopState.name });
|
|
399
|
+
runNextIteration();
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function runNextIteration() {
|
|
403
|
+
console.log("[ralph-loop] runNextIteration called, iteration: " + loopState.iteration + ", active: " + loopState.active + ", stopping: " + loopState.stopping);
|
|
404
|
+
if (!loopState.active || loopState.stopping) {
|
|
405
|
+
finishLoop("stopped");
|
|
406
|
+
return;
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
loopState.iteration++;
|
|
410
|
+
if (loopState.iteration > loopState.maxIterations) {
|
|
411
|
+
finishLoop("max_iterations");
|
|
412
|
+
return;
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
var session = sm.createSession();
|
|
416
|
+
var loopSource = loopRegistry.getById(loopState.loopId);
|
|
417
|
+
var loopName = (loopState.wizardData && loopState.wizardData.name) || (loopSource && loopSource.name) || "";
|
|
418
|
+
var loopSourceTag = (loopSource && loopSource.source) || null;
|
|
419
|
+
var isRalphLoop = loopSourceTag === "ralph";
|
|
420
|
+
session.loop = { active: true, iteration: loopState.iteration, role: "coder", loopId: loopState.loopId, name: loopName, source: loopSourceTag, startedAt: loopState.startedAt };
|
|
421
|
+
session.title = (isRalphLoop ? "Ralph" : "Task") + (loopName ? " " + loopName : "") + " #" + loopState.iteration;
|
|
422
|
+
sm.saveSessionFile(session);
|
|
423
|
+
sm.broadcastSessionList();
|
|
424
|
+
|
|
425
|
+
loopState.currentSessionId = session.localId;
|
|
426
|
+
|
|
427
|
+
send({
|
|
428
|
+
type: "loop_iteration",
|
|
429
|
+
iteration: loopState.iteration,
|
|
430
|
+
maxIterations: loopState.maxIterations,
|
|
431
|
+
sessionId: session.localId,
|
|
432
|
+
});
|
|
433
|
+
|
|
434
|
+
var coderCompleted = false;
|
|
435
|
+
session.onQueryComplete = function(completedSession) {
|
|
436
|
+
if (coderCompleted) return;
|
|
437
|
+
coderCompleted = true;
|
|
438
|
+
if (coderWatchdog) { clearTimeout(coderWatchdog); coderWatchdog = null; }
|
|
439
|
+
console.log("[ralph-loop] Coder #" + loopState.iteration + " onQueryComplete fired, history length: " + completedSession.history.length);
|
|
440
|
+
if (!loopState.active) { console.log("[ralph-loop] Coder: loopState.active is false, skipping"); return; }
|
|
441
|
+
// Check if session ended with error
|
|
442
|
+
var lastItems = completedSession.history.slice(-3);
|
|
443
|
+
var hadError = false;
|
|
444
|
+
for (var i = 0; i < lastItems.length; i++) {
|
|
445
|
+
if (lastItems[i].type === "error" || (lastItems[i].type === "done" && lastItems[i].code === 1)) {
|
|
446
|
+
hadError = true;
|
|
447
|
+
break;
|
|
448
|
+
}
|
|
449
|
+
}
|
|
450
|
+
if (hadError) {
|
|
451
|
+
loopState.results.push({
|
|
452
|
+
iteration: loopState.iteration,
|
|
453
|
+
verdict: "error",
|
|
454
|
+
summary: "Iteration ended with error",
|
|
455
|
+
});
|
|
456
|
+
send({
|
|
457
|
+
type: "loop_verdict",
|
|
458
|
+
iteration: loopState.iteration,
|
|
459
|
+
verdict: "error",
|
|
460
|
+
summary: "Iteration ended with error, retrying...",
|
|
461
|
+
});
|
|
462
|
+
setTimeout(function() { runNextIteration(); }, 2000);
|
|
463
|
+
return;
|
|
464
|
+
}
|
|
465
|
+
var _isSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
466
|
+
if (_isSimple) {
|
|
467
|
+
// Simple mode: no judge, proceed to next iteration or finish
|
|
468
|
+
if (loopState.iteration >= loopState.maxIterations) {
|
|
469
|
+
finishLoop("complete");
|
|
470
|
+
} else {
|
|
471
|
+
setTimeout(function() { runNextIteration(); }, 1000);
|
|
472
|
+
}
|
|
473
|
+
} else if (loopState.judgeText && loopState.maxIterations > 1) {
|
|
474
|
+
runJudge();
|
|
475
|
+
} else {
|
|
476
|
+
finishLoop("pass");
|
|
477
|
+
}
|
|
478
|
+
};
|
|
479
|
+
|
|
480
|
+
// Watchdog: if onQueryComplete hasn't fired after 10 minutes, force error and retry
|
|
481
|
+
var coderWatchdog = setTimeout(function() {
|
|
482
|
+
if (!coderCompleted && loopState.active && !loopState.stopping) {
|
|
483
|
+
console.error("[ralph-loop] Coder #" + loopState.iteration + " watchdog triggered — onQueryComplete never fired");
|
|
484
|
+
coderCompleted = true;
|
|
485
|
+
loopState.results.push({
|
|
486
|
+
iteration: loopState.iteration,
|
|
487
|
+
verdict: "error",
|
|
488
|
+
summary: "Coder session timed out (no completion signal)",
|
|
489
|
+
});
|
|
490
|
+
send({
|
|
491
|
+
type: "loop_verdict",
|
|
492
|
+
iteration: loopState.iteration,
|
|
493
|
+
verdict: "error",
|
|
494
|
+
summary: "Coder session timed out, retrying...",
|
|
495
|
+
});
|
|
496
|
+
setTimeout(function() { runNextIteration(); }, 2000);
|
|
497
|
+
}
|
|
498
|
+
}, 10 * 60 * 1000);
|
|
499
|
+
|
|
500
|
+
var userMsg = { type: "user_message", text: loopState.promptText };
|
|
501
|
+
session.history.push(userMsg);
|
|
502
|
+
sm.appendToSessionFile(session, userMsg);
|
|
503
|
+
|
|
504
|
+
session.isProcessing = true;
|
|
505
|
+
onProcessingChanged();
|
|
506
|
+
session.sentToolResults = {};
|
|
507
|
+
sendToSession(session.localId, { type: "status", status: "processing" });
|
|
508
|
+
session.acceptEditsAfterStart = true;
|
|
509
|
+
session.singleTurn = true;
|
|
510
|
+
if (loopState.settings) session.loopSettings = loopState.settings;
|
|
511
|
+
sdk.startQuery(session, loopState.promptText, undefined, getLinuxUserForSession(session));
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function runJudge() {
|
|
515
|
+
if (!loopState.active || loopState.stopping) {
|
|
516
|
+
finishLoop("stopped");
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
|
|
520
|
+
var diff;
|
|
521
|
+
try {
|
|
522
|
+
diff = execFileSync("git", ["diff", loopState.baseCommit], {
|
|
523
|
+
cwd: cwd, encoding: "utf8", timeout: 30000,
|
|
524
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
525
|
+
});
|
|
526
|
+
} catch (e) {
|
|
527
|
+
send({ type: "loop_error", text: "Failed to generate git diff: " + e.message });
|
|
528
|
+
finishLoop("error");
|
|
529
|
+
return;
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
var gitLog = "";
|
|
533
|
+
try {
|
|
534
|
+
gitLog = execFileSync("git", ["log", "--oneline", loopState.baseCommit + "..HEAD"], {
|
|
535
|
+
cwd: cwd, encoding: "utf8", timeout: 10000,
|
|
536
|
+
}).trim();
|
|
537
|
+
} catch (e) {}
|
|
538
|
+
|
|
539
|
+
var judgePrompt = "You are a judge evaluating whether a coding task has been completed.\n\n" +
|
|
540
|
+
"## Original Task (PROMPT.md)\n\n" + loopState.promptText + "\n\n" +
|
|
541
|
+
"## Evaluation Criteria (JUDGE.md)\n\n" + loopState.judgeText + "\n\n" +
|
|
542
|
+
"## Commit History\n\n```\n" + (gitLog || "(no commits yet)") + "\n```\n\n" +
|
|
543
|
+
"## Changes Made (git diff)\n\n```diff\n" + diff + "\n```\n\n" +
|
|
544
|
+
"Based on the evaluation criteria, has the task been completed successfully?\n\n" +
|
|
545
|
+
"IMPORTANT: The git diff above may not show everything. If criteria involve checking whether " +
|
|
546
|
+
"specific files, classes, or features exist, use tools (Read, Glob, Grep, Bash) to verify " +
|
|
547
|
+
"directly in the codebase. Do NOT assume something is missing just because it is not in the diff.\n\n" +
|
|
548
|
+
"After your evaluation, respond with exactly one of:\n" +
|
|
549
|
+
"- PASS: [brief explanation]\n" +
|
|
550
|
+
"- FAIL: [brief explanation of what is still missing]";
|
|
551
|
+
|
|
552
|
+
var judgeSession = sm.createSession();
|
|
553
|
+
var judgeSource = loopRegistry.getById(loopState.loopId);
|
|
554
|
+
var judgeName = (loopState.wizardData && loopState.wizardData.name) || (judgeSource && judgeSource.name) || "";
|
|
555
|
+
var judgeSourceTag = (judgeSource && judgeSource.source) || null;
|
|
556
|
+
var isRalphJudge = judgeSourceTag === "ralph";
|
|
557
|
+
judgeSession.loop = { active: true, iteration: loopState.iteration, role: "judge", loopId: loopState.loopId, name: judgeName, source: judgeSourceTag, startedAt: loopState.startedAt };
|
|
558
|
+
judgeSession.title = (isRalphJudge ? "Ralph" : "Task") + (judgeName ? " " + judgeName : "") + " Judge #" + loopState.iteration;
|
|
559
|
+
sm.saveSessionFile(judgeSession);
|
|
560
|
+
sm.broadcastSessionList();
|
|
561
|
+
loopState.judgeSessionId = judgeSession.localId;
|
|
562
|
+
|
|
563
|
+
send({
|
|
564
|
+
type: "loop_judging",
|
|
565
|
+
iteration: loopState.iteration,
|
|
566
|
+
sessionId: judgeSession.localId,
|
|
567
|
+
});
|
|
568
|
+
|
|
569
|
+
var judgeCompleted = false;
|
|
570
|
+
judgeSession.onQueryComplete = function(completedSession) {
|
|
571
|
+
if (judgeCompleted) return;
|
|
572
|
+
judgeCompleted = true;
|
|
573
|
+
if (judgeWatchdog) { clearTimeout(judgeWatchdog); judgeWatchdog = null; }
|
|
574
|
+
console.log("[ralph-loop] Judge #" + loopState.iteration + " onQueryComplete fired, history length: " + completedSession.history.length);
|
|
575
|
+
var verdict = parseJudgeVerdict(completedSession);
|
|
576
|
+
console.log("[ralph-loop] Judge verdict: " + (verdict.pass ? "PASS" : "FAIL") + " - " + verdict.explanation);
|
|
577
|
+
|
|
578
|
+
loopState.results.push({
|
|
579
|
+
iteration: loopState.iteration,
|
|
580
|
+
verdict: verdict.pass ? "pass" : "fail",
|
|
581
|
+
summary: verdict.explanation,
|
|
582
|
+
});
|
|
583
|
+
|
|
584
|
+
send({
|
|
585
|
+
type: "loop_verdict",
|
|
586
|
+
iteration: loopState.iteration,
|
|
587
|
+
verdict: verdict.pass ? "pass" : "fail",
|
|
588
|
+
summary: verdict.explanation,
|
|
589
|
+
});
|
|
590
|
+
|
|
591
|
+
if (verdict.pass) {
|
|
592
|
+
finishLoop("pass");
|
|
593
|
+
} else {
|
|
594
|
+
setTimeout(function() { runNextIteration(); }, 1000);
|
|
595
|
+
}
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
// Watchdog: judge may use tools to verify, so allow more time
|
|
599
|
+
var judgeWatchdog = setTimeout(function() {
|
|
600
|
+
if (!judgeCompleted && loopState.active && !loopState.stopping) {
|
|
601
|
+
console.error("[ralph-loop] Judge #" + loopState.iteration + " watchdog triggered — onQueryComplete never fired");
|
|
602
|
+
judgeCompleted = true;
|
|
603
|
+
loopState.results.push({
|
|
604
|
+
iteration: loopState.iteration,
|
|
605
|
+
verdict: "error",
|
|
606
|
+
summary: "Judge session timed out (no completion signal)",
|
|
607
|
+
});
|
|
608
|
+
send({
|
|
609
|
+
type: "loop_verdict",
|
|
610
|
+
iteration: loopState.iteration,
|
|
611
|
+
verdict: "error",
|
|
612
|
+
summary: "Judge session timed out, retrying...",
|
|
613
|
+
});
|
|
614
|
+
setTimeout(function() { runNextIteration(); }, 2000);
|
|
615
|
+
}
|
|
616
|
+
}, 10 * 60 * 1000);
|
|
617
|
+
|
|
618
|
+
var userMsg = { type: "user_message", text: judgePrompt };
|
|
619
|
+
judgeSession.history.push(userMsg);
|
|
620
|
+
sm.appendToSessionFile(judgeSession, userMsg);
|
|
621
|
+
|
|
622
|
+
judgeSession.isProcessing = true;
|
|
623
|
+
onProcessingChanged();
|
|
624
|
+
judgeSession.sentToolResults = {};
|
|
625
|
+
judgeSession.acceptEditsAfterStart = true;
|
|
626
|
+
judgeSession.singleTurn = true;
|
|
627
|
+
if (loopState.settings) judgeSession.loopSettings = loopState.settings;
|
|
628
|
+
sdk.startQuery(judgeSession, judgePrompt, undefined, getLinuxUserForSession(judgeSession));
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
function parseJudgeVerdict(session) {
|
|
632
|
+
var text = "";
|
|
633
|
+
for (var i = 0; i < session.history.length; i++) {
|
|
634
|
+
var h = session.history[i];
|
|
635
|
+
if (h.type === "delta" && h.text) text += h.text;
|
|
636
|
+
if (h.type === "text" && h.text) text += h.text;
|
|
637
|
+
}
|
|
638
|
+
console.log("[ralph-loop] Judge raw text (last 500 chars): " + text.slice(-500));
|
|
639
|
+
var upper = text.toUpperCase();
|
|
640
|
+
var passIdx = upper.indexOf("PASS");
|
|
641
|
+
var failIdx = upper.indexOf("FAIL");
|
|
642
|
+
if (passIdx !== -1 && (failIdx === -1 || passIdx < failIdx)) {
|
|
643
|
+
var explanation = text.substring(passIdx + 4).replace(/^[\s:]+/, "").split("\n")[0].trim();
|
|
644
|
+
return { pass: true, explanation: explanation || "Task completed" };
|
|
645
|
+
}
|
|
646
|
+
if (failIdx !== -1) {
|
|
647
|
+
var explanation = text.substring(failIdx + 4).replace(/^[\s:]+/, "").split("\n")[0].trim();
|
|
648
|
+
return { pass: false, explanation: explanation || "Task not yet complete" };
|
|
649
|
+
}
|
|
650
|
+
return { pass: false, explanation: "Could not parse judge verdict" };
|
|
651
|
+
}
|
|
652
|
+
|
|
653
|
+
function finishLoop(reason) {
|
|
654
|
+
console.log("[ralph-loop] finishLoop called, reason: " + reason + ", iteration: " + loopState.iteration);
|
|
655
|
+
|
|
656
|
+
// Unlock the last coder session so users can continue interacting with it
|
|
657
|
+
if (loopState.currentSessionId) {
|
|
658
|
+
var lastCoderSession = sm.sessions.get(loopState.currentSessionId);
|
|
659
|
+
if (lastCoderSession) {
|
|
660
|
+
lastCoderSession.singleTurn = false;
|
|
661
|
+
lastCoderSession.loop.active = false;
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
loopState.active = false;
|
|
666
|
+
loopState.phase = "done";
|
|
667
|
+
loopState.stopping = false;
|
|
668
|
+
loopState.currentSessionId = null;
|
|
669
|
+
loopState.judgeSessionId = null;
|
|
670
|
+
saveLoopState();
|
|
671
|
+
|
|
672
|
+
send({
|
|
673
|
+
type: "loop_finished",
|
|
674
|
+
reason: reason,
|
|
675
|
+
iterations: loopState.iteration,
|
|
676
|
+
results: loopState.results,
|
|
677
|
+
});
|
|
678
|
+
|
|
679
|
+
// Record result in loop registry
|
|
680
|
+
if (loopState.loopId) {
|
|
681
|
+
loopRegistry.recordRun(loopState.loopId, {
|
|
682
|
+
reason: reason,
|
|
683
|
+
startedAt: loopState.startedAt,
|
|
684
|
+
iterations: loopState.iteration,
|
|
685
|
+
});
|
|
686
|
+
}
|
|
687
|
+
if (activeRegistryId) {
|
|
688
|
+
send({ type: "schedule_run_finished", recordId: activeRegistryId, reason: reason, iterations: loopState.iteration });
|
|
689
|
+
activeRegistryId = null;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
if (pushModule) {
|
|
693
|
+
var _finishBody = reason === "pass" || reason === "complete"
|
|
694
|
+
? "Completed after " + loopState.iteration + " iteration(s)"
|
|
695
|
+
: reason === "max_iterations"
|
|
696
|
+
? "Reached max iterations (" + loopState.maxIterations + ")"
|
|
697
|
+
: reason === "stopped" ? "Stopped by user" : "Ended due to error";
|
|
698
|
+
pushModule.sendPush({
|
|
699
|
+
type: "done", slug: slug, title: "Loop Complete", body: _finishBody, tag: "ralph-loop-done",
|
|
700
|
+
});
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
if (notificationsModule) {
|
|
704
|
+
notificationsModule.notify("loop_complete", {
|
|
705
|
+
reason: reason,
|
|
706
|
+
name: loopState.name,
|
|
707
|
+
iterations: loopState.iteration,
|
|
708
|
+
maxIterations: loopState.maxIterations,
|
|
709
|
+
sessionId: loopState.currentSessionId,
|
|
710
|
+
});
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// Process next queued trigger if any
|
|
714
|
+
if (pendingTriggers.length > 0) {
|
|
715
|
+
var next = pendingTriggers.shift();
|
|
716
|
+
console.log("[loop-registry] Processing queued trigger: " + next.name);
|
|
717
|
+
setTimeout(function () {
|
|
718
|
+
triggerFromQueue(next);
|
|
719
|
+
}, 1000);
|
|
720
|
+
}
|
|
721
|
+
}
|
|
722
|
+
|
|
723
|
+
function resumeLoop() {
|
|
724
|
+
var dir = loopDir();
|
|
725
|
+
if (!dir) {
|
|
726
|
+
console.error("[ralph-loop] Cannot resume: no loop directory");
|
|
727
|
+
loopState.active = false;
|
|
728
|
+
loopState.phase = "idle";
|
|
729
|
+
saveLoopState();
|
|
730
|
+
return;
|
|
731
|
+
}
|
|
732
|
+
try {
|
|
733
|
+
loopState.promptText = fs.readFileSync(path.join(dir, "PROMPT.md"), "utf8");
|
|
734
|
+
} catch (e) {
|
|
735
|
+
console.error("[ralph-loop] Cannot resume: missing PROMPT.md");
|
|
736
|
+
loopState.active = false;
|
|
737
|
+
loopState.phase = "idle";
|
|
738
|
+
saveLoopState();
|
|
739
|
+
return;
|
|
740
|
+
}
|
|
741
|
+
var _isSimpleResume = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
742
|
+
if (!_isSimpleResume) {
|
|
743
|
+
try {
|
|
744
|
+
loopState.judgeText = fs.readFileSync(path.join(dir, "JUDGE.md"), "utf8");
|
|
745
|
+
} catch (e) {
|
|
746
|
+
console.error("[ralph-loop] Cannot resume: missing JUDGE.md");
|
|
747
|
+
loopState.active = false;
|
|
748
|
+
loopState.phase = "idle";
|
|
749
|
+
saveLoopState();
|
|
750
|
+
return;
|
|
751
|
+
}
|
|
752
|
+
} else {
|
|
753
|
+
loopState.judgeText = null;
|
|
754
|
+
}
|
|
755
|
+
// Retry the interrupted iteration (runNextIteration will increment)
|
|
756
|
+
if (loopState.iteration > 0) {
|
|
757
|
+
loopState.iteration--;
|
|
758
|
+
}
|
|
759
|
+
console.log("[ralph-loop] Resuming loop, next iteration will be " + (loopState.iteration + 1) + "/" + loopState.maxIterations);
|
|
760
|
+
send({ type: "loop_started", maxIterations: loopState.maxIterations });
|
|
761
|
+
runNextIteration();
|
|
762
|
+
}
|
|
763
|
+
|
|
764
|
+
function stopLoop() {
|
|
765
|
+
if (!loopState.active) return;
|
|
766
|
+
console.log("[ralph-loop] stopLoop called");
|
|
767
|
+
loopState.stopping = true;
|
|
768
|
+
|
|
769
|
+
// Abort all loop-related sessions (coder + judge)
|
|
770
|
+
var sessionIds = [loopState.currentSessionId, loopState.judgeSessionId];
|
|
771
|
+
for (var i = 0; i < sessionIds.length; i++) {
|
|
772
|
+
if (sessionIds[i] == null) continue;
|
|
773
|
+
var s = sm.sessions.get(sessionIds[i]);
|
|
774
|
+
if (!s) continue;
|
|
775
|
+
// End message queue so SDK exits prompt wait
|
|
776
|
+
if (s.messageQueue) { try { s.messageQueue.end(); } catch (e) {} }
|
|
777
|
+
// Abort active API call
|
|
778
|
+
if (s.abortController) { try { s.abortController.abort(); } catch (e) {} }
|
|
779
|
+
}
|
|
780
|
+
|
|
781
|
+
send({ type: "loop_stopping" });
|
|
782
|
+
|
|
783
|
+
// Fallback: force finish if onQueryComplete hasn't fired after 5s
|
|
784
|
+
setTimeout(function() {
|
|
785
|
+
if (loopState.active && loopState.stopping) {
|
|
786
|
+
console.log("[ralph-loop] Stop fallback triggered — forcing finishLoop");
|
|
787
|
+
finishLoop("stopped");
|
|
788
|
+
}
|
|
789
|
+
}, 5000);
|
|
790
|
+
}
|
|
791
|
+
|
|
792
|
+
// --- Message handler for loop-related messages ---
|
|
793
|
+
function handleLoopMessage(ws, msg) {
|
|
794
|
+
if (msg.type === "loop_start") {
|
|
795
|
+
// If this loop has a cron schedule, don't run immediately
|
|
796
|
+
if (loopState.wizardData && loopState.wizardData.cron) {
|
|
797
|
+
loopState.active = false;
|
|
798
|
+
loopState.phase = "done";
|
|
799
|
+
saveLoopState();
|
|
800
|
+
send({ type: "loop_finished", reason: "scheduled", iterations: 0, results: [] });
|
|
801
|
+
send({ type: "ralph_phase", phase: "idle", wizardData: null });
|
|
802
|
+
send({ type: "loop_scheduled", recordId: loopState.loopId, cron: loopState.wizardData.cron });
|
|
803
|
+
return true;
|
|
804
|
+
}
|
|
805
|
+
// Save per-loop settings to LOOP.json if provided
|
|
806
|
+
if (msg.settings && Object.keys(msg.settings).length > 0) {
|
|
807
|
+
var lDir3 = loopDir();
|
|
808
|
+
if (lDir3) {
|
|
809
|
+
var ljPath = path.join(lDir3, "LOOP.json");
|
|
810
|
+
var lj = {};
|
|
811
|
+
try { lj = JSON.parse(fs.readFileSync(ljPath, "utf8")); } catch (e) {}
|
|
812
|
+
lj.settings = msg.settings;
|
|
813
|
+
fs.writeFileSync(ljPath, JSON.stringify(lj, null, 2), "utf8");
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
startLoop({ maxIterations: msg.maxIterations });
|
|
817
|
+
return true;
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
if (msg.type === "loop_stop") {
|
|
821
|
+
stopLoop();
|
|
822
|
+
return true;
|
|
823
|
+
}
|
|
824
|
+
|
|
825
|
+
if (msg.type === "ralph_wizard_complete") {
|
|
826
|
+
var wData = msg.data || {};
|
|
827
|
+
var maxIter = wData.maxIterations || null;
|
|
828
|
+
var wizardCron = wData.cron || null;
|
|
829
|
+
var newLoopId = generateLoopId();
|
|
830
|
+
loopState.loopId = newLoopId;
|
|
831
|
+
var recordSource = wData.source === "task" ? null : "ralph";
|
|
832
|
+
loopState.wizardData = {
|
|
833
|
+
name: wData.name || wData.task || "Untitled",
|
|
834
|
+
task: wData.task || "",
|
|
835
|
+
maxIterations: maxIter,
|
|
836
|
+
cron: wizardCron,
|
|
837
|
+
loopMode: wData.loopMode || "judge",
|
|
838
|
+
promptAuthor: wData.promptAuthor || "clay",
|
|
839
|
+
judgeAuthor: wData.judgeAuthor || null,
|
|
840
|
+
source: recordSource,
|
|
841
|
+
};
|
|
842
|
+
loopState.phase = "crafting";
|
|
843
|
+
loopState.startedAt = Date.now();
|
|
844
|
+
saveLoopState();
|
|
845
|
+
|
|
846
|
+
// Register in loop registry
|
|
847
|
+
loopRegistry.register({
|
|
848
|
+
id: newLoopId,
|
|
849
|
+
name: loopState.wizardData.name,
|
|
850
|
+
task: wData.task || "",
|
|
851
|
+
cron: wizardCron,
|
|
852
|
+
enabled: wizardCron ? true : false,
|
|
853
|
+
maxIterations: maxIter,
|
|
854
|
+
source: recordSource,
|
|
855
|
+
});
|
|
856
|
+
|
|
857
|
+
// Create loop directory and write LOOP.json
|
|
858
|
+
var lDir = loopDir();
|
|
859
|
+
try { fs.mkdirSync(lDir, { recursive: true }); } catch (e) {}
|
|
860
|
+
var loopJsonPath = path.join(lDir, "LOOP.json");
|
|
861
|
+
var tmpLoopJson = loopJsonPath + ".tmp";
|
|
862
|
+
fs.writeFileSync(tmpLoopJson, JSON.stringify({ maxIterations: maxIter, loopMode: wData.loopMode || "judge" }, null, 2));
|
|
863
|
+
fs.renameSync(tmpLoopJson, loopJsonPath);
|
|
864
|
+
|
|
865
|
+
var craftName = (loopState.wizardData && loopState.wizardData.name) || "";
|
|
866
|
+
var isRalphCraft = recordSource === "ralph";
|
|
867
|
+
|
|
868
|
+
// User provided their own PROMPT.md (and optionally JUDGE.md)
|
|
869
|
+
if (wData.mode === "own" && wData.promptText) {
|
|
870
|
+
// Write PROMPT.md
|
|
871
|
+
var promptPath = path.join(lDir, "PROMPT.md");
|
|
872
|
+
var tmpPrompt = promptPath + ".tmp";
|
|
873
|
+
fs.writeFileSync(tmpPrompt, wData.promptText);
|
|
874
|
+
fs.renameSync(tmpPrompt, promptPath);
|
|
875
|
+
|
|
876
|
+
if (wData.judgeText) {
|
|
877
|
+
// Both provided: write JUDGE.md too
|
|
878
|
+
var judgePath = path.join(lDir, "JUDGE.md");
|
|
879
|
+
var tmpJudge = judgePath + ".tmp";
|
|
880
|
+
fs.writeFileSync(tmpJudge, wData.judgeText);
|
|
881
|
+
fs.renameSync(tmpJudge, judgePath);
|
|
882
|
+
} else if (wData.loopMode === "simple" || !recordSource) {
|
|
883
|
+
// Simple loop or scheduled task with no judge: go straight to approval
|
|
884
|
+
loopState.phase = "approval";
|
|
885
|
+
saveLoopState();
|
|
886
|
+
send({ type: "ralph_phase", phase: "approval", source: recordSource, wizardData: loopState.wizardData });
|
|
887
|
+
send({ type: "ralph_files_status", promptReady: true, judgeReady: false, bothReady: true });
|
|
888
|
+
return true;
|
|
889
|
+
} else {
|
|
890
|
+
// Ralph with judge mode but no judge provided: start a crafting session to create JUDGE.md
|
|
891
|
+
loopState.phase = "crafting";
|
|
892
|
+
saveLoopState();
|
|
893
|
+
|
|
894
|
+
var judgeCraftPrompt = "Use the /clay-ralph skill to design ONLY a JUDGE.md for an existing Ralph Loop. " +
|
|
895
|
+
"The user has already provided PROMPT.md, so do NOT create or modify PROMPT.md. " +
|
|
896
|
+
"You MUST invoke the clay-ralph skill — do NOT execute the task yourself. " +
|
|
897
|
+
"Your job is to read the existing PROMPT.md and create a JUDGE.md " +
|
|
898
|
+
"that will evaluate whether the coder session completed the task successfully.\n\n" +
|
|
899
|
+
"## Task\n" + (wData.task || "") +
|
|
900
|
+
"\n\n## Loop Directory\n" + lDir;
|
|
901
|
+
|
|
902
|
+
var judgeCraftSession = sm.createSession();
|
|
903
|
+
judgeCraftSession.title = (isRalphCraft ? "Ralph" : "Task") + (craftName ? " " + craftName : "") + " Crafting";
|
|
904
|
+
judgeCraftSession.ralphCraftingMode = true;
|
|
905
|
+
judgeCraftSession.loop = { active: true, iteration: 0, role: "crafting", loopId: newLoopId, name: craftName, source: recordSource, startedAt: loopState.startedAt };
|
|
906
|
+
sm.saveSessionFile(judgeCraftSession);
|
|
907
|
+
sm.switchSession(judgeCraftSession.localId, null, hydrateImageRefs);
|
|
908
|
+
loopState.craftingSessionId = judgeCraftSession.localId;
|
|
909
|
+
|
|
910
|
+
loopRegistry.updateRecord(newLoopId, { craftingSessionId: judgeCraftSession.localId });
|
|
911
|
+
|
|
912
|
+
startClaudeDirWatch();
|
|
913
|
+
|
|
914
|
+
judgeCraftSession.history.push({ type: "user_message", text: judgeCraftPrompt });
|
|
915
|
+
sm.appendToSessionFile(judgeCraftSession, { type: "user_message", text: judgeCraftPrompt });
|
|
916
|
+
sendToSession(judgeCraftSession.localId, { type: "user_message", text: judgeCraftPrompt });
|
|
917
|
+
judgeCraftSession.isProcessing = true;
|
|
918
|
+
onProcessingChanged();
|
|
919
|
+
judgeCraftSession.sentToolResults = {};
|
|
920
|
+
sendToSession(judgeCraftSession.localId, { type: "status", status: "processing" });
|
|
921
|
+
sdk.startQuery(judgeCraftSession, judgeCraftPrompt, undefined, getLinuxUserForSession(judgeCraftSession));
|
|
922
|
+
|
|
923
|
+
send({ type: "ralph_crafting_started", sessionId: judgeCraftSession.localId, taskId: newLoopId, source: recordSource });
|
|
924
|
+
send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: judgeCraftSession.localId });
|
|
925
|
+
send({ type: "ralph_files_status", promptReady: true, judgeReady: false, bothReady: false });
|
|
926
|
+
return true;
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
// Both prompt and judge provided: go straight to approval
|
|
930
|
+
loopState.phase = "approval";
|
|
931
|
+
saveLoopState();
|
|
932
|
+
send({ type: "ralph_phase", phase: "approval", source: recordSource, wizardData: loopState.wizardData });
|
|
933
|
+
send({ type: "ralph_files_status", promptReady: true, judgeReady: true, bothReady: true });
|
|
934
|
+
return true;
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
// Default: "draft" mode — Clay crafts files via the clay-ralph skill
|
|
938
|
+
var _draftIsSimple = wData.loopMode === "simple";
|
|
939
|
+
var craftingPrompt;
|
|
940
|
+
if (_draftIsSimple) {
|
|
941
|
+
craftingPrompt = "Use the /clay-ralph skill to design a Ralph Loop for the following task. " +
|
|
942
|
+
"You MUST invoke the clay-ralph skill — do NOT execute the task yourself. " +
|
|
943
|
+
"This is a Simple Loop (no judge). Your job is to create ONLY a PROMPT.md file " +
|
|
944
|
+
"that a future autonomous session will execute. Do NOT create a JUDGE.md file.\n\n" +
|
|
945
|
+
"## Task\n" + (wData.task || "") +
|
|
946
|
+
"\n\n## Loop Directory\n" + lDir;
|
|
947
|
+
} else if (wData.judgeAuthor === "me") {
|
|
948
|
+
craftingPrompt = "Use the /clay-ralph skill to design a Ralph Loop for the following task. " +
|
|
949
|
+
"You MUST invoke the clay-ralph skill — do NOT execute the task yourself. " +
|
|
950
|
+
"The user will provide their own JUDGE.md, so create ONLY a PROMPT.md file " +
|
|
951
|
+
"that a future autonomous session will execute. Do NOT create a JUDGE.md file.\n\n" +
|
|
952
|
+
"## Task\n" + (wData.task || "") +
|
|
953
|
+
"\n\n## Loop Directory\n" + lDir;
|
|
954
|
+
} else {
|
|
955
|
+
craftingPrompt = "Use the /clay-ralph skill to design a Ralph Loop for the following task. " +
|
|
956
|
+
"You MUST invoke the clay-ralph skill — do NOT execute the task yourself. " +
|
|
957
|
+
"Your job is to interview me, then create PROMPT.md and JUDGE.md files " +
|
|
958
|
+
"that a future autonomous session will execute.\n\n" +
|
|
959
|
+
"## Task\n" + (wData.task || "") +
|
|
960
|
+
"\n\n## Loop Directory\n" + lDir;
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
// Pre-write user-provided files before crafting starts
|
|
964
|
+
if (wData.judgeText && wData.judgeAuthor === "me") {
|
|
965
|
+
var _judgePathDraft = path.join(lDir, "JUDGE.md");
|
|
966
|
+
var _tmpJudgeDraft = _judgePathDraft + ".tmp";
|
|
967
|
+
fs.writeFileSync(_tmpJudgeDraft, wData.judgeText);
|
|
968
|
+
fs.renameSync(_tmpJudgeDraft, _judgePathDraft);
|
|
969
|
+
}
|
|
970
|
+
|
|
971
|
+
// Create a new session for crafting
|
|
972
|
+
var craftingSession = sm.createSession();
|
|
973
|
+
craftingSession.title = (isRalphCraft ? "Ralph" : "Task") + (craftName ? " " + craftName : "") + " Crafting";
|
|
974
|
+
craftingSession.ralphCraftingMode = true;
|
|
975
|
+
craftingSession.loop = { active: true, iteration: 0, role: "crafting", loopId: newLoopId, name: craftName, source: recordSource, startedAt: loopState.startedAt };
|
|
976
|
+
sm.saveSessionFile(craftingSession);
|
|
977
|
+
sm.switchSession(craftingSession.localId, null, hydrateImageRefs);
|
|
978
|
+
loopState.craftingSessionId = craftingSession.localId;
|
|
979
|
+
|
|
980
|
+
// Store crafting session ID in the registry record
|
|
981
|
+
loopRegistry.updateRecord(newLoopId, { craftingSessionId: craftingSession.localId });
|
|
982
|
+
|
|
983
|
+
// Start .claude/ directory watcher
|
|
984
|
+
startClaudeDirWatch();
|
|
985
|
+
|
|
986
|
+
// Send crafting prompt and start the conversation with Claude.
|
|
987
|
+
craftingSession.history.push({ type: "user_message", text: craftingPrompt });
|
|
988
|
+
sm.appendToSessionFile(craftingSession, { type: "user_message", text: craftingPrompt });
|
|
989
|
+
sendToSession(craftingSession.localId, { type: "user_message", text: craftingPrompt });
|
|
990
|
+
craftingSession.isProcessing = true;
|
|
991
|
+
onProcessingChanged();
|
|
992
|
+
craftingSession.sentToolResults = {};
|
|
993
|
+
sendToSession(craftingSession.localId, { type: "status", status: "processing" });
|
|
994
|
+
sdk.startQuery(craftingSession, craftingPrompt, undefined, getLinuxUserForSession(craftingSession));
|
|
995
|
+
|
|
996
|
+
send({ type: "ralph_crafting_started", sessionId: craftingSession.localId, taskId: newLoopId, source: recordSource });
|
|
997
|
+
send({ type: "ralph_phase", phase: "crafting", wizardData: loopState.wizardData, craftingSessionId: craftingSession.localId });
|
|
998
|
+
return true;
|
|
999
|
+
}
|
|
1000
|
+
|
|
1001
|
+
if (msg.type === "loop_registry_files") {
|
|
1002
|
+
var recId = msg.id;
|
|
1003
|
+
var lDir = path.join(cwd, ".claude", "loops", recId);
|
|
1004
|
+
var promptContent = "";
|
|
1005
|
+
var judgeContent = "";
|
|
1006
|
+
var loopSettings = null;
|
|
1007
|
+
try { promptContent = fs.readFileSync(path.join(lDir, "PROMPT.md"), "utf8"); } catch (e) {}
|
|
1008
|
+
try { judgeContent = fs.readFileSync(path.join(lDir, "JUDGE.md"), "utf8"); } catch (e) {}
|
|
1009
|
+
try {
|
|
1010
|
+
var loopJson = JSON.parse(fs.readFileSync(path.join(lDir, "LOOP.json"), "utf8"));
|
|
1011
|
+
loopSettings = loopJson.settings || null;
|
|
1012
|
+
} catch (e) {}
|
|
1013
|
+
send({
|
|
1014
|
+
type: "loop_registry_files_content",
|
|
1015
|
+
id: recId,
|
|
1016
|
+
prompt: promptContent,
|
|
1017
|
+
judge: judgeContent,
|
|
1018
|
+
settings: loopSettings,
|
|
1019
|
+
});
|
|
1020
|
+
return true;
|
|
1021
|
+
}
|
|
1022
|
+
|
|
1023
|
+
if (msg.type === "loop_registry_save_files") {
|
|
1024
|
+
var recId2 = msg.id;
|
|
1025
|
+
var lDir2 = path.join(cwd, ".claude", "loops", recId2);
|
|
1026
|
+
try {
|
|
1027
|
+
fs.mkdirSync(lDir2, { recursive: true });
|
|
1028
|
+
if (msg.prompt !== undefined) {
|
|
1029
|
+
fs.writeFileSync(path.join(lDir2, "PROMPT.md"), msg.prompt, "utf8");
|
|
1030
|
+
}
|
|
1031
|
+
if (msg.judge !== undefined) {
|
|
1032
|
+
fs.writeFileSync(path.join(lDir2, "JUDGE.md"), msg.judge, "utf8");
|
|
1033
|
+
}
|
|
1034
|
+
if (msg.settings !== undefined) {
|
|
1035
|
+
var loopJsonPath2 = path.join(lDir2, "LOOP.json");
|
|
1036
|
+
var loopJson2 = {};
|
|
1037
|
+
try { loopJson2 = JSON.parse(fs.readFileSync(loopJsonPath2, "utf8")); } catch (e) {}
|
|
1038
|
+
loopJson2.settings = msg.settings;
|
|
1039
|
+
fs.writeFileSync(loopJsonPath2, JSON.stringify(loopJson2, null, 2), "utf8");
|
|
1040
|
+
}
|
|
1041
|
+
send({ type: "loop_registry_save_files_result", id: recId2, ok: true });
|
|
1042
|
+
// Re-send updated content so the UI refreshes
|
|
1043
|
+
var updatedPrompt = "";
|
|
1044
|
+
var updatedJudge = "";
|
|
1045
|
+
var updatedSettings = null;
|
|
1046
|
+
try { updatedPrompt = fs.readFileSync(path.join(lDir2, "PROMPT.md"), "utf8"); } catch (e) {}
|
|
1047
|
+
try { updatedJudge = fs.readFileSync(path.join(lDir2, "JUDGE.md"), "utf8"); } catch (e) {}
|
|
1048
|
+
try {
|
|
1049
|
+
var uj = JSON.parse(fs.readFileSync(path.join(lDir2, "LOOP.json"), "utf8"));
|
|
1050
|
+
updatedSettings = uj.settings || null;
|
|
1051
|
+
} catch (e) {}
|
|
1052
|
+
send({ type: "loop_registry_files_content", id: recId2, prompt: updatedPrompt, judge: updatedJudge, settings: updatedSettings });
|
|
1053
|
+
} catch (e) {
|
|
1054
|
+
send({ type: "loop_registry_save_files_result", id: recId2, ok: false, error: e.message });
|
|
1055
|
+
}
|
|
1056
|
+
return true;
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
if (msg.type === "ralph_preview_files") {
|
|
1060
|
+
var promptContent = "";
|
|
1061
|
+
var judgeContent = "";
|
|
1062
|
+
var previewDir = loopDir();
|
|
1063
|
+
if (previewDir) {
|
|
1064
|
+
try { promptContent = fs.readFileSync(path.join(previewDir, "PROMPT.md"), "utf8"); } catch (e) {}
|
|
1065
|
+
try { judgeContent = fs.readFileSync(path.join(previewDir, "JUDGE.md"), "utf8"); } catch (e) {}
|
|
1066
|
+
}
|
|
1067
|
+
sendTo(ws, {
|
|
1068
|
+
type: "ralph_files_content",
|
|
1069
|
+
prompt: promptContent,
|
|
1070
|
+
judge: judgeContent,
|
|
1071
|
+
});
|
|
1072
|
+
return true;
|
|
1073
|
+
}
|
|
1074
|
+
|
|
1075
|
+
if (msg.type === "ralph_wizard_cancel") {
|
|
1076
|
+
stopClaudeDirWatch();
|
|
1077
|
+
// Clean up loop directory
|
|
1078
|
+
var cancelDir = loopDir();
|
|
1079
|
+
if (cancelDir) {
|
|
1080
|
+
try { fs.rmSync(cancelDir, { recursive: true, force: true }); } catch (e) {}
|
|
1081
|
+
}
|
|
1082
|
+
clearLoopState();
|
|
1083
|
+
send({ type: "ralph_phase", phase: "idle", wizardData: null });
|
|
1084
|
+
return true;
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
if (msg.type === "ralph_cancel_crafting") {
|
|
1088
|
+
// Abort the crafting session if running
|
|
1089
|
+
if (loopState.craftingSessionId != null) {
|
|
1090
|
+
var craftSession = sm.sessions.get(loopState.craftingSessionId) || null;
|
|
1091
|
+
if (craftSession && craftSession.abortController) {
|
|
1092
|
+
craftSession.abortController.abort();
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
stopClaudeDirWatch();
|
|
1096
|
+
// Clean up loop directory
|
|
1097
|
+
var craftCancelDir = loopDir();
|
|
1098
|
+
if (craftCancelDir) {
|
|
1099
|
+
try { fs.rmSync(craftCancelDir, { recursive: true, force: true }); } catch (e) {}
|
|
1100
|
+
}
|
|
1101
|
+
clearLoopState();
|
|
1102
|
+
send({ type: "ralph_phase", phase: "idle", wizardData: null });
|
|
1103
|
+
return true;
|
|
1104
|
+
}
|
|
1105
|
+
|
|
1106
|
+
// --- Schedule create (from calendar click) ---
|
|
1107
|
+
if (msg.type === "schedule_create") {
|
|
1108
|
+
var sData = msg.data || {};
|
|
1109
|
+
loopRegistry.register({
|
|
1110
|
+
name: sData.name || "Untitled",
|
|
1111
|
+
task: sData.name || "",
|
|
1112
|
+
description: sData.description || "",
|
|
1113
|
+
date: sData.date || null,
|
|
1114
|
+
time: sData.time || null,
|
|
1115
|
+
allDay: sData.allDay !== undefined ? sData.allDay : true,
|
|
1116
|
+
linkedTaskId: sData.taskId || null,
|
|
1117
|
+
cron: sData.cron || null,
|
|
1118
|
+
enabled: sData.cron ? (sData.enabled !== false) : false,
|
|
1119
|
+
maxIterations: sData.maxIterations || 3,
|
|
1120
|
+
source: "schedule",
|
|
1121
|
+
color: sData.color || null,
|
|
1122
|
+
recurrenceEnd: sData.recurrenceEnd || null,
|
|
1123
|
+
skipIfRunning: sData.skipIfRunning !== undefined ? sData.skipIfRunning : true,
|
|
1124
|
+
intervalEnd: sData.intervalEnd || null,
|
|
1125
|
+
});
|
|
1126
|
+
return true;
|
|
1127
|
+
}
|
|
1128
|
+
|
|
1129
|
+
// --- Hub: cross-project schedule aggregation ---
|
|
1130
|
+
if (msg.type === "hub_schedules_list") {
|
|
1131
|
+
sendTo(ws, { type: "hub_schedules", schedules: getHubSchedules() });
|
|
1132
|
+
return true;
|
|
1133
|
+
}
|
|
1134
|
+
|
|
1135
|
+
// --- Loop Registry messages ---
|
|
1136
|
+
if (msg.type === "loop_registry_list") {
|
|
1137
|
+
sendTo(ws, { type: "loop_registry_updated", records: getHubSchedules() });
|
|
1138
|
+
return true;
|
|
1139
|
+
}
|
|
1140
|
+
|
|
1141
|
+
if (msg.type === "loop_registry_update") {
|
|
1142
|
+
var updatedRec = loopRegistry.update(msg.id, msg.data || {});
|
|
1143
|
+
if (!updatedRec) {
|
|
1144
|
+
sendTo(ws, { type: "loop_registry_error", text: "Record not found" });
|
|
1145
|
+
}
|
|
1146
|
+
return true;
|
|
1147
|
+
}
|
|
1148
|
+
|
|
1149
|
+
if (msg.type === "loop_registry_rename") {
|
|
1150
|
+
if (msg.id && msg.name) {
|
|
1151
|
+
loopRegistry.updateRecord(msg.id, { name: String(msg.name).substring(0, 100) });
|
|
1152
|
+
sm.broadcastSessionList();
|
|
1153
|
+
}
|
|
1154
|
+
return true;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
if (msg.type === "loop_registry_remove") {
|
|
1158
|
+
var removedRec = loopRegistry.remove(msg.id);
|
|
1159
|
+
if (!removedRec) {
|
|
1160
|
+
sendTo(ws, { type: "loop_registry_error", text: "Record not found" });
|
|
1161
|
+
}
|
|
1162
|
+
return true;
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
if (msg.type === "loop_registry_convert") {
|
|
1166
|
+
// Convert ralph source to regular task (remove source tag)
|
|
1167
|
+
if (msg.id) {
|
|
1168
|
+
loopRegistry.updateRecord(msg.id, { source: null });
|
|
1169
|
+
sm.broadcastSessionList();
|
|
1170
|
+
}
|
|
1171
|
+
return true;
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
if (msg.type === "delete_loop_group") {
|
|
1175
|
+
// Delete all sessions belonging to this loopId, then remove registry record
|
|
1176
|
+
var loopIdToDel = msg.loopId;
|
|
1177
|
+
if (!loopIdToDel) return true;
|
|
1178
|
+
var sessionIds = [];
|
|
1179
|
+
sm.sessions.forEach(function (s, lid) {
|
|
1180
|
+
if (s.loop && s.loop.loopId === loopIdToDel) sessionIds.push(lid);
|
|
1181
|
+
});
|
|
1182
|
+
for (var di = 0; di < sessionIds.length; di++) {
|
|
1183
|
+
sm.deleteSessionQuiet(sessionIds[di]);
|
|
1184
|
+
}
|
|
1185
|
+
loopRegistry.remove(loopIdToDel);
|
|
1186
|
+
sm.broadcastSessionList();
|
|
1187
|
+
return true;
|
|
1188
|
+
}
|
|
1189
|
+
|
|
1190
|
+
if (msg.type === "loop_registry_toggle") {
|
|
1191
|
+
var toggledRec = loopRegistry.toggleEnabled(msg.id);
|
|
1192
|
+
if (!toggledRec) {
|
|
1193
|
+
sendTo(ws, { type: "loop_registry_error", text: "Record not found or not scheduled" });
|
|
1194
|
+
}
|
|
1195
|
+
return true;
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
if (msg.type === "loop_registry_rerun") {
|
|
1199
|
+
// Re-run an existing job (one-off from library)
|
|
1200
|
+
if (loopState.active || loopState.phase === "executing") {
|
|
1201
|
+
sendTo(ws, { type: "loop_registry_error", text: "A loop is already running" });
|
|
1202
|
+
return true;
|
|
1203
|
+
}
|
|
1204
|
+
var rerunRec = loopRegistry.getById(msg.id);
|
|
1205
|
+
if (!rerunRec) {
|
|
1206
|
+
sendTo(ws, { type: "loop_registry_error", text: "Record not found" });
|
|
1207
|
+
return true;
|
|
1208
|
+
}
|
|
1209
|
+
var rerunDir = path.join(cwd, ".claude", "loops", rerunRec.id);
|
|
1210
|
+
try {
|
|
1211
|
+
fs.accessSync(path.join(rerunDir, "PROMPT.md"));
|
|
1212
|
+
} catch (e) {
|
|
1213
|
+
sendTo(ws, { type: "loop_registry_error", text: "PROMPT.md missing for " + rerunRec.id });
|
|
1214
|
+
return true;
|
|
1215
|
+
}
|
|
1216
|
+
loopState.loopId = rerunRec.id;
|
|
1217
|
+
loopState.loopFilesId = null;
|
|
1218
|
+
activeRegistryId = null; // not a scheduled trigger
|
|
1219
|
+
send({ type: "loop_rerun_started", recordId: rerunRec.id });
|
|
1220
|
+
startLoop();
|
|
1221
|
+
return true;
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
return false; // not handled
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
// --- Connection state: send loop state to newly connected client ---
|
|
1228
|
+
function sendConnectionState(ws) {
|
|
1229
|
+
// Ralph Loop availability
|
|
1230
|
+
var _connIsSimple = loopState.wizardData && loopState.wizardData.loopMode === "simple";
|
|
1231
|
+
var hasLoopFiles = false;
|
|
1232
|
+
try {
|
|
1233
|
+
fs.accessSync(path.join(cwd, ".claude", "PROMPT.md"));
|
|
1234
|
+
if (!_connIsSimple) fs.accessSync(path.join(cwd, ".claude", "JUDGE.md"));
|
|
1235
|
+
hasLoopFiles = true;
|
|
1236
|
+
} catch (e) {}
|
|
1237
|
+
// Also check loop directory files
|
|
1238
|
+
if (!hasLoopFiles && loopState.loopId) {
|
|
1239
|
+
var _avDir = loopDir();
|
|
1240
|
+
if (_avDir) {
|
|
1241
|
+
try {
|
|
1242
|
+
fs.accessSync(path.join(_avDir, "PROMPT.md"));
|
|
1243
|
+
if (!_connIsSimple) fs.accessSync(path.join(_avDir, "JUDGE.md"));
|
|
1244
|
+
hasLoopFiles = true;
|
|
1245
|
+
} catch (e) {}
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
sendTo(ws, {
|
|
1249
|
+
type: "loop_available",
|
|
1250
|
+
available: hasLoopFiles,
|
|
1251
|
+
active: loopState.active,
|
|
1252
|
+
iteration: loopState.iteration,
|
|
1253
|
+
maxIterations: loopState.maxIterations,
|
|
1254
|
+
name: loopState.name || null,
|
|
1255
|
+
});
|
|
1256
|
+
|
|
1257
|
+
// Ralph phase state
|
|
1258
|
+
// Derive source from wizardData for reconnect (so client can distinguish ralph vs task)
|
|
1259
|
+
var _connSource = loopState.wizardData ? (loopState.wizardData.source || null) : null;
|
|
1260
|
+
sendTo(ws, {
|
|
1261
|
+
type: "ralph_phase",
|
|
1262
|
+
phase: loopState.phase,
|
|
1263
|
+
wizardData: loopState.wizardData,
|
|
1264
|
+
craftingSessionId: loopState.craftingSessionId || null,
|
|
1265
|
+
source: _connSource,
|
|
1266
|
+
});
|
|
1267
|
+
if (loopState.phase === "crafting" || loopState.phase === "approval") {
|
|
1268
|
+
var _hasPrompt = false;
|
|
1269
|
+
var _hasJudge = false;
|
|
1270
|
+
var _lDir = loopDir();
|
|
1271
|
+
if (_lDir) {
|
|
1272
|
+
try { fs.accessSync(path.join(_lDir, "PROMPT.md")); _hasPrompt = true; } catch (e) {}
|
|
1273
|
+
try { fs.accessSync(path.join(_lDir, "JUDGE.md")); _hasJudge = true; } catch (e) {}
|
|
1274
|
+
}
|
|
1275
|
+
var _connBothReady = _connIsSimple ? _hasPrompt : (_hasPrompt && _hasJudge);
|
|
1276
|
+
sendTo(ws, {
|
|
1277
|
+
type: "ralph_files_status",
|
|
1278
|
+
promptReady: _hasPrompt,
|
|
1279
|
+
judgeReady: _hasJudge,
|
|
1280
|
+
bothReady: _connBothReady,
|
|
1281
|
+
taskId: loopState.loopId,
|
|
1282
|
+
});
|
|
1283
|
+
}
|
|
1284
|
+
}
|
|
1285
|
+
|
|
1286
|
+
// --- Public API ---
|
|
1287
|
+
return {
|
|
1288
|
+
loopState: loopState,
|
|
1289
|
+
loopRegistry: loopRegistry,
|
|
1290
|
+
loopDir: loopDir,
|
|
1291
|
+
startLoop: startLoop,
|
|
1292
|
+
stopLoop: stopLoop,
|
|
1293
|
+
resumeLoop: resumeLoop,
|
|
1294
|
+
handleLoopMessage: handleLoopMessage,
|
|
1295
|
+
sendConnectionState: sendConnectionState,
|
|
1296
|
+
stopClaudeDirWatch: stopClaudeDirWatch,
|
|
1297
|
+
getSchedules: function () { return loopRegistry.getAll(); },
|
|
1298
|
+
importSchedule: function (data) { return loopRegistry.register(data); },
|
|
1299
|
+
removeSchedule: function (id) { return loopRegistry.remove(id); },
|
|
1300
|
+
stopTimer: function () { loopRegistry.stopTimer(); },
|
|
1301
|
+
};
|
|
1302
|
+
}
|
|
1303
|
+
|
|
1304
|
+
module.exports = { attachLoop: attachLoop };
|