@clagentic/console 1.5.0-beta.4 → 1.6.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.
@@ -7,13 +7,14 @@
7
7
  var fs = require("fs");
8
8
  var path = require("path");
9
9
  var { execFileSync } = require("child_process");
10
- var { CONFIG_DIR, REAL_HOME } = require("./config");
10
+ var { CLAGENTIC_HOME, REAL_HOME } = require("./config");
11
11
 
12
- // Lite home: <CONFIG_DIR>/lite/ — mirrors the path contract established in lr-dc6c.
13
- // CONFIG_DIR is the canonical clagentic data directory (resolves CLAGENTIC_HOME,
14
- // sudo users, and legacy ~/.clay/ migration the same way as every other daemon path).
12
+ // Lite home: ~/.clagentic/lite/ — Lite is a sibling tool that owns its own product
13
+ // folder under the shared ~/.clagentic/ root (lr-dc6c, lr-6204).
14
+ // Console owns ~/.clagentic/console/; Lite owns ~/.clagentic/lite/.
15
+ // Override: CLAGENTIC_LITE_HOME env var (matches clagentic-lite/bin/clagentic-lite:33).
15
16
  function getLiteHome() {
16
- return path.join(CONFIG_DIR, "lite");
17
+ return process.env.CLAGENTIC_LITE_HOME || path.join(CLAGENTIC_HOME, "lite");
17
18
  }
18
19
 
19
20
  // Return true when the Lite home directory exists.
@@ -0,0 +1,282 @@
1
+ /**
2
+ * Ralph Loop boundary compaction / handoff-to-disk (lr-ed10).
3
+ *
4
+ * At the completion of each loop iteration (the BOUNDARY between iterations),
5
+ * this module optionally writes a structured handoff file to disk and returns
6
+ * a brief summary that the next iteration prepends to its prompt.
7
+ *
8
+ * Design:
9
+ * - Opt-in only. No effect unless loopSettings.compactHandoff === true.
10
+ * - Handoff directory: CONFIG_DIR/handoffs/<loopId>/ — derived from the same
11
+ * config-dir root the rest of Console uses (lr-6204 path contract).
12
+ * - Each handoff file is named handoff-<N>.json (N = iteration number).
13
+ * - The structured frame contains: task, decisions, open_threads, key_files,
14
+ * verdict, iteration, timestamp. All fields are populated from the session
15
+ * history at the iteration boundary; fallback to empty when unavailable.
16
+ * - The summary injected into the next iteration is intentionally brief:
17
+ * a few lines of plain text covering just the fields above. It is
18
+ * prepended to the original PROMPT.md text by the caller.
19
+ * - Clean degradation: if the write fails the loop continues unchanged;
20
+ * if the read fails (no prior handoff exists) the loop continues unchanged.
21
+ *
22
+ * No new dependencies: uses only Node built-ins (fs, path, crypto).
23
+ */
24
+
25
+ "use strict";
26
+
27
+ var fs = require("fs");
28
+ var path = require("path");
29
+ var { CONFIG_DIR } = require("./config");
30
+
31
+ // ---------------------------------------------------------------------------
32
+ // Internal helpers
33
+ // ---------------------------------------------------------------------------
34
+
35
+ /**
36
+ * Build the handoff directory path for a given loopId.
37
+ * Always derived from CONFIG_DIR — never an absolute caller-supplied path.
38
+ * Returns null if loopId is missing or fails the safety regex.
39
+ *
40
+ * @param {string} loopId
41
+ * @returns {string|null}
42
+ */
43
+ function handoffDir(loopId) {
44
+ // Mirror the loop ID allowlist from scheduler.js / project-loop.js.
45
+ if (!loopId || !/^loop_[A-Za-z0-9_-]+$/.test(loopId)) return null;
46
+ return path.join(CONFIG_DIR, "handoffs", loopId);
47
+ }
48
+
49
+ /**
50
+ * Return the path for iteration N's handoff file.
51
+ * @param {string} loopId
52
+ * @param {number} iteration
53
+ * @returns {string|null}
54
+ */
55
+ function handoffFilePath(loopId, iteration) {
56
+ var dir = handoffDir(loopId);
57
+ if (!dir) return null;
58
+ return path.join(dir, "handoff-" + iteration + ".json");
59
+ }
60
+
61
+ /**
62
+ * Extract a brief human-readable summary from a completed session's history.
63
+ * Looks at the last assistant text blocks for decision/thread content.
64
+ * Returns a string up to ~1 000 chars — enough for a continuation frame
65
+ * without re-inflating the context.
66
+ *
67
+ * @param {Array} history session.history array
68
+ * @returns {string}
69
+ */
70
+ function extractSessionSummary(history) {
71
+ if (!Array.isArray(history) || history.length === 0) return "";
72
+
73
+ // Collect assistant text in reverse order until we have ~800 chars.
74
+ var chunks = [];
75
+ var total = 0;
76
+ for (var i = history.length - 1; i >= 0 && total < 800; i--) {
77
+ var entry = history[i];
78
+ var text = "";
79
+ if (entry.type === "delta" && entry.text) text = entry.text;
80
+ else if (entry.type === "text" && entry.text) text = entry.text;
81
+ if (text) {
82
+ chunks.unshift(text);
83
+ total += text.length;
84
+ }
85
+ }
86
+ return chunks.join("").slice(-800).trim();
87
+ }
88
+
89
+ /**
90
+ * Scan assistant text for lines that look like decisions or open items.
91
+ * Very lightweight heuristic — just extracts bullet-style lines.
92
+ *
93
+ * @param {string} text
94
+ * @returns {{ decisions: string[], open_threads: string[] }}
95
+ */
96
+ function parseDecisionsAndThreads(text) {
97
+ var decisions = [];
98
+ var threads = [];
99
+ if (!text) return { decisions: decisions, open_threads: threads };
100
+
101
+ var lines = text.split(/\r?\n/);
102
+ for (var i = 0; i < lines.length; i++) {
103
+ var line = lines[i].trim();
104
+ // Bullet / numbered list items
105
+ var isBullet = /^[-*•]\s+/.test(line) || /^\d+\.\s+/.test(line);
106
+ if (!isBullet || line.length < 5) continue;
107
+
108
+ var lower = line.toLowerCase();
109
+ // Decision-like: keywords that suggest a resolved choice
110
+ if (/\b(decided|chose|using|implemented|added|fixed|completed|done)\b/.test(lower)) {
111
+ decisions.push(line.substring(0, 120));
112
+ }
113
+ // Thread-like: keywords that suggest something still open
114
+ if (/\b(todo|open|still|pending|not yet|need to|should|must|missing|blocked)\b/.test(lower)) {
115
+ threads.push(line.substring(0, 120));
116
+ }
117
+ }
118
+ // Keep only the most recent N items to bound size
119
+ return {
120
+ decisions: decisions.slice(-5),
121
+ open_threads: threads.slice(-5),
122
+ };
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // Public API
127
+ // ---------------------------------------------------------------------------
128
+
129
+ /**
130
+ * Write a structured handoff file at the end of iteration N.
131
+ * Called at the iteration boundary — after the coder session completes
132
+ * and before the next iteration starts.
133
+ *
134
+ * Silently no-ops when:
135
+ * - compactHandoff is not enabled (settings.compactHandoff !== true)
136
+ * - loopId is missing or invalid
137
+ * - any write error occurs (loop must continue regardless)
138
+ *
139
+ * @param {object} opts
140
+ * @param {object} opts.loopState current loopState object
141
+ * @param {object} opts.session completed coder session (with .history)
142
+ * @param {string} [opts.verdict] judge verdict if available ("pass"|"fail"|null)
143
+ * @returns {boolean} true if a handoff file was written, false otherwise
144
+ */
145
+ function writeHandoff(opts) {
146
+ var loopState = opts.loopState;
147
+ var session = opts.session;
148
+ var verdict = opts.verdict || null;
149
+
150
+ // Guard: opt-in only
151
+ var settings = loopState.settings || {};
152
+ if (!settings.compactHandoff) return false;
153
+
154
+ var loopId = loopState.loopId;
155
+ var dir = handoffDir(loopId);
156
+ if (!dir) return false;
157
+
158
+ var filePath = handoffFilePath(loopId, loopState.iteration);
159
+ if (!filePath) return false;
160
+
161
+ try {
162
+ fs.mkdirSync(dir, { recursive: true });
163
+ } catch (e) {
164
+ console.warn("[loop-handoff] Failed to create handoff dir:", e.message);
165
+ return false;
166
+ }
167
+
168
+ var rawSummary = extractSessionSummary(session.history || []);
169
+ var parsed = parseDecisionsAndThreads(rawSummary);
170
+
171
+ var frame = {
172
+ schema_version: 1,
173
+ loop_id: loopId,
174
+ iteration: loopState.iteration,
175
+ task: (loopState.promptText || "").substring(0, 500),
176
+ decisions: parsed.decisions,
177
+ open_threads: parsed.open_threads,
178
+ key_files: [], // reserved for future tool-output parsing
179
+ verdict: verdict,
180
+ written_at: new Date().toISOString(),
181
+ };
182
+
183
+ var tmpPath = filePath + ".tmp";
184
+ try {
185
+ fs.writeFileSync(tmpPath, JSON.stringify(frame, null, 2), "utf8");
186
+ fs.renameSync(tmpPath, filePath);
187
+ console.log("[loop-handoff] Wrote handoff for " + loopId + " iteration " + loopState.iteration);
188
+ return true;
189
+ } catch (e) {
190
+ console.warn("[loop-handoff] Failed to write handoff file:", e.message);
191
+ try { fs.unlinkSync(tmpPath); } catch (_) {}
192
+ return false;
193
+ }
194
+ }
195
+
196
+ /**
197
+ * Read the most recent handoff file for a loop and return a brief
198
+ * structured summary string to prepend to the next iteration's prompt.
199
+ *
200
+ * Returns null when:
201
+ * - compactHandoff is not enabled
202
+ * - no prior handoff file exists (first iteration)
203
+ * - any read/parse error
204
+ *
205
+ * @param {object} opts
206
+ * @param {object} opts.loopState current loopState (iteration already incremented)
207
+ * @returns {string|null}
208
+ */
209
+ function buildHandoffPreamble(opts) {
210
+ var loopState = opts.loopState;
211
+
212
+ // Guard: opt-in only
213
+ var settings = loopState.settings || {};
214
+ if (!settings.compactHandoff) return null;
215
+
216
+ var loopId = loopState.loopId;
217
+ // The handoff was written for the PREVIOUS iteration
218
+ var prevIteration = loopState.iteration - 1;
219
+ if (prevIteration < 1) return null;
220
+
221
+ var filePath = handoffFilePath(loopId, prevIteration);
222
+ if (!filePath) return null;
223
+
224
+ var frame;
225
+ try {
226
+ var raw = fs.readFileSync(filePath, "utf8");
227
+ frame = JSON.parse(raw);
228
+ } catch (e) {
229
+ // No prior handoff — first iteration or file missing (clean degradation)
230
+ return null;
231
+ }
232
+
233
+ // Build a brief continuation frame — intentionally short
234
+ var lines = [
235
+ "## Continuation from iteration " + frame.iteration + " (structured handoff)",
236
+ "",
237
+ ];
238
+
239
+ if (frame.decisions && frame.decisions.length > 0) {
240
+ lines.push("**Decisions made in the previous iteration:**");
241
+ for (var i = 0; i < frame.decisions.length; i++) {
242
+ lines.push(" - " + frame.decisions[i]);
243
+ }
244
+ lines.push("");
245
+ }
246
+
247
+ if (frame.open_threads && frame.open_threads.length > 0) {
248
+ lines.push("**Open items from the previous iteration:**");
249
+ for (var j = 0; j < frame.open_threads.length; j++) {
250
+ lines.push(" - " + frame.open_threads[j]);
251
+ }
252
+ lines.push("");
253
+ }
254
+
255
+ if (frame.verdict) {
256
+ lines.push("**Previous judge verdict:** " + frame.verdict);
257
+ lines.push("");
258
+ }
259
+
260
+ lines.push("---");
261
+ lines.push("");
262
+
263
+ return lines.join("\n");
264
+ }
265
+
266
+ /**
267
+ * Return the handoff directory path for a given loopId.
268
+ * Exported for tests; not part of the runtime hot path.
269
+ */
270
+ function getHandoffDir(loopId) {
271
+ return handoffDir(loopId);
272
+ }
273
+
274
+ module.exports = {
275
+ writeHandoff: writeHandoff,
276
+ buildHandoffPreamble: buildHandoffPreamble,
277
+ getHandoffDir: getHandoffDir,
278
+ // Exported for unit tests only
279
+ _handoffFilePath: handoffFilePath,
280
+ _extractSessionSummary: extractSessionSummary,
281
+ _parseDecisionsAndThreads: parseDecisionsAndThreads,
282
+ };
package/lib/mcp-local.js CHANGED
@@ -6,8 +6,24 @@ var child_process = require("child_process");
6
6
  var fs = require("fs");
7
7
  var path = require("path");
8
8
  var os = require("os");
9
-
10
- var CLAY_CONFIG_PATH = path.join(os.homedir(), ".clagentic", "mcp.json");
9
+ var { CONFIG_DIR } = require("./config");
10
+
11
+ // mcp.json lives under the Console data dir (CONFIG_DIR = ~/.clagentic/console/).
12
+ // One-time migration: if the old root-level file exists and the new one does not,
13
+ // copy it so existing server configs are preserved on upgrade.
14
+ var CLAY_CONFIG_PATH = path.join(CONFIG_DIR, "mcp.json");
15
+ (function migrateMcpJson() {
16
+ var oldPath = path.join(os.homedir(), ".clagentic", "mcp.json");
17
+ try {
18
+ if (fs.existsSync(oldPath) && !fs.existsSync(CLAY_CONFIG_PATH)) {
19
+ fs.mkdirSync(path.dirname(CLAY_CONFIG_PATH), { recursive: true });
20
+ fs.copyFileSync(oldPath, CLAY_CONFIG_PATH);
21
+ console.log("[mcp-local] Migrated mcp.json → " + CLAY_CONFIG_PATH + " — root copy can be removed when verified");
22
+ }
23
+ } catch (e) {
24
+ // Non-fatal — mcp.json will be created fresh on first use
25
+ }
26
+ }());
11
27
 
12
28
  function createLocalMcp() {
13
29
  var _configCache = {}; // name -> { command, args, env, url }