@h-rig/task-sources-plugin 0.0.6-alpha.157 → 0.0.6-alpha.158

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.
Files changed (51) hide show
  1. package/dist/src/control-plane/native/github-token-env.d.ts +3 -0
  2. package/dist/src/control-plane/native/github-token-env.js +26 -0
  3. package/dist/src/control-plane/native/native-git.d.ts +18 -0
  4. package/dist/src/control-plane/native/native-git.js +291 -0
  5. package/dist/src/control-plane/native/runtime-binary-build.d.ts +9 -0
  6. package/dist/src/control-plane/native/runtime-binary-build.js +107 -0
  7. package/dist/src/control-plane/native/task-ops.d.ts +52 -0
  8. package/dist/src/control-plane/native/task-ops.js +3192 -0
  9. package/dist/src/control-plane/native/task-state.d.ts +30 -0
  10. package/dist/src/control-plane/native/task-state.js +944 -0
  11. package/dist/src/control-plane/native/utils.d.ts +7 -0
  12. package/dist/src/control-plane/native/utils.js +110 -0
  13. package/dist/src/control-plane/native/validator-binaries.d.ts +3 -0
  14. package/dist/src/control-plane/native/validator-binaries.js +175 -0
  15. package/dist/src/control-plane/native/validator.d.ts +44 -0
  16. package/dist/src/control-plane/native/validator.js +979 -0
  17. package/dist/src/control-plane/state-sync/index.d.ts +4 -0
  18. package/dist/src/control-plane/state-sync/index.js +1205 -0
  19. package/dist/src/control-plane/state-sync/native-git.d.ts +1 -0
  20. package/dist/src/control-plane/state-sync/native-git.js +281 -0
  21. package/dist/src/control-plane/state-sync/read.d.ts +46 -0
  22. package/dist/src/control-plane/state-sync/read.js +564 -0
  23. package/dist/src/control-plane/state-sync/reconcile.d.ts +28 -0
  24. package/dist/src/control-plane/state-sync/reconcile.js +260 -0
  25. package/dist/src/control-plane/state-sync/repo.d.ts +1 -0
  26. package/dist/src/control-plane/state-sync/repo.js +42 -0
  27. package/dist/src/control-plane/state-sync/types.d.ts +28 -0
  28. package/dist/src/control-plane/state-sync/types.js +111 -0
  29. package/dist/src/control-plane/state-sync/write.d.ts +83 -0
  30. package/dist/src/control-plane/state-sync/write.js +1165 -0
  31. package/dist/src/control-plane/task-data-service.d.ts +17 -0
  32. package/dist/src/control-plane/task-data-service.js +3653 -0
  33. package/dist/src/control-plane/task-fields.d.ts +1 -0
  34. package/dist/src/control-plane/task-fields.js +6 -0
  35. package/dist/src/control-plane/task-io-service.d.ts +6 -0
  36. package/dist/src/control-plane/task-io-service.js +108 -0
  37. package/dist/src/control-plane/task-source-bootstrap.d.ts +1 -0
  38. package/dist/src/control-plane/task-source-bootstrap.js +6 -0
  39. package/dist/src/control-plane/task-source.d.ts +2 -0
  40. package/dist/src/control-plane/task-source.js +6 -0
  41. package/dist/src/control-plane/tasks/legacy-task-config-source.d.ts +19 -0
  42. package/dist/src/control-plane/tasks/legacy-task-config-source.js +124 -0
  43. package/dist/src/control-plane/tasks/plugin-task-source.d.ts +30 -0
  44. package/dist/src/control-plane/tasks/plugin-task-source.js +99 -0
  45. package/dist/src/control-plane/tasks/source-aware-task-config-source.d.ts +28 -0
  46. package/dist/src/control-plane/tasks/source-aware-task-config-source.js +642 -0
  47. package/dist/src/control-plane/tasks/source-lifecycle.d.ts +56 -0
  48. package/dist/src/control-plane/tasks/source-lifecycle.js +834 -0
  49. package/dist/src/plugin.d.ts +1 -1
  50. package/dist/src/plugin.js +3927 -64
  51. package/package.json +57 -4
@@ -0,0 +1,564 @@
1
+ // @bun
2
+ // packages/task-sources-plugin/src/control-plane/state-sync/read.ts
3
+ import { existsSync as existsSync3, readFileSync as readFileSync2 } from "fs";
4
+ import { resolve as resolve3 } from "path";
5
+
6
+ // packages/task-sources-plugin/src/control-plane/native/native-git.ts
7
+ import { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "fs";
8
+ import { tmpdir } from "os";
9
+ import { dirname, isAbsolute, resolve } from "path";
10
+ import { createHash } from "crypto";
11
+ var taskSourcesGitNativeOutputDir = resolve(tmpdir(), "rig-task-sources-native");
12
+ var taskSourcesGitNativeOutputPath = resolve(taskSourcesGitNativeOutputDir, `rig-git-${process.platform}-${process.arch}${process.platform === "win32" ? ".exe" : ""}`);
13
+ var trackerCommandUsageProbe = "usage: rig-git fetch-ref <repo-path> <remote> <branch>";
14
+ function nativeFetchRef(repoPath, remote, branch) {
15
+ return requireGitNativeString("fetch-ref", [repoPath, remote, branch]);
16
+ }
17
+ function nativeReadBlobAtRef(repoPath, ref, path) {
18
+ const requestDir = resolve(taskSourcesGitNativeOutputDir, "reads", `${Date.now()}-${Math.random().toString(36).slice(2, 10)}`);
19
+ mkdirSync(requestDir, { recursive: true });
20
+ const outputPath = resolve(requestDir, "blob.txt");
21
+ try {
22
+ requireGitNative("read-blob-at-ref", [repoPath, ref, path, outputPath]);
23
+ return readFileSync(outputPath, "utf8");
24
+ } finally {
25
+ rmSync(requestDir, { recursive: true, force: true });
26
+ }
27
+ }
28
+ function runGitNative(command, args) {
29
+ if (process.env.RIG_DISABLE_ZIG_NATIVE === "1") {
30
+ return { ok: false, error: "rig-git native disabled" };
31
+ }
32
+ let binaryPath;
33
+ try {
34
+ binaryPath = resolveGitBinaryPath() ?? ensureRigGitBinaryPathSync(preferredGitBinaryOutputPath());
35
+ } catch (error) {
36
+ const message = error instanceof Error ? error.message : String(error);
37
+ return { ok: false, error: message.includes("rig-git.zig source file not found") ? "rig-git binary not found" : message };
38
+ }
39
+ try {
40
+ const proc = Bun.spawnSync([binaryPath, command, ...args], {
41
+ stdout: "pipe",
42
+ stderr: "pipe",
43
+ env: gitNativeEnv()
44
+ });
45
+ if (proc.exitCode !== 0) {
46
+ const stdoutText = proc.stdout.toString().trim();
47
+ if (stdoutText) {
48
+ try {
49
+ const parsed = JSON.parse(stdoutText);
50
+ if (!parsed.ok) {
51
+ return parsed;
52
+ }
53
+ } catch {}
54
+ }
55
+ const error = proc.stderr.toString().trim() || `exit code ${proc.exitCode}`;
56
+ return { ok: false, error };
57
+ }
58
+ return JSON.parse(proc.stdout.toString().trim());
59
+ } catch (error) {
60
+ return { ok: false, error: String(error) };
61
+ }
62
+ }
63
+ function requireGitNative(command, args) {
64
+ const result = runGitNative(command, args);
65
+ if (!result.ok) {
66
+ throw new Error(`rig-git ${command} failed: ${result.error}`);
67
+ }
68
+ return result;
69
+ }
70
+ function requireGitNativeString(command, args) {
71
+ const result = requireGitNative(command, args);
72
+ if ("value" in result && typeof result.value === "string") {
73
+ return result.value;
74
+ }
75
+ throw new Error(`rig-git ${command} returned an unexpected result payload`);
76
+ }
77
+ function gitNativeEnv() {
78
+ const env = { ...process.env };
79
+ const token = env.GITHUB_TOKEN?.trim() || env.GH_TOKEN?.trim() || env.RIG_GITHUB_TOKEN?.trim() || "";
80
+ if (token) {
81
+ env.RIG_GITHUB_TOKEN = env.RIG_GITHUB_TOKEN || token;
82
+ env.GITHUB_TOKEN = env.GITHUB_TOKEN || token;
83
+ env.GH_TOKEN = env.GH_TOKEN || token;
84
+ env.GIT_TERMINAL_PROMPT = "0";
85
+ env.GIT_CONFIG_COUNT = "2";
86
+ env.GIT_CONFIG_KEY_0 = "credential.helper";
87
+ env.GIT_CONFIG_VALUE_0 = "";
88
+ env.GIT_CONFIG_KEY_1 = "credential.helper";
89
+ env.GIT_CONFIG_VALUE_1 = '!f() { test "$1" = get || exit 0; token="${GITHUB_TOKEN:-${GH_TOKEN:-${RIG_GITHUB_TOKEN:-}}}"; test -n "$token" || exit 0; echo username=x-access-token; echo password="$token"; }; f';
90
+ }
91
+ return env;
92
+ }
93
+ function runtimeRigGitFileName() {
94
+ return `rig-git${process.platform === "win32" ? ".exe" : ""}`;
95
+ }
96
+ function preferredGitBinaryOutputPath() {
97
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
98
+ return explicit || taskSourcesGitNativeOutputPath;
99
+ }
100
+ function resolveGitBinaryPath() {
101
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
102
+ if (explicit && existsSync(explicit)) {
103
+ return explicit;
104
+ }
105
+ if (explicit) {
106
+ return null;
107
+ }
108
+ for (const candidate of rigGitBinaryCandidates()) {
109
+ if (candidate && existsSync(candidate)) {
110
+ return candidate;
111
+ }
112
+ }
113
+ return null;
114
+ }
115
+ function ensureRigGitBinaryPathSync(outputPath = taskSourcesGitNativeOutputPath) {
116
+ const explicit = process.env.RIG_NATIVE_GIT_BIN?.trim() || "";
117
+ if (explicit && existsSync(explicit)) {
118
+ return explicit;
119
+ }
120
+ const sourcePath = resolveGitSourcePath();
121
+ if (!sourcePath) {
122
+ const binaryPath = resolveGitBinaryPath();
123
+ if (binaryPath) {
124
+ return binaryPath;
125
+ }
126
+ throw new Error("rig-git.zig source file not found.");
127
+ }
128
+ const zigBinary = Bun.which("zig");
129
+ if (!zigBinary) {
130
+ throw new Error("zig is required to build native Rig git tools.");
131
+ }
132
+ mkdirSync(dirname(outputPath), { recursive: true });
133
+ const buildKey = JSON.stringify({
134
+ version: 1,
135
+ zigBinary,
136
+ platform: process.platform,
137
+ arch: process.arch,
138
+ sourcePath,
139
+ sourceDigest: createHash("sha256").update(readFileSync(sourcePath)).digest("hex")
140
+ });
141
+ const manifestPath = `${outputPath}.build-manifest.json`;
142
+ if (nativeBuildIsFresh(outputPath, manifestPath, buildKey)) {
143
+ chmodSync(outputPath, 493);
144
+ return outputPath;
145
+ }
146
+ const tempOutputPath = resolve(dirname(outputPath), `.rig-git-${process.pid}-${Date.now()}-${Math.random().toString(36).slice(2)}${process.platform === "win32" ? ".exe" : ""}`);
147
+ const build = Bun.spawnSync([
148
+ zigBinary,
149
+ "build-exe",
150
+ sourcePath,
151
+ "-O",
152
+ "ReleaseFast",
153
+ `-femit-bin=${tempOutputPath}`
154
+ ], {
155
+ cwd: dirname(sourcePath),
156
+ stdout: "pipe",
157
+ stderr: "pipe"
158
+ });
159
+ if (build.exitCode !== 0 || !existsSync(tempOutputPath)) {
160
+ const details = [build.stderr.toString().trim(), build.stdout.toString().trim()].filter(Boolean).join(`
161
+ `);
162
+ throw new Error(`Failed to build native Rig git tools: ${details || `zig exited with code ${build.exitCode}`}`);
163
+ }
164
+ chmodSync(tempOutputPath, 493);
165
+ renameSync(tempOutputPath, outputPath);
166
+ if (!binarySupportsTrackerCommands(outputPath)) {
167
+ rmSync(outputPath, { force: true });
168
+ throw new Error("Failed to build native Rig git tools: tracker command probe failed");
169
+ }
170
+ writeFileSync(manifestPath, `${JSON.stringify({ version: 1, buildKey }, null, 2)}
171
+ `, "utf8");
172
+ return outputPath;
173
+ }
174
+ function nativeBuildIsFresh(outputPath, manifestPath, buildKey) {
175
+ if (!existsSync(outputPath) || !existsSync(manifestPath)) {
176
+ return false;
177
+ }
178
+ try {
179
+ const manifest = JSON.parse(readFileSync(manifestPath, "utf8"));
180
+ return manifest.version === 1 && manifest.buildKey === buildKey && binarySupportsTrackerCommands(outputPath);
181
+ } catch {
182
+ return false;
183
+ }
184
+ }
185
+ function binarySupportsTrackerCommands(binaryPath) {
186
+ try {
187
+ const probe = Bun.spawnSync([binaryPath, "fetch-ref", "."], {
188
+ stdout: "pipe",
189
+ stderr: "pipe"
190
+ });
191
+ const stdout = probe.stdout.toString().trim();
192
+ const stderr = probe.stderr.toString().trim();
193
+ if (stdout.includes('"error":"unknown command"')) {
194
+ return false;
195
+ }
196
+ return probe.exitCode === 2 && stderr.includes(trackerCommandUsageProbe);
197
+ } catch {
198
+ return false;
199
+ }
200
+ }
201
+ function resolveGitSourcePath() {
202
+ for (const candidate of rigGitSourceCandidates()) {
203
+ if (candidate && existsSync(candidate)) {
204
+ return candidate;
205
+ }
206
+ }
207
+ return null;
208
+ }
209
+ function rigGitSourceCandidates() {
210
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
211
+ const cwd = process.cwd()?.trim() || "";
212
+ const projectRoot = process.env.PROJECT_RIG_ROOT?.trim() || "";
213
+ const hostProjectRoot = process.env.RIG_HOST_PROJECT_ROOT?.trim() || "";
214
+ return [...new Set([
215
+ process.env.RIG_NATIVE_GIT_SOURCE?.trim() || "",
216
+ resolve(import.meta.dir, "../../../native/rig-git.zig"),
217
+ projectRoot ? resolve(projectRoot, "packages/task-sources-plugin/native/rig-git.zig") : "",
218
+ projectRoot ? resolve(projectRoot, "packages/isolation-plugin/native/rig-git.zig") : "",
219
+ projectRoot ? resolve(projectRoot, "packages/shared/native/rig-git.zig") : "",
220
+ hostProjectRoot ? resolve(hostProjectRoot, "packages/task-sources-plugin/native/rig-git.zig") : "",
221
+ hostProjectRoot ? resolve(hostProjectRoot, "packages/isolation-plugin/native/rig-git.zig") : "",
222
+ hostProjectRoot ? resolve(hostProjectRoot, "packages/shared/native/rig-git.zig") : "",
223
+ cwd ? resolve(cwd, "packages/task-sources-plugin/native/rig-git.zig") : "",
224
+ cwd ? resolve(cwd, "packages/isolation-plugin/native/rig-git.zig") : "",
225
+ cwd ? resolve(cwd, "packages/shared/native/rig-git.zig") : "",
226
+ execDir ? resolve(execDir, "..", "native", "rig-git.zig") : ""
227
+ ].filter(Boolean))];
228
+ }
229
+ function rigGitBinaryCandidates() {
230
+ const execDir = process.execPath?.trim() ? dirname(process.execPath.trim()) : "";
231
+ const fileName = runtimeRigGitFileName();
232
+ return [...new Set([
233
+ ...nativePackageBinaryCandidates(import.meta.dir, fileName),
234
+ execDir ? resolve(execDir, fileName) : "",
235
+ execDir ? resolve(execDir, "..", fileName) : "",
236
+ execDir ? resolve(execDir, "..", "bin", fileName) : "",
237
+ taskSourcesGitNativeOutputPath
238
+ ].filter(Boolean))];
239
+ }
240
+ function nativePackageBinaryCandidates(fromDir, fileName) {
241
+ const candidates = [];
242
+ let cursor = resolve(fromDir);
243
+ for (let index = 0;index < 8; index += 1) {
244
+ candidates.push(resolve(cursor, "native", `${process.platform}-${process.arch}`, fileName), resolve(cursor, "native", `${process.platform}-${process.arch}`, "bin", fileName), resolve(cursor, "native", fileName), resolve(cursor, "native", "bin", fileName));
245
+ const parent = dirname(cursor);
246
+ if (parent === cursor)
247
+ break;
248
+ cursor = parent;
249
+ }
250
+ return candidates;
251
+ }
252
+ // packages/task-sources-plugin/src/control-plane/native/utils.ts
253
+ import { getScopeRules } from "@rig/core/scope-rules";
254
+ import { unique } from "@rig/core/exec";
255
+ import {
256
+ runCapture,
257
+ runCaptureAsync,
258
+ runInherit,
259
+ getValidationTimeoutMs,
260
+ readJsonFile,
261
+ nowIso,
262
+ unique as unique2,
263
+ fileLines
264
+ } from "@rig/core/exec";
265
+ import { resolveCheckoutRoot } from "@rig/core/checkout-root";
266
+ import { resolveHarnessPaths } from "@rig/core/harness-paths";
267
+ var scopeRegexCache = new Map;
268
+
269
+ // packages/task-sources-plugin/src/control-plane/state-sync/read.ts
270
+ import { RUNTIME_CONTEXT_ENV } from "@rig/core/runtime-context";
271
+
272
+ // packages/task-sources-plugin/src/control-plane/state-sync/repo.ts
273
+ import { existsSync as existsSync2 } from "fs";
274
+ import { resolve as resolve2 } from "path";
275
+ import { MANAGED_REPO_SERVICE_CAPABILITY } from "@rig/contracts";
276
+ import { defineCapability } from "@rig/core/capability";
277
+ import { getInstalledCapability } from "@rig/core/capability-loaders";
278
+ function resolveTrackerRepoPath(projectRoot) {
279
+ const monorepoRoot = resolveCheckoutRoot(projectRoot);
280
+ const managedRepos = getInstalledCapability(defineCapability(MANAGED_REPO_SERVICE_CAPABILITY));
281
+ if (managedRepos) {
282
+ try {
283
+ const layout = managedRepos.resolveMonorepoRepoLayout(projectRoot);
284
+ if (existsSync2(resolve2(layout.mirrorRoot, "HEAD"))) {
285
+ return layout.mirrorRoot;
286
+ }
287
+ } catch {}
288
+ }
289
+ return monorepoRoot;
290
+ }
291
+
292
+ // packages/task-sources-plugin/src/control-plane/state-sync/types.ts
293
+ var SUPPORTED_TASK_STATE_SCHEMA_VERSION = 1;
294
+ var CANONICAL_TASK_LIFECYCLE_STATUSES = new Set([
295
+ "draft",
296
+ "open",
297
+ "ready",
298
+ "queued",
299
+ "in_progress",
300
+ "under_review",
301
+ "blocked",
302
+ "completed",
303
+ "cancelled"
304
+ ]);
305
+ function normalizeTaskLifecycleStatus(status) {
306
+ switch (status) {
307
+ case "draft":
308
+ case "open":
309
+ case "ready":
310
+ case "queued":
311
+ case "in_progress":
312
+ case "under_review":
313
+ case "blocked":
314
+ case "completed":
315
+ case "cancelled":
316
+ return status;
317
+ case "closed":
318
+ return "completed";
319
+ case "running":
320
+ return "in_progress";
321
+ case "failed":
322
+ return "ready";
323
+ default:
324
+ return null;
325
+ }
326
+ }
327
+ function normalizeTaskStateMetadataStatus(status) {
328
+ if (CANONICAL_TASK_LIFECYCLE_STATUSES.has(status)) {
329
+ return status;
330
+ }
331
+ switch (status) {
332
+ case "closed":
333
+ return "completed";
334
+ case "running":
335
+ return "in_progress";
336
+ case "failed":
337
+ return "ready";
338
+ default:
339
+ return;
340
+ }
341
+ }
342
+ function canonicalizeTaskStateMetadata(raw) {
343
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
344
+ return null;
345
+ }
346
+ const metadata = raw;
347
+ const claimId = typeof metadata.claimId === "string" && metadata.claimId.length > 0 ? metadata.claimId : undefined;
348
+ const status = normalizeTaskStateMetadataStatus(metadata.status);
349
+ if (!status) {
350
+ return null;
351
+ }
352
+ return {
353
+ ...claimId ? { claimId } : {},
354
+ status,
355
+ ...typeof metadata.ownerId === "string" && metadata.ownerId.length > 0 ? { ownerId: metadata.ownerId } : {},
356
+ ...typeof metadata.claimedAt === "string" && metadata.claimedAt.length > 0 ? { claimedAt: metadata.claimedAt } : {},
357
+ ...typeof metadata.lastEvidenceAt === "string" && metadata.lastEvidenceAt.length > 0 ? { lastEvidenceAt: metadata.lastEvidenceAt } : {},
358
+ ...typeof metadata.runId === "string" && metadata.runId.length > 0 ? { runId: metadata.runId } : {},
359
+ ...typeof metadata.branchName === "string" && metadata.branchName.length > 0 ? { branchName: metadata.branchName } : {},
360
+ ...typeof metadata.prNumber === "number" ? { prNumber: metadata.prNumber } : {},
361
+ ...typeof metadata.prUrl === "string" && metadata.prUrl.length > 0 ? { prUrl: metadata.prUrl } : {},
362
+ ...typeof metadata.reviewState === "string" && metadata.reviewState.length > 0 ? { reviewState: metadata.reviewState } : {},
363
+ ...typeof metadata.blockerReason === "string" && metadata.blockerReason.length > 0 ? { blockerReason: metadata.blockerReason } : {},
364
+ ...typeof metadata.sourceCommit === "string" && metadata.sourceCommit.length > 0 ? { sourceCommit: metadata.sourceCommit } : {}
365
+ };
366
+ }
367
+ function readTaskStateMetadataEnvelope(raw) {
368
+ if (!raw || typeof raw !== "object") {
369
+ return { schemaVersion: SUPPORTED_TASK_STATE_SCHEMA_VERSION, supported: true, baseTrackerCommit: null, tasks: {} };
370
+ }
371
+ const envelope = raw;
372
+ const schemaVersion = typeof envelope.schemaVersion === "number" ? envelope.schemaVersion : SUPPORTED_TASK_STATE_SCHEMA_VERSION;
373
+ if (schemaVersion !== SUPPORTED_TASK_STATE_SCHEMA_VERSION) {
374
+ return { schemaVersion, supported: false, baseTrackerCommit: null, tasks: {} };
375
+ }
376
+ const rawTasks = envelope.tasks && typeof envelope.tasks === "object" && !Array.isArray(envelope.tasks) ? envelope.tasks : {};
377
+ const tasks = Object.fromEntries(Object.entries(rawTasks).map(([taskId, metadata]) => [taskId, canonicalizeTaskStateMetadata(metadata)]).filter((entry) => entry[1] != null));
378
+ return {
379
+ schemaVersion,
380
+ supported: true,
381
+ baseTrackerCommit: typeof envelope.baseTrackerCommit === "string" && envelope.baseTrackerCommit.length > 0 ? envelope.baseTrackerCommit : null,
382
+ tasks
383
+ };
384
+ }
385
+
386
+ // packages/task-sources-plugin/src/control-plane/state-sync/read.ts
387
+ var DEFAULT_READ_DEPS = {
388
+ fetchRef: nativeFetchRef,
389
+ readBlobAtRef: nativeReadBlobAtRef,
390
+ exists: existsSync3,
391
+ readFile: (path) => readFileSync2(path, "utf8")
392
+ };
393
+ function parseIssueStatus(rawStatus) {
394
+ const normalized = normalizeTaskLifecycleStatus(rawStatus);
395
+ return normalized ?? "unknown";
396
+ }
397
+ function parseIssueDependencies(raw) {
398
+ if (!Array.isArray(raw)) {
399
+ return [];
400
+ }
401
+ return raw.filter((entry) => !!entry && typeof entry === "object" && !Array.isArray(entry)).map((entry) => ({
402
+ issueId: typeof entry.issue_id === "string" && entry.issue_id.trim() ? entry.issue_id.trim() : null,
403
+ dependsOnId: typeof entry.depends_on_id === "string" && entry.depends_on_id.trim() ? entry.depends_on_id.trim() : null,
404
+ id: typeof entry.id === "string" && entry.id.trim() ? entry.id.trim() : null,
405
+ type: typeof entry.type === "string" && entry.type.trim() ? entry.type.trim() : null
406
+ }));
407
+ }
408
+ function dependencyTargetId(dependency) {
409
+ for (const candidate of [dependency.dependsOnId, dependency.id ?? null, dependency.issueId]) {
410
+ if (typeof candidate === "string" && candidate.trim()) {
411
+ return candidate.trim();
412
+ }
413
+ }
414
+ return null;
415
+ }
416
+ function parseIssuesJsonl(raw) {
417
+ const issues = [];
418
+ for (const line of raw.split(/\r?\n/)) {
419
+ const trimmed = line.trim();
420
+ if (!trimmed) {
421
+ continue;
422
+ }
423
+ try {
424
+ const record = JSON.parse(trimmed);
425
+ const id = typeof record.id === "string" && record.id.trim() ? record.id.trim() : "";
426
+ if (!id) {
427
+ continue;
428
+ }
429
+ const rawStatus = typeof record.status === "string" && record.status.trim() ? record.status.trim() : null;
430
+ issues.push({
431
+ id,
432
+ title: typeof record.title === "string" && record.title.trim() ? record.title.trim() : null,
433
+ description: typeof record.description === "string" && record.description.trim() ? record.description.trim() : null,
434
+ acceptanceCriteria: typeof record.acceptance_criteria === "string" && record.acceptance_criteria.trim() ? record.acceptance_criteria.trim() : typeof record.acceptanceCriteria === "string" && record.acceptanceCriteria.trim() ? record.acceptanceCriteria.trim() : null,
435
+ issueType: typeof record.issue_type === "string" && record.issue_type.trim() ? record.issue_type.trim() : null,
436
+ status: parseIssueStatus(rawStatus),
437
+ rawStatus,
438
+ priority: typeof record.priority === "number" ? record.priority : null,
439
+ dependencies: parseIssueDependencies(record.dependencies)
440
+ });
441
+ } catch {}
442
+ }
443
+ return issues;
444
+ }
445
+ function parseTaskStateEnvelope(raw) {
446
+ if (!raw || !raw.trim()) {
447
+ return readTaskStateMetadataEnvelope(null);
448
+ }
449
+ try {
450
+ return readTaskStateMetadataEnvelope(JSON.parse(raw));
451
+ } catch {
452
+ return readTaskStateMetadataEnvelope(null);
453
+ }
454
+ }
455
+ function readRemoteBlobAtRef(deps, repoPath, ref, path, options) {
456
+ try {
457
+ return deps.readBlobAtRef(repoPath, ref, path);
458
+ } catch (error) {
459
+ if (options.required) {
460
+ throw error;
461
+ }
462
+ return null;
463
+ }
464
+ }
465
+ function shouldPreferLocalTrackerState(options) {
466
+ if (!options.allowLocalFallback) {
467
+ return false;
468
+ }
469
+ const runtimeWorkspace = process.env.RIG_TASK_WORKSPACE?.trim();
470
+ if (!runtimeWorkspace) {
471
+ return false;
472
+ }
473
+ if (process.env.RIG_TASK_RUNTIME_ID?.trim()) {
474
+ return true;
475
+ }
476
+ const runtimeContextPath = process.env[RUNTIME_CONTEXT_ENV]?.trim();
477
+ if (runtimeContextPath) {
478
+ return true;
479
+ }
480
+ return existsSync3(resolve3(runtimeWorkspace, ".rig", "runtime-context.json"));
481
+ }
482
+ function readLocalTrackerState(projectRoot, deps) {
483
+ const monorepoRoot = resolveCheckoutRoot(projectRoot);
484
+ const issuesPath = resolve3(monorepoRoot, ".beads", "issues.jsonl");
485
+ const taskStatePath = resolve3(monorepoRoot, ".beads", "task-state.json");
486
+ return projectSyncedTrackerSnapshot({
487
+ source: "local",
488
+ issuesBaseOid: null,
489
+ issuesText: deps.exists(issuesPath) ? deps.readFile(issuesPath) : "",
490
+ taskStateBaseOid: null,
491
+ taskStateText: deps.exists(taskStatePath) ? deps.readFile(taskStatePath) : null
492
+ });
493
+ }
494
+ function projectSyncedTrackerSnapshot(input) {
495
+ if (input.source === "remote" && input.issuesBaseOid && input.taskStateBaseOid && input.issuesBaseOid !== input.taskStateBaseOid) {
496
+ throw new Error("Remote tracker files must be read from the same fetched base.");
497
+ }
498
+ return {
499
+ source: input.source,
500
+ baseOid: input.issuesBaseOid ?? input.taskStateBaseOid ?? null,
501
+ issues: parseIssuesJsonl(input.issuesText),
502
+ taskState: parseTaskStateEnvelope(input.taskStateText)
503
+ };
504
+ }
505
+ function readSyncedTrackerState(projectRoot, deps = {}, options = {}) {
506
+ const readDeps = { ...DEFAULT_READ_DEPS, ...deps };
507
+ const trackerRepoPath = resolveTrackerRepoPath(projectRoot);
508
+ if (shouldPreferLocalTrackerState(options)) {
509
+ return readLocalTrackerState(projectRoot, readDeps);
510
+ }
511
+ try {
512
+ const baseOid = readDeps.fetchRef(trackerRepoPath, "origin", "main");
513
+ return projectSyncedTrackerSnapshot({
514
+ source: "remote",
515
+ issuesBaseOid: baseOid,
516
+ issuesText: readRemoteBlobAtRef(readDeps, trackerRepoPath, baseOid, ".beads/issues.jsonl", {
517
+ required: true
518
+ }) ?? "",
519
+ taskStateBaseOid: baseOid,
520
+ taskStateText: readRemoteBlobAtRef(readDeps, trackerRepoPath, baseOid, ".beads/task-state.json", {
521
+ required: false
522
+ })
523
+ });
524
+ } catch (error) {
525
+ if (!options.allowLocalFallback) {
526
+ throw error;
527
+ }
528
+ return readLocalTrackerState(projectRoot, readDeps);
529
+ }
530
+ }
531
+ function listReadyTaskIdsFromTracker(snapshot) {
532
+ const tasks = snapshot.issues.filter((issue) => issue.issueType === "task");
533
+ const taskById = new Map(tasks.map((issue) => [issue.id, issue]));
534
+ const readyTaskIds = [];
535
+ for (const issue of tasks) {
536
+ if (issue.status === "ready") {
537
+ readyTaskIds.push(issue.id);
538
+ continue;
539
+ }
540
+ if (issue.status !== "open") {
541
+ continue;
542
+ }
543
+ const hasOpenBlocker = issue.dependencies.some((dependency) => {
544
+ if (dependency.type === "parent-child") {
545
+ return false;
546
+ }
547
+ const targetTaskId = dependencyTargetId(dependency);
548
+ if (!targetTaskId) {
549
+ return false;
550
+ }
551
+ const dependencyStatus = taskById.get(targetTaskId)?.status ?? "unknown";
552
+ return dependencyStatus !== "completed" && dependencyStatus !== "cancelled";
553
+ });
554
+ if (!hasOpenBlocker) {
555
+ readyTaskIds.push(issue.id);
556
+ }
557
+ }
558
+ return readyTaskIds;
559
+ }
560
+ export {
561
+ readSyncedTrackerState,
562
+ projectSyncedTrackerSnapshot,
563
+ listReadyTaskIdsFromTracker
564
+ };
@@ -0,0 +1,28 @@
1
+ import { type CanonicalTaskLifecycleStatus, type TaskStateMetadata } from "./types";
2
+ export type TrackerPullRequestEvidence = {
3
+ branchName?: string | null;
4
+ prNumber?: number | null;
5
+ prUrl?: string | null;
6
+ isOpen?: boolean;
7
+ isMerged?: boolean;
8
+ reviewState?: string | null;
9
+ };
10
+ export type TrackerReconcileEvidence = {
11
+ now?: string;
12
+ closeoutPassed?: boolean;
13
+ pr?: TrackerPullRequestEvidence | null;
14
+ activeOwnerIds?: string[];
15
+ };
16
+ export type TaskReconciliationProjection = {
17
+ valid: boolean;
18
+ reasons: string[];
19
+ isStale: boolean;
20
+ wouldReconcileTo: CanonicalTaskLifecycleStatus | null;
21
+ nextMetadata: TaskStateMetadata | null;
22
+ };
23
+ export declare function isTaskClaimStale(metadata: TaskStateMetadata | null, nowIso: string): boolean;
24
+ export declare function projectTaskReconciliation(input: {
25
+ lifecycleStatus: CanonicalTaskLifecycleStatus;
26
+ metadata: TaskStateMetadata | null;
27
+ evidence?: TrackerReconcileEvidence;
28
+ }): TaskReconciliationProjection;