@h-rig/docs-drift-plugin 0.0.6-alpha.156
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/README.md +1 -0
- package/dist/src/drift/detect.d.ts +11 -0
- package/dist/src/drift/detect.js +299 -0
- package/dist/src/drift/extract-refs.d.ts +7 -0
- package/dist/src/drift/extract-refs.js +60 -0
- package/dist/src/drift/git-adapter.d.ts +7 -0
- package/dist/src/drift/git-adapter.js +63 -0
- package/dist/src/drift/judge.d.ts +19 -0
- package/dist/src/drift/judge.js +16 -0
- package/dist/src/drift/metadata.d.ts +13 -0
- package/dist/src/drift/metadata.js +35 -0
- package/dist/src/drift/plugin.d.ts +53 -0
- package/dist/src/drift/plugin.js +509 -0
- package/dist/src/drift/summary.d.ts +24 -0
- package/dist/src/drift/summary.js +42 -0
- package/dist/src/plugin.d.ts +9 -0
- package/dist/src/plugin.js +665 -0
- package/package.json +33 -0
|
@@ -0,0 +1,509 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/docs-drift-plugin/src/drift/detect.ts
|
|
3
|
+
import { existsSync } from "fs";
|
|
4
|
+
import { readdir, readFile, stat } from "fs/promises";
|
|
5
|
+
import { basename, extname, relative, resolve } from "path";
|
|
6
|
+
|
|
7
|
+
// packages/docs-drift-plugin/src/drift/extract-refs.ts
|
|
8
|
+
var INLINE_CODE = /`([^`\n]+)`/g;
|
|
9
|
+
var MARKDOWN_LINK = /\[[^\]]+\]\(([^)\s]+)\)/g;
|
|
10
|
+
var SYMBOL_REF = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?$/;
|
|
11
|
+
var PATH_REF = /^(?:\.\.?\/)?(?:[A-Za-z0-9_.-]+\/)+[A-Za-z0-9_.-]+$|^[A-Za-z0-9_.-]+\.(?:ts|tsx|js|jsx|mjs|cjs|json|md|mdx|css|scss|html|yml|yaml|toml|rs|go|py|rb|java|kt|swift|c|cc|cpp|h|hpp)$/;
|
|
12
|
+
function stripFenceLines(markdown) {
|
|
13
|
+
const lines = markdown.split(/\r?\n/);
|
|
14
|
+
let fenced = false;
|
|
15
|
+
return lines.map((line) => {
|
|
16
|
+
if (/^\s*(```|~~~)/.test(line)) {
|
|
17
|
+
fenced = !fenced;
|
|
18
|
+
return "";
|
|
19
|
+
}
|
|
20
|
+
return fenced ? "" : line;
|
|
21
|
+
});
|
|
22
|
+
}
|
|
23
|
+
function normalizeToken(raw) {
|
|
24
|
+
return raw.trim().replace(/^['"]|['"]$/g, "").replace(/[),.;:]+$/g, "").replace(/#L\d+(?:-L\d+)?$/i, "");
|
|
25
|
+
}
|
|
26
|
+
function classifyReference(raw) {
|
|
27
|
+
if (raw.startsWith("@"))
|
|
28
|
+
return null;
|
|
29
|
+
if (PATH_REF.test(raw))
|
|
30
|
+
return "path";
|
|
31
|
+
if (SYMBOL_REF.test(raw))
|
|
32
|
+
return "symbol";
|
|
33
|
+
return null;
|
|
34
|
+
}
|
|
35
|
+
function pushReference(refs, seen, raw, line) {
|
|
36
|
+
const value = normalizeToken(raw);
|
|
37
|
+
if (!value)
|
|
38
|
+
return;
|
|
39
|
+
const kind = classifyReference(value);
|
|
40
|
+
if (!kind)
|
|
41
|
+
return;
|
|
42
|
+
const key = `${kind}:${value}:${line}`;
|
|
43
|
+
if (seen.has(key))
|
|
44
|
+
return;
|
|
45
|
+
seen.add(key);
|
|
46
|
+
refs.push({ kind, value, line });
|
|
47
|
+
}
|
|
48
|
+
function extractDriftReferences(markdown) {
|
|
49
|
+
const refs = [];
|
|
50
|
+
const seen = new Set;
|
|
51
|
+
const lines = stripFenceLines(markdown);
|
|
52
|
+
for (const [index, line] of lines.entries()) {
|
|
53
|
+
const lineNumber = index + 1;
|
|
54
|
+
for (const match of line.matchAll(INLINE_CODE)) {
|
|
55
|
+
pushReference(refs, seen, match[1] ?? "", lineNumber);
|
|
56
|
+
}
|
|
57
|
+
for (const match of line.matchAll(MARKDOWN_LINK)) {
|
|
58
|
+
pushReference(refs, seen, match[1] ?? "", lineNumber);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return refs;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// packages/docs-drift-plugin/src/drift/git-adapter.ts
|
|
65
|
+
import { execFile } from "child_process";
|
|
66
|
+
import { promisify } from "util";
|
|
67
|
+
var execFileAsync = promisify(execFile);
|
|
68
|
+
function processError(value) {
|
|
69
|
+
return value && typeof value === "object" ? value : null;
|
|
70
|
+
}
|
|
71
|
+
function lineCount(output) {
|
|
72
|
+
const trimmed = output.trim();
|
|
73
|
+
return trimmed ? trimmed.split(/\r?\n/).length : 0;
|
|
74
|
+
}
|
|
75
|
+
function makeDriftGit(projectRoot) {
|
|
76
|
+
async function git(args) {
|
|
77
|
+
const result = await execFileAsync("git", [...args], {
|
|
78
|
+
cwd: projectRoot,
|
|
79
|
+
encoding: "utf8",
|
|
80
|
+
maxBuffer: 10 * 1024 * 1024
|
|
81
|
+
});
|
|
82
|
+
return String(result.stdout);
|
|
83
|
+
}
|
|
84
|
+
async function grepCountAt(symbolOrPath, commit) {
|
|
85
|
+
try {
|
|
86
|
+
return lineCount(await git(["grep", "-F", "-n", "-e", symbolOrPath, commit, "--"]));
|
|
87
|
+
} catch (error) {
|
|
88
|
+
const detail = processError(error);
|
|
89
|
+
if (detail?.code === 1)
|
|
90
|
+
return 0;
|
|
91
|
+
throw error;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return {
|
|
95
|
+
async lastCommitTouching(path) {
|
|
96
|
+
const commit = (await git(["log", "-n", "1", "--format=%H", "--", path])).trim();
|
|
97
|
+
return commit || "HEAD";
|
|
98
|
+
},
|
|
99
|
+
async grepCount(symbolOrPath) {
|
|
100
|
+
return grepCountAt(symbolOrPath, "HEAD");
|
|
101
|
+
},
|
|
102
|
+
async grepCountAtCommit(symbolOrPath, commit) {
|
|
103
|
+
return grepCountAt(symbolOrPath, commit);
|
|
104
|
+
},
|
|
105
|
+
async wasRenamed(symbolOrPath, sinceCommit) {
|
|
106
|
+
if (!symbolOrPath.includes("/") && !symbolOrPath.includes("."))
|
|
107
|
+
return false;
|
|
108
|
+
try {
|
|
109
|
+
const output = await git(["log", "--name-status", "--format=", `${sinceCommit}..HEAD`]);
|
|
110
|
+
return output.split(/\r?\n/).some((line) => {
|
|
111
|
+
const match = line.match(/^R\d*\s+(.+?)\s+(.+)$/);
|
|
112
|
+
return Boolean(match && (match[1] === symbolOrPath || match[2] === symbolOrPath));
|
|
113
|
+
});
|
|
114
|
+
} catch (error) {
|
|
115
|
+
const detail = processError(error);
|
|
116
|
+
if (detail?.code === 128)
|
|
117
|
+
return false;
|
|
118
|
+
throw error;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
};
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// packages/docs-drift-plugin/src/drift/detect.ts
|
|
125
|
+
var DEFAULT_IGNORED_DIRS = {
|
|
126
|
+
".git": true,
|
|
127
|
+
node_modules: true,
|
|
128
|
+
dist: true,
|
|
129
|
+
build: true,
|
|
130
|
+
coverage: true,
|
|
131
|
+
".next": true,
|
|
132
|
+
vendor: true
|
|
133
|
+
};
|
|
134
|
+
var SOURCE_EXTENSIONS = {
|
|
135
|
+
".ts": true,
|
|
136
|
+
".tsx": true,
|
|
137
|
+
".js": true,
|
|
138
|
+
".jsx": true,
|
|
139
|
+
".mjs": true,
|
|
140
|
+
".cjs": true,
|
|
141
|
+
".rs": true,
|
|
142
|
+
".go": true,
|
|
143
|
+
".py": true,
|
|
144
|
+
".rb": true,
|
|
145
|
+
".java": true,
|
|
146
|
+
".kt": true,
|
|
147
|
+
".swift": true,
|
|
148
|
+
".c": true,
|
|
149
|
+
".cc": true,
|
|
150
|
+
".cpp": true,
|
|
151
|
+
".h": true,
|
|
152
|
+
".hpp": true,
|
|
153
|
+
".json": true,
|
|
154
|
+
".toml": true,
|
|
155
|
+
".yml": true,
|
|
156
|
+
".yaml": true
|
|
157
|
+
};
|
|
158
|
+
function globLikeMatch(path, pattern) {
|
|
159
|
+
if (pattern === path)
|
|
160
|
+
return true;
|
|
161
|
+
if (pattern.startsWith("**/*"))
|
|
162
|
+
return path.endsWith(pattern.slice(4));
|
|
163
|
+
if (pattern.endsWith("/**"))
|
|
164
|
+
return path.startsWith(pattern.slice(0, -3));
|
|
165
|
+
if (pattern.includes("*")) {
|
|
166
|
+
const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
|
|
167
|
+
return new RegExp(`^${escaped}$`).test(path);
|
|
168
|
+
}
|
|
169
|
+
return path.startsWith(pattern);
|
|
170
|
+
}
|
|
171
|
+
function isDefaultDoc(path) {
|
|
172
|
+
const lower = basename(path).toLowerCase();
|
|
173
|
+
return (path.endsWith(".md") || path.endsWith(".mdx")) && !lower.startsWith("changelog") && !lower.includes("generated");
|
|
174
|
+
}
|
|
175
|
+
function isIgnored(path, patterns) {
|
|
176
|
+
return (patterns ?? []).some((pattern) => globLikeMatch(path, pattern));
|
|
177
|
+
}
|
|
178
|
+
async function collectFiles(root, options) {
|
|
179
|
+
const files = [];
|
|
180
|
+
async function visit(dir) {
|
|
181
|
+
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
|
182
|
+
if (entry.isDirectory() && DEFAULT_IGNORED_DIRS[entry.name])
|
|
183
|
+
continue;
|
|
184
|
+
const absolute = resolve(dir, entry.name);
|
|
185
|
+
const rel = relative(root, absolute).replace(/\\/g, "/");
|
|
186
|
+
if (isIgnored(rel, options.ignore))
|
|
187
|
+
continue;
|
|
188
|
+
if (entry.isDirectory()) {
|
|
189
|
+
await visit(absolute);
|
|
190
|
+
continue;
|
|
191
|
+
}
|
|
192
|
+
if (!entry.isFile())
|
|
193
|
+
continue;
|
|
194
|
+
if (options.docs) {
|
|
195
|
+
const matchesConfigured = options.patterns && options.patterns.length > 0 ? options.patterns.some((pattern) => globLikeMatch(rel, pattern)) : isDefaultDoc(rel);
|
|
196
|
+
if (matchesConfigured)
|
|
197
|
+
files.push(rel);
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
if (SOURCE_EXTENSIONS[extname(entry.name)])
|
|
201
|
+
files.push(rel);
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
await visit(root);
|
|
205
|
+
return files.sort();
|
|
206
|
+
}
|
|
207
|
+
async function sourceReferenceCount(projectRoot, reference, docPath) {
|
|
208
|
+
if (reference.kind === "path")
|
|
209
|
+
return existsSync(resolve(projectRoot, reference.value)) ? 1 : 0;
|
|
210
|
+
let count = 0;
|
|
211
|
+
const sourceFiles = await collectFiles(projectRoot, { docs: false });
|
|
212
|
+
for (const sourceFile of sourceFiles) {
|
|
213
|
+
if (sourceFile === docPath)
|
|
214
|
+
continue;
|
|
215
|
+
const text = await readFile(resolve(projectRoot, sourceFile), "utf8").catch(() => "");
|
|
216
|
+
if (text.includes(reference.value))
|
|
217
|
+
count += 1;
|
|
218
|
+
}
|
|
219
|
+
return count;
|
|
220
|
+
}
|
|
221
|
+
function deletedReferenceFinding(docPath, reference) {
|
|
222
|
+
return {
|
|
223
|
+
kind: "deleted-reference",
|
|
224
|
+
docPath,
|
|
225
|
+
line: reference.line,
|
|
226
|
+
reference: reference.value,
|
|
227
|
+
detail: `Documented reference "${reference.value}" no longer exists in the source tree.`,
|
|
228
|
+
confidence: "high"
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
function staleAnchorFinding(docPath, reference) {
|
|
232
|
+
return {
|
|
233
|
+
kind: "stale-anchor",
|
|
234
|
+
docPath,
|
|
235
|
+
line: reference.line,
|
|
236
|
+
reference: reference.value,
|
|
237
|
+
detail: `Documented path "${reference.value}" changed after this doc was last updated.`,
|
|
238
|
+
confidence: "medium"
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
async function detectDeletedReferences(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
|
|
242
|
+
const markdown = await readFile(resolve(projectRoot, docPath), "utf8");
|
|
243
|
+
const docCommit = await git.lastCommitTouching(docPath);
|
|
244
|
+
const findings = [];
|
|
245
|
+
for (const reference of extractDriftReferences(markdown)) {
|
|
246
|
+
if (await sourceReferenceCount(projectRoot, reference, docPath) > 0)
|
|
247
|
+
continue;
|
|
248
|
+
if (await git.wasRenamed(reference.value, docCommit))
|
|
249
|
+
continue;
|
|
250
|
+
findings.push(deletedReferenceFinding(docPath, reference));
|
|
251
|
+
}
|
|
252
|
+
return findings;
|
|
253
|
+
}
|
|
254
|
+
async function detectStaleAnchors(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
|
|
255
|
+
const markdown = await readFile(resolve(projectRoot, docPath), "utf8");
|
|
256
|
+
const docCommit = await git.lastCommitTouching(docPath);
|
|
257
|
+
const findings = [];
|
|
258
|
+
for (const reference of extractDriftReferences(markdown).filter((ref) => ref.kind === "path")) {
|
|
259
|
+
if (!existsSync(resolve(projectRoot, reference.value)))
|
|
260
|
+
continue;
|
|
261
|
+
const sourceStat = await stat(resolve(projectRoot, reference.value)).catch(() => null);
|
|
262
|
+
if (!sourceStat?.isFile())
|
|
263
|
+
continue;
|
|
264
|
+
const sourceCommit = await git.lastCommitTouching(reference.value);
|
|
265
|
+
if (sourceCommit !== docCommit && !await git.wasRenamed(reference.value, docCommit)) {
|
|
266
|
+
findings.push(staleAnchorFinding(docPath, reference));
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
return findings;
|
|
270
|
+
}
|
|
271
|
+
async function detectDrift(options) {
|
|
272
|
+
const git = options.git ?? makeDriftGit(options.projectRoot);
|
|
273
|
+
const docs = await collectFiles(options.projectRoot, {
|
|
274
|
+
docs: true,
|
|
275
|
+
...options.docsGlobs !== undefined ? { patterns: options.docsGlobs } : {},
|
|
276
|
+
...options.ignoreGlobs !== undefined ? { ignore: options.ignoreGlobs } : {}
|
|
277
|
+
});
|
|
278
|
+
const findings = [];
|
|
279
|
+
let degraded = false;
|
|
280
|
+
for (const docPath of docs) {
|
|
281
|
+
try {
|
|
282
|
+
findings.push(...await detectDeletedReferences(options.projectRoot, docPath, git));
|
|
283
|
+
findings.push(...await detectStaleAnchors(options.projectRoot, docPath, git));
|
|
284
|
+
} catch {
|
|
285
|
+
degraded = true;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
return {
|
|
289
|
+
generatedAt: new Date().toISOString(),
|
|
290
|
+
scanned: docs.length,
|
|
291
|
+
degraded,
|
|
292
|
+
findings
|
|
293
|
+
};
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// packages/docs-drift-plugin/src/drift/metadata.ts
|
|
297
|
+
import { Schema } from "effect";
|
|
298
|
+
import { StageMutation as StageMutationSchema } from "@rig/contracts";
|
|
299
|
+
var DOCS_DRIFT_VALIDATOR_ID = "std:docs-drift";
|
|
300
|
+
var DOCS_DRIFT_CLI_ID = "std:drift";
|
|
301
|
+
var DOCS_DRIFT_STAGE_ID = "docs-drift";
|
|
302
|
+
var DOCS_DRIFT_CAPABILITY_ID = "std:docs-drift-capability";
|
|
303
|
+
var DOCS_DRIFT_VALIDATOR = {
|
|
304
|
+
id: DOCS_DRIFT_VALIDATOR_ID,
|
|
305
|
+
category: "regression",
|
|
306
|
+
description: "Detect documentation references that drifted from the source tree."
|
|
307
|
+
};
|
|
308
|
+
var DOCS_DRIFT_STAGE_MUTATION = Schema.decodeUnknownSync(StageMutationSchema)({
|
|
309
|
+
op: "insert",
|
|
310
|
+
stage: {
|
|
311
|
+
id: DOCS_DRIFT_STAGE_ID,
|
|
312
|
+
kind: "gate",
|
|
313
|
+
before: ["merge-gate"],
|
|
314
|
+
after: ["open-pr"],
|
|
315
|
+
priority: 0,
|
|
316
|
+
protected: false
|
|
317
|
+
},
|
|
318
|
+
contributedBy: DOCS_DRIFT_STAGE_ID
|
|
319
|
+
});
|
|
320
|
+
var DOCS_DRIFT_CLI_COMMAND = "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]";
|
|
321
|
+
// packages/docs-drift-plugin/src/drift/plugin.ts
|
|
322
|
+
function highConfidenceDriftFindings(report) {
|
|
323
|
+
return report.findings.filter((finding) => finding.confidence === "high");
|
|
324
|
+
}
|
|
325
|
+
function driftGateResult(report, mode = "enforce") {
|
|
326
|
+
const high = highConfidenceDriftFindings(report);
|
|
327
|
+
if (mode === "enforce" && high.length > 0) {
|
|
328
|
+
return { kind: "block", reason: `${high.length} high-confidence documentation drift finding(s).` };
|
|
329
|
+
}
|
|
330
|
+
return { kind: "allow" };
|
|
331
|
+
}
|
|
332
|
+
function createDocsDriftGateStage(options = {}) {
|
|
333
|
+
return async (ctx) => {
|
|
334
|
+
const projectRoot = typeof ctx.metadata?.projectRoot === "string" ? ctx.metadata.projectRoot : process.cwd();
|
|
335
|
+
const report = await detectDrift({
|
|
336
|
+
projectRoot,
|
|
337
|
+
...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
|
|
338
|
+
...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {}
|
|
339
|
+
});
|
|
340
|
+
return driftGateResult(report, options.failOnDrift ? "enforce" : "observe");
|
|
341
|
+
};
|
|
342
|
+
}
|
|
343
|
+
async function runDocsDriftValidation(options) {
|
|
344
|
+
const report = await detectDrift(options);
|
|
345
|
+
const high = highConfidenceDriftFindings(report);
|
|
346
|
+
const passed = options.failOnDrift ? high.length === 0 : true;
|
|
347
|
+
const findingWord = report.findings.length === 1 ? "finding" : "findings";
|
|
348
|
+
return {
|
|
349
|
+
id: DOCS_DRIFT_VALIDATOR_ID,
|
|
350
|
+
passed,
|
|
351
|
+
summary: `docs drift scanned ${report.scanned} doc(s), ${report.findings.length} ${findingWord}`,
|
|
352
|
+
details: JSON.stringify(report)
|
|
353
|
+
};
|
|
354
|
+
}
|
|
355
|
+
function createDocsDriftValidator(options = {}) {
|
|
356
|
+
return {
|
|
357
|
+
...DOCS_DRIFT_VALIDATOR,
|
|
358
|
+
async run(ctx) {
|
|
359
|
+
return runDocsDriftValidation({
|
|
360
|
+
projectRoot: ctx.workspaceRoot,
|
|
361
|
+
...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
|
|
362
|
+
...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {},
|
|
363
|
+
...options.failOnDrift !== undefined ? { failOnDrift: options.failOnDrift } : {}
|
|
364
|
+
});
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
}
|
|
368
|
+
function takeOptionValue(args, index, flag) {
|
|
369
|
+
const value = args[index + 1];
|
|
370
|
+
if (!value)
|
|
371
|
+
throw new Error(`${flag} requires a value`);
|
|
372
|
+
return value;
|
|
373
|
+
}
|
|
374
|
+
function takeFlag(args, flag) {
|
|
375
|
+
const rest = [...args];
|
|
376
|
+
const index = rest.indexOf(flag);
|
|
377
|
+
if (index < 0)
|
|
378
|
+
return { value: false, rest };
|
|
379
|
+
rest.splice(index, 1);
|
|
380
|
+
return { value: true, rest };
|
|
381
|
+
}
|
|
382
|
+
function takeOption(args, flag) {
|
|
383
|
+
const rest = [...args];
|
|
384
|
+
const index = rest.indexOf(flag);
|
|
385
|
+
if (index < 0)
|
|
386
|
+
return { rest };
|
|
387
|
+
const value = rest[index + 1];
|
|
388
|
+
if (!value || value.startsWith("-"))
|
|
389
|
+
throw new Error(`${flag} requires a value.`);
|
|
390
|
+
rest.splice(index, 2);
|
|
391
|
+
return { value, rest };
|
|
392
|
+
}
|
|
393
|
+
function requireNoExtraArgs(args, usage) {
|
|
394
|
+
if (args.length > 0)
|
|
395
|
+
throw new Error(`Unexpected argument: ${args[0]}
|
|
396
|
+
Usage: ${usage}`);
|
|
397
|
+
}
|
|
398
|
+
function parseCsv(value) {
|
|
399
|
+
return value?.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0) ?? [];
|
|
400
|
+
}
|
|
401
|
+
function driftSummary(report) {
|
|
402
|
+
const highConfidence = highConfidenceDriftFindings(report).length;
|
|
403
|
+
return { total: report.findings.length, highConfidence, degraded: report.degraded };
|
|
404
|
+
}
|
|
405
|
+
async function executeDrift(context, args, options = {}) {
|
|
406
|
+
const json = takeFlag(args, "--json");
|
|
407
|
+
const docs = takeOption(json.rest, "--docs");
|
|
408
|
+
const ignore = takeOption(docs.rest, "--ignore");
|
|
409
|
+
const failOnDrift = takeFlag(ignore.rest, "--fail-on-drift");
|
|
410
|
+
requireNoExtraArgs(failOnDrift.rest, "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]");
|
|
411
|
+
const docsGlobs = parseCsv(docs.value);
|
|
412
|
+
const ignoreGlobs = parseCsv(ignore.value);
|
|
413
|
+
const effectiveDocsGlobs = docsGlobs.length > 0 ? docsGlobs : options.docsGlobs;
|
|
414
|
+
const effectiveIgnoreGlobs = ignoreGlobs.length > 0 ? ignoreGlobs : options.ignoreGlobs;
|
|
415
|
+
const effectiveFailOnDrift = failOnDrift.value || options.failOnDrift === true;
|
|
416
|
+
const report = await detectDrift({
|
|
417
|
+
projectRoot: context.projectRoot,
|
|
418
|
+
...effectiveDocsGlobs !== undefined ? { docsGlobs: effectiveDocsGlobs } : {},
|
|
419
|
+
...effectiveIgnoreGlobs !== undefined ? { ignoreGlobs: effectiveIgnoreGlobs } : {}
|
|
420
|
+
});
|
|
421
|
+
const failed = effectiveFailOnDrift && highConfidenceDriftFindings(report).length > 0;
|
|
422
|
+
const details = { report, summary: driftSummary(report), failOnDrift: effectiveFailOnDrift, failed };
|
|
423
|
+
if (context.outputMode === "text") {
|
|
424
|
+
if (json.value)
|
|
425
|
+
console.log(JSON.stringify(details, null, 2));
|
|
426
|
+
else
|
|
427
|
+
console.log(report.findings.length === 0 ? `No drift findings across ${report.scanned} documents.` : report.findings.map((finding) => `${finding.docPath}:${finding.line ?? "?"} ${finding.kind} ${finding.confidence} ${finding.detail}`).join(`
|
|
428
|
+
`));
|
|
429
|
+
}
|
|
430
|
+
return { ok: !failed, group: "drift", command: "scan", details };
|
|
431
|
+
}
|
|
432
|
+
function createDocsDriftRuntimeCliCommand(options = {}) {
|
|
433
|
+
return {
|
|
434
|
+
id: DOCS_DRIFT_CLI_ID,
|
|
435
|
+
family: "drift",
|
|
436
|
+
command: DOCS_DRIFT_CLI_COMMAND,
|
|
437
|
+
description: "Scan documentation for stale code references.",
|
|
438
|
+
usage: DOCS_DRIFT_CLI_COMMAND,
|
|
439
|
+
projectRequired: true,
|
|
440
|
+
run: (context, args) => executeDrift(context, args, options)
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
var DOCS_DRIFT_RUNTIME_CLI_COMMAND = createDocsDriftRuntimeCliCommand();
|
|
444
|
+
async function runDriftCli(args, options = {}) {
|
|
445
|
+
const docsGlobs = [];
|
|
446
|
+
const ignoreGlobs = [];
|
|
447
|
+
let json = false;
|
|
448
|
+
let failOnDrift = false;
|
|
449
|
+
for (let index = 0;index < args.length; index += 1) {
|
|
450
|
+
const arg = args[index];
|
|
451
|
+
if (arg === "--json") {
|
|
452
|
+
json = true;
|
|
453
|
+
continue;
|
|
454
|
+
}
|
|
455
|
+
if (arg === "--fail-on-drift") {
|
|
456
|
+
failOnDrift = true;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (arg === "--docs") {
|
|
460
|
+
docsGlobs.push(takeOptionValue(args, index, arg));
|
|
461
|
+
index += 1;
|
|
462
|
+
continue;
|
|
463
|
+
}
|
|
464
|
+
if (arg === "--ignore") {
|
|
465
|
+
ignoreGlobs.push(takeOptionValue(args, index, arg));
|
|
466
|
+
index += 1;
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
throw new Error(`Unknown rig drift argument: ${arg}`);
|
|
470
|
+
}
|
|
471
|
+
const report = await detectDrift({
|
|
472
|
+
projectRoot: options.projectRoot ?? process.cwd(),
|
|
473
|
+
...docsGlobs.length > 0 ? { docsGlobs } : {},
|
|
474
|
+
...ignoreGlobs.length > 0 ? { ignoreGlobs } : {}
|
|
475
|
+
});
|
|
476
|
+
const write = options.write ?? ((message) => console.log(message));
|
|
477
|
+
if (json) {
|
|
478
|
+
write(JSON.stringify(report));
|
|
479
|
+
} else {
|
|
480
|
+
write(`Scanned ${report.scanned} doc(s); ${report.findings.length} drift finding(s).`);
|
|
481
|
+
for (const finding of report.findings) {
|
|
482
|
+
write(`${finding.confidence.toUpperCase()} ${finding.kind} ${finding.docPath}${finding.line ? `:${finding.line}` : ""} ${finding.reference ?? ""} \u2014 ${finding.detail}`);
|
|
483
|
+
}
|
|
484
|
+
}
|
|
485
|
+
const high = highConfidenceDriftFindings(report);
|
|
486
|
+
if (failOnDrift && high.length > 0) {
|
|
487
|
+
options.writeError?.(`${high.length} high-confidence drift finding(s).`);
|
|
488
|
+
return 2;
|
|
489
|
+
}
|
|
490
|
+
return 0;
|
|
491
|
+
}
|
|
492
|
+
export {
|
|
493
|
+
runDriftCli,
|
|
494
|
+
runDocsDriftValidation,
|
|
495
|
+
highConfidenceDriftFindings,
|
|
496
|
+
executeDrift,
|
|
497
|
+
driftGateResult,
|
|
498
|
+
createDocsDriftValidator,
|
|
499
|
+
createDocsDriftRuntimeCliCommand,
|
|
500
|
+
createDocsDriftGateStage,
|
|
501
|
+
DOCS_DRIFT_VALIDATOR_ID,
|
|
502
|
+
DOCS_DRIFT_VALIDATOR,
|
|
503
|
+
DOCS_DRIFT_STAGE_MUTATION,
|
|
504
|
+
DOCS_DRIFT_STAGE_ID,
|
|
505
|
+
DOCS_DRIFT_RUNTIME_CLI_COMMAND,
|
|
506
|
+
DOCS_DRIFT_CLI_ID,
|
|
507
|
+
DOCS_DRIFT_CLI_COMMAND,
|
|
508
|
+
DOCS_DRIFT_CAPABILITY_ID
|
|
509
|
+
};
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { DriftConfidence, DriftFinding, DriftKind, DriftReport } from "@rig/contracts";
|
|
2
|
+
export interface DriftScanInput {
|
|
3
|
+
readonly projectRoot: string;
|
|
4
|
+
readonly docsGlobs?: readonly string[];
|
|
5
|
+
readonly ignoreGlobs?: readonly string[];
|
|
6
|
+
readonly judge?: boolean;
|
|
7
|
+
}
|
|
8
|
+
export type DriftDetector = (input: DriftScanInput) => Promise<DriftReport> | DriftReport;
|
|
9
|
+
export interface DriftSummary {
|
|
10
|
+
readonly total: number;
|
|
11
|
+
readonly highConfidence: number;
|
|
12
|
+
readonly byKind: Readonly<Record<DriftKind, number>>;
|
|
13
|
+
readonly byConfidence: Readonly<Record<DriftConfidence, number>>;
|
|
14
|
+
readonly degraded: boolean;
|
|
15
|
+
}
|
|
16
|
+
export declare function runDriftScan(projectRoot: string, deps: {
|
|
17
|
+
readonly detectDrift: DriftDetector;
|
|
18
|
+
}, options?: Omit<DriftScanInput, "projectRoot">): Promise<DriftReport>;
|
|
19
|
+
export declare function summarizeDriftReport(report: DriftReport): DriftSummary;
|
|
20
|
+
export declare function driftFindingsByDocument(report: DriftReport): ReadonlyMap<string, readonly DriftFinding[]>;
|
|
21
|
+
export declare function shouldFailOnDrift(report: DriftReport, options?: {
|
|
22
|
+
readonly failOnDrift?: boolean;
|
|
23
|
+
readonly minimumConfidence?: DriftConfidence;
|
|
24
|
+
}): boolean;
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
// packages/docs-drift-plugin/src/drift/summary.ts
|
|
3
|
+
var DRIFT_KINDS = ["deleted-reference", "stale-anchor", "semantic-mismatch", "issue-mismatch"];
|
|
4
|
+
var DRIFT_CONFIDENCES = ["high", "medium", "low"];
|
|
5
|
+
async function runDriftScan(projectRoot, deps, options = {}) {
|
|
6
|
+
return deps.detectDrift({ projectRoot, ...options });
|
|
7
|
+
}
|
|
8
|
+
function summarizeDriftReport(report) {
|
|
9
|
+
const byKind = Object.fromEntries(DRIFT_KINDS.map((kind) => [kind, 0]));
|
|
10
|
+
const byConfidence = Object.fromEntries(DRIFT_CONFIDENCES.map((confidence) => [confidence, 0]));
|
|
11
|
+
for (const finding of report.findings) {
|
|
12
|
+
byKind[finding.kind] += 1;
|
|
13
|
+
byConfidence[finding.confidence] += 1;
|
|
14
|
+
}
|
|
15
|
+
return {
|
|
16
|
+
total: report.findings.length,
|
|
17
|
+
highConfidence: byConfidence.high,
|
|
18
|
+
byKind,
|
|
19
|
+
byConfidence,
|
|
20
|
+
degraded: report.degraded
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
function driftFindingsByDocument(report) {
|
|
24
|
+
const grouped = new Map;
|
|
25
|
+
for (const finding of report.findings) {
|
|
26
|
+
grouped.set(finding.docPath, [...grouped.get(finding.docPath) ?? [], finding]);
|
|
27
|
+
}
|
|
28
|
+
return new Map([...grouped.entries()].map(([path, findings]) => [path, findings.toSorted((left, right) => (left.line ?? 0) - (right.line ?? 0))]));
|
|
29
|
+
}
|
|
30
|
+
function shouldFailOnDrift(report, options = {}) {
|
|
31
|
+
if (!options.failOnDrift)
|
|
32
|
+
return false;
|
|
33
|
+
const threshold = options.minimumConfidence ?? "high";
|
|
34
|
+
const rank = { high: 3, medium: 2, low: 1 };
|
|
35
|
+
return report.findings.some((finding) => rank[finding.confidence] >= rank[threshold]);
|
|
36
|
+
}
|
|
37
|
+
export {
|
|
38
|
+
summarizeDriftReport,
|
|
39
|
+
shouldFailOnDrift,
|
|
40
|
+
runDriftScan,
|
|
41
|
+
driftFindingsByDocument
|
|
42
|
+
};
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type RigPlugin } from "@rig/core/config";
|
|
2
|
+
import { type DocsDriftPluginOptions } from "./drift/metadata";
|
|
3
|
+
export { DOCS_DRIFT_CAPABILITY_ID, DOCS_DRIFT_CLI_COMMAND, DOCS_DRIFT_CLI_ID, DOCS_DRIFT_STAGE_ID, DOCS_DRIFT_STAGE_MUTATION, DOCS_DRIFT_VALIDATOR, DOCS_DRIFT_VALIDATOR_ID } from "./drift/metadata";
|
|
4
|
+
export type { DocsDriftPluginOptions } from "./drift/metadata";
|
|
5
|
+
export type { DriftReference, DriftReferenceKind } from "./drift/extract-refs";
|
|
6
|
+
export type { DriftGit } from "./drift/git-adapter";
|
|
7
|
+
export type { DriftJudgeInput, DriftJudgeMismatch, DriftJudgeProvider } from "./drift/judge";
|
|
8
|
+
export declare const DOCS_HEALTH_PANEL_ID = "docs-health";
|
|
9
|
+
export declare function createStandardDocsDriftPlugin(opts?: DocsDriftPluginOptions): RigPlugin;
|