Repository navigation
Expand file tree
/
Copy pathagent_api.py
More file actions
3112 lines (2964 loc) · 229 KB
/
Copy pathagent_api.py
File metadata and controls
3112 lines (2964 loc) · 229 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Versioned agent operations and bounded client of the existing local HTTP owner.
Import/discovery use only the standard library. Pinned jsonschema is loaded by
argument validation, never by the application discovery route.
"""
import base64
import binascii
import copy
from collections import OrderedDict
from contextlib import contextmanager
import hashlib
import http.client
import json
import math
import os
from pathlib import Path
import re
import socket
import stat
import time
import threading
from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit
REGISTRY_VERSION = 1
REQUEST_LIMIT = 1024 * 1024
RESPONSE_LIMIT = 16 * 1024 * 1024
MCP_RESPONSE_LIMIT = 32 * 1024 * 1024
INLINE_LIMIT = 512 * 1024
DEPTH_LIMIT = 64
ID = {'type': 'string', 'pattern': '^[a-f0-9]{32}$'}
SHA = {'type': 'string', 'pattern': '^[a-f0-9]{64}$'}
REF = {'type': 'string', 'pattern': '^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$'}
NAME = {'type': 'string', 'pattern': '^[A-Za-z][A-Za-z0-9_-]{0,39}$'}
SLOT = '^[A-Za-z][A-Za-z0-9_-]{0,63}$'
ARTIFACT = {'type': 'string', 'pattern': '^[A-Za-z0-9][A-Za-z0-9_.-]{0,119}$',
'not': {'enum': ['artifact-manifest.json', 'custody-receipt.json']}}
class AgentAPIError(Exception):
"""Safe transport error: never contains a credential or remote traceback."""
def __init__(self, message, code='invalid', status=400, *, preflight_report=None, receipt=None):
super().__init__(message)
self.code, self.status = code, status
self.preflight_report = copy.deepcopy(preflight_report)
self.receipt = copy.deepcopy(receipt)
def encoded(value, *, ensure_ascii=True):
return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=ensure_ascii,
allow_nan=False).encode('utf-8')
def obj(properties=None, required=None):
properties = properties or {}
return {'type': 'object', 'properties': properties,
'required': list(properties) if required is None else required,
'additionalProperties': False}
def text(maximum, empty=False):
result = {'type': 'string', 'maxLength': maximum}
if not empty:
result.update(minLength=1, pattern=r'\S')
return result
def integer(minimum=0, maximum=None):
result = {'type': 'integer', 'minimum': minimum}
if maximum is not None:
result['maximum'] = maximum
return result
def array(items, maximum, minimum=0):
return {'type': 'array', 'items': items, 'minItems': minimum, 'maxItems': maximum}
def const(value):
return {'const': value}
GROUPS = array(text(120), 30, 1)
OPTIONAL_META = {'name': text(200), 'rights': text(1000), 'groups': GROUPS,
'parents': array(text(120), 30)}
B64 = {'type': 'string', 'maxLength': 4 * ((INLINE_LIMIT + 2) // 3),
'pattern': '^[A-Za-z0-9+/]*={0,2}$'}
PARAMETERS = {'type': 'object', 'maxProperties': 32, 'propertyNames': {'pattern': SLOT},
'additionalProperties': {'oneOf': [{'type': 'boolean'}, {'type': 'number'},
{'type': 'string', 'maxLength': 1024}]}}
BINDING = {'oneOf': [obj({'reference_id': REF, 'expected_sha256': SHA}),
obj({'kind': const('frozen_release'), 'release_id': SHA, 'expected_sha256': SHA}),
obj({'kind': const('run_artifact'), 'run_id': ID, 'artifact_name': ARTIFACT,
'expected_sha256': SHA})]}
BINDINGS = {'type': 'object', 'maxProperties': 32, 'propertyNames': {'pattern': SLOT},
'additionalProperties': BINDING}
EXTERNAL_INPUT = obj({'project_id': ID, 'recipe_id': REF, 'expected_sha256': SHA, 'inputs': BINDINGS})
RECIPES = ['image_classification', 'text_classification', 'audio_classification',
'mesh_validate_export', 'sequence_validate_export', 'pointcloud_validate_export',
'volume_validate_export', 'image_validate_export', 'text_validate_export', 'audio_validate_export']
TRAINING = {
'image_classification': obj({'epochs': integer(1, 5), 'batch_size': integer(1, 16),
'learning_rate': {'type': 'number', 'minimum': .00001, 'maximum': .01}, 'seed': integer(0, 2**32-1)}),
'text_classification': obj({'max_features': integer(64, 4096), 'alpha': {'type': 'number', 'minimum': .01, 'maximum': 10}}),
'audio_classification': obj({'C': {'type': 'number', 'minimum': .01, 'maximum': 100}}),
}
def graph_schema():
variants = []
for recipe in RECIPES + ['external_recipe']:
stages = {'input': EXTERNAL_INPUT, 'execute': PARAMETERS, 'output': obj()} if recipe == 'external_recipe' else {
'release': obj({'release_id': SHA}), 'validate': obj(), 'publish': obj()}
if recipe in TRAINING:
stages.update(train=TRAINING[recipe], evaluate=obj())
nodes = {'oneOf': [obj({'id': NAME, 'type': const(kind), 'definition_version': integer(1),
'parameters': params}) for kind, params in stages.items()]}
properties = {'schema_version': const(1), 'mode': const('real'), 'id': ID, 'revision': integer(1),
'name': text(120), 'recipe_version': const(1), 'recipe': const(recipe),
'nodes': array(nodes, 10, 1), 'edges': array(obj({k: NAME for k in ('from', 'output', 'to', 'input')}), 12),
'layout': {'type': 'object', 'maxProperties': 10, 'propertyNames': NAME,
'additionalProperties': obj({k: {'type': 'number', 'minimum': -10000, 'maximum': 10000} for k in ('x', 'y')})}}
required = [k for k in properties if k != 'layout' and not (k == 'recipe' and recipe == 'image_classification')]
variants.append(obj(properties, required))
return {'oneOf': variants}
ANNOTATIONS = {
'image_detection': obj({'boxes': array(obj({'label': text(80), 'x': {'type': 'number', 'minimum': 0},
'y': {'type': 'number', 'minimum': 0}, 'width': {'type': 'number', 'exclusiveMinimum': 0},
'height': {'type': 'number', 'exclusiveMinimum': 0}}), 500)}),
'image_classification': obj({'label': text(80)}), 'image_caption': obj({'caption': text(4000)}),
'text_classification': obj({'label': text(80)}),
'text_entities': obj({'spans': array(obj({'label': text(80), 'start': integer(), 'end': integer(1)}), 500)}),
'text_corpus': obj({'note': text(4000)}),
'audio_timed': obj({'segments': array(obj({'start_frame': integer(), 'end_frame': integer(1), 'channel': integer(),
'transcript': text(4000, True), 'label': text(80, True), 'speaker': text(120, True)}), 200, 1)}),
**{kind: obj({'note': text(4000, True)}) for kind in ('sequence_transport', 'mesh_geometry',
'pointcloud_geometry', 'volume_grid', 'field_sequence_fields')},
}
OUTPUT_SCHEMA = obj({'status': integer(100, 599), 'result': {}})
_OPERATIONS = []
def register(name, method, path, properties=None, required=None, *, schema=None, scopes=('inspect',),
mutation=False, query=(), injected=None, description=None, binary=()):
_OPERATIONS.append({'operation_id': name, 'mcp_name': name.replace('.', '_'),
'description': description or name.replace('.', ' ').replace('_', ' ') + '; existing domain authorization and validation apply.',
'method': method, 'path': path, 'inputSchema': dict(schema, type='object') if schema else obj(properties, required),
'outputSchema': OUTPUT_SCHEMA, 'scopes': list(scopes), 'side_effects': mutation,
'query': list(query), 'injected': injected or {}, 'binary_fields': list(binary)})
for name, path in [('context.get', 'workspace/context'), ('identity.get', 'access/session'),
('projects.list', 'workspace/projects'), ('recipes.list', 'workspace/definitions'),
('releases.list', 'workspace/releases'), ('releases.inputs', 'workbench/releases/input-candidates'),
('graphs.list', 'workspace/graphs'), ('runs.list', 'workspace/runs'),
('run_inputs.list', 'workspace/run-artifact-inputs')]:
register(name, 'GET', '/api/' + path)
register('projects.get', 'GET', '/api/workspace/projects/{project_id}', {'project_id': ID})
register('projects.open', 'POST', '/api/workspace/projects', {'root': text(160), 'manifest_path': text(512)}, scopes=('inspect', 'edit'), mutation=True)
register('projects.evidence', 'GET', '/api/workspace/projects/{project_id}/evidence/{reference_id}', {'project_id': ID, 'reference_id': REF})
register('recipes.inspect', 'GET', '/api/workspace/projects/{project_id}/recipes/{reference_id}',
{'project_id': ID, 'reference_id': REF, 'expected_sha256': SHA}, query=('expected_sha256',))
register('data.query', 'GET', '/api/workbench/records', {
'q': text(200, True), 'kind': {'enum': ['', 'image', 'text', 'sequence', 'mesh', 'audio', 'pointcloud', 'volume', 'field_sequence']},
'review': {'enum': ['', 'draft', 'human_reviewed', 'programmatically_verified']},
'sort': {'enum': ['', 'newest', 'oldest', 'name', 'review']}, 'task': {'enum': ['', *ANNOTATIONS]},
'label': text(80, True), 'group': text(120, True), 'rights': text(1000, True), 'offset': integer(), 'limit': integer(1, 100)},
required=[], query=('q', 'kind', 'review', 'sort', 'task', 'label', 'group', 'rights', 'offset', 'limit'))
for name, path in [('get', 'records'), ('history', 'history'), ('audio', 'audio-inspection'), ('mesh', 'mesh-inspection'), ('pointcloud', 'pointcloud-inspection')]:
register('data.' + name, 'GET', '/api/workbench/' + path + '/{record_id}', {'record_id': ID})
for name in ('responses', 'preferences'):
register('data.' + name, 'GET', '/api/workbench/records/{record_id}/' + name, {'record_id': ID})
register('data.volume', 'GET', '/api/workbench/volume-inspection/{record_id}', {'record_id': ID, 'axis': {'enum': ['x', 'y', 'z']}, 'index': integer()}, required=['record_id'], query=('axis', 'index'))
register('data.scientific', 'GET', '/api/workbench/records/{record_id}/scientific', {'record_id': ID, 'axis': {'enum': ['x', 'y', 'z']}, 'index': integer(), 'frame': integer(), 'field': text(120)}, required=['record_id'], query=('frame', 'field', 'axis', 'index'))
for kind in ('image', 'text'):
field = 'image' if kind == 'image' else 'text'
value = B64 if kind == 'image' else text(200000)
register('data.import_' + kind, 'POST', '/api/workbench/import', {field: value, **OPTIONAL_META},
required=[field, 'groups'], scopes=('inspect', 'edit'), mutation=True, injected={'kind': kind}, binary=[field] if kind == 'image' else [])
register('data.import_audio', 'POST', '/api/workbench/audio-import', {'wav': B64, **OPTIONAL_META}, required=['wav', 'groups'], scopes=('inspect', 'edit'), mutation=True, binary=['wav'])
for kind, names in [('mesh', ('mesh.ply', 'mesh.json')), ('pointcloud', ('points.ply', 'points.json')), ('volume', ('volume.npy', 'volume.json'))]:
register('data.import_' + kind, 'POST', '/api/workbench/' + kind + '-import', {'files': obj({name: B64 for name in names}), **OPTIONAL_META}, required=['files', 'groups'], scopes=('inspect', 'edit'), mutation=True, binary=['files'])
register('data.import_sequence', 'POST', '/api/workbench/sequence-import', {'files': {'oneOf': [obj({name: B64 for name in names}) for names in [('run.json', 'frames.jsonl')]]}, **OPTIONAL_META}, required=['files', 'groups'], scopes=('inspect', 'edit'), mutation=True, binary=['files'])
for kind, path, ids in [('project', '/api/workspace/projects/{project_id}/import-data/{reference_id}', {'project_id': ID, 'reference_id': REF}),
('run', '/api/workspace/runs/{run_id}/import-data/{artifact_name}', {'run_id': ID, 'artifact_name': ARTIFACT})]:
register('data.import_' + kind + '_scientific', 'POST', path, {**ids, 'expected_sha256': SHA, **OPTIONAL_META}, required=[*ids, 'expected_sha256'], scopes=('inspect', 'edit'), mutation=True)
register('data.save_draft', 'POST', '/api/workbench/records/{record_id}', schema={'oneOf': [obj({
'record_id': ID, 'revision': integer(), 'source_revision': integer(), 'task': const(task), 'annotation': annotation,
'groups': GROUPS, 'review': const('draft')}) for task, annotation in ANNOTATIONS.items()]}, scopes=('inspect', 'edit'), mutation=True)
register('responses.save_draft', 'POST', '/api/workbench/responses', {'id': ID, 'prompt_id': ID, 'revision': integer(),
'parent_revision': integer(), 'source_revision': integer(), 'completion': text(200000), 'review': const('draft')}, scopes=('inspect', 'edit'), mutation=True)
for family, path in [('caption', 'caption-proposals'), ('classification', 'text-classification-proposals')]:
register('proposals.'+family+'_list', 'GET', '/api/workbench/'+path)
register('proposals.'+family+'_get', 'GET', '/api/workbench/'+path+'/{job_id}', {'job_id': ID})
fields = {'job_id': ID, 'revision': integer(), 'decision': {'enum': ['reject', 'apply_draft']}}
if family == 'classification':
fields['labels'] = array(text(80), 30, 1)
register('proposals.'+family+'_decide', 'POST', '/api/workbench/'+path+'/decide/{job_id}', fields,
required=['job_id', 'revision', 'decision'], scopes=('inspect', 'edit'), mutation=True)
release = {'items': array(obj({'id': ID, 'revision': integer(), 'source_revision': integer()}), 5000, 1),
'ratios': obj({key: integer(0, 100) for key in ('train', 'validation', 'test')}), 'seed': integer(0, 2**32-1),
'format': const('canonical_v1'), 'preview_token': SHA}
register('releases.preview', 'POST', '/api/workbench/releases/preview', release, required=['items', 'ratios', 'seed'])
register('releases.freeze', 'POST', '/api/workbench/releases', release, required=['items', 'ratios', 'seed', 'preview_token'], scopes=('inspect', 'freeze'), mutation=True)
register('graphs.get', 'GET', '/api/workspace/graphs/{graph_id}', {'graph_id': ID})
register('graphs.create', 'POST', '/api/workspace/graphs', {'name': text(120), 'release_id': SHA, 'recipe': {'enum': RECIPES}}, required=['name', 'release_id'], scopes=('inspect', 'edit'), mutation=True)
register('graphs.create_external', 'POST', '/api/workspace/graphs/external', {'name': text(120), 'project_id': ID,
'recipe_id': REF, 'expected_sha256': SHA, 'inputs': BINDINGS, 'parameters': PARAMETERS}, required=['name', 'project_id', 'recipe_id', 'expected_sha256', 'inputs'], scopes=('inspect', 'edit'), mutation=True)
register('graphs.save', 'POST', '/api/workspace/graphs/{graph_id}', {'graph_id': ID, 'revision': integer(1), 'document': graph_schema()}, scopes=('inspect', 'edit'), mutation=True)
register('graphs.clone', 'POST', '/api/workspace/graphs/{graph_id}/clone', {'graph_id': ID, 'name': text(120)}, scopes=('inspect', 'edit'), mutation=True)
for name in ('validate', 'preflight_external'):
register('graphs.'+name, 'POST', '/api/workspace/graphs/{graph_id}/'+name.replace('_', '-'), {'graph_id': ID, 'revision': integer(1)})
for name, suffix in [('get', ''), ('progress', '/progress')]:
register('runs.'+name, 'GET', '/api/workspace/runs/{run_id}'+suffix, {'run_id': ID})
register('runs.predictions', 'GET', '/api/workspace/runs/{run_id}/predictions', {'run_id': ID, 'split': {'enum': ['validation', 'test']}}, required=['run_id'], query=('split',))
register('runs.submit_external', 'POST', '/api/workspace/runs/submit-external', {'request_key': {'type': 'string', 'pattern': '^[A-Za-z0-9_.:-]{8,128}$'}, 'graph_id': ID, 'graph_revision': integer(1), 'expected_digest': SHA, 'approval_id': ID}, scopes=('inspect', 'execute'), mutation=True,
description='Submit exact owner-granted material. Same request key/body reconciles admission; never creates a grant or automatically retries.')
register('runs.cancel', 'POST', '/api/workspace/runs/{run_id}/cancel', {'run_id': ID}, scopes=('inspect', 'cancel'), mutation=True)
register('runs.expose_test', 'POST', '/api/workspace/runs/{run_id}/expose-test', {'run_id': ID, 'reason': text(500)}, scopes=('inspect', 'expose-holdout'), mutation=True,
description='Irreversibly record disclosure of held-out classifier test results. Explicit expose-holdout scope required; non-idempotent, no automatic retry.')
register('runs.artifact_chunk', 'POST', '/api/workspace/runs/{run_id}/artifact-segment/{name}', {'run_id': ID, 'name': ARTIFACT, 'expected_sha256': SHA, 'offset': integer(), 'max_bytes': integer(1, 8*1024*1024)},
description='Read a bounded artifact segment; verify final reassembled whole SHA256 before use. Segment hash does not verify the whole artifact.')
def projected(properties):
"""Validate top-level domain shape; preserve unknown owned nested evidence."""
return {'type': 'object', 'properties': properties, 'required': list(properties), 'additionalProperties': True}
SEGMENT_SCHEMA = obj({'run_id': ID, 'name': ARTIFACT, 'expected_sha256': SHA,
'total_bytes': integer(0, 512*1024*1024), 'media_type': const('application/octet-stream'),
'offset': integer(0, 512*1024*1024), 'bytes': integer(0, 8*1024*1024),
'next_offset': integer(0, 512*1024*1024), 'eof': {'type': 'boolean'}, 'segment_sha256': SHA,
'data_base64': {'type': 'string', 'maxLength': 4*((8*1024*1024+2)//3), 'pattern': '^[A-Za-z0-9+/]*={0,2}$'},
'verification': const('segment_read_whole_hash_unverified')})
_LIST = {'type': 'array'}
_RECORD = projected({'id': ID, 'revision': integer(), 'kind': {'type': 'string'}})
_GRAPH = projected({'id': ID, 'revision': integer(1), 'nodes': _LIST, 'edges': _LIST})
_RUN = projected({'id': ID, 'state': {'type': 'string'}})
_SHAPES = {
'context.get': projected({'dataset_id': ID, 'mode': const('real')}),
'identity.get': projected({'catalog_id': ID, 'actor_id': ID, 'kind': const('agent'), 'scopes': _LIST}),
'projects.list': projected({'projects': _LIST, 'roots': _LIST}),
'projects.get': projected({'id': ID, 'manifest_sha256': SHA}),
'projects.open': projected({'id': ID, 'manifest_sha256': SHA}),
'projects.evidence': projected({'id': REF, 'text': {'type':'string'}, 'sha256': SHA}),
'recipes.list': projected({'recipes': _LIST, 'schema_version': const(1)}),
'recipes.inspect': projected({'definition': {'type':'object'}, 'receipt': {'type':'object'}, 'parameter_definitions': {'type':'object'}}),
'data.query': projected({'items': _LIST, 'total': integer(), 'offset': integer(), 'limit': integer(1,100)}),
'data.get': _RECORD, 'data.history': _LIST,
'data.responses': projected({'parent': _RECORD, 'responses': _LIST}),
'data.preferences': projected({'parent': _RECORD, 'responses': _LIST, 'judgments': _LIST}),
'data.save_draft': _RECORD,
'responses.save_draft': projected({'response': projected({'id': ID, 'prompt_id': ID, 'revision': integer()}), 'parent': _RECORD, 'changed': {'type':'boolean'}}),
'releases.list': _LIST, 'releases.inputs': projected({'releases': _LIST}),
'releases.preview': projected({'eligible': {'type':'boolean'}, 'blockers': _LIST}),
'releases.freeze': projected({'id': SHA, 'url': {'type':'string'}, 'records': integer()}),
'graphs.list': _LIST, 'graphs.get': _GRAPH, 'graphs.create': _GRAPH, 'graphs.create_external': _GRAPH,
'graphs.save': _GRAPH, 'graphs.clone': _GRAPH,
'graphs.validate': projected({'valid': {'type':'boolean'}, 'errors': _LIST}),
'graphs.preflight_external': projected({'valid': {'type':'boolean'}, 'material_sha256': SHA, 'material': {'type':'object'}}),
'run_inputs.list': projected({'runs': _LIST}), 'runs.list': _LIST, 'runs.get': _RUN,
'runs.submit_external': _RUN, 'runs.cancel': _RUN,
'runs.progress': projected({'run_id': ID, 'state': {'type':'string'}, 'evidence': {'type':'string'}}),
'runs.predictions': projected({'rows': _LIST}),
'runs.expose_test': projected({'id': ID, 'run_id': ID, 'release_id': SHA, 'reason': text(500),
'test_exposure': obj({'exposed': const(True), 'event_count': integer(1)})}),
'runs.artifact_chunk': SEGMENT_SCHEMA,
}
for _kind in ('audio','mesh','pointcloud','volume','scientific'):
_SHAPES['data.'+_kind] = projected({'id': ID, 'content_hash': SHA})
for _op in _OPERATIONS:
_name = _op['operation_id']
if _name.startswith('data.import_'):
_SHAPES[_name] = _RECORD
if _name.startswith('proposals.'):
_SHAPES[_name] = (projected({'jobs': _LIST}) if _name.endswith('_list') else
projected({'job': {'type':'object'}, 'changed': {'type':'boolean'}}) if _name.endswith('_decide') else
projected({'id': ID, 'status': {'type':'string'}}))
_op['outputSchema'] = {'type':'object', 'oneOf': [
obj({'status': integer(200,299), 'result': _SHAPES[_name]}),
obj({'status': integer(400,599), 'result': obj({'error': text(1000), 'code': text(120)}, required=['error'])})]}
EXCLUSIONS = ['owner review and execution grants', 'credential administration', 'provider/model discovery or execution',
'ordinary run submit/retry', 'backup/restore/runtime snapshots', 'bulk native import workflows',
'saved search/selection mutations', 'alternate release projections', 'arbitrary files/URLs', 'non-Run binary download tools']
LIMITS = {'request_bytes': REQUEST_LIMIT, 'http_response_bytes': RESPONSE_LIMIT, 'mcp_response_bytes': MCP_RESPONSE_LIMIT,
'inline_decoded_bytes': INLINE_LIMIT, 'json_depth': DEPTH_LIMIT, 'artifact_segment_bytes': 8*1024*1024}
# These IDs and bytes belong to installed f588 strict clients. New operations
# belong to the same registry but never silently enter the legacy projection.
_LEGACY_IDS = ('context.get', 'identity.get', 'projects.list', 'recipes.list', 'releases.list', 'releases.inputs', 'graphs.list', 'runs.list', 'run_inputs.list', 'projects.get', 'projects.open', 'projects.evidence', 'recipes.inspect', 'data.query', 'data.get', 'data.history', 'data.audio', 'data.mesh', 'data.pointcloud', 'data.responses', 'data.preferences', 'data.volume', 'data.scientific', 'data.import_image', 'data.import_text', 'data.import_audio', 'data.import_mesh', 'data.import_pointcloud', 'data.import_volume', 'data.import_sequence', 'data.import_project_scientific', 'data.import_run_scientific', 'data.save_draft', 'responses.save_draft', 'proposals.caption_list', 'proposals.caption_get', 'proposals.caption_decide', 'proposals.classification_list', 'proposals.classification_get', 'proposals.classification_decide', 'releases.preview', 'releases.freeze', 'graphs.get', 'graphs.create', 'graphs.create_external', 'graphs.save', 'graphs.clone', 'graphs.validate', 'graphs.preflight_external', 'runs.get', 'runs.progress', 'runs.predictions', 'runs.submit_external', 'runs.cancel', 'runs.expose_test', 'runs.artifact_chunk')
_LEGACY_DIGEST = 'cb070a69ebd35b48e4f95a57ca01647c75bd7567521429e49efc3a3a1daebae8'
_legacy_by_id = {op['operation_id']: op for op in _OPERATIONS}
_PAYLOAD = {'version': 1, 'operations': [copy.deepcopy(_legacy_by_id[name]) for name in _LEGACY_IDS],
'limits': copy.deepcopy(LIMITS), 'exclusions': copy.deepcopy(EXCLUSIONS)}
REGISTRY_DIGEST = hashlib.sha256(encoded(_PAYLOAD)).hexdigest()
if REGISTRY_DIGEST != _LEGACY_DIGEST:
raise RuntimeError('Frozen legacy agent contract changed; preserve its actual projection.')
# Additive contracts share the registry owner while the actual legacy projection
# above remains frozen. Model-aware trainer/evidence capabilities are not added here.
SAFE_NAT = integer(0, 2**53-1)
SAFE_POS = integer(1, 2**53-1)
KEY = {'type':'string','pattern':'^[A-Za-z0-9][A-Za-z0-9_.:-]{7,127}$'}
def material_ref(kind, revision=False):
fields={'kind':const(kind),'catalog_id':ID,'id':SHA if kind in ('recipe_material','runtime','release') else ID,
'sha256':SHA}
if revision:fields['revision']=SAFE_POS
return obj(fields)
MODEL_REF=material_ref('model',True)
MATERIAL_REF=material_ref('recipe_material')
POLICY_REF=material_ref('selection_policy',True)
TASK_REF=obj({'kind':const('task'),'catalog_id':ID,'id':text(64),'revision':SAFE_POS,'sha256':SHA})
JSON_OBJECT={'type':'object','maxProperties':128}
MODEL_FIELDS={'name':text(120),'task':TASK_REF,'kind':{'enum':['template','captured_source']},
'specification':JSON_OBJECT,'source_selector':{'oneOf':[{'type':'null'},obj({'project_id':ID,'recipe_id':REF,'expected_sha256':SHA})]},
'preprocessing_policy':JSON_OBJECT,'output_policy':JSON_OBJECT}
MODEL_DRAFT=obj(dict(MODEL_FIELDS,format=const('model_draft_v1'),id=ID,revision=SAFE_POS))
BUDGET=obj({key:SAFE_POS for key in ('attempt_slots','admitted_wall_seconds','retained_bytes','peak_staging_bytes')})
SELECTION_POLICY=obj({'format':const('selection_policy_v1'),'metric_definition_sha256':SHA,
'checkpoint_rule':{'enum':['selected','last','explicit']},'replicate_reduce':{'enum':['individual','mean']},
'required_capabilities':array(text(64),64),'numerical_acceptance':{'enum':['required','diagnostic']},'tie_break':const('trial_id')})
def model_operation(name,method,path,properties=None,required=None,*,output=None,scopes=('inspect',),mutation=False,
query=(),description=None):
register(name,method,path,properties,required,scopes=scopes,mutation=mutation,query=query,description=description)
_OPERATIONS[-1]['outputSchema']={'type':'object','oneOf':[
obj({'status':integer(200,299),'result':output or {'type':'object'}}),
obj({'status':integer(400,599),'result':obj({'error':text(1000),'code':text(120)},required=['error'])})]}
for _name,_path,_key in [('models','models','model_id'),('studies','studies','study_id')]:
model_operation(_name+'.list','GET','/api/workspace/'+_path,output=array({'type':'object'},10000))
model_operation(_name+'.get','GET','/api/workspace/'+_path+'/{'+_key+'}',{_key:ID})
model_operation('models.create','POST','/api/workspace/models',MODEL_FIELDS,scopes=('inspect','edit'),mutation=True,output=MODEL_DRAFT)
model_operation('models.save','POST','/api/workspace/models/{model_id}',{'model_id':ID,'revision':SAFE_POS,'document':MODEL_DRAFT},
scopes=('inspect','edit'),mutation=True,output=MODEL_DRAFT)
model_operation('models.publish','POST','/api/workspace/models/{model_id}/publish',
{'model_id':ID,'revision':SAFE_POS,'reconcile_capture':{'type':'boolean'}},['model_id','revision'],scopes=('inspect','edit'),mutation=True)
model_operation('models.material','POST','/api/workspace/model-material',{'ref':MODEL_REF})
model_operation('recipes.material','POST','/api/workspace/recipe-material',{'ref':MATERIAL_REF})
model_operation('recipes.preflight_material','POST','/api/workspace/recipe-material/preflight',{'ref':MATERIAL_REF},
description='Revalidate exact retained external Study material without execution, grant or reservation; native builtin probes are unsupported.')
model_operation('studies.trial','GET','/api/workspace/trials/{trial_id}',{'trial_id':ID})
model_operation('studies.create','POST','/api/workspace/studies',{'name':text(120),'limits':BUDGET,'policy':SELECTION_POLICY},
scopes=('inspect','edit'),mutation=True)
model_operation('studies.save','POST','/api/workspace/studies/{study_id}',
{'study_id':ID,'revision':SAFE_POS,'name':text(120),'limits':BUDGET,'policy':POLICY_REF},scopes=('inspect','edit'),mutation=True)
model_operation('studies.prepare_trial','POST','/api/workspace/studies/{study_id}/prepare-trial',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'graph_id':ID,'graph_revision':SAFE_POS,'model':MODEL_REF,'replicate':SAFE_NAT,
'reconcile_capture':{'type':'boolean'}},['study_id','request_key','revision','graph_id','graph_revision','model','replicate'],
scopes=('inspect','edit'),mutation=True)
model_operation('studies.continue','POST','/api/workspace/studies/{study_id}/continue',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'admission_epoch':SAFE_NAT},scopes=('inspect','execute'),mutation=True)
model_operation('studies.approve','POST','/api/workspace/studies/{study_id}/approve',
{'study_id':ID,'trial_id':ID,'expected_material_sha256':SHA,'consumer_actor_id':ID,'ttl_seconds':integer(60,3600)},
['study_id','trial_id','expected_material_sha256','consumer_actor_id'],scopes=('inspect','approve-execution'),mutation=True)
model_operation('studies.admit','POST','/api/workspace/studies/{study_id}/admit',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'admission_epoch':SAFE_NAT,'trial_id':ID,'approval_id':ID,'parent_run_id':ID},
['study_id','request_key','revision','admission_epoch','trial_id'],scopes=('inspect','execute'),mutation=True)
model_operation('studies.stop','POST','/api/workspace/studies/{study_id}/stop',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS},scopes=('inspect','cancel'),mutation=True)
model_operation('studies.reconcile','POST','/api/workspace/studies/{study_id}/reconcile',{'study_id':ID},mutation=True)
# Stable typed output bodies participate in each new contract identity.
_BLOB=obj({'name':text(80),'sha256':SHA,'bytes':SAFE_NAT,'media_type':text(80)})
_MODEL_MATERIAL=obj({'format':const('model_material_v1'),'catalog_id':ID,'model_definition_id':ID,
'model_definition_revision':SAFE_POS,'task':TASK_REF,'kind':{'enum':['template','captured_source']},
'entrypoint':text(1000),'source_selector':MODEL_FIELDS['source_selector'],
'source_closure':array(obj({'import_path':text(1000),'blob':_BLOB}),64,1),
'specification':_BLOB,'preprocessing_policy':_BLOB,'output_policy':_BLOB})
_STUDY=obj({'format':const('study_v1'),'id':ID,'revision':SAFE_POS,'name':text(120),'admission_epoch':SAFE_NAT,
'open':{'type':'boolean'},'state':{'enum':['draft','open','stopping','stopped','unknown']},'limits':BUDGET,
'policy':POLICY_REF,'membership_revision':SAFE_POS,'trial_ids':array(ID,10000),
'stop_receipt_id':{'oneOf':[ID,{'type':'null'}]}})
_TRIAL=obj({'format':const('trial_v1'),'id':ID,'study_id':ID,'material':MATERIAL_REF,'replicate':SAFE_NAT})
_CHARGE=obj({key:SAFE_NAT for key in BUDGET['properties']})
_RESERVATION=obj({'id':ID,'study_id':ID,'admission_epoch':SAFE_NAT,'request_key':KEY,'actor_id':ID,'trial_id':ID,
'parent_run_id':{'oneOf':[ID,{'type':'null'}]},'run_id':ID,'request_sha256':SHA,'material_sha256':SHA,
'envelope':BUDGET,'state':{'enum':['reserved','running','settled','unknown']},'settled':{'oneOf':[_CHARGE,{'type':'null'}]}})
_STUDY_VIEW=obj({'study':_STUDY,'reservations':array(_RESERVATION,100),'charged':_CHARGE})
_DEFINITION_REF=lambda kind:obj({'kind':const(kind),'catalog_id':ID,'id':text(64),'revision':SAFE_POS,'sha256':SHA})
_RECIPE_MATERIAL=obj({'format':const('recipe_material_v1'),'catalog_id':ID,'recipe_id':ID,'recipe_revision':SAFE_POS,
'recipe_document':_BLOB,'executable_sha256':SHA,'model':MODEL_REF,'data':array(material_ref('release'),64),
'trainer':_DEFINITION_REF('trainer'),'evaluation_profile':_DEFINITION_REF('profile'),'resolved_profile':_BLOB,
'runtime':material_ref('runtime'),'captures':array(_BLOB,128,1),'resource_envelope':BUDGET})
_RECIPE_FIELDS={'name':text(120),'task':TASK_REF,'data':array(material_ref('release'),64,1),'model':MODEL_REF,
'trainer':_DEFINITION_REF('trainer'),'parameters':JSON_OBJECT,'evaluation_profile':_DEFINITION_REF('profile'),
'runtime':material_ref('runtime'),'layout':{'type':'object','maxProperties':10,
'additionalProperties':obj({'x':{'type':'number','minimum':-10000,'maximum':10000},
'y':{'type':'number','minimum':-10000,'maximum':10000}})}}
_RECIPE_DRAFT=obj(dict(_RECIPE_FIELDS,format=const('recipe_draft_v2'),id=ID,revision=SAFE_POS))
model_operation('recipes.list_drafts','GET','/api/workspace/model-recipes',output=array(_RECIPE_DRAFT,10000))
model_operation('recipes.get','GET','/api/workspace/model-recipes/{recipe_id}',{'recipe_id':ID},output=_RECIPE_DRAFT)
model_operation('recipes.create','POST','/api/workspace/model-recipes',_RECIPE_FIELDS,
scopes=('inspect','edit'),mutation=True,output=_RECIPE_DRAFT)
model_operation('recipes.save','POST','/api/workspace/model-recipes/{recipe_id}',
{'recipe_id':ID,'revision':SAFE_POS,'document':_RECIPE_DRAFT},scopes=('inspect','edit'),mutation=True,output=_RECIPE_DRAFT)
_NEW_OUTPUTS={'models.list':array(MODEL_DRAFT,10000),'models.get':MODEL_DRAFT,
'models.publish':obj({'ref':MODEL_REF,'material':_MODEL_MATERIAL}),
'models.material':obj({'ref':MODEL_REF,'material':_MODEL_MATERIAL}),
'recipes.material':obj({'ref':MATERIAL_REF,'material':_RECIPE_MATERIAL}),
'studies.list':array(_STUDY_VIEW,10000),'studies.get':_STUDY_VIEW,'studies.trial':_TRIAL,
'studies.create':_STUDY,'studies.save':_STUDY,'studies.prepare_trial':_TRIAL,'studies.continue':_STUDY,
'studies.admit':obj({'reservation':_RESERVATION,'run':_RUN}),
'studies.approve':obj({'id':ID,'catalog_id':ID,'approver_actor_id':ID,'approver_credential_id':ID,
'consumer_actor_id':ID,'material_sha256':SHA,'created_at':SAFE_NAT,'expires_at':SAFE_NAT,'revoked_at':{'type':'null'}}),
'studies.stop':obj({'receipt':obj({'study_id':ID,'stop_receipt_id':ID,'admission_epoch':SAFE_NAT,'run_ids':array(ID,10000)}),
'status':_STUDY_VIEW}),'studies.reconcile':_STUDY_VIEW}
for _op in _OPERATIONS:
if _op['operation_id'] in _NEW_OUTPUTS:
_op['outputSchema']['oneOf'][0]['properties']['result']=_NEW_OUTPUTS[_op['operation_id']]
_PAGE_CURSOR={'oneOf':[ID,{'type':'null'}]}
_STUDY_PAGE=obj({'offset':SAFE_NAT,'limit':integer(1,100),'total':SAFE_NAT,'study_revision':SAFE_POS,
'next_offset':{'oneOf':[SAFE_NAT,{'type':'null'}]}})
_STUDY_VIEW['properties']['page']=_STUDY_PAGE
_STUDY_VIEW['required'].append('page')
_STUDY_SUMMARY=copy.deepcopy(_STUDY)
_STUDY_SUMMARY['properties'].pop('trial_ids');_STUDY_SUMMARY['required'].remove('trial_ids')
_STUDY_SUMMARY['properties']['trial_count']=integer(0,10000);_STUDY_SUMMARY['required'].append('trial_count')
_COLLECTION_OUTPUTS={'models.list':obj({'models':array(MODEL_DRAFT,20),'limit':integer(1,20),'next_cursor':_PAGE_CURSOR}),
'recipes.list_drafts':obj({'recipes':array(_RECIPE_DRAFT,20),'limit':integer(1,20),'next_cursor':_PAGE_CURSOR}),
'studies.list':obj({'studies':array(_STUDY_SUMMARY,20),'limit':integer(1,20),'next_cursor':_PAGE_CURSOR})}
for _op in _OPERATIONS:
if _op['operation_id'] in _COLLECTION_OUTPUTS:
_op['inputSchema']=obj({'cursor':ID,'limit':integer(1,20)},[]);_op['query']=['cursor','limit']
_op['outputSchema']['oneOf'][0]['properties']['result']=_COLLECTION_OUTPUTS[_op['operation_id']]
elif _op['operation_id']=='studies.get':
_op['inputSchema']=obj({'study_id':ID,'offset':SAFE_NAT,'limit':integer(1,100),'revision':SAFE_POS},['study_id'])
_op['query']=['offset','limit','revision']
_OWNER_OPERATION_IDS={'studies.create','studies.save','studies.continue','studies.approve'}
_MODEL_RECEIPT_IDS={'studies.prepare_trial','studies.continue','studies.admit','studies.stop'}
_MODEL_RECEIPT_IDS.add('studies.select_candidate')
_MODEL_RECEIPT_IDS.update({'studies.record_lineage','studies.branch_trial','studies.prepare_branch'})
_CANDIDATE=obj({'format':const('candidate_v1'),'id':ID,'study_id':ID,'trial_id':ID,'run_id':ID,
'checkpoint_sha256':SHA,'evaluation_sha256':SHA,'policy':POLICY_REF,
'decision':{'enum':['qualified','diagnostic']},'limitations':array(text(500),64)})
_CANDIDATE_RESULT=obj({'ref':material_ref('candidate'),'candidate':_CANDIDATE,'run_id':ID,'checkpoint':_BLOB})
model_operation('studies.select_candidate','POST','/api/workspace/studies/{study_id}/select-candidate',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'trial_id':ID,'run_id':ID,'checkpoint_sha256':SHA},
['study_id','request_key','revision','trial_id','run_id'],output=_CANDIDATE_RESULT,
scopes=('inspect','edit'),mutation=True)
model_operation('studies.candidate','GET','/api/workspace/candidates/{candidate_id}',
{'candidate_id':ID},output=_CANDIDATE_RESULT)
model_operation('studies.candidates','GET','/api/workspace/runs/{run_id}/candidates',
{'run_id':ID,'cursor':ID,'limit':integer(1,20)},['run_id'],
output=obj({'run_id':ID,'candidates':array(material_ref('candidate'),20),
'limit':integer(1,20),'next_cursor':_PAGE_CURSOR}))
_OPERATIONS[-1]['query']=['cursor','limit']
_PACKAGE_PREPARE_FIELDS={'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'candidate_id':ID,
'root':REF,'directory':ARTIFACT,'runtime_snapshot_sha256':SHA}
_PACKAGE_PREPARED_FIELDS={'state':const('prepared'),'candidate_id':ID,'trial':_TRIAL,
'graph':_GRAPH,'model':MODEL_REF,'runtime_snapshot_sha256':SHA}
for _action in ('package','verifier'):
_fields=dict(_PACKAGE_PREPARE_FIELDS);_result=dict(_PACKAGE_PREPARED_FIELDS)
if _action=='verifier':
_fields.update(package_run_id=ID,package_sha256=SHA)
_result.update(package_run_id=ID,package_sha256=SHA)
_name='studies.prepare_'+_action
model_operation(_name,'POST','/api/workspace/studies/{study_id}/prepare-'+_action,
_fields,output=obj(_result),scopes=('inspect','edit'),mutation=True)
_OWNER_OPERATION_IDS.add(_name);_MODEL_RECEIPT_IDS.add(_name)
model_operation('studies.package_state','GET','/api/workspace/candidates/{candidate_id}/package-state',
{'candidate_id':ID},output=obj({'candidate':_CANDIDATE_RESULT,
'state':{'enum':['selected','package_complete','fresh_verified']},
'packages':array(obj({'run_id':ID,'sha256':SHA,'bytes':SAFE_POS,'artifact_name':const('package.zip'),
'url':text(512)}),100),
'verifications':array(obj({'run_id':ID,'receipt':{'type':'object','maxProperties':64}}),100)}))
# Model evidence has a task-owned decoder. The public projection binds the
# complete result variant while retaining its bounded, versioned domain bodies.
_EVIDENCE_DOCUMENT={'type':'object','maxProperties':128}
_EVIDENCE_RESULT={'oneOf':[
obj({'state':const('unsupported'),'reason':text(1000)}),
obj({'state':const('verified'),'manifest':_EVIDENCE_DOCUMENT,
'checkpoint_index':_EVIDENCE_DOCUMENT,'probe':_EVIDENCE_DOCUMENT,
'metric_definitions':{'type':['object','array']},
'metric_definition_hashes':{'type':'object','maxProperties':64,
'propertyNames':text(64),'additionalProperties':SHA},
'observations':array(_EVIDENCE_DOCUMENT,1000),
'model_definition':_EVIDENCE_DOCUMENT,
'checkpoint':{'oneOf':[{'type':'null'},_EVIDENCE_DOCUMENT]},
'predictions':{'oneOf':[{'type':'null'},_EVIDENCE_DOCUMENT]}})]}
model_operation('runs.model_evidence','POST','/api/workspace/runs/{run_id}/model-evidence',
{'run_id':ID,'checkpoint_sha256':SHA},['run_id'],output=_EVIDENCE_RESULT)
from retained_analysis_schema import schemas as _retained_analysis_schemas
_retained_request, _retained_result = _retained_analysis_schemas(obj, text, integer, array, const, ID, SHA)
for _name, _suffix in (('runs.retained_analysis', ''), ('runs.export_retained_analysis', '/export')):
model_operation(_name, 'POST', '/api/workspace/runs/{run_id}/retained-analysis' + _suffix,
_retained_request['properties'], _retained_request['required'], output=_retained_result,
description='Read one exact retained classifier curve and bounded example page; current inspect access required.')
model_operation('runs.compare_model_evidence','POST','/api/workspace/runs/{run_id}/compare-model-evidence',
{'run_id':ID,'other_run_id':ID},output=obj({
'state':{'enum':['compatible','incompatible']},'run_ids':array(ID,2,2),
'reasons':array(text(1000),64),
'metrics':array(obj({'metric_id':text(64),
'values':array({'type':'number'},2,2),
'direction':{'enum':['minimize','maximize','none']},'units':text(80)}),64)}))
# Snapshot projections describe inert declarations, not runtime or execution grants.
_SNAPSHOT_SUMMARY={'id':ID,'name':text(120),'root':text(160),
'manifest_path':text(512),'manifest_sha256':SHA,'schema_version':{'enum':[1,2]}}
_SNAPSHOT_REFERENCE=obj({'id':REF,'label':text(160),'path':text(512),'sha256':SHA,
'status':{'enum':['available','missing','unavailable','present_unqualified','unverified']},
'integrity':{'enum':['unverified','verified','mismatch']},'reason':text(1000),
'bytes':SAFE_NAT,'observed_sha256':SHA},['id','label','status'])
_DECLARATION_STATE={'enum':['valid','invalid','unavailable','unsupported']}
_DECLARED_RUNTIME=obj({'profile':text(64),'snapshot_sha256':SHA},['profile'])
_DECLARED_RESOURCES=obj({'wall_seconds':integer(1,86400),
'source_bytes':integer(1,64*1024**2),'output_bytes':integer(1,64*1024**2)})
_UNQUALIFIED_FACET=obj({'state':const('unavailable'),'reason':text(1000)})
_SNAPSHOT_CONTRIBUTION=obj({'id':text(129),'version':text(32),
'kind':{'enum':['task','reader','model','trainer','evaluator','view']},
'path':text(512),'sha256':SHA,'bytes':SAFE_NAT,'state':_DECLARATION_STATE,
'definition':JSON_OBJECT,'reason':text(1000)},
['id','version','kind','path','sha256','bytes','state'])
_SNAPSHOT_PACKAGE=obj({'id':REF,'label':text(160),'path':text(512),'sha256':SHA,
'enabled':{'type':'boolean'},'discovered':{'type':'boolean'},'state':_DECLARATION_STATE,
'integrity':{'enum':['unverified','verified','mismatch']},
'contributions':array(_SNAPSHOT_CONTRIBUTION,64),
'host':{'oneOf':[_UNQUALIFIED_FACET,obj({'state':{'enum':['compatible','unsupported']},
'required':array(obj({'id':text(80),'version':text(32)}),64)})]},
'runtime':_UNQUALIFIED_FACET,'permission':_UNQUALIFIED_FACET,
'observed_sha256':SHA,'reason':text(1000),
'package':obj({'id':text(64),'version':text(32)}),'declared_runtime':_DECLARED_RUNTIME,
'effects':dict(array({'enum':['filesystem','network','subprocess']},3),uniqueItems=True),
'resources':_DECLARED_RESOURCES},
['id','label','path','sha256','enabled','discovered','state','integrity',
'contributions','host','runtime','permission'])
_SNAPSHOT_CATALOG=obj({'mode':const('inspection'),'execution':const('unsupported'),
'schema_sha256':obj({name:SHA for name in ('extension','contribution','parameter')},[]),
'bytes_inspected':integer(0,8*1024**2),'inspection_budget_consumed':integer(0,8*1024**2),
'packages':array(_SNAPSHOT_PACKAGE,64)})
# External activity is a bounded projection of ordinary evidence id "activity".
# It cannot make a Run or establish custody or scientific acceptance.
_ACTIVITY_COMMON={'authority':const('external_observation'),'reference_id':const('activity')}
_ACTIVITY={'oneOf':[
obj(dict(_ACTIVITY_COMMON,available=const(False),reason=text(1000))),
obj(dict(_ACTIVITY_COMMON,available=const(True),schema_version=const(1),
producer=text(120),sequence=SAFE_NAT,updated_at=text(80),
state={'enum':['idle','running','completed','failed','cancelled']},
phase=text(120),message=text(1000),
progress=obj({'completed':SAFE_NAT,'total':{'oneOf':[SAFE_NAT,{'type':'null'}]}}),
age_s={'type':'number','minimum':0},stale={'type':'boolean'},sha256=SHA))]}
_SNAPSHOT_FIELDS=dict(_SNAPSHOT_SUMMARY,mode=const('inspection'),execution=const('unsupported'),
manifest_status={'enum':['unavailable','unchanged','changed','missing']},
**{name:array(_SNAPSHOT_REFERENCE,64) for name in ('data','recipes','evidence','requirements')})
_SNAPSHOT_VIEW={'oneOf':[obj(dict(_SNAPSHOT_FIELDS,schema_version=const(1))),
obj(dict(_SNAPSHOT_FIELDS,schema_version=const(2),extensions=_SNAPSHOT_CATALOG))]}
_ACTIVITY_SNAPSHOT_VIEW={'oneOf':[
obj(dict(_SNAPSHOT_FIELDS,schema_version=const(1),activity=_ACTIVITY),
list(_SNAPSHOT_FIELDS)),
obj(dict(_SNAPSHOT_FIELDS,schema_version=const(2),extensions=_SNAPSHOT_CATALOG,activity=_ACTIVITY),
list(_SNAPSHOT_FIELDS)+['extensions'])]}
model_operation('project_snapshots.list','GET','/api/workspace/project-snapshots',
{'cursor':ID,'limit':integer(1,20)},[],query=('cursor','limit'),
output=obj({'mode':const('inspection'),'roots':array(text(160),10000),
'projects':array(obj(_SNAPSHOT_SUMMARY),20),'limit':integer(1,20),
'next_cursor':{'oneOf':[{'type':'null'},ID]}}),
description='List bounded immutable v1/v2 project snapshots and configured root aliases; no code or runtime execution.')
model_operation('project_snapshots.get','GET','/api/workspace/project-snapshots/{project_id}',
{'project_id':ID},output=_SNAPSHOT_VIEW,
description='Inspect exact saved v1/v2 declarations through current scoped, rooted, bounded readers; no source blobs or execution.')
model_operation('project_snapshots.open','POST','/api/workspace/project-snapshots',
{'root':text(160),'manifest_path':text(512)},scopes=('inspect','edit'),mutation=True,
output=_SNAPSHOT_VIEW,
description='Register and inspect an explicit configured-root v1/v2 manifest; inert metadata only, never approval or execution.')
# These E1 routes already have a supported unselected owner-browser consumer.
# Their domain dispatch keeps that owner gate; ordinary agents select contracts.
_LINEAGE_REF=obj({'catalog_id':ID,'trial_id':ID,'material_sha256':SHA})
_NULL={'type':'null'}
_LINEAGE_TARGET=obj({'metric_id':text(80),'metric_definition_sha256':{'oneOf':[SHA,_NULL]},
'direction':{'enum':['minimize','maximize','target']},
'threshold':{'oneOf':[{'type':'number','minimum':-(2**53-1),'maximum':2**53-1},_NULL]},
'acceptance':text(2000)})
_LINEAGE_INTENT=obj({'ancestry':{'enum':['unknown','root','derived']},
'parent':{'oneOf':[_LINEAGE_REF,_NULL]},'baseline':{'oneOf':[_LINEAGE_REF,_NULL]},
'cohort':text(120),'hypothesis':text(2000),'change_summary':text(2000),'target':_LINEAGE_TARGET})
_LINEAGE_RECORD=obj({'format':const('trial_lineage_v1'),'trial':_LINEAGE_REF,'intent':_LINEAGE_INTENT,
'actor_id':ID,'recorded_at':text(80),'timing':{'enum':['before_admission','retrospective']}})
_LINEAGE_RUN=obj({'id':ID,'state':{'enum':['queued','running','cancelling','completed','failed','cancelled','interrupted','unknown']},
'parent_run_id':{'oneOf':[ID,_NULL]},'created_at':text(80),'finished_at':{'oneOf':[text(80),_NULL]},
'validation':{'type':'object','maxProperties':4,'additionalProperties':{'type':'number'}}})
_LINEAGE_NODE=obj({'trial':_TRIAL,'lineage':{'oneOf':[_LINEAGE_RECORD,_NULL]},
'study':obj({'id':ID,'name':text(120)}),'recipe':obj({'id':ID,'revision':SAFE_POS}),
'model':MODEL_REF,'attempt_count':SAFE_NAT,'runs':array(_LINEAGE_RUN,5),'runs_truncated':{'type':'boolean'}})
model_operation('studies.lineage','GET','/api/workspace/experiment-lineage',
{'cursor':ID,'limit':integer(1,20),'revision':SHA,'cohort':text(120)},[],
query=('cursor','limit','revision','cohort'),
output=obj({'revision':SHA,'nodes':array(_LINEAGE_NODE,20),'related':array(_LINEAGE_REF,40),
'next_cursor':_PAGE_CURSOR,'limit':integer(1,20),'cohort':{'oneOf':[text(120),_NULL]}}),
description='Read a revision-pinned page of exact Trial ancestry and authored targets; Run summaries are saved metadata, not artifact verification.')
model_operation('studies.lineage_trial','GET','/api/workspace/experiment-lineage/{trial_id}',
{'trial_id':ID},output=_LINEAGE_NODE)
model_operation('studies.record_lineage','POST','/api/workspace/experiment-lineage',
{'request_key':KEY,'revision':SHA,'trial':_LINEAGE_REF,'intent':_LINEAGE_INTENT},
scopes=('inspect','edit'),mutation=True,output=_LINEAGE_RECORD,
description='Record immutable authored intent and exact ancestry once; historical admissions are explicitly retrospective. Never execute.')
model_operation('studies.branch_trial','POST','/api/workspace/experiment-lineage/branch',
{'request_key':KEY,'name':text(120),'intent':_LINEAGE_INTENT,'new_study_name':text(120)},
['request_key','name','intent'],scopes=('inspect','edit'),mutation=True,
output=obj({'request_key':KEY,'graph':_GRAPH,'model':MODEL_REF,'parent':_LINEAGE_REF,
'intent':_LINEAGE_INTENT,'study_id':ID,
'source':obj({'id':ID,'revision':SAFE_POS,'material':MATERIAL_REF})}),
description='Clone the exact retained Trial recipe; optional new Study remains owner-only with inherited finite policy/limits. No grant or Run.')
model_operation('studies.prepare_branch','POST','/api/workspace/studies/{study_id}/prepare-branch',
{'study_id':ID,'request_key':KEY,'revision':SAFE_POS,'branch_request_key':KEY,
'graph_revision':SAFE_POS,'replicate':SAFE_NAT,'model':MODEL_REF},
['study_id','request_key','revision','branch_request_key','graph_revision','replicate'],
scopes=('inspect','edit'),mutation=True,output=_TRIAL,
description='Prepare edited branch material and attach immutable exact lineage atomically; existing capture, authority and admission rules apply.')
PUBLICATION_SOURCE_REF = obj({'kind': const('external_publication_source'), 'schema_version': const(1),
'catalog_id': ID, 'run_id': ID, 'sha256': SHA})
PUBLICATION_RESULT_REF = obj({'kind': const('recovered_publication_result'), 'schema_version': const(1),
'catalog_id': ID, 'run_id': ID, **{key: SHA for key in (
'material_sha256', 'inventory_sha256', 'custody_receipt_sha256', 'sha256')}})
_PUBLICATION_FAULT = obj({'format': const('external_publication_fault_v1'), 'source_sha256': SHA,
'code': text(80), 'message': text(240), 'recorded_at': text(64)})
_PUBLICATION_STATE = obj({'run_id': ID, 'state': {'enum': ['recovering', 'paused', 'blocked', 'published']},
'original_run_state': {'enum': ['failed', 'interrupted']}, 'attempt_count': integer(1, 20),
'cancel_requested': {'type': 'boolean'}, 'result_ref': {'oneOf': [{'type': 'null'}, PUBLICATION_RESULT_REF]}})
_PUBLICATION_ARTIFACT = obj({'name': ARTIFACT, 'role': text(80), 'bytes': integer(0, 512*1024**2),
'sha256': SHA, 'media_type': const('application/octet-stream')})
_PUBLICATION_RESULT = obj({'format': const('recovered_publication_result_v1'), 'schema_version': const(1),
'catalog_id': ID, 'run_id': ID, **{key: SHA for key in ('request_sha256', 'material_sha256',
'continuation_request_sha256', 'inventory_sha256', 'custody_receipt_sha256')},
'source_ref': PUBLICATION_SOURCE_REF, 'artifacts': array(_PUBLICATION_ARTIFACT, 96),
'original_run_state': {'enum': ['failed', 'interrupted']}, 'original_fault': _PUBLICATION_FAULT,
'result_ref': PUBLICATION_RESULT_REF})
model_operation('runs.publication_status', 'GET', '/api/workspace/runs/{run_id}/publication', {'run_id': ID},
output=obj({'run_id': ID, 'original_run_state': text(64), 'verification': const('saved_metadata_only'),
'eligibility': {'enum': ['requires_verification', 'unavailable']},
'source_ref': {'oneOf': [{'type': 'null'}, PUBLICATION_SOURCE_REF]},
'original_fault': {'oneOf': [{'type': 'null'}, _PUBLICATION_FAULT]},
'continuation': {'oneOf': [{'type': 'null'}, _PUBLICATION_STATE]},
'limits': obj({'wall_seconds': const(60), 'max_attempts': const(20), 'copy_bytes': SAFE_NAT})}))
model_operation('runs.recover_publication', 'POST', '/api/workspace/runs/{run_id}/recover-publication',
{'run_id': ID, 'source_ref': PUBLICATION_SOURCE_REF, 'request_key': KEY}, output=_PUBLICATION_STATE,
scopes=('inspect', 'approve-execution'), mutation=True,
description='Explicit current owner action on exact retained original attempt; no compute replay or new grant/reservation. Inspect status after unknown acknowledgement.')
model_operation('runs.cancel_publication', 'POST', '/api/workspace/runs/{run_id}/cancel-publication',
{'run_id': ID, 'request_key': KEY}, output=_PUBLICATION_STATE,
scopes=('inspect', 'cancel'), mutation=True)
_OWNER_OPERATION_IDS.update(('runs.recover_publication', 'runs.cancel_publication'))
_MODEL_RECEIPT_IDS.add('runs.recover_publication')
_PHASE_MAX_MS = 7*24*60*60*1000
_PHASE_NAMES = ['catalog_lock_wait', 'prepare', 'capture', 'queue', 'launch_verification', 'custodian_preparation',
'go_wait', 'runtime_verification', 'leader_lifetime', 'drain', 'output_validation',
'publication', 'recovery_verification', 'recovery_publication']
_PHASE_OWNERS = {
'pipeline': {'prepare', 'capture'},
'runs': {'catalog_lock_wait', 'queue', 'launch_verification', 'output_validation',
'publication', 'recovery_verification', 'recovery_publication'},
'custodian': {'custodian_preparation', 'go_wait', 'runtime_verification', 'leader_lifetime', 'drain'},
}
_PHASE_SPAN = obj({'sequence': integer(1, 2**31-1), 'phase': {'enum': _PHASE_NAMES},
'state': {'enum': ['open', 'measured', 'incomplete']},
'started_offset_ms': integer(0, _PHASE_MAX_MS),
'ended_offset_ms': {'oneOf': [{'type': 'null'}, integer(0, _PHASE_MAX_MS)]},
'elapsed_ms': integer(0, _PHASE_MAX_MS), 'wait_reason': {'enum': [None,
'catalog_lock', 'capacity', 'preparing_material', 'capturing_inputs', 'scheduler', 'verifying_captures',
'owner_go', 'leader', 'descendants', 'validating_outputs', 'copying_outputs']}})
_PHASE_RECORD = obj({'format': const('owner_phase_timings_v1'),
'owner': {'enum': ['pipeline', 'runs', 'custodian']}, 'clock_id': ID,
'observed_at_ms': SAFE_NAT, 'dropped_spans': integer(0, 2**31-1), 'spans': array(_PHASE_SPAN, 32, 1)})
model_operation('runs.phase_timings', 'GET', '/api/workspace/runs/{run_id}/phase-timings', {'run_id': ID},
output=obj({'format': const('run_phase_timings_v1'), 'catalog_id': ID, 'run_id': ID,
'original_run_state': {'enum': ['queued', 'running', 'cancelling', 'completed', 'failed', 'cancelled', 'interrupted', 'unknown']},
'evidence': {'enum': ['owner_observed', 'partial', 'unknown_granularity', 'unavailable']},
'records': array(_PHASE_RECORD, 4)}),
description='Bounded owner-clock observations; overlapping spans are not additive, incomplete history is never reconstructed. No readiness or result authority.')
model_operation('graphs.preparation_timings', 'POST', '/api/workspace/graphs/{graph_id}/preparation-timings',
{'graph_id': ID, 'revision': integer(1, 2**31-1)},
output=obj({'format': const('graph_preparation_timings_v1'), 'catalog_id': ID, 'graph_id': ID,
'graph_revision': integer(1, 2**31-1), 'actor_id': ID,
'selection': const('latest_actor_graph_revision_observation'),
'observation': {'oneOf': [{'type': 'null'}, obj({
'operation': {'enum': ['graphs.preflight_external', 'graphs.capture_external']},
'clock_id': ID, 'material_sha256': {'oneOf': [{'type': 'null'}, SHA]}})]},
'evidence': {'enum': ['owner_observed', 'unknown_granularity']}, 'records': array(_PHASE_RECORD, 1)}),
description='Latest volatile exact actor/graph/revision preparation observation, including before a Run exists; never starts preparation.')
_COORDINATOR_HEALTH = obj({'format': const('run_coordinator_health_v1'), 'catalog_id': ID,
'generation': integer(1, 2**31-1),
'state': {'enum': ['healthy', 'idle', 'blocked', 'recovering', 'stopped', 'faulted']},
'updated_at': text(64), 'admission_ready': {'type': 'boolean'},
'recovery_request': {'oneOf': [{'type': 'null'}, obj({'actor_id': ID, 'request_key': KEY,
'request_sha256': SHA, 'expected_generation': integer(1, 2**31-1),
'completed_generation': {'oneOf': [{'type': 'null'}, integer(1, 2**31-1)]}})]},
'fault': {'oneOf': [{'type': 'null'}, obj({'category': text(80), 'at': text(64)})]}})
model_operation('runs.coordinator_health', 'GET', '/api/workspace/coordinator', {}, output=_COORDINATOR_HEALTH,
description='Current Runs-owned coordinator readiness and bounded fault; ordinary idle event waiting is healthy.')
model_operation('runs.recover_coordinator', 'POST', '/api/workspace/coordinator/recover',
{'expected_generation': integer(1, 2**31-1), 'request_key': KEY}, output=_COORDINATOR_HEALTH,
scopes=('inspect', 'approve-execution'), mutation=True,
description='Explicit owner recovery of one stopped coordinator generation; reconcile original custody without compute replay.')
_OWNER_OPERATION_IDS.add('runs.recover_coordinator')
_MODEL_RECEIPT_IDS.add('runs.recover_coordinator')
model_operation('runs.publication_result', 'POST', '/api/workspace/publication-results',
{'ref': PUBLICATION_RESULT_REF}, output=_PUBLICATION_RESULT)
_PUBLICATION_SEGMENT = copy.deepcopy(SEGMENT_SCHEMA)
_PUBLICATION_SEGMENT['properties']['result_ref'] = PUBLICATION_RESULT_REF
_PUBLICATION_SEGMENT['required'].append('result_ref')
model_operation('runs.publication_artifact_chunk', 'POST', '/api/workspace/publication-results/artifact-segment/{name}',
{'ref': PUBLICATION_RESULT_REF, 'name': ARTIFACT, 'expected_sha256': SHA, 'offset': integer(),
'max_bytes': integer(1, 8*1024*1024)}, output=_PUBLICATION_SEGMENT)
_ARTIFACT_SEGMENT_SOURCE = {'oneOf': [obj({'kind':const('run'),'run_id':ID}),
obj({'kind':const('publication'),'ref':PUBLICATION_RESULT_REF})]}
_ARTIFACT_SEGMENT_KEY = {'type':'string','pattern':'^[A-Za-z0-9_.:-]{1,64}$'}
_ARTIFACT_SEGMENT_REQUEST = obj({'key':_ARTIFACT_SEGMENT_KEY,'source':_ARTIFACT_SEGMENT_SOURCE,
'name':ARTIFACT,'expected_sha256':SHA,'offset':integer(0,512*1024**2),
'max_bytes':integer(1,8*1024**2)})
_ARTIFACT_SEGMENT_OUTCOME = {'oneOf': [
obj({'key':_ARTIFACT_SEGMENT_KEY,'source':_ARTIFACT_SEGMENT_SOURCE,'status':const(200),
'result':{'oneOf':[SEGMENT_SCHEMA,_PUBLICATION_SEGMENT]}}),
obj({'key':_ARTIFACT_SEGMENT_KEY,'source':_ARTIFACT_SEGMENT_SOURCE,'status':integer(400,599),
'error':obj({'code':text(120),'message':text(240)})})]}
_ARTIFACT_SEGMENTS_RESULT = obj({'format':const('artifact_segments_v1'),
'items':array(_ARTIFACT_SEGMENT_OUTCOME,20,1)})
model_operation('runs.artifact_segments','POST','/api/workspace/artifact-segments',
{'items':array(_ARTIFACT_SEGMENT_REQUEST,20,1)},output=_ARTIFACT_SEGMENTS_RESULT,
description='Explicit sequential external-Run or attached-publication segment collection; max20 items/8MiB requested raw bytes/60s. Typed item outcomes; current authority and client whole hashes remain required.')
model_operation('runs.publication_model_evidence', 'POST', '/api/workspace/publication-results/model-evidence',
{'ref': PUBLICATION_RESULT_REF, 'selectors': JSON_OBJECT}, ['ref'])
model_operation('runs.compare_publication_evidence', 'POST', '/api/workspace/publication-results/compare-model-evidence',
{'ref': PUBLICATION_RESULT_REF, 'other_ref': PUBLICATION_RESULT_REF, 'selection': JSON_OBJECT})
_SCIENTIFIC_OPERAND = {'oneOf': [obj({'kind':const('completed_run'), 'catalog_id':ID, 'run_id':ID}),
obj({'kind':const('publication_result'), 'ref':PUBLICATION_RESULT_REF})]}
model_operation('runs.compare_scientific_evidence', 'POST', '/api/workspace/scientific-comparison',
{'operands':array(_SCIENTIFIC_OPERAND,2,2), 'selection':JSON_OBJECT,
'point':obj({'field_id':REF, **{axis:integer(0,127) for axis in 'xyz'}})},
output=JSON_OBJECT, description='Read exact retained validation field-point diagnostics and scalar compatibility; no scientific criterion or compute is invented.')
# External file projects have independent lifecycle and text-only contracts.
# Keep these additive operations outside the installed legacy registry projection.
_PROJECT_FILES_ACTIONS = ['new', 'open', 'save', 'close', 'query', 'get', 'import_text', 'annotate']
_PROJECT_FILES_GROUPS = dict(GROUPS, uniqueItems=True)
_PROJECT_FILES_PARENTS = dict(array(text(120), 30), uniqueItems=True)
_PROJECT_FILES_PROVENANCE = obj({'method': const('import'), 'rights': text(1000),
'normalization': const('NFC; LF newlines')})
_PROJECT_FILES_RECORD_FIELDS = {
'id': ID, 'kind': const('text'), 'name': text(200), 'text': text(200000),
'groups': _PROJECT_FILES_GROUPS, 'parents': _PROJECT_FILES_PARENTS,
'provenance': _PROJECT_FILES_PROVENANCE, 'review': {'enum': ['draft', 'human_reviewed']},
'revision': SAFE_POS, 'source_revision': const(1),
'created_at': text(80), 'updated_at': text(80)}
_PROJECT_FILES_TASKS = ('text_classification', 'text_entities', 'text_corpus')
PROJECT_FILES_RECORD = {'oneOf': [obj(dict(_PROJECT_FILES_RECORD_FIELDS,
task=const(task), annotation={'oneOf': [{'type': 'null'}, ANNOTATIONS[task]]}))
for task in _PROJECT_FILES_TASKS]}
PROJECT_FILES_SUMMARY = obj({key: _PROJECT_FILES_RECORD_FIELDS[key] for key in
('id', 'kind', 'name', 'review', 'revision', 'source_revision', 'created_at', 'updated_at')} |
{'task': {'enum': list(_PROJECT_FILES_TASKS)}})
_PROJECT_FILES_PROJECT = obj({'project_id': ID, 'name': text(200), 'checkpoint': SHA})
_PROJECT_FILES_RECOVERY = obj({'action': const('open'), 'root': text(160), 'directory': text(512),
'reason': {'enum': ['unknown_publication', 'projection_unavailable']},
'request_key': {'oneOf': [KEY, {'type': 'null'}]}})
PROJECT_FILES_RECEIPT = {'oneOf': [
obj({'committed': const(True), 'selected': const(True), 'project_id': ID,
'checkpoint': SHA, 'request_key': KEY}),
obj({'committed': const(True), 'selected': const(False), 'project_id': ID,
'checkpoint': SHA, 'request_key': KEY, 'root': text(160), 'directory': text(512)})]}
_PROJECT_FILES_STATE_FIELDS = {'format': const('project_files_state_v1'), 'binding': ID,
'roots': dict(array(text(160), 100), uniqueItems=True),
'available_actions': dict(array({'enum': _PROJECT_FILES_ACTIONS}, 8), uniqueItems=True)}
PROJECT_FILES_STATE = {'oneOf': [
obj(dict(_PROJECT_FILES_STATE_FIELDS, state=const('no_project_open'), project={'type': 'null'})),
obj(dict(_PROJECT_FILES_STATE_FIELDS, state=const('open'),
project=_PROJECT_FILES_PROJECT)),
obj(dict(_PROJECT_FILES_STATE_FIELDS, state=const('recovery_required'),
project=_PROJECT_FILES_PROJECT, recovery=_PROJECT_FILES_RECOVERY,
available_actions=const(['open'])))]}
_PROJECT_FILES_BOUND_RESULT = {'binding': ID, 'project_id': ID, 'checkpoint': SHA}
PROJECT_FILES_RECORD_RESULT = obj(dict(_PROJECT_FILES_BOUND_RESULT, record=PROJECT_FILES_RECORD,
history=array(PROJECT_FILES_RECORD, 4),
next_history_before_revision={'oneOf': [SAFE_POS, {'type': 'null'}]}))
_PROJECT_FILES_MUTATION = {'binding': ID, 'expected_checkpoint': SHA, 'request_key': KEY}
model_operation('project_files.status', 'GET', '/api/workspace/project-files', output=PROJECT_FILES_STATE)
for _action in ('new', 'open'):
_fields = dict(_PROJECT_FILES_MUTATION, expected_checkpoint={'oneOf': [SHA, {'type': 'null'}]},
root=text(160), directory=text(512))
if _action == 'new':
_fields['name'] = text(200)
model_operation('project_files.' + _action, 'POST', '/api/workspace/project-files/' + _action,
_fields, output=PROJECT_FILES_STATE, scopes=('inspect', 'edit'), mutation=True,
description='Explicit file project ' + _action + '; requires the current process binding and checkpoint. Never executes project code.')
for _action in ('save', 'close'):
model_operation('project_files.' + _action, 'POST', '/api/workspace/project-files/' + _action,
_PROJECT_FILES_MUTATION, output=PROJECT_FILES_STATE, scopes=('inspect', 'edit'), mutation=True)
model_operation('project_files.query', 'GET', '/api/workspace/project-files/records',
{'binding': ID, 'checkpoint': SHA, 'after_id': ID, 'limit': integer(1, 100)},
required=['binding', 'checkpoint'], query=('binding', 'checkpoint', 'after_id', 'limit'),
output=obj(dict(_PROJECT_FILES_BOUND_RESULT, items=array(PROJECT_FILES_SUMMARY, 100),
next_after_id={'oneOf': [ID, {'type': 'null'}]})))
model_operation('project_files.get', 'GET', '/api/workspace/project-files/records/{record_id}',
{'record_id': ID, 'binding': ID, 'checkpoint': SHA, 'before_revision': SAFE_POS,
'history_limit': integer(1, 4)}, required=['record_id', 'binding', 'checkpoint'],
query=('binding', 'checkpoint', 'before_revision', 'history_limit'), output=PROJECT_FILES_RECORD_RESULT)
model_operation('project_files.import_text', 'POST', '/api/workspace/project-files/import-text',
dict(_PROJECT_FILES_MUTATION, asset=obj({'text': text(200000), 'name': text(200),
'groups': _PROJECT_FILES_GROUPS, 'parents': _PROJECT_FILES_PARENTS, 'rights': text(1000)},
required=['text', 'groups'])), output=PROJECT_FILES_RECORD_RESULT,
scopes=('inspect', 'edit'), mutation=True)
model_operation('project_files.annotate', 'POST', '/api/workspace/project-files/records/{record_id}',
dict(_PROJECT_FILES_MUTATION, record_id=ID, annotation={'oneOf': [obj({
'revision': SAFE_POS, 'source_revision': const(1), 'task': const(task),
'annotation': ANNOTATIONS[task], 'groups': _PROJECT_FILES_GROUPS,
'review': {'enum': ['draft', 'human_reviewed']}}) for task in _PROJECT_FILES_TASKS]}),
output=PROJECT_FILES_RECORD_RESULT, scopes=('inspect', 'edit'), mutation=True,
description='Save ordinary human text annotation or review at the exact checkpoint. Human review additionally requires the existing owner approve-review authority.')
_PROJECT_FILES_RECEIPT_IDS = frozenset('project_files.' + action
for action in ('new', 'open', 'save', 'close', 'import_text', 'annotate'))
_MODEL_RECEIPT_IDS.update(_PROJECT_FILES_RECEIPT_IDS)
_OWNER_OPERATION_IDS.update('project_files.' + action for action in ('new', 'open', 'save', 'close'))
for _op in _OPERATIONS:
if _op['operation_id'].startswith('project_files.'):
_op['outputSchema']['oneOf'][1]['properties']['result']['properties']['receipt'] = PROJECT_FILES_RECEIPT
# M2 operations are fixed domain projections. Domain owners validate versioned
# documents; the public boundary owns selection, bounds and outcome correlation.
PROJECT_FILES_M2 = set()
PROJECT_FILES_M3 = set()
PROJECT_FILES_M4 = set()
_PROJECT_FILES_PAGE_INPUT = {'offset': integer(0, 1000000), 'limit': integer(1, 40)}
_PROJECT_FILES_PAGE = obj({'items': array(JSON_OBJECT, 40), 'offset': integer(0, 1000000),
'total': integer(0, 1000000), 'limit': integer(1, 40)})
_PROJECT_FILES_READ = {'binding': ID, 'checkpoint': SHA}
_PROJECT_FILES_ORIGIN = {'origin_catalog_id': ID}
def _project_file_operation(action, method, suffix, fields=None, *, required=None,
output=JSON_OBJECT, mutation=False, owner=False, scopes=None,
domain=None, page=False, milestone=2, receipt=True):
fields = copy.deepcopy(fields or {})
needed = list(fields) if required is None else list(required)
if domain is not None:
original = next(op for op in _OPERATIONS if op['operation_id'] == domain)
fields.update(copy.deepcopy(original['inputSchema'].get('properties', {})))
needed += original['inputSchema'].get('required', [])
bound = (_PROJECT_FILES_MUTATION if receipt else {"binding": ID, "expected_checkpoint": SHA}) if mutation else _PROJECT_FILES_READ
fields.update(bound)
needed = list(dict.fromkeys(needed + list(bound)))
if action == 'data_query':
fields['limit'] = integer(1, 40)
if page:
fields.update(copy.deepcopy(_PROJECT_FILES_PAGE_INPUT))
output = copy.deepcopy(_PROJECT_FILES_PAGE)
if action in ('data_history', 'data_response_history', 'data_preference_history'):
fields['limit'] = integer(1, 4)
output['properties']['items']['maxItems'] = 4
output['properties']['limit'] = integer(1, 4)
name = 'project_files.' + action
model_operation(name, method, '/api/workspace/project-files' + suffix,
fields, needed, output=obj(dict(_PROJECT_FILES_BOUND_RESULT, value=output)),
query=tuple(key for key in fields if '{' + key + '}' not in suffix) if method == 'GET' else (),
scopes=scopes or (('inspect', 'edit') if mutation else ('inspect',)), mutation=mutation,
description=action.replace('_', ' ') + '; exact selected project checkpoint, existing domain authorization and validation.' + (' Historical content never grants current execution permission.' if milestone == 3 else ' No execution.'))
if domain is not None:
_OPERATIONS[-1]['binary_fields'] = copy.deepcopy(original['binary_fields'])
{2:PROJECT_FILES_M2,3:PROJECT_FILES_M3,4:PROJECT_FILES_M4}[milestone].add(name)
if mutation and receipt:
_MODEL_RECEIPT_IDS.add(name)
if owner:
_OWNER_OPERATION_IDS.add(name)
_OPERATIONS[-1]['outputSchema']['oneOf'][1]['properties']['result']['properties']['receipt'] = PROJECT_FILES_RECEIPT
_project_file_operation('definitions', 'GET', '/definitions')
# Actual data and its authored histories. Inline source imports retain the
# existing decoded-byte bound; compound sources use their existing parsers.
_project_file_operation('data_query', 'GET', '/data', domain='data.query')
_project_file_operation('data_get', 'GET', '/data/{record_id}', {'record_id': ID})
_project_file_operation('data_availability', 'GET', '/data/{record_id}/availability', {'record_id': ID})
for _action, _suffix in [('data_history', 'history'), ('data_responses', 'responses'),
('data_response_history', 'response-history'), ('data_preferences', 'preferences'),
('data_preference_history', 'preference-history')]:
_project_file_operation(_action, 'GET', '/data/{record_id}/' + _suffix, {'record_id': ID}, page=True)
for _kind in ('text', 'image', 'audio', 'mesh', 'pointcloud', 'volume', 'sequence'):
_project_file_operation('data_import_' + _kind, 'POST', '/data/import-' + _kind,
domain='data.import_' + _kind, mutation=True)
_project_file_operation('source_register', 'POST', '/sources/register',
{'root': text(160), 'manifest_path': text(512)}, mutation=True, owner=True)
_project_file_operation('data_import_scientific', 'POST', '/data/import-scientific', {
'snapshot': obj({'origin_catalog_id': ID, 'project_id': ID, 'manifest_sha256': SHA}),
'reference_id': REF, 'expected_sha256': SHA,
'document': obj(OPTIONAL_META, required=['groups'])}, mutation=True)
_project_file_operation('data_annotate', 'POST', '/data/{record_id}', {
'record_id': ID, 'revision': SAFE_POS, 'source_revision': SAFE_POS,
'task': {'enum': list(ANNOTATIONS)}, 'annotation': JSON_OBJECT,
'groups': _PROJECT_FILES_GROUPS, 'review': {'enum': ['draft', 'human_reviewed']}}, mutation=True)
_project_file_operation('data_rights', 'POST', '/data/{record_id}/rights', {
'record_id': ID, 'revision': SAFE_POS, 'source_revision': SAFE_POS,
'note': text(1000, True)}, mutation=True)
for _action, _suffix in [('data_source_save', '/source'), ('data_source_delete', '/source/delete')]:
_project_file_operation(_action, 'POST', '/data/{record_id}' + _suffix,
{'record_id': ID, 'document': JSON_OBJECT}, mutation=True,
scopes=('inspect', 'edit', 'approve-review') if _action == 'data_source_save' else ('inspect', 'edit'))
_project_file_operation('data_response_save', 'POST', '/responses', {
'document': obj({'id': ID, 'prompt_id': ID, 'revision': SAFE_NAT,
'parent_revision': SAFE_POS, 'source_revision': SAFE_POS, 'completion': text(200000),
'review': {'enum': ['draft', 'human_reviewed']}})}, mutation=True)
for _action, _suffix in [('data_preference_save', ''), ('data_preference_delete', '/delete')]:
_project_file_operation(_action, 'POST', '/preferences' + _suffix,
{'document': JSON_OBJECT}, mutation=True)
for _singular, _plural, _key in [('selection', 'selections', 'selection_id'), ('search', 'searches', 'search_id')]:
_project_file_operation(_plural, 'GET', '/' + _plural, page=True)
if _singular == 'selection':
_project_file_operation('selection_get', 'GET', '/selections/{selection_id}', {'selection_id': ID})
_project_file_operation(_singular + '_create', 'POST', '/' + _plural,
{'document': JSON_OBJECT}, mutation=True)
for _verb in ('rename', 'delete'):
_project_file_operation(_singular + '_' + _verb, 'POST', '/' + _plural + '/{' + _key + '}' + ('/delete' if _verb == 'delete' else ''),
{_key: ID, 'revision': SAFE_POS, **({'name': text(120)} if _verb == 'rename' else {})}, mutation=True)
for _action in ('preview', 'freeze'):
_project_file_operation('release_' + _action, 'POST', '/releases/' + _action,
domain='releases.' + _action, mutation=_action == 'freeze',
scopes=('inspect', 'freeze') if _action == 'freeze' else ('inspect',))
# Current metadata uses the same Model/Pipeline validators, with canonical
# publication wrapped by the project session. Runtime capture remains absent.
for _plural, _key, _domain in [('models', 'model_id', 'models'), ('graphs', 'graph_id', 'graphs')]:
_project_file_operation(_plural, 'GET', '/' + _plural, page=True)
for _verb in ('get', 'create', 'save'):
_project_file_operation(('model_' if _plural == 'models' else 'graph_') + _verb,
'GET' if _verb == 'get' else 'POST', '/' + _plural + ('/{' + _key + '}' if _verb != 'create' else ''),
domain=_domain + '.' + _verb, mutation=_verb != 'get')
_project_file_operation('graph_create_external', 'POST', '/graphs/external',
domain='graphs.create_external', mutation=True)
_project_file_operation('graph_clone', 'POST', '/graphs/{graph_id}/clone', domain='graphs.clone', mutation=True)
_project_file_operation('model_publish', 'POST', '/models/{model_id}/publish', domain='models.publish', mutation=True)
_project_file_operation('recipes', 'GET', '/recipes', page=True)
for _verb in ('get', 'create', 'save'):
_project_file_operation('recipe_' + _verb, 'GET' if _verb == 'get' else 'POST',
'/recipes' + ('/{recipe_id}' if _verb != 'create' else ''), domain='recipes.' + _verb,
mutation=_verb != 'get')
_project_file_operation('recipe_prepare', 'POST', '/recipes/{graph_id}/prepare', {
'graph_id': ID, 'revision': SAFE_POS, 'model': MODEL_REF,
'builtin': {'type': 'boolean'}, 'reconcile_capture': {'type': 'boolean'}},
required=['graph_id', 'revision', 'model'], mutation=True)
for _kind, _ref in [('model', MODEL_REF), ('recipe', MATERIAL_REF), ('runtime', material_ref('runtime'))]:
_project_file_operation(_kind + '_material', 'POST', '/materials/' + _kind,
{'ref': _ref, 'verify': {'type': 'boolean'}}, required=['ref'])
_project_file_operation('snapshot', 'POST', '/materials/snapshot', {
'project_id': ID, 'manifest_sha256': SHA, 'origin_catalog_id': ID, 'verify': {'type': 'boolean'}},
required=['project_id', 'manifest_sha256', 'origin_catalog_id'])
# Imported origin identity is an explicit selector, never a current grant.
for _action, _suffix, _key in [('study', 'studies', 'study_id'), ('trial', 'trials', 'trial_id'),
('run', 'runs', 'run_id'), ('candidate', 'candidates', 'candidate_id')]:
_project_file_operation(_action, 'GET', '/' + _suffix + '/{' + _key + '}',
{_key: ID, **_PROJECT_FILES_ORIGIN, **({'verify': {'type': 'boolean'}} if _action == 'candidate' else {})},
required=[_key, 'origin_catalog_id'])
# Study reservations are independently bounded while charge totals remain complete.
_study_operation = next(op for op in _OPERATIONS if op['operation_id'] == 'project_files.study')
_study_operation['inputSchema']['properties'].update(_PROJECT_FILES_PAGE_INPUT | {'revision': SAFE_POS})
_study_operation['query'].extend(['offset', 'limit', 'revision'])
_run_operation = next(op for op in _OPERATIONS if op['operation_id'] == 'project_files.run')
_run_operation['inputSchema']['properties'].update(_PROJECT_FILES_PAGE_INPUT)
_run_operation['query'].extend(['offset', 'limit'])
_PROJECT_RUN_DOCUMENT_SEGMENT = obj({'format': const('project_run_document_segment_v1'),
'origin_catalog_id': ID, 'run_id': ID, 'sha256': SHA, 'bytes': SAFE_NAT,
'offset': SAFE_NAT, 'limit': integer(1, 262144),
'base64': {'type': 'string', 'maxLength': 349528, 'pattern': '^[A-Za-z0-9+/]*={0,2}$'},
'next_offset': {'oneOf': [SAFE_NAT, {'type': 'null'}]}})
_project_file_operation('run_document_segment', 'GET', '/runs/{run_id}/document-segment',
{'run_id': ID, 'origin_catalog_id': ID, 'expected_sha256': SHA,
'offset': SAFE_NAT, 'limit': integer(1, 262144)},
required=['run_id', 'origin_catalog_id', 'expected_sha256', 'offset', 'limit'],
output=_PROJECT_RUN_DOCUMENT_SEGMENT)
_project_file_operation('source_references', 'GET', '/sources/{project_id}/references',
{'origin_catalog_id': ID, 'project_id': ID, 'manifest_sha256': SHA}, page=True)
_project_file_operation('publication_result', 'GET', '/runs/{run_id}/publication-result',
{'run_id': ID, **_PROJECT_FILES_ORIGIN})
_project_file_operation('package_state', 'GET', '/candidates/{candidate_id}/package-state',
{'candidate_id': ID, **_PROJECT_FILES_ORIGIN})
_project_file_operation('dependencies', 'GET', '/runs/{run_id}/dependencies',
{'run_id': ID, **_PROJECT_FILES_ORIGIN, **_PROJECT_FILES_PAGE_INPUT},
required=['run_id', 'origin_catalog_id'])
for _action in ('studies', 'runs', 'lineage', 'policies', 'artifacts', 'materials'):
_project_file_operation(_action, 'GET', '/' + _action, _PROJECT_FILES_ORIGIN,
required=[] if _action in ('studies', 'runs', 'artifacts', 'materials') else ['origin_catalog_id'], page=True)
# Intrinsic artifact identities span all origins in the selected project.
_artifacts_operation = next(op for op in _OPERATIONS if op['operation_id'] == 'project_files.artifacts')
_artifacts_operation['inputSchema']['properties'].pop('origin_catalog_id')
_artifacts_operation['query'].remove('origin_catalog_id')
_project_file_operation('policy', 'POST', '/policies/get', {'ref': POLICY_REF})
for _verb in ('create', 'save'):
_project_file_operation('study_' + _verb, 'POST', '/studies' + ('/{study_id}' if _verb == 'save' else ''),
domain='studies.' + _verb, mutation=True, owner=True)
_project_file_operation('trial_prepare', 'POST', '/studies/{study_id}/trials', {
'study_id': ID, 'revision': SAFE_POS, 'material': MATERIAL_REF, 'replicate': SAFE_NAT}, mutation=True)
_project_file_operation('lineage_record', 'POST', '/lineage', {'trial': _LINEAGE_REF, 'intent': _LINEAGE_INTENT}, mutation=True)
_project_file_operation('candidate_select', 'POST', '/studies/{study_id}/candidates',
domain='studies.select_candidate', mutation=True)
_project_file_operation('evidence', 'POST', '/runs/{run_id}/evidence', {
'run_id': ID, **_PROJECT_FILES_ORIGIN, 'selectors': JSON_OBJECT},
required=['run_id', 'origin_catalog_id'], output=_EVIDENCE_RESULT)
for _action, _suffix in [('retained_analysis', ''), ('retained_analysis_export', '/export')]:
_project_file_operation(_action, 'POST', '/runs/{run_id}/analysis' + _suffix,
{**_retained_request['properties'], **_PROJECT_FILES_ORIGIN},
required=[*_retained_request['required'], 'origin_catalog_id'], output=_retained_result)