@alvarolorentedev/opencode-taskfeed 0.0.0-stage → 0.1.0-alpha.1

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 (58) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +431 -2
  3. package/docs/architecture.md +123 -0
  4. package/docs/configuration.md +123 -0
  5. package/docs/development.md +312 -0
  6. package/docs/integrations.md +84 -0
  7. package/docs/operations.md +136 -0
  8. package/docs/releases/v0.1.0-alpha.1.md +164 -0
  9. package/docs/security.md +120 -0
  10. package/examples/README.md +7 -0
  11. package/examples/approvals/README.md +27 -0
  12. package/examples/flowgraph/config.yaml +28 -0
  13. package/examples/flowgraph/opencode.jsonc +14 -0
  14. package/examples/headless/README.md +25 -0
  15. package/examples/headless/config.yaml +21 -0
  16. package/examples/native-agent/config.yaml +31 -0
  17. package/examples/native-agent/opencode.jsonc +10 -0
  18. package/examples/playground/README.md +61 -0
  19. package/examples/playground/config.yaml +40 -0
  20. package/examples/playground/opencode.jsonc +5 -0
  21. package/package.json +89 -4
  22. package/src/config/load.ts +122 -0
  23. package/src/config/repository.ts +72 -0
  24. package/src/config/schema.ts +215 -0
  25. package/src/core/approval.ts +190 -0
  26. package/src/core/comments.ts +175 -0
  27. package/src/core/index.ts +5 -0
  28. package/src/core/ports.ts +185 -0
  29. package/src/core/state.ts +186 -0
  30. package/src/core/types.ts +430 -0
  31. package/src/executors/flowgraph/client.ts +27 -0
  32. package/src/executors/flowgraph/executor.ts +593 -0
  33. package/src/executors/flowgraph/lazy.ts +77 -0
  34. package/src/executors/flowgraph/rpc.ts +145 -0
  35. package/src/executors/flowgraph/worker.ts +538 -0
  36. package/src/executors/native/bridge.ts +421 -0
  37. package/src/executors/native/executor.ts +295 -0
  38. package/src/executors/native/prompt.ts +57 -0
  39. package/src/executors/native/trust.ts +105 -0
  40. package/src/index.ts +116 -0
  41. package/src/rpc.ts +75 -0
  42. package/src/runtime/backends.ts +27 -0
  43. package/src/runtime/engine.ts +2345 -0
  44. package/src/runtime/server-backends.ts +136 -0
  45. package/src/runtime/service.ts +276 -0
  46. package/src/sources/github/client.ts +98 -0
  47. package/src/sources/github/source.ts +490 -0
  48. package/src/storage/capacity.ts +223 -0
  49. package/src/storage/jobs.ts +249 -0
  50. package/src/storage/locks.ts +342 -0
  51. package/src/tui.tsx +399 -0
  52. package/src/util/ids.ts +18 -0
  53. package/src/util/logger.ts +52 -0
  54. package/src/util/process.ts +119 -0
  55. package/src/util/redact.ts +28 -0
  56. package/src/version.ts +2 -0
  57. package/src/workspaces/native.ts +162 -0
  58. package/src/workspaces/publication.ts +477 -0
@@ -0,0 +1,490 @@
1
+ import type { Logger } from "../../util/logger.js"
2
+ import { stableHash } from "../../util/ids.js"
3
+ import type {
4
+ AdmissionAuthorization,
5
+ DecisionComment,
6
+ IssueComment,
7
+ IssueSummary,
8
+ IssueContext,
9
+ LinkedPullRequest,
10
+ PublishedComment,
11
+ PullRequestInfo,
12
+ } from "../../core/types.js"
13
+ import type { ReadyListing, SourceValidation, WorkSource } from "../../core/ports.js"
14
+ import { GitHubClient, GitHubError, issuePath, repositoryPath } from "./client.js"
15
+
16
+ interface GhLabel {
17
+ readonly name: string
18
+ }
19
+
20
+ interface GhIssue {
21
+ readonly number: number
22
+ readonly title: string
23
+ readonly html_url: string
24
+ readonly body?: string | null
25
+ readonly state?: string
26
+ readonly updated_at: string
27
+ readonly labels: readonly (GhLabel | string)[]
28
+ readonly pull_request?: unknown
29
+ }
30
+
31
+ interface GhPullRequest {
32
+ readonly number: number
33
+ readonly html_url: string
34
+ readonly state?: string
35
+ readonly merged_at?: string | null
36
+ readonly draft?: boolean
37
+ readonly head?: { readonly sha?: string }
38
+ }
39
+
40
+ interface GhComment {
41
+ readonly id: number
42
+ readonly user?: { readonly login?: string }
43
+ readonly body?: string | null
44
+ readonly created_at: string
45
+ readonly updated_at: string
46
+ }
47
+
48
+ interface TimelineEvent {
49
+ readonly id?: number | string
50
+ readonly event?: string
51
+ readonly actor?: { readonly login?: string }
52
+ readonly label?: { readonly name?: string }
53
+ readonly created_at?: string
54
+ readonly source?: {
55
+ readonly issue?: {
56
+ readonly number?: number
57
+ readonly html_url?: string
58
+ readonly state?: string
59
+ readonly pull_request?: unknown
60
+ }
61
+ }
62
+ }
63
+
64
+ interface ReadyAuthorization {
65
+ readonly ok: boolean
66
+ readonly reason?: string
67
+ readonly actor?: string
68
+ readonly at?: string
69
+ readonly labels?: ReadonlyArray<{
70
+ readonly name: string
71
+ readonly actor: string
72
+ readonly at: string
73
+ readonly eventID?: number | string
74
+ }>
75
+ }
76
+
77
+ /**
78
+ * Authorization is evaluated from timeline state, not from discovery output.
79
+ * A label only counts while its latest event is an authorized application.
80
+ */
81
+ function authorizeReady(input: {
82
+ timeline: readonly TimelineEvent[]
83
+ currentLabels: readonly string[]
84
+ triggerLabels: readonly string[]
85
+ enqueueUsers: readonly string[]
86
+ }): ReadyAuthorization {
87
+ const allowed = new Set(input.enqueueUsers.map((value) => value.toLowerCase()))
88
+ const active = new Map<
89
+ string,
90
+ { actor: string; at: string; eventID?: number | string }
91
+ >()
92
+ for (const event of input.timeline) {
93
+ const label = event.label?.name
94
+ if (!label || !input.triggerLabels.includes(label)) continue
95
+ if (event.event === "labeled") {
96
+ if (typeof event.actor?.login === "string" && typeof event.created_at === "string") {
97
+ active.set(label, {
98
+ actor: event.actor.login,
99
+ at: event.created_at,
100
+ ...(event.id === undefined ? {} : { eventID: event.id }),
101
+ })
102
+ }
103
+ continue
104
+ }
105
+ if (event.event === "unlabeled") active.delete(label)
106
+ }
107
+ for (const label of input.triggerLabels) {
108
+ if (!input.currentLabels.includes(label)) {
109
+ return { ok: false, reason: `ready label ${label} is no longer present` }
110
+ }
111
+ const applied = active.get(label)
112
+ if (!applied) {
113
+ return { ok: false, reason: `no active ready-label history for ${label}` }
114
+ }
115
+ if (!allowed.has(applied.actor.toLowerCase())) {
116
+ return { ok: false, reason: `ready label ${label} was applied by unauthorized user ${applied.actor}` }
117
+ }
118
+ }
119
+ const values = [...active.values()]
120
+ if (values.some((value) => !Number.isFinite(Date.parse(value.at)))) {
121
+ return { ok: false, reason: "the active ready-label timestamp is invalid" }
122
+ }
123
+ const latest = values.sort((left, right) => Date.parse(right.at) - Date.parse(left.at))[0]
124
+ if (!latest) return { ok: false, reason: "no active ready-label application" }
125
+ return {
126
+ ok: true,
127
+ actor: latest.actor,
128
+ at: latest.at,
129
+ labels: input.triggerLabels.map((name) => {
130
+ const value = active.get(name)!
131
+ return { name, actor: value.actor, at: value.at, ...(value.eventID === undefined ? {} : { eventID: value.eventID }) }
132
+ }),
133
+ }
134
+ }
135
+
136
+ const LABEL_COLORS: Record<string, string> = {
137
+ "agent-ready": "0e8a16",
138
+ "agent-running": "1d76db",
139
+ "agent-review": "fbca04",
140
+ "agent-blocked": "d93f0b",
141
+ "agent-completed": "5319e7",
142
+ }
143
+
144
+ export interface GitHubSourceOptions {
145
+ readonly client: GitHubClient
146
+ readonly repository: string
147
+ readonly logger: Logger
148
+ readonly maxPages?: number
149
+ }
150
+
151
+ export class GitHubSource implements WorkSource {
152
+ readonly repository: string
153
+ private readonly client: GitHubClient
154
+ private readonly logger: Logger
155
+ private readonly maxPages: number
156
+
157
+ constructor(options: GitHubSourceOptions) {
158
+ this.client = options.client
159
+ this.repository = options.repository
160
+ this.logger = options.logger
161
+ this.maxPages = options.maxPages ?? 10
162
+ }
163
+
164
+ async validate(): Promise<SourceValidation> {
165
+ await this.client.raw(["auth", "status"])
166
+ const repo = await this.client.api<{
167
+ full_name: string
168
+ default_branch: string
169
+ permissions?: { push?: boolean; admin?: boolean; maintain?: boolean }
170
+ }>(repositoryPath(this.repository))
171
+ const canWrite = repo.permissions?.push || repo.permissions?.admin || repo.permissions?.maintain
172
+ if (!canWrite) {
173
+ throw new GitHubError(
174
+ `GitHub token does not have write access to ${repo.full_name}; Taskfeed needs label and comment access`,
175
+ "forbidden",
176
+ )
177
+ }
178
+ return { defaultBranch: repo.default_branch, repository: repo.full_name }
179
+ }
180
+
181
+ async ensureLabels(labels: readonly string[], signal?: AbortSignal): Promise<void> {
182
+ if (signal?.aborted) return
183
+ const existing = await this.client.gh<readonly { name: string }[]>([
184
+ "label",
185
+ "list",
186
+ "--repo",
187
+ this.repository,
188
+ "--limit",
189
+ "1000",
190
+ "--json",
191
+ "name",
192
+ ])
193
+ const names = new Set(existing.map((label) => label.name))
194
+ for (const label of labels) {
195
+ if (names.has(label)) continue
196
+ await this.client.raw([
197
+ "label",
198
+ "create",
199
+ label,
200
+ "--repo",
201
+ this.repository,
202
+ "--color",
203
+ LABEL_COLORS[label] ?? "ededed",
204
+ "--description",
205
+ label === "agent-ready"
206
+ ? "Taskfeed: authorized developer marked this issue ready for automation"
207
+ : "Taskfeed automation status",
208
+ ])
209
+ this.logger.info("created GitHub label", { label })
210
+ }
211
+ }
212
+
213
+ async listReady(input: {
214
+ triggerLabels: readonly string[]
215
+ enqueueUsers: readonly string[]
216
+ signal?: AbortSignal
217
+ }): Promise<ReadyListing> {
218
+ const issues: IssueSummary[] = []
219
+ const skipped: { number: number; reason: string }[] = []
220
+ for (let page = 1; page <= this.maxPages; page++) {
221
+ if (input.signal?.aborted) break
222
+ const query = new URLSearchParams({
223
+ state: "open",
224
+ labels: input.triggerLabels.join(","),
225
+ per_page: "100",
226
+ page: String(page),
227
+ sort: "created",
228
+ direction: "asc",
229
+ })
230
+ const batch = await this.client.api<GhIssue[]>(`${repositoryPath(this.repository)}/issues?${query.toString()}`)
231
+ for (const issue of batch) {
232
+ if (issue.pull_request) continue
233
+ const labels = issue.labels.map((label) => (typeof label === "string" ? label : label.name))
234
+ const timeline = await this.timeline(issue.number)
235
+ const authorization = authorizeReady({
236
+ timeline,
237
+ currentLabels: labels,
238
+ triggerLabels: input.triggerLabels,
239
+ enqueueUsers: input.enqueueUsers,
240
+ })
241
+ if (!authorization.ok) {
242
+ skipped.push({ number: issue.number, reason: authorization.reason ?? "unauthorized ready label" })
243
+ this.logger.warn("ignored ready label", { issue: issue.number, reason: authorization.reason })
244
+ continue
245
+ }
246
+ issues.push({
247
+ repository: this.repository,
248
+ number: issue.number,
249
+ title: issue.title,
250
+ url: issue.html_url,
251
+ updatedAt: issue.updated_at,
252
+ labels,
253
+ })
254
+ }
255
+ if (batch.length < 100) break
256
+ }
257
+ return { issues, skipped }
258
+ }
259
+
260
+ async authorizeAdmission(
261
+ summary: IssueSummary,
262
+ policy: { triggerLabels: readonly string[]; enqueueUsers: readonly string[] },
263
+ signal?: AbortSignal,
264
+ ): Promise<AdmissionAuthorization> {
265
+ if (signal?.aborted) throw new Error("issue admission cancelled")
266
+ const issue = await this.client.api<GhIssue>(issuePath(this.repository, summary.number))
267
+ if (issue.pull_request) throw new GitHubError(`issue #${summary.number} is a pull request`, "forbidden")
268
+ if (issue.state !== undefined && issue.state !== "open") {
269
+ throw new GitHubError(`issue #${summary.number} is not open`, "forbidden")
270
+ }
271
+ const labels = issue.labels.map((label) => (typeof label === "string" ? label : label.name))
272
+ const timeline = await this.timeline(summary.number)
273
+ const authorization = authorizeReady({
274
+ timeline,
275
+ currentLabels: labels,
276
+ triggerLabels: policy.triggerLabels,
277
+ enqueueUsers: policy.enqueueUsers,
278
+ })
279
+ if (!authorization.ok || !authorization.actor || !authorization.at || !authorization.labels) {
280
+ throw new GitHubError(
281
+ `issue #${summary.number} is not authorized for enqueue: ${authorization.reason ?? "unknown reason"}`,
282
+ "forbidden",
283
+ )
284
+ }
285
+ const admittedAt = Date.parse(authorization.at)
286
+ if (!Number.isFinite(admittedAt)) {
287
+ throw new GitHubError(`issue #${summary.number} has an invalid ready-label timestamp`, "unknown")
288
+ }
289
+ return {
290
+ repository: this.repository,
291
+ issueNumber: issue.number,
292
+ issueURL: issue.html_url,
293
+ actor: authorization.actor,
294
+ admittedAt,
295
+ labels: [...authorization.labels],
296
+ }
297
+ }
298
+
299
+ async loadContext(summary: IssueSummary, signal?: AbortSignal): Promise<IssueContext> {
300
+ if (signal?.aborted) throw new Error("issue load cancelled")
301
+ const issue = await this.client.api<GhIssue>(issuePath(this.repository, summary.number))
302
+ if (issue.pull_request) throw new GitHubError(`issue #${summary.number} is a pull request`, "forbidden")
303
+ if (issue.state !== undefined && issue.state !== "open") {
304
+ throw new GitHubError(`issue #${summary.number} is not open`, "forbidden")
305
+ }
306
+ if (issue.number !== summary.number || issue.html_url !== summary.url) {
307
+ throw new GitHubError(`issue #${summary.number} context identity changed`, "unknown")
308
+ }
309
+ const labels = issue.labels.map((label) => (typeof label === "string" ? label : label.name))
310
+ const timeline = await this.timeline(summary.number)
311
+ const comments = await this.comments(summary.number)
312
+ const body = issue.body ?? ""
313
+ return {
314
+ repository: this.repository,
315
+ number: issue.number,
316
+ title: issue.title,
317
+ url: issue.html_url,
318
+ body: body.slice(0, 32_000),
319
+ bodyHash: bodyHash(body),
320
+ labels,
321
+ updatedAt: issue.updated_at,
322
+ comments: this.relevantComments(comments),
323
+ linkedPullRequests: this.linkedPullRequestsFrom(timeline),
324
+ }
325
+ }
326
+
327
+ async readDecisions(job: { task: { repository: string; issueNumber: number } }): Promise<readonly DecisionComment[]> {
328
+ const comments = await this.comments(job.task.issueNumber)
329
+ return comments.slice(-100).map((comment) => ({
330
+ id: comment.id,
331
+ author: comment.user?.login ?? "unknown",
332
+ body: comment.body ?? "",
333
+ createdAt: comment.created_at,
334
+ updatedAt: comment.updated_at,
335
+ }))
336
+ }
337
+
338
+ async getComment(
339
+ repository: string,
340
+ issueNumber: number,
341
+ commentID: number,
342
+ ): Promise<DecisionComment | undefined> {
343
+ if (repository !== this.repository) throw new Error("comment repository does not match the configured source")
344
+ try {
345
+ const comment = await this.client.api<GhComment>(`${repositoryPath(repository)}/issues/comments/${commentID}`)
346
+ return {
347
+ id: comment.id,
348
+ author: comment.user?.login ?? "unknown",
349
+ body: comment.body ?? "",
350
+ createdAt: comment.created_at,
351
+ updatedAt: comment.updated_at,
352
+ }
353
+ } catch (error) {
354
+ if (error instanceof GitHubError && error.code === "not_found") return undefined
355
+ throw error
356
+ }
357
+ }
358
+
359
+ async applyLabels(input: {
360
+ repository: string
361
+ issueNumber: number
362
+ add: readonly string[]
363
+ remove: readonly string[]
364
+ }): Promise<void> {
365
+ if (input.add.length === 0 && input.remove.length === 0) return
366
+ const args = ["issue", "edit", String(input.issueNumber), "--repo", input.repository]
367
+ for (const label of input.add) args.push("--add-label", label)
368
+ for (const label of input.remove) args.push("--remove-label", label)
369
+ await this.client.raw(args)
370
+ }
371
+
372
+ async upsertComment(input: {
373
+ repository: string
374
+ issueNumber: number
375
+ marker: string
376
+ body: string
377
+ commentID?: number
378
+ }): Promise<PublishedComment> {
379
+ const body = `${input.body.trim()}\n\n${input.marker}`
380
+ let commentID = input.commentID
381
+ if (commentID === undefined) {
382
+ const comments = await this.comments(input.issueNumber)
383
+ commentID = comments.find((comment) => (comment.body ?? "").includes(input.marker))?.id
384
+ }
385
+ if (commentID !== undefined) {
386
+ const result = await this.client.api<{ id: number; html_url?: string }>(
387
+ `${repositoryPath(input.repository)}/issues/comments/${commentID}`,
388
+ { method: "PATCH", body: { body } },
389
+ )
390
+ return { commentID: result.id, ...(result.html_url === undefined ? {} : { url: result.html_url }) }
391
+ }
392
+ const result = await this.client.api<{ id: number; html_url?: string }>(
393
+ `${issuePath(input.repository, input.issueNumber)}/comments`,
394
+ { method: "POST", body: { body } },
395
+ )
396
+ return { commentID: result.id, ...(result.html_url === undefined ? {} : { url: result.html_url }) }
397
+ }
398
+
399
+ async listLinkedPullRequests(repository: string, issueNumber: number): Promise<readonly LinkedPullRequest[]> {
400
+ const timeline = await this.timeline(issueNumber)
401
+ const found = this.linkedPullRequestsFrom(timeline)
402
+ return await Promise.all(
403
+ found.map(async (pull) => (await this.getPullRequest(repository, pull.number).catch(() => undefined)) ?? pull),
404
+ )
405
+ }
406
+
407
+ async getPullRequest(
408
+ repository: string,
409
+ pullRequestNumber: number,
410
+ ): Promise<PullRequestInfo | undefined> {
411
+ if (!Number.isSafeInteger(pullRequestNumber) || pullRequestNumber <= 0) {
412
+ throw new Error("invalid pull request number")
413
+ }
414
+ try {
415
+ const detail = await this.client.api<GhPullRequest>(`${repositoryPath(repository)}/pulls/${pullRequestNumber}`)
416
+ if (typeof detail.head?.sha !== "string" || !detail.head.sha) return undefined
417
+ return {
418
+ number: detail.number,
419
+ url: detail.html_url,
420
+ state: detail.merged_at ? "merged" : detail.state === "closed" ? "closed" : "open",
421
+ headSHA: detail.head.sha,
422
+ draft: detail.draft === true,
423
+ }
424
+ } catch (error) {
425
+ if (error instanceof GitHubError && error.code === "not_found") return undefined
426
+ throw error
427
+ }
428
+ }
429
+
430
+ private async timeline(issueNumber: number): Promise<TimelineEvent[]> {
431
+ const events: TimelineEvent[] = []
432
+ for (let page = 1; page <= 10; page++) {
433
+ const batch = await this.client.api<TimelineEvent[]>(
434
+ `${issuePath(this.repository, issueNumber)}/timeline?per_page=100&page=${page}`,
435
+ )
436
+ events.push(...batch)
437
+ if (batch.length < 100) break
438
+ }
439
+ return events
440
+ }
441
+
442
+ private async comments(issueNumber: number): Promise<GhComment[]> {
443
+ const comments: GhComment[] = []
444
+ for (let page = 1; page <= this.maxPages; page++) {
445
+ const batch = await this.client.api<GhComment[]>(
446
+ `${issuePath(this.repository, issueNumber)}/comments?per_page=100&page=${page}`,
447
+ )
448
+ comments.push(...batch)
449
+ if (batch.length < 100) break
450
+ }
451
+ return comments
452
+ }
453
+
454
+ private relevantComments(comments: readonly GhComment[]): IssueComment[] {
455
+ const selected: IssueComment[] = []
456
+ let bytes = 0
457
+ for (const comment of comments.slice(-20)) {
458
+ const body = (comment.body ?? "").slice(0, 8_000)
459
+ bytes += Buffer.byteLength(body)
460
+ if (bytes > 32_000) break
461
+ selected.push({
462
+ id: comment.id,
463
+ author: comment.user?.login ?? "unknown",
464
+ body,
465
+ createdAt: comment.created_at,
466
+ updatedAt: comment.updated_at,
467
+ })
468
+ }
469
+ return selected
470
+ }
471
+
472
+ private linkedPullRequestsFrom(timeline: readonly TimelineEvent[]): LinkedPullRequest[] {
473
+ const found = new Map<number, LinkedPullRequest>()
474
+ for (const event of timeline) {
475
+ if (event.event !== "cross-referenced") continue
476
+ const issue = event.source?.issue
477
+ if (!issue?.pull_request || typeof issue.number !== "number" || typeof issue.html_url !== "string") continue
478
+ found.set(issue.number, {
479
+ number: issue.number,
480
+ url: issue.html_url,
481
+ state: issue.state === "closed" ? "closed" : "open",
482
+ })
483
+ }
484
+ return [...found.values()]
485
+ }
486
+ }
487
+
488
+ export function bodyHash(body: string): string {
489
+ return stableHash(body, 64)
490
+ }
@@ -0,0 +1,223 @@
1
+ import { readFile, rename, rm, writeFile } from "node:fs/promises"
2
+ import os from "node:os"
3
+ import path from "node:path"
4
+ import { randomUUID } from "node:crypto"
5
+ import { FileMutex, ensurePrivateDirectory, listJsonFiles } from "./locks.js"
6
+ import { stableHash } from "../util/ids.js"
7
+
8
+ export interface CapacitySlot {
9
+ readonly version: 1
10
+ readonly jobID: string
11
+ readonly projectKey: string
12
+ readonly token: string
13
+ readonly generation: number
14
+ readonly state: "active" | "ambiguous"
15
+ readonly acquiredAt: number
16
+ readonly heartbeatAt: number
17
+ readonly pid: number
18
+ readonly hostname: string
19
+ }
20
+
21
+ export interface CapacitySnapshot {
22
+ readonly limit: number
23
+ readonly used: number
24
+ readonly ambiguous: number
25
+ readonly slots: readonly CapacitySlot[]
26
+ }
27
+
28
+ interface SlotFence {
29
+ readonly projectKey: string
30
+ readonly jobID: string
31
+ readonly token: string
32
+ readonly generation?: number
33
+ }
34
+
35
+ async function readSlot(file: string): Promise<CapacitySlot | undefined> {
36
+ try {
37
+ const value = JSON.parse(await readFile(file, "utf8")) as Partial<CapacitySlot>
38
+ if (
39
+ value.version !== 1 ||
40
+ typeof value.jobID !== "string" ||
41
+ typeof value.projectKey !== "string" ||
42
+ typeof value.token !== "string" ||
43
+ (value.state !== "active" && value.state !== "ambiguous") ||
44
+ typeof value.heartbeatAt !== "number"
45
+ ) {
46
+ return undefined
47
+ }
48
+ return {
49
+ ...(value as CapacitySlot),
50
+ generation: typeof value.generation === "number" ? value.generation : 1,
51
+ }
52
+ } catch {
53
+ return undefined
54
+ }
55
+ }
56
+
57
+ async function writeJsonAtomic(file: string, value: unknown): Promise<void> {
58
+ const temp = `${file}.tmp-${randomUUID()}`
59
+ await writeFile(temp, JSON.stringify(value), { mode: 0o600 })
60
+ await rename(temp, file)
61
+ }
62
+
63
+ function matches(slot: CapacitySlot, fence: SlotFence): boolean {
64
+ return (
65
+ slot.projectKey === fence.projectKey &&
66
+ slot.jobID === fence.jobID &&
67
+ slot.token === fence.token &&
68
+ (fence.generation === undefined || slot.generation === fence.generation)
69
+ )
70
+ }
71
+
72
+ /**
73
+ * Server-boundary execution capacity. Slots are file-backed so independent
74
+ * plugin instances and multiple project leaders share one budget. Every
75
+ * mutation is serialized by the capacity mutex and fenced by token+generation,
76
+ * so a former owner can never overwrite a newer adoption. Ambiguous slots are
77
+ * never timed out into release.
78
+ */
79
+ export class CapacityManager {
80
+ private readonly mutex: FileMutex
81
+ readonly slotsDirectory: string
82
+
83
+ constructor(
84
+ readonly limit: number,
85
+ root = path.join(globalRootSafe(), "capacity"),
86
+ ) {
87
+ if (!Number.isInteger(limit) || limit < 1) throw new Error("global capacity must be a positive integer")
88
+ this.slotsDirectory = path.join(root, "slots")
89
+ this.mutex = new FileMutex(path.join(root, "mutex.lock"), { staleMs: 30_000, waitMs: 10_000 })
90
+ }
91
+
92
+ private async ensure(): Promise<void> {
93
+ await ensurePrivateDirectory(this.slotsDirectory)
94
+ }
95
+
96
+ private fileFor(projectKey: string, jobID: string): string {
97
+ return path.join(this.slotsDirectory, `${stableHash(`${projectKey}\0${jobID}`, 40)}.json`)
98
+ }
99
+
100
+ private async listUnlocked(): Promise<readonly CapacitySlot[]> {
101
+ const files = await listJsonFiles(this.slotsDirectory)
102
+ const slots: CapacitySlot[] = []
103
+ for (const file of files) {
104
+ const slot = await readSlot(file)
105
+ if (slot) slots.push(slot)
106
+ }
107
+ return slots.sort((a, b) => a.acquiredAt - b.acquiredAt)
108
+ }
109
+
110
+ async list(): Promise<readonly CapacitySlot[]> {
111
+ await this.ensure()
112
+ return await this.listUnlocked()
113
+ }
114
+
115
+ async snapshot(): Promise<CapacitySnapshot> {
116
+ const slots = await this.list()
117
+ return {
118
+ limit: this.limit,
119
+ used: slots.length,
120
+ ambiguous: slots.filter((slot) => slot.state === "ambiguous").length,
121
+ slots,
122
+ }
123
+ }
124
+
125
+ async acquire(input: {
126
+ projectKey: string
127
+ jobID: string
128
+ state?: "active" | "ambiguous"
129
+ recover?: boolean
130
+ }): Promise<CapacitySlot | undefined> {
131
+ await this.ensure()
132
+ const lock = await this.mutex.acquire()
133
+ if (!lock) return undefined
134
+ try {
135
+ const slotFile = this.fileFor(input.projectKey, input.jobID)
136
+ const existing = await readSlot(slotFile)
137
+ if (existing) {
138
+ if (input.recover !== true) return undefined
139
+ const adopted: CapacitySlot = {
140
+ ...existing,
141
+ token: randomUUID(),
142
+ generation: existing.generation + 1,
143
+ state: input.state ?? existing.state,
144
+ heartbeatAt: Date.now(),
145
+ pid: process.pid,
146
+ hostname: os.hostname(),
147
+ }
148
+ await writeJsonAtomic(slotFile, adopted)
149
+ return adopted
150
+ }
151
+ const slots = await this.listUnlocked()
152
+ if (slots.length >= this.limit && input.recover !== true) return undefined
153
+ const slot: CapacitySlot = {
154
+ version: 1,
155
+ jobID: input.jobID,
156
+ projectKey: input.projectKey,
157
+ token: randomUUID(),
158
+ generation: 1,
159
+ state: input.state ?? "active",
160
+ acquiredAt: Date.now(),
161
+ heartbeatAt: Date.now(),
162
+ pid: process.pid,
163
+ hostname: os.hostname(),
164
+ }
165
+ await writeJsonAtomic(slotFile, slot)
166
+ return slot
167
+ } finally {
168
+ await lock.release()
169
+ }
170
+ }
171
+
172
+ async heartbeat(slot: SlotFence): Promise<boolean> {
173
+ const lock = await this.mutex.acquire()
174
+ if (!lock) return false
175
+ try {
176
+ const slotFile = this.fileFor(slot.projectKey, slot.jobID)
177
+ const current = await readSlot(slotFile)
178
+ if (!current || !matches(current, slot)) return false
179
+ await writeJsonAtomic(slotFile, { ...current, heartbeatAt: Date.now() })
180
+ return true
181
+ } finally {
182
+ await lock.release()
183
+ }
184
+ }
185
+
186
+ async markAmbiguous(slot: SlotFence): Promise<CapacitySlot | undefined> {
187
+ const lock = await this.mutex.acquire()
188
+ if (!lock) return undefined
189
+ try {
190
+ const slotFile = this.fileFor(slot.projectKey, slot.jobID)
191
+ const current = await readSlot(slotFile)
192
+ if (!current || !matches(current, slot)) return undefined
193
+ const next: CapacitySlot = { ...current, state: "ambiguous", heartbeatAt: Date.now() }
194
+ await writeJsonAtomic(slotFile, next)
195
+ return next
196
+ } finally {
197
+ await lock.release()
198
+ }
199
+ }
200
+
201
+ async release(slot: SlotFence): Promise<boolean> {
202
+ const lock = await this.mutex.acquire()
203
+ if (!lock) return false
204
+ try {
205
+ const file = this.fileFor(slot.projectKey, slot.jobID)
206
+ const current = await readSlot(file)
207
+ if (!current || !matches(current, slot)) return false
208
+ await rm(file, { force: true })
209
+ return true
210
+ } finally {
211
+ await lock.release()
212
+ }
213
+ }
214
+
215
+ }
216
+
217
+ function globalRootSafe(): string {
218
+ // Lazily avoids importing the mutable root helper into test constructors.
219
+ const uid = typeof process.getuid === "function" ? process.getuid() : "user"
220
+ return process.env.XDG_RUNTIME_DIR
221
+ ? path.join(process.env.XDG_RUNTIME_DIR, "opencode-taskfeed")
222
+ : path.join(os.tmpdir(), `opencode-taskfeed-${uid}`)
223
+ }