@h-rig/standard-plugin 0.0.6-alpha.155 → 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.
@@ -1,53 +0,0 @@
1
- import type { DriftFinding, DriftReport, StageResult, StageRun } from "@rig/contracts";
2
- import type { RegisteredValidator, RuntimeCliCommand, RuntimeCliContext, ValidatorResult } from "@rig/core/config";
3
- import { type DriftDetectOptions } from "./detect";
4
- 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, type DocsDriftPluginOptions, } from "./metadata";
5
- import { type DocsDriftPluginOptions } from "./metadata";
6
- export declare function highConfidenceDriftFindings(report: DriftReport): readonly DriftFinding[];
7
- export declare function driftGateResult(report: DriftReport, mode?: "observe" | "enforce"): StageResult;
8
- /**
9
- * Executable for the `docs-drift` pre-merge gate stage (inserted by
10
- * DOCS_DRIFT_STAGE_MUTATION before `merge-gate`). Reads the project root from the
11
- * stage context metadata, runs deletion-survival drift detection, and blocks the
12
- * pipeline on high-confidence drift when enforcing (`failOnDrift`), else observes.
13
- */
14
- export declare function createDocsDriftGateStage(options?: DocsDriftPluginOptions): StageRun;
15
- export declare function runDocsDriftValidation(options: DriftDetectOptions & {
16
- failOnDrift?: boolean;
17
- }): Promise<ValidatorResult>;
18
- export declare function createDocsDriftValidator(options?: DocsDriftPluginOptions): RegisteredValidator;
19
- export interface RunDriftCliOptions {
20
- readonly projectRoot?: string;
21
- readonly write?: (message: string) => void;
22
- readonly writeError?: (message: string) => void;
23
- }
24
- export declare function executeDrift(context: RuntimeCliContext, args: readonly string[], options?: DocsDriftPluginOptions): Promise<{
25
- ok: boolean;
26
- group: string;
27
- command: string;
28
- details: {
29
- report: {
30
- readonly degraded: boolean;
31
- readonly generatedAt: string;
32
- readonly findings: readonly {
33
- readonly kind: "deleted-reference" | "stale-anchor" | "semantic-mismatch" | "issue-mismatch";
34
- readonly detail: string;
35
- readonly line: number | null;
36
- readonly reference: string | null;
37
- readonly docPath: string;
38
- readonly confidence: "high" | "medium" | "low";
39
- }[];
40
- readonly scanned: number;
41
- };
42
- summary: {
43
- total: number;
44
- highConfidence: number;
45
- degraded: boolean;
46
- };
47
- failOnDrift: boolean;
48
- failed: boolean;
49
- };
50
- }>;
51
- export declare function createDocsDriftRuntimeCliCommand(options?: DocsDriftPluginOptions): RuntimeCliCommand;
52
- export declare const DOCS_DRIFT_RUNTIME_CLI_COMMAND: RuntimeCliCommand;
53
- export declare function runDriftCli(args: readonly string[], options?: RunDriftCliOptions): Promise<number>;
@@ -1,509 +0,0 @@
1
- // @bun
2
- // packages/standard-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/standard-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/standard-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/standard-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/standard-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/standard-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
- };
@@ -1,18 +0,0 @@
1
- import type { RegisteredTaskSource } from "@rig/contracts";
2
- export interface FilesTaskSourceOptions {
3
- /**
4
- * Directory containing one JSON file per task. Use either `path` (matches
5
- * the `taskSource.path` field in rig.config.ts) or `dir` (back-compat).
6
- */
7
- path?: string;
8
- dir?: string;
9
- pattern?: RegExp;
10
- /**
11
- * Root a relative `path`/`dir` resolves against. The serving process's cwd
12
- * is NOT the project (workspace-spawned servers run from the engine
13
- * checkout), so without this a relative path silently reads the WRONG
14
- * repo's tasks. Defaults to cwd for direct programmatic use.
15
- */
16
- projectRoot?: string;
17
- }
18
- export declare function createFilesTaskSource(opts: FilesTaskSourceOptions): RegisteredTaskSource;
@@ -1,107 +0,0 @@
1
- // @bun
2
- // packages/standard-plugin/src/files-source.ts
3
- import { readFileSync, readdirSync, existsSync, statSync, writeFileSync } from "fs";
4
- import { join, basename, isAbsolute, resolve } from "path";
5
- var DEFAULT_PATTERN = /\.(task\.)?json$/;
6
- function readTaskFile(file, pattern) {
7
- const raw = JSON.parse(readFileSync(file, "utf-8"));
8
- const inferredId = basename(file).replace(pattern, "");
9
- const labels = Array.isArray(raw.labels) ? raw.labels.filter((label) => typeof label === "string") : [];
10
- const scope = labels.filter((label) => label.startsWith("scope:")).map((label) => label.slice("scope:".length));
11
- const validators = labels.filter((label) => label.startsWith("validator:")).map((label) => label.slice("validator:".length));
12
- const roleLabel = labels.find((label) => label.startsWith("role:"));
13
- return {
14
- id: raw["id"] ?? inferredId,
15
- deps: raw["deps"] ?? raw["depends_on"] ?? [],
16
- status: raw["status"] ?? "ready",
17
- ...scope.length > 0 ? { scope } : {},
18
- ...roleLabel ? { role: roleLabel.slice("role:".length) } : {},
19
- ...validators.length > 0 ? { validators, validation: validators } : {},
20
- ...raw
21
- };
22
- }
23
- function createFilesTaskSource(opts) {
24
- const pattern = opts.pattern ?? DEFAULT_PATTERN;
25
- const configured = opts.path ?? opts.dir;
26
- if (!configured) {
27
- throw new Error("createFilesTaskSource: either `path` or `dir` must be provided");
28
- }
29
- const directory = isAbsolute(configured) ? configured : resolve(opts.projectRoot ?? process.cwd(), configured);
30
- const findTaskFile = (id) => {
31
- if (!existsSync(directory))
32
- return;
33
- for (const name of readdirSync(directory)) {
34
- if (!pattern.test(name))
35
- continue;
36
- const p = join(directory, name);
37
- try {
38
- if (!statSync(p).isFile())
39
- continue;
40
- if (readTaskFile(p, pattern).id === id)
41
- return p;
42
- } catch {}
43
- }
44
- return;
45
- };
46
- const applyUpdate = (id, update) => {
47
- const file = findTaskFile(id);
48
- if (!file) {
49
- throw new Error(`files task not found: ${id}`);
50
- }
51
- const raw = JSON.parse(readFileSync(file, "utf-8"));
52
- if (update.status)
53
- raw.status = update.status;
54
- if (update.title !== undefined)
55
- raw.title = update.title;
56
- if (update.body !== undefined)
57
- raw.body = update.body;
58
- if (update.comment?.trim()) {
59
- const existing = Array.isArray(raw.comments) ? raw.comments : [];
60
- raw.comments = [
61
- ...existing,
62
- {
63
- body: update.comment,
64
- createdAt: new Date().toISOString(),
65
- source: "rig"
66
- }
67
- ];
68
- }
69
- writeFileSync(file, `${JSON.stringify(raw, null, 2)}
70
- `, "utf-8");
71
- };
72
- return {
73
- id: "std:files",
74
- kind: "files",
75
- async list() {
76
- if (!existsSync(directory))
77
- return [];
78
- const out = [];
79
- for (const name of readdirSync(directory)) {
80
- if (!pattern.test(name))
81
- continue;
82
- const p = join(directory, name);
83
- try {
84
- if (!statSync(p).isFile())
85
- continue;
86
- out.push(readTaskFile(p, pattern));
87
- } catch (err) {
88
- console.warn(`[files-source] skipped ${name}: ${err.message}`);
89
- }
90
- }
91
- return out;
92
- },
93
- async get(id) {
94
- const all = await this.list();
95
- return all.find((t) => t.id === id);
96
- },
97
- async updateStatus(id, status) {
98
- applyUpdate(id, { status });
99
- },
100
- async updateTask(id, update) {
101
- applyUpdate(id, update);
102
- }
103
- };
104
- }
105
- export {
106
- createFilesTaskSource
107
- };