@h-rig/task-sources-plugin 0.0.6-alpha.156

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,843 @@
1
+ // @bun
2
+ // packages/task-sources-plugin/src/github-issues-source.ts
3
+ import { spawnSync } from "child_process";
4
+ var STATUS_LABELS = new Set(["ready", "blocked", "in-progress", "under-review", "failed", "cancelled"]);
5
+ var RIG_STATUS_COMMENT_MARKER = "<!-- rig:status-comment -->";
6
+ var RIG_METADATA_START = "<!-- rig:metadata:start -->";
7
+ var RIG_METADATA_END = "<!-- rig:metadata:end -->";
8
+ var RIG_STATUS_LABELS = new Set(["rig:running", "rig:pr-open", "rig:ci-fixing", "rig:merging", "rig:done", "rig:needs-attention"]);
9
+ var DEFAULT_GH_TIMEOUT_MS = 15000;
10
+ var DEFAULT_GITHUB_ISSUE_LIST_LIMIT = 1000;
11
+ function statusFor(issue) {
12
+ const state = (issue.state ?? "").toUpperCase();
13
+ if (state === "CLOSED")
14
+ return "closed";
15
+ const labelNames = labelNamesFor(issue);
16
+ if (labelNames.includes("in-progress"))
17
+ return "in_progress";
18
+ if (labelNames.includes("blocked"))
19
+ return "blocked";
20
+ if (labelNames.includes("ready"))
21
+ return "ready";
22
+ if (labelNames.includes("under-review"))
23
+ return "under_review";
24
+ if (labelNames.includes("failed"))
25
+ return "failed";
26
+ if (labelNames.includes("cancelled"))
27
+ return "cancelled";
28
+ return "open";
29
+ }
30
+ function parseIssueRefs(raw) {
31
+ const refs = [...raw.matchAll(/(?:^|[^\w/.-])(?:[\w.-]+\/[\w.-]+#|#)?(\d+)\b/g)].map((match) => match[1]).filter((value) => Boolean(value));
32
+ return [...new Set(refs)];
33
+ }
34
+ function metadataKeyPattern(keys) {
35
+ return new RegExp(`^(?:${keys.map((key) => key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")}):\\s*(.*)$`, "i");
36
+ }
37
+ function parseMetadataList(body, keys) {
38
+ const block = body.match(/<!-- rig:metadata:start -->\s*([\s\S]*?)\s*<!-- rig:metadata:end -->/);
39
+ if (!block)
40
+ return [];
41
+ const lines = block[1].split(/\r?\n/);
42
+ const values = [];
43
+ const keyPattern = metadataKeyPattern(keys);
44
+ for (let index = 0;index < lines.length; index += 1) {
45
+ const line = lines[index];
46
+ const sameLine = line.match(keyPattern);
47
+ if (!sameLine)
48
+ continue;
49
+ const inlineValue = sameLine[1]?.trim() ?? "";
50
+ if (inlineValue) {
51
+ values.push(...parseIssueRefs(inlineValue));
52
+ continue;
53
+ }
54
+ for (let cursor = index + 1;cursor < lines.length; cursor += 1) {
55
+ const item = lines[cursor].match(/^\s*-\s*(.+)$/);
56
+ if (!item)
57
+ break;
58
+ values.push(...parseIssueRefs(item[1]));
59
+ }
60
+ }
61
+ return [...new Set(values)];
62
+ }
63
+ function bodyWithoutRigMetadataBlock(body) {
64
+ return body.replace(/<!-- rig:metadata:start -->\s*[\s\S]*?\s*<!-- rig:metadata:end -->/g, "");
65
+ }
66
+ function parseBodyKeyRefs(body, keys) {
67
+ const keyPattern = metadataKeyPattern(keys);
68
+ const values = bodyWithoutRigMetadataBlock(body).split(/\r?\n/).flatMap((line) => {
69
+ const match = line.match(keyPattern);
70
+ return match?.[1] ? parseIssueRefs(match[1]) : [];
71
+ });
72
+ return [...new Set(values)];
73
+ }
74
+ function parseDeps(body) {
75
+ const keys = ["depends-on", "deps", "blocked-by", "blocked_by"];
76
+ return [...new Set([...parseBodyKeyRefs(body, keys), ...parseMetadataList(body, keys)])];
77
+ }
78
+ function parseParents(body) {
79
+ const keys = ["parents", "parent"];
80
+ return [...new Set([...parseBodyKeyRefs(body, keys), ...parseMetadataList(body, keys)])];
81
+ }
82
+ function issueTypeFor(issue) {
83
+ const labels = labelNamesFor(issue);
84
+ const typed = labels.find((l) => l.startsWith("type:"));
85
+ if (typed)
86
+ return typed.slice("type:".length);
87
+ if (labels.includes("epic"))
88
+ return "epic";
89
+ return "task";
90
+ }
91
+ function issueToTask(issue, repo, nativeDependencies) {
92
+ const labelNames = labelNamesFor(issue);
93
+ const scope = labelNames.filter((l) => l.startsWith("scope:")).map((l) => l.slice("scope:".length));
94
+ const roleLabel = labelNames.find((l) => l.startsWith("role:"));
95
+ const role = roleLabel ? roleLabel.slice("role:".length) : undefined;
96
+ const validators = labelNames.filter((l) => l.startsWith("validator:")).map((l) => l.slice("validator:".length));
97
+ const body = issue.body ?? "";
98
+ const issueNodeId = issue.id ?? issue.nodeId ?? issue.node_id;
99
+ const parsedDeps = parseDeps(body);
100
+ const deps = nativeDependencies?.deps ? [...new Set([...parsedDeps, ...nativeDependencies.deps])] : parsedDeps;
101
+ return {
102
+ id: String(issue.number),
103
+ ...typeof issueNodeId === "string" && issueNodeId.trim() ? { issueNodeId: issueNodeId.trim() } : {},
104
+ deps,
105
+ status: statusFor(issue),
106
+ title: issue.title,
107
+ body,
108
+ scope,
109
+ role,
110
+ validators,
111
+ url: issue.url ?? issue.html_url,
112
+ issueType: issueTypeFor(issue),
113
+ sourceIssueId: `${repo}#${issue.number}`,
114
+ parentChildDeps: parseParents(body),
115
+ labels: labelNames,
116
+ ...nativeDependencies?.degraded ? { nativeDependenciesDegraded: true, nativeDependenciesError: nativeDependencies.degraded } : {},
117
+ raw: issue
118
+ };
119
+ }
120
+ function labelNamesFor(issue) {
121
+ return (issue.labels ?? []).flatMap((label) => {
122
+ if (typeof label === "string")
123
+ return [label];
124
+ return typeof label.name === "string" ? [label.name] : [];
125
+ });
126
+ }
127
+ function yamlScalar(value) {
128
+ if (Array.isArray(value)) {
129
+ return value.length === 0 ? "[]" : `
130
+ ${value.map((entry) => ` - ${String(entry)}`).join(`
131
+ `)}`;
132
+ }
133
+ if (value && typeof value === "object")
134
+ return JSON.stringify(value);
135
+ return String(value);
136
+ }
137
+ function updateRigOwnedMetadataBlock(body, metadata) {
138
+ const rendered = [
139
+ RIG_METADATA_START,
140
+ ...Object.entries(metadata).map(([key, value]) => Array.isArray(value) ? `${key}:${yamlScalar(value)}` : `${key}: ${yamlScalar(value)}`),
141
+ RIG_METADATA_END
142
+ ].join(`
143
+ `);
144
+ const pattern = new RegExp(`${RIG_METADATA_START.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}\\s*[\\s\\S]*?\\s*${RIG_METADATA_END.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}`);
145
+ if (pattern.test(body))
146
+ return body.replace(pattern, rendered);
147
+ return body.trim().length > 0 ? `${body.trimEnd()}
148
+
149
+ ${rendered}
150
+ ` : `${rendered}
151
+ `;
152
+ }
153
+ function buildRigStickyStatusComment(input) {
154
+ const lines = [
155
+ RIG_STATUS_COMMENT_MARKER,
156
+ `### Rig status: ${input.status}`,
157
+ "",
158
+ input.summary
159
+ ];
160
+ if (input.runId)
161
+ lines.push("", `- Run: ${input.runId}`);
162
+ if (input.prUrl)
163
+ lines.push(`- PR: ${input.prUrl}`);
164
+ for (const detail of input.details ?? [])
165
+ lines.push(`- ${detail}`);
166
+ return lines.join(`
167
+ `);
168
+ }
169
+ function isRigStickyStatusComment(body) {
170
+ return body.includes(RIG_STATUS_COMMENT_MARKER);
171
+ }
172
+ function ghSpawnOptions(extraEnv, timeoutMs) {
173
+ const env = {
174
+ ...process.env,
175
+ ...process.env.GH_TOKEN !== undefined ? { GH_TOKEN: process.env.GH_TOKEN } : {},
176
+ ...process.env.GITHUB_TOKEN !== undefined ? { GITHUB_TOKEN: process.env.GITHUB_TOKEN } : {},
177
+ ...process.env.RIG_GITHUB_TOKEN !== undefined ? { RIG_GITHUB_TOKEN: process.env.RIG_GITHUB_TOKEN } : {}
178
+ };
179
+ for (const [key, value] of Object.entries(extraEnv ?? {})) {
180
+ if (value === undefined)
181
+ delete env[key];
182
+ else
183
+ env[key] = value;
184
+ }
185
+ return {
186
+ encoding: "utf-8",
187
+ timeout: timeoutMs,
188
+ env
189
+ };
190
+ }
191
+ function credentialEnv(token) {
192
+ const clean = token?.trim() ?? "";
193
+ if (clean)
194
+ return { GH_TOKEN: clean, GITHUB_TOKEN: clean, RIG_GITHUB_TOKEN: clean };
195
+ return { GH_TOKEN: undefined, GITHUB_TOKEN: undefined, RIG_GITHUB_TOKEN: undefined };
196
+ }
197
+ async function resolveCredentialEnv(opts, purpose) {
198
+ if (!opts.credentialProvider)
199
+ return;
200
+ const input = {
201
+ owner: opts.owner,
202
+ repo: opts.repo,
203
+ workspaceId: opts.workspaceId ?? `${opts.owner}/${opts.repo}`,
204
+ ...opts.userId ? { userId: opts.userId } : {},
205
+ purpose
206
+ };
207
+ const resolved = await opts.credentialProvider.resolveGitHubToken(input);
208
+ return credentialEnv(resolved.token);
209
+ }
210
+ function tokenDiagnostic(value) {
211
+ const clean = value?.trim() ?? "";
212
+ return clean ? `present(len=${clean.length})` : "missing";
213
+ }
214
+ function runGh(bin, args, spawn, extraEnv, timeoutMs) {
215
+ const options = ghSpawnOptions(extraEnv, timeoutMs);
216
+ const res = spawn(bin, [...args], options);
217
+ assertGhSuccess(args, res, options.env);
218
+ if (!res.stdout || res.stdout.trim() === "")
219
+ return [];
220
+ return JSON.parse(res.stdout);
221
+ }
222
+ function runGhVoid(bin, args, spawn, extraEnv, timeoutMs) {
223
+ const options = ghSpawnOptions(extraEnv, timeoutMs);
224
+ const res = spawn(bin, [...args], options);
225
+ assertGhSuccess(args, res, options.env);
226
+ }
227
+ function assertGhSuccess(args, res, env) {
228
+ if (res.error) {
229
+ const msg = res.error.message ?? String(res.error);
230
+ throw new Error(`gh CLI not available \u2014 install gh (brew install gh / apt install gh): ${msg}`);
231
+ }
232
+ if (res.status !== 0) {
233
+ throw new Error(`gh ${args.join(" ")} failed (exit ${res.status}): ${res.stderr}
234
+ [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)}`);
235
+ }
236
+ }
237
+ var DEFAULT_PROJECT_STATUSES = {
238
+ todo: "Todo",
239
+ running: "In Progress",
240
+ prOpen: "In Review",
241
+ ciFixing: "In Review",
242
+ merging: "In Review",
243
+ done: "Done",
244
+ needsAttention: "Needs Attention"
245
+ };
246
+ function asProjectRecord(value) {
247
+ return value && typeof value === "object" && !Array.isArray(value) ? value : null;
248
+ }
249
+ function projectString(value) {
250
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : null;
251
+ }
252
+ function projectLifecycleStatusForTaskStatus(status) {
253
+ const normalized = status?.trim().toLowerCase().replace(/[-\s]+/g, "_");
254
+ switch (normalized) {
255
+ case "draft":
256
+ case "open":
257
+ case "queued":
258
+ case "ready":
259
+ return "todo";
260
+ case "running":
261
+ case "in_progress":
262
+ return "running";
263
+ case "under_review":
264
+ case "review":
265
+ case "pr_open":
266
+ return "prOpen";
267
+ case "ci_fixing":
268
+ case "fixing":
269
+ return "ciFixing";
270
+ case "merging":
271
+ case "merge":
272
+ return "merging";
273
+ case "closed":
274
+ case "completed":
275
+ case "done":
276
+ return "done";
277
+ case "blocked":
278
+ case "cancelled":
279
+ case "failed":
280
+ case "needs_attention":
281
+ return "needsAttention";
282
+ default:
283
+ return null;
284
+ }
285
+ }
286
+ function ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs) {
287
+ return async (query, variables) => {
288
+ const args = ["api", "graphql", "-f", `query=${query}`];
289
+ for (const [key, value] of Object.entries(variables)) {
290
+ if (value === undefined || value === null)
291
+ continue;
292
+ args.push("-f", `${key}=${String(value)}`);
293
+ }
294
+ const response = runGh(bin, args, spawnFn, extraEnv, timeoutMs);
295
+ return asProjectRecord(response)?.data ?? response;
296
+ };
297
+ }
298
+ function issueNodeIdFor(issue) {
299
+ const id = issue.id ?? issue.nodeId ?? issue.node_id;
300
+ return typeof id === "string" && id.trim().length > 0 ? id.trim() : null;
301
+ }
302
+ function nativeIssueDependencyRef(value, currentRepo) {
303
+ const record = asProjectRecord(value);
304
+ const number = typeof record?.number === "number" ? String(record.number) : projectString(record?.number);
305
+ if (!number)
306
+ return null;
307
+ const repository = asProjectRecord(record?.repository);
308
+ const owner = projectString(asProjectRecord(repository?.owner)?.login);
309
+ const name = projectString(repository?.name);
310
+ if (!owner || !name || `${owner}/${name}` === currentRepo)
311
+ return number;
312
+ return `${owner}/${name}#${number}`;
313
+ }
314
+ function nativeDependencyRefsFrom(data, currentRepo) {
315
+ const issue = asProjectRecord(asProjectRecord(data)?.node);
316
+ const blockedBy = asProjectRecord(issue?.blockedBy);
317
+ const nodes = Array.isArray(blockedBy?.nodes) ? blockedBy.nodes : [];
318
+ return [...new Set(nodes.flatMap((node) => {
319
+ const ref = nativeIssueDependencyRef(node, currentRepo);
320
+ return ref ? [ref] : [];
321
+ }))];
322
+ }
323
+ async function readNativeDependenciesForIssue(input) {
324
+ const issueId = issueNodeIdFor(input.issue);
325
+ if (!issueId)
326
+ return { deps: [], degraded: "GitHub issue node id is unavailable." };
327
+ const query = `
328
+ query RigIssueNativeDependencies($issueId: ID!) {
329
+ node(id: $issueId) {
330
+ ... on Issue {
331
+ blockedBy(first: 100) {
332
+ nodes {
333
+ number
334
+ repository { name owner { login } }
335
+ }
336
+ }
337
+ }
338
+ }
339
+ }
340
+ `;
341
+ try {
342
+ return {
343
+ deps: nativeDependencyRefsFrom(await input.fetchGraphQL(query, { issueId }, "gh-cli"), input.repo)
344
+ };
345
+ } catch (error) {
346
+ const detail = error instanceof Error ? error.message : String(error);
347
+ return { deps: [], degraded: detail };
348
+ }
349
+ }
350
+ function formatIssueReference(ref) {
351
+ const clean = ref.trim().replace(/^#/, "");
352
+ return /^\d+$/.test(clean) ? `#${clean}` : clean;
353
+ }
354
+ function appendReferenceLines(body, deps, parents) {
355
+ const lines = [];
356
+ const cleanDeps = (deps ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
357
+ const cleanParents = (parents ?? []).map(formatIssueReference).filter((ref) => ref.length > 0);
358
+ if (cleanDeps.length > 0)
359
+ lines.push(`depends-on: ${cleanDeps.join(", ")}`);
360
+ if (cleanParents.length > 0)
361
+ lines.push(`parents: ${cleanParents.join(", ")}`);
362
+ if (lines.length === 0)
363
+ return body;
364
+ return body.trim().length > 0 ? `${body.trimEnd()}
365
+
366
+ ${lines.join(`
367
+ `)}` : lines.join(`
368
+ `);
369
+ }
370
+ function bodyForCreatedTask(input) {
371
+ const metadata = { ...input.metadata ?? {} };
372
+ if (input.deps && input.deps.length > 0)
373
+ metadata["depends-on"] = input.deps.map(formatIssueReference);
374
+ if (input.parents && input.parents.length > 0)
375
+ metadata.parents = input.parents.map(formatIssueReference);
376
+ return updateRigOwnedMetadataBlock(appendReferenceLines(input.body, input.deps, input.parents), metadata);
377
+ }
378
+ function projectStatusFieldFrom(data, projectId) {
379
+ const fields = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.fields)?.nodes;
380
+ for (const node of Array.isArray(fields) ? fields : []) {
381
+ const record = asProjectRecord(node);
382
+ if (projectString(record?.name)?.toLowerCase() !== "status")
383
+ continue;
384
+ const id = projectString(record?.id);
385
+ if (!id)
386
+ continue;
387
+ const options = Array.isArray(record?.options) ? record.options.flatMap((option) => {
388
+ const optionRecord = asProjectRecord(option);
389
+ const optionId = projectString(optionRecord?.id);
390
+ const name = projectString(optionRecord?.name);
391
+ return optionId && name ? [{ id: optionId, name }] : [];
392
+ }) : [];
393
+ return { id, name: "Status", options };
394
+ }
395
+ throw new Error(`GitHub Project ${projectId} does not expose a Status single-select field.`);
396
+ }
397
+ async function resolveProjectStatusField(input) {
398
+ const query = `
399
+ query RigProjectStatusField($projectId: ID!) {
400
+ node(id: $projectId) {
401
+ ... on ProjectV2 {
402
+ fields(first: 50) {
403
+ nodes {
404
+ ... on ProjectV2FieldCommon { id name }
405
+ ... on ProjectV2SingleSelectField { id name options { id name } }
406
+ }
407
+ }
408
+ }
409
+ }
410
+ }
411
+ `;
412
+ return projectStatusFieldFrom(await input.fetchGraphQL(query, { projectId: input.projectId }, input.token), input.projectId);
413
+ }
414
+ async function ensureIssueProjectItem(input) {
415
+ const query = `
416
+ query RigFindProjectIssueItem($projectId: ID!) {
417
+ node(id: $projectId) {
418
+ ... on ProjectV2 {
419
+ items(first: 100) { nodes { id content { ... on Issue { id } } } }
420
+ }
421
+ }
422
+ }
423
+ `;
424
+ const data = await input.fetchGraphQL(query, { projectId: input.projectId }, input.token);
425
+ const nodes = asProjectRecord(asProjectRecord(asProjectRecord(data)?.node)?.items)?.nodes;
426
+ for (const node of Array.isArray(nodes) ? nodes : []) {
427
+ const record = asProjectRecord(node);
428
+ const content = asProjectRecord(record?.content);
429
+ if (projectString(content?.id) === input.issueNodeId) {
430
+ const id2 = projectString(record?.id);
431
+ if (id2)
432
+ return { id: id2, created: false };
433
+ }
434
+ }
435
+ const mutation = `
436
+ mutation RigAddIssueToProject($projectId: ID!, $contentId: ID!) {
437
+ addProjectV2ItemById(input: { projectId: $projectId, contentId: $contentId }) { item { id } }
438
+ }
439
+ `;
440
+ const created = await input.fetchGraphQL(mutation, { projectId: input.projectId, contentId: input.issueNodeId }, input.token);
441
+ const addResult = asProjectRecord(asProjectRecord(created)?.addProjectV2ItemById);
442
+ const id = projectString(asProjectRecord(addResult?.item)?.id);
443
+ if (!id)
444
+ throw new Error("GitHub Project item creation did not return an item id.");
445
+ return { id, created: true };
446
+ }
447
+ async function updateIssueProjectStatus(input) {
448
+ const mutation = `
449
+ mutation RigUpdateProjectStatus($projectId: ID!, $itemId: ID!, $fieldId: ID!, $optionId: String!) {
450
+ updateProjectV2ItemFieldValue(input: {
451
+ projectId: $projectId,
452
+ itemId: $itemId,
453
+ fieldId: $fieldId,
454
+ value: { singleSelectOptionId: $optionId }
455
+ }) { projectV2Item { id } }
456
+ }
457
+ `;
458
+ await input.fetchGraphQL(mutation, {
459
+ projectId: input.projectId,
460
+ itemId: input.itemId,
461
+ fieldId: input.fieldId,
462
+ optionId: input.optionId
463
+ }, input.token);
464
+ }
465
+ function fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
466
+ const issue = runGh(bin, ["issue", "view", String(id), "--repo", repo, "--json", "id"], spawnFn, extraEnv, timeoutMs);
467
+ return projectString(issue.id) ?? projectString(issue.nodeId) ?? projectString(issue.node_id);
468
+ }
469
+ async function syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs) {
470
+ if (!projects?.enabled)
471
+ return;
472
+ const projectId = projectString(projects.projectId);
473
+ if (!projectId)
474
+ throw new Error("GitHub Projects status sync is enabled but projectId is missing.");
475
+ const lifecycleStatus = projectLifecycleStatusForTaskStatus(status);
476
+ if (!lifecycleStatus)
477
+ return;
478
+ const issueNodeId = fetchIssueNodeId(bin, repo, spawnFn, id, extraEnv, timeoutMs);
479
+ if (!issueNodeId)
480
+ throw new Error(`GitHub issue ${repo}#${id} did not expose a node id for Projects status sync.`);
481
+ const projectStatus = projectString(projects.statuses?.[lifecycleStatus]) ?? DEFAULT_PROJECT_STATUSES[lifecycleStatus];
482
+ const fetchGraphQL = ghGraphQLFetch(bin, spawnFn, extraEnv, timeoutMs);
483
+ const field = await resolveProjectStatusField({ projectId, token: "gh-cli", fetchGraphQL });
484
+ const option = field.options.find((candidate) => candidate.name.toLowerCase() === projectStatus.toLowerCase() || candidate.id === projectStatus);
485
+ if (!option)
486
+ throw new Error(`GitHub Project ${projectId} Status field does not contain option "${projectStatus}".`);
487
+ const item = await ensureIssueProjectItem({ projectId, issueNodeId, token: "gh-cli", fetchGraphQL });
488
+ await updateIssueProjectStatus({
489
+ projectId,
490
+ itemId: item.id,
491
+ fieldId: projectString(projects.statusFieldId) ?? field.id,
492
+ optionId: option.id,
493
+ token: "gh-cli",
494
+ fetchGraphQL
495
+ });
496
+ }
497
+ var TERMINAL_TASK_STATUSES = new Set(["closed", "completed", "merged", "cancelled", "resolved", "done"]);
498
+ function normalizeTaskStatusToken(status) {
499
+ return status?.trim().toLowerCase().replace(/[-\s]+/g, "_") ?? "";
500
+ }
501
+ function issueUpdatesMode(value) {
502
+ return value === "off" || value === "minimal" || value === "lifecycle" ? value : "lifecycle";
503
+ }
504
+ function isTerminalTaskStatus(status) {
505
+ return TERMINAL_TASK_STATUSES.has(normalizeTaskStatusToken(status));
506
+ }
507
+ function shouldWriteIssueUpdate(mode, status) {
508
+ if (mode === "off")
509
+ return false;
510
+ if (mode === "lifecycle")
511
+ return true;
512
+ return isTerminalTaskStatus(status);
513
+ }
514
+ function isRunningStatus(status) {
515
+ return normalizeTaskStatusToken(status) === "running";
516
+ }
517
+ function assignRunningIssue(bin, repo, spawnFn, id, assignee, extraEnv, timeoutMs) {
518
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-assignee", assignee?.trim() || "@me"], spawnFn, extraEnv, timeoutMs);
519
+ }
520
+ function statusLabelFor(status) {
521
+ switch (status) {
522
+ case "running":
523
+ case "in_progress":
524
+ return "in-progress";
525
+ case "blocked":
526
+ return "blocked";
527
+ case "ready":
528
+ return "ready";
529
+ case "under_review":
530
+ return "under-review";
531
+ case "failed":
532
+ return "failed";
533
+ case "cancelled":
534
+ return "cancelled";
535
+ case "ci_fixing":
536
+ return "under-review";
537
+ case "merging":
538
+ return "under-review";
539
+ case "needs_attention":
540
+ return "blocked";
541
+ case "closed":
542
+ case "completed":
543
+ case "open":
544
+ return null;
545
+ default:
546
+ throw new Error(`unsupported status: ${status}`);
547
+ }
548
+ }
549
+ function rigStatusLabelFor(status) {
550
+ switch (status) {
551
+ case "running":
552
+ case "in_progress":
553
+ return "rig:running";
554
+ case "under_review":
555
+ return "rig:pr-open";
556
+ case "closed":
557
+ case "completed":
558
+ return "rig:done";
559
+ case "ci_fixing":
560
+ return "rig:ci-fixing";
561
+ case "merging":
562
+ return "rig:merging";
563
+ case "needs_attention":
564
+ case "failed":
565
+ case "blocked":
566
+ return "rig:needs-attention";
567
+ case "ready":
568
+ case "cancelled":
569
+ case "open":
570
+ return null;
571
+ default:
572
+ return null;
573
+ }
574
+ }
575
+ async function applyIssueStatus(bin, repo, spawnFn, id, status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
576
+ const targetLabel = status === "closed" || status === "completed" ? null : statusLabelFor(status);
577
+ const targetRigLabel = rigStatusLabelFor(status);
578
+ const shouldSyncLifecycle = shouldWriteIssueUpdate(issueUpdates, status);
579
+ for (const l of [...STATUS_LABELS, ...RIG_STATUS_LABELS]) {
580
+ if (targetLabel !== null && l === targetLabel)
581
+ continue;
582
+ if (targetRigLabel !== null && l === targetRigLabel)
583
+ continue;
584
+ try {
585
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--remove-label", l], spawnFn, extraEnv, timeoutMs);
586
+ } catch {}
587
+ }
588
+ for (const label of [targetLabel, targetRigLabel].filter((value) => Boolean(value))) {
589
+ try {
590
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
591
+ } catch (error) {
592
+ const message = error instanceof Error ? error.message : String(error);
593
+ if (!/not found/i.test(message)) {
594
+ throw error;
595
+ }
596
+ ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
597
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, "--add-label", label], spawnFn, extraEnv, timeoutMs);
598
+ }
599
+ }
600
+ if (isRunningStatus(status)) {
601
+ assignRunningIssue(bin, repo, spawnFn, id, runningAssignee, extraEnv, timeoutMs);
602
+ if (shouldSyncLifecycle) {
603
+ upsertRigStickyComment(bin, repo, spawnFn, String(id), buildRigStickyStatusComment({
604
+ status: "running",
605
+ summary: "Rig run started."
606
+ }), extraEnv, timeoutMs);
607
+ }
608
+ }
609
+ if (shouldSyncLifecycle) {
610
+ await syncGitHubProjectStatus(bin, repo, spawnFn, id, status, projects, extraEnv, timeoutMs);
611
+ }
612
+ if (status === "closed" || status === "completed") {
613
+ runGhVoid(bin, ["issue", "close", String(id), "--repo", repo], spawnFn, extraEnv, timeoutMs);
614
+ }
615
+ }
616
+ function ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs) {
617
+ try {
618
+ runGhVoid(bin, [
619
+ "label",
620
+ "create",
621
+ label,
622
+ "--repo",
623
+ repo,
624
+ "--color",
625
+ "6f42c1",
626
+ "--description",
627
+ "Task status managed by Rig"
628
+ ], spawnFn, extraEnv, timeoutMs);
629
+ } catch (error) {
630
+ const message = error instanceof Error ? error.message : String(error);
631
+ if (!/already exists/i.test(message)) {
632
+ throw error;
633
+ }
634
+ }
635
+ }
636
+ function upsertRigStickyComment(bin, repo, spawnFn, id, body, extraEnv, timeoutMs) {
637
+ const comments = runGh(bin, ["api", `repos/${repo}/issues/${id}/comments`, "--paginate"], spawnFn, extraEnv, timeoutMs);
638
+ const existing = comments.find((comment) => typeof comment.body === "string" && comment.body.includes(RIG_STATUS_COMMENT_MARKER));
639
+ if (existing) {
640
+ runGhVoid(bin, ["api", "-X", "PATCH", `repos/${repo}/issues/comments/${existing.id}`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
641
+ return;
642
+ }
643
+ runGhVoid(bin, ["api", "-X", "POST", `repos/${repo}/issues/${id}/comments`, "-f", `body=${body}`], spawnFn, extraEnv, timeoutMs);
644
+ }
645
+ function notifyTaskChanged(onTaskChanged, repo, id, status) {
646
+ onTaskChanged?.({ repo, id, ...status ? { status } : {}, reason: "github-issue-updated" });
647
+ }
648
+ function fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) {
649
+ const issue = runGh(bin, [
650
+ "issue",
651
+ "view",
652
+ String(id),
653
+ "--repo",
654
+ repo,
655
+ "--json",
656
+ "body"
657
+ ], spawnFn, extraEnv, timeoutMs);
658
+ return typeof issue.body === "string" ? issue.body : undefined;
659
+ }
660
+ function applyLabels(bin, repo, spawnFn, id, labels, action, extraEnv, timeoutMs) {
661
+ for (const rawLabel of labels) {
662
+ const label = rawLabel.trim();
663
+ if (!label)
664
+ continue;
665
+ if (action === "--add-label") {
666
+ try {
667
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
668
+ } catch (error) {
669
+ const message = error instanceof Error ? error.message : String(error);
670
+ if (!/not found/i.test(message))
671
+ throw error;
672
+ ensureStatusLabel(bin, repo, spawnFn, label, extraEnv, timeoutMs);
673
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
674
+ }
675
+ continue;
676
+ }
677
+ try {
678
+ runGhVoid(bin, ["issue", "edit", String(id), "--repo", repo, action, label], spawnFn, extraEnv, timeoutMs);
679
+ } catch {}
680
+ }
681
+ }
682
+ async function applyIssueUpdate(bin, repo, spawnFn, id, update, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs) {
683
+ if (update.status) {
684
+ await applyIssueStatus(bin, repo, spawnFn, id, update.status, projects, runningAssignee, issueUpdates, extraEnv, timeoutMs);
685
+ }
686
+ if (update.comment?.trim() && shouldWriteIssueUpdate(issueUpdates, update.status)) {
687
+ if (isRigStickyStatusComment(update.comment)) {
688
+ upsertRigStickyComment(bin, repo, spawnFn, String(id), update.comment, extraEnv, timeoutMs);
689
+ } else {
690
+ runGhVoid(bin, ["issue", "comment", String(id), "--repo", repo, "--body", update.comment], spawnFn, extraEnv, timeoutMs);
691
+ }
692
+ }
693
+ const editArgs = ["issue", "edit", String(id), "--repo", repo];
694
+ if (update.title?.trim()) {
695
+ editArgs.push("--title", update.title.trim());
696
+ }
697
+ const nextBody = update.metadata ? updateRigOwnedMetadataBlock(update.body ?? fetchIssueBody(bin, repo, spawnFn, id, extraEnv, timeoutMs) ?? "", update.metadata) : update.body;
698
+ if (nextBody !== undefined) {
699
+ editArgs.push("--body", nextBody);
700
+ }
701
+ if (editArgs.length > 5) {
702
+ runGhVoid(bin, editArgs, spawnFn, extraEnv, timeoutMs);
703
+ }
704
+ }
705
+ function createGitHubIssuesTaskSource(opts) {
706
+ const bin = opts.ghBinary ?? "gh";
707
+ const state = opts.state ?? "open";
708
+ const repo = `${opts.owner}/${opts.repo}`;
709
+ const spawnFn = opts.spawn ?? spawnSync;
710
+ const timeoutMs = Math.max(1000, Math.trunc(opts.timeoutMs ?? DEFAULT_GH_TIMEOUT_MS));
711
+ const listLimit = Math.max(1, Math.trunc(opts.listLimit ?? DEFAULT_GITHUB_ISSUE_LIST_LIMIT));
712
+ const issueUpdates = issueUpdatesMode(opts.issueUpdates);
713
+ async function issueToTaskWithOptionalNativeDependencies(issue, env) {
714
+ if (!opts.useNativeDependencies)
715
+ return issueToTask(issue, repo);
716
+ const nativeDependencies = await readNativeDependenciesForIssue({
717
+ issue,
718
+ repo,
719
+ fetchGraphQL: ghGraphQLFetch(bin, spawnFn, env, timeoutMs)
720
+ });
721
+ return issueToTask(issue, repo, nativeDependencies);
722
+ }
723
+ return {
724
+ id: "std:github-issues",
725
+ kind: "github-issues",
726
+ async list() {
727
+ const labelArg = opts.labels && opts.labels.length > 0 ? ["--label", opts.labels.join(",")] : [];
728
+ const assigneeArg = opts.assignee?.trim() ? ["--assignee", opts.assignee.trim()] : [];
729
+ const args = [
730
+ "issue",
731
+ "list",
732
+ "--repo",
733
+ repo,
734
+ ...labelArg,
735
+ ...assigneeArg,
736
+ "--state",
737
+ state,
738
+ "--limit",
739
+ String(listLimit),
740
+ "--json",
741
+ "number,title,body,labels,state,url,assignees,id"
742
+ ];
743
+ const env = await resolveCredentialEnv(opts, "selected-repo");
744
+ const rawIssues = runGh(bin, args, spawnFn, env, timeoutMs);
745
+ if (rawIssues.length >= listLimit) {
746
+ 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.`);
747
+ }
748
+ const issues = rawIssues.filter((issue) => !issue.pull_request);
749
+ return Promise.all(issues.map((issue) => issueToTaskWithOptionalNativeDependencies(issue, env)));
750
+ },
751
+ async get(id) {
752
+ const env = await resolveCredentialEnv(opts, "selected-repo");
753
+ let issue;
754
+ try {
755
+ issue = runGh(bin, [
756
+ "issue",
757
+ "view",
758
+ String(id),
759
+ "--repo",
760
+ repo,
761
+ "--json",
762
+ "number,title,body,labels,state,url,assignees,id"
763
+ ], spawnFn, env, timeoutMs);
764
+ } catch (error) {
765
+ const detail = error instanceof Error ? error.message : String(error);
766
+ 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)) {
767
+ return;
768
+ }
769
+ throw new Error(`Failed to read task ${id} from GitHub repo ${repo}: ${detail}`);
770
+ }
771
+ return issueToTaskWithOptionalNativeDependencies(issue, env);
772
+ },
773
+ async updateStatus(id, status) {
774
+ const env = await resolveCredentialEnv(opts, "selected-repo");
775
+ await applyIssueStatus(bin, repo, spawnFn, id, status, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
776
+ notifyTaskChanged(opts.onTaskChanged, repo, id, status);
777
+ },
778
+ async updateTask(id, update) {
779
+ const env = await resolveCredentialEnv(opts, "selected-repo");
780
+ await applyIssueUpdate(bin, repo, spawnFn, id, update, opts.projects, opts.assignee, issueUpdates, env, timeoutMs);
781
+ notifyTaskChanged(opts.onTaskChanged, repo, id, update.status);
782
+ },
783
+ async addLabels(id, labels) {
784
+ const env = await resolveCredentialEnv(opts, "selected-repo");
785
+ applyLabels(bin, repo, spawnFn, id, labels, "--add-label", env, timeoutMs);
786
+ notifyTaskChanged(opts.onTaskChanged, repo, id);
787
+ },
788
+ async removeLabels(id, labels) {
789
+ const env = await resolveCredentialEnv(opts, "selected-repo");
790
+ applyLabels(bin, repo, spawnFn, id, labels, "--remove-label", env, timeoutMs);
791
+ notifyTaskChanged(opts.onTaskChanged, repo, id);
792
+ },
793
+ async createIssue(input) {
794
+ const env = await resolveCredentialEnv(opts, "selected-repo");
795
+ const body = input.body ?? "";
796
+ const args = [
797
+ "api",
798
+ "-X",
799
+ "POST",
800
+ `repos/${repo}/issues`,
801
+ "-f",
802
+ `title=${input.title}`,
803
+ "-f",
804
+ `body=${body}`,
805
+ ...(input.labels ?? []).flatMap((label) => ["-f", `labels[]=${label}`])
806
+ ];
807
+ const issue = runGh(bin, args, spawnFn, env, timeoutMs);
808
+ notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
809
+ return issueToTask({ ...issue, body: issue.body ?? body }, repo);
810
+ },
811
+ async create(input) {
812
+ const env = await resolveCredentialEnv(opts, "selected-repo");
813
+ const body = bodyForCreatedTask(input);
814
+ const args = [
815
+ "api",
816
+ "-X",
817
+ "POST",
818
+ `repos/${repo}/issues`,
819
+ "-f",
820
+ `title=${input.title}`,
821
+ "-f",
822
+ `body=${body}`,
823
+ "-f",
824
+ "labels[]=rig:generated"
825
+ ];
826
+ const issue = runGh(bin, args, spawnFn, env, timeoutMs);
827
+ notifyTaskChanged(opts.onTaskChanged, repo, String(issue.number));
828
+ return issueToTask({ ...issue, body: issue.body ?? body }, repo);
829
+ },
830
+ async getIssueBody(id) {
831
+ const env = await resolveCredentialEnv(opts, "selected-repo");
832
+ return fetchIssueBody(bin, repo, spawnFn, id, env, timeoutMs);
833
+ }
834
+ };
835
+ }
836
+ export {
837
+ updateRigOwnedMetadataBlock,
838
+ createGitHubIssuesTaskSource,
839
+ buildRigStickyStatusComment,
840
+ RIG_STATUS_COMMENT_MARKER,
841
+ RIG_METADATA_START,
842
+ RIG_METADATA_END
843
+ };