@dogfood-lab/findings 1.2.1
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.
- package/LICENSE +21 -0
- package/README.md +96 -0
- package/advise/advice-bundle.js +155 -0
- package/advise/index.js +5 -0
- package/advise/query.js +182 -0
- package/cli.js +936 -0
- package/derive/dedupe.js +107 -0
- package/derive/derive-findings.js +187 -0
- package/derive/ids.js +48 -0
- package/derive/index.js +9 -0
- package/derive/load-records.js +153 -0
- package/derive/rules.js +415 -0
- package/derive/write-findings.js +63 -0
- package/index.js +11 -0
- package/lib/atomic-write.js +47 -0
- package/lib/file-lock.js +359 -0
- package/lib/rename-with-retry.js +43 -0
- package/package.json +70 -0
- package/reader.js +156 -0
- package/review/event-log.js +177 -0
- package/review/index.js +6 -0
- package/review/review-engine.js +288 -0
- package/review/transitions.js +79 -0
- package/synthesis/doctrine-derivation.js +128 -0
- package/synthesis/index.js +8 -0
- package/synthesis/pattern-derivation.js +184 -0
- package/synthesis/recommendation-derivation.js +156 -0
- package/synthesis/validate-artifacts.js +46 -0
- package/synthesis/write-artifacts.js +75 -0
- package/validate.js +87 -0
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deterministic pattern derivation from accepted findings.
|
|
3
|
+
*
|
|
4
|
+
* Clusters accepted, non-invalidated findings by shared dimensions:
|
|
5
|
+
* issue_kind + root_cause_kind + (optionally) product_surface
|
|
6
|
+
*
|
|
7
|
+
* A pattern candidate forms when 2+ accepted findings share these dimensions.
|
|
8
|
+
*/
|
|
9
|
+
|
|
10
|
+
import { loadFindings } from '../reader.js';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Derive candidate patterns from accepted findings.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} rootDir - dogfood-labs repo root
|
|
16
|
+
* @param {{ includeFixtures?: boolean }} opts
|
|
17
|
+
* @returns {{ patterns: Array, stats: { findingsConsidered: number, clustersFound: number, belowThreshold: number } }}
|
|
18
|
+
*/
|
|
19
|
+
export function derivePatterns(rootDir, opts = {}) {
|
|
20
|
+
// Load only accepted, non-invalidated findings
|
|
21
|
+
const allFindings = loadFindings(rootDir);
|
|
22
|
+
if (opts.includeFixtures) {
|
|
23
|
+
allFindings.push(...loadFindings(rootDir, { fixtures: true, fixtureKind: 'valid' }));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const accepted = allFindings.filter(f =>
|
|
27
|
+
f.valid &&
|
|
28
|
+
f.data?.status === 'accepted' &&
|
|
29
|
+
!f.data?.invalidation?.is_invalidated
|
|
30
|
+
);
|
|
31
|
+
|
|
32
|
+
// Cluster by shared dimensions
|
|
33
|
+
const clusters = new Map();
|
|
34
|
+
|
|
35
|
+
for (const f of accepted) {
|
|
36
|
+
const d = f.data;
|
|
37
|
+
const key = buildClusterKey(d);
|
|
38
|
+
|
|
39
|
+
if (!clusters.has(key)) {
|
|
40
|
+
clusters.set(key, {
|
|
41
|
+
issue_kind: d.issue_kind,
|
|
42
|
+
root_cause_kind: d.root_cause_kind,
|
|
43
|
+
remediation_kind: d.remediation_kind,
|
|
44
|
+
findings: []
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
clusters.get(key).findings.push(d);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// Filter clusters to those meeting threshold (2+ findings)
|
|
51
|
+
const patterns = [];
|
|
52
|
+
let belowThreshold = 0;
|
|
53
|
+
|
|
54
|
+
for (const [key, cluster] of clusters) {
|
|
55
|
+
if (cluster.findings.length < 2) {
|
|
56
|
+
belowThreshold++;
|
|
57
|
+
continue;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Check for false recurrence: all from same repo AND same source record
|
|
61
|
+
if (isFalseRecurrence(cluster.findings)) {
|
|
62
|
+
belowThreshold++;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
patterns.push(buildPatternCandidate(cluster));
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
return {
|
|
70
|
+
patterns,
|
|
71
|
+
stats: {
|
|
72
|
+
findingsConsidered: accepted.length,
|
|
73
|
+
clustersFound: clusters.size,
|
|
74
|
+
belowThreshold
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Build a cluster key from shared dimensions.
|
|
81
|
+
*/
|
|
82
|
+
function buildClusterKey(finding) {
|
|
83
|
+
return `${finding.issue_kind}::${finding.root_cause_kind}`;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Check for false recurrence: all findings from same root incident.
|
|
88
|
+
*/
|
|
89
|
+
function isFalseRecurrence(findings) {
|
|
90
|
+
// If all findings share exact same source_record_ids set, it's likely one incident split by extraction
|
|
91
|
+
if (findings.length < 2) return true;
|
|
92
|
+
|
|
93
|
+
const recordSets = findings.map(f => (f.source_record_ids || []).sort().join(','));
|
|
94
|
+
const unique = new Set(recordSets);
|
|
95
|
+
return unique.size === 1; // All from same records = false recurrence
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/**
|
|
99
|
+
* Build a pattern candidate from a cluster.
|
|
100
|
+
*/
|
|
101
|
+
function buildPatternCandidate(cluster) {
|
|
102
|
+
const { findings, issue_kind, root_cause_kind, remediation_kind } = cluster;
|
|
103
|
+
const now = new Date().toISOString();
|
|
104
|
+
|
|
105
|
+
// Compute support dimensions
|
|
106
|
+
const repos = new Set(findings.map(f => f.repo));
|
|
107
|
+
const surfaces = new Set(findings.map(f => f.product_surface));
|
|
108
|
+
const modes = new Set(findings.flatMap(f => f.execution_mode ? [f.execution_mode] : []));
|
|
109
|
+
const remediations = new Set(findings.map(f => f.remediation_kind));
|
|
110
|
+
|
|
111
|
+
// Determine transfer scope (widest from findings)
|
|
112
|
+
const scopes = findings.map(f => f.transfer_scope);
|
|
113
|
+
const transfer_scope = widenScope(scopes);
|
|
114
|
+
|
|
115
|
+
// Determine pattern kind
|
|
116
|
+
const pattern_kind = classifyPatternKind(issue_kind);
|
|
117
|
+
|
|
118
|
+
// Build slug — must include every dimension in the cluster key (issue_kind + root_cause_kind),
|
|
119
|
+
// otherwise two clusters that differ only by root_cause_kind collide on pattern_id and the
|
|
120
|
+
// second writePattern() silently overwrites the first on disk. Surface is added for readability,
|
|
121
|
+
// not for uniqueness.
|
|
122
|
+
const surfaceStr = surfaces.size === 1 ? [...surfaces][0] : 'multi-surface';
|
|
123
|
+
const slug = `${surfaceStr}-${issue_kind}-${root_cause_kind}`.replace(/_/g, '-');
|
|
124
|
+
|
|
125
|
+
// Determine strength
|
|
126
|
+
const strength = repos.size >= 3 ? 'strong' : repos.size >= 2 ? 'emerging' : 'emerging';
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
schema_version: '1.0.0',
|
|
130
|
+
pattern_id: `dpat-${slug}`,
|
|
131
|
+
title: buildPatternTitle(issue_kind, surfaces, repos.size),
|
|
132
|
+
status: 'candidate',
|
|
133
|
+
pattern_kind,
|
|
134
|
+
summary: buildPatternSummary(findings, issue_kind, root_cause_kind),
|
|
135
|
+
source_finding_ids: findings.map(f => f.finding_id),
|
|
136
|
+
support: {
|
|
137
|
+
finding_count: findings.length,
|
|
138
|
+
repo_count: repos.size,
|
|
139
|
+
surface_count: surfaces.size,
|
|
140
|
+
...(modes.size > 0 ? { execution_modes: [...modes] } : {})
|
|
141
|
+
},
|
|
142
|
+
dimensions: {
|
|
143
|
+
product_surfaces: [...surfaces],
|
|
144
|
+
issue_kinds: [issue_kind],
|
|
145
|
+
root_cause_kinds: [root_cause_kind],
|
|
146
|
+
remediation_kinds: [...remediations]
|
|
147
|
+
},
|
|
148
|
+
transfer_scope,
|
|
149
|
+
pattern_strength: strength,
|
|
150
|
+
lineage_note: `Derived from ${findings.length} accepted findings across ${repos.size} repo(s).`,
|
|
151
|
+
created_at: now,
|
|
152
|
+
updated_at: now
|
|
153
|
+
};
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
function classifyPatternKind(issueKind) {
|
|
157
|
+
if (/evidence/.test(issueKind)) return 'evidence_calibration';
|
|
158
|
+
if (/verification|provenance/.test(issueKind)) return 'verification_seam';
|
|
159
|
+
if (/policy|freshness/.test(issueKind)) return 'calibration_signal';
|
|
160
|
+
if (/build|entrypoint|flag|interface|surface/.test(issueKind)) return 'recurring_failure';
|
|
161
|
+
return 'recurring_failure';
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
function widenScope(scopes) {
|
|
165
|
+
const order = ['repo_local', 'surface_local', 'surface_archetype', 'execution_mode', 'org_wide'];
|
|
166
|
+
let widest = 0;
|
|
167
|
+
for (const s of scopes) {
|
|
168
|
+
const idx = order.indexOf(s);
|
|
169
|
+
if (idx > widest) widest = idx;
|
|
170
|
+
}
|
|
171
|
+
return order[widest];
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function buildPatternTitle(issueKind, surfaces, repoCount) {
|
|
175
|
+
const surfaceStr = surfaces.size === 1 ? `${[...surfaces][0]}` : `${surfaces.size} surfaces`;
|
|
176
|
+
const label = issueKind.replace(/_/g, ' ');
|
|
177
|
+
return `${label} recurs across ${repoCount} repo(s) on ${surfaceStr}`;
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function buildPatternSummary(findings, issueKind, rootCause) {
|
|
181
|
+
const repos = [...new Set(findings.map(f => f.repo))];
|
|
182
|
+
const repoNames = repos.map(r => r.split('/').pop()).join(', ');
|
|
183
|
+
return `Multiple accepted findings show ${issueKind.replace(/_/g, ' ')} caused by ${rootCause.replace(/_/g, ' ')} across repos: ${repoNames}. This recurrence indicates a structural pattern, not isolated incidents.`;
|
|
184
|
+
}
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Recommendation derivation from accepted patterns.
|
|
3
|
+
*
|
|
4
|
+
* Generates actionable guidance using constrained templates based on
|
|
5
|
+
* pattern kind, dimensions, and transfer scope.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { readFileSync, readdirSync, existsSync } from 'node:fs';
|
|
9
|
+
import { resolve, join } from 'node:path';
|
|
10
|
+
import yaml from 'js-yaml';
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Derive recommendations from accepted patterns.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} rootDir - dogfood-labs repo root
|
|
16
|
+
* @returns {{ recommendations: Array, stats: { patternsConsidered: number, recommendationsEmitted: number } }}
|
|
17
|
+
*/
|
|
18
|
+
export function deriveRecommendations(rootDir) {
|
|
19
|
+
const patterns = loadAcceptedPatterns(rootDir);
|
|
20
|
+
const recommendations = [];
|
|
21
|
+
|
|
22
|
+
for (const pat of patterns) {
|
|
23
|
+
const rec = deriveFromPattern(pat);
|
|
24
|
+
if (rec) recommendations.push(rec);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
return {
|
|
28
|
+
recommendations,
|
|
29
|
+
stats: {
|
|
30
|
+
patternsConsidered: patterns.length,
|
|
31
|
+
recommendationsEmitted: recommendations.length
|
|
32
|
+
}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* Derive a recommendation from a single accepted pattern.
|
|
38
|
+
*/
|
|
39
|
+
function deriveFromPattern(pattern) {
|
|
40
|
+
const now = new Date().toISOString();
|
|
41
|
+
const template = selectTemplate(pattern);
|
|
42
|
+
if (!template) return null;
|
|
43
|
+
|
|
44
|
+
const surfaces = pattern.dimensions?.product_surfaces || [];
|
|
45
|
+
const slug = `${surfaces[0] || 'general'}-${template.kind}`.replace(/_/g, '-');
|
|
46
|
+
|
|
47
|
+
return {
|
|
48
|
+
schema_version: '1.0.0',
|
|
49
|
+
recommendation_id: `drec-${slug}-${pattern.pattern_id.replace('dpat-', '')}`,
|
|
50
|
+
title: template.titleFn(pattern),
|
|
51
|
+
status: 'candidate',
|
|
52
|
+
recommendation_kind: template.kind,
|
|
53
|
+
summary: template.summaryFn(pattern),
|
|
54
|
+
applies_to: {
|
|
55
|
+
product_surfaces: surfaces,
|
|
56
|
+
...(pattern.support?.execution_modes?.length ? { execution_modes: pattern.support.execution_modes } : {}),
|
|
57
|
+
transfer_scope: pattern.transfer_scope
|
|
58
|
+
},
|
|
59
|
+
based_on_pattern_ids: [pattern.pattern_id],
|
|
60
|
+
action: {
|
|
61
|
+
type: template.actionType,
|
|
62
|
+
target: template.target,
|
|
63
|
+
details: template.detailsFn(pattern)
|
|
64
|
+
},
|
|
65
|
+
confidence: pattern.pattern_strength === 'strong' || pattern.pattern_strength === 'portfolio_stable' ? 'strong' : 'emerging',
|
|
66
|
+
created_at: now,
|
|
67
|
+
updated_at: now
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Select the right recommendation template for a pattern.
|
|
73
|
+
*/
|
|
74
|
+
function selectTemplate(pattern) {
|
|
75
|
+
const kind = pattern.pattern_kind;
|
|
76
|
+
const issueKinds = pattern.dimensions?.issue_kinds || [];
|
|
77
|
+
|
|
78
|
+
if (issueKinds.some(k => /interface|surface|entrypoint|build/.test(k))) {
|
|
79
|
+
return {
|
|
80
|
+
kind: 'starter_check',
|
|
81
|
+
actionType: 'add_check',
|
|
82
|
+
target: 'rollout',
|
|
83
|
+
titleFn: (p) => `Add ${issueKinds[0].replace(/_/g, ' ')} verification to starter rollout for ${fmtSurfaces(p)}`,
|
|
84
|
+
summaryFn: (p) => `New ${fmtSurfaces(p)} repos should verify ${issueKinds[0].replace(/_/g, ' ')} before rollout assumptions are encoded into scenarios or docs. This recurs across ${p.support.repo_count} repo(s).`,
|
|
85
|
+
detailsFn: (p) => `Verify ${issueKinds[0].replace(/_/g, ' ')} contract and invocation shape before scenario authoring for ${fmtSurfaces(p)} repos.`
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (kind === 'evidence_calibration') {
|
|
90
|
+
return {
|
|
91
|
+
kind: 'evidence_expectation',
|
|
92
|
+
actionType: 'set_evidence',
|
|
93
|
+
target: 'policy',
|
|
94
|
+
titleFn: (p) => `Calibrate evidence requirements for ${fmtSurfaces(p)} based on recurring miscalibration`,
|
|
95
|
+
summaryFn: (p) => `Evidence requirements for ${fmtSurfaces(p)} have been repeatedly miscalibrated. Default to natural output types rather than forced artifact shapes.`,
|
|
96
|
+
detailsFn: (p) => `Review and adjust evidence_requirements in surface policy to match natural outputs for ${fmtSurfaces(p)} repos.`
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
if (kind === 'verification_seam') {
|
|
101
|
+
return {
|
|
102
|
+
kind: 'verification_rule',
|
|
103
|
+
actionType: 'set_verification',
|
|
104
|
+
target: 'verification',
|
|
105
|
+
titleFn: (p) => `Add verification guard for ${issueKinds[0]?.replace(/_/g, ' ') || 'seam'} on ${fmtSurfaces(p)}`,
|
|
106
|
+
summaryFn: (p) => `A verification seam recurs on ${fmtSurfaces(p)}. Add a guard to prevent this class of verification failure.`,
|
|
107
|
+
detailsFn: (p) => `Add verification step to detect ${issueKinds[0]?.replace(/_/g, ' ') || 'verification gap'} before acceptance.`
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
if (kind === 'calibration_signal') {
|
|
112
|
+
return {
|
|
113
|
+
kind: 'policy_seed',
|
|
114
|
+
actionType: 'set_policy',
|
|
115
|
+
target: 'policy',
|
|
116
|
+
titleFn: (p) => `Seed ${fmtSurfaces(p)} policy with calibrated defaults from recurring pattern`,
|
|
117
|
+
summaryFn: (p) => `Policy miscalibration recurs on ${fmtSurfaces(p)}. Seed new repo policies with proven defaults.`,
|
|
118
|
+
detailsFn: (p) => `Apply calibrated policy defaults for ${fmtSurfaces(p)} repos based on ${p.support.finding_count} proven findings.`
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Default: starter_check
|
|
123
|
+
return {
|
|
124
|
+
kind: 'starter_check',
|
|
125
|
+
actionType: 'add_check',
|
|
126
|
+
target: 'rollout',
|
|
127
|
+
titleFn: (p) => `Add check for ${issueKinds[0]?.replace(/_/g, ' ') || 'recurring issue'} on ${fmtSurfaces(p)}`,
|
|
128
|
+
summaryFn: (p) => `A recurring issue pattern was detected on ${fmtSurfaces(p)}. Add a rollout check to prevent future occurrences.`,
|
|
129
|
+
detailsFn: (p) => `Add a rollout verification step for ${issueKinds[0]?.replace(/_/g, ' ') || 'this issue class'} on ${fmtSurfaces(p)} repos.`
|
|
130
|
+
};
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function fmtSurfaces(pattern) {
|
|
134
|
+
const s = pattern.dimensions?.product_surfaces || [];
|
|
135
|
+
return s.length ? s.join(', ') : 'general';
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
/**
|
|
139
|
+
* Load accepted patterns from disk.
|
|
140
|
+
*/
|
|
141
|
+
function loadAcceptedPatterns(rootDir) {
|
|
142
|
+
const dir = resolve(rootDir, 'patterns');
|
|
143
|
+
if (!existsSync(dir)) return [];
|
|
144
|
+
|
|
145
|
+
const patterns = [];
|
|
146
|
+
for (const file of readdirSync(dir)) {
|
|
147
|
+
if (!file.endsWith('.yaml')) continue;
|
|
148
|
+
try {
|
|
149
|
+
const data = yaml.load(readFileSync(join(dir, file), 'utf-8'));
|
|
150
|
+
if (data?.status === 'accepted') patterns.push(data);
|
|
151
|
+
} catch { /* skip */ }
|
|
152
|
+
}
|
|
153
|
+
return patterns;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export { loadAcceptedPatterns };
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Schema validation for pattern, recommendation, and doctrine artifacts.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { readFileSync } from 'node:fs';
|
|
6
|
+
import { dirname } from 'node:path';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
9
|
+
import addFormats from 'ajv-formats';
|
|
10
|
+
import yaml from 'js-yaml';
|
|
11
|
+
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
// Resolve the schemas package's json directory via its subpath export.
|
|
14
|
+
const SCHEMAS_DIR = dirname(
|
|
15
|
+
require.resolve('@dogfood-lab/schemas/json/dogfood-pattern.schema.json')
|
|
16
|
+
);
|
|
17
|
+
|
|
18
|
+
const _validators = {};
|
|
19
|
+
|
|
20
|
+
function getValidator(schemaFile) {
|
|
21
|
+
if (!_validators[schemaFile]) {
|
|
22
|
+
const schema = JSON.parse(readFileSync(`${SCHEMAS_DIR}/${schemaFile}`, 'utf-8'));
|
|
23
|
+
const ajv = new Ajv2020({ allErrors: true, strict: false });
|
|
24
|
+
addFormats(ajv);
|
|
25
|
+
_validators[schemaFile] = ajv.compile(schema);
|
|
26
|
+
}
|
|
27
|
+
return _validators[schemaFile];
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function validatePattern(data) {
|
|
31
|
+
const validate = getValidator('dogfood-pattern.schema.json');
|
|
32
|
+
const valid = validate(data);
|
|
33
|
+
return { valid, errors: valid ? [] : (validate.errors || []).map(e => ({ path: e.instancePath || '/', message: e.message })) };
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function validateRecommendation(data) {
|
|
37
|
+
const validate = getValidator('dogfood-recommendation.schema.json');
|
|
38
|
+
const valid = validate(data);
|
|
39
|
+
return { valid, errors: valid ? [] : (validate.errors || []).map(e => ({ path: e.instancePath || '/', message: e.message })) };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
export function validateDoctrine(data) {
|
|
43
|
+
const validate = getValidator('dogfood-doctrine.schema.json');
|
|
44
|
+
const valid = validate(data);
|
|
45
|
+
return { valid, errors: valid ? [] : (validate.errors || []).map(e => ({ path: e.instancePath || '/', message: e.message })) };
|
|
46
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Write pattern, recommendation, and doctrine artifacts to disk.
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
import { mkdirSync, existsSync, readdirSync, readFileSync } from 'node:fs';
|
|
6
|
+
import { resolve, join } from 'node:path';
|
|
7
|
+
import yaml from 'js-yaml';
|
|
8
|
+
|
|
9
|
+
import { atomicWriteFileSync } from '../lib/atomic-write.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Write a pattern to disk.
|
|
13
|
+
*/
|
|
14
|
+
export function writePattern(rootDir, pattern) {
|
|
15
|
+
const dir = resolve(rootDir, 'patterns');
|
|
16
|
+
mkdirSync(dir, { recursive: true });
|
|
17
|
+
const path = resolve(dir, `${pattern.pattern_id}.yaml`);
|
|
18
|
+
atomicWriteFileSync(path, yaml.dump(JSON.parse(JSON.stringify(pattern)), { lineWidth: 120, noRefs: true }));
|
|
19
|
+
return path;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* Write a recommendation to disk.
|
|
24
|
+
*/
|
|
25
|
+
export function writeRecommendation(rootDir, rec) {
|
|
26
|
+
const dir = resolve(rootDir, 'recommendations');
|
|
27
|
+
mkdirSync(dir, { recursive: true });
|
|
28
|
+
const path = resolve(dir, `${rec.recommendation_id}.yaml`);
|
|
29
|
+
atomicWriteFileSync(path, yaml.dump(JSON.parse(JSON.stringify(rec)), { lineWidth: 120, noRefs: true }));
|
|
30
|
+
return path;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Write a doctrine to disk.
|
|
35
|
+
*/
|
|
36
|
+
export function writeDoctrine(rootDir, doc) {
|
|
37
|
+
const dir = resolve(rootDir, 'doctrine');
|
|
38
|
+
mkdirSync(dir, { recursive: true });
|
|
39
|
+
const path = resolve(dir, `${doc.doctrine_id}.yaml`);
|
|
40
|
+
atomicWriteFileSync(path, yaml.dump(JSON.parse(JSON.stringify(doc)), { lineWidth: 120, noRefs: true }));
|
|
41
|
+
return path;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Load all patterns from disk.
|
|
46
|
+
*/
|
|
47
|
+
export function loadPatterns(rootDir) {
|
|
48
|
+
return loadArtifacts(resolve(rootDir, 'patterns'));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Load all recommendations from disk.
|
|
53
|
+
*/
|
|
54
|
+
export function loadRecommendations(rootDir) {
|
|
55
|
+
return loadArtifacts(resolve(rootDir, 'recommendations'));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Load all doctrines from disk.
|
|
60
|
+
*/
|
|
61
|
+
export function loadDoctrines(rootDir) {
|
|
62
|
+
return loadArtifacts(resolve(rootDir, 'doctrine'));
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function loadArtifacts(dir) {
|
|
66
|
+
if (!existsSync(dir)) return [];
|
|
67
|
+
return readdirSync(dir)
|
|
68
|
+
.filter(f => f.endsWith('.yaml'))
|
|
69
|
+
.map(f => {
|
|
70
|
+
try {
|
|
71
|
+
return yaml.load(readFileSync(join(dir, f), 'utf-8'));
|
|
72
|
+
} catch { return null; }
|
|
73
|
+
})
|
|
74
|
+
.filter(Boolean);
|
|
75
|
+
}
|
package/validate.js
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Finding schema validator.
|
|
3
|
+
* Validates YAML finding files against dogfood-finding.schema.json.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { readFileSync } from 'node:fs';
|
|
7
|
+
import { createRequire } from 'node:module';
|
|
8
|
+
import Ajv2020 from 'ajv/dist/2020.js';
|
|
9
|
+
import addFormats from 'ajv-formats';
|
|
10
|
+
import yaml from 'js-yaml';
|
|
11
|
+
|
|
12
|
+
const require = createRequire(import.meta.url);
|
|
13
|
+
|
|
14
|
+
/** Load and compile the finding schema once. */
|
|
15
|
+
function createValidator() {
|
|
16
|
+
const schemaPath = require.resolve('@dogfood-lab/schemas/json/dogfood-finding.schema.json');
|
|
17
|
+
const schema = JSON.parse(readFileSync(schemaPath, 'utf-8'));
|
|
18
|
+
|
|
19
|
+
const ajv = new Ajv2020({ allErrors: true, strict: false });
|
|
20
|
+
addFormats(ajv);
|
|
21
|
+
|
|
22
|
+
return ajv.compile(schema);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
let _validator = null;
|
|
26
|
+
|
|
27
|
+
function getValidator() {
|
|
28
|
+
if (!_validator) {
|
|
29
|
+
_validator = createValidator();
|
|
30
|
+
}
|
|
31
|
+
return _validator;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Parse a YAML finding file and return the data.
|
|
36
|
+
* @param {string} filePath - Absolute path to a .yaml finding file.
|
|
37
|
+
* @returns {{ data: object | null, error: string | null }}
|
|
38
|
+
*/
|
|
39
|
+
export function parseFinding(filePath) {
|
|
40
|
+
try {
|
|
41
|
+
const raw = readFileSync(filePath, 'utf-8');
|
|
42
|
+
const data = yaml.load(raw);
|
|
43
|
+
if (!data || typeof data !== 'object') {
|
|
44
|
+
return { data: null, error: 'File did not parse to an object' };
|
|
45
|
+
}
|
|
46
|
+
return { data, error: null };
|
|
47
|
+
} catch (err) {
|
|
48
|
+
return { data: null, error: `YAML parse error: ${err.message}` };
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Validate a parsed finding object against the schema.
|
|
54
|
+
* @param {object} finding - Parsed finding data.
|
|
55
|
+
* @returns {{ valid: boolean, errors: Array<{ path: string, message: string }> }}
|
|
56
|
+
*/
|
|
57
|
+
export function validateFinding(finding) {
|
|
58
|
+
const validate = getValidator();
|
|
59
|
+
const valid = validate(finding);
|
|
60
|
+
|
|
61
|
+
if (valid) {
|
|
62
|
+
return { valid: true, errors: [] };
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const errors = (validate.errors || []).map(err => ({
|
|
66
|
+
path: err.instancePath || '/',
|
|
67
|
+
message: err.message || 'unknown error',
|
|
68
|
+
params: err.params
|
|
69
|
+
}));
|
|
70
|
+
|
|
71
|
+
return { valid: false, errors };
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Parse and validate a YAML finding file in one call.
|
|
76
|
+
* @param {string} filePath - Absolute path to a .yaml finding file.
|
|
77
|
+
* @returns {{ valid: boolean, data: object | null, errors: Array<{ path: string, message: string }> }}
|
|
78
|
+
*/
|
|
79
|
+
export function validateFindingFile(filePath) {
|
|
80
|
+
const { data, error } = parseFinding(filePath);
|
|
81
|
+
if (error) {
|
|
82
|
+
return { valid: false, data: null, errors: [{ path: '/', message: error }] };
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
const result = validateFinding(data);
|
|
86
|
+
return { ...result, data };
|
|
87
|
+
}
|