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.
@@ -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