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,382 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require_relative 'intake'
5
+ require 'time'
6
+
7
+ module WorkRelayVerify
8
+ INPUT_LIMIT = 1024 * 1024
9
+ RECORDED_RUN_LIMIT = 4 * INPUT_LIMIT
10
+ SHA256 = /\A[0-9a-f]{64}\z/
11
+ REVISION = /\A(?:[0-9a-f]{40}|[0-9a-f]{64})\z/
12
+ KINDS = %w[behavior scope].freeze
13
+ STATUSES = %w[pass fail unverified].freeze
14
+ STATES = %w[running interrupted needs_input blocked completed].freeze
15
+ INTAKE_KEYS = %w[skillVersion profile task source workspace recordsDir roles verification
16
+ destination suggestedDestination publicationAuthority].freeze
17
+ CRITERION_KEYS = %w[id kind required method outcome].freeze
18
+ PLAN_KEYS = %w[schemaVersion task intakeSha256 intakeSkillVersion verifierSkillVersion createdAt criteria].freeze
19
+ RESULT_KEYS = %w[planSha256 revision state nextAction checks].freeze
20
+ RUN_KEYS = (RESULT_KEYS + %w[schemaVersion task run intakeSha256 intakeSkillVersion verifierSkillVersion observedAt]).freeze
21
+
22
+ USAGE = <<~TEXT
23
+ Usage: ruby verify.rb plan --intake RECEIPT.json --criteria CRITERIA.json
24
+ ruby verify.rb record --intake RECEIPT.json --run RUN --results RESULTS.json
25
+
26
+ Freeze behavioral and scope criteria against an existing intake receipt.
27
+ Save private local observations without executing checks or accessing remotes.
28
+ Plan output is private. Record output contains only state and result counts.
29
+ TEXT
30
+
31
+ InvalidInput = WorkRelayIntake::InvalidInput
32
+ RecordError = WorkRelayIntake::RecordError
33
+ Intake = Struct.new(:task, :records, :sha256, :profile_criteria, :skill_version, :destination,
34
+ :workspace, :source, :implementation_method)
35
+
36
+ module_function
37
+
38
+ def parse_options(args)
39
+ command, *flags = args
40
+ required = case command
41
+ when 'plan' then %w[--intake --criteria]
42
+ when 'record' then %w[--intake --run --results]
43
+ else raise InvalidInput, 'Choose plan or record. Use --help for usage.'
44
+ end
45
+ options = {}
46
+ flags.each_slice(2) do |flag, value|
47
+ unless required.include?(flag) && !options.key?(flag) && value && !value.empty? && !value.start_with?('--')
48
+ raise InvalidInput, 'Invalid or repeated option. Use --help for usage.'
49
+ end
50
+ options[flag] = value
51
+ end
52
+ raise InvalidInput, 'A required option is missing. Use --help for usage.' unless options.size == required.size
53
+
54
+ [command, options]
55
+ end
56
+
57
+ def json(raw, label)
58
+ JSON.parse(raw, object_class: WorkRelayIntake::UniqueKeys, allow_duplicate_key: false)
59
+ rescue JSON::ParserError, InvalidInput
60
+ raise InvalidInput, "#{label} must be valid JSON without duplicate keys."
61
+ end
62
+
63
+ def private_file?(stat)
64
+ stat.file? && stat.uid == Process.euid && (stat.mode & 0o777) == 0o600
65
+ end
66
+
67
+ def read_private(path, label, limit: INPUT_LIMIT)
68
+ original = File.lstat(path)
69
+ raise InvalidInput, "#{label} must be a user-owned regular file with mode 0600." unless private_file?(original)
70
+
71
+ File.open(path, File::RDONLY | File::NONBLOCK | File::NOFOLLOW) do |io|
72
+ current = io.stat
73
+ unless private_file?(current) && [current.dev, current.ino] == [original.dev, original.ino]
74
+ raise InvalidInput, "#{label} changed while opening it."
75
+ end
76
+
77
+ WorkRelayIntake.bounded_utf8(io, limit, label)
78
+ end
79
+ rescue SystemCallError, IOError
80
+ raise InvalidInput, "Cannot read #{label.downcase} as a private regular file."
81
+ end
82
+
83
+ def owned_directory!(path)
84
+ dir = File.lstat(path)
85
+ unless dir.directory? && dir.uid == Process.euid && (dir.mode & 0o022).zero?
86
+ raise InvalidInput, 'Records directory must be user-owned and not writable by others.'
87
+ end
88
+ end
89
+
90
+ # Keep the existing handoff lock name: verification, publication, and merge
91
+ # must serialize against the same persistent inode, including across upgrades.
92
+ def with_task_lock(intake)
93
+ owned_directory!(intake.records)
94
+ path = File.join(intake.records, "#{intake.task}.handoff.lock")
95
+ flags = File::RDWR | File::CREAT | File::NONBLOCK | File::NOFOLLOW
96
+ File.open(path, flags, 0o600) do |lock|
97
+ current = lock.stat
98
+ unless private_file?(current) && current.nlink == 1 && lock.flock(File::LOCK_EX | File::LOCK_NB)
99
+ raise RecordError, 'Cannot lock this task; another verification, handoff or merge may be in progress.'
100
+ end
101
+
102
+ named = File.lstat(path)
103
+ unless [named.dev, named.ino] == [current.dev, current.ino]
104
+ raise RecordError, 'Task lock changed while opening.'
105
+ end
106
+
107
+ yield
108
+ end
109
+ end
110
+
111
+ def intake_snapshot(input)
112
+ intake_path = File.expand_path(input)
113
+ records = File.realpath(File.dirname(intake_path))
114
+ owned_directory!(records)
115
+ raw = read_private(File.join(records, File.basename(intake_path)), 'Intake receipt')
116
+ snap = WorkRelayIntake.object(json(raw, 'Intake receipt'), INTAKE_KEYS, 'Intake receipt',
117
+ %w[receiptSchemaVersion implementationMethod])
118
+ skill_version = WorkRelayIntake.version(snap['skillVersion'], 'Intake skill version')
119
+ if snap.key?('receiptSchemaVersion')
120
+ schema = snap['receiptSchemaVersion']
121
+ raise InvalidInput, 'Unsupported intake receipt schema.' unless schema.is_a?(Integer) && schema == 1
122
+ elsif skill_version != '0.1.0'
123
+ raise InvalidInput, 'Intake receipt is missing its schema version.'
124
+ end
125
+ task = WorkRelayIntake.slug(snap['task'], 'Intake task')
126
+ unless snap['recordsDir'] == records && File.basename(intake_path) == "#{task}.intake.json" &&
127
+ snap['publicationAuthority'] == 'not_granted'
128
+ raise InvalidInput, 'Intake receipt does not match this task or records directory.'
129
+ end
130
+
131
+ profile = WorkRelayIntake.object(snap['profile'], %w[id version], 'Intake profile')
132
+ WorkRelayIntake.slug(profile['id'], 'Intake profile id')
133
+ WorkRelayIntake.version(profile['version'], 'Intake profile version')
134
+ source = WorkRelayIntake.object(snap['source'], %w[type sha256], 'Intake source')
135
+ unless %w[chat file].include?(source['type']) && source['sha256'].is_a?(String) && SHA256.match?(source['sha256'])
136
+ raise InvalidInput, 'Intake source is invalid.'
137
+ end
138
+ workspace = WorkRelayIntake.object(snap['workspace'], %w[mode path], 'Intake workspace')
139
+ unless %w[current directory worktree].include?(workspace['mode']) &&
140
+ WorkRelayIntake.descriptive_text(workspace['path'], 'Intake workspace path').start_with?('/')
141
+ raise InvalidInput, 'Intake workspace is invalid.'
142
+ end
143
+ roles = WorkRelayIntake.object(snap['roles'], %w[implementer verifier], 'Intake roles')
144
+ roles.each_value { |value| WorkRelayIntake.descriptive_text(value, 'Intake role') }
145
+ %w[destination suggestedDestination].each do |field|
146
+ next if snap[field].nil?
147
+
148
+ destination = WorkRelayIntake.object(snap[field], %w[target base], 'Intake destination')
149
+ WorkRelayIntake.destination(destination['target'], destination['base'], 'Intake destination')
150
+ end
151
+ method = WorkRelayIntake.implementation_method(snap.fetch('implementationMethod', 'native'),
152
+ 'Intake implementation method')
153
+ Intake.new(task, records, Digest::SHA256.hexdigest(raw), profile_criteria(snap['verification']), skill_version,
154
+ snap['destination'], workspace, source, method)
155
+ rescue SystemCallError, IOError
156
+ raise InvalidInput, 'Cannot locate a private intake receipt.'
157
+ end
158
+
159
+ def profile_criteria(checks)
160
+ unless checks.is_a?(Array) && !checks.empty?
161
+ raise InvalidInput, 'Intake receipt has no verification criteria.'
162
+ end
163
+
164
+ checks.map.with_index(1) do |item, index|
165
+ check = WorkRelayIntake.object(item, %w[method outcome], 'Profile verification criterion')
166
+ check.each_value { |value| WorkRelayIntake.descriptive_text(value, 'Profile verification criterion') }
167
+ { 'id' => "profile-#{index}", 'kind' => 'behavior', 'required' => true }.merge(check)
168
+ end
169
+ end
170
+
171
+ def validated_criteria(value)
172
+ raise InvalidInput, 'Criteria must be an array.' unless value.is_a?(Array)
173
+
174
+ ids = {}
175
+ value.each do |item|
176
+ check = WorkRelayIntake.object(item, CRITERION_KEYS, 'Criterion')
177
+ id = WorkRelayIntake.slug(check['id'], 'Criterion id')
178
+ raise InvalidInput, 'Criterion ids must be unique.' if ids[id]
179
+
180
+ ids[id] = true
181
+ unless KINDS.include?(check['kind']) && [true, false].include?(check['required'])
182
+ raise InvalidInput, 'Each criterion must have a valid kind and boolean required flag.'
183
+ end
184
+ if check['kind'] == 'scope' && !check['required']
185
+ raise InvalidInput, 'Scope criteria must be required.'
186
+ end
187
+ %w[method outcome].each { |key| WorkRelayIntake.descriptive_text(check[key], 'Criterion method or outcome') }
188
+ end
189
+ unless value.any? { |check| check['kind'] == 'scope' }
190
+ raise InvalidInput, 'At least one required scope criterion is needed.'
191
+ end
192
+
193
+ value
194
+ end
195
+
196
+ def save_private(records, filename, data)
197
+ owned_directory!(records)
198
+ target = File.join(records, filename)
199
+ Tempfile.create('.verification-', records) do |file|
200
+ file.chmod(0o600)
201
+ file.binmode
202
+ file.write(data)
203
+ file.close
204
+ # Atomic, create-only: concurrent writers cannot replace a saved checkpoint.
205
+ File.link(file.path, target)
206
+ end
207
+ rescue Errno::EEXIST
208
+ raise RecordError, 'Verification record already exists; existing records are never overwritten.'
209
+ rescue SystemCallError, IOError
210
+ raise RecordError, 'Cannot safely create the private verification record.'
211
+ end
212
+
213
+ def plan_filename(task)
214
+ "#{task}.verification-plan.json"
215
+ end
216
+
217
+ def freeze_plan(options, intake, verifier_version)
218
+ raw = WorkRelayIntake.read_regular(options.fetch('--criteria'), INPUT_LIMIT, 'Criteria')
219
+ extra = json(raw, 'Criteria')
220
+ raise InvalidInput, 'Criteria must be an array.' unless extra.is_a?(Array)
221
+
222
+ criteria = validated_criteria(intake.profile_criteria + extra)
223
+ plan = { 'schemaVersion' => 1, 'task' => intake.task, 'intakeSha256' => intake.sha256,
224
+ 'intakeSkillVersion' => intake.skill_version, 'verifierSkillVersion' => verifier_version,
225
+ 'createdAt' => Time.now.utc.iso8601, 'criteria' => criteria }
226
+ content = JSON.pretty_generate(plan) + "\n"
227
+ raise InvalidInput, 'Verification plan is too large.' if content.bytesize > INPUT_LIMIT
228
+
229
+ save_private(intake.records, plan_filename(intake.task), content)
230
+ { 'planSha256' => Digest::SHA256.hexdigest(content), 'criteria' => criteria }
231
+ end
232
+
233
+ def load_plan(intake)
234
+ raw = read_private(File.join(intake.records, plan_filename(intake.task)), 'Verification plan')
235
+ plan = WorkRelayIntake.object(json(raw, 'Verification plan'), PLAN_KEYS, 'Verification plan')
236
+ unless plan['schemaVersion'].is_a?(Integer) && plan['schemaVersion'] == 1 &&
237
+ plan['task'] == intake.task && plan['intakeSha256'] == intake.sha256 &&
238
+ plan['intakeSkillVersion'] == intake.skill_version
239
+ raise InvalidInput, 'Verification plan does not match the intake receipt.'
240
+ end
241
+
242
+ WorkRelayIntake.descriptive_text(plan['createdAt'], 'Plan timestamp')
243
+ WorkRelayIntake.version(plan['verifierSkillVersion'], 'Plan verifier skill version')
244
+ criteria = validated_criteria(plan['criteria'])
245
+ unless criteria.first(intake.profile_criteria.size) == intake.profile_criteria
246
+ raise InvalidInput, 'Verification plan does not contain the frozen profile criteria.'
247
+ end
248
+
249
+ [criteria, Digest::SHA256.hexdigest(raw)]
250
+ end
251
+
252
+ def private_text(value, label, allow_blank: false)
253
+ unless value.is_a?(String) && (allow_blank || !value.strip.empty?) &&
254
+ !value.match?(/[[:cntrl:]&&[^\t\r\n]]/)
255
+ raise InvalidInput, "#{label} must be text#{allow_blank ? '' : ' and must not be empty'}."
256
+ end
257
+ end
258
+
259
+ def checked_outcomes(criteria, values)
260
+ raise InvalidInput, 'Checks must be an array covering every criterion.' unless values.is_a?(Array)
261
+
262
+ known = criteria.each_with_object({}) { |check, map| map[check.fetch('id')] = check }
263
+ observed = {}
264
+ values.each do |item|
265
+ unless item.is_a?(Hash) && STATUSES.include?(item['status'])
266
+ raise InvalidInput, 'Each check needs a valid observation status.'
267
+ end
268
+
269
+ detail = item['status'] == 'unverified' ? 'reason' : 'evidence'
270
+ WorkRelayIntake.object(item, ['id', 'status', detail], 'Observation')
271
+ id = item['id']
272
+ unless known.key?(id) && !observed.key?(id)
273
+ raise InvalidInput, 'Observation ids must match frozen criteria without duplicates.'
274
+ end
275
+
276
+ private_text(item[detail], 'Observation evidence or reason')
277
+ observed[id] = item
278
+ end
279
+ if observed.size != known.size
280
+ raise InvalidInput, 'Checks must be an array covering every criterion.'
281
+ end
282
+
283
+ criteria.map { |criterion| criterion.merge(observed.fetch(criterion['id'])) }
284
+ end
285
+
286
+ def completed_run(intake, run)
287
+ WorkRelayIntake.slug(run, 'Run id')
288
+ criteria, plan_sha = load_plan(intake)
289
+ raw = read_private(File.join(intake.records, "#{intake.task}.#{run}.verification.json"), 'Verification run',
290
+ limit: RECORDED_RUN_LIMIT)
291
+ result = WorkRelayIntake.object(json(raw, 'Verification run'), RUN_KEYS, 'Verification run')
292
+ unless result.values_at('schemaVersion', 'task', 'run', 'intakeSha256', 'intakeSkillVersion', 'planSha256') ==
293
+ [1, intake.task, run, intake.sha256, intake.skill_version, plan_sha] && result['schemaVersion'].is_a?(Integer)
294
+ raise InvalidInput, 'Verification run does not match the intake and frozen plan.'
295
+ end
296
+ WorkRelayIntake.version(result['verifierSkillVersion'], 'Run verifier skill version')
297
+ WorkRelayIntake.descriptive_text(result['observedAt'], 'Run timestamp')
298
+ unless result['state'] == 'completed' && result['revision'].is_a?(String) && REVISION.match?(result['revision'])
299
+ raise InvalidInput, 'Choose a completed verification run for the exact revision.'
300
+ end
301
+ private_text(result['nextAction'], 'Next action', allow_blank: true)
302
+ observations = result['checks']
303
+ unless observations.is_a?(Array) && observations.all? { |row| row.is_a?(Hash) }
304
+ raise InvalidInput, 'Verification run has invalid observations.'
305
+ end
306
+ input_checks = observations.map { |row| row.slice('id', 'status', 'reason', 'evidence') }
307
+ checks = checked_outcomes(criteria, input_checks)
308
+ unless checks == observations && checks.none? { |row| row['required'] && row['status'] != 'pass' }
309
+ raise InvalidInput, 'Completed verification run does not match the original criteria or a required check did not pass.'
310
+ end
311
+
312
+ result
313
+ end
314
+
315
+ def record_run(options, intake, verifier_version)
316
+ run = WorkRelayIntake.slug(options.fetch('--run'), 'Run id')
317
+ criteria, plan_sha = load_plan(intake)
318
+ raw_result = WorkRelayIntake.read_regular(options.fetch('--results'), INPUT_LIMIT, 'Results')
319
+ result = WorkRelayIntake.object(json(raw_result, 'Results'), RESULT_KEYS, 'Results')
320
+ unless result['planSha256'] == plan_sha
321
+ raise InvalidInput, 'Results do not match the frozen verification plan digest.'
322
+ end
323
+
324
+ revision = result['revision']
325
+ unless revision.is_a?(String) && REVISION.match?(revision)
326
+ raise InvalidInput, 'Results must identify a 40- or 64-character lowercase hex revision.'
327
+ end
328
+
329
+ state = result['state']
330
+ raise InvalidInput, 'Unknown verification state.' unless STATES.include?(state)
331
+
332
+ private_text(result['nextAction'], 'Next action', allow_blank: state == 'completed')
333
+ checks = checked_outcomes(criteria, result['checks'])
334
+ if state == 'completed' && checks.any? { |check| check['required'] && check['status'] != 'pass' }
335
+ raise InvalidInput, 'Verification cannot be completed while a required check failed or is unverified.'
336
+ end
337
+
338
+ private_record = result.merge('schemaVersion' => 1, 'task' => intake.task, 'run' => run,
339
+ 'intakeSha256' => intake.sha256, 'intakeSkillVersion' => intake.skill_version,
340
+ 'verifierSkillVersion' => verifier_version, 'observedAt' => Time.now.utc.iso8601,
341
+ 'checks' => checks)
342
+ content = JSON.pretty_generate(private_record) + "\n"
343
+ raise InvalidInput, 'Verification record is too large.' if content.bytesize > RECORDED_RUN_LIMIT
344
+
345
+ save_private(intake.records, "#{intake.task}.#{run}.verification.json", content)
346
+ counts = KINDS.each_with_object({}) do |kind, totals|
347
+ totals[kind] = STATUSES.each_with_object({}) { |status, by_status| by_status[status] = 0 }
348
+ end
349
+ checks.each { |check| counts.fetch(check.fetch('kind'))[check.fetch('status')] += 1 }
350
+ { 'state' => state, 'counts' => counts }
351
+ end
352
+
353
+ def run(args)
354
+ if args == ['--help'] || args == ['-h']
355
+ puts USAGE
356
+ return 0
357
+ end
358
+
359
+ command, options = parse_options(args)
360
+ intake = intake_snapshot(options.fetch('--intake'))
361
+ raw_version = WorkRelayIntake.read_regular(File.expand_path('../VERSION', __dir__), 128, 'Skill version')
362
+ verifier_version = WorkRelayIntake.version(raw_version.strip, 'Verifier skill version')
363
+ payload = if command == 'plan'
364
+ freeze_plan(options, intake, verifier_version)
365
+ else
366
+ with_task_lock(intake) { record_run(options, intake, verifier_version) }
367
+ end
368
+ puts JSON.pretty_generate(payload)
369
+ 0
370
+ rescue InvalidInput => e
371
+ warn "Error: #{e.message}"
372
+ 64
373
+ rescue RecordError => e
374
+ warn "Error: #{e.message}"
375
+ 73
376
+ rescue SystemCallError, IOError, EncodingError, JSON::GeneratorError, ArgumentError
377
+ warn 'Error: Cannot process the private verification data.'
378
+ 74
379
+ end
380
+ end
381
+
382
+ exit WorkRelayVerify.run(ARGV) if $PROGRAM_NAME == __FILE__