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.
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative 'handoff'
5
+ require_relative 'lib/github_merge'
6
+
7
+ module WorkRelayMerge
8
+ InvalidInput = WorkRelayVerify::InvalidInput
9
+ RecordError = WorkRelayVerify::RecordError
10
+ REQUIRED = %w[--intake --run --checkout --branch].freeze
11
+ APPROVAL = %w[--approve-pr --approve-head].freeze
12
+ SHA = WorkRelayHandoff::SHA
13
+ USAGE = <<~TEXT
14
+ Usage: ruby merge.rb --intake RECEIPT.json --run RUN --checkout PATH --branch BRANCH
15
+ [--approve-pr https://github.com/OWNER/REPO/pull/N --approve-head FULL_SHA]
16
+
17
+ No GitHub writes by default. Supply both approval arguments only after a
18
+ separate trusted grant for this PR and verified commit. An inconclusive
19
+ submission must be reconciled read-only, never retried automatically.
20
+ TEXT
21
+
22
+ module_function
23
+
24
+ def arguments(args)
25
+ result = {}
26
+ args.each_slice(2) do |key, value|
27
+ unless (REQUIRED + APPROVAL).include?(key) && !result.key?(key) && value && !value.empty? && !value.start_with?('--')
28
+ raise InvalidInput, 'Invalid or repeated merge option. Use --help for usage.'
29
+ end
30
+ result[key] = value
31
+ end
32
+ unless (REQUIRED - result.keys).empty? && [0, 2].include?((APPROVAL & result.keys).size)
33
+ raise InvalidInput, 'Specify the four required options; an approval requires both the PR URL and full verified HEAD.'
34
+ end
35
+ result
36
+ end
37
+
38
+ def stored(intake, name, label)
39
+ raw = WorkRelayVerify.read_private(File.join(intake.records, name), label)
40
+ data = WorkRelayVerify.json(raw, label)
41
+ raise InvalidInput, "#{label} has an invalid schema." unless data.is_a?(Hash) && data['schemaVersion'].eql?(1)
42
+
43
+ data
44
+ end
45
+
46
+ # Only the newest verification for the task can authorize a write. The recorder
47
+ # has one-second precision; do not guess an order using names, mtimes or directory order.
48
+ def ensure_latest(intake, completed)
49
+ since = Time.iso8601(completed.fetch('observedAt'))
50
+ Dir.children(intake.records).each do |name|
51
+ match = /\A#{Regexp.escape(intake.task)}\.([^.]+)\.verification\.json\z/.match(name)
52
+ next unless match && match[1] != completed.fetch('run')
53
+
54
+ WorkRelayIntake.slug(match[1], 'Run id')
55
+ raw = WorkRelayVerify.read_private(File.join(intake.records, name), 'Verification run', limit: WorkRelayVerify::RECORDED_RUN_LIMIT)
56
+ other = WorkRelayVerify.json(raw, 'Verification run')
57
+ unless other.is_a?(Hash) && other['schemaVersion'].eql?(1) &&
58
+ other.values_at('task', 'run', 'intakeSha256') == [intake.task, match[1], intake.sha256] &&
59
+ other['observedAt'].is_a?(String) && Time.iso8601(other['observedAt']) < since
60
+ raise InvalidInput, 'A later, tied or invalid verification exists. Re-verify and hand off a new, unambiguous run.'
61
+ end
62
+ end
63
+ rescue ArgumentError
64
+ raise InvalidInput, 'Cannot establish the order of verification runs.'
65
+ end
66
+
67
+ def binding(options, intake)
68
+ completed = WorkRelayVerify.completed_run(intake, options.fetch('--run'))
69
+ ensure_latest(intake, completed)
70
+ head = completed.fetch('revision')
71
+ raise InvalidInput, 'An explicitly selected destination and verified Git commit are required.' unless intake.destination && SHA.match?(head)
72
+
73
+ target, base = intake.destination.values_at('target', 'base')
74
+ branch = options.fetch('--branch')
75
+ WorkRelayIntake.destination(target, branch, 'Working branch')
76
+ raise InvalidInput, 'The PR base and working branch must differ.' if base == branch
77
+
78
+ pin = { 'schemaVersion' => 1, 'task' => intake.task, 'intakeSha256' => intake.sha256,
79
+ 'target' => target, 'base' => base, 'branch' => branch }
80
+ identity = stored(intake, "#{intake.task}.handoff-pr.json", 'PR identity')
81
+ url = identity['prUrl']
82
+ unless stored(intake, "#{intake.task}.handoff-pin.json", 'Handoff pin') == pin &&
83
+ url.is_a?(String) && %r{\Ahttps://github\.com/#{Regexp.escape(target)}/pull/[1-9][0-9]*\z}i.match?(url) &&
84
+ identity == pin.merge('prUrl' => url)
85
+ raise RecordError, 'The handed-off repository, branches or PR identity do not match.'
86
+ end
87
+ result = identity.merge('run' => completed.fetch('run'), 'planSha256' => completed.fetch('planSha256'), 'verifiedHead' => head)
88
+ unless stored(intake, "#{intake.task}.#{completed.fetch('run')}.handoff.json", 'Handoff receipt') == result.merge('status' => 'handed_off')
89
+ raise RecordError, 'The selected run did not hand off this exact PR and verified HEAD.'
90
+ end
91
+ if options.key?('--approve-pr') && options.values_at(*APPROVAL) != [url, head]
92
+ raise InvalidInput, 'Separate approval must match the exact handed-off PR URL and verified commit.'
93
+ end
94
+
95
+ checkout = File.realpath(options.fetch('--checkout'))
96
+ ResumePullRequest.new(target: target, base: base, head: branch, local_head: head, verified_head: head,
97
+ worktree: checkout, portable_handoff: true).verify_checkout!
98
+ result
99
+ end
100
+
101
+ def observe(result, status, reason = nil, extra = {})
102
+ summary = result.slice('prUrl', 'verifiedHead').merge('status' => status).merge(extra)
103
+ puts JSON.generate(summary)
104
+ warn "Error: #{reason}" if reason
105
+ status == 'merged' ? 0 : 1
106
+ end
107
+
108
+ def report_remote(intake, result, remote_state)
109
+ status = remote_state['status']
110
+ if status != 'merged'
111
+ status = 'blocked' unless %w[head_changed closed blocked].include?(status)
112
+ return observe(result, status, remote_state['reason'] || 'Remote merge conditions are not satisfied.')
113
+ end
114
+ sha = remote_state['mergeSha']
115
+ unless sha.is_a?(String) && SHA.match?(sha)
116
+ return observe(result, 'unconfirmed', 'GitHub did not confirm the actual merge commit.')
117
+ end
118
+ receipt = result.merge('status' => 'merged', 'mergeSha' => sha)
119
+ WorkRelayHandoff.ensure_record(intake.records, "#{intake.task}.#{result.fetch('run')}.merge.json", receipt, create: true)
120
+ observe(result, 'merged', nil, 'mergeSha' => sha)
121
+ end
122
+
123
+ def reserve_attempt(intake, result, name, base_sha)
124
+ marker = result.merge('status' => 'attempt_reserved', 'baseSha' => base_sha, 'mergeMethod' => 'squash')
125
+ WorkRelayVerify.save_private(intake.records, name, JSON.pretty_generate(marker) + "\n")
126
+ # Do not transmit a mutation until the one-way marker is on disk.
127
+ File.open(File.join(intake.records, name), File::RDONLY | File::NOFOLLOW, &:fsync)
128
+ File.open(intake.records, File::RDONLY, &:fsync)
129
+ end
130
+
131
+ def reconcile(options, intake)
132
+ result = binding(options, intake)
133
+ remote = WorkRelayMergeRemote.new(target: result['target'], base: result['base'], branch: result['branch'],
134
+ pr_url: result['prUrl'], head: result['verifiedHead'])
135
+ state = remote.inspect_pr
136
+ return report_remote(intake, result, state) unless state['status'] == 'eligible'
137
+
138
+ name = "#{intake.task}.merge-attempt.json"
139
+ if WorkRelayHandoff.exists?(File.join(intake.records, name)) || Dir.children(intake.records).any? { |n| n.start_with?("#{intake.task}.") && n.end_with?('.merge.json') }
140
+ return observe(result, 'unconfirmed', 'An attempt or merge receipt exists but GitHub does not confirm a merge. Inspect it; no new request was sent.')
141
+ end
142
+ return observe(result, 'approval_required', 'No merge requested. Supply a separate trusted approval for this PR and commit.') unless options.key?('--approve-pr')
143
+
144
+ # Repeat the gates after the potentially slow first remote lookup, under the
145
+ # same lock as handoff. No write on a changed local binding or remote base.
146
+ fresh = remote.inspect_pr
147
+ return report_remote(intake, result, fresh) unless fresh['status'] == 'eligible'
148
+ unless state['baseSha'].is_a?(String) && SHA.match?(state['baseSha']) && state['baseSha'] == fresh['baseSha']
149
+ return observe(result, 'blocked', 'The base changed or could not be verified. Recheck the new base.')
150
+ end
151
+ current = WorkRelayVerify.intake_snapshot(options.fetch('--intake'))
152
+ raise RecordError, 'The intake or verification changed before merge.' unless current.sha256 == intake.sha256 && binding(options, current) == result
153
+
154
+ reserve_attempt(intake, result, name, fresh['baseSha'])
155
+ remote.submit # Mutation acknowledgement is not evidence of the resulting remote state.
156
+ after = remote.inspect_pr
157
+ return report_remote(intake, result, after) if %w[merged head_changed closed].include?(after['status'])
158
+
159
+ observe(result, 'unconfirmed', 'The remote merge was not confirmed. Re-run without approval to observe; do not resend.')
160
+ end
161
+
162
+ def run(args)
163
+ if [%w[--help], %w[-h]].include?(args)
164
+ puts USAGE
165
+ return 0
166
+ end
167
+ options = arguments(args)
168
+ intake = WorkRelayVerify.intake_snapshot(options.fetch('--intake'))
169
+ WorkRelayHandoff.with_task_lock(intake) { reconcile(options, intake) }
170
+ rescue ResumePullRequest::HeadChanged => e
171
+ puts JSON.generate('status' => 'head_changed')
172
+ warn "Error: #{e.message}"
173
+ 1
174
+ rescue ResumePullRequest::Blocked, InvalidInput, RecordError => e
175
+ warn "Error: #{e.message}"
176
+ 1
177
+ rescue SystemCallError, IOError, ArgumentError, EncodingError, JSON::GeneratorError
178
+ warn 'Error: Cannot safely process the merge inputs or private records. Inspect the PR before retrying.'
179
+ 1
180
+ end
181
+ end
182
+
183
+ exit WorkRelayMerge.run(ARGV) if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,177 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative 'verify'
5
+
6
+ module WorkRelayRoute
7
+ OPTIONS = %w[--intake --method --pstack-root --skill --session].freeze
8
+ PSTACK_SKILLS = %w[tdd principle-prove-it-works].freeze
9
+ PLUGIN_FILE_LIMIT = 64 * 1024
10
+ USAGE = <<~TEXT
11
+ Usage: ruby route.rb --intake RECEIPT.json [--method native|pstack]
12
+ [--pstack-root DIRECTORY --skill tdd|principle-prove-it-works]
13
+ [--session REGISTERED_SESSION.json]
14
+
15
+ Bind a local task to one implementation owner; nothing is launched.
16
+ When selecting pstack, supply a trusted installed Codex plugin directory.
17
+ Output and the saved execution binding are private.
18
+ TEXT
19
+
20
+ InvalidInput = WorkRelayVerify::InvalidInput
21
+ RecordError = WorkRelayVerify::RecordError
22
+
23
+ module_function
24
+
25
+ def arguments(args)
26
+ options = {}
27
+ args.each_slice(2) do |key, value|
28
+ unless OPTIONS.include?(key) && !options.key?(key) && value && !value.empty? && !value.start_with?('--')
29
+ raise InvalidInput, 'Invalid or repeated routing option. Use --help for usage.'
30
+ end
31
+
32
+ options[key] = value
33
+ end
34
+ raise InvalidInput, 'A private intake receipt is required.' unless options.key?('--intake')
35
+
36
+ options
37
+ end
38
+
39
+ def plugin_file(root, parts, label)
40
+ path = root
41
+ parts[0...-1].each do |part|
42
+ path = File.join(path, part)
43
+ raise InvalidInput, "#{label} directory must not be a symlink." unless File.lstat(path).directory?
44
+ end
45
+ path = File.join(path, parts.last)
46
+ raise InvalidInput, "#{label} must be inside the selected plugin." unless File.realpath(path) == path
47
+
48
+ [path, WorkRelayIntake.read_regular(path, PLUGIN_FILE_LIMIT, label)]
49
+ end
50
+
51
+ def pstack_playbook(options)
52
+ unless options.key?('--pstack-root') && options.key?('--skill')
53
+ raise InvalidInput, 'pstack selected: specify a trusted installed plugin root and supported skill. No fallback.'
54
+ end
55
+
56
+ skill = options.fetch('--skill')
57
+ raise InvalidInput, 'Choose a supported pstack skill: tdd or principle-prove-it-works.' unless PSTACK_SKILLS.include?(skill)
58
+
59
+ requested_root = File.expand_path(options.fetch('--pstack-root'))
60
+ raise InvalidInput, 'pstack plugin root must be an existing directory, not a symlink.' unless File.lstat(requested_root).directory?
61
+
62
+ root = File.realpath(requested_root)
63
+ _, manifest = plugin_file(root, %w[.codex-plugin plugin.json], 'pstack manifest')
64
+ manifest = WorkRelayVerify.json(manifest, 'pstack manifest')
65
+ unless manifest.is_a?(Hash) && manifest['name'] == 'pstack'
66
+ raise InvalidInput, 'The selected directory does not contain the pstack Codex plugin.'
67
+ end
68
+ version = WorkRelayIntake.version(manifest['version'], 'pstack plugin version')
69
+ path, raw = plugin_file(root, ['skills', skill, 'SKILL.md'], 'pstack skill')
70
+ verify_frontmatter(raw, skill)
71
+
72
+ { 'name' => skill, 'path' => path, 'version' => version, 'sha256' => Digest::SHA256.hexdigest(raw) }
73
+ rescue SystemCallError, IOError
74
+ raise InvalidInput, 'The selected pstack installation or skill is unavailable; no fallback was selected.'
75
+ end
76
+
77
+ def verify_frontmatter(raw, skill)
78
+ require 'yaml'
79
+ frontmatter = /\A---[ \t]*\r?\n(.*?)^---[ \t]*\r?\n(.*)\z/m.match(raw)
80
+ unless frontmatter && !frontmatter[2].strip.empty?
81
+ raise InvalidInput, 'The pstack skill must contain metadata and nonempty guidance.'
82
+ end
83
+ data = YAML.safe_load(frontmatter[1], permitted_classes: [], permitted_symbols: [], aliases: false)
84
+ unless data.is_a?(Hash) && data['name'] == skill
85
+ raise InvalidInput, 'The pstack skill does not match the selected name.'
86
+ end
87
+ rescue Psych::Exception
88
+ raise InvalidInput, 'The pstack skill has invalid metadata.'
89
+ end
90
+
91
+ def workspace_path(intake)
92
+ path = intake.workspace.fetch('path')
93
+ unless File.lstat(path).directory? && File.realpath(path) == path
94
+ raise InvalidInput, 'The recorded workspace is no longer a canonical directory.'
95
+ end
96
+
97
+ path
98
+ rescue SystemCallError, IOError
99
+ raise InvalidInput, 'The recorded workspace is unavailable.'
100
+ end
101
+
102
+ def binding(options, intake)
103
+ method = WorkRelayIntake.implementation_method(options.fetch('--method', intake.implementation_method),
104
+ 'Implementation method')
105
+ if method == 'native' && (options.key?('--pstack-root') || options.key?('--skill'))
106
+ raise InvalidInput, 'pstack plugin and skill options are only valid when pstack is selected.'
107
+ end
108
+ workspace = workspace_path(intake)
109
+ playbook = pstack_playbook(options) if method == 'pstack'
110
+ if options.key?('--session')
111
+ require_relative 'lib/registered_session'
112
+ session = WorkRelaySession.resolve(options.fetch('--session'), intake)
113
+ end
114
+
115
+ { 'schemaVersion' => 1, 'status' => 'ready', 'task' => intake.task, 'intakeSha256' => intake.sha256,
116
+ 'source' => intake.source, 'method' => method, 'workspace' => workspace,
117
+ 'owner' => session ? 'registered-session' : 'current-agent', 'session' => session,
118
+ 'playbook' => playbook, 'integrationAuthority' => 'none' }
119
+ end
120
+
121
+ def compare_existing(path, expected)
122
+ raw = WorkRelayVerify.read_private(path, 'Execution binding')
123
+ existing = WorkRelayVerify.json(raw, 'Execution binding')
124
+ unless existing == expected && existing['schemaVersion'].is_a?(Integer)
125
+ raise RecordError, 'This task is already bound to a different intake, workspace, owner or implementation method.'
126
+ end
127
+
128
+ raw
129
+ end
130
+
131
+ def bind_once(intake, expected)
132
+ name = "#{intake.task}.execution.json"
133
+ path = File.join(intake.records, name)
134
+ # lstat, unlike exist?, recognizes dangling symlinks as conflicting records.
135
+ begin
136
+ File.lstat(path)
137
+ return compare_existing(path, expected)
138
+ rescue Errno::ENOENT
139
+ # The private writer below uses atomic create-only semantics.
140
+ end
141
+
142
+ data = JSON.pretty_generate(expected) + "\n"
143
+ begin
144
+ WorkRelayVerify.save_private(intake.records, name, data)
145
+ rescue RecordError
146
+ # A simultaneous equivalent binding can be reused; a conflicting or
147
+ # unreadable one must never be replaced.
148
+ raise unless File.exist?(path) || File.symlink?(path)
149
+
150
+ return compare_existing(path, expected)
151
+ end
152
+ data
153
+ end
154
+
155
+ def run(args)
156
+ if args == ['--help'] || args == ['-h']
157
+ puts USAGE
158
+ return 0
159
+ end
160
+
161
+ options = arguments(args)
162
+ intake = WorkRelayVerify.intake_snapshot(options.fetch('--intake'))
163
+ print bind_once(intake, binding(options, intake))
164
+ 0
165
+ rescue InvalidInput => e
166
+ warn "Error: #{e.message}"
167
+ 64
168
+ rescue RecordError => e
169
+ warn "Error: #{e.message}"
170
+ 73
171
+ rescue SystemCallError, IOError, EncodingError, JSON::GeneratorError, ArgumentError
172
+ warn 'Error: Cannot prepare the private execution binding.'
173
+ 74
174
+ end
175
+ end
176
+
177
+ exit WorkRelayRoute.run(ARGV) if $PROGRAM_NAME == __FILE__