workrelay 0.0.0-stage → 1.0.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 +21 -0
- package/README.md +46 -2
- package/bin/workrelay.cjs +156 -0
- package/package.json +23 -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,185 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require_relative 'verify'
|
|
5
|
+
require_relative 'lib/github_pull_request'
|
|
6
|
+
|
|
7
|
+
module WorkRelayHandoff
|
|
8
|
+
InvalidInput = WorkRelayVerify::InvalidInput
|
|
9
|
+
RecordError = WorkRelayVerify::RecordError
|
|
10
|
+
SHA = /\A[0-9a-f]{40}\z/
|
|
11
|
+
FAILURE_STATUSES = %w[no_pr remote_head_missing merged closed blocked ambiguous head_changed draft].freeze
|
|
12
|
+
USAGE = <<~TEXT
|
|
13
|
+
Usage: ruby handoff.rb --intake RECEIPT.json --run RUN --checkout PATH --branch BRANCH
|
|
14
|
+
[--publish --title TITLE --body-file REVIEWED.md]
|
|
15
|
+
|
|
16
|
+
Check for an open GitHub PR matching a completed verification run. Read-only
|
|
17
|
+
on GitHub unless --publish is explicitly supplied. Never pushes or merges.
|
|
18
|
+
TEXT
|
|
19
|
+
|
|
20
|
+
module_function
|
|
21
|
+
|
|
22
|
+
def arguments(args)
|
|
23
|
+
required = %w[--intake --run --checkout --branch]
|
|
24
|
+
optional = %w[--title --body-file]
|
|
25
|
+
options = {}
|
|
26
|
+
until args.empty?
|
|
27
|
+
key = args.shift
|
|
28
|
+
if (required + optional).include?(key)
|
|
29
|
+
value = args.shift
|
|
30
|
+
unless value.is_a?(String) && !value.empty? && !value.start_with?('--')
|
|
31
|
+
raise InvalidInput, 'A required option value is missing.'
|
|
32
|
+
end
|
|
33
|
+
elsif key == '--publish'
|
|
34
|
+
value = true
|
|
35
|
+
else
|
|
36
|
+
raise InvalidInput, 'Unknown handoff option.'
|
|
37
|
+
end
|
|
38
|
+
raise InvalidInput, 'Handoff options may not be repeated.' if options.key?(key)
|
|
39
|
+
|
|
40
|
+
options[key] = value
|
|
41
|
+
end
|
|
42
|
+
unless required.all? { |key| options.key?(key) }
|
|
43
|
+
raise InvalidInput, 'An intake, verification run, checkout, and branch are required.'
|
|
44
|
+
end
|
|
45
|
+
if options['--publish'] ? !optional.all? { |key| options.key?(key) } : optional.any? { |key| options.key?(key) }
|
|
46
|
+
raise InvalidInput, 'Use --publish only with both an explicit title and a reviewed body file.'
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
options
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def exists?(path)
|
|
53
|
+
File.lstat(path)
|
|
54
|
+
true
|
|
55
|
+
rescue Errno::ENOENT
|
|
56
|
+
false
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
def ensure_record(records, name, expected, create:)
|
|
60
|
+
path = File.join(records, name)
|
|
61
|
+
if exists?(path)
|
|
62
|
+
actual = WorkRelayVerify.json(WorkRelayVerify.read_private(path, 'Handoff record'), 'Handoff record')
|
|
63
|
+
unless actual == expected && actual['schemaVersion'].is_a?(Integer)
|
|
64
|
+
raise RecordError, 'Existing handoff record conflicts with this branch or verified PR.'
|
|
65
|
+
end
|
|
66
|
+
elsif create
|
|
67
|
+
WorkRelayVerify.save_private(records, name, JSON.pretty_generate(expected) + "\n")
|
|
68
|
+
end
|
|
69
|
+
end
|
|
70
|
+
|
|
71
|
+
def with_task_lock(intake, &block)
|
|
72
|
+
WorkRelayVerify.with_task_lock(intake, &block)
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
def publication_content(options, records)
|
|
76
|
+
return [nil, nil] unless options['--publish']
|
|
77
|
+
|
|
78
|
+
title = WorkRelayIntake.descriptive_text(options['--title'], 'PR title')
|
|
79
|
+
raise InvalidInput, 'PR title must be valid UTF-8 and at most 256 bytes.' unless title.valid_encoding? && title.bytesize <= 256
|
|
80
|
+
|
|
81
|
+
requested_path = File.expand_path(options.fetch('--body-file'))
|
|
82
|
+
path = File.realpath(requested_path)
|
|
83
|
+
records_prefix = records.end_with?('/') ? records : records + '/'
|
|
84
|
+
if path.start_with?(records_prefix) || !File.lstat(requested_path).file?
|
|
85
|
+
raise InvalidInput, 'PR body must be a reviewed regular file outside the private records directory.'
|
|
86
|
+
end
|
|
87
|
+
flags = File::RDONLY | File::NONBLOCK | File::NOFOLLOW
|
|
88
|
+
File.open(path, flags) do |file|
|
|
89
|
+
stat = file.stat
|
|
90
|
+
original = File.lstat(requested_path)
|
|
91
|
+
unless stat.file? && stat.nlink == 1 && original.file? && [stat.dev, stat.ino] == [original.dev, original.ino]
|
|
92
|
+
raise InvalidInput, 'PR body must be a reviewed regular file, not a symlink or hard link.'
|
|
93
|
+
end
|
|
94
|
+
[title, WorkRelayIntake.bounded_utf8(file, 64 * 1024, 'PR body')]
|
|
95
|
+
end
|
|
96
|
+
rescue SystemCallError, IOError
|
|
97
|
+
raise InvalidInput, 'Cannot read the explicitly reviewed PR body.'
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
def handoff(options, intake, completed)
|
|
101
|
+
revision = completed.fetch('revision')
|
|
102
|
+
unless SHA.match?(revision)
|
|
103
|
+
raise InvalidInput, 'The completed verification run must name a GitHub commit (40 lowercase hex characters).'
|
|
104
|
+
end
|
|
105
|
+
raise InvalidInput, 'This intake has no explicitly selected destination.' unless intake.destination
|
|
106
|
+
|
|
107
|
+
target, base = intake.destination.values_at('target', 'base')
|
|
108
|
+
head = options.fetch('--branch')
|
|
109
|
+
WorkRelayIntake.destination(target, head, 'Working branch')
|
|
110
|
+
raise InvalidInput, 'The working branch and PR base must differ.' if head == base
|
|
111
|
+
|
|
112
|
+
checkout = File.realpath(options.fetch('--checkout'))
|
|
113
|
+
raise InvalidInput, 'A Git checkout directory is required.' unless File.directory?(checkout)
|
|
114
|
+
|
|
115
|
+
title, body = publication_content(options, intake.records)
|
|
116
|
+
pin = { 'schemaVersion' => 1, 'task' => intake.task, 'intakeSha256' => intake.sha256,
|
|
117
|
+
'target' => target, 'base' => base, 'branch' => head }
|
|
118
|
+
pin_name = "#{intake.task}.handoff-pin.json"
|
|
119
|
+
identity_name = "#{intake.task}.handoff-pr.json"
|
|
120
|
+
receipt_name = "#{intake.task}.#{completed.fetch('run')}.handoff.json"
|
|
121
|
+
with_task_lock(intake) do
|
|
122
|
+
ensure_record(intake.records, pin_name, pin, create: false)
|
|
123
|
+
pin_task = -> { ensure_record(intake.records, pin_name, pin, create: true) }
|
|
124
|
+
before_publish = lambda do
|
|
125
|
+
if [identity_name, receipt_name].any? { |name| exists?(File.join(intake.records, name)) }
|
|
126
|
+
raise RecordError, 'This task previously handed off a PR that could not be found. Inspect GitHub; no replacement was opened.'
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
pin_task.call
|
|
130
|
+
end
|
|
131
|
+
remote = ResumePullRequest.new(target: target, base: base, head: head, local_head: revision, verified_head: revision,
|
|
132
|
+
worktree: checkout, task: intake.task, open_pr: options['--publish'],
|
|
133
|
+
title: title, body: body, portable_handoff: true, before_publish: before_publish)
|
|
134
|
+
outcome = remote.run
|
|
135
|
+
result = remote.observation
|
|
136
|
+
unless outcome.zero? && %w[open created].include?(result[:status])
|
|
137
|
+
status = result[:status]
|
|
138
|
+
puts JSON.generate('status' => (FAILURE_STATUSES.include?(status) ? status : 'blocked'))
|
|
139
|
+
# The shared transport class returns fixed messages (or a numeric HTTP status), never subprocess stderr.
|
|
140
|
+
hint = status == 'no_pr' ? 'No open PR matches; confirm publication authority and use --publish with a reviewed title and body.' :
|
|
141
|
+
result[:nextAction]
|
|
142
|
+
warn "Error: #{hint || 'Inspect GitHub and retry the read-only handoff.'}"
|
|
143
|
+
return 1
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
url = result[:prUrl]
|
|
147
|
+
unless result.values_at(:localHead, :remoteHead, :prHead, :verifiedHead).all? { |sha| sha == revision } &&
|
|
148
|
+
url.is_a?(String) && %r{\Ahttps://github\.com/#{Regexp.escape(target)}/pull/[1-9][0-9]*\z}i.match?(url)
|
|
149
|
+
raise RecordError, 'Could not confirm the canonical open PR URL and verified commit.'
|
|
150
|
+
end
|
|
151
|
+
pin_task.call
|
|
152
|
+
ensure_record(intake.records, identity_name, pin.merge('prUrl' => url), create: true)
|
|
153
|
+
summary = { 'status' => 'handed_off', 'target' => target, 'base' => base,
|
|
154
|
+
'branch' => head, 'verifiedHead' => revision, 'prUrl' => url }
|
|
155
|
+
stored = summary.merge('schemaVersion' => 1, 'task' => intake.task, 'run' => completed.fetch('run'),
|
|
156
|
+
'intakeSha256' => intake.sha256, 'planSha256' => completed.fetch('planSha256'))
|
|
157
|
+
ensure_record(intake.records, receipt_name, stored, create: true)
|
|
158
|
+
puts JSON.generate(summary)
|
|
159
|
+
0
|
|
160
|
+
end
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def run(args)
|
|
164
|
+
if args == ['--help'] || args == ['-h']
|
|
165
|
+
puts USAGE
|
|
166
|
+
return 0
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
options = arguments(args)
|
|
170
|
+
intake = WorkRelayVerify.intake_snapshot(options.fetch('--intake'))
|
|
171
|
+
completed = WorkRelayVerify.completed_run(intake, options.fetch('--run'))
|
|
172
|
+
handoff(options, intake, completed)
|
|
173
|
+
rescue InvalidInput => e
|
|
174
|
+
warn "Error: #{e.message}"
|
|
175
|
+
64
|
|
176
|
+
rescue RecordError => e
|
|
177
|
+
warn "Error: #{e.message}"
|
|
178
|
+
73
|
|
179
|
+
rescue SystemCallError, IOError, EncodingError, JSON::GeneratorError, ArgumentError
|
|
180
|
+
warn 'Error: Cannot safely process the handoff inputs or private records.'
|
|
181
|
+
74
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
exit WorkRelayHandoff.run(ARGV) if $PROGRAM_NAME == __FILE__
|
|
@@ -0,0 +1,285 @@
|
|
|
1
|
+
#!/usr/bin/env ruby
|
|
2
|
+
# frozen_string_literal: true
|
|
3
|
+
|
|
4
|
+
require 'digest'
|
|
5
|
+
require 'json'
|
|
6
|
+
require 'tempfile'
|
|
7
|
+
|
|
8
|
+
module WorkRelayIntake
|
|
9
|
+
PROFILE_LIMIT = 64 * 1024
|
|
10
|
+
REQUEST_LIMIT = 1024 * 1024
|
|
11
|
+
SLUG = /\A[a-z0-9]+(?:-[a-z0-9]+)*\z/
|
|
12
|
+
IMPLEMENTATION_METHODS = %w[native pstack].freeze
|
|
13
|
+
VERSION = /\A[A-Za-z0-9][A-Za-z0-9._+-]{0,63}\z/
|
|
14
|
+
TARGET = %r{\A[A-Za-z0-9]+(?:-[A-Za-z0-9]+)*/[A-Za-z0-9_.-]+\z}
|
|
15
|
+
BASE = %r{\A[A-Za-z0-9_][A-Za-z0-9_./-]*\z}
|
|
16
|
+
USAGE = <<~TEXT
|
|
17
|
+
Usage: ruby intake.rb --profile PROFILE.json --task TASK (--chat | --file PATH)
|
|
18
|
+
[--target OWNER/REPO --base BRANCH] [--record]
|
|
19
|
+
|
|
20
|
+
Read a UTF-8 request (stdin with --chat), validate the profile and print a
|
|
21
|
+
local intake snapshot. No remote access or publication is performed.
|
|
22
|
+
--record also saves the snapshot without replacing an existing task record.
|
|
23
|
+
TEXT
|
|
24
|
+
|
|
25
|
+
class InvalidInput < StandardError; end
|
|
26
|
+
class RecordError < StandardError; end
|
|
27
|
+
|
|
28
|
+
class UniqueKeys < Hash
|
|
29
|
+
def []=(key, value)
|
|
30
|
+
raise InvalidInput, 'Profile contains a duplicate JSON key.' if key?(key)
|
|
31
|
+
|
|
32
|
+
super
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
module_function
|
|
37
|
+
|
|
38
|
+
def read_options(args)
|
|
39
|
+
options = {}
|
|
40
|
+
until args.empty?
|
|
41
|
+
flag = args.shift
|
|
42
|
+
case flag
|
|
43
|
+
when '--chat', '--record'
|
|
44
|
+
value = true
|
|
45
|
+
when '--profile', '--task', '--file', '--target', '--base'
|
|
46
|
+
value = args.shift
|
|
47
|
+
raise InvalidInput, 'An option is missing its value.' if value.nil? || value.empty? || value.start_with?('--')
|
|
48
|
+
else
|
|
49
|
+
raise InvalidInput, 'Unrecognized argument. Use --help for usage.'
|
|
50
|
+
end
|
|
51
|
+
raise InvalidInput, 'Options cannot be repeated.' if options.key?(flag)
|
|
52
|
+
|
|
53
|
+
options[flag] = value
|
|
54
|
+
end
|
|
55
|
+
raise InvalidInput, '--profile and --task are required.' unless options['--profile'] && options['--task']
|
|
56
|
+
raise InvalidInput, 'Select exactly one of --chat or --file.' unless options.key?('--chat') ^ options.key?('--file')
|
|
57
|
+
if options.key?('--target') ^ options.key?('--base')
|
|
58
|
+
raise InvalidInput, 'Specify --target and --base together.'
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
options
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
def bounded_utf8(io, limit, label)
|
|
65
|
+
value = io.binmode.read(limit + 1)
|
|
66
|
+
raise InvalidInput, "#{label} is too large (maximum #{limit} bytes)." if value && value.bytesize > limit
|
|
67
|
+
|
|
68
|
+
value = (value || '').dup.force_encoding(Encoding::UTF_8)
|
|
69
|
+
unless value.valid_encoding? && !value.include?("\0") && !value.strip.empty?
|
|
70
|
+
raise InvalidInput, "#{label} must be nonempty UTF-8 text."
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
value
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
def read_regular(path, limit, label)
|
|
77
|
+
original = File.lstat(path)
|
|
78
|
+
raise InvalidInput, "#{label} must be a regular file, not a symlink." unless original.file?
|
|
79
|
+
|
|
80
|
+
flags = File::RDONLY | File::NONBLOCK | File::NOFOLLOW
|
|
81
|
+
File.open(path, flags) do |io|
|
|
82
|
+
actual = io.stat
|
|
83
|
+
unless actual.file? && [actual.dev, actual.ino] == [original.dev, original.ino]
|
|
84
|
+
raise InvalidInput, "#{label} changed while opening it."
|
|
85
|
+
end
|
|
86
|
+
|
|
87
|
+
bounded_utf8(io, limit, label)
|
|
88
|
+
end
|
|
89
|
+
rescue SystemCallError, IOError, ArgumentError
|
|
90
|
+
raise InvalidInput, "Cannot read #{label.downcase} as a regular file."
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def object(value, required, label, optional = [])
|
|
94
|
+
unless value.is_a?(Hash) && (required - value.keys).empty? && (value.keys - required - optional).empty?
|
|
95
|
+
raise InvalidInput, "#{label} has missing or unsupported fields."
|
|
96
|
+
end
|
|
97
|
+
|
|
98
|
+
value
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def descriptive_text(value, label)
|
|
102
|
+
unless value.is_a?(String) && !value.strip.empty? && !value.match?(/[[:cntrl:]]/)
|
|
103
|
+
raise InvalidInput, "#{label} must be nonempty text without control characters."
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
value
|
|
107
|
+
end
|
|
108
|
+
|
|
109
|
+
def slug(value, label)
|
|
110
|
+
unless value.is_a?(String) && value.bytesize <= 64 && SLUG.match?(value)
|
|
111
|
+
raise InvalidInput, "#{label} must be a lowercase slug (at most 64 characters)."
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
value
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
def version(value, label)
|
|
118
|
+
raise InvalidInput, "#{label} must be a version identifier." unless value.is_a?(String) && VERSION.match?(value)
|
|
119
|
+
|
|
120
|
+
value
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def directory(value, root, label)
|
|
124
|
+
path = File.expand_path(descriptive_text(value, label), root)
|
|
125
|
+
unless File.lstat(path).directory?
|
|
126
|
+
raise InvalidInput, "#{label} must be an existing directory, not a symlink."
|
|
127
|
+
end
|
|
128
|
+
|
|
129
|
+
File.realpath(path)
|
|
130
|
+
rescue SystemCallError, ArgumentError
|
|
131
|
+
raise InvalidInput, "#{label} must be an existing directory."
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def destination(target, base, label)
|
|
135
|
+
unless target.is_a?(String) && TARGET.match?(target)
|
|
136
|
+
raise InvalidInput, "#{label} requires an OWNER/REPO target, not a URL."
|
|
137
|
+
end
|
|
138
|
+
owner, repo = target.split('/')
|
|
139
|
+
if owner.bytesize > 39 || repo.bytesize > 100 || %w[. ..].include?(repo) || repo.downcase.end_with?('.git')
|
|
140
|
+
raise InvalidInput, "#{label} contains an invalid repository name."
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
unless base.is_a?(String) && base.bytesize <= 255 && BASE.match?(base) && base != 'HEAD' &&
|
|
144
|
+
!base.start_with?('refs/') && !base.include?('..') && !base.end_with?('.', '/') &&
|
|
145
|
+
base.split('/').none? { |part| part.empty? || part.start_with?('.') || part.end_with?('.lock') }
|
|
146
|
+
raise InvalidInput, "#{label} requires a plain target branch name."
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
{ 'target' => target, 'base' => base }
|
|
150
|
+
end
|
|
151
|
+
|
|
152
|
+
def implementation_method(value, label)
|
|
153
|
+
unless IMPLEMENTATION_METHODS.include?(value)
|
|
154
|
+
raise InvalidInput, "#{label} must be native or pstack."
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
value
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def load_profile(file)
|
|
161
|
+
path = File.expand_path(file)
|
|
162
|
+
home = File.realpath(File.dirname(path))
|
|
163
|
+
raw = read_regular(File.join(home, File.basename(path)), PROFILE_LIMIT, 'Profile')
|
|
164
|
+
# The object hook catches duplicates on older JSON libraries. Newer ones
|
|
165
|
+
# detect them before passing normalized keys to the object hook.
|
|
166
|
+
data = JSON.parse(raw, object_class: UniqueKeys, allow_duplicate_key: false)
|
|
167
|
+
profile = object(data, %w[schemaVersion id version sources workspace recordsDir roles verification], 'Profile',
|
|
168
|
+
%w[defaults implementationMethod])
|
|
169
|
+
unless profile['schemaVersion'].is_a?(Integer) && profile['schemaVersion'] == 1
|
|
170
|
+
raise InvalidInput, 'Profile schemaVersion must be 1.'
|
|
171
|
+
end
|
|
172
|
+
slug(profile['id'], 'Profile id')
|
|
173
|
+
version(profile['version'], 'Profile version')
|
|
174
|
+
|
|
175
|
+
sources = profile['sources']
|
|
176
|
+
unless sources.is_a?(Array) && !sources.empty? && sources == sources.uniq && (sources - %w[chat file]).empty?
|
|
177
|
+
raise InvalidInput, 'Profile sources must contain chat, file, or both (without duplicates).'
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
workspace = object(profile['workspace'], %w[mode path], 'Profile workspace')
|
|
181
|
+
unless %w[current directory worktree].include?(workspace['mode'])
|
|
182
|
+
raise InvalidInput, 'Profile workspace mode must be current, directory, or worktree.'
|
|
183
|
+
end
|
|
184
|
+
workspace = workspace.merge('path' => directory(workspace['path'], home, 'Workspace path'))
|
|
185
|
+
records = directory(profile['recordsDir'], home, 'Records directory')
|
|
186
|
+
|
|
187
|
+
roles = object(profile['roles'], %w[implementer verifier], 'Profile roles')
|
|
188
|
+
roles.each_value { |value| descriptive_text(value, 'Each role') }
|
|
189
|
+
|
|
190
|
+
verification = profile['verification']
|
|
191
|
+
unless verification.is_a?(Array) && !verification.empty?
|
|
192
|
+
raise InvalidInput, 'Profile verification must contain at least one method and its observable outcome.'
|
|
193
|
+
end
|
|
194
|
+
verification.each do |check|
|
|
195
|
+
object(check, %w[method outcome], 'Verification check').each_value do |value|
|
|
196
|
+
descriptive_text(value, 'Verification method or outcome')
|
|
197
|
+
end
|
|
198
|
+
end
|
|
199
|
+
|
|
200
|
+
if profile.key?('implementationMethod')
|
|
201
|
+
implementation_method(profile['implementationMethod'], 'Profile implementation method')
|
|
202
|
+
end
|
|
203
|
+
if profile.key?('defaults')
|
|
204
|
+
defaults = object(profile['defaults'], %w[target base], 'Profile destination defaults')
|
|
205
|
+
defaults = destination(defaults['target'], defaults['base'], 'Profile destination defaults')
|
|
206
|
+
end
|
|
207
|
+
profile.merge('workspace' => workspace, 'recordsDir' => records, 'defaults' => defaults)
|
|
208
|
+
rescue JSON::ParserError
|
|
209
|
+
raise InvalidInput, 'Profile must contain a valid JSON object.'
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
def save_snapshot(snapshot, records, task)
|
|
213
|
+
dir = File.lstat(records)
|
|
214
|
+
unless dir.directory? && dir.uid == Process.euid && (dir.mode & 0o022).zero?
|
|
215
|
+
raise RecordError, 'Records directory must be owned by the current user and not writable by others.'
|
|
216
|
+
end
|
|
217
|
+
|
|
218
|
+
target = File.join(records, "#{task}.intake.json")
|
|
219
|
+
Tempfile.create('.intake-', records) do |file|
|
|
220
|
+
file.chmod(0o600)
|
|
221
|
+
file.write(snapshot)
|
|
222
|
+
file.close
|
|
223
|
+
# A hard link publishes the completed file atomically without replacing any
|
|
224
|
+
# existing directory entry, even another intake racing for the same ID.
|
|
225
|
+
File.link(file.path, target)
|
|
226
|
+
end
|
|
227
|
+
rescue Errno::EEXIST
|
|
228
|
+
raise RecordError, 'This task already has an intake record. Inspect it and preview changes without --record.'
|
|
229
|
+
rescue SystemCallError, IOError
|
|
230
|
+
raise RecordError, 'Cannot safely save an intake record in the chosen directory.'
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def run(args)
|
|
234
|
+
if args == ['--help'] || args == ['-h']
|
|
235
|
+
puts USAGE
|
|
236
|
+
return 0
|
|
237
|
+
end
|
|
238
|
+
|
|
239
|
+
options = read_options(args)
|
|
240
|
+
profile = load_profile(options.fetch('--profile'))
|
|
241
|
+
task = slug(options.fetch('--task'), 'Task ID')
|
|
242
|
+
selected = destination(options.fetch('--target'), options.fetch('--base'), 'Explicit destination') if options['--target']
|
|
243
|
+
type = options['--chat'] ? 'chat' : 'file'
|
|
244
|
+
unless profile.fetch('sources').include?(type)
|
|
245
|
+
raise InvalidInput, 'Selected request source is not enabled in this profile.'
|
|
246
|
+
end
|
|
247
|
+
|
|
248
|
+
request = if type == 'chat'
|
|
249
|
+
bounded_utf8(STDIN, REQUEST_LIMIT, 'Chat request')
|
|
250
|
+
else
|
|
251
|
+
read_regular(options.fetch('--file'), REQUEST_LIMIT, 'File request')
|
|
252
|
+
end
|
|
253
|
+
skill_version = read_regular(File.expand_path('../VERSION', __dir__), 128, 'Skill version').strip
|
|
254
|
+
data = {
|
|
255
|
+
'receiptSchemaVersion' => 1,
|
|
256
|
+
'skillVersion' => version(skill_version, 'Skill version'),
|
|
257
|
+
'profile' => profile.slice('id', 'version'),
|
|
258
|
+
'task' => task,
|
|
259
|
+
'source' => { 'type' => type, 'sha256' => Digest::SHA256.hexdigest(request) },
|
|
260
|
+
'workspace' => profile.fetch('workspace'),
|
|
261
|
+
'recordsDir' => profile.fetch('recordsDir'),
|
|
262
|
+
'roles' => profile.fetch('roles'),
|
|
263
|
+
'verification' => profile.fetch('verification'),
|
|
264
|
+
'destination' => selected,
|
|
265
|
+
'suggestedDestination' => profile['defaults'],
|
|
266
|
+
'publicationAuthority' => 'not_granted'
|
|
267
|
+
}
|
|
268
|
+
data['implementationMethod'] = profile['implementationMethod'] if profile.key?('implementationMethod')
|
|
269
|
+
snapshot = JSON.pretty_generate(data) + "\n"
|
|
270
|
+
save_snapshot(snapshot, profile.fetch('recordsDir'), task) if options['--record']
|
|
271
|
+
print snapshot
|
|
272
|
+
0
|
|
273
|
+
rescue InvalidInput => e
|
|
274
|
+
warn "Error: #{e.message}"
|
|
275
|
+
64
|
|
276
|
+
rescue RecordError => e
|
|
277
|
+
warn "Error: #{e.message}"
|
|
278
|
+
73
|
|
279
|
+
rescue SystemCallError, IOError, EncodingError, JSON::GeneratorError, ArgumentError
|
|
280
|
+
warn 'Error: Cannot process local intake options or inputs.'
|
|
281
|
+
74
|
|
282
|
+
end
|
|
283
|
+
end
|
|
284
|
+
|
|
285
|
+
exit WorkRelayIntake.run(ARGV) if $PROGRAM_NAME == __FILE__
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'github_pull_request'
|
|
4
|
+
|
|
5
|
+
# A github.com transport, not a source of merge approval. Only submit can write.
|
|
6
|
+
class WorkRelayMergeRemote
|
|
7
|
+
Blocked = ResumePullRequest::Blocked
|
|
8
|
+
SHA = ResumePullRequest::SHA
|
|
9
|
+
PR_QUERY = <<~GRAPHQL.freeze
|
|
10
|
+
query($owner:String!, $name:String!, $number:Int!) {
|
|
11
|
+
repository(owner:$owner, name:$name) {
|
|
12
|
+
nameWithOwner
|
|
13
|
+
pullRequest(number:$number) {
|
|
14
|
+
number url state headRepository { nameWithOwner }
|
|
15
|
+
baseRefName headRefName baseRefOid headRefOid
|
|
16
|
+
baseRef { target { oid } branchProtectionRule { id } } headRef { target { oid } }
|
|
17
|
+
isDraft mergeable mergeStateStatus reviewDecision mergedAt mergeCommit { oid }
|
|
18
|
+
reviewThreads(first:100) { pageInfo { hasNextPage } nodes { isResolved } }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
GRAPHQL
|
|
23
|
+
|
|
24
|
+
def initialize(target:, base:, branch:, pr_url:, head:)
|
|
25
|
+
WorkRelayIntake.destination(target, base, 'Merge target')
|
|
26
|
+
WorkRelayIntake.destination(target, branch, 'Merge branch')
|
|
27
|
+
match = %r{\Ahttps://github\.com/#{Regexp.escape(target)}/pull/([1-9][0-9]{0,9})\z}i.match(pr_url.to_s)
|
|
28
|
+
unless match && head.is_a?(String) && SHA.match?(head) && base != branch
|
|
29
|
+
raise WorkRelayIntake::InvalidInput, 'The PR identity or verified merge commit is invalid.'
|
|
30
|
+
end
|
|
31
|
+
@target, @base, @branch, @url, @head = target, base, branch, pr_url, head
|
|
32
|
+
@number = Integer(match[1], 10)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
def inspect_pr
|
|
36
|
+
@eligible_base = nil
|
|
37
|
+
pull = snapshot
|
|
38
|
+
initial = state(pull)
|
|
39
|
+
return initial unless initial['status'] == 'eligible'
|
|
40
|
+
|
|
41
|
+
check_policy
|
|
42
|
+
ancestor!(initial.fetch('baseSha'), @head)
|
|
43
|
+
# Checks are a separate lookup; do not associate them with a new ref or a
|
|
44
|
+
# PR whose review state changed during that lookup.
|
|
45
|
+
final = state(snapshot)
|
|
46
|
+
if final['status'] == 'eligible'
|
|
47
|
+
ensure_that(final['baseSha'] == initial['baseSha'], 'The base moved during inspection; revalidate before merging.')
|
|
48
|
+
@eligible_base = final.fetch('baseSha')
|
|
49
|
+
end
|
|
50
|
+
final
|
|
51
|
+
rescue Blocked => e
|
|
52
|
+
{ 'status' => 'blocked', 'reason' => e.message }
|
|
53
|
+
rescue KeyError, TypeError, NoMethodError, ArgumentError
|
|
54
|
+
{ 'status' => 'blocked', 'reason' => 'GitHub returned incomplete merge evidence.' }
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# The response is advisory, including after timeouts/409s. The caller must
|
|
58
|
+
# inspect again and persist only the independently confirmed remote result.
|
|
59
|
+
def submit
|
|
60
|
+
return false unless @eligible_base && !@attempted
|
|
61
|
+
|
|
62
|
+
base = @eligible_base
|
|
63
|
+
@eligible_base = nil
|
|
64
|
+
@attempted = true
|
|
65
|
+
current = snapshot
|
|
66
|
+
return false unless current['state'] == 'OPEN' && state(current) == { 'status' => 'eligible', 'baseSha' => base }
|
|
67
|
+
|
|
68
|
+
result = api('--method', 'PUT', "repos/#{@target}/pulls/#{@number}/merge", '--input', '-',
|
|
69
|
+
input: JSON.generate(sha: @head, merge_method: 'squash'))
|
|
70
|
+
result.is_a?(Hash) && result['merged'] == true && sha?(result['sha'])
|
|
71
|
+
rescue Blocked, KeyError, TypeError, NoMethodError, ArgumentError
|
|
72
|
+
false
|
|
73
|
+
end
|
|
74
|
+
|
|
75
|
+
private
|
|
76
|
+
|
|
77
|
+
def ensure_that(condition, hint)
|
|
78
|
+
raise Blocked, hint unless condition
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
def sha?(value)
|
|
82
|
+
value.is_a?(String) && SHA.match?(value)
|
|
83
|
+
end
|
|
84
|
+
|
|
85
|
+
def gh(*args, input: '')
|
|
86
|
+
stdout, _, status = Open3.capture3(ResumePullRequest::GITHUB_ENV, 'gh', *args, stdin_data: input)
|
|
87
|
+
ensure_that(status.success?, 'GitHub request failed; inspect access, required checks and remote state.')
|
|
88
|
+
JSON.parse(stdout)
|
|
89
|
+
rescue JSON::ParserError, SystemCallError, IOError, EncodingError
|
|
90
|
+
raise Blocked, 'Could not read GitHub merge evidence; check access and connectivity.'
|
|
91
|
+
end
|
|
92
|
+
|
|
93
|
+
def api(*args, input: '')
|
|
94
|
+
gh('api', '--hostname', 'github.com', *args, input: input)
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
def same_name?(actual, expected)
|
|
98
|
+
actual.is_a?(String) && actual.casecmp?(expected)
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
def snapshot
|
|
102
|
+
owner, name = @target.split('/')
|
|
103
|
+
result = api('graphql', '--input', '-', input: JSON.generate(query: PR_QUERY, variables: { owner: owner, name: name, number: @number }))
|
|
104
|
+
ensure_that(result.is_a?(Hash) && !result.key?('errors'), 'GitHub returned incomplete PR data.')
|
|
105
|
+
repo = result.dig('data', 'repository')
|
|
106
|
+
p = repo.fetch('pullRequest')
|
|
107
|
+
ensure_that(same_name?(repo['nameWithOwner'], @target) && same_name?(p.dig('headRepository', 'nameWithOwner'), @target) &&
|
|
108
|
+
p['number'].eql?(@number) && same_name?(p['url'], @url) &&
|
|
109
|
+
p['baseRefName'] == @base && p['headRefName'] == @branch, 'The PR target or source no longer matches the handoff.')
|
|
110
|
+
p
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
def state(pull)
|
|
114
|
+
unless pull['headRefOid'] == @head
|
|
115
|
+
return { 'status' => 'head_changed', 'reason' => 'PR HEAD differs from the verified commit; reverify and obtain approval for the new HEAD.' }
|
|
116
|
+
end
|
|
117
|
+
case pull.fetch('state')
|
|
118
|
+
when 'MERGED' then confirmed_merge(pull)
|
|
119
|
+
when 'CLOSED' then { 'status' => 'closed' }
|
|
120
|
+
when 'OPEN' then open_state(pull)
|
|
121
|
+
else raise Blocked, 'GitHub did not confirm the PR lifecycle state.'
|
|
122
|
+
end
|
|
123
|
+
end
|
|
124
|
+
|
|
125
|
+
def open_state(pull)
|
|
126
|
+
ensure_that(pull['isDraft'] == false && pull['mergeable'] == 'MERGEABLE' && pull['mergeStateStatus'] == 'CLEAN',
|
|
127
|
+
'The PR must be open, non-draft, mergeable and CLEAN.')
|
|
128
|
+
unless pull.dig('headRef', 'target', 'oid') == @head
|
|
129
|
+
return { 'status' => 'head_changed', 'reason' => 'The published head ref does not match the verified head.' }
|
|
130
|
+
end
|
|
131
|
+
base_sha = pull['baseRefOid']
|
|
132
|
+
ensure_that(sha?(base_sha) && pull.dig('baseRef', 'target', 'oid') == base_sha, 'The current base does not match the PR snapshot.')
|
|
133
|
+
ensure_that(pull.fetch('baseRef').fetch('branchProtectionRule').nil?, 'Overlapping classic branch protection requires manual review.')
|
|
134
|
+
review = pull.fetch('reviewDecision')
|
|
135
|
+
threads = pull.fetch('reviewThreads')
|
|
136
|
+
ensure_that([nil, 'APPROVED'].include?(review) && threads.dig('pageInfo', 'hasNextPage') == false &&
|
|
137
|
+
threads['nodes'].is_a?(Array) && threads['nodes'].all? { |n| n['isResolved'] == true },
|
|
138
|
+
'Reviews are pending, unresolved or could not be enumerated.')
|
|
139
|
+
{ 'status' => 'eligible', 'baseSha' => base_sha }
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
def check_policy
|
|
143
|
+
rules = api("repos/#{@target}/rules/branches/#{URI.encode_www_form_component(@base)}?per_page=100")
|
|
144
|
+
ensure_that(rules.is_a?(Array) && rules.size < 100 && rules.all? { |r| r.is_a?(Hash) && r['type'].is_a?(String) },
|
|
145
|
+
'Cannot enumerate the effective branch rules.')
|
|
146
|
+
ensure_that(rules.none? { |r| r['type'] == 'merge_queue' }, 'A merge queue requires a separate workflow.')
|
|
147
|
+
prs = rules.select { |r| r['type'] == 'pull_request' }
|
|
148
|
+
checks = rules.select { |r| r['type'] == 'required_status_checks' }
|
|
149
|
+
thread_rule = prs.any? { |r| r.dig('parameters', 'required_review_thread_resolution') == true }
|
|
150
|
+
ensure_that(thread_rule && checks.any? { |r| r.dig('parameters', 'strict_required_status_checks_policy') == true },
|
|
151
|
+
'Active resolved-thread and strict up-to-date required-check rulesets are required.')
|
|
152
|
+
# GitHub's merge API has a head guard, not a base/review guard. Only
|
|
153
|
+
# support active rulesets that cannot be bypassed by the authenticated actor.
|
|
154
|
+
ids = rules.map { |r| r['ruleset_id'] }.uniq
|
|
155
|
+
ids.each do |id|
|
|
156
|
+
ensure_that(id.is_a?(Integer) && id.positive?, 'Cannot identify the effective merge ruleset.')
|
|
157
|
+
detail = api("repos/#{@target}/rulesets/#{id}")
|
|
158
|
+
ensure_that(detail.is_a?(Hash) && detail['id'].eql?(id) && detail['enforcement'] == 'active' && detail['bypass_actors'] == [],
|
|
159
|
+
'Ruleset bypass actors must be visible and empty.')
|
|
160
|
+
end
|
|
161
|
+
names = checks.flat_map { |r| r.fetch('parameters').fetch('required_status_checks').map { |c| c.fetch('context') } }
|
|
162
|
+
ensure_that(!names.empty? && names.all? { |n| n.is_a?(String) && !n.empty? }, 'No identifiable required check contexts.')
|
|
163
|
+
observed = gh('pr', 'checks', @number.to_s, '--repo', "github.com/#{@target}", '--required', '--json', 'name,bucket,state')
|
|
164
|
+
ensure_that(observed.is_a?(Array) &&
|
|
165
|
+
observed.all? { |c| c['bucket'] == 'pass' && c['state'] == 'SUCCESS' } &&
|
|
166
|
+
(names - observed.map { |c| c['name'] }).empty?, 'Required checks are missing, skipped, pending or failing.')
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
def ancestor!(ancestor, descendant)
|
|
170
|
+
return if ancestor == descendant
|
|
171
|
+
comparison = api("repos/#{@target}/compare/#{ancestor}...#{descendant}?per_page=1")
|
|
172
|
+
ensure_that(comparison['status'] == 'ahead' && comparison.dig('merge_base_commit', 'sha') == ancestor,
|
|
173
|
+
'GitHub did not confirm the expected commit ancestry.')
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def confirmed_merge(pull)
|
|
177
|
+
merged_sha = pull.dig('mergeCommit', 'oid')
|
|
178
|
+
tip = pull.dig('baseRef', 'target', 'oid')
|
|
179
|
+
ensure_that(sha?(merged_sha) && sha?(tip) && pull['mergedAt'].is_a?(String) && !pull['mergedAt'].empty?,
|
|
180
|
+
'Missing the actual merge commit, remote base or merge timestamp.')
|
|
181
|
+
detail = api("repos/#{@target}/pulls/#{@number}")
|
|
182
|
+
ensure_that(detail['number'].eql?(@number) && same_name?(detail['html_url'], @url) && detail['state'] == 'closed' &&
|
|
183
|
+
detail['merged'] == true && detail['merge_commit_sha'] == merged_sha &&
|
|
184
|
+
detail.dig('head', 'sha') == @head && detail.dig('head', 'ref') == @branch && detail.dig('base', 'ref') == @base &&
|
|
185
|
+
%w[head base].all? { |ref| same_name?(detail.dig(ref, 'repo', 'full_name'), @target) },
|
|
186
|
+
'GitHub did not independently confirm this exact merged PR and commit.')
|
|
187
|
+
ancestor!(merged_sha, tip)
|
|
188
|
+
{ 'status' => 'merged', 'mergeSha' => merged_sha }
|
|
189
|
+
end
|
|
190
|
+
end
|