skill-monster 0.0.0-stage → 0.1.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.
Files changed (88) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +155 -2
  3. package/desk-ui/app.css +73 -0
  4. package/desk-ui/app.js +182 -0
  5. package/desk-ui/fonts/bricolage-grotesque-800.woff2 +0 -0
  6. package/desk-ui/fonts/ibm-plex-mono-400.woff2 +0 -0
  7. package/desk-ui/fonts/ibm-plex-mono-600.woff2 +0 -0
  8. package/desk-ui/fonts/ibm-plex-sans-400.woff2 +0 -0
  9. package/desk-ui/fonts/silkscreen-400.woff2 +0 -0
  10. package/desk-ui/fonts.css +70 -0
  11. package/desk-ui/index.html +29 -0
  12. package/desk-ui/mascot.svg +1 -0
  13. package/dist/build.json +1 -0
  14. package/dist/cli/index.d.ts +2 -0
  15. package/dist/cli/index.js +640 -0
  16. package/dist/cli/ui.d.ts +18 -0
  17. package/dist/cli/ui.js +120 -0
  18. package/dist/core/checkup.d.ts +14 -0
  19. package/dist/core/checkup.js +69 -0
  20. package/dist/core/corrections.d.ts +54 -0
  21. package/dist/core/corrections.js +138 -0
  22. package/dist/core/digest.d.ts +36 -0
  23. package/dist/core/digest.js +91 -0
  24. package/dist/core/export.d.ts +8 -0
  25. package/dist/core/export.js +28 -0
  26. package/dist/core/external.d.ts +48 -0
  27. package/dist/core/external.js +127 -0
  28. package/dist/core/guard.d.ts +10 -0
  29. package/dist/core/guard.js +48 -0
  30. package/dist/core/mirror.d.ts +37 -0
  31. package/dist/core/mirror.js +148 -0
  32. package/dist/core/release.d.ts +69 -0
  33. package/dist/core/release.js +173 -0
  34. package/dist/core/report.d.ts +10 -0
  35. package/dist/core/report.js +65 -0
  36. package/dist/core/scrub.d.ts +20 -0
  37. package/dist/core/scrub.js +67 -0
  38. package/dist/core/sign.d.ts +25 -0
  39. package/dist/core/sign.js +86 -0
  40. package/dist/core/skill.d.ts +26 -0
  41. package/dist/core/skill.js +68 -0
  42. package/dist/core/starters.d.ts +54 -0
  43. package/dist/core/starters.js +184 -0
  44. package/dist/core/types.d.ts +187 -0
  45. package/dist/core/types.js +1 -0
  46. package/dist/core/version.d.ts +4 -0
  47. package/dist/core/version.js +17 -0
  48. package/dist/core/workspace.d.ts +23 -0
  49. package/dist/core/workspace.js +79 -0
  50. package/dist/desk/server.d.ts +10 -0
  51. package/dist/desk/server.js +140 -0
  52. package/dist/index.d.ts +11 -0
  53. package/dist/index.js +10 -0
  54. package/dist/mcp/server.d.ts +8 -0
  55. package/dist/mcp/server.js +112 -0
  56. package/dist/providers/index.d.ts +15 -0
  57. package/dist/providers/index.js +123 -0
  58. package/dist/slack/api.d.ts +6 -0
  59. package/dist/slack/api.js +18 -0
  60. package/dist/slack/app.d.ts +70 -0
  61. package/dist/slack/app.js +387 -0
  62. package/dist/slack/manifest.d.ts +50 -0
  63. package/dist/slack/manifest.js +71 -0
  64. package/dist/slack/messages.d.ts +414 -0
  65. package/dist/slack/messages.js +226 -0
  66. package/dist/slack/socket.d.ts +24 -0
  67. package/dist/slack/socket.js +84 -0
  68. package/dist/stores/airtable.d.ts +26 -0
  69. package/dist/stores/airtable.js +52 -0
  70. package/dist/stores/confluence-format.d.ts +34 -0
  71. package/dist/stores/confluence-format.js +458 -0
  72. package/dist/stores/confluence.d.ts +55 -0
  73. package/dist/stores/confluence.js +204 -0
  74. package/dist/stores/index.d.ts +30 -0
  75. package/dist/stores/index.js +53 -0
  76. package/dist/stores/notion.d.ts +43 -0
  77. package/dist/stores/notion.js +313 -0
  78. package/docs/SECURITY.md +45 -0
  79. package/docs/slack.md +78 -0
  80. package/package.json +48 -4
  81. package/starters/_core/SKILL.md +30 -0
  82. package/starters/customer-support-answers/starter.yaml +98 -0
  83. package/starters/data-warehouse-kb/starter.yaml +119 -0
  84. package/starters/engineering-house-rules/starter.yaml +106 -0
  85. package/starters/people-policies/starter.yaml +89 -0
  86. package/starters/pricing-and-packaging/starter.yaml +90 -0
  87. package/starters/product-analytics-kb/starter.yaml +109 -0
  88. package/starters/security-questionnaire-answers/starter.yaml +94 -0
@@ -0,0 +1,65 @@
1
+ import fs from 'node:fs';
2
+ import os from 'node:os';
3
+ import { findBlanks, loadSkill, loadTests } from './skill.js';
4
+ import { listReleases, verifyRelease } from './release.js';
5
+ import { listCorrections } from './corrections.js';
6
+ import { checkSkill } from './checkup.js';
7
+ import { openStore } from '../stores/index.js';
8
+ /**
9
+ * A run report that is safe to send outside the company: counts, versions, model names,
10
+ * provider types and test ids only. It never includes skill content, questions, answers,
11
+ * test expectations, error text, names, page ids or paths.
12
+ */
13
+ export async function buildReport(ws, toolVersion, opts = {}) {
14
+ const lines = [
15
+ '# Skill Monster run report',
16
+ '',
17
+ '_Counts only. No knowledge-base content, questions, answers, names, page ids or paths._',
18
+ '',
19
+ `- Skill Monster ${toolVersion} · Node ${process.version} · ${os.platform()}`,
20
+ `- Store type: ${ws.config.store.type}`,
21
+ `- Models: ${ws.config.models.map(m => `${m.name} (${m.provider})`).join(', ') || 'none'}`,
22
+ `- allow_untested: ${!!ws.config.allow_untested}`,
23
+ ];
24
+ let storeOk = true;
25
+ for (const [i, n] of ws.listSkills().entries()) {
26
+ // A skill's name can reveal the domain, so it's shown only when asked for (report --names).
27
+ const label = opts.names ? n : `skill ${i + 1}`;
28
+ const meta = loadSkill(ws, n);
29
+ const tests = loadTests(ws, n);
30
+ const rels = listReleases(ws, n);
31
+ const latest = rels[0];
32
+ let blanks = '?', chars = '?', emptySections = '?', findings = '?';
33
+ try {
34
+ const sections = await openStore(ws).readSections(meta);
35
+ blanks = String(findBlanks(sections).length);
36
+ chars = String(Object.values(sections).reduce((a, s) => a + s.length, 0));
37
+ emptySections = String(Object.values(sections).filter(s => !s.trim()).length);
38
+ const f = await checkSkill(ws, n);
39
+ findings = `${f.filter(x => x.level === 'block').length} block, ${f.filter(x => x.level === 'warn').length} warn`;
40
+ }
41
+ catch {
42
+ storeOk = false;
43
+ }
44
+ const verified = rels.filter(r => { try {
45
+ return verifyRelease(ws, n, r.version).ok;
46
+ }
47
+ catch {
48
+ return false;
49
+ } }).length;
50
+ lines.push('', `## ${label}${rels.length ? "" : " (unreleased)"} · starter: ${meta.starter ?? "none"}`, '', `- Sections: ${meta.sections.length} (${emptySections} empty) · content size: ${chars} characters · visible blanks: ${blanks}`, `- Guard tests: ${tests.length} (${tests.filter(t => t.seeded).length} seeded, ${tests.filter(t => !t.seeded).length} added)`, `- Check-up: ${findings}`, `- Releases: ${rels.length} (${verified} verify) · latest: ${latest?.version ?? 'none'}`);
51
+ if (latest) {
52
+ lines.push('', '| Model | Tested | Passed | Failing test ids |', '|---|---|---|---|');
53
+ for (const [m, w] of Object.entries(latest.works_on))
54
+ lines.push(`| ${m} | ${w.tested ? 'yes' : 'no'} | ${w.tested ? `${w.pass} / ${w.total}` : '–'} | ${w.failed.join(', ') || '–'} |`);
55
+ }
56
+ const cors = listCorrections(ws).filter(c => c.skill === n);
57
+ lines.push('', `- Corrections: ${cors.length} (${['open', 'approved', 'declined', 'snoozed'].map(s => `${cors.filter(c => c.status === s).length} ${s}`).join(', ')})`);
58
+ }
59
+ if (!ws.listSkills().length)
60
+ lines.push('', 'No skills yet.');
61
+ if (!storeOk)
62
+ lines.push('', '- The store could not be read when this report ran (counts marked "?").');
63
+ return lines.join('\n') + '\n';
64
+ }
65
+ export function writeReport(file, text) { fs.writeFileSync(file, text); }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Removes names, contact details, customer data, money amounts and secrets from free text
3
+ * before it is written anywhere. Runs locally; nothing is sent to a service.
4
+ */
5
+ export interface ScrubResult {
6
+ text: string;
7
+ removed: string[];
8
+ }
9
+ export declare function scrub(text: string, opts?: {
10
+ names?: string[];
11
+ extra?: string[];
12
+ }): ScrubResult;
13
+ /** Findings for the release check-up. Secrets block a release; personal data blocks too. */
14
+ export declare function findSensitive(text: string): {
15
+ kind: string;
16
+ sample: string;
17
+ severity: 'block' | 'warn';
18
+ }[];
19
+ /** Money amounts and counts of customers, accounts and the like. Warnings only: a KB may quote a real fee on purpose. */
20
+ export declare function findFigures(text: string): string[];
@@ -0,0 +1,67 @@
1
+ const SECRET_PATTERNS = [
2
+ [/\b(?:sk|pk|rk)-[A-Za-z0-9_\-]{16,}\b/g, 'API key'],
3
+ [/\bsk-ant-[A-Za-z0-9_\-]{16,}\b/g, 'API key'],
4
+ [/\bAKIA[0-9A-Z]{16}\b/g, 'AWS key'],
5
+ [/\bgh[pousr]_[A-Za-z0-9]{30,}\b/g, 'GitHub token'],
6
+ [/\bxox[abposr]-[A-Za-z0-9-]{10,}\b/g, 'Slack token'],
7
+ [/\bAIza[0-9A-Za-z_\-]{30,}\b/g, 'Google key'],
8
+ [/\b(?:secret|ntn)_[A-Za-z0-9]{30,}\b/g, 'Notion token'],
9
+ [/\bATATT[A-Za-z0-9_\-=]{30,}\b/g, 'Atlassian token'],
10
+ [/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g, 'private key'],
11
+ [/\b(?:password|passwd|pwd|token|api[_-]?key|secret)\s*[:=]\s*\S+/gi, 'password-like value'],
12
+ ];
13
+ const PII_PATTERNS = [
14
+ [/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, 'email address'],
15
+ [/(?:\+?\d{1,3}[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b/g, 'phone number'],
16
+ [/\b\d{3}-\d{2}-\d{4}\b/g, 'ID number'],
17
+ [/\b(?:\d[ -]?){13,19}\b/g, 'card or account number'],
18
+ [/\b(?:\d{1,3}\.){3}\d{1,3}\b/g, 'IP address'],
19
+ ];
20
+ const MONEY = /(?:[$€£¥]\s?\d[\d,]*(?:\.\d+)?(?:\s?(?:[kKmMbB]n?|million|billion)\b)?)|(?:\b\d[\d,]*(?:\.\d+)?\s?(?:USD|EUR|GBP|dollars|euros)\b)/g;
21
+ const BIG_COUNT = /(?<![\d,.])\d[\d,]*\d(?=\s+(?:refunds?|customers?|accounts?|users?|orders?|invoices?|workspaces?|people|employees|deals?))/gi;
22
+ export function scrub(text, opts = {}) {
23
+ const removed = new Set();
24
+ let t = text ?? '';
25
+ const rep = (re, label, token) => {
26
+ t = t.replace(re, () => { removed.add(label); return token; });
27
+ };
28
+ for (const [re, label] of SECRET_PATTERNS)
29
+ rep(re, label, `[${label} removed]`);
30
+ for (const [re, label] of PII_PATTERNS)
31
+ rep(re, label, `[${label} removed]`);
32
+ rep(MONEY, 'dollar amounts', '[amount]');
33
+ rep(BIG_COUNT, 'counts', '[n]');
34
+ for (const n of opts.names ?? []) {
35
+ if (!n.trim())
36
+ continue;
37
+ rep(new RegExp(`\\b${escapeRe(n.trim())}\\b`, 'gi'), 'names', '[name]');
38
+ }
39
+ for (const p of opts.extra ?? [])
40
+ rep(new RegExp(p, 'g'), 'custom pattern', '[removed]');
41
+ return { text: t, removed: [...removed] };
42
+ }
43
+ /** Findings for the release check-up. Secrets block a release; personal data blocks too. */
44
+ export function findSensitive(text) {
45
+ const found = [];
46
+ for (const [re, label] of SECRET_PATTERNS)
47
+ for (const m of text.matchAll(re))
48
+ found.push({ kind: label, sample: mask(m[0]), severity: 'block' });
49
+ for (const [re, label] of PII_PATTERNS.slice(0, 4))
50
+ for (const m of text.matchAll(re)) {
51
+ if (label === 'email address' && /@(example\.(com|org)|acme\.(com|internal))$/i.test(m[0]))
52
+ continue;
53
+ found.push({ kind: label, sample: mask(m[0]), severity: 'block' });
54
+ }
55
+ return found;
56
+ }
57
+ /** Money amounts and counts of customers, accounts and the like. Warnings only: a KB may quote a real fee on purpose. */
58
+ export function findFigures(text) {
59
+ const out = [];
60
+ if (text.match(MONEY))
61
+ out.push('money amount');
62
+ if (text.match(BIG_COUNT))
63
+ out.push('count');
64
+ return out;
65
+ }
66
+ const mask = (s) => (s.length <= 8 ? '****' : s.slice(0, 4) + '…' + '*'.repeat(4));
67
+ const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
@@ -0,0 +1,25 @@
1
+ import type { ReleaseRecord } from './types.js';
2
+ import type { Workspace } from './workspace.js';
3
+ /**
4
+ * Releases are signed with an Ed25519 key. The public key lives in the workspace
5
+ * (.skill-monster/keys/<id>.pub) so anyone can verify. The private key never enters
6
+ * the repo: it lives in ~/.config/skill-monster/keys or in SKILL_MONSTER_SIGNING_KEY (for CI).
7
+ */
8
+ /**
9
+ * Where the private key lives: SKILL_MONSTER_KEY_DIR, else keys_dir in skill-monster.yaml
10
+ * (handy where environment variables don't persist, e.g. a sandboxed agent), else ~/.config.
11
+ */
12
+ export declare function keyHome(ws?: Workspace): string;
13
+ /** Warnings about where the private key ends up. Worded for the person; empty when it's fine. */
14
+ export declare function keyDirWarnings(ws: Workspace): string[];
15
+ export declare function ensureKey(ws: Workspace): {
16
+ keyId: string;
17
+ created: boolean;
18
+ };
19
+ export declare function canonical(v: unknown): string;
20
+ export declare const sha256: (s: string | Buffer) => string;
21
+ export declare function signRecord(ws: Workspace, rec: Omit<ReleaseRecord, 'signature' | 'key_id'>): ReleaseRecord;
22
+ export declare function verifyRecord(ws: Workspace, rec: ReleaseRecord): {
23
+ ok: boolean;
24
+ reason: string;
25
+ };
@@ -0,0 +1,86 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ /**
6
+ * Releases are signed with an Ed25519 key. The public key lives in the workspace
7
+ * (.skill-monster/keys/<id>.pub) so anyone can verify. The private key never enters
8
+ * the repo: it lives in ~/.config/skill-monster/keys or in SKILL_MONSTER_SIGNING_KEY (for CI).
9
+ */
10
+ /**
11
+ * Where the private key lives: SKILL_MONSTER_KEY_DIR, else keys_dir in skill-monster.yaml
12
+ * (handy where environment variables don't persist, e.g. a sandboxed agent), else ~/.config.
13
+ */
14
+ export function keyHome(ws) {
15
+ if (process.env.SKILL_MONSTER_KEY_DIR)
16
+ return process.env.SKILL_MONSTER_KEY_DIR;
17
+ const dir = ws?.config.keys_dir;
18
+ if (dir)
19
+ return path.resolve(ws.root, dir.replace(/^~(?=$|\/)/, os.homedir()));
20
+ return path.join(os.homedir(), '.config', 'skill-monster', 'keys');
21
+ }
22
+ /** Warnings about where the private key ends up. Worded for the person; empty when it's fine. */
23
+ export function keyDirWarnings(ws) {
24
+ const out = [];
25
+ const raw = process.env.SKILL_MONSTER_KEY_DIR ? undefined : ws.config.keys_dir;
26
+ if (raw && /^~(?=$|\/)/.test(raw))
27
+ out.push(`keys_dir starts with "~", which is ${os.homedir()} for this shell. In a sandboxed agent that home folder can be wiped after the session. A path relative to the workspace, such as ../.skill-monster-keys, resolves to the same folder everywhere.`);
28
+ const rel = path.relative(ws.root, path.resolve(keyHome(ws)));
29
+ if (!rel.startsWith('..') && !path.isAbsolute(rel))
30
+ out.push(`The private signing key is inside the workspace (${rel || '.'}), so it could be committed or mirrored. Move it outside, e.g. keys_dir: ../.skill-monster-keys.`);
31
+ return out;
32
+ }
33
+ export function ensureKey(ws) {
34
+ const pubDir = ws.records('keys');
35
+ const existing = fs.existsSync(pubDir) ? fs.readdirSync(pubDir).filter(f => f.endsWith('.pub')) : [];
36
+ for (const f of existing) {
37
+ const id = f.replace(/\.pub$/, '');
38
+ if (loadPrivate(id, ws))
39
+ return { keyId: id, created: false };
40
+ }
41
+ const { publicKey, privateKey } = crypto.generateKeyPairSync('ed25519');
42
+ const pub = publicKey.export({ type: 'spki', format: 'pem' }).toString();
43
+ const keyId = crypto.createHash('sha256').update(pub).digest('hex').slice(0, 16);
44
+ fs.mkdirSync(pubDir, { recursive: true });
45
+ fs.writeFileSync(path.join(pubDir, `${keyId}.pub`), pub);
46
+ fs.mkdirSync(keyHome(ws), { recursive: true, mode: 0o700 });
47
+ fs.writeFileSync(path.join(keyHome(ws), `${keyId}.pem`), privateKey.export({ type: 'pkcs8', format: 'pem' }).toString(), { mode: 0o600 });
48
+ return { keyId, created: true };
49
+ }
50
+ function loadPrivate(keyId, ws) {
51
+ const env = process.env.SKILL_MONSTER_SIGNING_KEY;
52
+ if (env) {
53
+ const k = crypto.createPrivateKey(env.includes('BEGIN') ? env : Buffer.from(env, 'base64').toString());
54
+ const pub = crypto.createPublicKey(k).export({ type: 'spki', format: 'pem' }).toString();
55
+ if (crypto.createHash('sha256').update(pub).digest('hex').slice(0, 16) === keyId)
56
+ return k;
57
+ }
58
+ const f = path.join(keyHome(ws), `${keyId}.pem`);
59
+ return fs.existsSync(f) ? crypto.createPrivateKey(fs.readFileSync(f)) : undefined;
60
+ }
61
+ export function canonical(v) {
62
+ if (Array.isArray(v))
63
+ return `[${v.map(canonical).join(',')}]`;
64
+ if (v && typeof v === 'object') {
65
+ return `{${Object.keys(v).sort().filter(k => v[k] !== undefined).map(k => `${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`;
66
+ }
67
+ return JSON.stringify(v);
68
+ }
69
+ export const sha256 = (s) => crypto.createHash('sha256').update(s).digest('hex');
70
+ export function signRecord(ws, rec) {
71
+ const { keyId } = ensureKey(ws);
72
+ const key = loadPrivate(keyId, ws);
73
+ const body = { ...rec, key_id: keyId };
74
+ const signature = crypto.sign(null, Buffer.from(canonical(body)), key).toString('base64');
75
+ return { ...body, signature };
76
+ }
77
+ export function verifyRecord(ws, rec) {
78
+ const f = ws.records('keys', `${rec.key_id}.pub`);
79
+ if (!fs.existsSync(f))
80
+ return { ok: false, reason: `Unknown signing key ${rec.key_id}` };
81
+ const { signature, ...body } = rec;
82
+ if (!signature)
83
+ return { ok: false, reason: 'Not signed' };
84
+ const ok = crypto.verify(null, Buffer.from(canonical(body)), crypto.createPublicKey(fs.readFileSync(f)), Buffer.from(signature, 'base64'));
85
+ return { ok, reason: ok ? 'Signature valid' : 'Signature does not match: the record or its files were changed after signing' };
86
+ }
@@ -0,0 +1,26 @@
1
+ import type { GuardTest, SkillMeta } from './types.js';
2
+ import { type Workspace } from './workspace.js';
3
+ export declare const BLANK_RE: RegExp;
4
+ export declare function loadSkill(ws: Workspace, name: string): SkillMeta;
5
+ export declare function saveSkill(ws: Workspace, meta: SkillMeta): void;
6
+ export declare function loadTests(ws: Workspace, name: string): GuardTest[];
7
+ export declare function saveTest(ws: Workspace, skill: string, t: GuardTest): void;
8
+ export declare function nextTestId(ws: Workspace, skill: string): string;
9
+ export declare function bumpVersion(v: string, kind?: 'patch' | 'minor' | 'major'): string;
10
+ export declare function compareVersions(a: string, b: string): number;
11
+ export declare function readContent(ws: Workspace, meta: SkillMeta): Promise<{
12
+ entry: string;
13
+ sections: Record<string, string>;
14
+ }>;
15
+ /** One text bundle a model reads before answering. Sections follow the entry file's router. */
16
+ export declare function renderBundle(meta: SkillMeta, entry: string, sections: Record<string, string>): string;
17
+ export declare function stripFrontmatter(md: string): string;
18
+ export declare function findBlanks(sections: Record<string, string>): {
19
+ section: string;
20
+ what: string;
21
+ ask?: string;
22
+ }[];
23
+ export declare function trustFooterInstruction(meta: {
24
+ name: string;
25
+ version: string;
26
+ }): string;
@@ -0,0 +1,68 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { readYaml, writeYaml } from './workspace.js';
4
+ import { openStore } from '../stores/index.js';
5
+ export const BLANK_RE = /Not defined yet:\s*([^\n.]+)\.?(?:\s*Ask ([^\n.]+)\.)?/g;
6
+ export function loadSkill(ws, name) {
7
+ const f = path.join(ws.skillDir(name), 'skill.yaml');
8
+ if (!fs.existsSync(f))
9
+ throw new Error(`No skill called "${name}". Skills here: ${ws.listSkills().join(', ') || 'none yet'}.`);
10
+ return readYaml(f);
11
+ }
12
+ export function saveSkill(ws, meta) {
13
+ writeYaml(path.join(ws.skillDir(meta.name), 'skill.yaml'), meta);
14
+ }
15
+ export function loadTests(ws, name) {
16
+ const d = path.join(ws.skillDir(name), 'tests');
17
+ if (!fs.existsSync(d))
18
+ return [];
19
+ return fs.readdirSync(d).filter(f => f.endsWith('.yaml')).sort().map(f => readYaml(path.join(d, f)));
20
+ }
21
+ export function saveTest(ws, skill, t) {
22
+ writeYaml(path.join(ws.skillDir(skill), 'tests', `${t.id}.yaml`), t);
23
+ }
24
+ export function nextTestId(ws, skill) {
25
+ const ids = loadTests(ws, skill).map(t => Number(t.id.replace(/\D/g, '')) || 0);
26
+ return `test-${String((ids.length ? Math.max(...ids) : 0) + 1).padStart(2, '0')}`;
27
+ }
28
+ export function bumpVersion(v, kind = 'patch') {
29
+ const [a, b, c] = v.split('.').map(Number);
30
+ if (kind === 'major')
31
+ return `${a + 1}.0.0`;
32
+ if (kind === 'minor')
33
+ return `${a}.${b + 1}.0`;
34
+ return `${a}.${b}.${c + 1}`;
35
+ }
36
+ export function compareVersions(a, b) {
37
+ const x = a.split('.').map(Number), y = b.split('.').map(Number);
38
+ for (let i = 0; i < 3; i++)
39
+ if (x[i] !== y[i])
40
+ return x[i] - y[i];
41
+ return 0;
42
+ }
43
+ export async function readContent(ws, meta) {
44
+ const entry = fs.readFileSync(path.join(ws.skillDir(meta.name), 'SKILL.md'), 'utf8');
45
+ const sections = await openStore(ws).readSections(meta);
46
+ return { entry, sections };
47
+ }
48
+ /** One text bundle a model reads before answering. Sections follow the entry file's router. */
49
+ export function renderBundle(meta, entry, sections) {
50
+ const body = meta.sections.map(id => `\n\n<!-- section: ${id} -->\n${(sections[id] ?? '').trim()}`).join('');
51
+ return `${stripFrontmatter(entry).trim()}${body}\n`;
52
+ }
53
+ export function stripFrontmatter(md) { return md.replace(/^---\n[\s\S]*?\n---\n/, ''); }
54
+ export function findBlanks(sections) {
55
+ const out = [];
56
+ for (const [section, md] of Object.entries(sections)) {
57
+ for (const m of md.matchAll(BLANK_RE))
58
+ out.push({ section, what: m[1].trim(), ask: m[2]?.trim() });
59
+ if (!md.trim())
60
+ out.push({ section, what: `the whole "${section}" section` });
61
+ }
62
+ return out;
63
+ }
64
+ export function trustFooterInstruction(meta) {
65
+ return `When you answer from this skill, end with one line: "Answered from ${meta.name} ${meta.version}". ` +
66
+ `If the skill marks something "Not defined yet", say you don't know and name who to ask. Never invent a definition, price, policy or rule. ` +
67
+ `If the user says your answer is wrong, offer to send a correction to the skill's owner with the skill-monster tool.`;
68
+ }
@@ -0,0 +1,54 @@
1
+ import type { GuardTest, SkillMeta } from './types.js';
2
+ import type { Workspace } from './workspace.js';
3
+ export interface InterviewQuestion {
4
+ key: string;
5
+ question: string;
6
+ hint?: string;
7
+ list?: boolean;
8
+ }
9
+ export interface StarterSection {
10
+ id: string;
11
+ title: string;
12
+ template: string;
13
+ }
14
+ export interface StarterDef {
15
+ id: string;
16
+ title: string;
17
+ tagline: string;
18
+ for: string;
19
+ curator_hint: string;
20
+ default_skill: string;
21
+ sections: StarterSection[];
22
+ interview: InterviewQuestion[];
23
+ router: Record<string, string>;
24
+ tests: (GuardTest & {
25
+ needs?: string;
26
+ })[];
27
+ }
28
+ export declare function startersDir(): string;
29
+ export declare function listStarters(): StarterDef[];
30
+ export declare function loadStarter(id: string): StarterDef;
31
+ /** Fills {{key}} or {{key|Label}}. Missing values become visible blanks, never invented text. */
32
+ export declare function fill(tpl: string, vars: Record<string, string | undefined>, owner: string): string;
33
+ /** Answers files may use YAML lists, numbers or blocks. Turn every answer into trimmed text; drop empty ones. */
34
+ export declare function normalizeAnswers(raw: Record<string, unknown> | null | undefined): Record<string, string>;
35
+ /**
36
+ * Lets an answers file fit the starter to the team's KB without forking it:
37
+ * kb_title: Royalty KB
38
+ * section_titles: { metrics: Royalty rules } # rename a section (its id stays)
39
+ * drop_sections: [dashboards] # leave a section out
40
+ * extra_sections: # add sections
41
+ * - { id: contracts, title: Contract terms, router: Which contract terms apply, content: "optional Markdown" }
42
+ */
43
+ export declare function shapeStarter(st: StarterDef, raw: Record<string, unknown>): StarterDef;
44
+ export interface HatchResult {
45
+ meta: SkillMeta;
46
+ blanks: number;
47
+ filled: number;
48
+ tests: number;
49
+ }
50
+ /** Creates a skill from a starter and interview answers. Unanswered questions stay visible blanks. */
51
+ export declare function hatch(ws: Workspace, starterId: string, rawAnswers: Record<string, unknown>, opts?: {
52
+ name?: string;
53
+ owner?: string;
54
+ }): Promise<HatchResult>;
@@ -0,0 +1,184 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import YAML from 'yaml';
5
+ import { saveSkill, saveTest } from './skill.js';
6
+ import { openStore } from '../stores/index.js';
7
+ export function startersDir() {
8
+ const here = path.dirname(fileURLToPath(import.meta.url));
9
+ for (const c of [path.resolve(here, '../../starters'), path.resolve(here, '../../../starters')])
10
+ if (fs.existsSync(c))
11
+ return c;
12
+ throw new Error('Starters folder not found');
13
+ }
14
+ export function listStarters() {
15
+ const d = startersDir();
16
+ return fs.readdirSync(d).filter(n => !n.startsWith('_') && fs.existsSync(path.join(d, n, 'starter.yaml'))).map(loadStarter)
17
+ .sort((a, b) => ORDER.indexOf(a.id) - ORDER.indexOf(b.id));
18
+ }
19
+ const ORDER = ['product-analytics-kb', 'data-warehouse-kb', 'customer-support-answers', 'pricing-and-packaging', 'engineering-house-rules', 'security-questionnaire-answers', 'people-policies'];
20
+ export function loadStarter(id) {
21
+ const f = path.join(startersDir(), id, 'starter.yaml');
22
+ if (!fs.existsSync(f))
23
+ throw new Error(`No starter "${id}". Starters: ${ORDER.join(', ')}`);
24
+ return { id, ...YAML.parse(fs.readFileSync(f, 'utf8')) };
25
+ }
26
+ const PLACEHOLDER = /\{\{(\w+)(?:\|([^}]+))?\}\}/g;
27
+ const blankText = (k, label, owner) => `Not defined yet: ${label ?? k.replace(/_/g, ' ')}. Ask ${owner}.`;
28
+ /**
29
+ * A blank in the middle of a sentence ("Cutoffs use {{timezone}}.") would read as
30
+ * "Cutoffs use Not defined yet: …". Such a sentence becomes the blank sentence instead.
31
+ * A blank that reads as a value ("Warehouse: {{warehouse}}", or on a line of its own) stays inline.
32
+ */
33
+ function blankOutSentences(line, missing, owner) {
34
+ const lead = line.match(/^\s*(?:[-*]\s+|\d+\.\s+)?/)[0];
35
+ for (let guard = 0; guard < 20; guard++) {
36
+ let hit;
37
+ for (const m of line.matchAll(PLACEHOLDER)) {
38
+ if (!missing(m[1]))
39
+ continue;
40
+ const at = m.index, after = at + m[0].length;
41
+ const stop = line.lastIndexOf('. ', at - 1);
42
+ const start = stop >= lead.length ? stop + 2 : lead.length;
43
+ const dot = line.indexOf('.', after);
44
+ const end = dot < 0 ? line.length : dot + 1;
45
+ const before = line.slice(start, at).trim(), rest = line.slice(after, end).trim();
46
+ if ((!before || before.endsWith(':')) && /^\.?$/.test(rest))
47
+ continue;
48
+ const blanks = [...line.slice(start, end).matchAll(PLACEHOLDER)].filter(x => missing(x[1])).map(x => blankText(x[1], x[2], owner));
49
+ hit = { start, end, text: blanks.join(' ') };
50
+ break;
51
+ }
52
+ if (!hit)
53
+ return line;
54
+ line = line.slice(0, hit.start) + hit.text + line.slice(hit.end);
55
+ }
56
+ return line;
57
+ }
58
+ /** Fills {{key}} or {{key|Label}}. Missing values become visible blanks, never invented text. */
59
+ export function fill(tpl, vars, owner) {
60
+ const missing = (k) => !(vars[k] && vars[k].trim());
61
+ tpl = tpl.split('\n').map(l => blankOutSentences(l, missing, owner)).join('\n');
62
+ return tpl.replace(/\{\{(\w+)(?:\|([^}]+))?\}\}(\.?)/g, (_m, k, label, dot, at) => {
63
+ const v = vars[k];
64
+ if (v && v.trim()) {
65
+ const val = v.trim();
66
+ const lineStart = tpl.lastIndexOf('\n', at - 1) + 1;
67
+ const before = tpl.slice(lineStart, at);
68
+ // A list answer placed mid-line becomes an indented sub-list, so the Markdown stays valid.
69
+ if (val.includes('\n') && before.trim())
70
+ return '\n' + val.split('\n').map(l => `${' '.repeat(before.search(/\S|$/) + 2)}${l}`).join('\n');
71
+ // A one-item list placed mid-line reads as plain text, not "- item".
72
+ const text = before.trim() && val.startsWith('- ') ? val.slice(2) : val;
73
+ // An answer that already ends a sentence doesn't get the template's full stop too.
74
+ return text + (/[.!?]$/.test(text) ? '' : dot);
75
+ }
76
+ return blankText(k, label, owner);
77
+ });
78
+ }
79
+ const asList = (v) => v ? v.split(/\n|;|,(?![^(]*\))/).map(s => s.trim()).filter(Boolean).map(s => `- ${s}`).join('\n') : undefined;
80
+ /** Answers files may use YAML lists, numbers or blocks. Turn every answer into trimmed text; drop empty ones. */
81
+ export function normalizeAnswers(raw) {
82
+ const out = {};
83
+ for (const [k, v] of Object.entries(raw ?? {})) {
84
+ const s = Array.isArray(v) ? v.map(x => String(x ?? '').trim()).filter(Boolean).join('\n')
85
+ : v === null || v === undefined ? '' : typeof v === 'object' ? '' : String(v).trim();
86
+ if (s)
87
+ out[k] = s;
88
+ }
89
+ return out;
90
+ }
91
+ const SECTION_ID = /^[a-z0-9][a-z0-9-]{0,40}$/;
92
+ /**
93
+ * Lets an answers file fit the starter to the team's KB without forking it:
94
+ * kb_title: Royalty KB
95
+ * section_titles: { metrics: Royalty rules } # rename a section (its id stays)
96
+ * drop_sections: [dashboards] # leave a section out
97
+ * extra_sections: # add sections
98
+ * - { id: contracts, title: Contract terms, router: Which contract terms apply, content: "optional Markdown" }
99
+ */
100
+ export function shapeStarter(st, raw) {
101
+ const out = { ...st, sections: st.sections.map(s => ({ ...s })), router: { ...st.router } };
102
+ const titles = (raw.section_titles ?? {});
103
+ if (titles && typeof titles === 'object')
104
+ for (const [id, t] of Object.entries(titles)) {
105
+ const sec = out.sections.find(s => s.id === id);
106
+ if (!sec)
107
+ throw new Error(`section_titles: no section "${id}" in ${st.id}. Sections: ${st.sections.map(s => s.id).join(', ')}`);
108
+ if (t)
109
+ sec.title = String(t).trim();
110
+ }
111
+ const drop = Array.isArray(raw.drop_sections) ? raw.drop_sections.map(String) : [];
112
+ for (const id of drop) {
113
+ if (!out.sections.some(s => s.id === id))
114
+ throw new Error(`drop_sections: no section "${id}" in ${st.id}.`);
115
+ out.sections = out.sections.filter(s => s.id !== id);
116
+ delete out.router[id];
117
+ }
118
+ const extra = Array.isArray(raw.extra_sections) ? raw.extra_sections : [];
119
+ for (const x of extra) {
120
+ const id = String(x?.id ?? '').trim();
121
+ if (!SECTION_ID.test(id))
122
+ throw new Error(`extra_sections: "${id}" is not a usable id. Use lowercase letters, digits and dashes, e.g. contract-terms.`);
123
+ if (out.sections.some(s => s.id === id))
124
+ throw new Error(`extra_sections: "${id}" already exists. Rename it with section_titles instead.`);
125
+ const title = String(x.title ?? id).trim();
126
+ const content = typeof x.content === 'string' && x.content.trim() ? x.content.trim() : `Not defined yet: ${title}. Ask {{owner}}.`;
127
+ out.sections.push({ id, title, template: content });
128
+ out.router[id] = String(x.router ?? title).trim();
129
+ }
130
+ if (!out.sections.length)
131
+ throw new Error('Every section was dropped. Keep at least one.');
132
+ return out;
133
+ }
134
+ /** Creates a skill from a starter and interview answers. Unanswered questions stay visible blanks. */
135
+ export async function hatch(ws, starterId, rawAnswers, opts = {}) {
136
+ const st = shapeStarter(loadStarter(starterId), rawAnswers ?? {});
137
+ const { section_titles: _t, drop_sections: _d, extra_sections: _e, ...plain } = rawAnswers ?? {};
138
+ const answers = normalizeAnswers(plain);
139
+ if (answers.kb_title)
140
+ st.title = answers.kb_title;
141
+ const name = opts.name ?? st.default_skill;
142
+ if (fs.existsSync(path.join(ws.skillDir(name), 'skill.yaml')))
143
+ throw new Error(`A skill called "${name}" already exists here.`);
144
+ const owner = opts.owner ?? answers.owner ?? ws.config.curator;
145
+ const vars = { ...answers, owner, org: ws.config.org, skill: name, title: st.title };
146
+ for (const q of st.interview)
147
+ if (q.list && answers[q.key])
148
+ vars[q.key] = asList(answers[q.key]);
149
+ vars.router = Object.entries(st.router).map(([sec, when]) => `- ${when} → section \`${sec}\``).join('\n');
150
+ vars.description = `${st.tagline} Curated by ${owner} at ${ws.config.org}. Use it for questions about ${st.title.toLowerCase()}.`;
151
+ const meta = { name, title: st.title, version: '0.1.0', owner, description: vars.description, starter: st.id, sections: st.sections.map(s => s.id), teams: answers.teams ? answers.teams.split(/,|;|\n/).map(s => s.trim()).filter(Boolean) : undefined };
152
+ fs.mkdirSync(ws.skillDir(name), { recursive: true });
153
+ const core = fs.readFileSync(path.join(startersDir(), '_core', 'SKILL.md'), 'utf8');
154
+ fs.writeFileSync(path.join(ws.skillDir(name), 'SKILL.md'), fill(core, vars, owner));
155
+ saveSkill(ws, meta);
156
+ const store = openStore(ws);
157
+ let blanks = 0, filled = 0;
158
+ try {
159
+ for (const s of st.sections) {
160
+ const md = fill(`# ${s.title}\n\n${s.template.trim()}\n`, vars, owner);
161
+ const n = (md.match(/Not defined yet:/g) ?? []).length;
162
+ blanks += n;
163
+ if (n === 0)
164
+ filled++;
165
+ await store.writeSection(meta, s.id, md);
166
+ }
167
+ }
168
+ catch (e) {
169
+ // Leave nothing half made, so the same command can simply be run again once the store is fixed.
170
+ fs.rmSync(ws.skillDir(name), { recursive: true, force: true });
171
+ throw e;
172
+ }
173
+ let tests = 0;
174
+ for (const t of st.tests) {
175
+ if (t.needs && !answers[t.needs])
176
+ continue;
177
+ const { needs, ...test } = t;
178
+ const deep = (v) => typeof v === 'string' ? fill(v, vars, owner) : Array.isArray(v) ? v.map(deep) : v && typeof v === 'object' ? Object.fromEntries(Object.entries(v).map(([k, x]) => [k, deep(x)])) : v;
179
+ const filledTest = deep(test);
180
+ saveTest(ws, name, { ...filledTest, seeded: true, verified_on: new Date().toISOString().slice(0, 10) });
181
+ tests++;
182
+ }
183
+ return { meta, blanks, filled, tests };
184
+ }