geloforge 0.6.0 → 0.9.0

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.
@@ -0,0 +1,488 @@
1
+ /**
2
+ * Deterministic MCP tool-surface pinning (`.geloforge/mcp-lock.json`).
3
+ * Probes configured stdio MCP servers via JSON-RPC 2.0 (zero network calls),
4
+ * hashes canonical tool definitions, and detects tool-surface drift.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { spawn } from "node:child_process";
9
+ import { buildProviderEnv } from "./audit-provider.mjs";
10
+ import { MCP_CLIENTS, parseConfig } from "./mcp-init.mjs";
11
+ import {
12
+ findHeaderSeparator,
13
+ MAX_MCP_HEADER_BYTES,
14
+ MAX_MCP_MESSAGE_BYTES,
15
+ parseLspContentLength,
16
+ } from "./mcp-server.mjs";
17
+ import { assertSafeWithinRoot, atomicWriteFile, hasSecretContent, redactSecretContent } from "./path-safety.mjs";
18
+ import { loadProjectManifestAndState } from "./project-locator.mjs";
19
+ import { withProjectLock } from "./project-lock.mjs";
20
+ import { readRegularFile, sha256 } from "./runtime-files.mjs";
21
+
22
+ export const MCP_LOCK_PATH = ".geloforge/mcp-lock.json";
23
+ const DEFAULT_PROBE_TIMEOUT_MS = 8000;
24
+ const MAX_TOOL_PAGES = 50;
25
+
26
+ function compareCodepoints(a, b) {
27
+ return a < b ? -1 : a > b ? 1 : 0;
28
+ }
29
+
30
+ function canonicalSort(value) {
31
+ if (Array.isArray(value)) return value.map(canonicalSort);
32
+ if (value && typeof value === "object") {
33
+ const out = {};
34
+ for (const key of Object.keys(value).sort(compareCodepoints)) {
35
+ if (value[key] !== undefined) out[key] = canonicalSort(value[key]);
36
+ }
37
+ return out;
38
+ }
39
+ return value;
40
+ }
41
+
42
+ function canonicalStringify(value) {
43
+ return JSON.stringify(canonicalSort(value));
44
+ }
45
+
46
+ function resolveTargetClients(clients) {
47
+ const list = clients?.length ? [...new Set(clients)] : Object.keys(MCP_CLIENTS);
48
+ for (const name of list) {
49
+ if (!Object.hasOwn(MCP_CLIENTS, name)) {
50
+ throw new Error(`Unknown MCP client "${name}". Use ${Object.keys(MCP_CLIENTS).join(", ")}.`);
51
+ }
52
+ }
53
+ return list;
54
+ }
55
+
56
+ function discoverConfiguredServers(projectDir, clients) {
57
+ const clientNames = resolveTargetClients(clients);
58
+ const stdio = [];
59
+ const skipped = [];
60
+
61
+ for (const clientName of clientNames) {
62
+ const client = MCP_CLIENTS[clientName];
63
+ const absPath = assertSafeWithinRoot(projectDir, client.config);
64
+ const stat = fs.lstatSync(absPath, { throwIfNoEntry: false });
65
+ if (!stat) continue;
66
+ if (!stat.isFile()) {
67
+ throw new Error(`Expected a regular MCP config file at ${client.config}.`);
68
+ }
69
+ const raw = fs.readFileSync(absPath, "utf8");
70
+ const { data } = parseConfig(raw, client.config);
71
+ if (!Object.hasOwn(data, client.key) || data[client.key] == null) continue;
72
+ const servers = data[client.key];
73
+ if (Array.isArray(servers) || typeof servers !== "object") {
74
+ throw new Error(`Expected ${client.key} to be an object in ${client.config}.`);
75
+ }
76
+ for (const name of Object.keys(servers).sort(compareCodepoints)) {
77
+ const entry = servers[name];
78
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
79
+ skipped.push({ configPath: client.config, name, reason: "invalid_entry" });
80
+ continue;
81
+ }
82
+ const isNonStdio =
83
+ Boolean(entry.url || entry.httpUrl || entry.serverUrl) ||
84
+ (entry.type && entry.type !== "stdio") ||
85
+ typeof entry.command !== "string" ||
86
+ !entry.command.trim();
87
+ if (isNonStdio) {
88
+ skipped.push({ configPath: client.config, name, reason: "non_stdio_skipped" });
89
+ continue;
90
+ }
91
+ if (entry.args !== undefined && !Array.isArray(entry.args)) {
92
+ throw new Error(`Expected args array for MCP server "${name}" in ${client.config}.`);
93
+ }
94
+ if (entry.env !== undefined && (!entry.env || Array.isArray(entry.env) || typeof entry.env !== "object")) {
95
+ throw new Error(`Expected env object for MCP server "${name}" in ${client.config}.`);
96
+ }
97
+ stdio.push({
98
+ client: clientName,
99
+ configPath: client.config,
100
+ name,
101
+ command: entry.command,
102
+ args: (entry.args ?? []).map(String),
103
+ env: entry.env ?? null,
104
+ });
105
+ }
106
+ }
107
+ return { stdio, skipped };
108
+ }
109
+
110
+ function createRpcFramer(onMessage, onError) {
111
+ let buffer = Buffer.alloc(0);
112
+ return (chunk) => {
113
+ buffer = Buffer.concat([buffer, Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)]);
114
+ if (buffer.length > MAX_MCP_MESSAGE_BYTES * 2) {
115
+ onError(new Error("MCP server stdout exceeded bounded buffer limit."));
116
+ return;
117
+ }
118
+ while (buffer.length > 0) {
119
+ let skip = 0;
120
+ while (skip < buffer.length && [0x20, 0x09, 0x0d, 0x0a].includes(buffer[skip])) skip += 1;
121
+ if (skip > 0) buffer = buffer.subarray(skip);
122
+ if (buffer.length === 0) break;
123
+
124
+ const preview = buffer.subarray(0, Math.min(32, buffer.length)).toString("utf8");
125
+ if (/^content-(?:length|type)\s*:/i.test(preview)) {
126
+ const sep = findHeaderSeparator(buffer);
127
+ if (sep.index === -1) {
128
+ if (buffer.length > MAX_MCP_HEADER_BYTES) onError(new Error("MCP response header exceeded limit."));
129
+ break;
130
+ }
131
+ const parsed = parseLspContentLength(buffer.subarray(0, sep.index).toString("utf8"), MAX_MCP_MESSAGE_BYTES);
132
+ if (!parsed.ok) {
133
+ onError(new Error(parsed.error));
134
+ return;
135
+ }
136
+ const bodyStart = sep.index + sep.len;
137
+ if (buffer.length < bodyStart + parsed.contentLength) break;
138
+ const body = buffer.subarray(bodyStart, bodyStart + parsed.contentLength).toString("utf8");
139
+ buffer = buffer.subarray(bodyStart + parsed.contentLength);
140
+ onMessage(body);
141
+ } else {
142
+ const nl = buffer.indexOf("\n");
143
+ if (nl === -1) break;
144
+ const line = buffer.subarray(0, nl).toString("utf8").trim();
145
+ buffer = buffer.subarray(nl + 1);
146
+ if (line) onMessage(line);
147
+ }
148
+ }
149
+ };
150
+ }
151
+
152
+ async function probeStdioServer(server, projectDir, timeoutMs) {
153
+ const child = spawn(server.command, server.args, {
154
+ cwd: projectDir,
155
+ env: buildProviderEnv(null, server.env),
156
+ stdio: ["pipe", "pipe", "pipe"],
157
+ windowsHide: true,
158
+ });
159
+ const pending = new Map();
160
+ let stderrTail = "";
161
+ let fatal = null;
162
+ let timer = null;
163
+
164
+ const failPending = (err) => {
165
+ fatal = fatal ?? err;
166
+ for (const { reject } of pending.values()) reject(fatal);
167
+ pending.clear();
168
+ };
169
+
170
+ const closePromise = new Promise((resolve) => child.once("close", (code) => resolve(code)));
171
+ child.stdin?.on("error", () => {});
172
+ child.on("error", (err) => failPending(new Error(`Failed to start "${server.name}": ${redactSecretContent(err.message)}`)));
173
+ child.stderr?.on("data", (chunk) => {
174
+ stderrTail = `${stderrTail}${chunk.toString("utf8")}`.slice(-4096);
175
+ });
176
+ child.on("close", (code) => {
177
+ if (pending.size > 0) {
178
+ const detail = stderrTail ? ` (${redactSecretContent(stderrTail.trim()).slice(0, 200)})` : "";
179
+ failPending(new Error(`MCP server "${server.name}" exited (code ${code ?? "null"}) before responding${detail}.`));
180
+ }
181
+ });
182
+
183
+ const feed = createRpcFramer(
184
+ (raw) => {
185
+ let msg;
186
+ try {
187
+ msg = JSON.parse(raw);
188
+ } catch {
189
+ return;
190
+ }
191
+ if (msg && msg.id !== undefined && msg.id !== null && pending.has(msg.id)) {
192
+ const entry = pending.get(msg.id);
193
+ pending.delete(msg.id);
194
+ if (msg.error) {
195
+ entry.reject(new Error(`MCP server "${server.name}" error: ${redactSecretContent(String(msg.error.message ?? msg.error.code))}`));
196
+ } else {
197
+ entry.resolve(msg.result ?? {});
198
+ }
199
+ }
200
+ },
201
+ (err) => failPending(err)
202
+ );
203
+ child.stdout?.on("data", feed);
204
+
205
+ const timeoutPromise = new Promise((_, reject) => {
206
+ timer = setTimeout(() => {
207
+ const err = new Error(`MCP probe for "${server.name}" timed out after ${timeoutMs}ms.`);
208
+ failPending(err);
209
+ reject(err);
210
+ }, timeoutMs);
211
+ });
212
+
213
+ let nextId = 0;
214
+ const rpcRequest = (method, params = {}) => {
215
+ if (fatal) return Promise.reject(fatal);
216
+ const id = ++nextId;
217
+ const responsePromise = new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
218
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", id, method, params })}\n`);
219
+ return Promise.race([responsePromise, timeoutPromise]);
220
+ };
221
+
222
+ try {
223
+ const initResult = await rpcRequest("initialize", {
224
+ protocolVersion: "2025-06-18",
225
+ capabilities: {},
226
+ clientInfo: { name: "geloforge-mcp-lock", version: "1.0.0" },
227
+ });
228
+ child.stdin.write(`${JSON.stringify({ jsonrpc: "2.0", method: "notifications/initialized" })}\n`);
229
+
230
+ const rawTools = [];
231
+ let cursor = undefined;
232
+ for (let page = 0; page < MAX_TOOL_PAGES; page += 1) {
233
+ const listResult = await rpcRequest("tools/list", cursor ? { cursor } : {});
234
+ if (Array.isArray(listResult.tools)) rawTools.push(...listResult.tools);
235
+ if (!listResult.nextCursor) break;
236
+ cursor = String(listResult.nextCursor);
237
+ if (page === MAX_TOOL_PAGES - 1) {
238
+ throw new Error(`MCP server "${server.name}" exceeded maximum tools/list pagination depth.`);
239
+ }
240
+ }
241
+
242
+ const canonicalTools = rawTools
243
+ .map((tool) => {
244
+ if (!tool || typeof tool !== "object" || typeof tool.name !== "string" || !tool.name) {
245
+ throw new Error(`MCP server "${server.name}" returned a tool entry without a valid name.`);
246
+ }
247
+ return {
248
+ name: tool.name,
249
+ description: typeof tool.description === "string" ? tool.description : "",
250
+ inputSchema: tool.inputSchema ?? null,
251
+ ...(tool.outputSchema !== undefined ? { outputSchema: tool.outputSchema } : {}),
252
+ ...(tool.annotations !== undefined ? { annotations: tool.annotations } : {}),
253
+ ...(tool.input_examples !== undefined ? { input_examples: tool.input_examples } : {}),
254
+ };
255
+ })
256
+ .sort((a, b) => compareCodepoints(a.name, b.name));
257
+
258
+ const canonicalJson = canonicalStringify(canonicalTools);
259
+ if (hasSecretContent(canonicalJson)) {
260
+ throw new Error(`Refusing credential-like content in MCP tool definitions for "${server.name}".`);
261
+ }
262
+ const pinnedTools = canonicalTools.map((tool) => ({
263
+ name: tool.name,
264
+ digest: sha256(canonicalStringify(tool)),
265
+ }));
266
+ const serverInfo = initResult?.serverInfo && typeof initResult.serverInfo === "object"
267
+ ? {
268
+ name: typeof initResult.serverInfo.name === "string" ? initResult.serverInfo.name : null,
269
+ version: typeof initResult.serverInfo.version === "string" ? initResult.serverInfo.version : null,
270
+ }
271
+ : null;
272
+
273
+ return {
274
+ configPath: server.configPath,
275
+ name: server.name,
276
+ transport: "stdio",
277
+ commandBasename: path.basename(server.command),
278
+ serverInfo,
279
+ toolCount: pinnedTools.length,
280
+ surfaceDigest: sha256(canonicalJson),
281
+ tools: pinnedTools,
282
+ };
283
+ } finally {
284
+ clearTimeout(timer);
285
+ pending.clear();
286
+ try {
287
+ child.stdin?.end();
288
+ } catch {
289
+ // Ignore stdin shutdown failures on exited processes.
290
+ }
291
+ const cleanWait = Promise.race([
292
+ closePromise,
293
+ new Promise((resolve) => setTimeout(resolve, 250)),
294
+ ]);
295
+ await cleanWait;
296
+ if (child.exitCode === null && child.signalCode === null) {
297
+ try {
298
+ child.kill("SIGKILL");
299
+ } catch {
300
+ // Process already exited.
301
+ }
302
+ await Promise.race([closePromise, new Promise((resolve) => setTimeout(resolve, 200))]);
303
+ }
304
+ }
305
+ }
306
+
307
+ function validateTimeoutMs(timeoutMs) {
308
+ if (timeoutMs === undefined || timeoutMs === null) return DEFAULT_PROBE_TIMEOUT_MS;
309
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 100 || timeoutMs > 60_000) {
310
+ throw new Error("--timeout-ms must be an integer between 100 and 60000.");
311
+ }
312
+ return timeoutMs;
313
+ }
314
+
315
+ function serverKey(entry) {
316
+ return `${entry.configPath}::${entry.name}`;
317
+ }
318
+
319
+ function diffPinnedToolSurface(expected, actual) {
320
+ const expMap = new Map((expected.tools ?? []).map((t) => [t.name, t.digest]));
321
+ const actMap = new Map((actual.tools ?? []).map((t) => [t.name, t.digest]));
322
+ const addedTools = [];
323
+ const removedTools = [];
324
+ const changedTools = [];
325
+
326
+ for (const [name, digest] of actMap) {
327
+ if (!expMap.has(name)) addedTools.push(name);
328
+ else if (expMap.get(name) !== digest) changedTools.push(name);
329
+ }
330
+ for (const name of expMap.keys()) {
331
+ if (!actMap.has(name)) removedTools.push(name);
332
+ }
333
+ addedTools.sort(compareCodepoints);
334
+ removedTools.sort(compareCodepoints);
335
+ changedTools.sort(compareCodepoints);
336
+
337
+ const hasDrift =
338
+ expected.surfaceDigest !== actual.surfaceDigest ||
339
+ addedTools.length > 0 ||
340
+ removedTools.length > 0 ||
341
+ changedTools.length > 0;
342
+ if (!hasDrift) return null;
343
+
344
+ return {
345
+ configPath: actual.configPath,
346
+ name: actual.name,
347
+ expectedDigest: expected.surfaceDigest,
348
+ actualDigest: actual.surfaceDigest,
349
+ addedTools,
350
+ removedTools,
351
+ changedTools,
352
+ };
353
+ }
354
+
355
+ /**
356
+ * Probes configured stdio MCP servers and pins their canonical tool digests to `.geloforge/mcp-lock.json`.
357
+ */
358
+ export async function lockMcpServers({
359
+ projectDir,
360
+ harnessDir,
361
+ clients = null,
362
+ timeoutMs,
363
+ dryRun = false,
364
+ } = {}) {
365
+ const loaded = loadProjectManifestAndState(projectDir, harnessDir);
366
+ const safeTimeout = validateTimeoutMs(timeoutMs);
367
+ const { stdio, skipped } = discoverConfiguredServers(loaded.projectDir, clients);
368
+ const servers = [];
369
+ for (const target of stdio) {
370
+ servers.push(await probeStdioServer(target, loaded.projectDir, safeTimeout));
371
+ }
372
+ servers.sort((a, b) => compareCodepoints(serverKey(a), serverKey(b)));
373
+ const lockPayload = {
374
+ version: 1,
375
+ generatedAt: new Date().toISOString(),
376
+ servers,
377
+ skipped,
378
+ };
379
+ if (!dryRun) {
380
+ withProjectLock(loaded.projectDir, () => {
381
+ const lockAbs = assertSafeWithinRoot(loaded.projectDir, MCP_LOCK_PATH);
382
+ const stat = fs.lstatSync(lockAbs, { throwIfNoEntry: false });
383
+ if (stat && !stat.isFile()) {
384
+ throw new Error(`Refusing symbolic link or non-regular lock file: ${MCP_LOCK_PATH}`);
385
+ }
386
+ atomicWriteFile(lockAbs, `${JSON.stringify(lockPayload, null, 2)}\n`, { allowOverwrite: true, mode: 0o600 });
387
+ });
388
+ }
389
+ return {
390
+ action: "locked",
391
+ projectDir: loaded.projectDir,
392
+ lockPath: MCP_LOCK_PATH,
393
+ dryRun: Boolean(dryRun),
394
+ serverCount: servers.length,
395
+ skippedCount: skipped.length,
396
+ servers,
397
+ skipped,
398
+ };
399
+ }
400
+
401
+ /**
402
+ * Verifies currently configured stdio MCP servers against the saved `.geloforge/mcp-lock.json`.
403
+ */
404
+ export async function checkMcpLock({
405
+ projectDir,
406
+ harnessDir,
407
+ clients = null,
408
+ timeoutMs,
409
+ } = {}) {
410
+ const loaded = loadProjectManifestAndState(projectDir, harnessDir);
411
+ const safeTimeout = validateTimeoutMs(timeoutMs);
412
+ const lockAbs = assertSafeWithinRoot(loaded.projectDir, MCP_LOCK_PATH);
413
+ const raw = readRegularFile(lockAbs, MAX_MCP_MESSAGE_BYTES);
414
+ if (!raw) {
415
+ throw new Error(`MCP lock file not found at ${MCP_LOCK_PATH}. Run "geloforge mcp lock" first.`);
416
+ }
417
+ let lockData;
418
+ try {
419
+ lockData = JSON.parse(raw.toString("utf8").replace(/^\uFEFF/, ""));
420
+ } catch {
421
+ throw new Error(`Invalid JSON in ${MCP_LOCK_PATH}. Re-generate with "geloforge mcp lock".`);
422
+ }
423
+ if (!lockData || lockData.version !== 1 || !Array.isArray(lockData.servers)) {
424
+ throw new Error(`Unsupported or corrupt MCP lock schema in ${MCP_LOCK_PATH}.`);
425
+ }
426
+
427
+ const targetClientConfigs = new Set(resolveTargetClients(clients).map((name) => MCP_CLIENTS[name].config));
428
+ const pinnedMap = new Map(
429
+ lockData.servers
430
+ .filter((entry) => entry && typeof entry.configPath === "string" && typeof entry.name === "string")
431
+ .filter((entry) => targetClientConfigs.has(entry.configPath))
432
+ .map((entry) => [serverKey(entry), entry])
433
+ );
434
+
435
+ const { stdio, skipped } = discoverConfiguredServers(loaded.projectDir, clients);
436
+ const actualMap = new Map();
437
+ const errors = [];
438
+ for (const target of stdio) {
439
+ try {
440
+ const probed = await probeStdioServer(target, loaded.projectDir, safeTimeout);
441
+ actualMap.set(serverKey(probed), probed);
442
+ } catch (err) {
443
+ errors.push({
444
+ configPath: target.configPath,
445
+ name: target.name,
446
+ error: redactSecretContent(err.message),
447
+ });
448
+ }
449
+ }
450
+
451
+ const addedServers = [];
452
+ const removedServers = [];
453
+ const driftedServers = [];
454
+
455
+ for (const [key, actual] of actualMap) {
456
+ if (!pinnedMap.has(key)) {
457
+ addedServers.push({ configPath: actual.configPath, name: actual.name, actualDigest: actual.surfaceDigest });
458
+ continue;
459
+ }
460
+ const diff = diffPinnedToolSurface(pinnedMap.get(key), actual);
461
+ if (diff) driftedServers.push(diff);
462
+ }
463
+ const errorKeys = new Set(errors.map((e) => `${e.configPath}::${e.name}`));
464
+ for (const [key, expected] of pinnedMap) {
465
+ if (!actualMap.has(key) && !errorKeys.has(key)) {
466
+ removedServers.push({ configPath: expected.configPath, name: expected.name, expectedDigest: expected.surfaceDigest });
467
+ }
468
+ }
469
+
470
+ const passed =
471
+ addedServers.length === 0 &&
472
+ removedServers.length === 0 &&
473
+ driftedServers.length === 0 &&
474
+ errors.length === 0;
475
+
476
+ return {
477
+ action: "check",
478
+ projectDir: loaded.projectDir,
479
+ lockPath: MCP_LOCK_PATH,
480
+ passed,
481
+ checkedCount: actualMap.size,
482
+ addedServers,
483
+ removedServers,
484
+ driftedServers,
485
+ skipped,
486
+ errors,
487
+ };
488
+ }
@@ -24,6 +24,7 @@ import {
24
24
  } from "./task-manager.mjs";
25
25
  import { createCheckpoint, getCheckpoint, listCheckpoints } from "./checkpoint.mjs";
26
26
  import { discoverSkills, resolveProjectForSkills } from "./skills.mjs";
27
+ import { suggestProjectSkills } from "./skills-advisor.mjs";
27
28
  import { lintDiscoveredSkills, lintSkill } from "./skills-lint.mjs";
28
29
  import { draftSkillFromExperience, getSkillHistory, proposeSkillUpdate } from "./skills-lifecycle.mjs";
29
30
  import { redactSecretContent } from "./path-safety.mjs";
@@ -39,7 +40,7 @@ export const MAX_MCP_HEADER_BYTES = 4096;
39
40
 
40
41
  const MUTATING_TASK_ACTIONS = new Set(["new", "update", "done", "claim", "release"]);
41
42
  const MUTATING_CHECKPOINT_ACTIONS = new Set(["create"]);
42
- const MUTATING_SKILLS_ACTIONS = new Set(["draft", "propose", "propose-update"]);
43
+ const MUTATING_SKILLS_ACTIONS = new Set(["draft", "propose", "propose-update", "scaffold"]);
43
44
 
44
45
  function getHarnessVersion(harnessDir) {
45
46
  try {
@@ -113,6 +114,10 @@ export const MCP_TOOLS = [
113
114
  excludeUnverified: { type: "boolean" },
114
115
  },
115
116
  },
117
+ input_examples: [
118
+ { task: "TASK-0001", profile: "working", map: true, skills: true },
119
+ { query: "authentication flow", profile: "quick", fromDiff: true },
120
+ ],
116
121
  },
117
122
  {
118
123
  name: "geloforge_task",
@@ -153,6 +158,10 @@ export const MCP_TOOLS = [
153
158
  dryRun: { type: "boolean" },
154
159
  },
155
160
  },
161
+ input_examples: [
162
+ { action: "list" },
163
+ { action: "claim", task: "TASK-0001", tool: "cursor", sessionId: "sess-1", scopes: ["src/"] },
164
+ ],
156
165
  },
157
166
  {
158
167
  name: "geloforge_checkpoint",
@@ -180,16 +189,20 @@ export const MCP_TOOLS = [
180
189
  dryRun: { type: "boolean" },
181
190
  },
182
191
  },
192
+ input_examples: [
193
+ { action: "list" },
194
+ { action: "create", summary: "Verification checks passed", evidenceRef: "EVID-0001" },
195
+ ],
183
196
  },
184
197
  {
185
198
  name: "geloforge_skills",
186
199
  description:
187
- "[READ + QUARANTINED-DRAFT ONLY] Inspect, lint, view history, or stage quarantined skill drafts/updates from verified evidence. Read-only actions: list, show, validate, lint, history. Mutating (quarantine-only, disabled in --read-only): draft, propose. Refused: promote, rollback, keygen, sign.",
200
+ "[READ + QUARANTINED-DRAFT ONLY] Inspect, lint, suggest, view history, or stage quarantined skill drafts/updates from verified evidence or repository signals. Read-only actions: list, show, validate, lint, suggest, history. Mutating (quarantine-only, disabled in --read-only): draft, propose, scaffold. Refused: promote, rollback, keygen, sign.",
188
201
  annotations: {
189
202
  readOnlyHint: false,
190
203
  destructiveHint: false,
191
- readOnlyActions: ["list", "show", "validate", "lint", "history"],
192
- mutatingActions: ["draft", "propose"],
204
+ readOnlyActions: ["list", "show", "validate", "lint", "suggest", "history"],
205
+ mutatingActions: ["draft", "propose", "scaffold"],
193
206
  refusedActions: ["promote", "rollback", "keygen", "sign"],
194
207
  },
195
208
  inputSchema: {
@@ -199,10 +212,14 @@ export const MCP_TOOLS = [
199
212
  properties: {
200
213
  action: {
201
214
  type: "string",
202
- enum: ["list", "show", "validate", "lint", "draft", "propose", "history"],
215
+ enum: ["list", "show", "validate", "lint", "suggest", "scaffold", "draft", "propose", "history"],
203
216
  },
204
217
  project: { type: "string" },
205
218
  name: { type: "string" },
219
+ goal: { type: "string" },
220
+ query: { type: "string" },
221
+ task: { type: "string" },
222
+ limit: { type: "integer", minimum: 1, maximum: 20 },
206
223
  includeDrafts: { type: "boolean" },
207
224
  strict: { type: "boolean" },
208
225
  evidenceIds: { type: "array", items: { type: "string" } },
@@ -217,6 +234,11 @@ export const MCP_TOOLS = [
217
234
  dryRun: { type: "boolean" },
218
235
  },
219
236
  },
237
+ input_examples: [
238
+ { action: "list", includeDrafts: false },
239
+ { action: "suggest", goal: "verify database migrations" },
240
+ { action: "lint", strict: true },
241
+ ],
220
242
  },
221
243
  ];
222
244
 
@@ -414,6 +436,25 @@ function invokeSkillsTool(args, ctx) {
414
436
  const projectDir = resolveTargetProject(args, ctx);
415
437
  const { harnessDir } = ctx;
416
438
 
439
+ if (action === "suggest" || action === "scaffold") {
440
+ return suggestProjectSkills({
441
+ projectDir,
442
+ harnessDir,
443
+ taskId: args.task || null,
444
+ goal: args.goal || null,
445
+ query: args.query || null,
446
+ limit: args.limit,
447
+ includeDrafts: Boolean(args.includeDrafts),
448
+ scaffoldDraft: action === "scaffold",
449
+ skillName: args.name || null,
450
+ title: args.title || null,
451
+ description: args.description || null,
452
+ tags: args.tags,
453
+ triggers: args.triggers,
454
+ dryRun: Boolean(args.dryRun),
455
+ });
456
+ }
457
+
417
458
  if (action === "draft") {
418
459
  return draftSkillFromExperience({
419
460
  projectDir,
@@ -509,6 +550,27 @@ function invokeSkillsTool(args, ctx) {
509
550
  throw new Error(`Unsupported skills action "${action}".`);
510
551
  }
511
552
 
553
+ function formatToolErrorWithHint(toolName, toolArgs, err, ctx) {
554
+ const base = redactSecretContent(err?.message || "Tool execution failed");
555
+ const tool = MCP_TOOLS.find((t) => t.name === toolName);
556
+ const hints = [];
557
+ if (ctx.readOnly && /read-only/i.test(base) && tool?.annotations?.readOnlyActions?.length) {
558
+ hints.push(`Read-only actions allowed: ${tool.annotations.readOnlyActions.join(", ")}.`);
559
+ } else if (tool?.inputSchema?.properties?.action?.enum) {
560
+ const validActions = tool.inputSchema.properties.action.enum;
561
+ const passedAction = String(toolArgs?.action ?? "").trim().toLowerCase();
562
+ if (!passedAction || !validActions.includes(passedAction) || /^(Unknown|Unsupported|Missing).*action/i.test(base)) {
563
+ hints.push(`Valid actions: ${validActions.join(", ")}.`);
564
+ }
565
+ } else if (toolName === "geloforge_context" && !toolArgs?.task && !toolArgs?.query && !toolArgs?.fromDiff) {
566
+ hints.push('Pass at least one target: "task" ("TASK-NNNN"), "query" ("..."), or "fromDiff": true.');
567
+ }
568
+ if (hints.length > 0 && Array.isArray(tool?.input_examples) && tool.input_examples.length > 0 && !(ctx.readOnly && /read-only/i.test(base))) {
569
+ hints.push(`Example: ${JSON.stringify(tool.input_examples[0])}`);
570
+ }
571
+ return redactSecretContent(hints.length > 0 ? `${base}\nHint: ${hints.join(" ")}` : base);
572
+ }
573
+
512
574
  function executeToolCall(name, args, ctx) {
513
575
  switch (name) {
514
576
  case "geloforge_status": {
@@ -662,7 +724,7 @@ export function handleMcpMessage(
662
724
  jsonrpc: "2.0",
663
725
  id: msg.id,
664
726
  result: {
665
- content: [{ type: "text", text: redactSecretContent(err.message || "Tool execution failed") }],
727
+ content: [{ type: "text", text: formatToolErrorWithHint(toolName, toolArgs, err, ctx) }],
666
728
  isError: true,
667
729
  },
668
730
  };
@@ -698,7 +760,7 @@ function writeFramedResponse(output, responseObj, framing) {
698
760
  }
699
761
  }
700
762
 
701
- function parseLspContentLength(headersText, maxMessageBytes) {
763
+ export function parseLspContentLength(headersText, maxMessageBytes) {
702
764
  const lines = headersText.split(/\r?\n/);
703
765
  const contentLengths = [];
704
766
  for (const rawLine of lines) {
@@ -737,7 +799,7 @@ function parseLspContentLength(headersText, maxMessageBytes) {
737
799
  return { ok: true, contentLength: contentLengths[0] };
738
800
  }
739
801
 
740
- function findHeaderSeparator(buffer) {
802
+ export function findHeaderSeparator(buffer) {
741
803
  const crlf = buffer.indexOf("\r\n\r\n");
742
804
  const lf = buffer.indexOf("\n\n");
743
805
  if (crlf !== -1 && (lf === -1 || crlf <= lf)) {