@h-rig/standard-plugin 0.0.6-alpha.14 → 0.0.6-alpha.141

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