@greenrenge/skills 0.1.0 → 0.3.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,1179 @@
1
+ /**
2
+ * Categorized catalog views, dependency tree planner, preflight renderer,
3
+ * host-fact / run-contract generators, and interactive onboarding CLI.
4
+ * Zero external dependencies — Node.js built-ins only.
5
+ */
6
+ import { spawnSync } from "node:child_process";
7
+ import { copyFileSync, existsSync, lstatSync, mkdirSync, symlinkSync, unlinkSync, writeFileSync } from "node:fs";
8
+ import { dirname, join, resolve } from "node:path";
9
+ import { createInterface } from "node:readline";
10
+ import {
11
+ collectToolsToProbe,
12
+ evaluateRequirements,
13
+ HOST_FACT_META,
14
+ probeHost,
15
+ TOOL_META,
16
+ } from "./probe.mjs";
17
+
18
+ const USE_COLOR = Boolean(process.stdout.isTTY && !process.env.NO_COLOR);
19
+
20
+ export const c = {
21
+ bold: (s) => (USE_COLOR ? `\x1b[1m${s}\x1b[0m` : s),
22
+ dim: (s) => (USE_COLOR ? `\x1b[2m${s}\x1b[0m` : s),
23
+ cyan: (s) => (USE_COLOR ? `\x1b[36m${s}\x1b[0m` : s),
24
+ green: (s) => (USE_COLOR ? `\x1b[32m${s}\x1b[0m` : s),
25
+ yellow: (s) => (USE_COLOR ? `\x1b[33m${s}\x1b[0m` : s),
26
+ red: (s) => (USE_COLOR ? `\x1b[31m${s}\x1b[0m` : s),
27
+ magenta: (s) => (USE_COLOR ? `\x1b[35m${s}\x1b[0m` : s),
28
+ };
29
+
30
+ export function orderedCategories(catalog) {
31
+ return Object.entries(catalog.categories ?? {}).sort(
32
+ (a, b) => (a[1].order ?? 999) - (b[1].order ?? 999),
33
+ );
34
+ }
35
+
36
+ export function skillBadges(skill) {
37
+ const badges = [];
38
+ const req = skill?.requires ?? {};
39
+ if (req.tools?.includes("ocr")) badges.push("[ocr CLI]");
40
+ if (req.hostFacts?.length) badges.push("[host facts]");
41
+ if (req.runContract) badges.push("[run contract]");
42
+ if (req.harness === "t3-code") badges.push("[T3]");
43
+ return badges;
44
+ }
45
+
46
+ /**
47
+ * Expand user-supplied bundle/skill/category names into a structured install plan.
48
+ */
49
+ export function expandPlan(inputs, catalog, { includeDeps = true } = {}) {
50
+ const requested = new Set();
51
+ const depOf = new Map(); // skill -> Set<parentSkill>
52
+ const ordered = [];
53
+ const visited = new Set();
54
+ const stack = new Set();
55
+
56
+ function addDepEdge(child, parent) {
57
+ if (!depOf.has(child)) depOf.set(child, new Set());
58
+ depOf.get(child).add(parent);
59
+ }
60
+
61
+ function visitSkill(name, parent = null) {
62
+ if (parent) addDepEdge(name, parent);
63
+ else requested.add(name);
64
+
65
+ if (visited.has(name)) return;
66
+ if (stack.has(name)) {
67
+ throw new Error(`Cycle detected while expanding "${name}"`);
68
+ }
69
+ const skill = catalog.skills[name];
70
+ if (!skill) {
71
+ const bundleNames = Object.keys(catalog.bundles).join(", ");
72
+ throw new Error(
73
+ `Unknown skill or bundle "${name}". Run "list" to inspect available bundles (${bundleNames}) and skills.`,
74
+ );
75
+ }
76
+
77
+ stack.add(name);
78
+ if (includeDeps && Array.isArray(skill.dependsOn)) {
79
+ for (const dep of skill.dependsOn) {
80
+ visitSkill(dep, name);
81
+ }
82
+ }
83
+ stack.delete(name);
84
+ visited.add(name);
85
+ ordered.push(name);
86
+ }
87
+
88
+ function visitInput(name, bStack = new Set()) {
89
+ if (catalog.bundles[name]) {
90
+ if (bStack.has(name)) {
91
+ throw new Error(`Cycle detected in bundle "${name}"`);
92
+ }
93
+ bStack.add(name);
94
+ for (const item of catalog.bundles[name].items) {
95
+ visitInput(item, bStack);
96
+ }
97
+ bStack.delete(name);
98
+ return;
99
+ }
100
+ visitSkill(name, null);
101
+ }
102
+
103
+ for (const input of inputs) {
104
+ visitInput(input);
105
+ }
106
+
107
+ const selectedSet = new Set(ordered);
108
+
109
+ // Group selected skills by ordered category
110
+ const catOrder = orderedCategories(catalog);
111
+ const byCategory = [];
112
+ const categorized = new Set();
113
+
114
+ for (const [catId, catMeta] of catOrder) {
115
+ const members = ordered.filter((name) => catalog.skills[name]?.category === catId);
116
+ if (members.length === 0) continue;
117
+ for (const m of members) categorized.add(m);
118
+ byCategory.push({
119
+ id: catId,
120
+ title: catMeta.title,
121
+ tagline: catMeta.tagline,
122
+ optIn: Boolean(catMeta.optIn),
123
+ skills: members,
124
+ });
125
+ }
126
+
127
+ const uncategorized = ordered.filter((name) => !categorized.has(name));
128
+ if (uncategorized.length > 0) {
129
+ byCategory.push({
130
+ id: "other",
131
+ title: "Other",
132
+ tagline: "",
133
+ optIn: false,
134
+ skills: uncategorized,
135
+ });
136
+ }
137
+
138
+ // Collect suggested optional skills not yet in selectedSet
139
+ const suggestedOptionalMap = new Map();
140
+ for (const name of ordered) {
141
+ for (const opt of catalog.skills[name]?.optionalSkills ?? []) {
142
+ if (selectedSet.has(opt) || !catalog.skills[opt]) continue;
143
+ if (!suggestedOptionalMap.has(opt)) suggestedOptionalMap.set(opt, []);
144
+ suggestedOptionalMap.get(opt).push(name);
145
+ }
146
+ }
147
+ const suggestedOptional = [...suggestedOptionalMap.entries()].map(([skill, forSkills]) => ({
148
+ skill,
149
+ forSkills,
150
+ }));
151
+
152
+ const transitiveOnly = ordered.filter((n) => !requested.has(n));
153
+ const bundledCount = ordered.filter((n) => catalog.skills[n]?.kind === "bundled").length;
154
+ const upstreamCount = ordered.length - bundledCount;
155
+
156
+ return {
157
+ ordered,
158
+ selectedSet,
159
+ requested,
160
+ transitiveOnly,
161
+ depOf,
162
+ byCategory,
163
+ suggestedOptional,
164
+ counts: {
165
+ total: ordered.length,
166
+ requested: requested.size,
167
+ transitive: transitiveOnly.length,
168
+ bundled: bundledCount,
169
+ upstream: upstreamCount,
170
+ },
171
+ };
172
+ }
173
+
174
+ export function renderCatalogList(catalog, pkgJson) {
175
+ const lines = [];
176
+ lines.push(`${c.bold(pkgJson.name)} ${c.dim(`v${pkgJson.version}`)}`);
177
+ lines.push("");
178
+
179
+ const cats = orderedCategories(catalog);
180
+ lines.push(c.bold("Categories (installable as bundles):"));
181
+ cats.forEach(([catId, cat], idx) => {
182
+ const bundle = catalog.bundles[catId];
183
+ const count = bundle ? expandPlan([catId], catalog, { includeDeps: false }).ordered.length : 0;
184
+ const optTag = cat.optIn ? ` ${c.yellow("[opt-in]")}` : "";
185
+ const num = c.cyan(`${idx + 1}.`);
186
+ lines.push(
187
+ ` ${num} ${c.bold(catId.padEnd(15))} ${c.dim(`(${String(count).padStart(2)} skills)`)} ${cat.title}${optTag}`,
188
+ );
189
+ lines.push(` ${c.dim(cat.tagline)}`);
190
+ });
191
+
192
+ const aliases = Object.entries(catalog.bundles).filter(([name, b]) => !b.category && !catalog.categories?.[name]);
193
+ if (aliases.length > 0) {
194
+ lines.push("");
195
+ lines.push(c.bold("Bundle aliases:"));
196
+ for (const [name, b] of aliases) {
197
+ const count = expandPlan([name], catalog, { includeDeps: true }).ordered.length;
198
+ lines.push(` ${c.bold(name.padEnd(18))} ${c.dim(`(${String(count).padStart(2)} skills)`)} ${b.description}`);
199
+ }
200
+ }
201
+
202
+ lines.push("");
203
+ lines.push(c.bold("Skills by category:"));
204
+ cats.forEach(([catId, cat], idx) => {
205
+ const members = Object.entries(catalog.skills).filter(([, s]) => s.category === catId);
206
+ if (members.length === 0) return;
207
+ const optTag = cat.optIn ? ` ${c.yellow("[opt-in]")}` : "";
208
+ lines.push("");
209
+ lines.push(` ${c.cyan(`${idx + 1}.`)} ${c.bold(cat.title)} ${c.dim(`(${catId})`)}${optTag}`);
210
+ for (const [name, skill] of members) {
211
+ const kindTag =
212
+ skill.kind === "bundled" ? c.green("[bundled] ") : c.magenta("[upstream]");
213
+ const badges = skillBadges(skill);
214
+ const badgeStr = badges.length ? ` ${c.yellow(badges.join(" "))}` : "";
215
+ lines.push(` ${c.bold(name.padEnd(26))} ${kindTag}${badgeStr}`);
216
+ lines.push(` ${c.dim(skill.description)}`);
217
+ if (skill.dependsOn?.length) {
218
+ lines.push(` ${c.dim(`└─ depends on: ${skill.dependsOn.join(", ")}`)}`);
219
+ }
220
+ }
221
+ });
222
+
223
+ const recipes = Object.entries(catalog.recipes ?? {});
224
+ if (recipes.length > 0) {
225
+ lines.push("");
226
+ lines.push(c.bold("Dedicated recipes (custom CLI workflows with overlapping skills):"));
227
+ for (const [id, meta] of recipes) {
228
+ lines.push(` ${c.bold(c.cyan(id.padEnd(18)))} ${meta.title}`);
229
+ lines.push(` ${c.dim(meta.description)}`);
230
+ lines.push(` ${c.dim(`└─ run: npx ${pkgJson.name} setup ${id} (or: npx ${pkgJson.name} ${id})`)}`);
231
+ }
232
+ }
233
+
234
+ lines.push("");
235
+ lines.push(
236
+ c.dim(`Tip: run "${pkgJson.name.startsWith("@") ? `npx ${pkgJson.name}` : pkgJson.name} onboard" for guided setup, "setup <recipe>" for workflows, or "install <category-or-skill>".`),
237
+ );
238
+ return lines.join("\n");
239
+ }
240
+
241
+ function renderCategoryTreeLines(group, plan, catalog) {
242
+ const lines = [];
243
+ const memberSet = new Set(group.skills);
244
+
245
+ // Build parent -> child map within the entire selected set
246
+ const childrenOf = (skillName) =>
247
+ (catalog.skills[skillName]?.dependsOn ?? []).filter((d) => plan.selectedSet.has(d));
248
+
249
+ // Skills in this category that are NOT depended on by another skill in the same category
250
+ const dependedWithinCat = new Set();
251
+ for (const name of group.skills) {
252
+ for (const dep of childrenOf(name)) {
253
+ if (memberSet.has(dep)) dependedWithinCat.add(dep);
254
+ }
255
+ }
256
+
257
+ const roots = group.skills.filter((name) => !dependedWithinCat.has(name));
258
+ // Fallback if every skill in category is in a mutual reference (shouldn't happen due to DAG check)
259
+ const displayRoots = roots.length > 0 ? roots : [...group.skills];
260
+
261
+ const printed = new Set();
262
+
263
+ function formatNode(name, isChild) {
264
+ const skill = catalog.skills[name];
265
+ const kind = skill.kind === "bundled" ? c.green("[bundled]") : c.magenta("[upstream]");
266
+ const origin = plan.requested.has(name)
267
+ ? c.dim("(requested)")
268
+ : isChild
269
+ ? c.cyan("(dep)")
270
+ : c.cyan(`(dep of ${[...(plan.depOf.get(name) ?? [])].join(", ")})`);
271
+ const badges = skillBadges(skill);
272
+ const badgeStr = badges.length ? ` ${c.yellow(badges.join(" "))}` : "";
273
+ return `${c.bold(name)} ${kind} ${origin}${badgeStr}`;
274
+ }
275
+
276
+ function printSubtree(name, prefix, isLast, isChild) {
277
+ const branch = isLast ? "└─ " : "├─ ";
278
+ if (printed.has(name)) {
279
+ lines.push(`${prefix}${branch}${c.dim(`${name} (already listed above)`)}`);
280
+ return;
281
+ }
282
+ printed.add(name);
283
+ lines.push(`${prefix}${branch}${formatNode(name, isChild)}`);
284
+
285
+ const kids = childrenOf(name);
286
+ const childPrefix = prefix + (isLast ? " " : "│ ");
287
+ kids.forEach((kid, idx) => {
288
+ const kidLast = idx === kids.length - 1;
289
+ if (!memberSet.has(kid)) {
290
+ const kidCat = catalog.skills[kid]?.category ?? "other";
291
+ lines.push(`${childPrefix}${kidLast ? "└─ " : "├─ "}${c.dim(`${kid} (in category: ${kidCat})`)}`);
292
+ } else {
293
+ printSubtree(kid, childPrefix, kidLast, true);
294
+ }
295
+ });
296
+ }
297
+
298
+ displayRoots.forEach((rootName, idx) => {
299
+ printSubtree(rootName, " ", idx === displayRoots.length - 1, false);
300
+ });
301
+
302
+ // Safety net: print any member not reached from roots
303
+ const remaining = group.skills.filter((name) => !printed.has(name));
304
+ remaining.forEach((name, idx) => {
305
+ printSubtree(name, " ", idx === remaining.length - 1, false);
306
+ });
307
+
308
+ return lines;
309
+ }
310
+
311
+ export function renderInstallPlan(plan, catalog, { scope, targets, root } = {}) {
312
+ const lines = [];
313
+ const catCount = plan.byCategory.length;
314
+ lines.push(
315
+ c.bold(
316
+ `Install plan (${plan.counts.total} skill${plan.counts.total === 1 ? "" : "s"} across ${catCount} categor${catCount === 1 ? "y" : "ies"})`,
317
+ ),
318
+ );
319
+ if (scope || root) {
320
+ lines.push(` Scope: ${scope ?? "project"}${root ? ` ${c.dim(`(${root})`)}` : ""}`);
321
+ }
322
+ if (targets?.length) {
323
+ lines.push(` Targets: ${targets.join(", ")}`);
324
+ }
325
+
326
+ for (const group of plan.byCategory) {
327
+ const optTag = group.optIn ? ` ${c.yellow("[opt-in]")}` : "";
328
+ lines.push("");
329
+ lines.push(` ${c.bold(c.cyan(group.title))} ${c.dim(`(${group.id})`)}${optTag}`);
330
+ lines.push(...renderCategoryTreeLines(group, plan, catalog));
331
+ }
332
+
333
+ lines.push("");
334
+ const parts = [`${plan.counts.requested} requested`];
335
+ if (plan.counts.transitive > 0) {
336
+ parts.push(`${plan.counts.transitive} transitive dep${plan.counts.transitive === 1 ? "" : "s"}`);
337
+ }
338
+ lines.push(
339
+ ` ${c.dim(`Total: ${parts.join(" + ")} = ${plan.counts.total} (${plan.counts.bundled} bundled, ${plan.counts.upstream} upstream)`)}`,
340
+ );
341
+
342
+ if (plan.suggestedOptional.length > 0) {
343
+ const tips = plan.suggestedOptional
344
+ .map((s) => `${s.skill} (for ${s.forSkills.join(", ")})`)
345
+ .join("; ");
346
+ lines.push(` ${c.dim(`Optional companions available: ${tips}`)}`);
347
+ }
348
+
349
+ return lines.join("\n");
350
+ }
351
+
352
+ export function renderSkillOrBundleInfo(name, catalog, skillSourceFn) {
353
+ const lines = [];
354
+ if (catalog.bundles[name]) {
355
+ const b = catalog.bundles[name];
356
+ const plan = expandPlan([name], catalog, { includeDeps: true });
357
+ lines.push(`${c.bold("Bundle:")} ${name}`);
358
+ if (b.category && catalog.categories?.[b.category]) {
359
+ lines.push(`${c.bold("Category:")} ${catalog.categories[b.category].title} (${b.category})`);
360
+ }
361
+ lines.push(`${c.bold("Description:")} ${b.description}`);
362
+ lines.push(`${c.bold("Items:")} ${b.items.join(", ")}`);
363
+ lines.push("");
364
+ lines.push(renderInstallPlan(plan, catalog));
365
+ return lines.join("\n");
366
+ }
367
+
368
+ const s = catalog.skills[name];
369
+ if (!s) return null;
370
+ const catTitle = catalog.categories?.[s.category]?.title ?? s.category ?? "other";
371
+ lines.push(`${c.bold("Skill:")} ${name}`);
372
+ lines.push(`${c.bold("Category:")} ${catTitle} (${s.category ?? "other"})`);
373
+ lines.push(`${c.bold("Kind:")} ${s.kind}`);
374
+ lines.push(`${c.bold("Source:")} ${skillSourceFn(name)}`);
375
+ lines.push(`${c.bold("Description:")} ${s.description}`);
376
+ if (s.dependsOn?.length) {
377
+ lines.push(`${c.bold("Depends on:")} ${s.dependsOn.join(", ")}`);
378
+ }
379
+ if (s.optionalSkills?.length) {
380
+ lines.push(`${c.bold("Optional companions:")} ${s.optionalSkills.join(", ")}`);
381
+ }
382
+ const req = s.requires ?? {};
383
+ const reqLines = [];
384
+ if (req.tools?.length) reqLines.push(` tools: ${req.tools.join(", ")}`);
385
+ if (req.anyOfTools?.length) {
386
+ for (const grp of req.anyOfTools) reqLines.push(` any of: ${grp.join(" | ")}`);
387
+ }
388
+ if (req.optionalTools?.length) reqLines.push(` optional tools: ${req.optionalTools.join(", ")}`);
389
+ if (req.harness) reqLines.push(` harness: ${req.harness}`);
390
+ if (req.optionalHarness) reqLines.push(` optional harness: ${req.optionalHarness}`);
391
+ if (req.hostFacts?.length) {
392
+ for (const f of req.hostFacts) {
393
+ const meta = HOST_FACT_META[f];
394
+ reqLines.push(` host facts: ${f}${meta ? ` — ${meta.reason}` : ""}`);
395
+ }
396
+ }
397
+ if (req.runContract) {
398
+ reqLines.push(
399
+ " run contract: required (per-repo slots: plan_skill, bootstrap_command, verify_targets, etc.)",
400
+ );
401
+ }
402
+ if (reqLines.length > 0) {
403
+ lines.push(`${c.bold("Requirements:")}`);
404
+ lines.push(...reqLines);
405
+ }
406
+ return lines.join("\n");
407
+ }
408
+
409
+ export function renderPreflightReport(evalResult, probeResult) {
410
+ const lines = [];
411
+ const { host, rules } = probeResult;
412
+ lines.push(c.bold("Host & Requirements Preflight"));
413
+ lines.push(
414
+ ` Host: ${host.hostname} ${c.dim(`(${host.platform}/${host.arch}, Node ${process.version})`)}`,
415
+ );
416
+
417
+ const hasToolChecks =
418
+ evalResult.requiredTools.length > 0 ||
419
+ evalResult.anyOfGroups.length > 0 ||
420
+ evalResult.optionalTools.length > 0;
421
+
422
+ if (hasToolChecks) {
423
+ lines.push("");
424
+ lines.push(` ${c.bold("Tools & Runtimes:")}`);
425
+ for (const r of evalResult.requiredTools) {
426
+ const who = c.dim(`(${r.skills.join(", ")})`);
427
+ if (r.ok) {
428
+ const extra = [r.status.version, r.status.detail].filter(Boolean).join(" — ");
429
+ lines.push(` ${c.green("✓")} ${r.tool.padEnd(14)} ${extra || r.status.path} ${who}`);
430
+ } else {
431
+ lines.push(` ${c.red("✗")} ${r.tool.padEnd(14)} ${c.red("missing")} ${who}`);
432
+ if (r.hint) lines.push(` ${c.dim(`install: ${r.hint}`)}`);
433
+ }
434
+ }
435
+
436
+ for (const g of evalResult.anyOfGroups) {
437
+ const label = g.tools.join(" | ");
438
+ const who = c.dim(`(${g.skills.join(", ")})`);
439
+ if (g.ok) {
440
+ const found = g.satisfiedBy
441
+ .map((t) => {
442
+ const st = probeResult.tools[t];
443
+ return st?.path ? `${t} (${st.path})` : t;
444
+ })
445
+ .join(", ");
446
+ lines.push(` ${c.green("✓")} ${label} -> ${found} ${who}`);
447
+ } else {
448
+ lines.push(` ${c.red("✗")} ${label} ${c.red("none installed")} ${who}`);
449
+ for (const h of g.hints) {
450
+ if (h.hint) lines.push(` ${c.dim(`option (${h.tool}): ${h.hint}`)}`);
451
+ }
452
+ }
453
+ }
454
+
455
+ for (const o of evalResult.optionalTools) {
456
+ const who = c.dim(`(optional for ${o.skills.join(", ")})`);
457
+ if (o.ok) {
458
+ const extra = o.status.path || o.status.version || "available";
459
+ lines.push(` ${c.green("✓")} ${o.tool.padEnd(14)} ${extra} ${who}`);
460
+ } else {
461
+ lines.push(` ${c.yellow("⚠")} ${o.tool.padEnd(14)} ${c.yellow("not found")} ${who}`);
462
+ if (o.hint) lines.push(` ${c.dim(`tip: ${o.hint}`)}`);
463
+ }
464
+ }
465
+ }
466
+
467
+ if (evalResult.harnesses.length > 0) {
468
+ lines.push("");
469
+ lines.push(` ${c.bold("Agent Harness:")}`);
470
+ for (const h of evalResult.harnesses) {
471
+ if (h.requiredBy.length) {
472
+ lines.push(
473
+ ` ${c.cyan("ℹ")} ${h.name} required by: ${h.requiredBy.join(", ")}`,
474
+ );
475
+ }
476
+ if (h.optionalBy.length) {
477
+ lines.push(
478
+ ` ${c.dim("ℹ")} ${h.name} optional for: ${h.optionalBy.join(", ")}`,
479
+ );
480
+ }
481
+ }
482
+ }
483
+
484
+ if (evalResult.needsHostFacts) {
485
+ lines.push("");
486
+ lines.push(` ${c.bold("Host Facts (personal machine profile):")}`);
487
+ const skillList = [...new Set(evalResult.hostFacts.flatMap((f) => f.skills))].join(", ");
488
+ if (evalResult.hostProfileFound) {
489
+ lines.push(
490
+ ` ${c.green("✓")} Host profile found: ${rules.hostProfilePaths.join(", ")} ${c.dim(`(used by ${skillList})`)}`,
491
+ );
492
+ } else {
493
+ lines.push(
494
+ ` ${c.yellow("⚠")} No host profile rule found in ~/.agents/rules/host-*.md ${c.dim(`(needed by ${skillList})`)}`,
495
+ );
496
+ for (const f of evalResult.hostFacts) {
497
+ if (f.reason) lines.push(` ${c.dim(f.reason)}`);
498
+ }
499
+ lines.push(
500
+ ` ${c.dim(`Recommended: scaffold ~/.agents/rules/host-${host.shortHostname}.md (user-scoped, never committed to shared repos).`)}`,
501
+ );
502
+ }
503
+ }
504
+
505
+ if (evalResult.ocrSkills?.length > 0) {
506
+ lines.push("");
507
+ lines.push(` ${c.bold("Open Code Review (ocr) CLI:")}`);
508
+ const who = c.dim(`(used by ${evalResult.ocrSkills.join(", ")})`);
509
+ if (!evalResult.ocrInstalled) {
510
+ lines.push(` ${c.red("✗")} ocr binary not installed ${who}`);
511
+ lines.push(` ${c.dim("Install: npm install -g @alibaba-group/open-code-review")}`);
512
+ lines.push(` ${c.dim("Then configure an LLM provider: ocr config provider && ocr llm test")}`);
513
+ } else if (!evalResult.ocrConfigured) {
514
+ lines.push(
515
+ ` ${c.yellow("⚠")} ocr is installed (${evalResult.ocrStatus.path}) but no LLM provider is configured ${who}`,
516
+ );
517
+ lines.push(` ${c.dim("Configure: ocr config provider (then verify with: ocr llm test)")}`);
518
+ } else {
519
+ const label = evalResult.ocrStatus.providerLabel
520
+ ? ` (${evalResult.ocrStatus.providerLabel})`
521
+ : "";
522
+ lines.push(
523
+ ` ${c.green("✓")} ocr installed & LLM provider configured${label} ${who}`,
524
+ );
525
+ }
526
+ }
527
+
528
+ if (evalResult.needsRunContract) {
529
+ lines.push("");
530
+ lines.push(` ${c.bold("Orchestrator Run Contract:")}`);
531
+ const skillList = evalResult.runContractBy.join(", ");
532
+ if (evalResult.contractFound) {
533
+ lines.push(
534
+ ` ${c.green("✓")} Run Contract found: ${rules.contractPaths.join(", ")} ${c.dim(`(used by ${skillList})`)}`,
535
+ );
536
+ } else {
537
+ lines.push(
538
+ ` ${c.yellow("⚠")} No Run Contract found ${c.dim(`(needed by ${skillList})`)}`,
539
+ );
540
+ lines.push(
541
+ ` ${c.dim("Scaffold a personal contract in ~/.agents/rules/<repo>-contract.md or a shared one in docs/agents/orchestrator-contract.md.")}`,
542
+ );
543
+ }
544
+ }
545
+
546
+ if (!evalResult.hasIssues) {
547
+ lines.push("");
548
+ lines.push(` ${c.green("All checks passed.")}`);
549
+ }
550
+
551
+ return lines.join("\n");
552
+ }
553
+
554
+ export function generateHostProfile(probeResult, answers = {}) {
555
+ const { host, tools } = probeResult;
556
+ const hostLabel = answers.hostLabel || host.hostname;
557
+ const chromiumPath = answers.chromiumPath ?? tools.chromium?.path ?? "";
558
+ const preferredRenderer =
559
+ answers.preferredRenderer ??
560
+ (tools["playwright-py"]?.ok
561
+ ? "playwright-py"
562
+ : tools.magick?.ok
563
+ ? "magick"
564
+ : chromiumPath
565
+ ? "chromium-headless"
566
+ : "none-detected");
567
+ const scratchDir = answers.scratchDir ?? host.tmpdir;
568
+ const extraNotes = (answers.extraNotes ?? "").trim();
569
+
570
+ const lines = [
571
+ `# Host Profile: ${hostLabel}`,
572
+ "",
573
+ `<!-- Generated by @greenrenge/skills onboard on ${new Date().toISOString().slice(0, 10)}. Safe to edit manually. -->`,
574
+ "<!-- Keep this file in user scope (~/.agents/rules/ or ~/.claude/rules/); do not commit machine facts into shared team repositories. -->",
575
+ "",
576
+ "## Machine & Runtimes",
577
+ "",
578
+ `- **Host:** \`${hostLabel}\` (\`${host.platform}/${host.arch}\`)`,
579
+ `- **Node.js:** \`${tools.node?.version ?? process.version}\``,
580
+ `- **Python 3:** ${tools.python3?.ok ? `\`${tools.python3.version || tools.python3.path}\`` : "not detected"}`,
581
+ `- **Git:** ${tools.git?.ok ? `\`${tools.git.version || tools.git.path}\`` : "not detected"}`,
582
+ `- **GitHub CLI (\`gh\`):** ${tools.gh?.ok ? `\`${tools.gh.version || "installed"}\` (${tools.gh.detail || "ok"})` : "not detected"}`,
583
+ "",
584
+ "## Diagram & Browser Rendering",
585
+ "",
586
+ `- **Preferred PNG / visual-QA renderer:** \`${preferredRenderer}\``,
587
+ `- **Headless Chromium / Chrome binary:** ${chromiumPath ? `\`${chromiumPath}\`` : "not configured (install Chromium or set path here)"}`,
588
+ `- **Python Playwright:** ${tools["playwright-py"]?.ok ? "installed" : "not installed — fall back to ImageMagick or headless Chromium"}`,
589
+ `- **ImageMagick (\`magick\`):** ${tools.magick?.ok ? `\`${tools.magick.path}\`` : "not detected"}`,
590
+ `- **pr-lens CLI cache:** ${tools["pr-lens-cache"]?.ok ? `\`${tools["pr-lens-cache"].path}\`` : "not pre-cached (will install on first run)"}`,
591
+ ];
592
+
593
+ if (chromiumPath) {
594
+ lines.push("");
595
+ lines.push("Headless screenshot fallback command:");
596
+ lines.push("```bash");
597
+ lines.push(
598
+ `"${chromiumPath}" --headless --no-sandbox --disable-gpu --hide-scrollbars --window-size=1440,900 --screenshot=out.png "file://$PWD/page.html"`,
599
+ );
600
+ lines.push("```");
601
+ }
602
+
603
+ lines.push("");
604
+ lines.push("## Scratch & Temp Directory");
605
+ lines.push("");
606
+ lines.push(`- **Preferred scratch / temp dir:** \`${scratchDir}\``);
607
+ if (host.isTmpfsTmp && scratchDir === "/tmp") {
608
+ lines.push(
609
+ "- **Note:** `/tmp` is RAM-backed (`tmpfs`) on this Linux host — route heavy test suites or large artifacts to a disk-backed `TMPDIR`.",
610
+ );
611
+ }
612
+
613
+ if (extraNotes) {
614
+ lines.push("");
615
+ lines.push("## Additional Host Notes");
616
+ lines.push("");
617
+ lines.push(extraNotes);
618
+ }
619
+
620
+ lines.push("");
621
+ return lines.join("\n");
622
+ }
623
+
624
+ export function writeHostProfile(content, probeResult, slugOverride = null) {
625
+ const { host, rules } = probeResult;
626
+ const slug = (slugOverride || host.shortHostname)
627
+ .toLowerCase()
628
+ .replace(/[^a-z0-9._-]+/g, "-") || "local";
629
+ const fileName = `host-${slug}.md`;
630
+ mkdirSync(rules.agentsRulesDir, { recursive: true });
631
+ const primaryPath = join(rules.agentsRulesDir, fileName);
632
+ writeFileSync(primaryPath, content, "utf8");
633
+
634
+ let secondaryPath = null;
635
+ if (rules.claudeDirExists && !rules.claudeSharesAgentsRules) {
636
+ mkdirSync(rules.claudeRulesDir, { recursive: true });
637
+ secondaryPath = join(rules.claudeRulesDir, fileName);
638
+ try {
639
+ if (existsSync(secondaryPath) || isBrokenSymlink(secondaryPath)) {
640
+ unlinkSync(secondaryPath);
641
+ }
642
+ symlinkSync(primaryPath, secondaryPath);
643
+ } catch {
644
+ copyFileSync(primaryPath, secondaryPath);
645
+ }
646
+ }
647
+
648
+ return {
649
+ primaryPath,
650
+ secondaryPath,
651
+ sharedWithClaude: rules.claudeSharesAgentsRules,
652
+ };
653
+ }
654
+
655
+ function isBrokenSymlink(p) {
656
+ try {
657
+ lstatSync(p);
658
+ return true;
659
+ } catch {
660
+ return false;
661
+ }
662
+ }
663
+
664
+ export function generateRunContract(answers) {
665
+ const repoName = answers.repoName || "my-repo";
666
+ const lines = [
667
+ `# Orchestrator Run Contract: ${repoName}`,
668
+ "",
669
+ `<!-- Generated by @greenrenge/skills onboard on ${new Date().toISOString().slice(0, 10)}. Safe to edit manually. -->`,
670
+ "",
671
+ `Apply these slots whenever running \`t3-ticket-orchestrator\` on \`${repoName}\`:`,
672
+ "",
673
+ "| Slot | Value |",
674
+ "|---|---|",
675
+ `| \`target_branch\` | \`${answers.targetBranch || "main"}\` |`,
676
+ `| \`plan_skill\` | ${answers.planSkill ? `\`${answers.planSkill}\`` : "*(none — supply in prompt)*"} |`,
677
+ `| \`implement_command\` | ${answers.implementCommand ? `\`${answers.implementCommand}\`` : "*(none)*"} |`,
678
+ `| \`bootstrap_command\` | ${answers.bootstrapCommand ? `\`${answers.bootstrapCommand}\`` : "*(none)*"} |`,
679
+ `| \`env_flags\` | ${answers.envFlags ? `\`${answers.envFlags}\`` : "*(none)*"} |`,
680
+ `| \`verify_targets\` | ${answers.verifyTargets ? `\`${answers.verifyTargets}\`` : "*(copy from PR-gating CI job)*"} |`,
681
+ `| \`evidence_skill\` | ${answers.evidenceSkill ? `\`${answers.evidenceSkill}\`` : "*(none)*"} |`,
682
+ `| \`pr_review_label\` | ${answers.prReviewLabel ? `\`${answers.prReviewLabel}\`` : "*(none)*"} |`,
683
+ `| \`gate_config_paths\` | ${answers.gateConfigPaths ? `\`${answers.gateConfigPaths}\`` : "*(none)*"} |`,
684
+ "",
685
+ ];
686
+ return lines.join("\n");
687
+ }
688
+
689
+ export function writeRunContract(content, targetPath, probeResult = null) {
690
+ const abs = resolve(targetPath);
691
+ mkdirSync(dirname(abs), { recursive: true });
692
+ writeFileSync(abs, content, "utf8");
693
+
694
+ let secondaryPath = null;
695
+ if (
696
+ probeResult &&
697
+ dirname(abs) === resolve(probeResult.rules.agentsRulesDir) &&
698
+ probeResult.rules.claudeDirExists &&
699
+ !probeResult.rules.claudeSharesAgentsRules
700
+ ) {
701
+ const fileName = abs.split(/[\\/]/).pop();
702
+ mkdirSync(probeResult.rules.claudeRulesDir, { recursive: true });
703
+ secondaryPath = join(probeResult.rules.claudeRulesDir, fileName);
704
+ try {
705
+ if (existsSync(secondaryPath) || isBrokenSymlink(secondaryPath)) {
706
+ unlinkSync(secondaryPath);
707
+ }
708
+ symlinkSync(abs, secondaryPath);
709
+ } catch {
710
+ copyFileSync(abs, secondaryPath);
711
+ }
712
+ }
713
+ return { primaryPath: abs, secondaryPath };
714
+ }
715
+
716
+ /**
717
+ * Buffered prompt helper that works reliably for BOTH live interactive TTYs
718
+ * and multi-line piped stdin (never drops buffered lines on EOF).
719
+ */
720
+ export function createPrompter() {
721
+ const rl = createInterface({
722
+ input: process.stdin,
723
+ output: process.stdout,
724
+ terminal: Boolean(process.stdin.isTTY && process.stdout.isTTY),
725
+ });
726
+
727
+ const queue = [];
728
+ const waiters = [];
729
+ let closed = false;
730
+
731
+ rl.on("line", (line) => {
732
+ if (waiters.length > 0) {
733
+ const resolveNext = waiters.shift();
734
+ resolveNext(line);
735
+ } else {
736
+ queue.push(line);
737
+ }
738
+ });
739
+
740
+ rl.on("close", () => {
741
+ closed = true;
742
+ while (waiters.length > 0) {
743
+ const resolveNext = waiters.shift();
744
+ resolveNext(null);
745
+ }
746
+ });
747
+
748
+ async function nextLine(promptText) {
749
+ process.stdout.write(promptText);
750
+ if (queue.length > 0) {
751
+ const val = queue.shift();
752
+ if (!process.stdin.isTTY) process.stdout.write(`${val}\n`);
753
+ return val;
754
+ }
755
+ if (closed) {
756
+ process.stdout.write("\n");
757
+ return null;
758
+ }
759
+ return new Promise((resolveNext) => {
760
+ waiters.push((val) => {
761
+ if (!process.stdin.isTTY && val !== null) process.stdout.write(`${val}\n`);
762
+ resolveNext(val);
763
+ });
764
+ });
765
+ }
766
+
767
+ return {
768
+ async ask(question, defaultVal = "") {
769
+ const hint = defaultVal ? ` ${c.dim(`[${defaultVal}]`)}` : "";
770
+ const raw = await nextLine(`${question}${hint}: `);
771
+ if (raw === null) return defaultVal;
772
+ const trimmed = raw.trim();
773
+ return trimmed === "" ? defaultVal : trimmed;
774
+ },
775
+
776
+ async confirm(question, defaultYes = true) {
777
+ const hint = defaultYes ? "[Y/n]" : "[y/N]";
778
+ const raw = await nextLine(`${question} ${c.dim(hint)}: `);
779
+ if (raw === null) return defaultYes;
780
+ const trimmed = raw.trim().toLowerCase();
781
+ if (trimmed === "") return defaultYes;
782
+ return trimmed === "y" || trimmed === "yes";
783
+ },
784
+
785
+ close() {
786
+ rl.close();
787
+ },
788
+ };
789
+ }
790
+
791
+ export async function promptOcrSetupWizard(prompter, probeResult) {
792
+ console.log("");
793
+ console.log(c.bold("Open Code Review (ocr) CLI Setup"));
794
+ console.log(
795
+ c.dim(" open-code-review skills invoke the `ocr` CLI (npm: @alibaba-group/open-code-review)."),
796
+ );
797
+
798
+ let ocrStatus = probeResult.tools.ocr ?? probeHost({ onlyTools: new Set(["ocr"]) }).tools.ocr;
799
+
800
+ if (!ocrStatus?.ok) {
801
+ const installNow = await prompter.confirm(
802
+ " Install `@alibaba-group/open-code-review` globally via npm now?",
803
+ true,
804
+ );
805
+ if (installNow) {
806
+ const npmCmd = process.platform === "win32" ? "npm.cmd" : "npm";
807
+ console.log(c.dim(" Running: npm install -g @alibaba-group/open-code-review"));
808
+ const res = spawnSync(npmCmd, ["install", "-g", "@alibaba-group/open-code-review"], {
809
+ stdio: "inherit",
810
+ });
811
+ if (res.status === 0) {
812
+ ocrStatus = probeHost({ onlyTools: new Set(["ocr"]) }).tools.ocr;
813
+ if (ocrStatus?.ok) {
814
+ console.log(` ${c.green("✓")} Installed ocr (${ocrStatus.version || ocrStatus.path})`);
815
+ } else {
816
+ console.log(
817
+ ` ${c.yellow("⚠")} npm install succeeded, but \`ocr\` is not yet in PATH — check your global npm bin directory.`,
818
+ );
819
+ }
820
+ } else {
821
+ console.log(
822
+ ` ${c.yellow("⚠")} Global npm install did not complete (exit ${res.status ?? "error"}). Install manually with: npm install -g @alibaba-group/open-code-review`,
823
+ );
824
+ return { installed: false, configured: false };
825
+ }
826
+ } else {
827
+ console.log(
828
+ c.dim(" Skipped install. Later run: npm install -g @alibaba-group/open-code-review && ocr config provider"),
829
+ );
830
+ return { installed: false, configured: false };
831
+ }
832
+ } else {
833
+ console.log(` ${c.green("✓")} ocr binary detected: ${ocrStatus.path}`);
834
+ }
835
+
836
+ if (ocrStatus?.ok && !ocrStatus.configured) {
837
+ console.log(
838
+ c.dim(" `ocr review` requires a configured LLM provider (Anthropic, OpenAI-compatible, or AWS Bedrock)."),
839
+ );
840
+ const isInteractiveTty = Boolean(process.stdin.isTTY && process.stdout.isTTY);
841
+ if (isInteractiveTty) {
842
+ const configureNow = await prompter.confirm(
843
+ " Run interactive `ocr config provider` now?",
844
+ true,
845
+ );
846
+ if (configureNow) {
847
+ const res = spawnSync(ocrStatus.path || "ocr", ["config", "provider"], {
848
+ stdio: "inherit",
849
+ });
850
+ if (res.status === 0) {
851
+ const testNow = await prompter.confirm(" Verify connectivity with `ocr llm test`?", true);
852
+ if (testNow) {
853
+ spawnSync(ocrStatus.path || "ocr", ["llm", "test"], { stdio: "inherit" });
854
+ }
855
+ ocrStatus = probeHost({ onlyTools: new Set(["ocr"]) }).tools.ocr;
856
+ }
857
+ } else {
858
+ console.log(c.dim(" Configure later with: ocr config provider && ocr llm test"));
859
+ }
860
+ } else {
861
+ console.log(" Next step (interactive terminal required): run `ocr config provider && ocr llm test`");
862
+ }
863
+ } else if (ocrStatus?.ok && ocrStatus.configured) {
864
+ console.log(
865
+ ` ${c.green("✓")} LLM provider already configured (${ocrStatus.providerLabel || ocrStatus.configPath})`,
866
+ );
867
+ }
868
+
869
+ return { installed: Boolean(ocrStatus?.ok), configured: Boolean(ocrStatus?.configured) };
870
+ }
871
+
872
+ export async function promptHostProfileWizard(prompter, probeResult) {
873
+ const { host, tools } = probeResult;
874
+ console.log("");
875
+ console.log(c.bold("Host Profile Setup (~/.agents/rules/host-<name>.md)"));
876
+ console.log(
877
+ c.dim(" Stored in user scope so personal paths never leak into shared team repos."),
878
+ );
879
+
880
+ const profileSlug = await prompter.ask(
881
+ " Host profile name (used in host-<name>.md)",
882
+ host.shortHostname,
883
+ );
884
+
885
+ const detectedChromium = tools.chromium?.path ?? "";
886
+ const chromiumPath = await prompter.ask(
887
+ " Headless Chromium/Chrome binary path (leave blank if none)",
888
+ detectedChromium,
889
+ );
890
+
891
+ const defaultRenderer = tools["playwright-py"]?.ok
892
+ ? "playwright-py"
893
+ : tools.magick?.ok
894
+ ? "magick"
895
+ : chromiumPath
896
+ ? "chromium-headless"
897
+ : "none";
898
+ const preferredRenderer = await prompter.ask(
899
+ " Preferred diagram PNG renderer (playwright-py / magick / chromium-headless)",
900
+ defaultRenderer,
901
+ );
902
+
903
+ const defaultScratch = host.isTmpfsTmp ? join(host.homeDir, ".cache", "agent-tmp") : host.tmpdir;
904
+ const scratchPrompt = host.isTmpfsTmp
905
+ ? " Scratch temp dir (/tmp is RAM-backed tmpfs; disk-backed dir recommended)"
906
+ : " Scratch temp dir";
907
+ const scratchDir = await prompter.ask(scratchPrompt, defaultScratch);
908
+
909
+ const extraNotes = await prompter.ask(
910
+ " Extra host notes (optional, e.g. local proxy/gateway — leave blank to skip)",
911
+ "",
912
+ );
913
+
914
+ const md = generateHostProfile(probeResult, {
915
+ hostLabel: profileSlug,
916
+ chromiumPath,
917
+ preferredRenderer,
918
+ scratchDir,
919
+ extraNotes,
920
+ });
921
+ const written = writeHostProfile(md, probeResult, profileSlug);
922
+ console.log(` ${c.green("✓")} Wrote host profile: ${written.primaryPath}`);
923
+ if (written.sharedWithClaude) {
924
+ console.log(` ${c.dim("(already shared with ~/.claude/rules)")}`);
925
+ } else if (written.secondaryPath) {
926
+ console.log(` ${c.green("✓")} Linked for Claude Code: ${written.secondaryPath}`);
927
+ }
928
+ return written;
929
+ }
930
+
931
+ export async function promptRunContractWizard(prompter, probeResult, { defaultPlanSkill = "" } = {}) {
932
+ const proj = probeResult.project;
933
+ const defaultRepo = proj?.name ?? "my-repo";
934
+ console.log("");
935
+ console.log(c.bold("Orchestrator Run Contract Setup (t3-ticket-orchestrator)"));
936
+
937
+ const repoName = await prompter.ask(" Repository name", defaultRepo);
938
+ const targetBranch = await prompter.ask(" Default target branch", proj?.defaultBranch ?? "main");
939
+ const bootstrapCommand = await prompter.ask(
940
+ " Bootstrap command for fresh worktrees (optional)",
941
+ proj?.bootstrapCommand ?? "",
942
+ );
943
+ const verifyTargets = await prompter.ask(
944
+ " PR-gating verify targets / command",
945
+ proj?.verifyTargets?.join(", ") ?? "",
946
+ );
947
+ const envFlags = await prompter.ask(" Fresh-worktree env flags (optional)", "");
948
+ const planSkill = await prompter.ask(" Ticket planning skill name (optional)", defaultPlanSkill);
949
+ const implementCommand = await prompter.ask(" Worker implement command (optional, e.g. /implement)", "");
950
+ const evidenceSkill = await prompter.ask(" Live-stack evidence skill (optional)", "");
951
+ const prReviewLabel = await prompter.ask(" PR review bot label (optional)", "");
952
+ const gateConfigPaths = await prompter.ask(
953
+ " Gate config paths (comma-separated, optional)",
954
+ proj?.gateConfigPaths?.join(", ") ?? "",
955
+ );
956
+
957
+ const slug = repoName.toLowerCase().replace(/[^a-z0-9._-]+/g, "-") || "repo";
958
+ const personalPath = join(probeResult.rules.agentsRulesDir, `${slug}-contract.md`);
959
+ const repoSharedPath = proj?.dir
960
+ ? join(proj.dir, "docs", "agents", "orchestrator-contract.md")
961
+ : null;
962
+
963
+ let chosenPath = personalPath;
964
+ if (repoSharedPath) {
965
+ const scopeChoice = await prompter.ask(
966
+ ` Save location: (1) personal ${personalPath} (2) repo-shared ${repoSharedPath}`,
967
+ "1",
968
+ );
969
+ if (scopeChoice === "2" || scopeChoice.toLowerCase().startsWith("repo")) {
970
+ chosenPath = repoSharedPath;
971
+ }
972
+ }
973
+
974
+ const md = generateRunContract({
975
+ repoName,
976
+ targetBranch,
977
+ bootstrapCommand,
978
+ verifyTargets,
979
+ envFlags,
980
+ planSkill,
981
+ implementCommand,
982
+ evidenceSkill,
983
+ prReviewLabel,
984
+ gateConfigPaths,
985
+ });
986
+ const saved = writeRunContract(md, chosenPath, probeResult);
987
+ console.log(` ${c.green("✓")} Wrote Run Contract: ${saved.primaryPath}`);
988
+ if (saved.secondaryPath) {
989
+ console.log(` ${c.green("✓")} Linked for Claude Code: ${saved.secondaryPath}`);
990
+ }
991
+ return saved.primaryPath;
992
+ }
993
+
994
+ function parseSelectionInput(raw, catalog) {
995
+ const cats = orderedCategories(catalog);
996
+ const tokens = raw
997
+ .split(/[\s,]+/)
998
+ .map((t) => t.trim())
999
+ .filter(Boolean);
1000
+
1001
+ const resolved = [];
1002
+ const invalid = [];
1003
+ for (const tok of tokens) {
1004
+ if (/^\d+$/.test(tok)) {
1005
+ const idx = Number(tok) - 1;
1006
+ if (idx >= 0 && idx < cats.length) {
1007
+ resolved.push(cats[idx][0]);
1008
+ } else {
1009
+ invalid.push(tok);
1010
+ }
1011
+ } else if (catalog.bundles[tok] || catalog.skills[tok]) {
1012
+ resolved.push(tok);
1013
+ } else {
1014
+ invalid.push(tok);
1015
+ }
1016
+ }
1017
+ return { resolved: [...new Set(resolved)], invalid };
1018
+ }
1019
+
1020
+ export async function runOnboard({
1021
+ catalog,
1022
+ pkgJson,
1023
+ flags,
1024
+ resolveRoot,
1025
+ parseTargetsList,
1026
+ ensureManifest,
1027
+ addSkillToManifest,
1028
+ skillSource,
1029
+ runSkillfold,
1030
+ MANIFEST_FILENAME,
1031
+ }) {
1032
+ const prompter = createPrompter();
1033
+ try {
1034
+ console.log("");
1035
+ console.log(c.bold(`${pkgJson.name} v${pkgJson.version} — Interactive Onboarding`));
1036
+ console.log(c.dim("Select skill categories, review dependencies, probe your host, and install.\n"));
1037
+
1038
+ // Step 1: Scope & Targets
1039
+ let isGlobal = Boolean(flags.global);
1040
+ if (!flags.global && !flags.dir) {
1041
+ const scopeAns = await prompter.ask(
1042
+ "1. Install scope — (1) current project (2) global (~/.config/skillfold)",
1043
+ "1",
1044
+ );
1045
+ isGlobal = scopeAns === "2" || scopeAns.toLowerCase().startsWith("g");
1046
+ }
1047
+ const effectiveFlags = { ...flags, global: isGlobal };
1048
+ const root = resolveRoot(effectiveFlags);
1049
+ const scopeLabel = isGlobal ? "global" : "project";
1050
+
1051
+ let targets = parseTargetsList(flags.targets);
1052
+ if (!flags.targets) {
1053
+ const targetsAns = await prompter.ask(
1054
+ "2. Agent targets (comma-separated: claude, codex, cursor)",
1055
+ targets.join(","),
1056
+ );
1057
+ targets = parseTargetsList(targetsAns);
1058
+ }
1059
+
1060
+ // Step 2: Category & Skill Selection
1061
+ const cats = orderedCategories(catalog);
1062
+ console.log("");
1063
+ console.log(c.bold("3. Choose skill categories (numbers, category/skill names, or 'all'):"));
1064
+ cats.forEach(([catId, cat], idx) => {
1065
+ const count = expandPlan([catId], catalog, { includeDeps: false }).ordered.length;
1066
+ const optTag = cat.optIn ? ` ${c.yellow("[opt-in]")}` : "";
1067
+ const needsTags = [];
1068
+ const catSkills = Object.values(catalog.skills).filter((s) => s.category === catId);
1069
+ if (catSkills.some((s) => s.requires?.tools?.includes("ocr"))) needsTags.push("[ocr CLI]");
1070
+ if (catSkills.some((s) => s.requires?.hostFacts?.length)) needsTags.push("[host facts]");
1071
+ if (catSkills.some((s) => s.requires?.runContract)) needsTags.push("[run contract]");
1072
+ const needStr = needsTags.length ? ` ${c.dim(needsTags.join(" "))}` : "";
1073
+ console.log(
1074
+ ` ${c.cyan(`${idx + 1}.`)} ${c.bold(catId.padEnd(15))} ${c.dim(`(${String(count).padStart(2)} skills)`)} ${cat.title}${optTag}${needStr}`,
1075
+ );
1076
+ console.log(` ${c.dim(cat.tagline)}`);
1077
+ });
1078
+ console.log(
1079
+ c.dim(" Examples: '1,2,3' | 'diagrams,workflow' | 'pr-diagram-portfolio' | 'all'"),
1080
+ );
1081
+
1082
+ let selectedInputs = [];
1083
+ while (selectedInputs.length === 0) {
1084
+ const rawSel = await prompter.ask(" Selection", "1,2,3");
1085
+ const { resolved, invalid } = parseSelectionInput(rawSel, catalog);
1086
+ if (invalid.length > 0) {
1087
+ console.log(c.red(` Unknown selection(s): ${invalid.join(", ")}. Please try again.`));
1088
+ if (!process.stdin.isTTY) {
1089
+ throw new Error(`Invalid onboard selection: ${invalid.join(", ")}`);
1090
+ }
1091
+ continue;
1092
+ }
1093
+ if (resolved.length === 0) {
1094
+ console.log(c.yellow(" Select at least one category or skill."));
1095
+ if (!process.stdin.isTTY) {
1096
+ throw new Error("Empty onboard selection");
1097
+ }
1098
+ continue;
1099
+ }
1100
+ selectedInputs = resolved;
1101
+ }
1102
+
1103
+ // Step 3: Expand & render categorized dependency tree
1104
+ const plan = expandPlan(selectedInputs, catalog, { includeDeps: !flags.noDeps });
1105
+ console.log("");
1106
+ console.log(renderInstallPlan(plan, catalog, { scope: scopeLabel, targets, root }));
1107
+
1108
+ // Step 4: Preflight host probe
1109
+ const toolsNeeded = collectToolsToProbe(plan.ordered, catalog);
1110
+ const projectDir = isGlobal ? process.cwd() : root;
1111
+ const probeResult = probeHost({ projectDir, onlyTools: toolsNeeded });
1112
+ const evalResult = evaluateRequirements(plan.ordered, catalog, probeResult);
1113
+
1114
+ console.log("");
1115
+ console.log(renderPreflightReport(evalResult, probeResult));
1116
+
1117
+ // Step 5: Interactive OCR CLI, Host Profile & Run Contract setup when needed
1118
+ const writtenArtifacts = [];
1119
+ if (evalResult.needsOcrSetup || flags.setupOcr) {
1120
+ await promptOcrSetupWizard(prompter, probeResult);
1121
+ }
1122
+
1123
+ if (evalResult.needsHostFacts && (!evalResult.hostProfileFound || flags.setupHost)) {
1124
+ console.log("");
1125
+ const doHost = await prompter.confirm(
1126
+ `Selected skills benefit from host facts. Scaffold ~/.agents/rules/host-${probeResult.host.shortHostname}.md now?`,
1127
+ true,
1128
+ );
1129
+ if (doHost) {
1130
+ const res = await promptHostProfileWizard(prompter, probeResult);
1131
+ writtenArtifacts.push(res.primaryPath);
1132
+ }
1133
+ }
1134
+
1135
+ if (evalResult.needsRunContract && (!evalResult.contractFound || flags.setupContract)) {
1136
+ console.log("");
1137
+ const doContract = await prompter.confirm(
1138
+ "Selected orchestration/ticket skills need a per-repo Run Contract. Scaffold one now?",
1139
+ true,
1140
+ );
1141
+ if (doContract) {
1142
+ const defaultPlanSkill = plan.selectedSet.has("ticket-scheme") ? "ticket-scheme" : "";
1143
+ const saved = await promptRunContractWizard(prompter, probeResult, { defaultPlanSkill });
1144
+ writtenArtifacts.push(saved);
1145
+ }
1146
+ }
1147
+
1148
+ // Step 6: Confirm & Install
1149
+ console.log("");
1150
+ const ok = await prompter.confirm(
1151
+ `Install ${plan.counts.total} skill(s) into ${join(root, MANIFEST_FILENAME)}?`,
1152
+ true,
1153
+ );
1154
+ if (!ok) {
1155
+ console.log("Cancelled — no skills were installed.");
1156
+ return;
1157
+ }
1158
+
1159
+ const manifestPath = ensureManifest(root, targets, true);
1160
+ for (const name of plan.ordered) {
1161
+ const src = skillSource(name, { local: flags.local });
1162
+ addSkillToManifest(manifestPath, name, src);
1163
+ }
1164
+
1165
+ console.log("");
1166
+ runSkillfold(["install"], effectiveFlags);
1167
+ console.log("");
1168
+ console.log(c.green(c.bold(`Onboarding complete — ${plan.counts.total} skill(s) installed.`)));
1169
+ console.log(` Manifest: ${manifestPath}`);
1170
+ for (const p of writtenArtifacts) {
1171
+ console.log(` Rule: ${p}`);
1172
+ }
1173
+ console.log(
1174
+ c.dim(` Verify anytime with: npx ${pkgJson.name} doctor${isGlobal ? " --global" : ""}`),
1175
+ );
1176
+ } finally {
1177
+ prompter.close();
1178
+ }
1179
+ }