@h-rig/standard-plugin 0.0.6-alpha.142 → 0.0.6-alpha.144

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,1488 +1,1578 @@
1
1
  // @bun
2
- // packages/standard-plugin/src/plugin.ts
3
- import { resolve as resolve4 } from "path";
4
- import { definePlugin } from "@rig/core";
2
+ var __defProp = Object.defineProperty;
3
+ var __returnValue = (v) => v;
4
+ function __exportSetter(name, newValue) {
5
+ this[name] = __returnValue.bind(null, newValue);
6
+ }
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, {
10
+ get: all[name],
11
+ enumerable: true,
12
+ configurable: true,
13
+ set: __exportSetter.bind(all, name)
14
+ });
15
+ };
16
+ var __esm = (fn, res) => () => (fn && (res = fn(fn = 0)), res);
5
17
 
6
- // packages/standard-plugin/src/github-issues-source.ts
7
- import { spawnSync } from "child_process";
8
- import { existsSync, readFileSync } from "fs";
9
- import { resolve } from "path";
10
- function cleanToken(value) {
11
- const trimmed = value?.trim() ?? "";
12
- return trimmed.length > 0 ? trimmed : null;
13
- }
14
- function createEnvGitHubCredentialProvider() {
15
- return {
16
- async resolveGitHubToken(input) {
17
- if (input.purpose === "selected-repo") {
18
- return { token: cleanToken(process.env.RIG_GITHUB_SELECTED_TOKEN ?? process.env.RIG_GITHUB_TOKEN ?? null) ?? "", source: "signed-in-user" };
19
- }
20
- const token = cleanToken(process.env.RIG_GITHUB_TOKEN ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? null);
21
- if (!token) {
22
- throw new Error("No host GitHub token is configured for admin fallback.");
23
- }
24
- return { token, source: "host-admin-fallback" };
25
- }
26
- };
27
- }
28
- function createStateGitHubCredentialProvider(options = {}) {
29
- const stateFileCandidates = () => {
30
- const candidates = [];
31
- const explicitFile = options.stateFile ?? process.env.RIG_GITHUB_AUTH_STATE_FILE;
32
- if (explicitFile?.trim())
33
- candidates.push(resolve(explicitFile.trim()));
34
- for (const dir of [options.stateDir, process.env.RIG_STATE_DIR]) {
35
- if (dir?.trim())
36
- candidates.push(resolve(dir.trim(), "github-auth.json"));
37
- }
38
- return candidates;
39
- };
40
- const readToken = () => {
41
- for (const stateFile of stateFileCandidates()) {
42
- if (!existsSync(stateFile))
43
- continue;
44
- try {
45
- const parsed = JSON.parse(readFileSync(stateFile, "utf8"));
46
- const token = typeof parsed.token === "string" ? cleanToken(parsed.token) : null;
47
- if (token)
48
- return token;
49
- } catch {}
50
- }
51
- return null;
18
+ // packages/standard-plugin/src/drift/metadata.ts
19
+ import { Schema } from "effect";
20
+ import { StageMutation as StageMutationSchema } from "@rig/contracts";
21
+ var DOCS_DRIFT_VALIDATOR_ID = "std:docs-drift", DOCS_DRIFT_CLI_ID = "std:drift", DOCS_DRIFT_STAGE_ID = "docs-drift", DOCS_DRIFT_CAPABILITY_ID = "std:docs-drift-capability", DOCS_DRIFT_VALIDATOR, DOCS_DRIFT_STAGE_MUTATION, DOCS_DRIFT_CLI_COMMAND = "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]";
22
+ var init_metadata = __esm(() => {
23
+ DOCS_DRIFT_VALIDATOR = {
24
+ id: DOCS_DRIFT_VALIDATOR_ID,
25
+ category: "regression",
26
+ description: "Detect documentation references that drifted from the source tree."
52
27
  };
53
- return {
54
- async resolveGitHubToken(input) {
55
- const token = readToken();
56
- if (input.purpose === "selected-repo") {
57
- return { token: token ?? cleanToken(process.env.RIG_GITHUB_SELECTED_TOKEN ?? process.env.RIG_GITHUB_TOKEN ?? null) ?? "", source: "signed-in-user" };
58
- }
59
- if (token) {
60
- return { token, source: "signed-in-user" };
61
- }
62
- const fallback = cleanToken(process.env.RIG_GITHUB_TOKEN ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? null);
63
- if (!fallback) {
64
- throw new Error("No signed-in GitHub token is stored for Rig and no host admin fallback token is configured.");
65
- }
66
- return { token: fallback, source: "host-admin-fallback" };
28
+ DOCS_DRIFT_STAGE_MUTATION = Schema.decodeUnknownSync(StageMutationSchema)({
29
+ op: "insert",
30
+ stage: {
31
+ id: DOCS_DRIFT_STAGE_ID,
32
+ kind: "gate",
33
+ before: ["merge-gate"],
34
+ after: ["open-pr"]
35
+ },
36
+ contributedBy: DOCS_DRIFT_STAGE_ID
37
+ });
38
+ });
39
+
40
+ // packages/standard-plugin/src/drift/extract-refs.ts
41
+ function stripFenceLines(markdown) {
42
+ const lines = markdown.split(/\r?\n/);
43
+ let fenced = false;
44
+ return lines.map((line) => {
45
+ if (/^\s*(```|~~~)/.test(line)) {
46
+ fenced = !fenced;
47
+ return "";
67
48
  }
68
- };
49
+ return fenced ? "" : line;
50
+ });
69
51
  }
70
- var STATUS_LABELS = new Set(["ready", "blocked", "in-progress", "under-review", "failed", "cancelled"]);
71
- var RIG_STATUS_COMMENT_MARKER = "<!-- rig:status-comment -->";
72
- var RIG_METADATA_START = "<!-- rig:metadata:start -->";
73
- var RIG_METADATA_END = "<!-- rig:metadata:end -->";
74
- var RIG_STATUS_LABELS = new Set(["rig:running", "rig:pr-open", "rig:ci-fixing", "rig:merging", "rig:done", "rig:needs-attention"]);
75
- var DEFAULT_GH_TIMEOUT_MS = 15000;
76
- var DEFAULT_GITHUB_ISSUE_LIST_LIMIT = 1000;
77
- function statusFor(issue) {
78
- const state = (issue.state ?? "").toUpperCase();
79
- if (state === "CLOSED")
80
- return "closed";
81
- const labelNames = labelNamesFor(issue);
82
- if (labelNames.includes("in-progress"))
83
- return "in_progress";
84
- if (labelNames.includes("blocked"))
85
- return "blocked";
86
- if (labelNames.includes("ready"))
87
- return "ready";
88
- if (labelNames.includes("under-review"))
89
- return "under_review";
90
- if (labelNames.includes("failed"))
91
- return "failed";
92
- if (labelNames.includes("cancelled"))
93
- return "cancelled";
94
- return "open";
52
+ function normalizeToken(raw) {
53
+ return raw.trim().replace(/^['"]|['"]$/g, "").replace(/[),.;:]+$/g, "").replace(/#L\d+(?:-L\d+)?$/i, "");
95
54
  }
96
- function parseIssueRefs(raw) {
97
- return raw.split(",").map((s) => s.trim()).map((s) => s.replace(/^#/, "").match(/^(\d+)/)?.[1] ?? "").filter((s) => s.length > 0);
55
+ function classifyReference(raw) {
56
+ if (raw.startsWith("@"))
57
+ return null;
58
+ if (PATH_REF.test(raw))
59
+ return "path";
60
+ if (SYMBOL_REF.test(raw))
61
+ return "symbol";
62
+ return null;
98
63
  }
99
- function parseMetadataList(body, key) {
100
- const block = body.match(/<!-- rig:metadata:start -->\s*([\s\S]*?)\s*<!-- rig:metadata:end -->/);
101
- if (!block)
102
- return [];
103
- const lines = block[1].split(/\r?\n/);
104
- const values = [];
105
- for (let index = 0;index < lines.length; index += 1) {
106
- const line = lines[index];
107
- const sameLine = line.match(new RegExp(`^${key}:\\s*(.+)$`, "i"));
108
- if (sameLine) {
109
- values.push(...parseIssueRefs(sameLine[1]));
110
- continue;
64
+ function pushReference(refs, seen, raw, line) {
65
+ const value = normalizeToken(raw);
66
+ if (!value)
67
+ return;
68
+ const kind = classifyReference(value);
69
+ if (!kind)
70
+ return;
71
+ const key = `${kind}:${value}:${line}`;
72
+ if (seen.has(key))
73
+ return;
74
+ seen.add(key);
75
+ refs.push({ kind, value, line });
76
+ }
77
+ function extractDriftReferences(markdown) {
78
+ const refs = [];
79
+ const seen = new Set;
80
+ const lines = stripFenceLines(markdown);
81
+ for (const [index, line] of lines.entries()) {
82
+ const lineNumber = index + 1;
83
+ for (const match of line.matchAll(INLINE_CODE)) {
84
+ pushReference(refs, seen, match[1] ?? "", lineNumber);
111
85
  }
112
- if (!new RegExp(`^${key}:\\s*$`, "i").test(line))
113
- continue;
114
- for (let cursor = index + 1;cursor < lines.length; cursor += 1) {
115
- const item = lines[cursor].match(/^\s*-\s*(.+)$/);
116
- if (!item)
117
- break;
118
- values.push(...parseIssueRefs(item[1]));
86
+ for (const match of line.matchAll(MARKDOWN_LINK)) {
87
+ pushReference(refs, seen, match[1] ?? "", lineNumber);
119
88
  }
120
89
  }
121
- return [...new Set(values)];
122
- }
123
- function parseDeps(body) {
124
- const match = body.match(/^depends-on:\s*([^\n]+)/im);
125
- const bodyRefs = match ? parseIssueRefs(match[1]) : [];
126
- return [...new Set([...bodyRefs, ...parseMetadataList(body, "depends-on")])];
90
+ return refs;
127
91
  }
128
- function parseParents(body) {
129
- const match = body.match(/^parents?:\s*([^\n]+)/im);
130
- const bodyRefs = match ? parseIssueRefs(match[1]) : [];
131
- return [...new Set([...bodyRefs, ...parseMetadataList(body, "parents")])];
92
+ var INLINE_CODE, MARKDOWN_LINK, SYMBOL_REF, PATH_REF;
93
+ var init_extract_refs = __esm(() => {
94
+ INLINE_CODE = /`([^`\n]+)`/g;
95
+ MARKDOWN_LINK = /\[[^\]]+\]\(([^)\s]+)\)/g;
96
+ SYMBOL_REF = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?$/;
97
+ 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)$/;
98
+ });
99
+
100
+ // packages/standard-plugin/src/drift/git-adapter.ts
101
+ import { execFile } from "child_process";
102
+ import { promisify } from "util";
103
+ function processError(value) {
104
+ return value && typeof value === "object" ? value : null;
132
105
  }
133
- function issueTypeFor(issue) {
134
- const labels = labelNamesFor(issue);
135
- const typed = labels.find((l) => l.startsWith("type:"));
136
- if (typed)
137
- return typed.slice("type:".length);
138
- if (labels.includes("epic"))
139
- return "epic";
140
- return "task";
106
+ function lineCount(output) {
107
+ const trimmed = output.trim();
108
+ return trimmed ? trimmed.split(/\r?\n/).length : 0;
141
109
  }
142
- function issueToTask(issue, repo, nativeDependencies) {
143
- const labelNames = labelNamesFor(issue);
144
- const scope = labelNames.filter((l) => l.startsWith("scope:")).map((l) => l.slice("scope:".length));
145
- const roleLabel = labelNames.find((l) => l.startsWith("role:"));
146
- const role = roleLabel ? roleLabel.slice("role:".length) : undefined;
147
- const validators = labelNames.filter((l) => l.startsWith("validator:")).map((l) => l.slice("validator:".length));
148
- const body = issue.body ?? "";
149
- const issueNodeId = issue.id ?? issue.nodeId ?? issue.node_id;
150
- const parsedDeps = parseDeps(body);
151
- const deps = nativeDependencies?.deps ? [...new Set([...parsedDeps, ...nativeDependencies.deps])] : parsedDeps;
110
+ function makeDriftGit(projectRoot) {
111
+ async function git(args) {
112
+ const result = await execFileAsync("git", [...args], {
113
+ cwd: projectRoot,
114
+ encoding: "utf8",
115
+ maxBuffer: 10 * 1024 * 1024
116
+ });
117
+ return String(result.stdout);
118
+ }
119
+ async function grepCountAt(symbolOrPath, commit) {
120
+ try {
121
+ return lineCount(await git(["grep", "-F", "-n", "-e", symbolOrPath, commit, "--"]));
122
+ } catch (error) {
123
+ const detail = processError(error);
124
+ if (detail?.code === 1)
125
+ return 0;
126
+ throw error;
127
+ }
128
+ }
152
129
  return {
153
- id: String(issue.number),
154
- ...typeof issueNodeId === "string" && issueNodeId.trim() ? { issueNodeId: issueNodeId.trim() } : {},
155
- deps,
156
- status: statusFor(issue),
157
- title: issue.title,
158
- body,
159
- scope,
160
- role,
161
- validators,
162
- url: issue.url ?? issue.html_url,
163
- issueType: issueTypeFor(issue),
164
- sourceIssueId: `${repo}#${issue.number}`,
165
- parentChildDeps: parseParents(body),
166
- labels: labelNames,
167
- ...nativeDependencies?.degraded ? { nativeDependenciesDegraded: true, nativeDependenciesError: nativeDependencies.degraded } : {},
168
- raw: issue
130
+ async lastCommitTouching(path) {
131
+ const commit = (await git(["log", "-n", "1", "--format=%H", "--", path])).trim();
132
+ return commit || "HEAD";
133
+ },
134
+ async grepCount(symbolOrPath) {
135
+ return grepCountAt(symbolOrPath, "HEAD");
136
+ },
137
+ async grepCountAtCommit(symbolOrPath, commit) {
138
+ return grepCountAt(symbolOrPath, commit);
139
+ },
140
+ async wasRenamed(symbolOrPath, sinceCommit) {
141
+ if (!symbolOrPath.includes("/") && !symbolOrPath.includes("."))
142
+ return false;
143
+ try {
144
+ const output = await git(["log", "--name-status", "--format=", `${sinceCommit}..HEAD`]);
145
+ return output.split(/\r?\n/).some((line) => {
146
+ const match = line.match(/^R\d*\s+(.+?)\s+(.+)$/);
147
+ return Boolean(match && (match[1] === symbolOrPath || match[2] === symbolOrPath));
148
+ });
149
+ } catch (error) {
150
+ const detail = processError(error);
151
+ if (detail?.code === 128)
152
+ return false;
153
+ throw error;
154
+ }
155
+ }
169
156
  };
170
157
  }
171
- function labelNamesFor(issue) {
172
- return (issue.labels ?? []).flatMap((label) => {
173
- if (typeof label === "string")
174
- return [label];
175
- return typeof label.name === "string" ? [label.name] : [];
176
- });
177
- }
178
- function yamlScalar(value) {
179
- if (Array.isArray(value)) {
180
- return value.length === 0 ? "[]" : `
181
- ${value.map((entry) => ` - ${String(entry)}`).join(`
182
- `)}`;
183
- }
184
- if (value && typeof value === "object")
185
- return JSON.stringify(value);
186
- return String(value);
187
- }
188
- function updateRigOwnedMetadataBlock(body, metadata) {
189
- const rendered = [
190
- RIG_METADATA_START,
191
- ...Object.entries(metadata).map(([key, value]) => Array.isArray(value) ? `${key}:${yamlScalar(value)}` : `${key}: ${yamlScalar(value)}`),
192
- RIG_METADATA_END
193
- ].join(`
194
- `);
195
- const pattern = new RegExp(`${RIG_METADATA_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[\\s\\S]*?\\s*${RIG_METADATA_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
196
- if (pattern.test(body))
197
- return body.replace(pattern, rendered);
198
- return body.trim().length > 0 ? `${body.trimEnd()}
158
+ var execFileAsync;
159
+ var init_git_adapter = __esm(() => {
160
+ execFileAsync = promisify(execFile);
161
+ });
199
162
 
200
- ${rendered}
201
- ` : `${rendered}
202
- `;
163
+ // packages/standard-plugin/src/drift/detect.ts
164
+ var exports_detect = {};
165
+ __export(exports_detect, {
166
+ detectStaleAnchors: () => detectStaleAnchors,
167
+ detectDrift: () => detectDrift,
168
+ detectDeletedReferences: () => detectDeletedReferences
169
+ });
170
+ import { existsSync as existsSync3 } from "fs";
171
+ import { readdir, readFile, stat } from "fs/promises";
172
+ import { basename as basename2, extname, relative, resolve as resolve3 } from "path";
173
+ function globLikeMatch(path, pattern) {
174
+ if (pattern === path)
175
+ return true;
176
+ if (pattern.startsWith("**/*"))
177
+ return path.endsWith(pattern.slice(4));
178
+ if (pattern.endsWith("/**"))
179
+ return path.startsWith(pattern.slice(0, -3));
180
+ if (pattern.includes("*")) {
181
+ const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
182
+ return new RegExp(`^${escaped}$`).test(path);
183
+ }
184
+ return path.startsWith(pattern);
203
185
  }
204
- function buildRigStickyStatusComment(input) {
205
- const lines = [
206
- RIG_STATUS_COMMENT_MARKER,
207
- `### Rig status: ${input.status}`,
208
- "",
209
- input.summary
210
- ];
211
- if (input.runId)
212
- lines.push("", `- Run: ${input.runId}`);
213
- if (input.prUrl)
214
- lines.push(`- PR: ${input.prUrl}`);
215
- for (const detail of input.details ?? [])
216
- lines.push(`- ${detail}`);
217
- return lines.join(`
218
- `);
186
+ function isDefaultDoc(path) {
187
+ const lower = basename2(path).toLowerCase();
188
+ return (path.endsWith(".md") || path.endsWith(".mdx")) && !lower.startsWith("changelog") && !lower.includes("generated");
219
189
  }
220
- function isRigStickyStatusComment(body) {
221
- return body.includes(RIG_STATUS_COMMENT_MARKER);
190
+ function isIgnored(path, patterns) {
191
+ return (patterns ?? []).some((pattern) => globLikeMatch(path, pattern));
222
192
  }
223
- function ghSpawnOptions(extraEnv, timeoutMs) {
224
- return {
225
- encoding: "utf-8",
226
- timeout: timeoutMs,
227
- env: {
228
- ...process.env,
229
- ...process.env.GH_TOKEN !== undefined ? { GH_TOKEN: process.env.GH_TOKEN } : {},
230
- ...process.env.GITHUB_TOKEN !== undefined ? { GITHUB_TOKEN: process.env.GITHUB_TOKEN } : {},
231
- ...process.env.RIG_GITHUB_TOKEN !== undefined ? { RIG_GITHUB_TOKEN: process.env.RIG_GITHUB_TOKEN } : {},
232
- ...extraEnv ?? {}
193
+ async function collectFiles(root, options) {
194
+ const files = [];
195
+ async function visit(dir) {
196
+ for (const entry of await readdir(dir, { withFileTypes: true })) {
197
+ if (entry.isDirectory() && DEFAULT_IGNORED_DIRS[entry.name])
198
+ continue;
199
+ const absolute = resolve3(dir, entry.name);
200
+ const rel = relative(root, absolute).replace(/\\/g, "/");
201
+ if (isIgnored(rel, options.ignore))
202
+ continue;
203
+ if (entry.isDirectory()) {
204
+ await visit(absolute);
205
+ continue;
206
+ }
207
+ if (!entry.isFile())
208
+ continue;
209
+ if (options.docs) {
210
+ const matchesConfigured = options.patterns && options.patterns.length > 0 ? options.patterns.some((pattern) => globLikeMatch(rel, pattern)) : isDefaultDoc(rel);
211
+ if (matchesConfigured)
212
+ files.push(rel);
213
+ continue;
214
+ }
215
+ if (SOURCE_EXTENSIONS[extname(entry.name)])
216
+ files.push(rel);
233
217
  }
234
- };
218
+ }
219
+ await visit(root);
220
+ return files.sort();
235
221
  }
236
- function credentialEnv(token) {
237
- const clean = token?.trim() ?? "";
238
- return { GH_TOKEN: clean, GITHUB_TOKEN: clean, RIG_GITHUB_TOKEN: clean };
222
+ async function sourceReferenceCount(projectRoot, reference, docPath) {
223
+ if (reference.kind === "path")
224
+ return existsSync3(resolve3(projectRoot, reference.value)) ? 1 : 0;
225
+ let count = 0;
226
+ const sourceFiles = await collectFiles(projectRoot, { docs: false });
227
+ for (const sourceFile of sourceFiles) {
228
+ if (sourceFile === docPath)
229
+ continue;
230
+ const text = await readFile(resolve3(projectRoot, sourceFile), "utf8").catch(() => "");
231
+ if (text.includes(reference.value))
232
+ count += 1;
233
+ }
234
+ return count;
239
235
  }
240
- async function resolveCredentialEnv(opts, purpose) {
241
- if (!opts.credentialProvider)
242
- return;
243
- const input = {
244
- owner: opts.owner,
245
- repo: opts.repo,
246
- workspaceId: opts.workspaceId ?? `${opts.owner}/${opts.repo}`,
247
- ...opts.userId ? { userId: opts.userId } : {},
248
- purpose
236
+ function deletedReferenceFinding(docPath, reference) {
237
+ return {
238
+ kind: "deleted-reference",
239
+ docPath,
240
+ line: reference.line,
241
+ reference: reference.value,
242
+ detail: `Documented reference "${reference.value}" no longer exists in the source tree.`,
243
+ confidence: "high"
249
244
  };
250
- const resolved = await opts.credentialProvider.resolveGitHubToken(input);
251
- return credentialEnv(resolved.token);
252
245
  }
253
- function tokenDiagnostic(value) {
254
- const clean = value?.trim() ?? "";
255
- return clean ? `present(len=${clean.length})` : "missing";
246
+ function staleAnchorFinding(docPath, reference) {
247
+ return {
248
+ kind: "stale-anchor",
249
+ docPath,
250
+ line: reference.line,
251
+ reference: reference.value,
252
+ detail: `Documented path "${reference.value}" changed after this doc was last updated.`,
253
+ confidence: "medium"
254
+ };
256
255
  }
257
- function runGh(bin, args, spawn, extraEnv, timeoutMs) {
258
- const options = ghSpawnOptions(extraEnv, timeoutMs);
259
- const res = spawn(bin, [...args], options);
260
- assertGhSuccess(args, res, options.env);
261
- if (!res.stdout || res.stdout.trim() === "")
262
- return [];
263
- return JSON.parse(res.stdout);
256
+ async function detectDeletedReferences(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
257
+ const markdown = await readFile(resolve3(projectRoot, docPath), "utf8");
258
+ const docCommit = await git.lastCommitTouching(docPath);
259
+ const findings = [];
260
+ for (const reference of extractDriftReferences(markdown)) {
261
+ if (await sourceReferenceCount(projectRoot, reference, docPath) > 0)
262
+ continue;
263
+ if (await git.wasRenamed(reference.value, docCommit))
264
+ continue;
265
+ findings.push(deletedReferenceFinding(docPath, reference));
266
+ }
267
+ return findings;
264
268
  }
265
- function runGhVoid(bin, args, spawn, extraEnv, timeoutMs) {
266
- const options = ghSpawnOptions(extraEnv, timeoutMs);
267
- const res = spawn(bin, [...args], options);
268
- assertGhSuccess(args, res, options.env);
269
+ async function detectStaleAnchors(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
270
+ const markdown = await readFile(resolve3(projectRoot, docPath), "utf8");
271
+ const docCommit = await git.lastCommitTouching(docPath);
272
+ const findings = [];
273
+ for (const reference of extractDriftReferences(markdown).filter((ref) => ref.kind === "path")) {
274
+ if (!existsSync3(resolve3(projectRoot, reference.value)))
275
+ continue;
276
+ const sourceStat = await stat(resolve3(projectRoot, reference.value)).catch(() => null);
277
+ if (!sourceStat?.isFile())
278
+ continue;
279
+ const sourceCommit = await git.lastCommitTouching(reference.value);
280
+ if (sourceCommit !== docCommit && !await git.wasRenamed(reference.value, docCommit)) {
281
+ findings.push(staleAnchorFinding(docPath, reference));
282
+ }
283
+ }
284
+ return findings;
269
285
  }
270
- function assertGhSuccess(args, res, env) {
271
- if (res.error) {
272
- const msg = res.error.message ?? String(res.error);
273
- throw new Error(`gh CLI not available \u2014 install gh (brew install gh / apt install gh): ${msg}`);
286
+ async function detectDrift(options) {
287
+ const git = options.git ?? makeDriftGit(options.projectRoot);
288
+ const docs = await collectFiles(options.projectRoot, {
289
+ docs: true,
290
+ ...options.docsGlobs !== undefined ? { patterns: options.docsGlobs } : {},
291
+ ...options.ignoreGlobs !== undefined ? { ignore: options.ignoreGlobs } : {}
292
+ });
293
+ const findings = [];
294
+ let degraded = false;
295
+ for (const docPath of docs) {
296
+ try {
297
+ findings.push(...await detectDeletedReferences(options.projectRoot, docPath, git));
298
+ findings.push(...await detectStaleAnchors(options.projectRoot, docPath, git));
299
+ } catch {
300
+ degraded = true;
301
+ }
274
302
  }
275
- if (res.status !== 0) {
276
- throw new Error(`gh ${args.join(" ")} failed (exit ${res.status}): ${res.stderr}
277
- [rig gh env:standard-plugin] GH_TOKEN=${tokenDiagnostic(env.GH_TOKEN)} GITHUB_TOKEN=${tokenDiagnostic(env.GITHUB_TOKEN)} RIG_GITHUB_TOKEN=${tokenDiagnostic(env.RIG_GITHUB_TOKEN)}`);
303
+ return {
304
+ generatedAt: new Date().toISOString(),
305
+ scanned: docs.length,
306
+ degraded,
307
+ findings
308
+ };
309
+ }
310
+ var DEFAULT_IGNORED_DIRS, SOURCE_EXTENSIONS;
311
+ var init_detect = __esm(() => {
312
+ init_extract_refs();
313
+ init_git_adapter();
314
+ DEFAULT_IGNORED_DIRS = {
315
+ ".git": true,
316
+ node_modules: true,
317
+ dist: true,
318
+ build: true,
319
+ coverage: true,
320
+ ".next": true,
321
+ vendor: true
322
+ };
323
+ SOURCE_EXTENSIONS = {
324
+ ".ts": true,
325
+ ".tsx": true,
326
+ ".js": true,
327
+ ".jsx": true,
328
+ ".mjs": true,
329
+ ".cjs": true,
330
+ ".rs": true,
331
+ ".go": true,
332
+ ".py": true,
333
+ ".rb": true,
334
+ ".java": true,
335
+ ".kt": true,
336
+ ".swift": true,
337
+ ".c": true,
338
+ ".cc": true,
339
+ ".cpp": true,
340
+ ".h": true,
341
+ ".hpp": true,
342
+ ".json": true,
343
+ ".toml": true,
344
+ ".yml": true,
345
+ ".yaml": true
346
+ };
347
+ });
348
+
349
+ // packages/standard-plugin/src/drift/plugin.ts
350
+ var exports_plugin = {};
351
+ __export(exports_plugin, {
352
+ runDriftCli: () => runDriftCli,
353
+ runDocsDriftValidation: () => runDocsDriftValidation,
354
+ highConfidenceDriftFindings: () => highConfidenceDriftFindings,
355
+ executeDrift: () => executeDrift,
356
+ driftGateResult: () => driftGateResult,
357
+ createDocsDriftValidator: () => createDocsDriftValidator,
358
+ createDocsDriftRuntimeCliCommand: () => createDocsDriftRuntimeCliCommand,
359
+ createDocsDriftGateStage: () => createDocsDriftGateStage,
360
+ DOCS_DRIFT_VALIDATOR_ID: () => DOCS_DRIFT_VALIDATOR_ID,
361
+ DOCS_DRIFT_VALIDATOR: () => DOCS_DRIFT_VALIDATOR,
362
+ DOCS_DRIFT_STAGE_MUTATION: () => DOCS_DRIFT_STAGE_MUTATION,
363
+ DOCS_DRIFT_STAGE_ID: () => DOCS_DRIFT_STAGE_ID,
364
+ DOCS_DRIFT_RUNTIME_CLI_COMMAND: () => DOCS_DRIFT_RUNTIME_CLI_COMMAND,
365
+ DOCS_DRIFT_CLI_ID: () => DOCS_DRIFT_CLI_ID,
366
+ DOCS_DRIFT_CLI_COMMAND: () => DOCS_DRIFT_CLI_COMMAND,
367
+ DOCS_DRIFT_CAPABILITY_ID: () => DOCS_DRIFT_CAPABILITY_ID
368
+ });
369
+ function highConfidenceDriftFindings(report) {
370
+ return report.findings.filter((finding) => finding.confidence === "high");
371
+ }
372
+ function driftGateResult(report, mode = "enforce") {
373
+ const high = highConfidenceDriftFindings(report);
374
+ if (mode === "enforce" && high.length > 0) {
375
+ return { kind: "block", reason: `${high.length} high-confidence documentation drift finding(s).` };
278
376
  }
377
+ return { kind: "allow" };
279
378
  }
280
- var DEFAULT_PROJECT_STATUSES = {
281
- todo: "Todo",
282
- running: "In Progress",
283
- prOpen: "In Review",
284
- ciFixing: "In Review",
285
- merging: "In Review",
286
- done: "Done",
287
- needsAttention: "Needs Attention"
288
- };
289
- function asProjectRecord(value) {
290
- return value && typeof value === "object" && !Array.isArray(value) ? value : null;
379
+ function createDocsDriftGateStage(options = {}) {
380
+ return async (ctx) => {
381
+ const projectRoot = typeof ctx.metadata?.projectRoot === "string" ? ctx.metadata.projectRoot : process.cwd();
382
+ const report = await detectDrift({
383
+ projectRoot,
384
+ ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
385
+ ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {}
386
+ });
387
+ return driftGateResult(report, options.failOnDrift ? "enforce" : "observe");
388
+ };
291
389
  }
292
- function projectString(value) {
293
- return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
390
+ async function runDocsDriftValidation(options) {
391
+ const report = await detectDrift(options);
392
+ const high = highConfidenceDriftFindings(report);
393
+ const passed = options.failOnDrift ? high.length === 0 : true;
394
+ const findingWord = report.findings.length === 1 ? "finding" : "findings";
395
+ return {
396
+ id: DOCS_DRIFT_VALIDATOR_ID,
397
+ passed,
398
+ summary: `docs drift scanned ${report.scanned} doc(s), ${report.findings.length} ${findingWord}`,
399
+ details: JSON.stringify(report)
400
+ };
294
401
  }
295
- function projectLifecycleStatusForTaskStatus(status) {
296
- const normalized = status?.trim().toLowerCase().replace(/[-\s]+/g, "_");
297
- switch (normalized) {
298
- case "draft":
299
- case "open":
300
- case "queued":
301
- case "ready":
302
- return "todo";
303
- case "running":
304
- case "in_progress":
305
- return "running";
306
- case "under_review":
307
- case "review":
308
- case "pr_open":
309
- return "prOpen";
310
- case "ci_fixing":
311
- case "fixing":
312
- return "ciFixing";
313
- case "merging":
314
- case "merge":
315
- return "merging";
316
- case "closed":
317
- case "completed":
318
- case "done":
319
- return "done";
320
- case "blocked":
321
- case "cancelled":
322
- case "failed":
323
- case "needs_attention":
324
- return "needsAttention";
325
- default:
326
- return null;
327
- }
328
- }
329
- function ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs) {
330
- return async (query, variables) => {
331
- const args = ["api", "graphql", "-f", `query=${query}`];
332
- for (const [key, value] of Object.entries(variables)) {
333
- if (value === undefined || value === null)
334
- continue;
335
- args.push("-f", `${key}=${String(value)}`);
402
+ function createDocsDriftValidator(options = {}) {
403
+ return {
404
+ ...DOCS_DRIFT_VALIDATOR,
405
+ async run(ctx) {
406
+ return runDocsDriftValidation({
407
+ projectRoot: ctx.workspaceRoot,
408
+ ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
409
+ ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {},
410
+ ...options.failOnDrift !== undefined ? { failOnDrift: options.failOnDrift } : {}
411
+ });
336
412
  }
337
- const response = runGh(bin, args, spawnFn, extraEnv, timeoutMs);
338
- return asProjectRecord(response)?.data ?? response;
339
413
  };
340
414
  }
341
- function issueNodeIdFor(issue) {
342
- const id = issue.id ?? issue.nodeId ?? issue.node_id;
343
- return typeof id === "string" && id.trim().length > 0 ? id.trim() : null;
344
- }
345
- function nativeIssueDependencyRef(value, currentRepo) {
346
- const record = asProjectRecord(value);
347
- const number = typeof record?.number === "number" ? String(record.number) : projectString(record?.number);
348
- if (!number)
349
- return null;
350
- const repository = asProjectRecord(record?.repository);
351
- const owner = projectString(asProjectRecord(repository?.owner)?.login);
352
- const name = projectString(repository?.name);
353
- if (!owner || !name || `${owner}/${name}` === currentRepo)
354
- return number;
355
- return `${owner}/${name}#${number}`;
415
+ function takeOptionValue(args, index, flag) {
416
+ const value = args[index + 1];
417
+ if (!value)
418
+ throw new Error(`${flag} requires a value`);
419
+ return value;
356
420
  }
357
- function nativeDependencyRefsFrom(data, currentRepo) {
358
- const issue = asProjectRecord(asProjectRecord(data)?.node);
359
- const blockedBy = asProjectRecord(issue?.blockedBy);
360
- const nodes = Array.isArray(blockedBy?.nodes) ? blockedBy.nodes : [];
361
- return [...new Set(nodes.flatMap((node) => {
362
- const ref = nativeIssueDependencyRef(node, currentRepo);
363
- return ref ? [ref] : [];
364
- }))];
421
+ function takeFlag(args, flag) {
422
+ const rest = [...args];
423
+ const index = rest.indexOf(flag);
424
+ if (index < 0)
425
+ return { value: false, rest };
426
+ rest.splice(index, 1);
427
+ return { value: true, rest };
365
428
  }
366
- async function readNativeDependenciesForIssue(input) {
367
- const issueId = issueNodeIdFor(input.issue);
368
- if (!issueId)
369
- return { deps: [], degraded: "GitHub issue node id is unavailable." };
370
- const query = `
371
- query RigIssueNativeDependencies($issueId: ID!) {
372
- node(id: $issueId) {
373
- ... on Issue {
374
- blockedBy(first: 100) {
375
- nodes {
376
- number
377
- repository { name owner { login } }
378
- }
379
- }
380
- }
381
- }
382
- }
383
- `;
384
- try {
385
- return {
386
- deps: nativeDependencyRefsFrom(await input.fetchGraphQL(query, { issueId }, "gh-cli"), input.repo)
387
- };
388
- } catch (error) {
389
- const detail = error instanceof Error ? error.message : String(error);
390
- return { deps: [], degraded: detail };
391
- }
429
+ function takeOption(args, flag) {
430
+ const rest = [...args];
431
+ const index = rest.indexOf(flag);
432
+ if (index < 0)
433
+ return { rest };
434
+ const value = rest[index + 1];
435
+ if (!value || value.startsWith("-"))
436
+ throw new Error(`${flag} requires a value.`);
437
+ rest.splice(index, 2);
438
+ return { value, rest };
392
439
  }
393
- function formatIssueReference(ref) {
394
- const clean = ref.trim().replace(/^#/, "");
395
- return /^\d+$/.test(clean) ? `#${clean}` : clean;
440
+ function requireNoExtraArgs(args, usage) {
441
+ if (args.length > 0)
442
+ throw new Error(`Unexpected argument: ${args[0]}
443
+ Usage: ${usage}`);
396
444
  }
397
- function appendReferenceLines(body, deps, parents) {
398
- const lines = [];
399
- const cleanDeps = (deps ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
400
- const cleanParents = (parents ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
401
- if (cleanDeps.length > 0)
402
- lines.push(`depends-on: ${cleanDeps.join(", ")}`);
403
- if (cleanParents.length > 0)
404
- lines.push(`parents: ${cleanParents.join(", ")}`);
405
- if (lines.length === 0)
406
- return body;
407
- return body.trim().length > 0 ? `${body.trimEnd()}
408
-
409
- ${lines.join(`
410
- `)}` : lines.join(`
411
- `);
445
+ function parseCsv(value) {
446
+ return value?.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0) ?? [];
412
447
  }
413
- function bodyForCreatedTask(input) {
414
- const metadata = { ...input.metadata ?? {} };
415
- if (input.deps && input.deps.length > 0)
416
- metadata["depends-on"] = input.deps.map(formatIssueReference);
417
- if (input.parents && input.parents.length > 0)
418
- metadata.parents = input.parents.map(formatIssueReference);
419
- return updateRigOwnedMetadataBlock(appendReferenceLines(input.body, input.deps, input.parents), metadata);
448
+ function driftSummary(report) {
449
+ const highConfidence = highConfidenceDriftFindings(report).length;
450
+ return { total: report.findings.length, highConfidence, degraded: report.degraded };
420
451
  }
421
- function projectStatusFieldFrom(data, projectId) {
422
- const fields = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.fields)?.nodes;
423
- for (const node of Array.isArray(fields) ? fields : []) {
424
- const record = asProjectRecord(node);
425
- if (projectString(record?.name)?.toLowerCase() !== "status")
426
- continue;
427
- const id = projectString(record?.id);
428
- if (!id)
429
- continue;
430
- const options = Array.isArray(record?.options) ? record.options.flatMap((option) => {
431
- const optionRecord = asProjectRecord(option);
432
- const optionId = projectString(optionRecord?.id);
433
- const name = projectString(optionRecord?.name);
434
- return optionId && name ? [{ id: optionId, name }] : [];
435
- }) : [];
436
- return { id, name: "Status", options };
452
+ async function executeDrift(context, args, options = {}) {
453
+ const json = takeFlag(args, "--json");
454
+ const docs = takeOption(json.rest, "--docs");
455
+ const ignore = takeOption(docs.rest, "--ignore");
456
+ const failOnDrift = takeFlag(ignore.rest, "--fail-on-drift");
457
+ requireNoExtraArgs(failOnDrift.rest, "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]");
458
+ const docsGlobs = parseCsv(docs.value);
459
+ const ignoreGlobs = parseCsv(ignore.value);
460
+ const effectiveDocsGlobs = docsGlobs.length > 0 ? docsGlobs : options.docsGlobs;
461
+ const effectiveIgnoreGlobs = ignoreGlobs.length > 0 ? ignoreGlobs : options.ignoreGlobs;
462
+ const effectiveFailOnDrift = failOnDrift.value || options.failOnDrift === true;
463
+ const report = await detectDrift({
464
+ projectRoot: context.projectRoot,
465
+ ...effectiveDocsGlobs !== undefined ? { docsGlobs: effectiveDocsGlobs } : {},
466
+ ...effectiveIgnoreGlobs !== undefined ? { ignoreGlobs: effectiveIgnoreGlobs } : {}
467
+ });
468
+ const failed = effectiveFailOnDrift && highConfidenceDriftFindings(report).length > 0;
469
+ const details = { report, summary: driftSummary(report), failOnDrift: effectiveFailOnDrift, failed };
470
+ if (context.outputMode === "text") {
471
+ if (json.value)
472
+ console.log(JSON.stringify(details, null, 2));
473
+ else
474
+ 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(`
475
+ `));
437
476
  }
438
- throw new Error(`GitHub Project ${projectId} does not expose a Status single-select field.`);
477
+ return { ok: !failed, group: "drift", command: "scan", details };
439
478
  }
440
- async function resolveProjectStatusField(input) {
441
- const query = `
442
- query RigProjectStatusField($projectId: ID!) {
443
- node(id: $projectId) {
444
- ... on ProjectV2 {
445
- fields(first: 50) {
446
- nodes {
447
- ... on ProjectV2FieldCommon { id name }
448
- ... on ProjectV2SingleSelectField { id name options { id name } }
449
- }
450
- }
451
- }
452
- }
453
- }
454
- `;
455
- return projectStatusFieldFrom(await input.fetchGraphQL(query, { projectId: input.projectId }, input.token), input.projectId);
479
+ function createDocsDriftRuntimeCliCommand(options = {}) {
480
+ return {
481
+ id: DOCS_DRIFT_CLI_ID,
482
+ family: "drift",
483
+ command: DOCS_DRIFT_CLI_COMMAND,
484
+ description: "Scan documentation for stale code references.",
485
+ usage: DOCS_DRIFT_CLI_COMMAND,
486
+ projectRequired: true,
487
+ run: (context, args) => executeDrift(context, args, options)
488
+ };
456
489
  }
457
- async function ensureIssueProjectItem(input) {
458
- const query = `
459
- query RigFindProjectIssueItem($projectId: ID!) {
460
- node(id: $projectId) {
461
- ... on ProjectV2 {
462
- items(first: 100) { nodes { id content { ... on Issue { id } } } }
463
- }
464
- }
490
+ async function runDriftCli(args, options = {}) {
491
+ const docsGlobs = [];
492
+ const ignoreGlobs = [];
493
+ let json = false;
494
+ let failOnDrift = false;
495
+ for (let index = 0;index < args.length; index += 1) {
496
+ const arg = args[index];
497
+ if (arg === "--json") {
498
+ json = true;
499
+ continue;
465
500
  }
466
- `;
467
- const data = await input.fetchGraphQL(query, { projectId: input.projectId }, input.token);
468
- const nodes = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.items)?.nodes;
469
- for (const node of Array.isArray(nodes) ? nodes : []) {
470
- const record = asProjectRecord(node);
471
- const content = asProjectRecord(record?.content);
472
- if (projectString(content?.id) === input.issueNodeId) {
473
- const id2 = projectString(record?.id);
474
- if (id2)
475
- return { id: id2, created: false };
501
+ if (arg === "--fail-on-drift") {
502
+ failOnDrift = true;
503
+ continue;
476
504
  }
477
- }
478
- const mutation = `
479
- mutation RigAddIssueToProject($projectId: ID!, $contentId: ID!) {
480
- addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) { item { id } }
505
+ if (arg === "--docs") {
506
+ docsGlobs.push(takeOptionValue(args, index, arg));
507
+ index += 1;
508
+ continue;
481
509
  }
482
- `;
483
- const created = await input.fetchGraphQL(mutation, { projectId: input.projectId, contentId: input.issueNodeId }, input.token);
484
- const addResult = asProjectRecord(asProjectRecord(created)?.addProjectV2ItemById);
485
- const id = projectString(asProjectRecord(addResult?.item)?.id);
486
- if (!id)
487
- throw new Error("GitHub Project item creation did not return an item id.");
488
- return { id, created: true };
510
+ if (arg === "--ignore") {
511
+ ignoreGlobs.push(takeOptionValue(args, index, arg));
512
+ index += 1;
513
+ continue;
514
+ }
515
+ throw new Error(`Unknown rig drift argument: ${arg}`);
516
+ }
517
+ const report = await detectDrift({
518
+ projectRoot: options.projectRoot ?? process.cwd(),
519
+ ...docsGlobs.length > 0 ? { docsGlobs } : {},
520
+ ...ignoreGlobs.length > 0 ? { ignoreGlobs } : {}
521
+ });
522
+ const write = options.write ?? ((message) => console.log(message));
523
+ if (json) {
524
+ write(JSON.stringify(report));
525
+ } else {
526
+ write(`Scanned ${report.scanned} doc(s); ${report.findings.length} drift finding(s).`);
527
+ for (const finding of report.findings) {
528
+ write(`${finding.confidence.toUpperCase()} ${finding.kind} ${finding.docPath}${finding.line ? `:${finding.line}` : ""} ${finding.reference ?? ""} \u2014 ${finding.detail}`);
529
+ }
530
+ }
531
+ const high = highConfidenceDriftFindings(report);
532
+ if (failOnDrift && high.length > 0) {
533
+ options.writeError?.(`${high.length} high-confidence drift finding(s).`);
534
+ return 2;
535
+ }
536
+ return 0;
489
537
  }
490
- async function updateIssueProjectStatus(input) {
491
- const mutation = `
492
- mutation RigUpdateProjectStatus($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
493
- updateProjectV2ItemFieldValue(input: {
494
- projectId: $projectId,
495
- itemId: $itemId,
496
- fieldId: $fieldId,
497
- value: { singleSelectOptionId: $optionId }
498
- }) { projectV2Item { id } }
538
+ var DOCS_DRIFT_RUNTIME_CLI_COMMAND;
539
+ var init_plugin = __esm(() => {
540
+ init_detect();
541
+ init_metadata();
542
+ init_metadata();
543
+ DOCS_DRIFT_RUNTIME_CLI_COMMAND = createDocsDriftRuntimeCliCommand();
544
+ });
545
+
546
+ // packages/standard-plugin/src/plugin.ts
547
+ import { resolve as resolve4 } from "path";
548
+ import { definePlugin } from "@rig/core/config";
549
+
550
+ // packages/standard-plugin/src/github-issues-source.ts
551
+ import { spawnSync } from "child_process";
552
+ import { existsSync, readFileSync } from "fs";
553
+ import { resolve } from "path";
554
+ function cleanToken(value) {
555
+ const trimmed = value?.trim() ?? "";
556
+ return trimmed.length > 0 ? trimmed : null;
557
+ }
558
+ function createEnvGitHubCredentialProvider() {
559
+ return {
560
+ async resolveGitHubToken(input) {
561
+ if (input.purpose === "selected-repo") {
562
+ return { token: cleanToken(process.env.RIG_GITHUB_SELECTED_TOKEN ?? null) ?? "", source: "signed-in-user" };
563
+ }
564
+ const token = cleanToken(process.env.RIG_GITHUB_TOKEN ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? null);
565
+ if (!token) {
566
+ throw new Error("No host GitHub token is configured for admin fallback.");
567
+ }
568
+ return { token, source: "host-admin-fallback" };
499
569
  }
500
- `;
501
- await input.fetchGraphQL(mutation, {
502
- projectId: input.projectId,
503
- itemId: input.itemId,
504
- fieldId: input.fieldId,
505
- optionId: input.optionId
506
- }, input.token);
570
+ };
507
571
  }
508
- function fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
509
- const issue = runGh(bin, ["issue", "view", String(id), "--repo", repo, "--json", "id"], spawnFn, extraEnv, timeoutMs);
510
- return projectString(issue.id) ?? projectString(issue.nodeId) ?? projectString(issue.node_id);
572
+ function createStateGitHubCredentialProvider(options = {}) {
573
+ const addCandidate = (candidates, path) => {
574
+ const trimmed = path?.trim();
575
+ if (!trimmed)
576
+ return;
577
+ const resolved = resolve(trimmed);
578
+ if (!candidates.includes(resolved))
579
+ candidates.push(resolved);
580
+ };
581
+ const addStateDir = (candidates, dir) => {
582
+ const trimmed = dir?.trim();
583
+ if (!trimmed)
584
+ return;
585
+ addCandidate(candidates, resolve(trimmed, "github-auth.json"));
586
+ };
587
+ const addProjectStateDir = (candidates, root) => {
588
+ const trimmed = root?.trim();
589
+ if (!trimmed)
590
+ return;
591
+ addStateDir(candidates, resolve(trimmed, ".rig", "state"));
592
+ };
593
+ const stateFileCandidates = () => {
594
+ const candidates = [];
595
+ addCandidate(candidates, options.stateFile ?? process.env.RIG_GITHUB_AUTH_STATE_FILE);
596
+ addStateDir(candidates, options.stateDir);
597
+ addStateDir(candidates, process.env.RIG_STATE_DIR);
598
+ addProjectStateDir(candidates, process.env.PROJECT_RIG_ROOT);
599
+ addProjectStateDir(candidates, process.env.RIG_PROJECT_ROOT);
600
+ addProjectStateDir(candidates, process.env.RIG_HOST_PROJECT_ROOT);
601
+ addProjectStateDir(candidates, process.cwd());
602
+ return candidates;
603
+ };
604
+ const readToken = () => {
605
+ for (const stateFile of stateFileCandidates()) {
606
+ if (!existsSync(stateFile))
607
+ continue;
608
+ try {
609
+ const parsed = JSON.parse(readFileSync(stateFile, "utf8"));
610
+ const token = typeof parsed.token === "string" ? cleanToken(parsed.token) : null;
611
+ if (token)
612
+ return token;
613
+ } catch {}
614
+ }
615
+ return null;
616
+ };
617
+ return {
618
+ async resolveGitHubToken(input) {
619
+ const token = readToken();
620
+ if (input.purpose === "selected-repo") {
621
+ return { token: token ?? cleanToken(process.env.RIG_GITHUB_SELECTED_TOKEN ?? null) ?? "", source: "signed-in-user" };
622
+ }
623
+ if (token) {
624
+ return { token, source: "signed-in-user" };
625
+ }
626
+ const fallback = cleanToken(process.env.RIG_GITHUB_TOKEN ?? process.env.GH_TOKEN ?? process.env.GITHUB_TOKEN ?? null);
627
+ if (!fallback) {
628
+ throw new Error("No signed-in GitHub token is stored for Rig and no host admin fallback token is configured.");
629
+ }
630
+ return { token: fallback, source: "host-admin-fallback" };
631
+ }
632
+ };
511
633
  }
512
- async function syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs) {
513
- if (!projects?.enabled)
514
- return;
515
- const projectId = projectString(projects.projectId);
516
- if (!projectId)
517
- throw new Error("GitHub Projects status sync is enabled but projectId is missing.");
518
- const lifecycleStatus = projectLifecycleStatusForTaskStatus(status);
519
- if (!lifecycleStatus)
520
- return;
521
- const issueNodeId = fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs);
522
- if (!issueNodeId)
523
- throw new Error(`GitHub issue ${repo}#${id} did not expose a node id for Projects status sync.`);
524
- const projectStatus = projectString(projects.statuses?.[lifecycleStatus]) ?? DEFAULT_PROJECT_STATUSES[lifecycleStatus];
525
- const fetchGraphQL = ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs);
526
- const field = await resolveProjectStatusField({ projectId, token: "gh-cli", fetchGraphQL });
527
- const option = field.options.find((candidate) => candidate.name.toLowerCase() === projectStatus.toLowerCase() || candidate.id === projectStatus);
528
- if (!option)
529
- throw new Error(`GitHub Project ${projectId} Status field does not contain option "${projectStatus}".`);
530
- const item = await ensureIssueProjectItem({ projectId, issueNodeId, token: "gh-cli", fetchGraphQL });
531
- await updateIssueProjectStatus({
532
- projectId,
533
- itemId: item.id,
534
- fieldId: projectString(projects.statusFieldId) ?? field.id,
535
- optionId: option.id,
536
- token: "gh-cli",
537
- fetchGraphQL
538
- });
634
+ var STATUS_LABELS = new Set(["ready", "blocked", "in-progress", "under-review", "failed", "cancelled"]);
635
+ var RIG_STATUS_COMMENT_MARKER = "<!-- rig:status-comment -->";
636
+ var RIG_METADATA_START = "<!-- rig:metadata:start -->";
637
+ var RIG_METADATA_END = "<!-- rig:metadata:end -->";
638
+ var RIG_STATUS_LABELS = new Set(["rig:running", "rig:pr-open", "rig:ci-fixing", "rig:merging", "rig:done", "rig:needs-attention"]);
639
+ var DEFAULT_GH_TIMEOUT_MS = 15000;
640
+ var DEFAULT_GITHUB_ISSUE_LIST_LIMIT = 1000;
641
+ function statusFor(issue) {
642
+ const state = (issue.state ?? "").toUpperCase();
643
+ if (state === "CLOSED")
644
+ return "closed";
645
+ const labelNames = labelNamesFor(issue);
646
+ if (labelNames.includes("in-progress"))
647
+ return "in_progress";
648
+ if (labelNames.includes("blocked"))
649
+ return "blocked";
650
+ if (labelNames.includes("ready"))
651
+ return "ready";
652
+ if (labelNames.includes("under-review"))
653
+ return "under_review";
654
+ if (labelNames.includes("failed"))
655
+ return "failed";
656
+ if (labelNames.includes("cancelled"))
657
+ return "cancelled";
658
+ return "open";
539
659
  }
540
- var TERMINAL_TASK_STATUSES = new Set(["closed", "completed", "merged", "cancelled", "resolved", "done"]);
541
- function normalizeTaskStatusToken(status) {
542
- return status?.trim().toLowerCase().replace(/[-\s]+/g, "_") ?? "";
660
+ function parseIssueRefs(raw) {
661
+ const refs = [...raw.matchAll(/(?:^|[^\w/.-])(?:[\w.-]+\/[\w.-]+#|#)?(\d+)\b/g)].map((match) => match[1]).filter((value) => Boolean(value));
662
+ return [...new Set(refs)];
543
663
  }
544
- function issueUpdatesMode(value) {
545
- return value === "off" || value === "minimal" || value === "lifecycle" ? value : "lifecycle";
664
+ function metadataKeyPattern(keys) {
665
+ return new RegExp(`^(?:${keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")}):\\s*(.*)$`, "i");
546
666
  }
547
- function isTerminalTaskStatus(status) {
548
- return TERMINAL_TASK_STATUSES.has(normalizeTaskStatusToken(status));
667
+ function parseMetadataList(body, keys) {
668
+ const block = body.match(/<!-- rig:metadata:start -->\s*([\s\S]*?)\s*<!-- rig:metadata:end -->/);
669
+ if (!block)
670
+ return [];
671
+ const lines = block[1].split(/\r?\n/);
672
+ const values = [];
673
+ const keyPattern = metadataKeyPattern(keys);
674
+ for (let index = 0;index < lines.length; index += 1) {
675
+ const line = lines[index];
676
+ const sameLine = line.match(keyPattern);
677
+ if (!sameLine)
678
+ continue;
679
+ const inlineValue = sameLine[1]?.trim() ?? "";
680
+ if (inlineValue) {
681
+ values.push(...parseIssueRefs(inlineValue));
682
+ continue;
683
+ }
684
+ for (let cursor = index + 1;cursor < lines.length; cursor += 1) {
685
+ const item = lines[cursor].match(/^\s*-\s*(.+)$/);
686
+ if (!item)
687
+ break;
688
+ values.push(...parseIssueRefs(item[1]));
689
+ }
690
+ }
691
+ return [...new Set(values)];
549
692
  }
550
- function shouldWriteIssueUpdate(mode, status) {
551
- if (mode === "off")
552
- return false;
553
- if (mode === "lifecycle")
554
- return true;
555
- return isTerminalTaskStatus(status);
693
+ function bodyWithoutRigMetadataBlock(body) {
694
+ return body.replace(/<!-- rig:metadata:start -->\s*[\s\S]*?\s*<!-- rig:metadata:end -->/g, "");
556
695
  }
557
- function isRunningStatus(status) {
558
- return normalizeTaskStatusToken(status) === "running";
696
+ function parseBodyKeyRefs(body, keys) {
697
+ const keyPattern = metadataKeyPattern(keys);
698
+ const values = bodyWithoutRigMetadataBlock(body).split(/\r?\n/).flatMap((line) => {
699
+ const match = line.match(keyPattern);
700
+ return match?.[1] ? parseIssueRefs(match[1]) : [];
701
+ });
702
+ return [...new Set(values)];
559
703
  }
560
- function assignRunningIssue(bin, repo, spawnFn, id, assignee, extraEnv, timeoutMs) {
561
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-assignee", assignee?.trim() || "@me"], spawnFn, extraEnv, timeoutMs);
704
+ function parseDeps(body) {
705
+ const keys = ["depends-on", "deps", "blocked-by", "blocked_by"];
706
+ return [...new Set([...parseBodyKeyRefs(body, keys), ...parseMetadataList(body, keys)])];
562
707
  }
563
- function statusLabelFor(status) {
564
- switch (status) {
565
- case "running":
566
- case "in_progress":
567
- return "in-progress";
568
- case "blocked":
569
- return "blocked";
570
- case "ready":
571
- return "ready";
572
- case "under_review":
573
- return "under-review";
574
- case "failed":
575
- return "failed";
576
- case "cancelled":
577
- return "cancelled";
578
- case "ci_fixing":
579
- return "under-review";
580
- case "merging":
581
- return "under-review";
582
- case "needs_attention":
583
- return "blocked";
584
- case "closed":
585
- case "completed":
586
- case "open":
587
- return null;
588
- default:
589
- throw new Error(`unsupported status: ${status}`);
590
- }
708
+ function parseParents(body) {
709
+ const keys = ["parents", "parent"];
710
+ return [...new Set([...parseBodyKeyRefs(body, keys), ...parseMetadataList(body, keys)])];
591
711
  }
592
- function rigStatusLabelFor(status) {
593
- switch (status) {
594
- case "running":
595
- case "in_progress":
596
- return "rig:running";
597
- case "under_review":
598
- return "rig:pr-open";
599
- case "closed":
600
- case "completed":
601
- return "rig:done";
602
- case "ci_fixing":
603
- return "rig:ci-fixing";
604
- case "merging":
605
- return "rig:merging";
606
- case "needs_attention":
607
- case "failed":
608
- case "blocked":
609
- return "rig:needs-attention";
610
- case "ready":
611
- case "cancelled":
612
- case "open":
613
- return null;
614
- default:
615
- return null;
616
- }
712
+ function issueTypeFor(issue) {
713
+ const labels = labelNamesFor(issue);
714
+ const typed = labels.find((l) => l.startsWith("type:"));
715
+ if (typed)
716
+ return typed.slice("type:".length);
717
+ if (labels.includes("epic"))
718
+ return "epic";
719
+ return "task";
617
720
  }
618
- async function applyIssueStatus(bin, repo, spawnFn, id, status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
619
- const targetLabel = status === "closed" || status === "completed" ? null : statusLabelFor(status);
620
- const targetRigLabel = rigStatusLabelFor(status);
621
- const shouldSyncLifecycle = shouldWriteIssueUpdate(issueUpdates, status);
622
- for (const l of [...STATUS_LABELS, ...RIG_STATUS_LABELS]) {
623
- if (targetLabel !== null && l === targetLabel)
624
- continue;
625
- if (targetRigLabel !== null && l === targetRigLabel)
626
- continue;
627
- try {
628
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--remove-label", l], spawnFn, extraEnv, timeoutMs);
629
- } catch {}
630
- }
631
- for (const label of [targetLabel, targetRigLabel].filter((value) => Boolean(value))) {
632
- try {
633
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
634
- } catch (error) {
635
- const message = error instanceof Error ? error.message : String(error);
636
- if (!/not found/i.test(message)) {
637
- throw error;
638
- }
639
- ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
640
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
641
- }
642
- }
643
- if (isRunningStatus(status)) {
644
- assignRunningIssue(bin, repo, spawnFn, id, runningAssignee, extraEnv, timeoutMs);
645
- if (shouldSyncLifecycle) {
646
- upsertRigStickyComment(bin, repo, spawnFn, String(id), buildRigStickyStatusComment({
647
- status: "running",
648
- summary: "Rig run started."
649
- }), extraEnv, timeoutMs);
650
- }
651
- }
652
- if (shouldSyncLifecycle) {
653
- await syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs);
654
- }
655
- if (status === "closed" || status === "completed") {
656
- runGhVoid(bin, ["issue", "close", String(id), "--repo", repo], spawnFn, extraEnv, timeoutMs);
721
+ function issueToTask(issue, repo, nativeDependencies) {
722
+ const labelNames = labelNamesFor(issue);
723
+ const scope = labelNames.filter((l) => l.startsWith("scope:")).map((l) => l.slice("scope:".length));
724
+ const roleLabel = labelNames.find((l) => l.startsWith("role:"));
725
+ const role = roleLabel ? roleLabel.slice("role:".length) : undefined;
726
+ const validators = labelNames.filter((l) => l.startsWith("validator:")).map((l) => l.slice("validator:".length));
727
+ const body = issue.body ?? "";
728
+ const issueNodeId = issue.id ?? issue.nodeId ?? issue.node_id;
729
+ const parsedDeps = parseDeps(body);
730
+ const deps = nativeDependencies?.deps ? [...new Set([...parsedDeps, ...nativeDependencies.deps])] : parsedDeps;
731
+ return {
732
+ id: String(issue.number),
733
+ ...typeof issueNodeId === "string" && issueNodeId.trim() ? { issueNodeId: issueNodeId.trim() } : {},
734
+ deps,
735
+ status: statusFor(issue),
736
+ title: issue.title,
737
+ body,
738
+ scope,
739
+ role,
740
+ validators,
741
+ url: issue.url ?? issue.html_url,
742
+ issueType: issueTypeFor(issue),
743
+ sourceIssueId: `${repo}#${issue.number}`,
744
+ parentChildDeps: parseParents(body),
745
+ labels: labelNames,
746
+ ...nativeDependencies?.degraded ? { nativeDependenciesDegraded: true, nativeDependenciesError: nativeDependencies.degraded } : {},
747
+ raw: issue
748
+ };
749
+ }
750
+ function labelNamesFor(issue) {
751
+ return (issue.labels ?? []).flatMap((label) => {
752
+ if (typeof label === "string")
753
+ return [label];
754
+ return typeof label.name === "string" ? [label.name] : [];
755
+ });
756
+ }
757
+ function yamlScalar(value) {
758
+ if (Array.isArray(value)) {
759
+ return value.length === 0 ? "[]" : `
760
+ ${value.map((entry) => ` - ${String(entry)}`).join(`
761
+ `)}`;
657
762
  }
763
+ if (value && typeof value === "object")
764
+ return JSON.stringify(value);
765
+ return String(value);
658
766
  }
659
- function ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs) {
660
- try {
661
- runGhVoid(bin, [
662
- "label",
663
- "create",
664
- label,
665
- "--repo",
666
- repo,
667
- "--color",
668
- "6f42c1",
669
- "--description",
670
- "Task status managed by Rig"
671
- ], spawnFn, extraEnv, timeoutMs);
672
- } catch (error) {
673
- const message = error instanceof Error ? error.message : String(error);
674
- if (!/already exists/i.test(message)) {
675
- throw error;
676
- }
767
+ function updateRigOwnedMetadataBlock(body, metadata) {
768
+ const rendered = [
769
+ RIG_METADATA_START,
770
+ ...Object.entries(metadata).map(([key, value]) => Array.isArray(value) ? `${key}:${yamlScalar(value)}` : `${key}: ${yamlScalar(value)}`),
771
+ RIG_METADATA_END
772
+ ].join(`
773
+ `);
774
+ const pattern = new RegExp(`${RIG_METADATA_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[\\s\\S]*?\\s*${RIG_METADATA_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
775
+ if (pattern.test(body))
776
+ return body.replace(pattern, rendered);
777
+ return body.trim().length > 0 ? `${body.trimEnd()}
778
+
779
+ ${rendered}
780
+ ` : `${rendered}
781
+ `;
782
+ }
783
+ function buildRigStickyStatusComment(input) {
784
+ const lines = [
785
+ RIG_STATUS_COMMENT_MARKER,
786
+ `### Rig status: ${input.status}`,
787
+ "",
788
+ input.summary
789
+ ];
790
+ if (input.runId)
791
+ lines.push("", `- Run: ${input.runId}`);
792
+ if (input.prUrl)
793
+ lines.push(`- PR: ${input.prUrl}`);
794
+ for (const detail of input.details ?? [])
795
+ lines.push(`- ${detail}`);
796
+ return lines.join(`
797
+ `);
798
+ }
799
+ function isRigStickyStatusComment(body) {
800
+ return body.includes(RIG_STATUS_COMMENT_MARKER);
801
+ }
802
+ function ghSpawnOptions(extraEnv, timeoutMs) {
803
+ const env = {
804
+ ...process.env,
805
+ ...process.env.GH_TOKEN !== undefined ? { GH_TOKEN: process.env.GH_TOKEN } : {},
806
+ ...process.env.GITHUB_TOKEN !== undefined ? { GITHUB_TOKEN: process.env.GITHUB_TOKEN } : {},
807
+ ...process.env.RIG_GITHUB_TOKEN !== undefined ? { RIG_GITHUB_TOKEN: process.env.RIG_GITHUB_TOKEN } : {}
808
+ };
809
+ for (const [key, value] of Object.entries(extraEnv ?? {})) {
810
+ if (value === undefined)
811
+ delete env[key];
812
+ else
813
+ env[key] = value;
677
814
  }
815
+ return {
816
+ encoding: "utf-8",
817
+ timeout: timeoutMs,
818
+ env
819
+ };
678
820
  }
679
- function upsertRigStickyComment(bin, repo, spawnFn, id, body, extraEnv, timeoutMs) {
680
- const comments = runGh(bin, ["api", `repos/${repo}/issues/${id}/comments`, "--paginate"], spawnFn, extraEnv, timeoutMs);
681
- const existing = comments.find((comment) => typeof comment.body === "string" && comment.body.includes(RIG_STATUS_COMMENT_MARKER));
682
- if (existing) {
683
- runGhVoid(bin, ["api", "-X", "PATCH", `repos/${repo}/issues/comments/${existing.id}`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
821
+ function credentialEnv(token) {
822
+ const clean = token?.trim() ?? "";
823
+ if (clean)
824
+ return { GH_TOKEN: clean, GITHUB_TOKEN: clean, RIG_GITHUB_TOKEN: clean };
825
+ return { GH_TOKEN: undefined, GITHUB_TOKEN: undefined, RIG_GITHUB_TOKEN: undefined };
826
+ }
827
+ async function resolveCredentialEnv(opts, purpose) {
828
+ if (!opts.credentialProvider)
684
829
  return;
685
- }
686
- runGhVoid(bin, ["api", "-X", "POST", `repos/${repo}/issues/${id}/comments`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
830
+ const input = {
831
+ owner: opts.owner,
832
+ repo: opts.repo,
833
+ workspaceId: opts.workspaceId ?? `${opts.owner}/${opts.repo}`,
834
+ ...opts.userId ? { userId: opts.userId } : {},
835
+ purpose
836
+ };
837
+ const resolved = await opts.credentialProvider.resolveGitHubToken(input);
838
+ return credentialEnv(resolved.token);
687
839
  }
688
- function notifyTaskChanged(onTaskChanged, repo, id, status) {
689
- onTaskChanged?.({ repo, id, ...status ? { status } : {}, reason: "github-issue-updated" });
840
+ function tokenDiagnostic(value) {
841
+ const clean = value?.trim() ?? "";
842
+ return clean ? `present(len=${clean.length})` : "missing";
690
843
  }
691
- function fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
692
- const issue = runGh(bin, [
693
- "issue",
694
- "view",
695
- String(id),
696
- "--repo",
697
- repo,
698
- "--json",
699
- "body"
700
- ], spawnFn, extraEnv, timeoutMs);
701
- return typeof issue.body === "string" ? issue.body : undefined;
844
+ function runGh(bin, args, spawn, extraEnv, timeoutMs) {
845
+ const options = ghSpawnOptions(extraEnv, timeoutMs);
846
+ const res = spawn(bin, [...args], options);
847
+ assertGhSuccess(args, res, options.env);
848
+ if (!res.stdout || res.stdout.trim() === "")
849
+ return [];
850
+ return JSON.parse(res.stdout);
702
851
  }
703
- function applyLabels(bin, repo, spawnFn, id, labels, action, extraEnv, timeoutMs) {
704
- for (const rawLabel of labels) {
705
- const label = rawLabel.trim();
706
- if (!label)
707
- continue;
708
- if (action === "--add-label") {
709
- try {
710
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
711
- } catch (error) {
712
- const message = error instanceof Error ? error.message : String(error);
713
- if (!/not found/i.test(message))
714
- throw error;
715
- ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
716
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
717
- }
718
- continue;
719
- }
720
- try {
721
- runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
722
- } catch {}
723
- }
852
+ function runGhVoid(bin, args, spawn, extraEnv, timeoutMs) {
853
+ const options = ghSpawnOptions(extraEnv, timeoutMs);
854
+ const res = spawn(bin, [...args], options);
855
+ assertGhSuccess(args, res, options.env);
724
856
  }
725
- async function applyIssueUpdate(bin, repo, spawnFn, id, update, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
726
- if (update.status) {
727
- await applyIssueStatus(bin, repo, spawnFn, id, update.status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs);
728
- }
729
- if (update.comment?.trim() && shouldWriteIssueUpdate(issueUpdates, update.status)) {
730
- if (isRigStickyStatusComment(update.comment)) {
731
- upsertRigStickyComment(bin, repo, spawnFn, String(id), update.comment, extraEnv, timeoutMs);
732
- } else {
733
- runGhVoid(bin, ["issue", "comment", String(id), "--repo", repo, "--body", update.comment], spawnFn, extraEnv, timeoutMs);
734
- }
735
- }
736
- const editArgs = ["issue", "edit", String(id), "--repo", repo];
737
- if (update.title?.trim()) {
738
- editArgs.push("--title", update.title.trim());
739
- }
740
- const nextBody = update.metadata ? updateRigOwnedMetadataBlock(update.body ?? fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) ?? "", update.metadata) : update.body;
741
- if (nextBody !== undefined) {
742
- editArgs.push("--body", nextBody);
857
+ function assertGhSuccess(args, res, env) {
858
+ if (res.error) {
859
+ const msg = res.error.message ?? String(res.error);
860
+ throw new Error(`gh CLI not available \u2014 install gh (brew install gh / apt install gh): ${msg}`);
743
861
  }
744
- if (editArgs.length > 5) {
745
- runGhVoid(bin, editArgs, spawnFn, extraEnv, timeoutMs);
862
+ if (res.status !== 0) {
863
+ throw new Error(`gh ${args.join(" ")} failed (exit ${res.status}): ${res.stderr}
864
+ [rig gh env:standard-plugin] GH_TOKEN=${tokenDiagnostic(env.GH_TOKEN)} GITHUB_TOKEN=${tokenDiagnostic(env.GITHUB_TOKEN)} RIG_GITHUB_TOKEN=${tokenDiagnostic(env.RIG_GITHUB_TOKEN)}`);
746
865
  }
747
866
  }
748
- function createGitHubIssuesTaskSource(opts) {
749
- const bin = opts.ghBinary ?? "gh";
750
- const state = opts.state ?? "open";
751
- const repo = `${opts.owner}/${opts.repo}`;
752
- const spawnFn = opts.spawn ?? spawnSync;
753
- const timeoutMs = Math.max(1000, Math.trunc(opts.timeoutMs ?? DEFAULT_GH_TIMEOUT_MS));
754
- const listLimit = Math.max(1, Math.trunc(opts.listLimit ?? DEFAULT_GITHUB_ISSUE_LIST_LIMIT));
755
- const issueUpdates = issueUpdatesMode(opts.issueUpdates);
756
- async function issueToTaskWithOptionalNativeDependencies(issue, env) {
757
- if (!opts.useNativeDependencies)
758
- return issueToTask(issue, repo);
759
- const nativeDependencies = await readNativeDependenciesForIssue({
760
- issue,
761
- repo,
762
- fetchGraphQL: ghGraphQLFetch(bin, spawnFn, env, timeoutMs)
763
- });
764
- return issueToTask(issue, repo, nativeDependencies);
867
+ var DEFAULT_PROJECT_STATUSES = {
868
+ todo: "Todo",
869
+ running: "In Progress",
870
+ prOpen: "In Review",
871
+ ciFixing: "In Review",
872
+ merging: "In Review",
873
+ done: "Done",
874
+ needsAttention: "Needs Attention"
875
+ };
876
+ function asProjectRecord(value) {
877
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
878
+ }
879
+ function projectString(value) {
880
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
881
+ }
882
+ function projectLifecycleStatusForTaskStatus(status) {
883
+ const normalized = status?.trim().toLowerCase().replace(/[-\s]+/g, "_");
884
+ switch (normalized) {
885
+ case "draft":
886
+ case "open":
887
+ case "queued":
888
+ case "ready":
889
+ return "todo";
890
+ case "running":
891
+ case "in_progress":
892
+ return "running";
893
+ case "under_review":
894
+ case "review":
895
+ case "pr_open":
896
+ return "prOpen";
897
+ case "ci_fixing":
898
+ case "fixing":
899
+ return "ciFixing";
900
+ case "merging":
901
+ case "merge":
902
+ return "merging";
903
+ case "closed":
904
+ case "completed":
905
+ case "done":
906
+ return "done";
907
+ case "blocked":
908
+ case "cancelled":
909
+ case "failed":
910
+ case "needs_attention":
911
+ return "needsAttention";
912
+ default:
913
+ return null;
765
914
  }
766
- return {
767
- id: "std:github-issues",
768
- kind: "github-issues",
769
- async list() {
770
- const labelArg = opts.labels && opts.labels.length > 0 ? ["--label", opts.labels.join(",")] : [];
771
- const assigneeArg = opts.assignee?.trim() ? ["--assignee", opts.assignee.trim()] : [];
772
- const args = [
773
- "issue",
774
- "list",
775
- "--repo",
776
- repo,
777
- ...labelArg,
778
- ...assigneeArg,
779
- "--state",
780
- state,
781
- "--limit",
782
- String(listLimit),
783
- "--json",
784
- "number,title,body,labels,state,url,assignees,id"
785
- ];
786
- const env = await resolveCredentialEnv(opts, "selected-repo");
787
- const rawIssues = runGh(bin, args, spawnFn, env, timeoutMs);
788
- if (rawIssues.length >= listLimit) {
789
- throw new Error(`GitHub issue list for ${repo} reached the configured limit (${listLimit}); refusing to silently truncate matching issues. Increase taskSource.options.listLimit or narrow labels/state/assignee.`);
790
- }
791
- const issues = rawIssues.filter((issue) => !issue.pull_request);
792
- return Promise.all(issues.map((issue) => issueToTaskWithOptionalNativeDependencies(issue, env)));
793
- },
794
- async get(id) {
795
- const env = await resolveCredentialEnv(opts, "selected-repo");
796
- let issue;
797
- try {
798
- issue = runGh(bin, [
799
- "issue",
800
- "view",
801
- String(id),
802
- "--repo",
803
- repo,
804
- "--json",
805
- "number,title,body,labels,state,url,assignees,id"
806
- ], spawnFn, env, timeoutMs);
807
- } catch (error) {
808
- const detail = error instanceof Error ? error.message : String(error);
809
- if (/could not resolve to (an? )?(issue|pullrequest)|no issues? (found|matched)|404 not found|gh: not found|gh issue view\b[\s\S]*failed \(exit \d+\): not found\b/i.test(detail)) {
810
- return;
915
+ }
916
+ function ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs) {
917
+ return async (query, variables) => {
918
+ const args = ["api", "graphql", "-f", `query=${query}`];
919
+ for (const [key, value] of Object.entries(variables)) {
920
+ if (value === undefined || value === null)
921
+ continue;
922
+ args.push("-f", `${key}=${String(value)}`);
923
+ }
924
+ const response = runGh(bin, args, spawnFn, extraEnv, timeoutMs);
925
+ return asProjectRecord(response)?.data ?? response;
926
+ };
927
+ }
928
+ function issueNodeIdFor(issue) {
929
+ const id = issue.id ?? issue.nodeId ?? issue.node_id;
930
+ return typeof id === "string" && id.trim().length > 0 ? id.trim() : null;
931
+ }
932
+ function nativeIssueDependencyRef(value, currentRepo) {
933
+ const record = asProjectRecord(value);
934
+ const number = typeof record?.number === "number" ? String(record.number) : projectString(record?.number);
935
+ if (!number)
936
+ return null;
937
+ const repository = asProjectRecord(record?.repository);
938
+ const owner = projectString(asProjectRecord(repository?.owner)?.login);
939
+ const name = projectString(repository?.name);
940
+ if (!owner || !name || `${owner}/${name}` === currentRepo)
941
+ return number;
942
+ return `${owner}/${name}#${number}`;
943
+ }
944
+ function nativeDependencyRefsFrom(data, currentRepo) {
945
+ const issue = asProjectRecord(asProjectRecord(data)?.node);
946
+ const blockedBy = asProjectRecord(issue?.blockedBy);
947
+ const nodes = Array.isArray(blockedBy?.nodes) ? blockedBy.nodes : [];
948
+ return [...new Set(nodes.flatMap((node) => {
949
+ const ref = nativeIssueDependencyRef(node, currentRepo);
950
+ return ref ? [ref] : [];
951
+ }))];
952
+ }
953
+ async function readNativeDependenciesForIssue(input) {
954
+ const issueId = issueNodeIdFor(input.issue);
955
+ if (!issueId)
956
+ return { deps: [], degraded: "GitHub issue node id is unavailable." };
957
+ const query = `
958
+ query RigIssueNativeDependencies($issueId: ID!) {
959
+ node(id: $issueId) {
960
+ ... on Issue {
961
+ blockedBy(first: 100) {
962
+ nodes {
963
+ number
964
+ repository { name owner { login } }
965
+ }
966
+ }
811
967
  }
812
- throw new Error(`Failed to read task ${id} from GitHub repo ${repo}: ${detail}`);
813
968
  }
814
- return issueToTaskWithOptionalNativeDependencies(issue, env);
815
- },
816
- async updateStatus(id, status) {
817
- const env = await resolveCredentialEnv(opts, "selected-repo");
818
- await applyIssueStatus(bin, repo, spawnFn, id, status, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
819
- notifyTaskChanged(opts.onTaskChanged, repo, id, status);
820
- },
821
- async updateTask(id, update) {
822
- const env = await resolveCredentialEnv(opts, "selected-repo");
823
- await applyIssueUpdate(bin, repo, spawnFn, id, update, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
824
- notifyTaskChanged(opts.onTaskChanged, repo, id, update.status);
825
- },
826
- async addLabels(id, labels) {
827
- const env = await resolveCredentialEnv(opts, "selected-repo");
828
- applyLabels(bin, repo, spawnFn, id, labels, "--add-label", env, timeoutMs);
829
- notifyTaskChanged(opts.onTaskChanged, repo, id);
830
- },
831
- async removeLabels(id, labels) {
832
- const env = await resolveCredentialEnv(opts, "selected-repo");
833
- applyLabels(bin, repo, spawnFn, id, labels, "--remove-label", env, timeoutMs);
834
- notifyTaskChanged(opts.onTaskChanged, repo, id);
835
- },
836
- async createIssue(input) {
837
- const env = await resolveCredentialEnv(opts, "selected-repo");
838
- const body = input.body ?? "";
839
- const args = [
840
- "api",
841
- "-X",
842
- "POST",
843
- `repos/${repo}/issues`,
844
- "-f",
845
- `title=${input.title}`,
846
- "-f",
847
- `body=${body}`,
848
- ...(input.labels ?? []).flatMap((label) => ["-f", `labels[]=${label}`])
849
- ];
850
- const issue = runGh(bin, args, spawnFn, env, timeoutMs);
851
- notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
852
- return issueToTask({ ...issue, body: issue.body ?? body }, repo);
853
- },
854
- async create(input) {
855
- const env = await resolveCredentialEnv(opts, "selected-repo");
856
- const body = bodyForCreatedTask(input);
857
- const args = [
858
- "api",
859
- "-X",
860
- "POST",
861
- `repos/${repo}/issues`,
862
- "-f",
863
- `title=${input.title}`,
864
- "-f",
865
- `body=${body}`,
866
- "-f",
867
- "labels[]=rig:generated"
868
- ];
869
- const issue = runGh(bin, args, spawnFn, env, timeoutMs);
870
- notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
871
- return issueToTask({ ...issue, body: issue.body ?? body }, repo);
872
- },
873
- async getIssueBody(id) {
874
- const env = await resolveCredentialEnv(opts, "selected-repo");
875
- return fetchIssueBody(bin, repo, spawnFn, id, env, timeoutMs);
876
969
  }
877
- };
970
+ `;
971
+ try {
972
+ return {
973
+ deps: nativeDependencyRefsFrom(await input.fetchGraphQL(query, { issueId }, "gh-cli"), input.repo)
974
+ };
975
+ } catch (error) {
976
+ const detail = error instanceof Error ? error.message : String(error);
977
+ return { deps: [], degraded: detail };
978
+ }
979
+ }
980
+ function formatIssueReference(ref) {
981
+ const clean = ref.trim().replace(/^#/, "");
982
+ return /^\d+$/.test(clean) ? `#${clean}` : clean;
878
983
  }
984
+ function appendReferenceLines(body, deps, parents) {
985
+ const lines = [];
986
+ const cleanDeps = (deps ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
987
+ const cleanParents = (parents ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
988
+ if (cleanDeps.length > 0)
989
+ lines.push(`depends-on: ${cleanDeps.join(", ")}`);
990
+ if (cleanParents.length > 0)
991
+ lines.push(`parents: ${cleanParents.join(", ")}`);
992
+ if (lines.length === 0)
993
+ return body;
994
+ return body.trim().length > 0 ? `${body.trimEnd()}
879
995
 
880
- // packages/standard-plugin/src/files-source.ts
881
- import { readFileSync as readFileSync2, readdirSync, existsSync as existsSync2, statSync, writeFileSync } from "fs";
882
- import { join, basename, isAbsolute, resolve as resolve2 } from "path";
883
- var DEFAULT_PATTERN = /\.(task\.)?json$/;
884
- function readTaskFile(file, pattern) {
885
- const raw = JSON.parse(readFileSync2(file, "utf-8"));
886
- const inferredId = basename(file).replace(pattern, "");
887
- const labels = Array.isArray(raw.labels) ? raw.labels.filter((label) => typeof label === "string") : [];
888
- const scope = labels.filter((label) => label.startsWith("scope:")).map((label) => label.slice("scope:".length));
889
- const validators = labels.filter((label) => label.startsWith("validator:")).map((label) => label.slice("validator:".length));
890
- const roleLabel = labels.find((label) => label.startsWith("role:"));
891
- return {
892
- id: raw["id"] ?? inferredId,
893
- deps: raw["deps"] ?? raw["depends_on"] ?? [],
894
- status: raw["status"] ?? "ready",
895
- ...scope.length > 0 ? { scope } : {},
896
- ...roleLabel ? { role: roleLabel.slice("role:".length) } : {},
897
- ...validators.length > 0 ? { validators, validation: validators } : {},
898
- ...raw
899
- };
996
+ ${lines.join(`
997
+ `)}` : lines.join(`
998
+ `);
900
999
  }
901
- function createFilesTaskSource(opts) {
902
- const pattern = opts.pattern ?? DEFAULT_PATTERN;
903
- const configured = opts.path ?? opts.dir;
904
- if (!configured) {
905
- throw new Error("createFilesTaskSource: either `path` or `dir` must be provided");
1000
+ function bodyForCreatedTask(input) {
1001
+ const metadata = { ...input.metadata ?? {} };
1002
+ if (input.deps && input.deps.length > 0)
1003
+ metadata["depends-on"] = input.deps.map(formatIssueReference);
1004
+ if (input.parents && input.parents.length > 0)
1005
+ metadata.parents = input.parents.map(formatIssueReference);
1006
+ return updateRigOwnedMetadataBlock(appendReferenceLines(input.body, input.deps, input.parents), metadata);
1007
+ }
1008
+ function projectStatusFieldFrom(data, projectId) {
1009
+ const fields = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.fields)?.nodes;
1010
+ for (const node of Array.isArray(fields) ? fields : []) {
1011
+ const record = asProjectRecord(node);
1012
+ if (projectString(record?.name)?.toLowerCase() !== "status")
1013
+ continue;
1014
+ const id = projectString(record?.id);
1015
+ if (!id)
1016
+ continue;
1017
+ const options = Array.isArray(record?.options) ? record.options.flatMap((option) => {
1018
+ const optionRecord = asProjectRecord(option);
1019
+ const optionId = projectString(optionRecord?.id);
1020
+ const name = projectString(optionRecord?.name);
1021
+ return optionId && name ? [{ id: optionId, name }] : [];
1022
+ }) : [];
1023
+ return { id, name: "Status", options };
906
1024
  }
907
- const directory = isAbsolute(configured) ? configured : resolve2(opts.projectRoot ?? process.cwd(), configured);
908
- const findTaskFile = (id) => {
909
- if (!existsSync2(directory))
910
- return;
911
- for (const name of readdirSync(directory)) {
912
- if (!pattern.test(name))
913
- continue;
914
- const p = join(directory, name);
915
- try {
916
- if (!statSync(p).isFile())
917
- continue;
918
- if (readTaskFile(p, pattern).id === id)
919
- return p;
920
- } catch {}
921
- }
922
- return;
923
- };
924
- const applyUpdate = (id, update) => {
925
- const file = findTaskFile(id);
926
- if (!file) {
927
- throw new Error(`files task not found: ${id}`);
928
- }
929
- const raw = JSON.parse(readFileSync2(file, "utf-8"));
930
- if (update.status)
931
- raw.status = update.status;
932
- if (update.title !== undefined)
933
- raw.title = update.title;
934
- if (update.body !== undefined)
935
- raw.body = update.body;
936
- if (update.comment?.trim()) {
937
- const existing = Array.isArray(raw.comments) ? raw.comments : [];
938
- raw.comments = [
939
- ...existing,
940
- {
941
- body: update.comment,
942
- createdAt: new Date().toISOString(),
943
- source: "rig"
1025
+ throw new Error(`GitHub Project ${projectId} does not expose a Status single-select field.`);
1026
+ }
1027
+ async function resolveProjectStatusField(input) {
1028
+ const query = `
1029
+ query RigProjectStatusField($projectId: ID!) {
1030
+ node(id: $projectId) {
1031
+ ... on ProjectV2 {
1032
+ fields(first: 50) {
1033
+ nodes {
1034
+ ... on ProjectV2FieldCommon { id name }
1035
+ ... on ProjectV2SingleSelectField { id name options { id name } }
1036
+ }
1037
+ }
944
1038
  }
945
- ];
1039
+ }
946
1040
  }
947
- writeFileSync(file, `${JSON.stringify(raw, null, 2)}
948
- `, "utf-8");
949
- };
950
- return {
951
- id: "std:files",
952
- kind: "files",
953
- async list() {
954
- if (!existsSync2(directory))
955
- return [];
956
- const out = [];
957
- for (const name of readdirSync(directory)) {
958
- if (!pattern.test(name))
959
- continue;
960
- const p = join(directory, name);
961
- try {
962
- if (!statSync(p).isFile())
963
- continue;
964
- out.push(readTaskFile(p, pattern));
965
- } catch (err) {
966
- console.warn(`[files-source] skipped ${name}: ${err.message}`);
1041
+ `;
1042
+ return projectStatusFieldFrom(await input.fetchGraphQL(query, { projectId: input.projectId }, input.token), input.projectId);
1043
+ }
1044
+ async function ensureIssueProjectItem(input) {
1045
+ const query = `
1046
+ query RigFindProjectIssueItem($projectId: ID!) {
1047
+ node(id: $projectId) {
1048
+ ... on ProjectV2 {
1049
+ items(first: 100) { nodes { id content { ... on Issue { id } } } }
967
1050
  }
968
1051
  }
969
- return out;
970
- },
971
- async get(id) {
972
- const all = await this.list();
973
- return all.find((t) => t.id === id);
974
- },
975
- async updateStatus(id, status) {
976
- applyUpdate(id, { status });
977
- },
978
- async updateTask(id, update) {
979
- applyUpdate(id, update);
980
1052
  }
981
- };
982
- }
983
-
984
- // packages/standard-plugin/src/drift/plugin.ts
985
- import { Schema } from "effect";
986
- import { StageMutation as StageMutationSchema } from "@rig/contracts";
987
-
988
- // packages/standard-plugin/src/drift/detect.ts
989
- import { existsSync as existsSync3 } from "fs";
990
- import { readdir, readFile, stat } from "fs/promises";
991
- import { basename as basename2, extname, relative, resolve as resolve3 } from "path";
992
-
993
- // packages/standard-plugin/src/drift/extract-refs.ts
994
- var INLINE_CODE = /`([^`\n]+)`/g;
995
- var MARKDOWN_LINK = /\[[^\]]+\]\(([^)\s]+)\)/g;
996
- var SYMBOL_REF = /^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)?$/;
997
- 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)$/;
998
- function stripFenceLines(markdown) {
999
- const lines = markdown.split(/\r?\n/);
1000
- let fenced = false;
1001
- return lines.map((line) => {
1002
- if (/^\s*(```|~~~)/.test(line)) {
1003
- fenced = !fenced;
1004
- return "";
1053
+ `;
1054
+ const data = await input.fetchGraphQL(query, { projectId: input.projectId }, input.token);
1055
+ const nodes = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.items)?.nodes;
1056
+ for (const node of Array.isArray(nodes) ? nodes : []) {
1057
+ const record = asProjectRecord(node);
1058
+ const content = asProjectRecord(record?.content);
1059
+ if (projectString(content?.id) === input.issueNodeId) {
1060
+ const id2 = projectString(record?.id);
1061
+ if (id2)
1062
+ return { id: id2, created: false };
1005
1063
  }
1006
- return fenced ? "" : line;
1007
- });
1064
+ }
1065
+ const mutation = `
1066
+ mutation RigAddIssueToProject($projectId: ID!, $contentId: ID!) {
1067
+ addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) { item { id } }
1068
+ }
1069
+ `;
1070
+ const created = await input.fetchGraphQL(mutation, { projectId: input.projectId, contentId: input.issueNodeId }, input.token);
1071
+ const addResult = asProjectRecord(asProjectRecord(created)?.addProjectV2ItemById);
1072
+ const id = projectString(asProjectRecord(addResult?.item)?.id);
1073
+ if (!id)
1074
+ throw new Error("GitHub Project item creation did not return an item id.");
1075
+ return { id, created: true };
1008
1076
  }
1009
- function normalizeToken(raw) {
1010
- return raw.trim().replace(/^['"]|['"]$/g, "").replace(/[),.;:]+$/g, "").replace(/#L\d+(?:-L\d+)?$/i, "");
1077
+ async function updateIssueProjectStatus(input) {
1078
+ const mutation = `
1079
+ mutation RigUpdateProjectStatus($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
1080
+ updateProjectV2ItemFieldValue(input: {
1081
+ projectId: $projectId,
1082
+ itemId: $itemId,
1083
+ fieldId: $fieldId,
1084
+ value: { singleSelectOptionId: $optionId }
1085
+ }) { projectV2Item { id } }
1086
+ }
1087
+ `;
1088
+ await input.fetchGraphQL(mutation, {
1089
+ projectId: input.projectId,
1090
+ itemId: input.itemId,
1091
+ fieldId: input.fieldId,
1092
+ optionId: input.optionId
1093
+ }, input.token);
1011
1094
  }
1012
- function classifyReference(raw) {
1013
- if (raw.startsWith("@"))
1014
- return null;
1015
- if (PATH_REF.test(raw))
1016
- return "path";
1017
- if (SYMBOL_REF.test(raw))
1018
- return "symbol";
1019
- return null;
1095
+ function fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
1096
+ const issue = runGh(bin, ["issue", "view", String(id), "--repo", repo, "--json", "id"], spawnFn, extraEnv, timeoutMs);
1097
+ return projectString(issue.id) ?? projectString(issue.nodeId) ?? projectString(issue.node_id);
1020
1098
  }
1021
- function pushReference(refs, seen, raw, line) {
1022
- const value = normalizeToken(raw);
1023
- if (!value)
1024
- return;
1025
- const kind = classifyReference(value);
1026
- if (!kind)
1099
+ async function syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs) {
1100
+ if (!projects?.enabled)
1027
1101
  return;
1028
- const key = `${kind}:${value}:${line}`;
1029
- if (seen.has(key))
1102
+ const projectId = projectString(projects.projectId);
1103
+ if (!projectId)
1104
+ throw new Error("GitHub Projects status sync is enabled but projectId is missing.");
1105
+ const lifecycleStatus = projectLifecycleStatusForTaskStatus(status);
1106
+ if (!lifecycleStatus)
1030
1107
  return;
1031
- seen.add(key);
1032
- refs.push({ kind, value, line });
1108
+ const issueNodeId = fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs);
1109
+ if (!issueNodeId)
1110
+ throw new Error(`GitHub issue ${repo}#${id} did not expose a node id for Projects status sync.`);
1111
+ const projectStatus = projectString(projects.statuses?.[lifecycleStatus]) ?? DEFAULT_PROJECT_STATUSES[lifecycleStatus];
1112
+ const fetchGraphQL = ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs);
1113
+ const field = await resolveProjectStatusField({ projectId, token: "gh-cli", fetchGraphQL });
1114
+ const option = field.options.find((candidate) => candidate.name.toLowerCase() === projectStatus.toLowerCase() || candidate.id === projectStatus);
1115
+ if (!option)
1116
+ throw new Error(`GitHub Project ${projectId} Status field does not contain option "${projectStatus}".`);
1117
+ const item = await ensureIssueProjectItem({ projectId, issueNodeId, token: "gh-cli", fetchGraphQL });
1118
+ await updateIssueProjectStatus({
1119
+ projectId,
1120
+ itemId: item.id,
1121
+ fieldId: projectString(projects.statusFieldId) ?? field.id,
1122
+ optionId: option.id,
1123
+ token: "gh-cli",
1124
+ fetchGraphQL
1125
+ });
1033
1126
  }
1034
- function extractDriftReferences(markdown) {
1035
- const refs = [];
1036
- const seen = new Set;
1037
- const lines = stripFenceLines(markdown);
1038
- for (const [index, line] of lines.entries()) {
1039
- const lineNumber = index + 1;
1040
- for (const match of line.matchAll(INLINE_CODE)) {
1041
- pushReference(refs, seen, match[1] ?? "", lineNumber);
1042
- }
1043
- for (const match of line.matchAll(MARKDOWN_LINK)) {
1044
- pushReference(refs, seen, match[1] ?? "", lineNumber);
1045
- }
1127
+ var TERMINAL_TASK_STATUSES = new Set(["closed", "completed", "merged", "cancelled", "resolved", "done"]);
1128
+ function normalizeTaskStatusToken(status) {
1129
+ return status?.trim().toLowerCase().replace(/[-\s]+/g, "_") ?? "";
1130
+ }
1131
+ function issueUpdatesMode(value) {
1132
+ return value === "off" || value === "minimal" || value === "lifecycle" ? value : "lifecycle";
1133
+ }
1134
+ function isTerminalTaskStatus(status) {
1135
+ return TERMINAL_TASK_STATUSES.has(normalizeTaskStatusToken(status));
1136
+ }
1137
+ function shouldWriteIssueUpdate(mode, status) {
1138
+ if (mode === "off")
1139
+ return false;
1140
+ if (mode === "lifecycle")
1141
+ return true;
1142
+ return isTerminalTaskStatus(status);
1143
+ }
1144
+ function isRunningStatus(status) {
1145
+ return normalizeTaskStatusToken(status) === "running";
1146
+ }
1147
+ function assignRunningIssue(bin, repo, spawnFn, id, assignee, extraEnv, timeoutMs) {
1148
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-assignee", assignee?.trim() || "@me"], spawnFn, extraEnv, timeoutMs);
1149
+ }
1150
+ function statusLabelFor(status) {
1151
+ switch (status) {
1152
+ case "running":
1153
+ case "in_progress":
1154
+ return "in-progress";
1155
+ case "blocked":
1156
+ return "blocked";
1157
+ case "ready":
1158
+ return "ready";
1159
+ case "under_review":
1160
+ return "under-review";
1161
+ case "failed":
1162
+ return "failed";
1163
+ case "cancelled":
1164
+ return "cancelled";
1165
+ case "ci_fixing":
1166
+ return "under-review";
1167
+ case "merging":
1168
+ return "under-review";
1169
+ case "needs_attention":
1170
+ return "blocked";
1171
+ case "closed":
1172
+ case "completed":
1173
+ case "open":
1174
+ return null;
1175
+ default:
1176
+ throw new Error(`unsupported status: ${status}`);
1046
1177
  }
1047
- return refs;
1048
- }
1049
-
1050
- // packages/standard-plugin/src/drift/git-adapter.ts
1051
- import { execFile } from "child_process";
1052
- import { promisify } from "util";
1053
- var execFileAsync = promisify(execFile);
1054
- function processError(value) {
1055
- return value && typeof value === "object" ? value : null;
1056
1178
  }
1057
- function lineCount(output) {
1058
- const trimmed = output.trim();
1059
- return trimmed ? trimmed.split(/\r?\n/).length : 0;
1179
+ function rigStatusLabelFor(status) {
1180
+ switch (status) {
1181
+ case "running":
1182
+ case "in_progress":
1183
+ return "rig:running";
1184
+ case "under_review":
1185
+ return "rig:pr-open";
1186
+ case "closed":
1187
+ case "completed":
1188
+ return "rig:done";
1189
+ case "ci_fixing":
1190
+ return "rig:ci-fixing";
1191
+ case "merging":
1192
+ return "rig:merging";
1193
+ case "needs_attention":
1194
+ case "failed":
1195
+ case "blocked":
1196
+ return "rig:needs-attention";
1197
+ case "ready":
1198
+ case "cancelled":
1199
+ case "open":
1200
+ return null;
1201
+ default:
1202
+ return null;
1203
+ }
1060
1204
  }
1061
- function makeDriftGit(projectRoot) {
1062
- async function git(args) {
1063
- const result = await execFileAsync("git", [...args], {
1064
- cwd: projectRoot,
1065
- encoding: "utf8",
1066
- maxBuffer: 10 * 1024 * 1024
1067
- });
1068
- return String(result.stdout);
1205
+ async function applyIssueStatus(bin, repo, spawnFn, id, status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
1206
+ const targetLabel = status === "closed" || status === "completed" ? null : statusLabelFor(status);
1207
+ const targetRigLabel = rigStatusLabelFor(status);
1208
+ const shouldSyncLifecycle = shouldWriteIssueUpdate(issueUpdates, status);
1209
+ for (const l of [...STATUS_LABELS, ...RIG_STATUS_LABELS]) {
1210
+ if (targetLabel !== null && l === targetLabel)
1211
+ continue;
1212
+ if (targetRigLabel !== null && l === targetRigLabel)
1213
+ continue;
1214
+ try {
1215
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--remove-label", l], spawnFn, extraEnv, timeoutMs);
1216
+ } catch {}
1069
1217
  }
1070
- async function grepCountAt(symbolOrPath, commit) {
1218
+ for (const label of [targetLabel, targetRigLabel].filter((value) => Boolean(value))) {
1071
1219
  try {
1072
- return lineCount(await git(["grep", "-F", "-n", "-e", symbolOrPath, commit, "--"]));
1220
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
1073
1221
  } catch (error) {
1074
- const detail = processError(error);
1075
- if (detail?.code === 1)
1076
- return 0;
1077
- throw error;
1078
- }
1079
- }
1080
- return {
1081
- async lastCommitTouching(path) {
1082
- const commit = (await git(["log", "-n", "1", "--format=%H", "--", path])).trim();
1083
- return commit || "HEAD";
1084
- },
1085
- async grepCount(symbolOrPath) {
1086
- return grepCountAt(symbolOrPath, "HEAD");
1087
- },
1088
- async grepCountAtCommit(symbolOrPath, commit) {
1089
- return grepCountAt(symbolOrPath, commit);
1090
- },
1091
- async wasRenamed(symbolOrPath, sinceCommit) {
1092
- if (!symbolOrPath.includes("/") && !symbolOrPath.includes("."))
1093
- return false;
1094
- try {
1095
- const output = await git(["log", "--name-status", "--format=", `${sinceCommit}..HEAD`]);
1096
- return output.split(/\r?\n/).some((line) => {
1097
- const match = line.match(/^R\d*\s+(.+?)\s+(.+)$/);
1098
- return Boolean(match && (match[1] === symbolOrPath || match[2] === symbolOrPath));
1099
- });
1100
- } catch (error) {
1101
- const detail = processError(error);
1102
- if (detail?.code === 128)
1103
- return false;
1222
+ const message = error instanceof Error ? error.message : String(error);
1223
+ if (!/not found/i.test(message)) {
1104
1224
  throw error;
1105
1225
  }
1226
+ ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
1227
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
1106
1228
  }
1107
- };
1108
- }
1109
-
1110
- // packages/standard-plugin/src/drift/detect.ts
1111
- var DEFAULT_IGNORED_DIRS = {
1112
- ".git": true,
1113
- node_modules: true,
1114
- dist: true,
1115
- build: true,
1116
- coverage: true,
1117
- ".next": true,
1118
- vendor: true
1119
- };
1120
- var SOURCE_EXTENSIONS = {
1121
- ".ts": true,
1122
- ".tsx": true,
1123
- ".js": true,
1124
- ".jsx": true,
1125
- ".mjs": true,
1126
- ".cjs": true,
1127
- ".rs": true,
1128
- ".go": true,
1129
- ".py": true,
1130
- ".rb": true,
1131
- ".java": true,
1132
- ".kt": true,
1133
- ".swift": true,
1134
- ".c": true,
1135
- ".cc": true,
1136
- ".cpp": true,
1137
- ".h": true,
1138
- ".hpp": true,
1139
- ".json": true,
1140
- ".toml": true,
1141
- ".yml": true,
1142
- ".yaml": true
1143
- };
1144
- function globLikeMatch(path, pattern) {
1145
- if (pattern === path)
1146
- return true;
1147
- if (pattern.startsWith("**/*"))
1148
- return path.endsWith(pattern.slice(4));
1149
- if (pattern.endsWith("/**"))
1150
- return path.startsWith(pattern.slice(0, -3));
1151
- if (pattern.includes("*")) {
1152
- const escaped = pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
1153
- return new RegExp(`^${escaped}$`).test(path);
1154
1229
  }
1155
- return path.startsWith(pattern);
1156
- }
1157
- function isDefaultDoc(path) {
1158
- const lower = basename2(path).toLowerCase();
1159
- return (path.endsWith(".md") || path.endsWith(".mdx")) && !lower.startsWith("changelog") && !lower.includes("generated");
1160
- }
1161
- function isIgnored(path, patterns) {
1162
- return (patterns ?? []).some((pattern) => globLikeMatch(path, pattern));
1163
- }
1164
- async function collectFiles(root, options) {
1165
- const files = [];
1166
- async function visit(dir) {
1167
- for (const entry of await readdir(dir, { withFileTypes: true })) {
1168
- if (entry.isDirectory() && DEFAULT_IGNORED_DIRS[entry.name])
1169
- continue;
1170
- const absolute = resolve3(dir, entry.name);
1171
- const rel = relative(root, absolute).replace(/\\/g, "/");
1172
- if (isIgnored(rel, options.ignore))
1173
- continue;
1174
- if (entry.isDirectory()) {
1175
- await visit(absolute);
1176
- continue;
1177
- }
1178
- if (!entry.isFile())
1179
- continue;
1180
- if (options.docs) {
1181
- const matchesConfigured = options.patterns && options.patterns.length > 0 ? options.patterns.some((pattern) => globLikeMatch(rel, pattern)) : isDefaultDoc(rel);
1182
- if (matchesConfigured)
1183
- files.push(rel);
1184
- continue;
1185
- }
1186
- if (SOURCE_EXTENSIONS[extname(entry.name)])
1187
- files.push(rel);
1230
+ if (isRunningStatus(status)) {
1231
+ assignRunningIssue(bin, repo, spawnFn, id, runningAssignee, extraEnv, timeoutMs);
1232
+ if (shouldSyncLifecycle) {
1233
+ upsertRigStickyComment(bin, repo, spawnFn, String(id), buildRigStickyStatusComment({
1234
+ status: "running",
1235
+ summary: "Rig run started."
1236
+ }), extraEnv, timeoutMs);
1188
1237
  }
1189
1238
  }
1190
- await visit(root);
1191
- return files.sort();
1239
+ if (shouldSyncLifecycle) {
1240
+ await syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs);
1241
+ }
1242
+ if (status === "closed" || status === "completed") {
1243
+ runGhVoid(bin, ["issue", "close", String(id), "--repo", repo], spawnFn, extraEnv, timeoutMs);
1244
+ }
1192
1245
  }
1193
- async function sourceReferenceCount(projectRoot, reference, docPath) {
1194
- if (reference.kind === "path")
1195
- return existsSync3(resolve3(projectRoot, reference.value)) ? 1 : 0;
1196
- let count = 0;
1197
- const sourceFiles = await collectFiles(projectRoot, { docs: false });
1198
- for (const sourceFile of sourceFiles) {
1199
- if (sourceFile === docPath)
1200
- continue;
1201
- const text = await readFile(resolve3(projectRoot, sourceFile), "utf8").catch(() => "");
1202
- if (text.includes(reference.value))
1203
- count += 1;
1246
+ function ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs) {
1247
+ try {
1248
+ runGhVoid(bin, [
1249
+ "label",
1250
+ "create",
1251
+ label,
1252
+ "--repo",
1253
+ repo,
1254
+ "--color",
1255
+ "6f42c1",
1256
+ "--description",
1257
+ "Task status managed by Rig"
1258
+ ], spawnFn, extraEnv, timeoutMs);
1259
+ } catch (error) {
1260
+ const message = error instanceof Error ? error.message : String(error);
1261
+ if (!/already exists/i.test(message)) {
1262
+ throw error;
1263
+ }
1204
1264
  }
1205
- return count;
1206
1265
  }
1207
- function deletedReferenceFinding(docPath, reference) {
1208
- return {
1209
- kind: "deleted-reference",
1210
- docPath,
1211
- line: reference.line,
1212
- reference: reference.value,
1213
- detail: `Documented reference "${reference.value}" no longer exists in the source tree.`,
1214
- confidence: "high"
1215
- };
1266
+ function upsertRigStickyComment(bin, repo, spawnFn, id, body, extraEnv, timeoutMs) {
1267
+ const comments = runGh(bin, ["api", `repos/${repo}/issues/${id}/comments`, "--paginate"], spawnFn, extraEnv, timeoutMs);
1268
+ const existing = comments.find((comment) => typeof comment.body === "string" && comment.body.includes(RIG_STATUS_COMMENT_MARKER));
1269
+ if (existing) {
1270
+ runGhVoid(bin, ["api", "-X", "PATCH", `repos/${repo}/issues/comments/${existing.id}`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
1271
+ return;
1272
+ }
1273
+ runGhVoid(bin, ["api", "-X", "POST", `repos/${repo}/issues/${id}/comments`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
1216
1274
  }
1217
- function staleAnchorFinding(docPath, reference) {
1218
- return {
1219
- kind: "stale-anchor",
1220
- docPath,
1221
- line: reference.line,
1222
- reference: reference.value,
1223
- detail: `Documented path "${reference.value}" changed after this doc was last updated.`,
1224
- confidence: "medium"
1225
- };
1275
+ function notifyTaskChanged(onTaskChanged, repo, id, status) {
1276
+ onTaskChanged?.({ repo, id, ...status ? { status } : {}, reason: "github-issue-updated" });
1226
1277
  }
1227
- async function detectDeletedReferences(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
1228
- const markdown = await readFile(resolve3(projectRoot, docPath), "utf8");
1229
- const docCommit = await git.lastCommitTouching(docPath);
1230
- const findings = [];
1231
- for (const reference of extractDriftReferences(markdown)) {
1232
- if (await sourceReferenceCount(projectRoot, reference, docPath) > 0)
1233
- continue;
1234
- if (await git.wasRenamed(reference.value, docCommit))
1235
- continue;
1236
- findings.push(deletedReferenceFinding(docPath, reference));
1237
- }
1238
- return findings;
1278
+ function fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
1279
+ const issue = runGh(bin, [
1280
+ "issue",
1281
+ "view",
1282
+ String(id),
1283
+ "--repo",
1284
+ repo,
1285
+ "--json",
1286
+ "body"
1287
+ ], spawnFn, extraEnv, timeoutMs);
1288
+ return typeof issue.body === "string" ? issue.body : undefined;
1239
1289
  }
1240
- async function detectStaleAnchors(projectRoot, docPath, git = makeDriftGit(projectRoot)) {
1241
- const markdown = await readFile(resolve3(projectRoot, docPath), "utf8");
1242
- const docCommit = await git.lastCommitTouching(docPath);
1243
- const findings = [];
1244
- for (const reference of extractDriftReferences(markdown).filter((ref) => ref.kind === "path")) {
1245
- if (!existsSync3(resolve3(projectRoot, reference.value)))
1290
+ function applyLabels(bin, repo, spawnFn, id, labels, action, extraEnv, timeoutMs) {
1291
+ for (const rawLabel of labels) {
1292
+ const label = rawLabel.trim();
1293
+ if (!label)
1246
1294
  continue;
1247
- const sourceStat = await stat(resolve3(projectRoot, reference.value)).catch(() => null);
1248
- if (!sourceStat?.isFile())
1295
+ if (action === "--add-label") {
1296
+ try {
1297
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
1298
+ } catch (error) {
1299
+ const message = error instanceof Error ? error.message : String(error);
1300
+ if (!/not found/i.test(message))
1301
+ throw error;
1302
+ ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
1303
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
1304
+ }
1249
1305
  continue;
1250
- const sourceCommit = await git.lastCommitTouching(reference.value);
1251
- if (sourceCommit !== docCommit && !await git.wasRenamed(reference.value, docCommit)) {
1252
- findings.push(staleAnchorFinding(docPath, reference));
1253
1306
  }
1307
+ try {
1308
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
1309
+ } catch {}
1254
1310
  }
1255
- return findings;
1256
1311
  }
1257
- async function detectDrift(options) {
1258
- const git = options.git ?? makeDriftGit(options.projectRoot);
1259
- const docs = await collectFiles(options.projectRoot, {
1260
- docs: true,
1261
- ...options.docsGlobs !== undefined ? { patterns: options.docsGlobs } : {},
1262
- ...options.ignoreGlobs !== undefined ? { ignore: options.ignoreGlobs } : {}
1263
- });
1264
- const findings = [];
1265
- let degraded = false;
1266
- for (const docPath of docs) {
1267
- try {
1268
- findings.push(...await detectDeletedReferences(options.projectRoot, docPath, git));
1269
- findings.push(...await detectStaleAnchors(options.projectRoot, docPath, git));
1270
- } catch {
1271
- degraded = true;
1312
+ async function applyIssueUpdate(bin, repo, spawnFn, id, update, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
1313
+ if (update.status) {
1314
+ await applyIssueStatus(bin, repo, spawnFn, id, update.status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs);
1315
+ }
1316
+ if (update.comment?.trim() && shouldWriteIssueUpdate(issueUpdates, update.status)) {
1317
+ if (isRigStickyStatusComment(update.comment)) {
1318
+ upsertRigStickyComment(bin, repo, spawnFn, String(id), update.comment, extraEnv, timeoutMs);
1319
+ } else {
1320
+ runGhVoid(bin, ["issue", "comment", String(id), "--repo", repo, "--body", update.comment], spawnFn, extraEnv, timeoutMs);
1272
1321
  }
1273
1322
  }
1274
- return {
1275
- generatedAt: new Date().toISOString(),
1276
- scanned: docs.length,
1277
- degraded,
1278
- findings
1279
- };
1280
- }
1281
-
1282
- // packages/standard-plugin/src/drift/plugin.ts
1283
- var DOCS_DRIFT_VALIDATOR_ID = "std:docs-drift";
1284
- var DOCS_DRIFT_CLI_ID = "std:drift";
1285
- var DOCS_DRIFT_STAGE_ID = "docs-drift";
1286
- var DOCS_DRIFT_CAPABILITY_ID = "std:docs-drift-capability";
1287
- var DOCS_DRIFT_VALIDATOR = {
1288
- id: DOCS_DRIFT_VALIDATOR_ID,
1289
- category: "regression",
1290
- description: "Detect documentation references that drifted from the source tree."
1291
- };
1292
- var DOCS_DRIFT_STAGE_MUTATION = Schema.decodeUnknownSync(StageMutationSchema)({
1293
- op: "insert",
1294
- stage: {
1295
- id: DOCS_DRIFT_STAGE_ID,
1296
- kind: "gate",
1297
- before: ["merge-gate"],
1298
- after: ["open-pr"]
1299
- },
1300
- contributedBy: DOCS_DRIFT_STAGE_ID
1301
- });
1302
- var DOCS_DRIFT_CLI_COMMAND = "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]";
1303
- function highConfidenceDriftFindings(report) {
1304
- return report.findings.filter((finding) => finding.confidence === "high");
1305
- }
1306
- function driftGateResult(report, mode = "enforce") {
1307
- const high = highConfidenceDriftFindings(report);
1308
- if (mode === "enforce" && high.length > 0) {
1309
- return { kind: "block", reason: `${high.length} high-confidence documentation drift finding(s).` };
1323
+ const editArgs = ["issue", "edit", String(id), "--repo", repo];
1324
+ if (update.title?.trim()) {
1325
+ editArgs.push("--title", update.title.trim());
1326
+ }
1327
+ const nextBody = update.metadata ? updateRigOwnedMetadataBlock(update.body ?? fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) ?? "", update.metadata) : update.body;
1328
+ if (nextBody !== undefined) {
1329
+ editArgs.push("--body", nextBody);
1330
+ }
1331
+ if (editArgs.length > 5) {
1332
+ runGhVoid(bin, editArgs, spawnFn, extraEnv, timeoutMs);
1310
1333
  }
1311
- return { kind: "allow" };
1312
1334
  }
1313
- function createDocsDriftGateStage(options = {}) {
1314
- return async (ctx) => {
1315
- const projectRoot = typeof ctx.metadata?.projectRoot === "string" ? ctx.metadata.projectRoot : process.cwd();
1316
- const report = await detectDrift({
1317
- projectRoot,
1318
- ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
1319
- ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {}
1335
+ function createGitHubIssuesTaskSource(opts) {
1336
+ const bin = opts.ghBinary ?? "gh";
1337
+ const state = opts.state ?? "open";
1338
+ const repo = `${opts.owner}/${opts.repo}`;
1339
+ const spawnFn = opts.spawn ?? spawnSync;
1340
+ const timeoutMs = Math.max(1000, Math.trunc(opts.timeoutMs ?? DEFAULT_GH_TIMEOUT_MS));
1341
+ const listLimit = Math.max(1, Math.trunc(opts.listLimit ?? DEFAULT_GITHUB_ISSUE_LIST_LIMIT));
1342
+ const issueUpdates = issueUpdatesMode(opts.issueUpdates);
1343
+ async function issueToTaskWithOptionalNativeDependencies(issue, env) {
1344
+ if (!opts.useNativeDependencies)
1345
+ return issueToTask(issue, repo);
1346
+ const nativeDependencies = await readNativeDependenciesForIssue({
1347
+ issue,
1348
+ repo,
1349
+ fetchGraphQL: ghGraphQLFetch(bin, spawnFn, env, timeoutMs)
1320
1350
  });
1321
- return driftGateResult(report, options.failOnDrift ? "enforce" : "observe");
1322
- };
1323
- }
1324
- async function runDocsDriftValidation(options) {
1325
- const report = await detectDrift(options);
1326
- const high = highConfidenceDriftFindings(report);
1327
- const passed = options.failOnDrift ? high.length === 0 : true;
1328
- const findingWord = report.findings.length === 1 ? "finding" : "findings";
1329
- return {
1330
- id: DOCS_DRIFT_VALIDATOR_ID,
1331
- passed,
1332
- summary: `docs drift scanned ${report.scanned} doc(s), ${report.findings.length} ${findingWord}`,
1333
- details: JSON.stringify(report)
1334
- };
1335
- }
1336
- function createDocsDriftValidator(options = {}) {
1337
- return {
1338
- ...DOCS_DRIFT_VALIDATOR,
1339
- async run(ctx) {
1340
- return runDocsDriftValidation({
1341
- projectRoot: ctx.workspaceRoot,
1342
- ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
1343
- ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {},
1344
- ...options.failOnDrift !== undefined ? { failOnDrift: options.failOnDrift } : {}
1345
- });
1346
- }
1347
- };
1348
- }
1349
- function takeOptionValue(args, index, flag) {
1350
- const value = args[index + 1];
1351
- if (!value)
1352
- throw new Error(`${flag} requires a value`);
1353
- return value;
1354
- }
1355
- function takeFlag(args, flag) {
1356
- const rest = [...args];
1357
- const index = rest.indexOf(flag);
1358
- if (index < 0)
1359
- return { value: false, rest };
1360
- rest.splice(index, 1);
1361
- return { value: true, rest };
1362
- }
1363
- function takeOption(args, flag) {
1364
- const rest = [...args];
1365
- const index = rest.indexOf(flag);
1366
- if (index < 0)
1367
- return { rest };
1368
- const value = rest[index + 1];
1369
- if (!value || value.startsWith("-"))
1370
- throw new Error(`${flag} requires a value.`);
1371
- rest.splice(index, 2);
1372
- return { value, rest };
1373
- }
1374
- function requireNoExtraArgs(args, usage) {
1375
- if (args.length > 0)
1376
- throw new Error(`Unexpected argument: ${args[0]}
1377
- Usage: ${usage}`);
1378
- }
1379
- function parseCsv(value) {
1380
- return value?.split(",").map((entry) => entry.trim()).filter((entry) => entry.length > 0) ?? [];
1381
- }
1382
- function driftSummary(report) {
1383
- const highConfidence = highConfidenceDriftFindings(report).length;
1384
- return { total: report.findings.length, highConfidence, degraded: report.degraded };
1385
- }
1386
- async function executeDrift(context, args, options = {}) {
1387
- const json = takeFlag(args, "--json");
1388
- const docs = takeOption(json.rest, "--docs");
1389
- const ignore = takeOption(docs.rest, "--ignore");
1390
- const failOnDrift = takeFlag(ignore.rest, "--fail-on-drift");
1391
- requireNoExtraArgs(failOnDrift.rest, "rig drift [--docs <csv>] [--ignore <csv>] [--fail-on-drift] [--json]");
1392
- const docsGlobs = parseCsv(docs.value);
1393
- const ignoreGlobs = parseCsv(ignore.value);
1394
- const effectiveDocsGlobs = docsGlobs.length > 0 ? docsGlobs : options.docsGlobs;
1395
- const effectiveIgnoreGlobs = ignoreGlobs.length > 0 ? ignoreGlobs : options.ignoreGlobs;
1396
- const effectiveFailOnDrift = failOnDrift.value || options.failOnDrift === true;
1397
- const report = await detectDrift({
1398
- projectRoot: context.projectRoot,
1399
- ...effectiveDocsGlobs !== undefined ? { docsGlobs: effectiveDocsGlobs } : {},
1400
- ...effectiveIgnoreGlobs !== undefined ? { ignoreGlobs: effectiveIgnoreGlobs } : {}
1401
- });
1402
- const failed = effectiveFailOnDrift && highConfidenceDriftFindings(report).length > 0;
1403
- const details = { report, summary: driftSummary(report), failOnDrift: effectiveFailOnDrift, failed };
1404
- if (context.outputMode === "text") {
1405
- if (json.value)
1406
- console.log(JSON.stringify(details, null, 2));
1407
- else
1408
- 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(`
1409
- `));
1351
+ return issueToTask(issue, repo, nativeDependencies);
1410
1352
  }
1411
- return { ok: !failed, group: "drift", command: "scan", details };
1353
+ return {
1354
+ id: "std:github-issues",
1355
+ kind: "github-issues",
1356
+ async list() {
1357
+ const labelArg = opts.labels && opts.labels.length > 0 ? ["--label", opts.labels.join(",")] : [];
1358
+ const assigneeArg = opts.assignee?.trim() ? ["--assignee", opts.assignee.trim()] : [];
1359
+ const args = [
1360
+ "issue",
1361
+ "list",
1362
+ "--repo",
1363
+ repo,
1364
+ ...labelArg,
1365
+ ...assigneeArg,
1366
+ "--state",
1367
+ state,
1368
+ "--limit",
1369
+ String(listLimit),
1370
+ "--json",
1371
+ "number,title,body,labels,state,url,assignees,id"
1372
+ ];
1373
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1374
+ const rawIssues = runGh(bin, args, spawnFn, env, timeoutMs);
1375
+ if (rawIssues.length >= listLimit) {
1376
+ throw new Error(`GitHub issue list for ${repo} reached the configured limit (${listLimit}); refusing to silently truncate matching issues. Increase taskSource.options.listLimit or narrow labels/state/assignee.`);
1377
+ }
1378
+ const issues = rawIssues.filter((issue) => !issue.pull_request);
1379
+ return Promise.all(issues.map((issue) => issueToTaskWithOptionalNativeDependencies(issue, env)));
1380
+ },
1381
+ async get(id) {
1382
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1383
+ let issue;
1384
+ try {
1385
+ issue = runGh(bin, [
1386
+ "issue",
1387
+ "view",
1388
+ String(id),
1389
+ "--repo",
1390
+ repo,
1391
+ "--json",
1392
+ "number,title,body,labels,state,url,assignees,id"
1393
+ ], spawnFn, env, timeoutMs);
1394
+ } catch (error) {
1395
+ const detail = error instanceof Error ? error.message : String(error);
1396
+ if (/could not resolve to (an? )?(issue|pullrequest)|no issues? (found|matched)|404 not found|gh: not found|gh issue view\b[\s\S]*failed \(exit \d+\): not found\b/i.test(detail)) {
1397
+ return;
1398
+ }
1399
+ throw new Error(`Failed to read task ${id} from GitHub repo ${repo}: ${detail}`);
1400
+ }
1401
+ return issueToTaskWithOptionalNativeDependencies(issue, env);
1402
+ },
1403
+ async updateStatus(id, status) {
1404
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1405
+ await applyIssueStatus(bin, repo, spawnFn, id, status, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
1406
+ notifyTaskChanged(opts.onTaskChanged, repo, id, status);
1407
+ },
1408
+ async updateTask(id, update) {
1409
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1410
+ await applyIssueUpdate(bin, repo, spawnFn, id, update, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
1411
+ notifyTaskChanged(opts.onTaskChanged, repo, id, update.status);
1412
+ },
1413
+ async addLabels(id, labels) {
1414
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1415
+ applyLabels(bin, repo, spawnFn, id, labels, "--add-label", env, timeoutMs);
1416
+ notifyTaskChanged(opts.onTaskChanged, repo, id);
1417
+ },
1418
+ async removeLabels(id, labels) {
1419
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1420
+ applyLabels(bin, repo, spawnFn, id, labels, "--remove-label", env, timeoutMs);
1421
+ notifyTaskChanged(opts.onTaskChanged, repo, id);
1422
+ },
1423
+ async createIssue(input) {
1424
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1425
+ const body = input.body ?? "";
1426
+ const args = [
1427
+ "api",
1428
+ "-X",
1429
+ "POST",
1430
+ `repos/${repo}/issues`,
1431
+ "-f",
1432
+ `title=${input.title}`,
1433
+ "-f",
1434
+ `body=${body}`,
1435
+ ...(input.labels ?? []).flatMap((label) => ["-f", `labels[]=${label}`])
1436
+ ];
1437
+ const issue = runGh(bin, args, spawnFn, env, timeoutMs);
1438
+ notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
1439
+ return issueToTask({ ...issue, body: issue.body ?? body }, repo);
1440
+ },
1441
+ async create(input) {
1442
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1443
+ const body = bodyForCreatedTask(input);
1444
+ const args = [
1445
+ "api",
1446
+ "-X",
1447
+ "POST",
1448
+ `repos/${repo}/issues`,
1449
+ "-f",
1450
+ `title=${input.title}`,
1451
+ "-f",
1452
+ `body=${body}`,
1453
+ "-f",
1454
+ "labels[]=rig:generated"
1455
+ ];
1456
+ const issue = runGh(bin, args, spawnFn, env, timeoutMs);
1457
+ notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
1458
+ return issueToTask({ ...issue, body: issue.body ?? body }, repo);
1459
+ },
1460
+ async getIssueBody(id) {
1461
+ const env = await resolveCredentialEnv(opts, "selected-repo");
1462
+ return fetchIssueBody(bin, repo, spawnFn, id, env, timeoutMs);
1463
+ }
1464
+ };
1412
1465
  }
1413
- function createDocsDriftRuntimeCliCommand(options = {}) {
1466
+
1467
+ // packages/standard-plugin/src/files-source.ts
1468
+ import { readFileSync as readFileSync2, readdirSync, existsSync as existsSync2, statSync, writeFileSync } from "fs";
1469
+ import { join, basename, isAbsolute, resolve as resolve2 } from "path";
1470
+ var DEFAULT_PATTERN = /\.(task\.)?json$/;
1471
+ function readTaskFile(file, pattern) {
1472
+ const raw = JSON.parse(readFileSync2(file, "utf-8"));
1473
+ const inferredId = basename(file).replace(pattern, "");
1474
+ const labels = Array.isArray(raw.labels) ? raw.labels.filter((label) => typeof label === "string") : [];
1475
+ const scope = labels.filter((label) => label.startsWith("scope:")).map((label) => label.slice("scope:".length));
1476
+ const validators = labels.filter((label) => label.startsWith("validator:")).map((label) => label.slice("validator:".length));
1477
+ const roleLabel = labels.find((label) => label.startsWith("role:"));
1414
1478
  return {
1415
- id: DOCS_DRIFT_CLI_ID,
1416
- family: "drift",
1417
- command: DOCS_DRIFT_CLI_COMMAND,
1418
- description: "Scan documentation for stale code references.",
1419
- usage: DOCS_DRIFT_CLI_COMMAND,
1420
- projectRequired: true,
1421
- run: (context, args) => executeDrift(context, args, options)
1479
+ id: raw["id"] ?? inferredId,
1480
+ deps: raw["deps"] ?? raw["depends_on"] ?? [],
1481
+ status: raw["status"] ?? "ready",
1482
+ ...scope.length > 0 ? { scope } : {},
1483
+ ...roleLabel ? { role: roleLabel.slice("role:".length) } : {},
1484
+ ...validators.length > 0 ? { validators, validation: validators } : {},
1485
+ ...raw
1422
1486
  };
1423
1487
  }
1424
- var DOCS_DRIFT_RUNTIME_CLI_COMMAND = createDocsDriftRuntimeCliCommand();
1425
- async function runDriftCli(args, options = {}) {
1426
- const docsGlobs = [];
1427
- const ignoreGlobs = [];
1428
- let json = false;
1429
- let failOnDrift = false;
1430
- for (let index = 0;index < args.length; index += 1) {
1431
- const arg = args[index];
1432
- if (arg === "--json") {
1433
- json = true;
1434
- continue;
1435
- }
1436
- if (arg === "--fail-on-drift") {
1437
- failOnDrift = true;
1438
- continue;
1488
+ function createFilesTaskSource(opts) {
1489
+ const pattern = opts.pattern ?? DEFAULT_PATTERN;
1490
+ const configured = opts.path ?? opts.dir;
1491
+ if (!configured) {
1492
+ throw new Error("createFilesTaskSource: either `path` or `dir` must be provided");
1493
+ }
1494
+ const directory = isAbsolute(configured) ? configured : resolve2(opts.projectRoot ?? process.cwd(), configured);
1495
+ const findTaskFile = (id) => {
1496
+ if (!existsSync2(directory))
1497
+ return;
1498
+ for (const name of readdirSync(directory)) {
1499
+ if (!pattern.test(name))
1500
+ continue;
1501
+ const p = join(directory, name);
1502
+ try {
1503
+ if (!statSync(p).isFile())
1504
+ continue;
1505
+ if (readTaskFile(p, pattern).id === id)
1506
+ return p;
1507
+ } catch {}
1439
1508
  }
1440
- if (arg === "--docs") {
1441
- docsGlobs.push(takeOptionValue(args, index, arg));
1442
- index += 1;
1443
- continue;
1509
+ return;
1510
+ };
1511
+ const applyUpdate = (id, update) => {
1512
+ const file = findTaskFile(id);
1513
+ if (!file) {
1514
+ throw new Error(`files task not found: ${id}`);
1444
1515
  }
1445
- if (arg === "--ignore") {
1446
- ignoreGlobs.push(takeOptionValue(args, index, arg));
1447
- index += 1;
1448
- continue;
1516
+ const raw = JSON.parse(readFileSync2(file, "utf-8"));
1517
+ if (update.status)
1518
+ raw.status = update.status;
1519
+ if (update.title !== undefined)
1520
+ raw.title = update.title;
1521
+ if (update.body !== undefined)
1522
+ raw.body = update.body;
1523
+ if (update.comment?.trim()) {
1524
+ const existing = Array.isArray(raw.comments) ? raw.comments : [];
1525
+ raw.comments = [
1526
+ ...existing,
1527
+ {
1528
+ body: update.comment,
1529
+ createdAt: new Date().toISOString(),
1530
+ source: "rig"
1531
+ }
1532
+ ];
1449
1533
  }
1450
- throw new Error(`Unknown rig drift argument: ${arg}`);
1451
- }
1452
- const report = await detectDrift({
1453
- projectRoot: options.projectRoot ?? process.cwd(),
1454
- ...docsGlobs.length > 0 ? { docsGlobs } : {},
1455
- ...ignoreGlobs.length > 0 ? { ignoreGlobs } : {}
1456
- });
1457
- const write = options.write ?? ((message) => console.log(message));
1458
- if (json) {
1459
- write(JSON.stringify(report));
1460
- } else {
1461
- write(`Scanned ${report.scanned} doc(s); ${report.findings.length} drift finding(s).`);
1462
- for (const finding of report.findings) {
1463
- write(`${finding.confidence.toUpperCase()} ${finding.kind} ${finding.docPath}${finding.line ? `:${finding.line}` : ""} ${finding.reference ?? ""} \u2014 ${finding.detail}`);
1534
+ writeFileSync(file, `${JSON.stringify(raw, null, 2)}
1535
+ `, "utf-8");
1536
+ };
1537
+ return {
1538
+ id: "std:files",
1539
+ kind: "files",
1540
+ async list() {
1541
+ if (!existsSync2(directory))
1542
+ return [];
1543
+ const out = [];
1544
+ for (const name of readdirSync(directory)) {
1545
+ if (!pattern.test(name))
1546
+ continue;
1547
+ const p = join(directory, name);
1548
+ try {
1549
+ if (!statSync(p).isFile())
1550
+ continue;
1551
+ out.push(readTaskFile(p, pattern));
1552
+ } catch (err) {
1553
+ console.warn(`[files-source] skipped ${name}: ${err.message}`);
1554
+ }
1555
+ }
1556
+ return out;
1557
+ },
1558
+ async get(id) {
1559
+ const all = await this.list();
1560
+ return all.find((t) => t.id === id);
1561
+ },
1562
+ async updateStatus(id, status) {
1563
+ applyUpdate(id, { status });
1564
+ },
1565
+ async updateTask(id, update) {
1566
+ applyUpdate(id, update);
1464
1567
  }
1465
- }
1466
- const high = highConfidenceDriftFindings(report);
1467
- if (failOnDrift && high.length > 0) {
1468
- options.writeError?.(`${high.length} high-confidence drift finding(s).`);
1469
- return 2;
1470
- }
1471
- return 0;
1472
- }
1473
- // packages/standard-plugin/src/drift/judge.ts
1474
- async function judgeDocumentationDrift(provider, input) {
1475
- const result = await provider.judge(input);
1476
- return result.mismatches.map((mismatch) => ({
1477
- kind: "semantic-mismatch",
1478
- docPath: input.docPath,
1479
- line: mismatch.line ?? null,
1480
- reference: mismatch.reference ?? input.reference ?? null,
1481
- detail: mismatch.detail,
1482
- confidence: mismatch.confidence ?? "medium"
1483
- }));
1568
+ };
1484
1569
  }
1570
+
1485
1571
  // packages/standard-plugin/src/plugin.ts
1572
+ init_metadata();
1573
+ init_metadata();
1574
+ import { createStandardProductEntrypointPlugin, standardProductEntrypointPlugin } from "@rig/product-entrypoint-plugin/plugin";
1575
+ import { createStandardTaskCliPlugin, standardTaskCliPlugin } from "@rig/task-cli-plugin/plugin";
1486
1576
  var DOCS_HEALTH_PANEL_ID = "docs-health";
1487
1577
  function requireStringField(config, field, kind) {
1488
1578
  const value = config[field];
@@ -1539,7 +1629,8 @@ function createDocsHealthPanelProducer(options = {}) {
1539
1629
  const projectRoot = panelProjectRoot(context);
1540
1630
  if (!projectRoot)
1541
1631
  return;
1542
- const report = await detectDrift({
1632
+ const { detectDrift: detectDrift2 } = await Promise.resolve().then(() => (init_detect(), exports_detect));
1633
+ const report = await detectDrift2({
1543
1634
  projectRoot,
1544
1635
  ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
1545
1636
  ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {}
@@ -1557,24 +1648,46 @@ function createDocsHealthPanelProducer(options = {}) {
1557
1648
  };
1558
1649
  };
1559
1650
  }
1560
- function standardPlugin(opts = {}) {
1651
+ function createLazyDocsDriftValidator(options = {}) {
1652
+ return {
1653
+ ...DOCS_DRIFT_VALIDATOR,
1654
+ async run(ctx) {
1655
+ const { runDocsDriftValidation: runDocsDriftValidation2 } = await Promise.resolve().then(() => (init_plugin(), exports_plugin));
1656
+ return runDocsDriftValidation2({
1657
+ projectRoot: ctx.workspaceRoot,
1658
+ ...options.docsGlobs !== undefined ? { docsGlobs: options.docsGlobs } : {},
1659
+ ...options.ignoreGlobs !== undefined ? { ignoreGlobs: options.ignoreGlobs } : {},
1660
+ ...options.failOnDrift !== undefined ? { failOnDrift: options.failOnDrift } : {}
1661
+ });
1662
+ }
1663
+ };
1664
+ }
1665
+ function createLazyDocsDriftGateStage(options = {}) {
1666
+ return async (ctx) => {
1667
+ const { createDocsDriftGateStage: createDocsDriftGateStage2 } = await Promise.resolve().then(() => (init_plugin(), exports_plugin));
1668
+ return createDocsDriftGateStage2(options)(ctx);
1669
+ };
1670
+ }
1671
+ function createLazyDocsDriftRuntimeCliCommand(options = {}) {
1672
+ return {
1673
+ id: DOCS_DRIFT_CLI_ID,
1674
+ family: "drift",
1675
+ command: DOCS_DRIFT_CLI_COMMAND,
1676
+ description: "Scan documentation for stale code references.",
1677
+ usage: DOCS_DRIFT_CLI_COMMAND,
1678
+ projectRequired: true,
1679
+ run: async (context, args) => {
1680
+ const { executeDrift: executeDrift2 } = await Promise.resolve().then(() => (init_plugin(), exports_plugin));
1681
+ return executeDrift2(context, args, options);
1682
+ }
1683
+ };
1684
+ }
1685
+ function createStandardDocsDriftPlugin(opts = {}) {
1561
1686
  return definePlugin({
1562
- name: "rig-standard",
1687
+ name: "@rig/standard-plugin:docs-drift",
1563
1688
  version: "0.1.0",
1564
1689
  contributes: {
1565
1690
  validators: [DOCS_DRIFT_VALIDATOR],
1566
- taskSources: [
1567
- {
1568
- id: "std:github-issues",
1569
- kind: "github-issues",
1570
- description: "GitHub Issues via gh CLI"
1571
- },
1572
- {
1573
- id: "std:files",
1574
- kind: "files",
1575
- description: "JSON files in a local directory"
1576
- }
1577
- ],
1578
1691
  capabilities: [
1579
1692
  { id: DOCS_DRIFT_CAPABILITY_ID, title: "Documentation drift detection", commandId: DOCS_DRIFT_CLI_ID, panelId: DOCS_HEALTH_PANEL_ID }
1580
1693
  ],
@@ -1593,15 +1706,36 @@ function standardPlugin(opts = {}) {
1593
1706
  stageMutations: [DOCS_DRIFT_STAGE_MUTATION]
1594
1707
  }
1595
1708
  }, {
1596
- validators: [createDocsDriftValidator(opts.drift)],
1597
- stages: { [DOCS_DRIFT_STAGE_ID]: createDocsDriftGateStage(opts.drift) },
1709
+ validators: [createLazyDocsDriftValidator(opts)],
1710
+ stages: { [DOCS_DRIFT_STAGE_ID]: createLazyDocsDriftGateStage(opts) },
1598
1711
  featureCapabilities: [
1599
1712
  { id: DOCS_DRIFT_CAPABILITY_ID, title: "Documentation drift detection", commandId: DOCS_DRIFT_CLI_ID, panelId: DOCS_HEALTH_PANEL_ID }
1600
1713
  ],
1601
1714
  panels: [
1602
- { id: DOCS_HEALTH_PANEL_ID, slot: "capability", title: "Documentation drift", capabilityId: DOCS_DRIFT_CAPABILITY_ID, produce: createDocsHealthPanelProducer(opts.drift) }
1715
+ { id: DOCS_HEALTH_PANEL_ID, slot: "capability", title: "Documentation drift", capabilityId: DOCS_DRIFT_CAPABILITY_ID, produce: createDocsHealthPanelProducer(opts) }
1603
1716
  ],
1604
- cliCommands: [createDocsDriftRuntimeCliCommand(opts.drift)],
1717
+ cliCommands: [createLazyDocsDriftRuntimeCliCommand(opts)]
1718
+ });
1719
+ }
1720
+ function createStandardTaskSourcesPlugin(opts = {}) {
1721
+ return definePlugin({
1722
+ name: "@rig/standard-plugin:task-sources",
1723
+ version: "0.1.0",
1724
+ contributes: {
1725
+ taskSources: [
1726
+ {
1727
+ id: "std:github-issues",
1728
+ kind: "github-issues",
1729
+ description: "GitHub Issues via gh CLI"
1730
+ },
1731
+ {
1732
+ id: "std:files",
1733
+ kind: "files",
1734
+ description: "JSON files in a local directory"
1735
+ }
1736
+ ]
1737
+ }
1738
+ }, {
1605
1739
  taskSources: [
1606
1740
  {
1607
1741
  id: "std:github-issues",
@@ -1659,27 +1793,22 @@ function standardPlugin(opts = {}) {
1659
1793
  });
1660
1794
  }
1661
1795
  export {
1662
- runDriftCli,
1663
- runDocsDriftValidation,
1664
- makeDriftGit,
1665
- judgeDocumentationDrift,
1666
- extractDriftReferences,
1667
- executeDrift,
1668
- driftGateResult,
1669
- detectStaleAnchors,
1670
- detectDrift,
1671
- detectDeletedReferences,
1672
- standardPlugin as default,
1796
+ standardTaskCliPlugin,
1797
+ standardProductEntrypointPlugin,
1673
1798
  createStateGitHubCredentialProvider,
1799
+ createStandardTaskSourcesPlugin,
1800
+ createStandardTaskCliPlugin,
1801
+ createStandardProductEntrypointPlugin,
1802
+ createStandardDocsDriftPlugin,
1674
1803
  createGitHubIssuesTaskSource,
1675
1804
  createFilesTaskSource,
1676
1805
  createEnvGitHubCredentialProvider,
1677
- createDocsDriftValidator,
1678
- createDocsDriftRuntimeCliCommand,
1679
1806
  DOCS_HEALTH_PANEL_ID,
1680
1807
  DOCS_DRIFT_VALIDATOR_ID,
1808
+ DOCS_DRIFT_VALIDATOR,
1809
+ DOCS_DRIFT_STAGE_MUTATION,
1681
1810
  DOCS_DRIFT_STAGE_ID,
1682
- DOCS_DRIFT_RUNTIME_CLI_COMMAND,
1683
1811
  DOCS_DRIFT_CLI_ID,
1812
+ DOCS_DRIFT_CLI_COMMAND,
1684
1813
  DOCS_DRIFT_CAPABILITY_ID
1685
1814
  };