workrelay 0.0.0-stage → 1.0.0
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 +21 -0
- package/README.md +36 -2
- package/bin/workrelay.cjs +156 -0
- package/package.json +15 -4
- package/skills/workrelay/LICENSE +21 -0
- package/skills/workrelay/SKILL.md +39 -0
- package/skills/workrelay/VERSION +1 -0
- package/skills/workrelay/assets/development.example.json +19 -0
- package/skills/workrelay/assets/document-review.example.json +19 -0
- package/skills/workrelay/assets/verification-criteria.example.json +23 -0
- package/skills/workrelay/references/execution.md +21 -0
- package/skills/workrelay/references/merge.md +41 -0
- package/skills/workrelay/references/verification.md +13 -0
- package/skills/workrelay/scripts/handoff.rb +185 -0
- package/skills/workrelay/scripts/intake.rb +285 -0
- package/skills/workrelay/scripts/lib/github_merge.rb +190 -0
- package/skills/workrelay/scripts/lib/github_pull_request.rb +420 -0
- package/skills/workrelay/scripts/lib/registered_session.rb +147 -0
- package/skills/workrelay/scripts/merge.rb +183 -0
- package/skills/workrelay/scripts/route.rb +177 -0
- package/skills/workrelay/scripts/verify.rb +382 -0
|
@@ -0,0 +1,420 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'json'
|
|
4
|
+
require 'open3'
|
|
5
|
+
require 'uri'
|
|
6
|
+
require_relative '../intake'
|
|
7
|
+
|
|
8
|
+
# Reconcile one local WorkRelay task with a same-repository GitHub pull request.
|
|
9
|
+
# GitHub is the source of truth: this helper does not store or trust a cached PR URL.
|
|
10
|
+
class ResumePullRequest
|
|
11
|
+
SHA = /\A[0-9a-f]{40}\z/
|
|
12
|
+
TARGET = %r{\A[A-Za-z0-9][A-Za-z0-9-]*/[A-Za-z0-9_.-]+\z}
|
|
13
|
+
ORIGIN = %r{\A(?:https://github\.com/|git@github\.com:|ssh://git@github\.com/)([^/]+/[^/]+)\z}i
|
|
14
|
+
BODY_LIMIT = 64 * 1024
|
|
15
|
+
# Preserve normal git config/remote semantics but ignore inherited repository,
|
|
16
|
+
# index, ref and command-line config overrides. Never take optional write locks.
|
|
17
|
+
GIT_OVERRIDES = %w[GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_CONFIG GIT_CONFIG_PARAMETERS GIT_CONFIG_COUNT
|
|
18
|
+
GIT_OBJECT_DIRECTORY GIT_DIR GIT_WORK_TREE GIT_IMPLICIT_WORK_TREE GIT_GRAFT_FILE
|
|
19
|
+
GIT_INDEX_FILE GIT_REPLACE_REF_BASE GIT_PREFIX GIT_SHALLOW_FILE GIT_COMMON_DIR
|
|
20
|
+
GIT_NAMESPACE GIT_CEILING_DIRECTORIES GIT_DISCOVERY_ACROSS_FILESYSTEM].freeze
|
|
21
|
+
GITHUB_ENV = { 'GH_PROMPT_DISABLED' => '1', 'GH_NO_UPDATE_NOTIFIER' => '1' }.freeze
|
|
22
|
+
|
|
23
|
+
class Blocked < StandardError; end
|
|
24
|
+
class Ambiguous < Blocked; end
|
|
25
|
+
class HeadChanged < Blocked; end
|
|
26
|
+
class ApiFailure < Blocked
|
|
27
|
+
attr_reader :http_status
|
|
28
|
+
|
|
29
|
+
def initialize(http_status)
|
|
30
|
+
@http_status = http_status
|
|
31
|
+
super(http_status ? "GitHub lookup failed (HTTP #{http_status}). Check access and retry." :
|
|
32
|
+
'GitHub request failed. Check gh authentication and connectivity before retrying.')
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
attr_reader :observation
|
|
37
|
+
|
|
38
|
+
def self.git_read(worktree, *argv)
|
|
39
|
+
env = GIT_OVERRIDES.each_with_object({}) { |key, config| config[key] = nil }
|
|
40
|
+
env.update('GIT_OPTIONAL_LOCKS' => '0', 'GIT_NO_REPLACE_OBJECTS' => '1')
|
|
41
|
+
stdout, _, process = Open3.capture3(env, 'git', '-C', worktree, '-c', 'core.fsmonitor=false', *argv)
|
|
42
|
+
raise Blocked, 'Cannot verify the local Git worktree or origin configuration.' unless process.success?
|
|
43
|
+
|
|
44
|
+
stdout
|
|
45
|
+
rescue Errno::ENOENT
|
|
46
|
+
raise Blocked, 'Git is required to verify the worktree and origin.'
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
def initialize(options)
|
|
50
|
+
@options = options
|
|
51
|
+
@target = options[:target]
|
|
52
|
+
@base = options[:base]
|
|
53
|
+
@head = options[:head]
|
|
54
|
+
@worktree = options[:worktree]
|
|
55
|
+
@verified_head = options[:verified_head]
|
|
56
|
+
@portable = options[:portable_handoff]
|
|
57
|
+
@result = {
|
|
58
|
+
status: nil, task: options[:task], branch: @head, worktree: @worktree, prUrl: nil,
|
|
59
|
+
localHead: options[:local_head], remoteHead: nil, prHead: nil, verifiedHead: @verified_head, nextAction: nil
|
|
60
|
+
}
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def run
|
|
64
|
+
if @portable
|
|
65
|
+
unless @target.is_a?(String) && TARGET.match?(@target) &&
|
|
66
|
+
@target.split('/').none? { |part| %w[. ..].include?(part) }
|
|
67
|
+
raise Blocked, 'Choose a canonical github.com repository.'
|
|
68
|
+
end
|
|
69
|
+
unless @verified_head.is_a?(String) && SHA.match?(@verified_head)
|
|
70
|
+
raise Blocked, 'A verified Git commit SHA is required for handoff.'
|
|
71
|
+
end
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
verify_local
|
|
75
|
+
verify_repository
|
|
76
|
+
pr = unique_pull(check_other_base: @portable)
|
|
77
|
+
outcome = reconcile(pr)
|
|
78
|
+
return outcome if outcome
|
|
79
|
+
|
|
80
|
+
unless @options[:open_pr]
|
|
81
|
+
option = @portable ? '--publish' : '--open-pr'
|
|
82
|
+
return result('no_pr', "No matching PR exists; use #{option} after verifying and pushing the branch.", @portable ? 1 : 0)
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
open_pull
|
|
86
|
+
rescue Ambiguous => e
|
|
87
|
+
result('ambiguous', e.message, 1)
|
|
88
|
+
rescue HeadChanged => e
|
|
89
|
+
result('head_changed', e.message, 1)
|
|
90
|
+
rescue Blocked => e
|
|
91
|
+
result('blocked', e.message, 1)
|
|
92
|
+
rescue SystemCallError, IOError, EncodingError
|
|
93
|
+
result('blocked', 'Cannot read the worktree or publication inputs. Check local paths and permissions.', 1)
|
|
94
|
+
end
|
|
95
|
+
|
|
96
|
+
# Validate the exact checkout independently of any GitHub lookup or mutation.
|
|
97
|
+
def verify_checkout!
|
|
98
|
+
verify_local
|
|
99
|
+
verify_origin
|
|
100
|
+
end
|
|
101
|
+
|
|
102
|
+
private
|
|
103
|
+
|
|
104
|
+
def result(state, next_action, code = 0)
|
|
105
|
+
@observation = @result.merge(status: state, nextAction: next_action)
|
|
106
|
+
code
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def git(*argv)
|
|
110
|
+
return self.class.git_read(@worktree, *argv) if @portable
|
|
111
|
+
|
|
112
|
+
stdout, _, process = Open3.capture3('git', '-C', @worktree, *argv)
|
|
113
|
+
raise Blocked, 'Cannot verify the local Git worktree or origin configuration.' unless process.success?
|
|
114
|
+
|
|
115
|
+
stdout
|
|
116
|
+
rescue Errno::ENOENT
|
|
117
|
+
raise Blocked, 'Git is required to verify the worktree and origin.'
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def verify_origin
|
|
121
|
+
urls = [git('remote', 'get-url', '--all', 'origin'), git('remote', 'get-url', '--push', '--all', 'origin')]
|
|
122
|
+
same_origin = urls.all? do |each|
|
|
123
|
+
remotes = each.lines.map(&:chomp)
|
|
124
|
+
name = remotes.length == 1 && ORIGIN.match(remotes.first)&.[](1)
|
|
125
|
+
name && name.sub(/\.git\z/i, '').casecmp?(@target)
|
|
126
|
+
end
|
|
127
|
+
unless same_origin
|
|
128
|
+
raise Blocked, 'The origin fetch and push destinations must both be the requested github.com repository.'
|
|
129
|
+
end
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def verify_repository
|
|
133
|
+
verify_origin
|
|
134
|
+
repo = github("repos/#{@target}")
|
|
135
|
+
raise Blocked, 'The requested repository must be a canonical github.com target.' unless same_repo?(repo)
|
|
136
|
+
if @portable && @options[:open_pr]
|
|
137
|
+
permissions = repo['permissions']
|
|
138
|
+
unless permissions.is_a?(Hash) && permissions['push'] == true
|
|
139
|
+
raise Blocked, 'GitHub did not confirm write access to the requested repository; no PR was opened.'
|
|
140
|
+
end
|
|
141
|
+
end
|
|
142
|
+
end
|
|
143
|
+
|
|
144
|
+
def verify_local
|
|
145
|
+
refs_valid = [@base, @head].all? do |branch|
|
|
146
|
+
_, _, status = Open3.capture3('git', 'check-ref-format', "refs/heads/#{branch}")
|
|
147
|
+
status.success?
|
|
148
|
+
end
|
|
149
|
+
unless refs_valid && @base != @head && !@base.start_with?('-') && !@head.start_with?('-')
|
|
150
|
+
raise Blocked, 'Choose distinct, valid base and head branch names.'
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
actual_top = git('rev-parse', '--show-toplevel').chomp
|
|
154
|
+
unless File.realpath(actual_top) == File.realpath(@worktree) &&
|
|
155
|
+
git('symbolic-ref', '--quiet', 'HEAD').chomp == "refs/heads/#{@head}"
|
|
156
|
+
raise Blocked, 'The current checkout does not match the recorded task worktree and branch.'
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
actual_head = git('rev-parse', '--verify', 'HEAD^{commit}').chomp
|
|
160
|
+
raise Blocked, 'The local Git HEAD is not a GitHub commit SHA.' unless SHA.match?(actual_head)
|
|
161
|
+
|
|
162
|
+
if actual_head != @options[:local_head]
|
|
163
|
+
@result[:localHead] = actual_head
|
|
164
|
+
raise HeadChanged, 'The local worktree HEAD changed during resume. Re-run resume and review the current checkout.'
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
if @portable
|
|
168
|
+
raise HeadChanged, 'The local worktree HEAD is not the verified commit.' unless actual_head == @verified_head
|
|
169
|
+
|
|
170
|
+
verify_clean
|
|
171
|
+
end
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def verify_clean
|
|
175
|
+
args = ['status', '--porcelain', '--untracked-files=all']
|
|
176
|
+
args << '--ignore-submodules=none' if @portable
|
|
177
|
+
unless git(*args).empty?
|
|
178
|
+
raise Blocked, 'The task worktree must be clean before handing off a pull request.'
|
|
179
|
+
end
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
def github(*argv, input: '')
|
|
183
|
+
stdout, stderr, process = Open3.capture3(GITHUB_ENV, 'gh', 'api', '--hostname', 'github.com', *argv, stdin_data: input)
|
|
184
|
+
raise ApiFailure, stderr[/\(HTTP (\d{3})\)/, 1] unless process.success?
|
|
185
|
+
|
|
186
|
+
JSON.parse(stdout)
|
|
187
|
+
rescue Errno::ENOENT
|
|
188
|
+
raise Blocked, 'GitHub CLI (gh) is required to reconcile a pull request.'
|
|
189
|
+
rescue JSON::ParserError
|
|
190
|
+
raise Blocked, 'GitHub returned an invalid response. Do not create a replacement PR.'
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def same_repo?(object)
|
|
194
|
+
object.is_a?(Hash) && object['full_name'].is_a?(String) && object['full_name'].casecmp?(@target)
|
|
195
|
+
end
|
|
196
|
+
|
|
197
|
+
def unique_pull(check_other_base: false)
|
|
198
|
+
owner = @target.split('/').first
|
|
199
|
+
filters = ['-f', 'state=all', '-f', "head=#{owner}:#{@head}", '-f', 'per_page=100']
|
|
200
|
+
filters.concat(['-f', "base=#{@base}"]) unless check_other_base
|
|
201
|
+
pages = github('--paginate', '--slurp', '--method', 'GET', pulls_path, *filters)
|
|
202
|
+
unless pages.is_a?(Array) && !pages.empty? && pages.all? { |page| page.is_a?(Array) }
|
|
203
|
+
raise Blocked, 'Cannot verify that all pull request results were read.'
|
|
204
|
+
end
|
|
205
|
+
|
|
206
|
+
matches = pages.flatten(1).select { |pull| matching_pull?(pull, exact_base: !check_other_base) }
|
|
207
|
+
if check_other_base && matches.any? { |pull| pull.dig('base', 'ref') != @base }
|
|
208
|
+
raise Blocked, 'This branch already has a PR against another base. Review the target on GitHub; no PR was opened.'
|
|
209
|
+
end
|
|
210
|
+
if matches.length > 1
|
|
211
|
+
raise Ambiguous, 'Multiple PRs match the same repository, base, and head. Resolve the ambiguity on GitHub.'
|
|
212
|
+
end
|
|
213
|
+
|
|
214
|
+
matches.first
|
|
215
|
+
end
|
|
216
|
+
|
|
217
|
+
def matching_pull?(pull, exact_base: true)
|
|
218
|
+
unless pull.is_a?(Hash) && pull['base'].is_a?(Hash) && pull['head'].is_a?(Hash) &&
|
|
219
|
+
pull['base']['ref'].is_a?(String) && pull['head']['ref'].is_a?(String)
|
|
220
|
+
raise Blocked, 'GitHub returned a pull request with incomplete branch identity.'
|
|
221
|
+
end
|
|
222
|
+
return false if pull['head']['ref'] != @head || (exact_base && pull['base']['ref'] != @base)
|
|
223
|
+
|
|
224
|
+
unless same_repo?(pull['base']['repo']) && pull['head']['repo'].is_a?(Hash) &&
|
|
225
|
+
pull['head']['repo']['full_name'].is_a?(String)
|
|
226
|
+
raise Blocked, 'GitHub returned a pull request with incomplete repository identity.'
|
|
227
|
+
end
|
|
228
|
+
|
|
229
|
+
same_repo?(pull['head']['repo'])
|
|
230
|
+
end
|
|
231
|
+
|
|
232
|
+
def pulls_path
|
|
233
|
+
"repos/#{@target}/pulls"
|
|
234
|
+
end
|
|
235
|
+
|
|
236
|
+
def branch_sha(branch)
|
|
237
|
+
encoded = branch.split('/').map { |part| URI.encode_www_form_component(part) }.join('/')
|
|
238
|
+
reference = github("repos/#{@target}/git/ref/heads/#{encoded}")
|
|
239
|
+
object = reference.is_a?(Hash) && reference['object']
|
|
240
|
+
unless object.is_a?(Hash) && reference['ref'] == "refs/heads/#{branch}" && object['type'] == 'commit' &&
|
|
241
|
+
SHA.match?(object['sha'].to_s)
|
|
242
|
+
raise Blocked, 'GitHub returned an unexpected branch reference.'
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
object['sha']
|
|
246
|
+
rescue ApiFailure => e
|
|
247
|
+
raise unless e.http_status == '404'
|
|
248
|
+
|
|
249
|
+
nil
|
|
250
|
+
end
|
|
251
|
+
|
|
252
|
+
def remember_pull(pull)
|
|
253
|
+
number = pull['number']
|
|
254
|
+
url = pull['html_url']
|
|
255
|
+
sha = pull.dig('head', 'sha')
|
|
256
|
+
unless number.is_a?(Integer) && number.positive? && url.is_a?(String) &&
|
|
257
|
+
url.casecmp?("https://github.com/#{@target}/pull/#{number}") && SHA.match?(sha.to_s)
|
|
258
|
+
raise Blocked, 'GitHub returned an unexpected pull request identity.'
|
|
259
|
+
end
|
|
260
|
+
|
|
261
|
+
@result[:prUrl] = url
|
|
262
|
+
@result[:prHead] = sha
|
|
263
|
+
number
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
def reconcile(pull, opened_status: 'open', after_post: false)
|
|
267
|
+
@result[:prUrl] = @result[:remoteHead] = @result[:prHead] = nil
|
|
268
|
+
if pull
|
|
269
|
+
number = remember_pull(pull)
|
|
270
|
+
if pull['state'] == 'closed'
|
|
271
|
+
detail = github("#{pulls_path}/#{number}")
|
|
272
|
+
unless matching_pull?(detail) && detail['number'] == number && detail['state'] == 'closed' &&
|
|
273
|
+
[true, false].include?(detail['merged'])
|
|
274
|
+
raise Blocked, 'Pull request state changed during reconciliation; re-run resume.'
|
|
275
|
+
end
|
|
276
|
+
remember_pull(detail)
|
|
277
|
+
if after_post && @result[:prHead] != @verified_head
|
|
278
|
+
return result('head_changed', 'The PR was recorded but its HEAD differs from the verified SHA. Inspect the PR; do not retry.', 1)
|
|
279
|
+
end
|
|
280
|
+
different_local = @result[:prHead] != @result[:localHead]
|
|
281
|
+
local_note = different_local ? ' Local HEAD differs from the terminal PR HEAD; inspect it separately.' : ''
|
|
282
|
+
if detail['merged']
|
|
283
|
+
return result('merged', "The matching PR was already merged; do not create another PR.#{local_note}", @portable ? 1 : 0)
|
|
284
|
+
end
|
|
285
|
+
|
|
286
|
+
return result('closed', "The matching PR was closed without merging; review it before making further changes.#{local_note}", 1)
|
|
287
|
+
end
|
|
288
|
+
raise Blocked, 'GitHub returned an unknown pull request state.' unless pull['state'] == 'open'
|
|
289
|
+
if @portable
|
|
290
|
+
return result('draft', 'The matching pull request is a draft, not an open handoff.', 1) if pull['draft'] == true
|
|
291
|
+
raise Blocked, 'GitHub did not confirm a non-draft open pull request; do not hand it off.' unless pull['draft'] == false
|
|
292
|
+
end
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
raise Blocked, 'The base branch is missing or inaccessible on GitHub.' unless branch_sha(@base)
|
|
296
|
+
|
|
297
|
+
@result[:remoteHead] = branch_sha(@head)
|
|
298
|
+
unless @result[:remoteHead]
|
|
299
|
+
return result('remote_head_missing', 'The matching head branch is not published. Verify the destination before publishing it.', 1)
|
|
300
|
+
end
|
|
301
|
+
|
|
302
|
+
heads = [@result[:localHead], @result[:remoteHead], @verified_head, pull && pull.dig('head', 'sha')].compact
|
|
303
|
+
if heads.uniq.length != 1
|
|
304
|
+
return result('head_changed', 'Local, remote, PR, or verified HEAD differ. Inspect and re-verify before publication.', 1)
|
|
305
|
+
end
|
|
306
|
+
|
|
307
|
+
if @options[:open_pr] && !@verified_head
|
|
308
|
+
raise Blocked, 'An explicit verified HEAD SHA is required to open a pull request.'
|
|
309
|
+
end
|
|
310
|
+
|
|
311
|
+
if pull
|
|
312
|
+
if @portable
|
|
313
|
+
outcome = confirm_open_pull(number)
|
|
314
|
+
return outcome if outcome
|
|
315
|
+
|
|
316
|
+
verify_local
|
|
317
|
+
end
|
|
318
|
+
message = @verified_head ? 'Reuse the matching open PR; no additional PR is needed.' :
|
|
319
|
+
'Reuse the matching open PR, but obtain verification for the current HEAD.'
|
|
320
|
+
return result(opened_status, message)
|
|
321
|
+
end
|
|
322
|
+
|
|
323
|
+
nil
|
|
324
|
+
end
|
|
325
|
+
|
|
326
|
+
# Read the specific PR after the ref checks so a close, draft, retarget or
|
|
327
|
+
# force-push between listing and reading the refs cannot be treated as success.
|
|
328
|
+
def confirm_open_pull(number)
|
|
329
|
+
detail = github("#{pulls_path}/#{number}")
|
|
330
|
+
unless matching_pull?(detail) && detail['number'] == number && detail['html_url'] == @result[:prUrl]
|
|
331
|
+
raise Blocked, 'The pull request identity changed after lookup; do not hand it off.'
|
|
332
|
+
end
|
|
333
|
+
remember_pull(detail)
|
|
334
|
+
if detail['state'] == 'closed' && [true, false].include?(detail['merged'])
|
|
335
|
+
return result('merged', 'The pull request was merged during handoff; do not create another PR.', 1) if detail['merged']
|
|
336
|
+
|
|
337
|
+
return result('closed', 'The pull request was closed during handoff; do not create another PR.', 1)
|
|
338
|
+
end
|
|
339
|
+
raise Blocked, 'GitHub did not confirm the pull request is open.' unless detail['state'] == 'open'
|
|
340
|
+
|
|
341
|
+
return result('draft', 'The pull request is a draft, not an open handoff.', 1) if detail['draft'] == true
|
|
342
|
+
|
|
343
|
+
raise Blocked, 'GitHub did not confirm a non-draft open pull request.' unless detail['draft'] == false
|
|
344
|
+
if @result[:prHead] != @verified_head
|
|
345
|
+
return result('head_changed', 'The pull request HEAD changed after lookup; re-verify before handing it off.', 1)
|
|
346
|
+
end
|
|
347
|
+
|
|
348
|
+
nil
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
def reviewed_body
|
|
352
|
+
unless @portable
|
|
353
|
+
body = File.read(@options.fetch(:body_file), encoding: 'UTF-8')
|
|
354
|
+
raise Blocked, 'The PR body file must be valid UTF-8.' unless body.valid_encoding?
|
|
355
|
+
|
|
356
|
+
return body
|
|
357
|
+
end
|
|
358
|
+
|
|
359
|
+
body = @options[:body]
|
|
360
|
+
if body.nil? && @options[:body_file].is_a?(String)
|
|
361
|
+
body = WorkRelayIntake.read_regular(@options[:body_file], BODY_LIMIT, 'PR body')
|
|
362
|
+
end
|
|
363
|
+
unless body.is_a?(String) && body.encoding == Encoding::UTF_8 && body.valid_encoding? &&
|
|
364
|
+
body.bytesize <= BODY_LIMIT && !body.include?("\0") && !body.strip.empty?
|
|
365
|
+
raise Blocked, 'The reviewed PR body must be nonempty, bounded UTF-8 text.'
|
|
366
|
+
end
|
|
367
|
+
|
|
368
|
+
body
|
|
369
|
+
rescue WorkRelayIntake::InvalidInput => e
|
|
370
|
+
raise Blocked, e.message
|
|
371
|
+
end
|
|
372
|
+
|
|
373
|
+
def open_pull
|
|
374
|
+
if @portable
|
|
375
|
+
title = @options[:title]
|
|
376
|
+
unless title.is_a?(String) && title.valid_encoding? && title.bytesize <= 256 &&
|
|
377
|
+
!title.strip.empty? && !title.match?(/[[:cntrl:]]/)
|
|
378
|
+
raise Blocked, 'A reviewed PR title is required.'
|
|
379
|
+
end
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
payload = JSON.generate(base: @base, head: @head, title: @options.fetch(:title), body: reviewed_body)
|
|
383
|
+
verify_repository
|
|
384
|
+
outcome = reconcile(unique_pull(check_other_base: true))
|
|
385
|
+
return outcome if outcome
|
|
386
|
+
|
|
387
|
+
@options[:before_publish]&.call if @portable
|
|
388
|
+
verify_local
|
|
389
|
+
unless @portable || git('status', '--porcelain', '--untracked-files=all').empty?
|
|
390
|
+
raise Blocked, 'The task worktree must be clean before opening a pull request.'
|
|
391
|
+
end
|
|
392
|
+
|
|
393
|
+
# GitHub's create API accepts branch names, not a compare-and-set HEAD.
|
|
394
|
+
# Reconcile the result (including a failed response) without a second POST.
|
|
395
|
+
failure = nil
|
|
396
|
+
created = begin
|
|
397
|
+
github('--method', 'POST', pulls_path, '--input', '-', input: payload)
|
|
398
|
+
rescue Blocked => e
|
|
399
|
+
failure = e
|
|
400
|
+
nil
|
|
401
|
+
end
|
|
402
|
+
|
|
403
|
+
pull = unique_pull(check_other_base: @portable)
|
|
404
|
+
unless pull
|
|
405
|
+
operation = @portable ? 'handoff' : 'resume'
|
|
406
|
+
message = "PR creation could not be confirmed from GitHub. No retry was sent; re-run #{operation} to reconcile."
|
|
407
|
+
raise Blocked, [message, failure&.message].compact.join(' ')
|
|
408
|
+
end
|
|
409
|
+
|
|
410
|
+
number = remember_pull(pull)
|
|
411
|
+
if created.is_a?(Hash) && created['number'].is_a?(Integer) && created['number'] != number
|
|
412
|
+
raise Blocked, 'GitHub returned conflicting PR identities. Inspect the remote; no retry was sent.'
|
|
413
|
+
end
|
|
414
|
+
# Portable reconciliation rechecks the local state after the final remote
|
|
415
|
+
# read; the legacy flow retains its pre-reconcile recheck.
|
|
416
|
+
verify_local unless @portable
|
|
417
|
+
opened_status = created.is_a?(Hash) && created['number'] == number ? 'created' : 'open'
|
|
418
|
+
reconcile(pull, opened_status: opened_status, after_post: true)
|
|
419
|
+
end
|
|
420
|
+
end
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'yaml'
|
|
4
|
+
require_relative '../verify'
|
|
5
|
+
require_relative 'github_pull_request'
|
|
6
|
+
|
|
7
|
+
# Resolve existing local workspace records; never prepare or start an agent.
|
|
8
|
+
module WorkRelaySession
|
|
9
|
+
InvalidInput = WorkRelayVerify::InvalidInput
|
|
10
|
+
LEGACY_ID = /\A[A-Za-z0-9][A-Za-z0-9._-]{0,63}\z/
|
|
11
|
+
AUTOMATED_SECTION = /^## Automated request \/ 자동 요청\n/
|
|
12
|
+
REQUEST_SECTION = /^### User request \/ 사용자 요청\n\n/
|
|
13
|
+
|
|
14
|
+
module_function
|
|
15
|
+
|
|
16
|
+
def resolve(file, intake)
|
|
17
|
+
metadata_path = input_path(File.expand_path(file), 'Session record', :file)
|
|
18
|
+
raw = WorkRelayVerify.read_private(metadata_path, 'Session record')
|
|
19
|
+
session = WorkRelayVerify.json(raw, 'Session record')
|
|
20
|
+
unless session.is_a?(Hash) && session['version'].is_a?(Integer) && session['version'] == 1 &&
|
|
21
|
+
session['taskSlug'] == intake.task && LEGACY_ID.match?(intake.task)
|
|
22
|
+
raise InvalidInput, 'Session version or task does not match the intake.'
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
repo, agent = session.values_at('repo', 'agent')
|
|
26
|
+
unless [repo, agent].all? { |id| id.is_a?(String) && LEGACY_ID.match?(id) }
|
|
27
|
+
raise InvalidInput, 'Invalid registered repo or agent identifier.'
|
|
28
|
+
end
|
|
29
|
+
branch = WorkRelayIntake.descriptive_text(session['branch'], 'Registered branch')
|
|
30
|
+
tmux = WorkRelayIntake.descriptive_text(session['tmuxSession'], 'Registered session name')
|
|
31
|
+
config_path = input_path(session['configPath'], 'Session configuration', :file)
|
|
32
|
+
config = YAML.safe_load(WorkRelayIntake.read_regular(config_path, WorkRelayVerify::INPUT_LIMIT, 'Session configuration'),
|
|
33
|
+
permitted_classes: [], permitted_symbols: [], aliases: false)
|
|
34
|
+
roots, repo_path = configured_paths(config, config_path, repo)
|
|
35
|
+
expected_metadata = File.join(roots.fetch('sessionsDir'), repo, "#{agent}-#{intake.task}.json")
|
|
36
|
+
unless metadata_path == expected_metadata
|
|
37
|
+
raise InvalidInput, 'Use the original configured session record for this repo and task.'
|
|
38
|
+
end
|
|
39
|
+
if input_path(session['repoPath'], 'Registered repo path', :directory) != repo_path
|
|
40
|
+
raise InvalidInput, 'Registered repo path does not match the workspace configuration.'
|
|
41
|
+
end
|
|
42
|
+
|
|
43
|
+
checkout = contained_path(session['worktreePath'], roots.fetch('worktreesDir'), 'Registered worktree', :directory)
|
|
44
|
+
unless intake.workspace['mode'] == 'worktree' && checkout == intake.workspace['path']
|
|
45
|
+
raise InvalidInput, 'Registered worktree does not match the workspace in the intake.'
|
|
46
|
+
end
|
|
47
|
+
verify_worktree(repo_path, checkout, branch)
|
|
48
|
+
|
|
49
|
+
prompt = contained_path(session['promptPath'], roots.fetch('promptsDir'), 'Registered prompt', :file)
|
|
50
|
+
prompt_sha = verify_prompt(prompt, intake.source)
|
|
51
|
+
logs = contained_path(session['logDir'], roots.fetch('logsDir'), 'Registered log directory', :directory)
|
|
52
|
+
summary = contained_path(session['summaryPath'], logs, 'Registered summary', :file)
|
|
53
|
+
|
|
54
|
+
{ 'sessionPath' => metadata_path, 'sessionSha256' => Digest::SHA256.hexdigest(raw), 'repo' => repo,
|
|
55
|
+
'repoPath' => repo_path, 'worktreePath' => checkout, 'promptPath' => prompt, 'promptSha256' => prompt_sha,
|
|
56
|
+
'logDir' => logs,
|
|
57
|
+
'summaryPath' => summary, 'agent' => agent, 'branch' => branch, 'tmuxSession' => tmux }
|
|
58
|
+
rescue Psych::Exception
|
|
59
|
+
raise InvalidInput, 'Cannot read the registered session configuration as plain YAML.'
|
|
60
|
+
rescue SystemCallError, ArgumentError
|
|
61
|
+
raise InvalidInput, 'Cannot locate the original registered session artifacts.'
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def input_path(path, label, kind)
|
|
65
|
+
unless path.is_a?(String) && path.start_with?('/') && !path.match?(/[[:cntrl:]]/)
|
|
66
|
+
raise InvalidInput, "#{label} must be an absolute path."
|
|
67
|
+
end
|
|
68
|
+
|
|
69
|
+
stat = File.lstat(path)
|
|
70
|
+
correct_type = kind == :directory ? stat.directory? : stat.file?
|
|
71
|
+
unless correct_type && stat.uid == Process.euid && (stat.mode & 0o022).zero?
|
|
72
|
+
raise InvalidInput, "#{label} must be an existing user-owned #{kind}, not writable by others."
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
File.realpath(path)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def contained_path(path, parent, label, kind, allow_root: false)
|
|
79
|
+
real = input_path(path, label, kind)
|
|
80
|
+
return real if real == parent ? allow_root : real.start_with?(parent == '/' ? '/' : "#{parent}/")
|
|
81
|
+
|
|
82
|
+
raise InvalidInput, "#{label} is outside its configured directory."
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def absolute_path(value, base, label)
|
|
86
|
+
File.expand_path(WorkRelayIntake.descriptive_text(value, label), base)
|
|
87
|
+
end
|
|
88
|
+
|
|
89
|
+
def configured_paths(config, config_path, repo)
|
|
90
|
+
unless config.is_a?(Hash) && config['version'].is_a?(Integer) && config['version'] == 1 &&
|
|
91
|
+
config['workspace'].is_a?(Hash) && config['repos'].is_a?(Hash) && config['repos'][repo].is_a?(Hash)
|
|
92
|
+
raise InvalidInput, 'Session configuration must contain a version 1 workspace and the registered repo.'
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
workspace = config['workspace']
|
|
96
|
+
root = input_path(absolute_path(workspace['root'], File.dirname(config_path), 'Workspace root'),
|
|
97
|
+
'Workspace root', :directory)
|
|
98
|
+
roots = %w[worktreesDir promptsDir logsDir sessionsDir].each_with_object({}) do |key, result|
|
|
99
|
+
parent = key == 'sessionsDir' ? result.fetch('logsDir') : root
|
|
100
|
+
path = absolute_path(workspace[key], root, 'Configured workspace subdirectory')
|
|
101
|
+
# The legacy config permits a directory itself as the root (e.g., sessionsDir equal to logsDir).
|
|
102
|
+
result[key] = contained_path(path, parent, 'Configured workspace subdirectory', :directory, allow_root: true)
|
|
103
|
+
end
|
|
104
|
+
local_repo = WorkRelayIntake.descriptive_text(config['repos'][repo]['path'], 'Configured repo path')
|
|
105
|
+
raise InvalidInput, 'Configured repo path must be relative to the workspace.' if local_repo.start_with?('/')
|
|
106
|
+
|
|
107
|
+
repo_path = contained_path(File.expand_path(local_repo, root), root, 'Configured repo path', :directory, allow_root: true)
|
|
108
|
+
[roots, repo_path]
|
|
109
|
+
end
|
|
110
|
+
|
|
111
|
+
def verify_worktree(repo, checkout, branch)
|
|
112
|
+
git = ResumePullRequest.method(:git_read)
|
|
113
|
+
unless checkout != repo && File.lstat(File.join(checkout, '.git')).file? &&
|
|
114
|
+
git.call(repo, 'rev-parse', '--show-toplevel').chomp == repo &&
|
|
115
|
+
git.call(checkout, 'rev-parse', '--show-toplevel').chomp == checkout &&
|
|
116
|
+
git.call(checkout, 'symbolic-ref', '--quiet', 'HEAD').chomp == "refs/heads/#{branch}" &&
|
|
117
|
+
File.realpath(git.call(repo, 'rev-parse', '--path-format=absolute', '--git-common-dir').chomp) ==
|
|
118
|
+
File.realpath(git.call(checkout, 'rev-parse', '--path-format=absolute', '--git-common-dir').chomp)
|
|
119
|
+
raise InvalidInput, 'The linked Git checkout, repo and branch do not match the registered session.'
|
|
120
|
+
end
|
|
121
|
+
|
|
122
|
+
rows = git.call(repo, 'worktree', 'list', '--porcelain', '-z').split("\0\0")
|
|
123
|
+
fields = ["worktree #{checkout}", "branch refs/heads/#{branch}"]
|
|
124
|
+
unless rows.any? { |row| (fields - row.split("\0")).empty? && !row.match?(/(?:\A|\0)prunable(?: |\z)/) }
|
|
125
|
+
raise InvalidInput, 'The worktree is not registered under the recorded branch.'
|
|
126
|
+
end
|
|
127
|
+
rescue ResumePullRequest::Blocked, SystemCallError
|
|
128
|
+
raise InvalidInput, 'Cannot verify the linked Git worktree for the registered session.'
|
|
129
|
+
end
|
|
130
|
+
|
|
131
|
+
def verify_prompt(path, source)
|
|
132
|
+
prompt = WorkRelayIntake.read_regular(path, WorkRelayVerify::INPUT_LIMIT, 'Registered prompt')
|
|
133
|
+
digest = source.fetch('sha256')
|
|
134
|
+
prompt_sha = Digest::SHA256.hexdigest(prompt)
|
|
135
|
+
return prompt_sha if source['type'] == 'file' && prompt_sha == digest
|
|
136
|
+
|
|
137
|
+
# The shipped runner ends the generated prompt with the request followed by a newline.
|
|
138
|
+
automated = AUTOMATED_SECTION.match(prompt)
|
|
139
|
+
header = REQUEST_SECTION.match(prompt, automated.end(0)) if automated
|
|
140
|
+
request = prompt[header.end(0)..-1] if header
|
|
141
|
+
if request && [request, request.delete_suffix("\n")].any? { |value| Digest::SHA256.hexdigest(value) == digest }
|
|
142
|
+
return prompt_sha
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
raise InvalidInput, 'The registered prompt does not match the intake source. Use the original request or prompt file.'
|
|
146
|
+
end
|
|
147
|
+
end
|