geloforge 0.7.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,944 @@
1
+ /**
2
+ * Deterministic Project/Goal Skills Advisor & Quarantined Draft Scaffolder.
3
+ *
4
+ * Analyzes local repository signals (package manifests, CI workflows, Second Brain
5
+ * constraints/architecture, active task scope, and EVID-* records) against trusted
6
+ * `.agents/skills/` and global skills to:
7
+ * 1. Rank existing skills relevant to the current project or goal.
8
+ * 2. Identify concrete, evidence/repo-grounded skill gaps.
9
+ * 3. Optionally scaffold a strictly quarantined SKILL.md draft under
10
+ * `<proposals_dir>/skills/<name>/` (never auto-activating or bypassing approval).
11
+ *
12
+ * Security invariants:
13
+ * - Zero third-party dependencies, zero network calls, zero shell execution.
14
+ * - Rejects symlinked manifests/directories cleanly and never emits secret literals.
15
+ */
16
+
17
+ import crypto from "node:crypto";
18
+ import fs from "node:fs";
19
+ import os from "node:os";
20
+ import path from "node:path";
21
+ import { fileURLToPath } from "node:url";
22
+ import { parseYaml, serializeYaml } from "./yaml-subset.mjs";
23
+ import { loadProjectManifestAndState } from "./project-locator.mjs";
24
+ import { getTask } from "./task-manager.mjs";
25
+ import { validateCreatedAt } from "./template-utils.mjs";
26
+ import { scoreBm25Documents, tokenizeKeywords, tokenizeTerms } from "./text-utils.mjs";
27
+ import {
28
+ assertSafeWithinRoot,
29
+ deriveSlug,
30
+ hasSecretContent,
31
+ redactSecretContent,
32
+ validateScalarText,
33
+ walkNonSymlinkFiles,
34
+ } from "./path-safety.mjs";
35
+ import { discoverSkills, scoreSkillForContext } from "./skills.mjs";
36
+ import { draftSkillFromExperience } from "./skills-lifecycle.mjs";
37
+ import {
38
+ assertSafeAncestorChain,
39
+ assertSafeDirNonSymlink,
40
+ removeDirSafe,
41
+ renameSyncRetry,
42
+ validateAndLintSkillStaging,
43
+ validateSkillSlugName,
44
+ } from "./skills-history.mjs";
45
+
46
+ const __filename = fileURLToPath(import.meta.url);
47
+ const __dirname = path.dirname(__filename);
48
+ const DEFAULT_HARNESS_DIR = path.resolve(__dirname, "..");
49
+
50
+ const MAX_READ_BYTES = 64 * 1024;
51
+ const NODE_DEP_STACKS = [
52
+ ["typescript", "typescript"],
53
+ ["next", "nextjs"],
54
+ ["react", "react"],
55
+ ["vue", "vue"],
56
+ ["nuxt", "nuxt"],
57
+ ["express", "express"],
58
+ ["fastify", "fastify"],
59
+ ["prisma", "prisma"],
60
+ ["@prisma/client", "prisma"],
61
+ ["drizzle-orm", "drizzle"],
62
+ ["drizzle-kit", "drizzle"],
63
+ ["pg", "postgres"],
64
+ ["postgres", "postgres"],
65
+ ["playwright", "playwright"],
66
+ ["@playwright/test", "playwright"],
67
+ ["cypress", "cypress"],
68
+ ["vitest", "vitest"],
69
+ ["jest", "jest"],
70
+ ["stripe", "stripe"],
71
+ ["tailwindcss", "tailwind"],
72
+ ];
73
+ const SCRIPT_PRIORITY = ["test", "lint", "typecheck", "build", "eval", "check", "verify"];
74
+
75
+ function readSmallNonSymlinkText(projectDir, relPath, maxBytes = MAX_READ_BYTES) {
76
+ if (typeof relPath !== "string" || relPath.trim().length === 0) {
77
+ return null;
78
+ }
79
+ let resolved;
80
+ try {
81
+ resolved = assertSafeWithinRoot(projectDir, relPath);
82
+ } catch {
83
+ return null;
84
+ }
85
+ try {
86
+ const st = fs.lstatSync(resolved);
87
+ if (st.isSymbolicLink() || !st.isFile() || st.size > maxBytes) {
88
+ return null;
89
+ }
90
+ return fs.readFileSync(resolved, "utf8");
91
+ } catch {
92
+ return null;
93
+ }
94
+ }
95
+
96
+ function hasSafeSubdir(projectDir, relPath) {
97
+ try {
98
+ const resolved = assertSafeWithinRoot(projectDir, relPath);
99
+ const st = fs.lstatSync(resolved);
100
+ return !st.isSymbolicLink() && st.isDirectory();
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ function extractMarkdownHeadings(text, maxHeadings = 12, maxLevel = 3) {
107
+ if (typeof text !== "string" || text.length === 0) {
108
+ return [];
109
+ }
110
+ const lines = text.split(/\r?\n/);
111
+ let idx = 0;
112
+ if (lines[0] && lines[0].trim() === "---") {
113
+ const closingIdx = lines.findIndex((line, i) => i > 0 && line.trim() === "---");
114
+ if (closingIdx !== -1) {
115
+ idx = closingIdx + 1;
116
+ }
117
+ }
118
+ const headings = [];
119
+ let inFence = false;
120
+ const headingRe = new RegExp(`^#{1,${maxLevel}}\\s+(.+?)\\s*#*\\s*$`);
121
+ for (; idx < lines.length && headings.length < maxHeadings; idx += 1) {
122
+ const trimmed = lines[idx].trim();
123
+ if (/^(?:`{3,}|~{3,})/.test(trimmed)) {
124
+ inFence = !inFence;
125
+ continue;
126
+ }
127
+ if (inFence) continue;
128
+ const match = headingRe.exec(trimmed);
129
+ if (match && match[1]) {
130
+ const cleaned = redactSecretContent(match[1].trim());
131
+ if (cleaned && !hasSecretContent(cleaned)) {
132
+ headings.push(cleaned);
133
+ }
134
+ }
135
+ }
136
+ return headings;
137
+ }
138
+
139
+ function extractConstraintBullets(constraintsText, maxBullets = 8) {
140
+ if (typeof constraintsText !== "string" || constraintsText.length === 0) {
141
+ return [];
142
+ }
143
+ const lines = constraintsText.split(/\r?\n/);
144
+ const bullets = [];
145
+ let inFence = false;
146
+ for (const line of lines) {
147
+ const trimmed = line.trim();
148
+ if (/^(?:`{3,}|~{3,})/.test(trimmed)) {
149
+ inFence = !inFence;
150
+ continue;
151
+ }
152
+ if (inFence) continue;
153
+ const match = /^[-*]\s+(.+)$/.exec(trimmed);
154
+ if (!match) continue;
155
+ const body = match[1].trim();
156
+ if (body.length < 12 || /\{\{[^}]+\}\}/.test(body)) continue;
157
+ if (hasSecretContent(body)) continue;
158
+ const cleaned = redactSecretContent(body);
159
+ if (!cleaned.startsWith("-")) {
160
+ bullets.push(cleaned);
161
+ }
162
+ if (bullets.length >= maxBullets) break;
163
+ }
164
+ return bullets;
165
+ }
166
+
167
+ function detectStacksAndCommands(projectDir, manifest, overviewText, constraintsText) {
168
+ const stacks = [];
169
+ const stackSet = new Set();
170
+ const commands = [];
171
+ const commandSet = new Set();
172
+
173
+ const addStack = (name) => {
174
+ const clean = String(name || "").trim().toLowerCase();
175
+ if (clean && !stackSet.has(clean)) {
176
+ stackSet.add(clean);
177
+ stacks.push(clean);
178
+ }
179
+ };
180
+ const addCommand = (cmd, source) => {
181
+ const clean = typeof cmd === "string" ? cmd.trim() : "";
182
+ if (!clean || hasSecretContent(clean) || commandSet.has(clean)) return;
183
+ commandSet.add(clean);
184
+ commands.push({ command: redactSecretContent(clean), source });
185
+ };
186
+
187
+ if (typeof manifest?.profile === "string" && manifest.profile.trim()) {
188
+ addStack(manifest.profile.trim());
189
+ }
190
+
191
+ const pkgRaw = readSmallNonSymlinkText(projectDir, "package.json");
192
+ if (pkgRaw) {
193
+ try {
194
+ const pkg = JSON.parse(pkgRaw);
195
+ addStack("node");
196
+ const allDeps = {
197
+ ...(pkg && typeof pkg.dependencies === "object" ? pkg.dependencies : {}),
198
+ ...(pkg && typeof pkg.devDependencies === "object" ? pkg.devDependencies : {}),
199
+ };
200
+ for (const [dep, stackName] of NODE_DEP_STACKS) {
201
+ if (Object.hasOwn(allDeps, dep)) {
202
+ addStack(stackName);
203
+ }
204
+ }
205
+ const scripts = pkg && typeof pkg.scripts === "object" ? pkg.scripts : {};
206
+ for (const key of SCRIPT_PRIORITY) {
207
+ const val = scripts[key];
208
+ if (typeof val !== "string" || val.trim().length === 0) continue;
209
+ if (/no test specified/i.test(val) || hasSecretContent(val)) continue;
210
+ addCommand(key === "test" ? "npm test" : `npm run ${key}`, "package.json");
211
+ }
212
+ } catch {
213
+ // Ignore malformed package.json safely
214
+ }
215
+ }
216
+
217
+ const pyprojectText = readSmallNonSymlinkText(projectDir, "pyproject.toml");
218
+ const reqText = readSmallNonSymlinkText(projectDir, "requirements.txt");
219
+ if (pyprojectText || reqText) {
220
+ addStack("python");
221
+ if (/\bpytest\b/i.test(`${pyprojectText || ""}\n${reqText || ""}`)) {
222
+ addCommand("pytest", pyprojectText ? "pyproject.toml" : "requirements.txt");
223
+ }
224
+ }
225
+
226
+ if (readSmallNonSymlinkText(projectDir, "go.mod")) {
227
+ addStack("go");
228
+ addCommand("go test ./...", "go.mod");
229
+ }
230
+
231
+ if (readSmallNonSymlinkText(projectDir, "Cargo.toml")) {
232
+ addStack("rust");
233
+ addCommand("cargo test", "Cargo.toml");
234
+ }
235
+
236
+ if (
237
+ readSmallNonSymlinkText(projectDir, "Dockerfile") ||
238
+ readSmallNonSymlinkText(projectDir, "docker-compose.yml") ||
239
+ readSmallNonSymlinkText(projectDir, "compose.yaml")
240
+ ) {
241
+ addStack("docker");
242
+ }
243
+
244
+ if (hasSafeSubdir(projectDir, ".github/workflows")) {
245
+ const wfRoot = assertSafeWithinRoot(projectDir, ".github/workflows");
246
+ const wfFiles = walkNonSymlinkFiles(projectDir, wfRoot, (p) => /\.ya?ml$/i.test(p));
247
+ if (wfFiles.length > 0) {
248
+ addStack("github-actions");
249
+ addStack("ci");
250
+ }
251
+ }
252
+
253
+ const n8nSignalText = [manifest?.description || "", overviewText || "", constraintsText || ""].join("\n");
254
+ if (/\bn8n\b/i.test(n8nSignalText) || hasSafeSubdir(projectDir, "adapters/n8n") || hasSafeSubdir(projectDir, "workflows")) {
255
+ addStack("n8n");
256
+ }
257
+
258
+ return { stacks, commands };
259
+ }
260
+
261
+ function scanEvidenceRecords(projectDir, evidenceDirRel) {
262
+ const verifiedEvidence = [];
263
+ const failedChecks = [];
264
+ const absDir = assertSafeWithinRoot(projectDir, evidenceDirRel);
265
+ if (!assertSafeDirNonSymlink(absDir, evidenceDirRel)) {
266
+ return { verifiedEvidence, failedChecks };
267
+ }
268
+ const files = walkNonSymlinkFiles(projectDir, absDir, (p) => /^EVID-\d{4}.*\.ya?ml$/i.test(path.basename(p)));
269
+ for (const filePath of files) {
270
+ const relPath = path.relative(projectDir, filePath).replace(/\\/g, "/");
271
+ const raw = readSmallNonSymlinkText(projectDir, relPath);
272
+ if (!raw) continue;
273
+ let parsed;
274
+ try {
275
+ parsed = parseYaml(raw, relPath);
276
+ } catch {
277
+ continue;
278
+ }
279
+ if (!parsed || typeof parsed !== "object" || parsed.is_example === true) continue;
280
+ const checks = Array.isArray(parsed.checks) ? parsed.checks : [];
281
+ const safeChecks = [];
282
+ for (const chk of checks) {
283
+ if (!chk || typeof chk !== "object") continue;
284
+ const cmd = typeof chk.command === "string" ? chk.command.trim() : "";
285
+ if (cmd && hasSecretContent(cmd)) continue;
286
+ const item = {
287
+ command: cmd ? redactSecretContent(cmd) : "",
288
+ exit_code: chk.exit_code,
289
+ result: chk.result || null,
290
+ };
291
+ safeChecks.push(item);
292
+ if (
293
+ item.result === "failed" ||
294
+ item.result === "blocked" ||
295
+ (item.exit_code !== undefined && item.exit_code !== null && Number.isFinite(Number(item.exit_code)) && Number(item.exit_code) !== 0)
296
+ ) {
297
+ failedChecks.push({
298
+ id: parsed.id || relPath,
299
+ title: parsed.title || parsed.id || relPath,
300
+ command: item.command,
301
+ exit_code: item.exit_code,
302
+ result: item.result,
303
+ });
304
+ }
305
+ }
306
+ const hasPassedCheck = safeChecks.some((c) => c.result === "passed");
307
+ const hasBadCheck = safeChecks.some((c) => c.result === "failed" || c.result === "blocked");
308
+ if (parsed.status === "verified" && parsed.id && hasPassedCheck && !hasBadCheck) {
309
+ verifiedEvidence.push({
310
+ id: String(parsed.id),
311
+ relPath,
312
+ title: typeof parsed.title === "string" ? redactSecretContent(parsed.title) : String(parsed.id),
313
+ tags: Array.isArray(parsed.tags) ? parsed.tags.map((t) => String(t)) : [],
314
+ relatedTasks: Array.isArray(parsed.related_tasks) ? parsed.related_tasks.map((t) => String(t)) : [],
315
+ taskId: typeof parsed.task_id === "string" ? parsed.task_id : null,
316
+ checks: safeChecks,
317
+ });
318
+ }
319
+ }
320
+ return { verifiedEvidence, failedChecks };
321
+ }
322
+
323
+ /**
324
+ * Extracts deterministic repository, goal, task, and verified evidence signals for skill discovery/advisory.
325
+ */
326
+ export function analyzeProjectSignals({
327
+ projectDir: rawProjectDir,
328
+ harnessDir: rawHarnessDir = DEFAULT_HARNESS_DIR,
329
+ taskId = null,
330
+ goal = null,
331
+ query = null,
332
+ } = {}) {
333
+ const harnessDir = path.resolve(rawHarnessDir || DEFAULT_HARNESS_DIR);
334
+ const loaded = loadProjectManifestAndState(rawProjectDir, harnessDir);
335
+ const { projectDir, manifest, state, projectPaths } = loaded;
336
+
337
+ const goalText = typeof goal === "string" && goal.trim() ? goal.trim() : typeof query === "string" && query.trim() ? query.trim() : null;
338
+ const constraintsText = readSmallNonSymlinkText(projectDir, projectPaths.constraints_doc) || "";
339
+ const overviewText = readSmallNonSymlinkText(projectDir, projectPaths.architecture) || "";
340
+
341
+ const { stacks, commands } = detectStacksAndCommands(projectDir, manifest, overviewText, constraintsText);
342
+ const constraintHeadings = extractMarkdownHeadings(constraintsText, 8, 3);
343
+ const constraintBullets = extractConstraintBullets(constraintsText, 8);
344
+ const overviewHeadings = extractMarkdownHeadings(overviewText, 12, 3);
345
+
346
+ let targetTask = null;
347
+ if (typeof taskId === "string" && taskId.trim().length > 0) {
348
+ targetTask = getTask({ projectDir, taskId: taskId.trim(), harnessDir });
349
+ } else if (!goalText && Array.isArray(state.active_tasks) && state.active_tasks.length > 0) {
350
+ try {
351
+ targetTask = getTask({ projectDir, taskId: state.active_tasks[0], harnessDir });
352
+ } catch {
353
+ targetTask = null;
354
+ }
355
+ }
356
+
357
+ const { verifiedEvidence, failedChecks } = scanEvidenceRecords(projectDir, projectPaths.evidence_dir);
358
+
359
+ const goalParts = [];
360
+ if (goalText) goalParts.push(goalText);
361
+ if (targetTask?.record) {
362
+ const r = targetTask.record;
363
+ goalParts.push(r.id || "", r.title || "", r.objective || "");
364
+ if (Array.isArray(r.scope_in)) goalParts.push(...r.scope_in);
365
+ if (Array.isArray(r.acceptance_criteria)) goalParts.push(...r.acceptance_criteria);
366
+ }
367
+ const goalKeywords = tokenizeKeywords(goalParts.join(" "));
368
+
369
+ const projectParts = [
370
+ ...stacks,
371
+ ...commands.map((c) => c.command),
372
+ ...constraintHeadings,
373
+ ...constraintBullets,
374
+ ...overviewHeadings,
375
+ ...verifiedEvidence.slice(0, 12).flatMap((ev) => [ev.title, ...ev.tags, ...ev.checks.map((c) => c.command)]),
376
+ ];
377
+ const projectKeywords = tokenizeKeywords(projectParts.join(" "));
378
+
379
+ return {
380
+ projectDir,
381
+ harnessDir,
382
+ manifest,
383
+ state,
384
+ projectPaths,
385
+ goal: goalText,
386
+ taskId: targetTask?.id || null,
387
+ targetTask,
388
+ stacks,
389
+ commands,
390
+ constraintHeadings,
391
+ constraintBullets,
392
+ overviewHeadings,
393
+ verifiedEvidence,
394
+ failedChecks,
395
+ goalKeywords,
396
+ projectKeywords,
397
+ };
398
+ }
399
+
400
+ function scoreAndRankSkills(discovery, signals, limit) {
401
+ const validSkills = (discovery.activeSkills || []).filter((s) => s.valid && !s.blocked);
402
+ if (validSkills.length === 0) {
403
+ return [];
404
+ }
405
+
406
+ const combinedMetaDocs = validSkills.map((skill) => ({
407
+ id: skill.name,
408
+ terms: tokenizeTerms(
409
+ [
410
+ skill.name.replace(/-/g, " "),
411
+ ...(skill.tags || []),
412
+ ...(skill.triggers || []),
413
+ skill.frontmatter?.description || "",
414
+ ].join(" ")
415
+ ),
416
+ }));
417
+ const bodyDocs = validSkills.map((skill) => ({
418
+ id: skill.name,
419
+ terms: tokenizeTerms(skill.body || ""),
420
+ }));
421
+
422
+ const goalMetaBm25 = scoreBm25Documents(signals.goalKeywords, combinedMetaDocs);
423
+ const goalBodyBm25 = scoreBm25Documents(signals.goalKeywords, bodyDocs);
424
+ const projMetaBm25 = scoreBm25Documents(signals.projectKeywords, combinedMetaDocs);
425
+ const projBodyBm25 = scoreBm25Documents(signals.projectKeywords, bodyDocs);
426
+
427
+ const ranked = [];
428
+ for (const skill of validSkills) {
429
+ const skillMetaTokens = tokenizeKeywords(
430
+ [
431
+ skill.name.replace(/-/g, " "),
432
+ ...(skill.tags || []),
433
+ ...(skill.triggers || []),
434
+ skill.frontmatter?.description || "",
435
+ ].join(" ")
436
+ );
437
+ const skillAllTokens = new Set([...skillMetaTokens, ...tokenizeKeywords(skill.body || "")]);
438
+
439
+ const matchedGoalKeywords = [...signals.goalKeywords].filter((k) => skillAllTokens.has(k));
440
+ const matchedProjectKeywords = [...signals.projectKeywords].filter((k) => skillAllTokens.has(k));
441
+ const minProjectOverlap = signals.goalKeywords.size > 0 ? 2 : 1;
442
+ if (matchedGoalKeywords.length === 0 && matchedProjectKeywords.length < minProjectOverlap) {
443
+ continue;
444
+ }
445
+
446
+ const baseCtx = scoreSkillForContext(skill, {
447
+ queryKeywords: signals.goalKeywords.size > 0 ? signals.goalKeywords : signals.projectKeywords,
448
+ pinnedSet: new Set(),
449
+ });
450
+ const bm25Score =
451
+ (goalMetaBm25.get(skill.name) ?? 0) * 18 +
452
+ (goalBodyBm25.get(skill.name) ?? 0) * 8 +
453
+ (projMetaBm25.get(skill.name) ?? 0) * 6 +
454
+ (projBodyBm25.get(skill.name) ?? 0) * 2;
455
+ const score = Math.round((baseCtx.score * 0.25 + bm25Score) * 1e6) / 1e6;
456
+
457
+ const reasons = [];
458
+ if (matchedGoalKeywords.length > 0) {
459
+ reasons.push(`matched goal keywords: ${matchedGoalKeywords.slice(0, 6).join(", ")}`);
460
+ }
461
+ if (matchedProjectKeywords.length > 0) {
462
+ reasons.push(`matched project signals: ${matchedProjectKeywords.slice(0, 6).join(", ")}`);
463
+ }
464
+
465
+ ranked.push({
466
+ name: skill.name,
467
+ source: skill.source,
468
+ trustTier: skill.trustTier,
469
+ displayPath: skill.displayPath,
470
+ description: skill.frontmatter?.description || "",
471
+ score,
472
+ matchedGoalKeywords,
473
+ matchedProjectKeywords,
474
+ reasons,
475
+ command: `geloforge context --skills --skill ${skill.name}`,
476
+ });
477
+ }
478
+
479
+ ranked.sort((a, b) => {
480
+ if (b.score !== a.score) return b.score - a.score;
481
+ return a.name.localeCompare(b.name);
482
+ });
483
+ return ranked.slice(0, limit);
484
+ }
485
+
486
+ function isTopicCoveredBySkills(topicKeywords, validSkills) {
487
+ if (!topicKeywords || topicKeywords.size === 0) return false;
488
+ const requiredHits = topicKeywords.size <= 2 ? 1 : 2;
489
+ for (const skill of validSkills) {
490
+ const metaTokens = tokenizeKeywords(
491
+ [
492
+ skill.name.replace(/-/g, " "),
493
+ ...(skill.tags || []),
494
+ ...(skill.triggers || []),
495
+ skill.frontmatter?.description || "",
496
+ ].join(" ")
497
+ );
498
+ let hits = 0;
499
+ for (const kw of topicKeywords) {
500
+ if (metaTokens.has(kw)) hits += 1;
501
+ }
502
+ if (hits >= requiredHits) {
503
+ return true;
504
+ }
505
+ }
506
+ return false;
507
+ }
508
+
509
+ function slugifySkillName(rawText, fallback = "project-workflow") {
510
+ const cleaned = String(rawText || "")
511
+ .toLowerCase()
512
+ .replace(/[^a-z0-9]+/g, "-")
513
+ .replace(/-+/g, "-")
514
+ .replace(/^-+|-+$/g, "")
515
+ .slice(0, 48)
516
+ .replace(/-+$/g, "");
517
+ const base = cleaned.length >= 2 ? cleaned : deriveSlug(fallback);
518
+ return validateSkillSlugName(base.length >= 2 ? base : fallback, fallback);
519
+ }
520
+
521
+ function uniqueCommandsFromEvidence(evList) {
522
+ const out = [];
523
+ const seen = new Set();
524
+ for (const ev of evList) {
525
+ for (const chk of ev.checks || []) {
526
+ if (chk.command && !seen.has(chk.command)) {
527
+ seen.add(chk.command);
528
+ out.push(chk.command);
529
+ }
530
+ }
531
+ }
532
+ return out;
533
+ }
534
+
535
+ function detectSkillGaps(signals, discovery) {
536
+ const validActive = (discovery.activeSkills || []).filter((s) => s.valid && !s.blocked);
537
+ const activeNames = new Set((discovery.activeSkills || []).map((s) => s.name));
538
+ const quarantinedNames = new Set((discovery.quarantinedSkills || []).map((s) => s.name));
539
+ const gaps = [];
540
+ const seenKinds = new Set();
541
+
542
+ const evScored = signals.verifiedEvidence.map((ev) => {
543
+ const evTokens = tokenizeKeywords([ev.title, ...ev.tags, ...ev.checks.map((c) => c.command)].join(" "));
544
+ let goalHits = 0;
545
+ for (const kw of signals.goalKeywords) {
546
+ if (evTokens.has(kw)) goalHits += 1;
547
+ }
548
+ const taskLinked = Boolean(
549
+ signals.taskId && (ev.taskId === signals.taskId || ev.relatedTasks.includes(signals.taskId))
550
+ );
551
+ return { ev, evTokens, goalHits, taskLinked };
552
+ });
553
+
554
+ const goalMatchedEv = evScored
555
+ .filter((item) => item.taskLinked || item.goalHits > 0)
556
+ .sort((a, b) => Number(b.taskLinked) - Number(a.taskLinked) || b.goalHits - a.goalHits || b.ev.id.localeCompare(a.ev.id));
557
+
558
+ // Gap 1: Goal or active task with verified matching evidence
559
+ if (goalMatchedEv.length > 0) {
560
+ const chosen = goalMatchedEv.slice(0, 3).map((x) => x.ev);
561
+ const topicKeywords = new Set(goalMatchedEv.slice(0, 3).flatMap((x) => [...x.evTokens]));
562
+ for (const kw of signals.goalKeywords) topicKeywords.add(kw);
563
+
564
+ if (!isTopicCoveredBySkills(topicKeywords, validActive)) {
565
+ const titleSource = signals.goal || signals.targetTask?.record?.title || chosen[0].title;
566
+ const suggestedName = slugifySkillName(titleSource, "verified-workflow");
567
+ const commands = uniqueCommandsFromEvidence(chosen);
568
+ gaps.push({
569
+ kind: "evidence_backed_workflow",
570
+ suggestedName,
571
+ title: titleSource,
572
+ reason: `Verified evidence (${chosen.map((e) => e.id).join(", ")}) backs this workflow, and no active skill covers it.`,
573
+ evidenceIds: chosen.map((e) => e.id),
574
+ commands,
575
+ constraints: signals.constraintBullets.slice(0, 3),
576
+ promotableAfterReview: true,
577
+ existingQuarantinedDraft: quarantinedNames.has(suggestedName),
578
+ scaffoldable: !activeNames.has(suggestedName) && !quarantinedNames.has(suggestedName),
579
+ recommendedCommand: `geloforge skills draft --from-evidence ${chosen.map((e) => e.id).join(" --from-evidence ")} --name ${suggestedName}`,
580
+ });
581
+ seenKinds.add("evidence_backed_workflow");
582
+ }
583
+ } else if (signals.goalKeywords.size > 0 && !isTopicCoveredBySkills(signals.goalKeywords, validActive)) {
584
+ // Gap 2: Explicit goal or active task without verified evidence yet
585
+ const goalLabel = signals.goal || signals.targetTask?.record?.title || "project-goal";
586
+ const suggestedName = slugifySkillName(goalLabel, "goal-workflow");
587
+ gaps.push({
588
+ kind: "goal_workflow",
589
+ suggestedName,
590
+ title: goalLabel,
591
+ reason: `No active skill covers the current goal/task ("${goalLabel}"). Stage a quarantined repo-grounded draft and capture verification evidence before promotion.`,
592
+ evidenceIds: [],
593
+ commands: signals.commands.map((c) => c.command),
594
+ constraints: signals.constraintBullets.slice(0, 4),
595
+ promotableAfterReview: false,
596
+ existingQuarantinedDraft: quarantinedNames.has(suggestedName),
597
+ scaffoldable: !activeNames.has(suggestedName) && !quarantinedNames.has(suggestedName),
598
+ recommendedCommand: signals.goal
599
+ ? `geloforge skills suggest --goal ${JSON.stringify(signals.goal)} --scaffold-draft`
600
+ : `geloforge skills suggest --scaffold-draft`,
601
+ });
602
+ seenKinds.add("goal_workflow");
603
+ }
604
+
605
+ // Secondary Gap: Uncovered verified evidence elsewhere in the project
606
+ if (gaps.length < 3 && !seenKinds.has("evidence_backed_workflow") && signals.verifiedEvidence.length > 0) {
607
+ const withCommands = signals.verifiedEvidence.filter((e) => e.checks.some((c) => c.command));
608
+ const pool = withCommands.length > 0 ? withCommands : signals.verifiedEvidence;
609
+ const chosen = pool.slice(0, 3);
610
+ const evTopic = tokenizeKeywords(chosen.flatMap((e) => [e.title, ...e.tags]).join(" "));
611
+ if (!isTopicCoveredBySkills(evTopic, validActive)) {
612
+ const suggestedName = slugifySkillName(chosen[0].title, "verified-project-checks");
613
+ gaps.push({
614
+ kind: "evidence_backed_workflow",
615
+ suggestedName,
616
+ title: chosen[0].title,
617
+ reason: `Verified evidence (${chosen.map((e) => e.id).join(", ")}) records reusable checks not yet captured in an active skill.`,
618
+ evidenceIds: chosen.map((e) => e.id),
619
+ commands: uniqueCommandsFromEvidence(chosen),
620
+ constraints: signals.constraintBullets.slice(0, 3),
621
+ promotableAfterReview: true,
622
+ existingQuarantinedDraft: quarantinedNames.has(suggestedName),
623
+ scaffoldable: !activeNames.has(suggestedName) && !quarantinedNames.has(suggestedName),
624
+ recommendedCommand: `geloforge skills draft --from-evidence ${chosen.map((e) => e.id).join(" --from-evidence ")} --name ${suggestedName}`,
625
+ });
626
+ seenKinds.add("evidence_backed_workflow");
627
+ }
628
+ }
629
+
630
+ // Gap 3: Day-1 baseline workflow when no active skills exist and repo has concrete commands or constraints
631
+ if (
632
+ validActive.length === 0 &&
633
+ gaps.length === 0 &&
634
+ (signals.commands.length > 0 || signals.constraintBullets.length > 0)
635
+ ) {
636
+ const projectName = signals.manifest?.name || path.basename(signals.projectDir);
637
+ const suggestedName = slugifySkillName(`${projectName}-verification`, "project-verification");
638
+ gaps.push({
639
+ kind: "repo_baseline_workflow",
640
+ suggestedName,
641
+ title: `${projectName} Verification Workflow`,
642
+ reason:
643
+ "No active skills are configured, and concrete verification commands or constraints were detected in this repository.",
644
+ evidenceIds: [],
645
+ commands: signals.commands.map((c) => c.command),
646
+ constraints: signals.constraintBullets.slice(0, 5),
647
+ promotableAfterReview: false,
648
+ existingQuarantinedDraft: quarantinedNames.has(suggestedName),
649
+ scaffoldable: !activeNames.has(suggestedName) && !quarantinedNames.has(suggestedName),
650
+ recommendedCommand: "geloforge skills suggest --scaffold-draft",
651
+ });
652
+ }
653
+
654
+ return gaps.slice(0, 3);
655
+ }
656
+
657
+ function buildRepoScaffoldMarkdown({ skillName, title, description, gap, signals, tags, triggers }) {
658
+ const mergedTags = Array.from(new Set(["repo-scaffold", ...signals.stacks.slice(0, 4), ...tags])).join(", ");
659
+ const mergedTriggers = Array.from(
660
+ new Set(triggers.length > 0 ? triggers : [skillName.replace(/-/g, " "), ...signals.stacks.slice(0, 3)])
661
+ ).join(", ");
662
+
663
+ const frontmatterObj = {
664
+ name: skillName,
665
+ description,
666
+ license: "MIT",
667
+ metadata: {
668
+ geloforge_origin: "repo_scaffold",
669
+ geloforge_promotion_status: "requires_verified_evidence",
670
+ geloforge_tags: mergedTags,
671
+ geloforge_triggers: mergedTriggers,
672
+ },
673
+ };
674
+
675
+ const groundingLines = [
676
+ `- **Detected Stack:** ${signals.stacks.join(", ") || "none detected"}`,
677
+ ...(gap.commands.length > 0
678
+ ? [`- **Detected Repository Commands:** ${gap.commands.map((c) => `\`${c}\``).join(", ")}`]
679
+ : ["- **Detected Repository Commands:** (none detected in package/build manifests)"]),
680
+ ...(signals.constraintBullets.length > 0
681
+ ? signals.constraintBullets.slice(0, 4).map((b) => `- **Project Constraint:** ${b}`)
682
+ : ["- **Project Constraint:** Follow A0 approval boundaries and record evidence before closure."]),
683
+ ...(signals.failedChecks.length > 0
684
+ ? [
685
+ `- **Recent Failed Checks Seen in History:** ${signals.failedChecks
686
+ .slice(0, 2)
687
+ .map((f) => `${f.id} (\`${f.command || "check"}\` exit=${f.exit_code})`)
688
+ .join(", ")}`,
689
+ ]
690
+ : []),
691
+ ];
692
+
693
+ const procSteps = [];
694
+ if (signals.goal) {
695
+ procSteps.push(`Review goal scope and repository constraints for: ${redactSecretContent(signals.goal)}.`);
696
+ } else {
697
+ procSteps.push("Review repository constraints and active task scope before modifying code.");
698
+ }
699
+ if (gap.commands.length > 0) {
700
+ for (const cmd of gap.commands.slice(0, 4)) {
701
+ procSteps.push(`Run verification command \`${cmd}\` via \`geloforge evidence capture\` and inspect output.`);
702
+ }
703
+ } else {
704
+ procSteps.push("Capture command-backed verification via `geloforge evidence capture --task <TASK-NNNN> -- <command>`.");
705
+ }
706
+ procSteps.push(
707
+ `After capturing verified EVID-NNNN, regenerate an evidence-backed draft with \`geloforge skills draft --from-evidence <EVID-NNNN> --name ${skillName}\` before requesting human promotion.`
708
+ );
709
+
710
+ const mdLines = [
711
+ "---",
712
+ serializeYaml(frontmatterObj).trimEnd(),
713
+ "---",
714
+ "",
715
+ `# ${title}`,
716
+ "",
717
+ "> **Quarantined Scaffold Draft:** Generated solely from local repository signals and goal context without verified EVID-* provenance. Human review and verified evidence are required before any promotion.",
718
+ "",
719
+ "## When to Use",
720
+ "",
721
+ `Use this skill when working on ${title.toLowerCase()} where the grounded project commands and constraints below apply.`,
722
+ "",
723
+ "## Detected Project Grounding (Factual Repo Signals)",
724
+ "",
725
+ ...groundingLines,
726
+ "",
727
+ "## Suggested Procedure (Unverified Draft — Review & Capture Evidence)",
728
+ "",
729
+ ...procSteps.map((step, idx) => `${idx + 1}. ${step}`),
730
+ "",
731
+ ];
732
+
733
+ return redactSecretContent(mdLines.join("\n"));
734
+ }
735
+
736
+ function scaffoldFromGap({ targetGap, signals, options }) {
737
+ const createdAt = validateCreatedAt(options.createdAt);
738
+ const skillName = validateSkillSlugName(options.skillName || targetGap.suggestedName, targetGap.suggestedName);
739
+
740
+ const activeDir = assertSafeWithinRoot(signals.projectDir, `.agents/skills/${skillName}`);
741
+ if (fs.existsSync(activeDir)) {
742
+ throw new Error(
743
+ `Active skill "${skillName}" already exists at .agents/skills/${skillName}. Choose a different --name or use "geloforge skills propose-update ${skillName}".`
744
+ );
745
+ }
746
+
747
+ const proposalsSkillsRel = `${signals.projectPaths.proposals_dir}/skills`;
748
+ const proposalRel = `${proposalsSkillsRel}/${skillName}`;
749
+ const proposalDir = assertSafeWithinRoot(signals.projectDir, proposalRel);
750
+ if (fs.existsSync(proposalDir)) {
751
+ throw new Error(`Quarantined draft "${skillName}" already exists at ${proposalRel}. Review or remove it before scaffolding again.`);
752
+ }
753
+
754
+ const extraTags = Array.isArray(options.tags) ? options.tags : signals.stacks.slice(0, 4);
755
+ const extraTriggers = Array.isArray(options.triggers) ? options.triggers : [];
756
+ const rawTitle = validateScalarText(
757
+ "title",
758
+ String(options.title || targetGap.title || skillName).replace(/\s+/g, " ").trim()
759
+ );
760
+ const title = redactSecretContent(rawTitle);
761
+
762
+ if (targetGap.evidenceIds.length > 0) {
763
+ const steps = [];
764
+ for (const cmd of targetGap.commands.slice(0, 4)) {
765
+ steps.push(`Run verified project check \`${cmd}\` with \`geloforge evidence capture\`.`);
766
+ }
767
+ for (const cBullet of targetGap.constraints.slice(0, 2)) {
768
+ steps.push(`Enforce project constraint: ${cBullet}`);
769
+ }
770
+ const res = draftSkillFromExperience({
771
+ projectDir: signals.projectDir,
772
+ harnessDir: signals.harnessDir,
773
+ evidenceIds: targetGap.evidenceIds,
774
+ skillName,
775
+ title,
776
+ steps: steps.length > 0 ? steps : undefined,
777
+ tags: extraTags,
778
+ triggers: extraTriggers,
779
+ createdAt,
780
+ dryRun: Boolean(options.dryRun),
781
+ });
782
+ return {
783
+ mode: "evidence_draft",
784
+ quarantined: true,
785
+ promotable: true,
786
+ gapKind: targetGap.kind,
787
+ ...res,
788
+ };
789
+ }
790
+
791
+ // Day-1 repo/goal scaffold (quarantined ONLY; intentionally lacks .proposals/<name>.yaml so promotion stays fail-closed)
792
+ const rawDesc =
793
+ options.description ||
794
+ `Apply verified project checks and constraints for ${title} grounded in local repository signals (${signals.stacks.join(", ") || "project rules"}).`;
795
+ let description = redactSecretContent(validateScalarText("description", rawDesc));
796
+ if (description.length < 20) {
797
+ description = `${description} — quarantined repository workflow draft.`;
798
+ }
799
+ if (description.length > 1024) {
800
+ description = `${description.slice(0, 1021)}...`;
801
+ }
802
+ if (hasSecretContent(title) || hasSecretContent(description)) {
803
+ throw new Error("Refusing scaffold metadata containing credential-like content.");
804
+ }
805
+
806
+ const markdown = buildRepoScaffoldMarkdown({
807
+ skillName,
808
+ title,
809
+ description,
810
+ gap: targetGap,
811
+ signals,
812
+ tags: extraTags,
813
+ triggers: extraTriggers,
814
+ });
815
+ if (hasSecretContent(markdown)) {
816
+ throw new Error("Refusing scaffold draft because generated SKILL.md triggered secret-content detection.");
817
+ }
818
+
819
+ const skillsProposalsRoot = assertSafeWithinRoot(signals.projectDir, proposalsSkillsRel);
820
+ assertSafeAncestorChain(skillsProposalsRoot, signals.projectDir, proposalsSkillsRel);
821
+ if (fs.existsSync(skillsProposalsRoot)) {
822
+ assertSafeDirNonSymlink(skillsProposalsRoot, proposalsSkillsRel);
823
+ } else if (!options.dryRun) {
824
+ fs.mkdirSync(skillsProposalsRoot, { recursive: true });
825
+ }
826
+
827
+ const stageParent = options.dryRun ? os.tmpdir() : skillsProposalsRoot;
828
+ const stageDir = path.join(stageParent, `.geloforge-stage-${crypto.randomBytes(6).toString("hex")}`);
829
+ try {
830
+ fs.mkdirSync(stageDir, { recursive: true });
831
+ fs.writeFileSync(path.join(stageDir, "SKILL.md"), markdown, { encoding: "utf8", flag: "wx" });
832
+ const verified = validateAndLintSkillStaging({
833
+ stageDir,
834
+ skillName,
835
+ displayRoot: proposalsSkillsRel,
836
+ });
837
+
838
+ const nextSteps = [
839
+ `Inspect draft safely: geloforge skills show ${skillName} --include-drafts`,
840
+ `Capture real verification evidence: geloforge evidence capture --task <TASK-NNNN> -- ${targetGap.commands[0] || "<command>"}`,
841
+ `Replace unverified scaffold with an evidence-backed proposal via: geloforge skills draft --from-evidence <EVID-NNNN> --name ${skillName}`,
842
+ ];
843
+
844
+ if (options.dryRun) {
845
+ return {
846
+ mode: "repo_scaffold_quarantined",
847
+ dryRun: true,
848
+ quarantined: true,
849
+ promotable: false,
850
+ gapKind: targetGap.kind,
851
+ skillName,
852
+ proposalDir: proposalRel,
853
+ candidateDigest: verified.digestInfo.digest,
854
+ lintPassed: true,
855
+ markdown,
856
+ nextSteps,
857
+ };
858
+ }
859
+
860
+ assertSafeAncestorChain(proposalDir, signals.projectDir, proposalRel);
861
+ renameSyncRetry(stageDir, proposalDir);
862
+
863
+ return {
864
+ mode: "repo_scaffold_quarantined",
865
+ dryRun: false,
866
+ quarantined: true,
867
+ promotable: false,
868
+ gapKind: targetGap.kind,
869
+ skillName,
870
+ proposalDir: proposalRel,
871
+ candidateDigest: verified.digestInfo.digest,
872
+ lintPassed: true,
873
+ nextSteps,
874
+ };
875
+ } finally {
876
+ removeDirSafe(stageDir);
877
+ }
878
+ }
879
+
880
+ /**
881
+ * Recommends relevant active skills and detects concrete evidence/repo-grounded gaps.
882
+ * Optionally stages a strictly quarantined draft skill when `scaffoldDraft: true`.
883
+ */
884
+ export function suggestProjectSkills(options = {}) {
885
+ const limitRaw = options.limit !== undefined && options.limit !== null ? Number(options.limit) : 5;
886
+ if (!Number.isInteger(limitRaw) || limitRaw < 1 || limitRaw > 20) {
887
+ throw new Error("--limit must be an integer between 1 and 20.");
888
+ }
889
+ const scaffoldDraft = Boolean(options.scaffoldDraft);
890
+ if (options.dryRun && !scaffoldDraft) {
891
+ throw new Error("--dry-run is only valid together with --scaffold-draft.");
892
+ }
893
+
894
+ const signals = analyzeProjectSignals({
895
+ projectDir: options.projectDir,
896
+ harnessDir: options.harnessDir,
897
+ taskId: options.taskId,
898
+ goal: options.goal,
899
+ query: options.query,
900
+ });
901
+
902
+ const discovery = discoverSkills({
903
+ projectDir: signals.projectDir,
904
+ globalSkillsDir: options.globalSkillsDir,
905
+ proposalsDir: signals.projectPaths.proposals_dir,
906
+ includeDrafts: Boolean(options.includeDrafts),
907
+ });
908
+
909
+ const recommendedSkills = scoreAndRankSkills(discovery, signals, limitRaw);
910
+ const skillGaps = detectSkillGaps(signals, discovery);
911
+
912
+ let scaffoldResult = null;
913
+ if (scaffoldDraft) {
914
+ const requestedName = options.skillName ? validateSkillSlugName(options.skillName) : null;
915
+ const candidateGap =
916
+ (requestedName ? skillGaps[0] : skillGaps.find((g) => g.scaffoldable)) || null;
917
+ if (!candidateGap) {
918
+ throw new Error(
919
+ "No grounded, un-scaffolded skill gap was detected for this project/goal. Capture verified EVID-NNNN or specify an explicit --goal and unused --name."
920
+ );
921
+ }
922
+ scaffoldResult = scaffoldFromGap({ targetGap: candidateGap, signals, options });
923
+ }
924
+
925
+ return {
926
+ projectDir: signals.projectDir,
927
+ projectId: signals.manifest?.project_id || null,
928
+ goal: signals.goal,
929
+ taskId: signals.taskId,
930
+ detectedSignals: {
931
+ stacks: signals.stacks,
932
+ commands: signals.commands,
933
+ constraintCount: signals.constraintBullets.length,
934
+ overviewHeadings: signals.overviewHeadings.slice(0, 6),
935
+ verifiedEvidenceIds: signals.verifiedEvidence.map((e) => e.id),
936
+ failedCheckCount: signals.failedChecks.length,
937
+ },
938
+ activeSkillCount: (discovery.activeSkills || []).length,
939
+ quarantinedDraftCount: (discovery.quarantinedSkills || []).length,
940
+ recommendedSkills,
941
+ skillGaps,
942
+ scaffoldResult,
943
+ };
944
+ }