forked from garrytan/gbrain
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcheck-resolvable.ts
More file actions
662 lines (615 loc) · 25.3 KB
/
Copy pathcheck-resolvable.ts
File metadata and controls
662 lines (615 loc) · 25.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
/**
* check-resolvable.ts — Shared core function for resolver validation.
*
* Three call sites:
* 1. `bun test` — unit tests import and assert on checkResolvable()
* 2. `gbrain doctor` — runtime health check with actionable agent guidance
* 3. skill-creator skill — mandatory post-creation validation gate
*
* @param skillsDir — the `skills/` directory (NOT repo root). Parser joins
* this path with manifest paths like `query/SKILL.md`.
*/
import { readFileSync, existsSync, readdirSync } from 'fs';
import { join, relative } from 'path';
import { findResolverFile, findAllResolverFiles, RESOLVER_FILENAMES_LABEL } from './resolver-filenames.ts';
import { loadOrDeriveManifest } from './skill-manifest.ts';
import {
indexResolverTriggers,
lintRoutingFixtures,
loadRoutingFixtures,
runRoutingEval,
} from './routing-eval.ts';
import { runFilingAudit } from './filing-audit.ts';
import {
entriesToResolverContent,
findPrimaryResolverPath,
loadSkillTriggerIndex,
} from './skill-trigger-index.ts';
// ---------------------------------------------------------------------------
// Types
// ---------------------------------------------------------------------------
export interface ResolvableFix {
type: 'add_trigger' | 'remove_trigger' | 'add_frontmatter' | 'create_stub';
file: string;
section?: string;
skill_path?: string;
}
export interface ResolvableIssue {
type:
| 'unreachable'
| 'mece_overlap'
| 'mece_gap'
| 'dry_violation'
| 'missing_file'
| 'orphan_trigger'
// Check 5 (W2): routing eval results surfaced as advisories.
| 'routing_miss'
| 'routing_ambiguous'
| 'routing_false_positive'
| 'routing_fixture_lint'
// Check 6 (W3): brain-filing audit findings.
| 'filing_missing_writes_to'
| 'filing_unknown_directory'
// D-CX-9: scaffolded skill still carries SKILLIFY_STUB sentinel.
| 'skillify_stub_unreplaced';
severity: 'error' | 'warning';
skill: string;
message: string;
action: string;
fix?: ResolvableFix;
}
export interface ResolvableReport {
/**
* True when there are no error-severity issues. Warnings do NOT flip `ok`.
* Callers that want strict-mode (warnings fail CI too) should gate on
* `errors.length === 0 && warnings.length === 0`.
*/
ok: boolean;
/**
* Error-severity issues only. Determines `ok` and default exit codes.
* A subset of `issues[]`.
*/
errors: ResolvableIssue[];
/**
* Warning-severity issues. Informational by default; `--strict` promotes.
* A subset of `issues[]`.
*/
warnings: ResolvableIssue[];
/**
* @deprecated Use `errors` and `warnings` separately. Kept for one-release
* backwards compatibility; will be removed in v0.18. Equivalent to
* `[...errors, ...warnings]`.
*/
issues: ResolvableIssue[];
summary: {
total_skills: number;
reachable: number;
unreachable: number;
overlaps: number;
gaps: number;
};
}
export interface FixResult {
issue: ResolvableIssue;
applied: boolean;
detail: string;
}
// ---------------------------------------------------------------------------
// Internal helpers
// ---------------------------------------------------------------------------
/** Skills that intentionally overlap with many others (always-on, routers). */
const OVERLAP_WHITELIST = new Set([
'ingest', // router that delegates to idea-ingest, media-ingest, meeting-ingestion
'signal-detector', // always-on, fires on every message
'brain-ops', // always-on, every brain read/write
]);
export interface ResolverEntry {
trigger: string;
skillPath: string; // e.g., 'skills/query/SKILL.md'
isGStack: boolean; // GStack: X entries (external, skip file check)
section: string; // e.g., 'Brain operations'
}
/**
* Parse RESOLVER.md / AGENTS.md into structured entries. Supports two formats
* that can mix in one file:
*
* Format 1 (table) — original gbrain shape:
* | trigger phrase | `skills/<name>/SKILL.md` |
*
* Format 2 (compact list, v0.41.7.0) — OpenClaw-native shape:
* - **skill-name**: trigger1 | trigger2 | trigger3
* - skill-name: trigger1 | trigger2
*
* List-format constraints (v0.41.7.0):
* - Skill name MUST be kebab-lowercase (`[a-z][a-z0-9-]+`). Bold names
* like `**Note**`, `**Convention**`, `**TODO**` are deliberately
* skipped so prose bullets in real-world AGENTS.md files don't get
* mis-parsed as skill rows.
* - `skillPath` is ALWAYS derived as `skills/<name>/SKILL.md`. An
* optional `→ \`skills/path\`` (or ASCII `->`) suffix is stripped from
* the trigger string but NOT honored as the path: downstream consumers
* (`routing-eval.ts:skillSlugFromPath`, the manifest lookup at this
* file's :367) both assume the convention. For non-conventional paths,
* use the table format.
* - Multiple triggers fan out to one entry per trigger, all sharing the
* same `skillPath`. `checkResolvable` dedupes by `skillPath` downstream,
* so the integration reachability count counts each skill once.
*/
export function parseResolverEntries(resolverContent: string): ResolverEntry[] {
const entries: ResolverEntry[] = [];
let currentSection = '';
for (const line of resolverContent.split('\n')) {
// Track section headings
const headingMatch = line.match(/^##\s+(.+)/);
if (headingMatch) {
currentSection = headingMatch[1].trim();
continue;
}
// ── Format 1: Markdown table rows ──
if (line.startsWith('|') && !line.includes('---')) {
const cols = line.split('|').map(c => c.trim()).filter(Boolean);
if (cols.length < 2) continue;
const trigger = cols[0];
const skillCol = cols[1];
// Skip header rows
if (trigger.toLowerCase() === 'trigger' || trigger.toLowerCase() === 'skill') continue;
// GStack / external references (Check `ACCESS_POLICY.md`, Read X, GStack: Y)
if (skillCol.startsWith('GStack:') || skillCol.startsWith('Check ') || skillCol.startsWith('Read ')) {
entries.push({ trigger, skillPath: skillCol, isGStack: true, section: currentSection });
continue;
}
// Backtick-wrapped skill path
const pathMatch = skillCol.match(/`(skills\/[^`]+\/SKILL\.md)`/);
if (pathMatch) {
entries.push({ trigger, skillPath: pathMatch[1], isGStack: false, section: currentSection });
}
continue;
}
// ── Format 2: Compact list rows (v0.41.7.0) ──
// Bold form preferred: `- **skill-name**: trigger1 | trigger2`
// Plain fallback: `- skill-name: trigger1 | trigger2`
// Name regex is kebab-lowercase only so prose bullets like `- **Note**: …`
// don't false-match as skill rows (codex F2 / D4).
const listBold = line.match(/^-\s+\*\*([a-z][a-z0-9-]+)\*\*\s*:\s*(.+)$/);
const listPlain = listBold ? null : line.match(/^-\s+([a-z][a-z0-9-]+)\s*:\s*(.+)$/);
const listMatch = listBold ?? listPlain;
if (listMatch) {
const skillName = listMatch[1];
const triggersRaw = listMatch[2].trim();
// Strip optional explicit path suffix (D3: stripped, NOT captured).
// Both Unicode → and ASCII -> accepted; skillPath is always derived.
const cleaned = triggersRaw.replace(/\s*(?:→|->)\s*`skills\/[^`]+`\s*$/, '');
// Split on |, drop empty pieces and the literal `...` placeholder.
const triggers = cleaned
.split('|')
.map(t => t.trim())
.filter(t => t.length > 0 && t !== '...');
const skillPath = `skills/${skillName}/SKILL.md`;
// Multiple entries share skillPath; checkResolvable dedupes downstream.
for (const trigger of triggers) {
entries.push({ trigger, skillPath, isGStack: false, section: currentSection });
}
}
}
return entries;
}
// Manifest loading is now delegated to src/core/skill-manifest.ts
// (loadOrDeriveManifest). That module auto-derives from walking
// `skillsDir/*/SKILL.md` when manifest.json is missing — the scenario
// needed for AGENTS.md-only OpenClaw deployments. See D-CX-12 / F-ENG-1.
/** Simple YAML frontmatter parser — extracts triggers array if present. */
function extractTriggers(skillContent: string): string[] {
const fmMatch = skillContent.match(/^---\n([\s\S]*?)\n---/);
if (!fmMatch) return [];
const fm = fmMatch[1];
const triggersMatch = fm.match(/^triggers:\s*\n((?:\s+-\s+.+\n?)*)/m);
if (!triggersMatch) return [];
return triggersMatch[1]
.split('\n')
.map(l => l.replace(/^\s+-\s+/, '').replace(/^["']|["']$/g, '').trim())
.filter(Boolean);
}
/**
* Scan for inlined cross-cutting rules that should reference convention
* files. Each pattern can list multiple valid delegation targets — e.g.,
* notability rules live in both `conventions/quality.md` and
* `_brain-filing-rules.md`, and referencing either counts as delegation.
*/
export interface CrossCuttingPattern {
pattern: RegExp;
conventions: string[];
label: string;
}
export const CROSS_CUTTING_PATTERNS: CrossCuttingPattern[] = [
{ pattern: /iron\s*law.*back-?link/i,
conventions: ['conventions/quality.md'],
label: 'Iron Law back-linking' },
{ pattern: /citation.*format.*\[Source:/i,
conventions: ['conventions/quality.md'],
label: 'citation format rules' },
{ pattern: /notability.*gate/i,
conventions: ['conventions/quality.md', '_brain-filing-rules.md'],
label: 'notability gate' },
];
/** Proximity window (lines) within which a delegation reference suppresses
* a DRY match. Typical skill section is 20-30 lines; 40 covers header +
* section without leaking across document-length files. */
export const DRY_PROXIMITY_LINES = 40;
export interface DelegationRef {
convention: string; // normalized relative path, e.g., 'conventions/quality.md'
line: number; // 1-indexed line number of the reference
}
/**
* Extract delegation references from skill content. Recognizes three shapes:
* 1. `> **Convention:** ... \`skills/<path>\` ...`
* 2. `> **Filing rule:** ... \`skills/<path>\` ...`
* 3. Inline backtick `\`skills/conventions/*.md\`` or
* `\`skills/_brain-filing-rules.md\``
*
* Paths are normalized by stripping the leading `skills/` so they match the
* `conventions` field of CROSS_CUTTING_PATTERNS.
*/
export function extractDelegationTargets(content: string): DelegationRef[] {
const refs: DelegationRef[] = [];
const lines = content.split('\n');
// Match backtick-wrapped skills/ paths that point at a known delegation
// target. Scoped to conventions/ subtree and _brain-filing-rules.md.
const pathRe = /`skills\/((?:conventions\/[^`]+\.md)|(?:_brain-filing-rules\.md))`/g;
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
pathRe.lastIndex = 0;
let m: RegExpExecArray | null;
while ((m = pathRe.exec(line)) !== null) {
refs.push({ convention: m[1], line: i + 1 });
}
}
return refs;
}
// ---------------------------------------------------------------------------
// Main function
// ---------------------------------------------------------------------------
/**
* Validate that all skills are reachable from RESOLVER.md, detect MECE
* violations, and check for DRY issues.
*
* @param skillsDir — path to the `skills/` directory
*/
export function checkResolvable(skillsDir: string): ResolvableReport {
const issues: ResolvableIssue[] = [];
// Load inputs via the v0.41.11 shared primitive. UNION semantics
// across two surfaces:
// 1. Per-skill SKILL.md frontmatter `triggers:` (canonical) — every
// skill ships its own triggers; new skills don't need a
// RESOLVER.md row to be reachable.
// 2. Curated RESOLVER.md / AGENTS.md rows from skillsDir AND parent
// directory (D-CX-14 OpenClaw workspace-root layout preserved).
//
// Frontmatter is the source of truth (closes the #1451 drift class);
// RESOLVER.md rows still contribute additively so the human-readable
// dispatcher map stays load-bearing. See src/core/skill-trigger-index.ts.
const triggerEntries = loadSkillTriggerIndex(skillsDir);
// Primary RESOLVER.md path is still needed for error messages and
// --fix targets that have to point at a concrete file. When neither
// RESOLVER.md nor AGENTS.md exists but frontmatter triggers DO
// populate the index, fall back to a suggested path so `fix:` blocks
// still have a concrete target (auto-fix paths that touch RESOLVER.md
// will create it on first write).
const resolverPathOrNull = findPrimaryResolverPath(skillsDir);
const resolverPath = resolverPathOrNull ?? join(skillsDir, 'RESOLVER.md');
if (!resolverPathOrNull && triggerEntries.length === 0) {
// No RESOLVER.md / AGENTS.md anywhere AND no skill ships frontmatter
// triggers — the resolver tree is fully empty. Preserve the
// original 'missing_file' error semantics so doctor's UX doesn't
// regress for genuinely-uninitialized skills directories.
const suggested = join(skillsDir, 'RESOLVER.md');
const missingIssue: ResolvableIssue = {
type: 'missing_file',
severity: 'error',
skill: RESOLVER_FILENAMES_LABEL,
message: `${RESOLVER_FILENAMES_LABEL} not found in ${skillsDir} or its parent (and no SKILL.md frontmatter declares triggers:)`,
action: `Create ${suggested} with skill routing tables, or add 'triggers:' to each SKILL.md frontmatter`,
fix: { type: 'create_stub', file: suggested },
};
return {
ok: false,
errors: [missingIssue],
warnings: [],
issues: [missingIssue],
summary: { total_skills: 0, reachable: 0, unreachable: 0, overlaps: 0, gaps: 0 },
};
}
// Project to ResolverEntry[] shape that downstream code already
// consumes (source field is only needed for action-text routing).
const entries: ResolverEntry[] = triggerEntries;
// Build a synthesized resolver-content string for the routing-eval
// and lint stages that still take string content. Re-emits both
// frontmatter-derived AND RESOLVER.md-derived entries as one table.
const resolverContent = entriesToResolverContent(triggerEntries);
const { skills: manifest } = loadOrDeriveManifest(skillsDir);
// Build lookup sets
const resolverSkillPaths = new Set(
entries.filter(e => !e.isGStack).map(e => e.skillPath)
);
// 1. Check every manifest skill is reachable from RESOLVER.md
let reachable = 0;
let unreachable = 0;
for (const skill of manifest) {
const expectedPath = `skills/${skill.path}`;
if (resolverSkillPaths.has(expectedPath)) {
reachable++;
} else {
// Also check if the skill name appears in any resolver entry
const nameInResolver = entries.some(
e => e.skillPath.includes(skill.name) || e.trigger.includes(skill.name)
);
if (nameInResolver) {
reachable++;
} else {
unreachable++;
// Find the best section for this skill based on its description
const section = 'Brain operations'; // default suggestion
issues.push({
type: 'unreachable',
severity: 'error',
skill: skill.name,
message: `Skill '${skill.name}' is in manifest but has no trigger row in ${RESOLVER_FILENAMES_LABEL}`,
action: `Add a trigger row for 'skills/${skill.path}' in RESOLVER.md under ${section}`,
fix: {
type: 'add_trigger',
file: resolverPath,
section,
skill_path: `skills/${skill.path}`,
},
});
}
}
}
// 2. Check every resolver entry points to a file that exists
for (const entry of entries) {
if (entry.isGStack) continue;
// Resolver uses 'skills/query/SKILL.md', manifest uses 'query/SKILL.md'
// The file on disk is at skillsDir + 'query/SKILL.md'
const relPath = entry.skillPath.replace(/^skills\//, '');
const fullPath = join(skillsDir, relPath);
if (!existsSync(fullPath)) {
issues.push({
type: 'missing_file',
severity: 'error',
skill: entry.skillPath,
message: `RESOLVER.md references '${entry.skillPath}' but the file doesn't exist`,
action: `Create the skill at '${fullPath}' or remove the resolver entry`,
fix: { type: 'create_stub', file: fullPath },
});
}
// Check if in manifest
const skillName = relPath.replace(/\/SKILL\.md$/, '');
const inManifest = manifest.some(s => s.name === skillName);
if (!inManifest && existsSync(fullPath)) {
issues.push({
type: 'orphan_trigger',
severity: 'warning',
skill: skillName,
message: `RESOLVER.md has a trigger for '${skillName}' which is not in manifest.json`,
action: `Register '${skillName}' in skills/manifest.json or remove from RESOLVER.md`,
fix: { type: 'remove_trigger', file: resolverPath, skill_path: entry.skillPath },
});
}
}
// 3. MECE overlap detection
let overlaps = 0;
// Build trigger→skill map from SKILL.md frontmatter triggers
const triggerMap = new Map<string, string[]>();
for (const skill of manifest) {
const skillPath = join(skillsDir, skill.path);
if (!existsSync(skillPath)) continue;
try {
const content = readFileSync(skillPath, 'utf-8');
const triggers = extractTriggers(content);
for (const t of triggers) {
const normalized = t.toLowerCase().trim();
if (!triggerMap.has(normalized)) triggerMap.set(normalized, []);
triggerMap.get(normalized)!.push(skill.name);
}
} catch {
// Skip unreadable files
}
}
for (const [trigger, skills] of triggerMap) {
if (skills.length <= 1) continue;
// Filter out whitelisted skills
const nonWhitelisted = skills.filter(s => !OVERLAP_WHITELIST.has(s));
if (nonWhitelisted.length <= 1) continue;
overlaps++;
issues.push({
type: 'mece_overlap',
severity: 'warning',
skill: nonWhitelisted.join(', '),
message: `Trigger '${trigger}' matches multiple skills: ${nonWhitelisted.join(', ')}`,
action: `Add disambiguation rule in RESOLVER.md or narrow triggers in one skill's frontmatter`,
});
}
// 4. Gap detection — skills with no triggers in frontmatter
let gaps = 0;
for (const skill of manifest) {
if (OVERLAP_WHITELIST.has(skill.name)) continue; // always-on don't need triggers
const skillPath = join(skillsDir, skill.path);
if (!existsSync(skillPath)) continue;
try {
const content = readFileSync(skillPath, 'utf-8');
const triggers = extractTriggers(content);
if (triggers.length === 0) {
gaps++;
issues.push({
type: 'mece_gap',
severity: 'warning',
skill: skill.name,
message: `Skill '${skill.name}' has no triggers: field in its SKILL.md frontmatter`,
action: `Add a triggers: array to the frontmatter of skills/${skill.path}`,
fix: {
type: 'add_frontmatter',
file: skillPath,
skill_path: `skills/${skill.path}`,
},
});
}
} catch {
// Skip unreadable
}
}
// 5. DRY detection — inlined cross-cutting rules.
// A match is suppressed when the skill references one of the pattern's
// accepted convention files within DRY_PROXIMITY_LINES lines of the match.
// This catches the common case where a skill delegates at a section
// header but still contains prose mentioning the rule by name.
for (const skill of manifest) {
const skillPath = join(skillsDir, skill.path);
if (!existsSync(skillPath)) continue;
try {
const content = readFileSync(skillPath, 'utf-8');
const delegations = extractDelegationTargets(content);
for (const { pattern, conventions, label } of CROSS_CUTTING_PATTERNS) {
const globalRe = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g');
const matches = [...content.matchAll(globalRe)];
for (const m of matches) {
const matchLine = content.slice(0, m.index ?? 0).split('\n').length;
const suppressed = delegations.some(
d => conventions.includes(d.convention) && Math.abs(d.line - matchLine) <= DRY_PROXIMITY_LINES
);
if (suppressed) continue;
issues.push({
type: 'dry_violation',
severity: 'warning',
skill: skill.name,
message: `Skill '${skill.name}' inlines ${label} instead of delegating to a convention file`,
action: `Replace inlined rules with a reference to one of: ${conventions.join(', ')}`,
});
break; // one issue per pattern per skill
}
}
} catch {
// Skip unreadable
}
}
// Check 5 (W2, v0.17): structural routing eval. Surfaces as warnings
// only — routing issues are advisory. Agents running under --strict
// will fail on them; default runs see them as informational.
const loaded = loadRoutingFixtures(skillsDir);
if (loaded.fixtures.length > 0) {
const triggerIndex = indexResolverTriggers(resolverContent);
const lintIssues = lintRoutingFixtures(loaded.fixtures, triggerIndex);
for (const lint of lintIssues) {
issues.push({
type: 'routing_fixture_lint',
severity: 'warning',
skill: lint.fixture.expected_skill ?? 'unknown',
message: `Routing fixture lint (${lint.reason}): "${lint.fixture.intent}"`,
action: `Edit skills/<skill>/routing-eval.jsonl to fix: ${lint.detail}`,
});
}
const routingReport = runRoutingEval(resolverContent, loaded.fixtures);
for (const d of routingReport.details) {
if (d.outcome === 'pass') continue;
const kind =
d.outcome === 'missed'
? 'routing_miss'
: d.outcome === 'ambiguous'
? 'routing_ambiguous'
: 'routing_false_positive';
const skillName = d.fixture.expected_skill ?? 'negative-case';
// v0.41.11: triggers live in SKILL.md frontmatter (canonical) AND
// RESOLVER.md rows. Point the agent at the canonical surface
// first; the dispatcher map is the secondary edit point.
const editTarget = d.fixture.expected_skill
? `skills/${d.fixture.expected_skill}/SKILL.md frontmatter triggers: (canonical) or skills/RESOLVER.md row (dispatcher map)`
: `the relevant skill's SKILL.md frontmatter triggers:`;
issues.push({
type: kind,
severity: 'warning',
skill: skillName,
message: `Routing ${d.outcome} for intent "${d.fixture.intent}"`,
action: `Update routing-eval.jsonl fixture or broaden ${editTarget} (${d.note ?? 'no additional detail'})`,
});
}
}
for (const m of loaded.malformed) {
issues.push({
type: 'routing_fixture_lint',
severity: 'warning',
skill: 'routing-eval',
message: `Malformed routing fixture ${m.file}:${m.line}`,
action: `Fix the JSONL in routing-eval.jsonl at line ${m.line}: ${m.error}`,
});
}
// D-CX-9 SKILLIFY_STUB sentinel check: scan every SKILL.md + script
// file under skillsDir for the sentinel marker emitted by
// `gbrain skillify scaffold`. Presence means a scaffolded skill
// shipped without a real implementation — warning-severity in
// default mode, error-promoted under --strict via D-CX-3.
for (const skill of manifest) {
const skillDir = join(skillsDir, skill.path.replace(/\/SKILL\.md$/, ''));
const scriptDir = join(skillDir, 'scripts');
const candidates: string[] = [join(skillsDir, skill.path)];
if (existsSync(scriptDir)) {
try {
for (const f of readdirSync(scriptDir)) {
if (f.match(/\.(ts|mjs|js|py)$/)) candidates.push(join(scriptDir, f));
}
} catch {
// Skip unreadable script dir.
}
}
for (const candidate of candidates) {
try {
const content = readFileSync(candidate, 'utf-8');
if (content.includes('SKILLIFY_STUB: replace before running check-resolvable --strict')) {
issues.push({
type: 'skillify_stub_unreplaced',
severity: 'warning',
skill: skill.name,
message: `Skill '${skill.name}' still contains the SKILLIFY_STUB sentinel in ${relative(skillsDir, candidate)}`,
action: `Replace the SKILLIFY_STUB sentinel in ${candidate} with a real implementation or remove the file. D-CX-9 gate.`,
});
break; // one issue per skill
}
} catch {
// Skip unreadable file.
}
}
}
// Check 6 (W3, v0.17): brain-filing audit. Warning-only per
// D-CX-3 + D-CX-5 — does not break CI for workspaces that haven't
// adopted writes_pages:/writes_to: yet. Any errors in the rules
// doc itself surface as a single fatal-ish entry.
try {
const filingReport = runFilingAudit(skillsDir);
for (const issue of filingReport.issues) {
issues.push(issue);
}
} catch (err) {
issues.push({
type: 'filing_unknown_directory',
severity: 'warning',
skill: 'brain-filing-rules',
message: `_brain-filing-rules.json failed to load`,
action: `Fix skills/_brain-filing-rules.json: ${(err as Error).message}`,
});
}
const errors = issues.filter(i => i.severity === 'error');
const warnings = issues.filter(i => i.severity === 'warning');
return {
ok: errors.length === 0,
errors,
warnings,
issues,
summary: {
total_skills: manifest.length,
reachable,
unreachable,
overlaps,
gaps,
},
};
}
// Re-export auto-fix so callers have one canonical entry point.
export { autoFixDryViolations } from './dry-fix.ts';
export type { AutoFixOptions, AutoFixReport, FixOutcome } from './dry-fix.ts';