@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.
- package/LICENSE +202 -0
- package/README.md +431 -2
- package/docs/architecture.md +123 -0
- package/docs/configuration.md +123 -0
- package/docs/development.md +312 -0
- package/docs/integrations.md +84 -0
- package/docs/operations.md +136 -0
- package/docs/releases/v0.1.0-alpha.1.md +164 -0
- package/docs/security.md +120 -0
- package/examples/README.md +7 -0
- package/examples/approvals/README.md +27 -0
- package/examples/flowgraph/config.yaml +28 -0
- package/examples/flowgraph/opencode.jsonc +14 -0
- package/examples/headless/README.md +25 -0
- package/examples/headless/config.yaml +21 -0
- package/examples/native-agent/config.yaml +31 -0
- package/examples/native-agent/opencode.jsonc +10 -0
- package/examples/playground/README.md +61 -0
- package/examples/playground/config.yaml +40 -0
- package/examples/playground/opencode.jsonc +5 -0
- package/package.json +89 -4
- package/src/config/load.ts +122 -0
- package/src/config/repository.ts +72 -0
- package/src/config/schema.ts +215 -0
- package/src/core/approval.ts +190 -0
- package/src/core/comments.ts +175 -0
- package/src/core/index.ts +5 -0
- package/src/core/ports.ts +185 -0
- package/src/core/state.ts +186 -0
- package/src/core/types.ts +430 -0
- package/src/executors/flowgraph/client.ts +27 -0
- package/src/executors/flowgraph/executor.ts +593 -0
- package/src/executors/flowgraph/lazy.ts +77 -0
- package/src/executors/flowgraph/rpc.ts +145 -0
- package/src/executors/flowgraph/worker.ts +538 -0
- package/src/executors/native/bridge.ts +421 -0
- package/src/executors/native/executor.ts +295 -0
- package/src/executors/native/prompt.ts +57 -0
- package/src/executors/native/trust.ts +105 -0
- package/src/index.ts +116 -0
- package/src/rpc.ts +75 -0
- package/src/runtime/backends.ts +27 -0
- package/src/runtime/engine.ts +2345 -0
- package/src/runtime/server-backends.ts +136 -0
- package/src/runtime/service.ts +276 -0
- package/src/sources/github/client.ts +98 -0
- package/src/sources/github/source.ts +490 -0
- package/src/storage/capacity.ts +223 -0
- package/src/storage/jobs.ts +249 -0
- package/src/storage/locks.ts +342 -0
- package/src/tui.tsx +399 -0
- package/src/util/ids.ts +18 -0
- package/src/util/logger.ts +52 -0
- package/src/util/process.ts +119 -0
- package/src/util/redact.ts +28 -0
- package/src/version.ts +2 -0
- package/src/workspaces/native.ts +162 -0
- package/src/workspaces/publication.ts +477 -0
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
import path from "node:path"
|
|
2
|
+
import { lstat } from "node:fs/promises"
|
|
3
|
+
import type { CommandRunner } from "../util/process.js"
|
|
4
|
+
import { CommandFailure } from "../util/process.js"
|
|
5
|
+
import type { Logger } from "../util/logger.js"
|
|
6
|
+
import type { Workspace } from "../core/types.js"
|
|
7
|
+
import type { WorkspaceProvider, WorkspaceState } from "../core/ports.js"
|
|
8
|
+
import { stableHash, slug } from "../util/ids.js"
|
|
9
|
+
|
|
10
|
+
export interface NativeWorktreeApi {
|
|
11
|
+
create(input: { projectID: string; name?: string; branch?: string; from?: string }): Promise<{ directory: string }>
|
|
12
|
+
list(input: { projectID: string }): Promise<readonly { directory: string }[]>
|
|
13
|
+
remove(input: { projectID: string; directory: string; force: boolean }): Promise<void>
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export interface NativeWorkspaceProviderOptions {
|
|
17
|
+
readonly worktree: NativeWorktreeApi
|
|
18
|
+
readonly runner: CommandRunner
|
|
19
|
+
readonly logger: Logger
|
|
20
|
+
readonly projectID: string
|
|
21
|
+
readonly canonicalDirectory: string
|
|
22
|
+
readonly branchPrefix: string
|
|
23
|
+
readonly now?: () => number
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export class NativeWorkspaceProvider implements WorkspaceProvider {
|
|
27
|
+
private readonly options: NativeWorkspaceProviderOptions
|
|
28
|
+
private readonly now: () => number
|
|
29
|
+
|
|
30
|
+
constructor(options: NativeWorkspaceProviderOptions) {
|
|
31
|
+
this.options = options
|
|
32
|
+
this.now = options.now ?? Date.now
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async prepare(input: {
|
|
36
|
+
jobID: string
|
|
37
|
+
issueNumber: number
|
|
38
|
+
title: string
|
|
39
|
+
baseBranch?: string
|
|
40
|
+
}): Promise<Workspace> {
|
|
41
|
+
const short = stableHash(`${this.options.projectID}:${input.jobID}`, 8)
|
|
42
|
+
const branch = `${this.options.branchPrefix}issue-${input.issueNumber}-${short}`
|
|
43
|
+
const name = `taskfeed-${input.issueNumber}-${slug(input.title, 20)}-${short}`
|
|
44
|
+
const baseRef = await this.resolveBase(input.baseBranch)
|
|
45
|
+
let created: { directory: string }
|
|
46
|
+
try {
|
|
47
|
+
created = await this.options.worktree.create({
|
|
48
|
+
projectID: this.options.projectID,
|
|
49
|
+
name,
|
|
50
|
+
...(baseRef === undefined ? {} : { branch: baseRef }),
|
|
51
|
+
})
|
|
52
|
+
} catch (error) {
|
|
53
|
+
throw new Error(`Could not create isolated worktree: ${error instanceof Error ? error.message : String(error)}`)
|
|
54
|
+
}
|
|
55
|
+
const directory = path.resolve(created.directory)
|
|
56
|
+
if (directory === path.resolve(this.options.canonicalDirectory)) {
|
|
57
|
+
await this.removeOwned(directory, true).catch(() => undefined)
|
|
58
|
+
throw new Error("OpenCode returned the canonical checkout instead of a worktree")
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
const exists = await this.branchExists(branch)
|
|
62
|
+
const args = exists ? ["switch", branch] : ["switch", "-c", branch]
|
|
63
|
+
const switched = await this.options.runner.run("git", args, {
|
|
64
|
+
cwd: directory,
|
|
65
|
+
timeoutMs: 30_000,
|
|
66
|
+
env: { GIT_TERMINAL_PROMPT: "0" },
|
|
67
|
+
})
|
|
68
|
+
if (switched.exitCode !== 0) throw new CommandFailure(switched)
|
|
69
|
+
const head = await this.options.runner.run("git", ["rev-parse", "HEAD"], {
|
|
70
|
+
cwd: directory,
|
|
71
|
+
timeoutMs: 10_000,
|
|
72
|
+
})
|
|
73
|
+
if (head.exitCode !== 0) throw new CommandFailure(head)
|
|
74
|
+
return {
|
|
75
|
+
directory,
|
|
76
|
+
branch,
|
|
77
|
+
baseSHA: head.stdout.trim(),
|
|
78
|
+
strategy: "opencode-worktree",
|
|
79
|
+
createdAt: this.now(),
|
|
80
|
+
}
|
|
81
|
+
} catch (error) {
|
|
82
|
+
await this.removeOwned(directory, true).catch(() => undefined)
|
|
83
|
+
throw error
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
async state(workspace: Workspace): Promise<WorkspaceState> {
|
|
88
|
+
try {
|
|
89
|
+
const info = await lstat(workspace.directory)
|
|
90
|
+
if (!info.isDirectory() || info.isSymbolicLink()) return { exists: false, clean: false, dirtyFiles: [] }
|
|
91
|
+
} catch {
|
|
92
|
+
return { exists: false, clean: false, dirtyFiles: [] }
|
|
93
|
+
}
|
|
94
|
+
const status = await this.options.runner.run("git", ["status", "--porcelain=v1", "--untracked-files=all"], {
|
|
95
|
+
cwd: workspace.directory,
|
|
96
|
+
timeoutMs: 20_000,
|
|
97
|
+
})
|
|
98
|
+
if (status.exitCode !== 0) throw new CommandFailure(status)
|
|
99
|
+
const head = await this.options.runner.run("git", ["rev-parse", "HEAD"], {
|
|
100
|
+
cwd: workspace.directory,
|
|
101
|
+
timeoutMs: 10_000,
|
|
102
|
+
})
|
|
103
|
+
if (head.exitCode !== 0) throw new CommandFailure(head)
|
|
104
|
+
return {
|
|
105
|
+
exists: true,
|
|
106
|
+
clean: status.stdout.trim() === "",
|
|
107
|
+
headSHA: head.stdout.trim(),
|
|
108
|
+
dirtyFiles: status.stdout
|
|
109
|
+
.split(/\r?\n/u)
|
|
110
|
+
.map((line) => line.slice(3).trim())
|
|
111
|
+
.filter(Boolean),
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async cleanup(workspace: Workspace): Promise<void> {
|
|
116
|
+
const state = await this.state(workspace)
|
|
117
|
+
if (!state.exists) throw new Error("Workspace no longer exists; nothing was deleted")
|
|
118
|
+
if (!state.clean) {
|
|
119
|
+
throw new Error(`Refusing to delete a worktree with uncommitted work: ${state.dirtyFiles.slice(0, 10).join(", ")}`)
|
|
120
|
+
}
|
|
121
|
+
if (!workspace.branch.startsWith(this.options.branchPrefix)) {
|
|
122
|
+
throw new Error("Refusing to remove a worktree whose branch is not Taskfeed-owned")
|
|
123
|
+
}
|
|
124
|
+
const inventory = await this.options.worktree.list({ projectID: this.options.projectID })
|
|
125
|
+
const entry = inventory.find((item) => path.resolve(item.directory) === path.resolve(workspace.directory))
|
|
126
|
+
if (!entry) throw new Error("Refusing to remove a directory absent from worktree inventory")
|
|
127
|
+
if (path.resolve(workspace.directory) === path.resolve(this.options.canonicalDirectory)) {
|
|
128
|
+
throw new Error("Refusing to remove the canonical checkout")
|
|
129
|
+
}
|
|
130
|
+
await this.options.worktree.remove({
|
|
131
|
+
projectID: this.options.projectID,
|
|
132
|
+
directory: workspace.directory,
|
|
133
|
+
force: false,
|
|
134
|
+
})
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
private async resolveBase(baseBranch?: string): Promise<string | undefined> {
|
|
138
|
+
if (!baseBranch) return undefined
|
|
139
|
+
for (const ref of [`refs/remotes/origin/${baseBranch}`, `refs/heads/${baseBranch}`, baseBranch]) {
|
|
140
|
+
const result = await this.options.runner.run("git", ["rev-parse", "--verify", `${ref}^{commit}`], {
|
|
141
|
+
cwd: this.options.canonicalDirectory,
|
|
142
|
+
timeoutMs: 10_000,
|
|
143
|
+
})
|
|
144
|
+
if (result.exitCode === 0) return result.stdout.trim()
|
|
145
|
+
}
|
|
146
|
+
throw new Error(`Configured workspace base branch is unavailable: ${baseBranch}`)
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async branchExists(branch: string): Promise<boolean> {
|
|
150
|
+
const result = await this.options.runner.run("git", ["show-ref", "--verify", `refs/heads/${branch}`], {
|
|
151
|
+
cwd: this.options.canonicalDirectory,
|
|
152
|
+
timeoutMs: 10_000,
|
|
153
|
+
})
|
|
154
|
+
return result.exitCode === 0
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
private async removeOwned(directory: string, force: boolean): Promise<void> {
|
|
158
|
+
const inventory = await this.options.worktree.list({ projectID: this.options.projectID })
|
|
159
|
+
if (!inventory.some((item) => path.resolve(item.directory) === path.resolve(directory))) return
|
|
160
|
+
await this.options.worktree.remove({ projectID: this.options.projectID, directory, force })
|
|
161
|
+
}
|
|
162
|
+
}
|
|
@@ -0,0 +1,477 @@
|
|
|
1
|
+
import type { CommandOptions, CommandRunner, CommandResult } from "../util/process.js"
|
|
2
|
+
import { CommandFailure } from "../util/process.js"
|
|
3
|
+
import type { Logger } from "../util/logger.js"
|
|
4
|
+
import type { ExecutionEvidence, PublicationResult, Workspace } from "../core/types.js"
|
|
5
|
+
import type { PublicationInput, Publisher } from "../core/ports.js"
|
|
6
|
+
import { GitHubClient, repositoryPath } from "../sources/github/client.js"
|
|
7
|
+
import { redact } from "../util/redact.js"
|
|
8
|
+
|
|
9
|
+
export interface GitHubPublisherOptions {
|
|
10
|
+
readonly runner: CommandRunner
|
|
11
|
+
readonly client: GitHubClient
|
|
12
|
+
readonly logger: Logger
|
|
13
|
+
readonly repository: string
|
|
14
|
+
readonly canonicalDirectory: string
|
|
15
|
+
readonly baseBranch?: string
|
|
16
|
+
readonly remote: string
|
|
17
|
+
readonly branchPrefix: string
|
|
18
|
+
readonly protectedPaths: readonly string[]
|
|
19
|
+
readonly generatedArtifacts?: readonly string[]
|
|
20
|
+
readonly maxFileBytes?: number
|
|
21
|
+
readonly enabled: boolean
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
interface PullRequest {
|
|
25
|
+
readonly number: number
|
|
26
|
+
readonly html_url: string
|
|
27
|
+
readonly state?: string
|
|
28
|
+
readonly draft: boolean
|
|
29
|
+
readonly body?: string | null
|
|
30
|
+
readonly head: { readonly ref: string; readonly sha: string }
|
|
31
|
+
readonly base: { readonly ref: string }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
interface ChangedFile {
|
|
35
|
+
readonly status: string
|
|
36
|
+
readonly path: string
|
|
37
|
+
readonly oldPath?: string
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const SHA = /^[0-9a-f]{40}$/u
|
|
41
|
+
const SECRET_CONTENT = [
|
|
42
|
+
/-----BEGIN (?:RSA |DSA |EC |OPENSSH |PGP )?PRIVATE KEY-----/u,
|
|
43
|
+
/-----BEGIN CERTIFICATE-----/u,
|
|
44
|
+
/PuTTY-User-Key-File-\d+:/u,
|
|
45
|
+
/\bgh[pousr]_[A-Za-z0-9_]{20,}\b/u,
|
|
46
|
+
/\bgithub_pat_[A-Za-z0-9_]{20,}\b/u,
|
|
47
|
+
/\bsk-[A-Za-z0-9_-]{20,}\b/u,
|
|
48
|
+
/\bAKIA[0-9A-Z]{16}\b/u,
|
|
49
|
+
/\bASIA[0-9A-Z]{16}\b/u,
|
|
50
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}\b/u,
|
|
51
|
+
/\bnpm_[A-Za-z0-9]{30,}\b/u,
|
|
52
|
+
/\bpypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{20,}\b/u,
|
|
53
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/u,
|
|
54
|
+
]
|
|
55
|
+
|
|
56
|
+
function globToRegExp(pattern: string): RegExp {
|
|
57
|
+
let source = "^"
|
|
58
|
+
for (let index = 0; index < pattern.length; index++) {
|
|
59
|
+
const char = pattern[index]!
|
|
60
|
+
if (char === "*") {
|
|
61
|
+
if (pattern[index + 1] === "*") {
|
|
62
|
+
index++
|
|
63
|
+
if (pattern[index + 1] === "/") index++
|
|
64
|
+
source += ".*"
|
|
65
|
+
} else {
|
|
66
|
+
source += "[^/]*"
|
|
67
|
+
}
|
|
68
|
+
} else if (char === "?") {
|
|
69
|
+
source += "[^/]"
|
|
70
|
+
} else {
|
|
71
|
+
source += char.replace(/[\\^$.*+?()[\]{}|]/gu, "\\$&")
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
return new RegExp(`${source}$`, "u")
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export class GitHubPublisher implements Publisher {
|
|
78
|
+
readonly enabled: boolean
|
|
79
|
+
private readonly options: GitHubPublisherOptions
|
|
80
|
+
|
|
81
|
+
constructor(options: GitHubPublisherOptions) {
|
|
82
|
+
this.options = options
|
|
83
|
+
this.enabled = options.enabled
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async publish(input: PublicationInput): Promise<PublicationResult> {
|
|
87
|
+
if (!this.enabled) {
|
|
88
|
+
return { status: "disabled", branch: input.branch, error: "Taskfeed publication is disabled" }
|
|
89
|
+
}
|
|
90
|
+
if (!SHA.test(input.headSHA)) {
|
|
91
|
+
return { status: "failed", branch: input.branch, error: "Candidate commit SHA is invalid" }
|
|
92
|
+
}
|
|
93
|
+
try {
|
|
94
|
+
const baseBranch = await this.resolveBaseBranch()
|
|
95
|
+
if (!input.branch.startsWith(this.options.branchPrefix) || input.branch === baseBranch) {
|
|
96
|
+
return { status: "failed", branch: input.branch, error: "Branch is not a Taskfeed-owned branch" }
|
|
97
|
+
}
|
|
98
|
+
const state = await this.state(input)
|
|
99
|
+
if (!state.clean) {
|
|
100
|
+
return {
|
|
101
|
+
status: "local_only",
|
|
102
|
+
branch: input.branch,
|
|
103
|
+
error: `Worktree is not clean: ${state.dirtyFiles.slice(0, 10).join(", ")}`,
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
if (state.headSHA !== input.headSHA) {
|
|
107
|
+
return { status: "failed", branch: input.branch, error: "Workspace HEAD changed before publication" }
|
|
108
|
+
}
|
|
109
|
+
const candidate = input.headSHA
|
|
110
|
+
const baseline = await this.remoteBaseline(input, candidate, baseBranch)
|
|
111
|
+
const existing = await this.existingPullRequest(input, candidate, baseBranch)
|
|
112
|
+
const guard = await this.scanOutgoing(input, baseline, candidate)
|
|
113
|
+
if (guard) return { status: "local_only", branch: input.branch, error: guard }
|
|
114
|
+
|
|
115
|
+
await this.push(input, candidate)
|
|
116
|
+
const remoteSHA = await this.remoteSHA(input.branch)
|
|
117
|
+
if (remoteSHA !== candidate) {
|
|
118
|
+
return {
|
|
119
|
+
status: "failed",
|
|
120
|
+
branch: input.branch,
|
|
121
|
+
headSHA: remoteSHA,
|
|
122
|
+
error: "Remote branch does not point at the validated commit",
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const pullRequest = await this.ensurePullRequest(input, candidate, baseBranch, existing)
|
|
127
|
+
return {
|
|
128
|
+
status: "published",
|
|
129
|
+
branch: input.branch,
|
|
130
|
+
remote: this.options.remote,
|
|
131
|
+
pullRequestNumber: pullRequest.number,
|
|
132
|
+
pullRequestURL: pullRequest.html_url,
|
|
133
|
+
headSHA: candidate,
|
|
134
|
+
}
|
|
135
|
+
} catch (error) {
|
|
136
|
+
this.options.logger.warn("publication failed", {
|
|
137
|
+
jobID: input.jobID,
|
|
138
|
+
branch: input.branch,
|
|
139
|
+
error: error instanceof Error ? error.message : String(error),
|
|
140
|
+
})
|
|
141
|
+
return {
|
|
142
|
+
status: "failed",
|
|
143
|
+
branch: input.branch,
|
|
144
|
+
error: redact(error instanceof Error ? error.message : String(error)),
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
private async run(
|
|
150
|
+
cwd: string,
|
|
151
|
+
args: readonly string[],
|
|
152
|
+
options: CommandOptions = {},
|
|
153
|
+
): Promise<CommandResult> {
|
|
154
|
+
const result = await this.options.runner.run("git", args, {
|
|
155
|
+
cwd,
|
|
156
|
+
timeoutMs: 30_000,
|
|
157
|
+
...options,
|
|
158
|
+
env: { GIT_NO_REPLACE_OBJECTS: "1", ...options.env },
|
|
159
|
+
})
|
|
160
|
+
if (result.truncated === true) {
|
|
161
|
+
throw new Error(`Git publication scanner output was truncated while running ${args[0]}`)
|
|
162
|
+
}
|
|
163
|
+
return result
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
private async state(input: PublicationInput): Promise<{ clean: boolean; headSHA: string; dirtyFiles: string[] }> {
|
|
167
|
+
const status = await this.run(input.workspace.directory, ["status", "--porcelain=v1", "--untracked-files=all"])
|
|
168
|
+
if (status.exitCode !== 0) throw new CommandFailure(status)
|
|
169
|
+
const head = await this.run(input.workspace.directory, ["rev-parse", "HEAD"])
|
|
170
|
+
if (head.exitCode !== 0) throw new CommandFailure(head)
|
|
171
|
+
return {
|
|
172
|
+
clean: status.stdout.trim() === "",
|
|
173
|
+
headSHA: head.stdout.trim(),
|
|
174
|
+
dirtyFiles: status.stdout
|
|
175
|
+
.split(/\r?\n/u)
|
|
176
|
+
.map((line) => line.slice(3).trim())
|
|
177
|
+
.filter(Boolean),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
private async ensureObject(sha: string): Promise<void> {
|
|
182
|
+
if (!SHA.test(sha)) throw new Error(`Invalid Git object SHA ${sha}`)
|
|
183
|
+
const local = await this.run(this.options.canonicalDirectory, ["cat-file", "-e", `${sha}^{commit}`])
|
|
184
|
+
if (local.exitCode === 0) return
|
|
185
|
+
const fetched = await this.run(this.options.canonicalDirectory, ["fetch", "--no-tags", "--no-write-fetch-head", this.options.remote, sha], {
|
|
186
|
+
timeoutMs: 120_000,
|
|
187
|
+
env: { GIT_TERMINAL_PROMPT: "0" },
|
|
188
|
+
})
|
|
189
|
+
if (fetched.exitCode !== 0) throw new CommandFailure(fetched)
|
|
190
|
+
const verified = await this.run(this.options.canonicalDirectory, ["cat-file", "-e", `${sha}^{commit}`])
|
|
191
|
+
if (verified.exitCode !== 0) throw new CommandFailure(verified)
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
private async isAncestor(ancestor: string, descendant: string): Promise<boolean> {
|
|
195
|
+
await this.ensureObject(ancestor)
|
|
196
|
+
await this.ensureObject(descendant)
|
|
197
|
+
const result = await this.run(this.options.canonicalDirectory, ["merge-base", "--is-ancestor", ancestor, descendant])
|
|
198
|
+
if (result.exitCode === 0) return true
|
|
199
|
+
if (result.exitCode === 1) return false
|
|
200
|
+
throw new CommandFailure(result)
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
private async remoteBaseline(input: PublicationInput, candidate: string, baseBranch: string): Promise<string> {
|
|
204
|
+
const branchSHA = await this.remoteSHA(input.branch)
|
|
205
|
+
const baseSHA = await this.remoteSHA(baseBranch)
|
|
206
|
+
if (!baseSHA) throw new Error(`Remote base branch ${baseBranch} does not exist`)
|
|
207
|
+
if (branchSHA) {
|
|
208
|
+
if (branchSHA === candidate) return branchSHA
|
|
209
|
+
if (!(await this.isAncestor(branchSHA, candidate))) {
|
|
210
|
+
throw new Error("Taskfeed branch is not a fast-forward of the current remote branch")
|
|
211
|
+
}
|
|
212
|
+
return branchSHA
|
|
213
|
+
}
|
|
214
|
+
if (!(await this.isAncestor(baseSHA, candidate))) {
|
|
215
|
+
throw new Error("Candidate commit is not a fast-forward of the remote base branch")
|
|
216
|
+
}
|
|
217
|
+
return baseSHA
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
private async scanOutgoing(input: PublicationInput, baseline: string, candidate: string): Promise<string | undefined> {
|
|
221
|
+
const commits = await this.run(this.options.canonicalDirectory, [
|
|
222
|
+
"rev-list",
|
|
223
|
+
"--reverse",
|
|
224
|
+
`${baseline}..${candidate}`,
|
|
225
|
+
])
|
|
226
|
+
if (commits.exitCode !== 0) throw new CommandFailure(commits)
|
|
227
|
+
const commitIDs = commits.stdout.split(/\r?\n/u).filter(Boolean)
|
|
228
|
+
if (commitIDs.some((sha) => !SHA.test(sha))) throw new Error("Could not enumerate the complete outgoing commit history")
|
|
229
|
+
if (commitIDs.length === 0) return undefined
|
|
230
|
+
const objects = await this.run(
|
|
231
|
+
this.options.canonicalDirectory,
|
|
232
|
+
["rev-list", "--objects", "--no-object-names", `${baseline}..${candidate}`],
|
|
233
|
+
{ maxBytes: 16 * 1024 * 1024 },
|
|
234
|
+
)
|
|
235
|
+
if (objects.exitCode !== 0) throw new CommandFailure(objects)
|
|
236
|
+
const objectIDs = objects.stdout.split(/\r?\n/u).filter(Boolean)
|
|
237
|
+
if (objectIDs.some((sha) => !SHA.test(sha))) throw new Error("Could not enumerate all newly reachable Git objects")
|
|
238
|
+
const types = await this.run(
|
|
239
|
+
this.options.canonicalDirectory,
|
|
240
|
+
["cat-file", "--batch-check=%(objectname) %(objecttype) %(objectsize)"],
|
|
241
|
+
{ stdin: `${objectIDs.join("\n")}\n`, maxBytes: 16 * 1024 * 1024 },
|
|
242
|
+
)
|
|
243
|
+
if (types.exitCode !== 0) throw new CommandFailure(types)
|
|
244
|
+
const rows = types.stdout.split(/\r?\n/u).filter(Boolean)
|
|
245
|
+
if (rows.length !== objectIDs.length) throw new Error("Git object inspection was incomplete")
|
|
246
|
+
const protectedPatterns = this.options.protectedPaths.map(globToRegExp)
|
|
247
|
+
const generatedPatterns = (this.options.generatedArtifacts ?? []).map(globToRegExp)
|
|
248
|
+
const maxFileBytes = this.options.maxFileBytes ?? 1_048_576
|
|
249
|
+
const scannedBlobs = new Set<string>()
|
|
250
|
+
for (const row of rows) {
|
|
251
|
+
const [sha, type, sizeText] = row.split(" ")
|
|
252
|
+
if (!sha || !SHA.test(sha) || !type || !sizeText) throw new Error("Git object inspection returned an invalid record")
|
|
253
|
+
const size = Number(sizeText)
|
|
254
|
+
if (!Number.isSafeInteger(size) || size < 0) throw new Error(`Could not determine the size of Git object ${sha}`)
|
|
255
|
+
if (type === "tag") throw new Error("Annotated tags are not supported in Taskfeed publication history")
|
|
256
|
+
if (type !== "blob" && type !== "tree" && type !== "commit") {
|
|
257
|
+
throw new Error(`Unsupported Git object type ${type}`)
|
|
258
|
+
}
|
|
259
|
+
if (type !== "blob" || scannedBlobs.has(sha)) continue
|
|
260
|
+
scannedBlobs.add(sha)
|
|
261
|
+
if (size > maxFileBytes) return `Publication blocked: Git object ${sha} exceeds the ${maxFileBytes} byte review file limit`
|
|
262
|
+
const content = await this.run(this.options.canonicalDirectory, ["cat-file", "blob", sha], {
|
|
263
|
+
maxBytes: maxFileBytes + 1,
|
|
264
|
+
})
|
|
265
|
+
if (content.exitCode !== 0) throw new CommandFailure(content)
|
|
266
|
+
if (SECRET_CONTENT.some((pattern) => pattern.test(content.stdout))) {
|
|
267
|
+
return `Publication blocked: Git object ${sha} contains a probable secret`
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
for (const commit of commitIDs) {
|
|
271
|
+
const message = await this.run(this.options.canonicalDirectory, [
|
|
272
|
+
"show",
|
|
273
|
+
"-s",
|
|
274
|
+
"--format=%an%n%ae%n%cn%n%ce%n%B",
|
|
275
|
+
commit,
|
|
276
|
+
])
|
|
277
|
+
if (message.exitCode !== 0) throw new CommandFailure(message)
|
|
278
|
+
if (SECRET_CONTENT.some((pattern) => pattern.test(message.stdout))) {
|
|
279
|
+
return `Publication blocked: commit ${commit} message contains a probable secret`
|
|
280
|
+
}
|
|
281
|
+
const changed = await this.changedFiles(commit)
|
|
282
|
+
for (const file of changed) {
|
|
283
|
+
const paths = file.status === "D" ? [] : [file.path, ...(file.oldPath ? [file.oldPath] : [])]
|
|
284
|
+
if (paths.some((filePath) => protectedPatterns.some((pattern) => pattern.test(filePath)))) {
|
|
285
|
+
return `Publication blocked: protected path changed in commit ${commit} (${paths.join(", ")})`
|
|
286
|
+
}
|
|
287
|
+
const allPaths = [file.path, ...(file.oldPath ? [file.oldPath] : [])]
|
|
288
|
+
if (allPaths.some((filePath) => generatedPatterns.some((pattern) => pattern.test(filePath)))) {
|
|
289
|
+
return `Publication blocked: generated artifacts changed in commit ${commit} (${allPaths.join(", ")})`
|
|
290
|
+
}
|
|
291
|
+
if (file.status === "D") continue
|
|
292
|
+
const tree = await this.run(this.options.canonicalDirectory, ["ls-tree", "-z", commit, "--", file.path])
|
|
293
|
+
if (tree.exitCode !== 0) throw new CommandFailure(tree)
|
|
294
|
+
const record = tree.stdout.split("\0").find((entry) => entry.length > 0)
|
|
295
|
+
if (!record) throw new Error(`Could not inspect ${file.path} in commit ${commit}`)
|
|
296
|
+
const mode = record.split("\t")[0]?.split(" ")[0]
|
|
297
|
+
if (mode === "120000") return `Publication blocked: ${file.path} is a symbolic link in commit ${commit}`
|
|
298
|
+
if (mode === "160000") return `Publication blocked: ${file.path} is a Git submodule in commit ${commit}`
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
return undefined
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
private async changedFiles(commit: string): Promise<ChangedFile[]> {
|
|
305
|
+
const result = await this.run(
|
|
306
|
+
this.options.canonicalDirectory,
|
|
307
|
+
["diff-tree", "--no-commit-id", "--name-status", "-r", "-z", "-m", "--root", commit],
|
|
308
|
+
{ maxBytes: 8 * 1024 * 1024 },
|
|
309
|
+
)
|
|
310
|
+
if (result.exitCode !== 0) throw new CommandFailure(result)
|
|
311
|
+
const tokens = result.stdout.split("\0")
|
|
312
|
+
const files: ChangedFile[] = []
|
|
313
|
+
for (let index = 0; index < tokens.length; ) {
|
|
314
|
+
const status = tokens[index++]?.trim()
|
|
315
|
+
if (!status) break
|
|
316
|
+
if (status.startsWith("R") || status.startsWith("C")) {
|
|
317
|
+
const oldPath = tokens[index++]
|
|
318
|
+
const newPath = tokens[index++]
|
|
319
|
+
if (!oldPath || !newPath) throw new Error("Could not parse the renamed publication path")
|
|
320
|
+
this.assertSafePath(oldPath)
|
|
321
|
+
this.assertSafePath(newPath)
|
|
322
|
+
files.push({ status: status[0]!, path: newPath, oldPath })
|
|
323
|
+
continue
|
|
324
|
+
}
|
|
325
|
+
const file = tokens[index++]
|
|
326
|
+
if (!file) throw new Error("Could not parse the changed publication path")
|
|
327
|
+
this.assertSafePath(file)
|
|
328
|
+
files.push({ status: status[0]!, path: file })
|
|
329
|
+
}
|
|
330
|
+
return files
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
private assertSafePath(file: string): void {
|
|
334
|
+
if (file.startsWith("/") || file.split("/").some((segment) => segment === ".." || segment === "")) {
|
|
335
|
+
throw new Error(`Publication blocked: unsafe Git path ${file}`)
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
private async existingPullRequest(
|
|
340
|
+
input: PublicationInput,
|
|
341
|
+
candidate: string,
|
|
342
|
+
baseBranch: string,
|
|
343
|
+
): Promise<PullRequest | undefined> {
|
|
344
|
+
const pulls = await this.openPullRequests(input)
|
|
345
|
+
if (pulls.length === 0) return undefined
|
|
346
|
+
if (pulls.length > 1) throw new Error("Multiple open pull requests use the Taskfeed branch")
|
|
347
|
+
const found = await this.pullRequestDetail(input, pulls[0]!.number)
|
|
348
|
+
this.assertReusablePull(input, found, baseBranch)
|
|
349
|
+
if (found.head.sha !== candidate && !(await this.isAncestor(found.head.sha, candidate))) {
|
|
350
|
+
throw new Error("Existing pull request head is not a fast-forward ancestor of the validated commit")
|
|
351
|
+
}
|
|
352
|
+
return found
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
private assertReusablePull(input: PublicationInput, pull: PullRequest, baseBranch: string): void {
|
|
356
|
+
if (pull.state !== undefined && pull.state !== "open") {
|
|
357
|
+
throw new Error(`Existing pull request #${pull.number} is not open; Taskfeed will not modify its branch`)
|
|
358
|
+
}
|
|
359
|
+
if (pull.draft !== true) {
|
|
360
|
+
throw new Error(
|
|
361
|
+
`Existing pull request #${pull.number} is not a draft. Mark it as a draft or close it before Taskfeed can publish a review artifact.`,
|
|
362
|
+
)
|
|
363
|
+
}
|
|
364
|
+
if (pull.head.ref !== input.branch || pull.base.ref !== baseBranch) {
|
|
365
|
+
throw new Error(`Existing pull request #${pull.number} does not target the expected Taskfeed branch and base`)
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
private async push(input: PublicationInput, candidate: string): Promise<void> {
|
|
370
|
+
const ref = `refs/heads/${input.branch}`
|
|
371
|
+
const result = await this.run(input.workspace.directory, ["push", this.options.remote, `${candidate}:${ref}`], {
|
|
372
|
+
timeoutMs: 120_000,
|
|
373
|
+
env: { GIT_TERMINAL_PROMPT: "0" },
|
|
374
|
+
})
|
|
375
|
+
if (result.exitCode !== 0) {
|
|
376
|
+
throw new Error(`Git push failed; refusing to overwrite the remote branch: ${redact(result.stderr).trim()}`)
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
private async remoteSHA(branch: string): Promise<string | undefined> {
|
|
381
|
+
const result = await this.run(this.options.canonicalDirectory, ["ls-remote", this.options.remote, `refs/heads/${branch}`], {
|
|
382
|
+
env: { GIT_TERMINAL_PROMPT: "0" },
|
|
383
|
+
})
|
|
384
|
+
if (result.exitCode !== 0) throw new CommandFailure(result)
|
|
385
|
+
const line = result.stdout.trim().split(/\s+/u)[0]
|
|
386
|
+
return line || undefined
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
private async resolveBaseBranch(): Promise<string> {
|
|
390
|
+
if (this.options.baseBranch) return this.options.baseBranch
|
|
391
|
+
const local = await this.run(this.options.canonicalDirectory, ["symbolic-ref", "--short", "refs/remotes/origin/HEAD"])
|
|
392
|
+
if (local.exitCode === 0) {
|
|
393
|
+
const ref = local.stdout.trim().replace(/^origin\//u, "")
|
|
394
|
+
if (ref) return ref
|
|
395
|
+
}
|
|
396
|
+
const repo = await this.options.client.api<{ default_branch?: string }>(
|
|
397
|
+
`${repositoryPath(this.options.repository)}`,
|
|
398
|
+
)
|
|
399
|
+
if (!repo.default_branch) throw new Error("Could not resolve the GitHub default branch")
|
|
400
|
+
return repo.default_branch
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
private async openPullRequests(input: PublicationInput): Promise<readonly PullRequest[]> {
|
|
404
|
+
const owner = this.options.repository.split("/")[0]!
|
|
405
|
+
return await this.options.client.api<PullRequest[]>(
|
|
406
|
+
`${repositoryPath(this.options.repository)}/pulls?state=open&head=${encodeURIComponent(`${owner}:${input.branch}`)}`,
|
|
407
|
+
)
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
private async pullRequestDetail(input: PublicationInput, number: number): Promise<PullRequest> {
|
|
411
|
+
return await this.options.client.api<PullRequest>(`${repositoryPath(this.options.repository)}/pulls/${number}`)
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
private async ensurePullRequest(
|
|
415
|
+
input: PublicationInput,
|
|
416
|
+
headSHA: string,
|
|
417
|
+
baseBranch: string,
|
|
418
|
+
existing: PullRequest | undefined,
|
|
419
|
+
): Promise<PullRequest> {
|
|
420
|
+
if (existing) {
|
|
421
|
+
const found = await this.pullRequestDetail(input, existing.number)
|
|
422
|
+
this.assertReusablePull(input, found, baseBranch)
|
|
423
|
+
if (found.head.sha !== headSHA) throw new Error("Updated pull request head does not match the validated commit")
|
|
424
|
+
await this.updatePullRequestBody(found.number, this.body(input, found.number))
|
|
425
|
+
return found
|
|
426
|
+
}
|
|
427
|
+
const created = await this.options.client.api<PullRequest>(`${repositoryPath(this.options.repository)}/pulls`, {
|
|
428
|
+
method: "POST",
|
|
429
|
+
body: {
|
|
430
|
+
title: this.title(input),
|
|
431
|
+
head: input.branch,
|
|
432
|
+
base: baseBranch,
|
|
433
|
+
body: this.body(input),
|
|
434
|
+
draft: true,
|
|
435
|
+
},
|
|
436
|
+
})
|
|
437
|
+
if (created.draft !== true) throw new Error("GitHub did not create the Taskfeed pull request as a draft")
|
|
438
|
+
if (created.head.sha !== headSHA) throw new Error("Created pull request head does not match the validated commit")
|
|
439
|
+
return created
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
private async updatePullRequestBody(number: number, body: string): Promise<void> {
|
|
443
|
+
await this.options.client.api(`${repositoryPath(this.options.repository)}/pulls/${number}`, {
|
|
444
|
+
method: "PATCH",
|
|
445
|
+
body: { body },
|
|
446
|
+
})
|
|
447
|
+
}
|
|
448
|
+
|
|
449
|
+
private title(input: PublicationInput): string {
|
|
450
|
+
return `[Taskfeed] #${input.issueNumber} ${input.title}`.slice(0, 240)
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
private body(input: PublicationInput, number?: number): string {
|
|
454
|
+
const evidence = input.evidence
|
|
455
|
+
.map((item) => `- **${item.kind}**: ${item.value}`)
|
|
456
|
+
.join("\n")
|
|
457
|
+
return [
|
|
458
|
+
`Taskfeed draft review for #${input.issueNumber}`,
|
|
459
|
+
"",
|
|
460
|
+
`- Issue: ${input.issueURL}`,
|
|
461
|
+
`- Branch: \`${input.branch}\``,
|
|
462
|
+
`- Commit: \`${input.headSHA}\``,
|
|
463
|
+
...(number === undefined ? [] : [`- Pull request: #${number}`]),
|
|
464
|
+
"",
|
|
465
|
+
"## Summary",
|
|
466
|
+
"",
|
|
467
|
+
input.summary.trim() || "The configured agent completed without a textual summary.",
|
|
468
|
+
"",
|
|
469
|
+
"## Evidence",
|
|
470
|
+
"",
|
|
471
|
+
evidence || "- No evidence supplied.",
|
|
472
|
+
"",
|
|
473
|
+
"Taskfeed does not merge or deploy this pull request. Merge remains a human decision.",
|
|
474
|
+
`<!-- taskfeed:publication:${input.jobID} -->`,
|
|
475
|
+
].join("\n")
|
|
476
|
+
}
|
|
477
|
+
}
|