taskcarry 0.3.2__py3-none-any.whl

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.
Files changed (105) hide show
  1. taskcarry/__init__.py +3 -0
  2. taskcarry/__main__.py +4 -0
  3. taskcarry/adapter_contracts.py +166 -0
  4. taskcarry/agy_turns.py +282 -0
  5. taskcarry/api.py +111 -0
  6. taskcarry/board.py +313 -0
  7. taskcarry/board_assets/board.css +1087 -0
  8. taskcarry/board_assets/board.js +1187 -0
  9. taskcarry/board_assets/browse.js +214 -0
  10. taskcarry/board_assets/index.html +43 -0
  11. taskcarry/board_assets/taskcarry-icon.ico +0 -0
  12. taskcarry/board_assets/taskcarry-mark.svg +28 -0
  13. taskcarry/board_data.py +466 -0
  14. taskcarry/chat_joins.py +157 -0
  15. taskcarry/cli.py +119 -0
  16. taskcarry/codex_capture.py +184 -0
  17. taskcarry/codex_host.py +293 -0
  18. taskcarry/collaboration_exchange.py +316 -0
  19. taskcarry/connection.py +159 -0
  20. taskcarry/continuity.py +300 -0
  21. taskcarry/contracts.py +165 -0
  22. taskcarry/conversation_capture.py +669 -0
  23. taskcarry/core.py +896 -0
  24. taskcarry/cycle_contracts.py +73 -0
  25. taskcarry/discovery.py +434 -0
  26. taskcarry/discovery_contracts.py +52 -0
  27. taskcarry/exchange_contracts.py +67 -0
  28. taskcarry/exchange_endpoint.py +377 -0
  29. taskcarry/exchange_packets.py +142 -0
  30. taskcarry/experience_contracts.py +129 -0
  31. taskcarry/experience_exchange.py +214 -0
  32. taskcarry/experience_notes.py +433 -0
  33. taskcarry/experience_storage.py +125 -0
  34. taskcarry/experience_tools.py +26 -0
  35. taskcarry/feishu/__init__.py +1 -0
  36. taskcarry/feishu/display.py +122 -0
  37. taskcarry/feishu/project_watch.py +145 -0
  38. taskcarry/feishu/review_sets.py +80 -0
  39. taskcarry/feishu/sender.py +42 -0
  40. taskcarry/feishu/subscription.py +193 -0
  41. taskcarry/feishu/windows_agent.py +287 -0
  42. taskcarry/feishu/windows_secret.py +34 -0
  43. taskcarry/gitops.py +170 -0
  44. taskcarry/governance.py +88 -0
  45. taskcarry/governance_cycle.py +775 -0
  46. taskcarry/identification.py +82 -0
  47. taskcarry/integration.py +663 -0
  48. taskcarry/maintenance.py +118 -0
  49. taskcarry/mcp.py +183 -0
  50. taskcarry/member_join.py +184 -0
  51. taskcarry/member_routing.py +145 -0
  52. taskcarry/onboarding.py +272 -0
  53. taskcarry/onboarding_complete.py +252 -0
  54. taskcarry/path_batches.py +19 -0
  55. taskcarry/preservation.py +257 -0
  56. taskcarry/project_collaboration.py +453 -0
  57. taskcarry/project_history.py +166 -0
  58. taskcarry/project_identity.py +51 -0
  59. taskcarry/project_recovery.py +824 -0
  60. taskcarry/recovery_contracts.py +25 -0
  61. taskcarry/recovery_files.py +153 -0
  62. taskcarry/recovery_git.py +234 -0
  63. taskcarry/remote_capture.py +89 -0
  64. taskcarry/remote_transfer.py +356 -0
  65. taskcarry/role_connection.py +215 -0
  66. taskcarry/setup.py +597 -0
  67. taskcarry/shared_workbench.py +480 -0
  68. taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
  69. taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
  70. taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
  71. taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
  72. taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
  73. taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
  74. taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
  75. taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
  76. taskcarry/source_review_set.py +80 -0
  77. taskcarry/state_format.py +47 -0
  78. taskcarry/store.py +472 -0
  79. taskcarry/task_context.py +141 -0
  80. taskcarry/text_handback.py +98 -0
  81. taskcarry/transfer_contracts.py +18 -0
  82. taskcarry/updates.py +351 -0
  83. taskcarry/workbench.py +625 -0
  84. taskcarry/workbench_contracts.py +32 -0
  85. taskcarry/workbuddy_capture.py +451 -0
  86. taskcarry/workbuddy_setup.py +212 -0
  87. taskcarry/worker_channel.py +859 -0
  88. taskcarry/worker_contracts.py +190 -0
  89. taskcarry/worker_storage.py +60 -0
  90. taskcarry/worker_tools.py +111 -0
  91. taskcarry-0.3.2.dist-info/METADATA +203 -0
  92. taskcarry-0.3.2.dist-info/RECORD +105 -0
  93. taskcarry-0.3.2.dist-info/WHEEL +5 -0
  94. taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
  95. taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
  96. taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
  97. taskcarry-0.3.2.dist-info/top_level.txt +2 -0
  98. taskcarry_https/__init__.py +1 -0
  99. taskcarry_https/consent.py +207 -0
  100. taskcarry_https/reader.py +132 -0
  101. taskcarry_https/review.py +116 -0
  102. taskcarry_https/server.py +163 -0
  103. taskcarry_https/team.py +335 -0
  104. taskcarry_https/team_host.py +109 -0
  105. taskcarry_https/web_host.py +82 -0
@@ -0,0 +1,377 @@
1
+ """Local last-known view and outbox, without a second project database."""
2
+ from __future__ import annotations
3
+
4
+ import re
5
+ from pathlib import Path
6
+
7
+ from .core import _id, read_file_bytes, validate_relative_path
8
+ from .exchange_packets import build, inspect, sha, require, git_source, read_git, parse, MAX_PACKET, MAX_OBJECT
9
+ from .recovery_files import normal, safe, atomic, lock
10
+ from .remote_transfer import _git, _out
11
+ from .worker_channel import WorkerChannel, packed, fingerprint, MEDIA
12
+ from .worker_contracts import validate_record, _relative_path
13
+ from .store import GovernanceError
14
+
15
+
16
+ def git_layer(root, path, layer):
17
+ if layer == 'index':
18
+ rows = _git(root, 'ls-files', '--stage', '-z', '--', path).stdout.split(b'\0')
19
+ rows = [x for x in rows if x]
20
+ require(len(rows) <= 1, 'Resolve conflicted index stages before selected capture.')
21
+ if not rows:
22
+ return None
23
+ meta, actual = rows[0].split(b'\t', 1)
24
+ mode, oid, stage = meta.decode().split()
25
+ require(stage == '0' and actual.decode('utf-8') == path, 'Unexpected index path/stage.')
26
+ else:
27
+ row = _git(root, 'ls-tree', '-z', 'HEAD', '--', path).stdout.rstrip(b'\0')
28
+ if not row:
29
+ return None
30
+ meta, actual = row.split(b'\t', 1)
31
+ mode, kind, oid = meta.decode().split()
32
+ require(kind == 'blob' and actual.decode('utf-8') == path, 'Unexpected HEAD path/type.')
33
+ require(mode in {'100644', '100755'}, 'Linked Git files are not captured.')
34
+ require(int(_out(root, 'cat-file', '-s', oid)) <= MAX_OBJECT, 'Selected Git layer too large.')
35
+ return _git(root, 'cat-file', 'blob', oid).stdout, mode
36
+
37
+
38
+ def validate_preservation(value, objects):
39
+ require(isinstance(value, dict) and set(value) == {'task_id', 'workspace_id', 'head_commit', 'files'},
40
+ 'Invalid selected preservation.')
41
+ _id(value['task_id'], 'Task'); _id(value['workspace_id'], 'Workspace')
42
+ require(value['head_commit'] is None or isinstance(value['head_commit'], str)
43
+ and re.fullmatch('[0-9a-f]{40}|[0-9a-f]{64}', value['head_commit']), 'Invalid captured HEAD.')
44
+ require(isinstance(value['files'], list) and 1 <= len(value['files']) <= 100, 'Select bounded exact files.')
45
+ seen = set()
46
+ for entry in value['files']:
47
+ require(set(entry) == {'path', 'head', 'index', 'worktree'}, 'Invalid captured layer entry.')
48
+ _relative_path(entry['path'])
49
+ require(entry['path'].casefold() not in seen, 'Duplicate or case-colliding selected paths.')
50
+ seen.add(entry['path'].casefold())
51
+ for layer in ('head', 'index', 'worktree'):
52
+ item = entry[layer]
53
+ if item is None:
54
+ continue
55
+ require(isinstance(item, dict) and set(item) == {'sha256', 'size', 'mode'}
56
+ and item['sha256'] in objects and type(item['size']) is int
57
+ and len(objects[item['sha256']]) == item['size'] and item['mode'] in {'100644', '100755'},
58
+ 'Missing or invalid selected layer bytes.')
59
+
60
+
61
+ class ExchangeEndpoint:
62
+ def __init__(self, root):
63
+ self.root = normal(root)
64
+ require(self.root.is_dir(), 'Choose an existing independent endpoint directory.')
65
+ require(not (self.root / '.taskcarry' / 'state.sqlite3').exists(), 'Use an endpoint directory, not a project control.')
66
+ self.meta = safe(self.root, '.taskcarry-endpoint')
67
+
68
+ def _json(self, name):
69
+ path = safe(self.meta, name)
70
+ return parse(read_file_bytes(path, MAX_PACKET)) if path.exists() else None
71
+
72
+ def config(self):
73
+ value = self._json('connection.json')
74
+ require(value is not None, 'Join a reviewed project view first.', 'ENDPOINT_NOT_JOINED')
75
+ require(value['endpoint_identity'] == self._identity(), 'Endpoint was relocated; explicitly rejoin.', 'ENDPOINT_REBIND_REQUIRED')
76
+ return value
77
+
78
+ def _identity(self):
79
+ return [str(self.root), self.root.stat().st_dev, self.root.stat().st_ino]
80
+
81
+ def view(self):
82
+ config = self.config()
83
+ body, objects = inspect(read_file_bytes(safe(self.meta, 'packets/' + config['packet_sha256'] + '.zip'), MAX_PACKET),
84
+ config['packet_sha256'])
85
+ return config, body, objects
86
+
87
+ def _plan(self, operation, payload, review):
88
+ body = {'operation': operation, 'endpoint_identity': self._identity(), 'payload': payload,
89
+ 'before': fingerprint(self._json('connection.json'))}
90
+ key = 'ep-' + fingerprint(body)
91
+ atomic(safe(self.meta, 'plans/' + key + '.json'), packed(body))
92
+ return {'plan_id': key, 'operation': operation, 'review': review, 'effects_executed': False}
93
+
94
+ def invoke(self, action, plan_id=None, repository=None, remote=None, input_ref=None, packet_path=None,
95
+ commit=None, expected_sha256=None, project_id=None, binding_id=None, invitation_id=None,
96
+ workspaces=None, sources=None, handbacks=None, reads=None, preservations=None, output_path=None,
97
+ section=None, reference=None, cursor=None, limit=5, max_bytes=4096,
98
+ task_id=None, workspace_id=None, path=None, experience_feedback=None):
99
+ if action == 'inspect':
100
+ return self.brief(section or 'overview', limit, cursor)
101
+ if action == 'read':
102
+ return self.read(reference, cursor, max_bytes)
103
+ if action in {'join_plan', 'refresh_plan'}:
104
+ previous = self._json('connection.json')
105
+ if action == 'refresh_plan':
106
+ previous = self.config()
107
+ source = previous['source']
108
+ mappings = previous['workspaces']
109
+ project_id, binding_id, invitation_id = (previous[x] for x in ('project_id', 'binding_id', 'invitation_id'))
110
+ require(not any(x is not None for x in (repository, remote, input_ref, packet_path, workspaces)),
111
+ 'Refresh keeps the trusted connection and local workspace mapping.')
112
+ else:
113
+ require(previous is None, 'Keep the existing endpoint; use refresh for a new view.', 'ENDPOINT_ALREADY_JOINED')
114
+ source = git_source(repository, remote, input_ref, packet_path)
115
+ mappings = []
116
+ for item in workspaces or []:
117
+ root = normal(item['path'])
118
+ require(root.is_dir() and root != self.root and not root.is_relative_to(self.meta),
119
+ 'Choose an existing separate work directory.')
120
+ mappings.append({'workspace_id': _id(item['workspace_id'], 'Workspace'), 'path': str(root),
121
+ 'identity': [root.stat().st_dev, root.stat().st_ino]})
122
+ require(mappings and len({x['workspace_id'] for x in mappings}) == len(mappings), 'Map each selected workspace once.')
123
+ require(isinstance(expected_sha256, str) and re.fullmatch('[0-9a-f]{64}', expected_sha256),
124
+ 'Supply the independently reviewed view packet SHA-256.')
125
+ data, origin = read_git(source, commit)
126
+ body, objects = inspect(data, expected_sha256)
127
+ require(body['kind'] == 'view' and body['project_id'] == project_id and body['binding_id'] == binding_id
128
+ and body['invitation_id'] == invitation_id, 'View differs from the selected project/member/invitation.', 'EXCHANGE_MEMBER_MISMATCH')
129
+ require(body['view_id'] == fingerprint({k: v for k, v in body.items() if k != 'view_id'}), 'View fingerprint mismatch.')
130
+ binding = validate_record('binding', body['binding'])
131
+ require(binding['role'] == 'worker' and binding['state'] == 'active'
132
+ and binding['binding_id'] == binding_id and binding['project_id'] == project_id, 'Invalid invited role.')
133
+ allowed = {x['workspace_id'] for x in binding['assignments']}
134
+ require(all(x['workspace_id'] in allowed for x in mappings), 'A local mapping is not assigned to this member.')
135
+ for record in body['sources']:
136
+ value = validate_record('source', record)
137
+ require(value['project_id'] == project_id and value['content_sha256'] in objects
138
+ and len(objects[value['content_sha256']]) == value['size'], 'Invalid view source.')
139
+ if 'experience' in body:
140
+ from .experience_exchange import validate_view
141
+ validate_view(body, objects)
142
+ if previous:
143
+ require(_git(source['repository'], 'merge-base', '--is-ancestor', previous['origin']['commit'], commit,
144
+ check=False).returncode == 0, 'View history moved backwards or diverged.', 'ENDPOINT_VIEW_ROLLBACK')
145
+ _, old, _ = self.view()
146
+ require(body['binding']['revision'] >= old['binding']['revision']
147
+ and body['invitation_revision'] >= old['invitation_revision'], 'View scope revision moved backwards.')
148
+ config = {'format': 1, 'source': source, 'project_id': project_id, 'binding_id': binding_id,
149
+ 'invitation_id': invitation_id, 'workspaces': mappings, 'packet_sha256': sha(data),
150
+ 'origin': origin, 'endpoint_identity': self._identity()}
151
+ atomic(safe(self.meta, 'packets/' + sha(data) + '.zip'), data)
152
+ return self._plan('join', {'connection': config}, {'project_id': project_id, 'binding_id': binding_id,
153
+ 'view_id': body['view_id'], 'last_known': True, 'second_control_created': False})
154
+ if action == 'reply_plan':
155
+ return self.reply(sources or [], handbacks or [], reads or [], preservations or [], output_path, experience_feedback)
156
+ if action == 'acquire_plan':
157
+ config, view, objects = self.view()
158
+ source = next((s for s in view['sources'] if
159
+ {k: s[k] for k in ('reference_id', 'revision', 'content_sha256')} == reference), None)
160
+ require(source is not None, 'Source is absent from the selected cache.', 'WORKER_SOURCE_UNAVAILABLE')
161
+ root = self.workspace(config, view, task_id, workspace_id, 'handback')
162
+ target = validate_relative_path(root, path)
163
+ require(target.parent.is_dir(), 'Create the selected destination parent first.')
164
+ require(not target.exists() or read_file_bytes(target) == objects[source['content_sha256']],
165
+ 'Preserve existing different content.', 'WORKER_DESTINATION_CONFLICT')
166
+ return self._plan('acquire', {'reference': reference, 'task_id': task_id, 'workspace_id': workspace_id,
167
+ 'path': path, 'packet_sha256': config['packet_sha256']},
168
+ {'reference': reference, 'workspace_id': workspace_id, 'path': path, 'last_known': True})
169
+ require(action == 'execute' and isinstance(plan_id, str), 'Use a supported endpoint action and exact plan.')
170
+ require(not any(x is not None for x in (repository, remote, input_ref, packet_path, commit,
171
+ expected_sha256, project_id, binding_id, invitation_id, workspaces, sources,
172
+ handbacks, reads, preservations, output_path, section, reference, cursor, task_id, workspace_id, path, experience_feedback)),
173
+ 'Execute only the exact saved plan; no replacement fields.')
174
+ _id(plan_id, 'Endpoint plan')
175
+ with lock(safe(self.meta, 'endpoint.lock')):
176
+ plan = self._json('plans/' + plan_id + '.json')
177
+ require(plan and plan_id == 'ep-' + fingerprint(plan) and plan['endpoint_identity'] == self._identity(),
178
+ 'Unknown or relocated endpoint plan.', 'ENDPOINT_PLAN_INVALID')
179
+ receipt = self._json('receipts/' + plan_id + '.json')
180
+ if receipt:
181
+ if plan['operation'] == 'acquire':
182
+ config, view, objects = self.view()
183
+ payload = plan['payload']
184
+ root = self.workspace(config, view, payload['task_id'], payload['workspace_id'], 'handback')
185
+ target = validate_relative_path(root, payload['path'], allow_missing=False)
186
+ require(sha(read_file_bytes(target)) == payload['reference']['content_sha256'],
187
+ 'Acquired file changed; preserve the edit.', 'WORKER_DESTINATION_CONFLICT')
188
+ elif plan['operation'] == 'reply':
189
+ target = normal(plan['payload']['destination'])
190
+ require(target.exists() and sha(read_file_bytes(target, MAX_PACKET)) == plan['payload']['packet_sha256'],
191
+ 'Completed output was modified; preserve the change.', 'EXCHANGE_OUTPUT_CHANGED')
192
+ return {**receipt, 'reused': True, 'effects_executed': False}
193
+ payload = plan['payload']
194
+ current = self._json('connection.json')
195
+ if plan['operation'] == 'join':
196
+ require(fingerprint(current) == plan['before'] or current == payload['connection'],
197
+ 'Endpoint changed after planning.', 'ENDPOINT_CHANGED')
198
+ # Recheck pinned Git source, exact packet and local directory identities.
199
+ data, _ = read_git(payload['connection']['source'], payload['connection']['origin']['commit'])
200
+ inspect(data, payload['connection']['packet_sha256'])
201
+ for mapping in payload['connection']['workspaces']:
202
+ root = normal(mapping['path'])
203
+ require(root.is_dir() and [root.stat().st_dev, root.stat().st_ino] == mapping['identity'], 'Local workspace changed.')
204
+ atomic(safe(self.meta, 'connection.json'), packed(payload['connection']), replace=True)
205
+ result = {'project_id': payload['connection']['project_id'], 'binding_id': payload['connection']['binding_id'],
206
+ 'packet_sha256': payload['connection']['packet_sha256'], 'last_known': True, 'read_acknowledged': False}
207
+ elif plan['operation'] == 'acquire':
208
+ require(fingerprint(current) == plan['before'], 'Cached view changed; review a new acquisition.', 'ENDPOINT_CHANGED')
209
+ config, view, objects = self.view()
210
+ root = self.workspace(config, view, payload['task_id'], payload['workspace_id'], 'handback')
211
+ target = validate_relative_path(root, payload['path'])
212
+ data = objects[payload['reference']['content_sha256']]
213
+ require(not target.exists() or read_file_bytes(target) == data,
214
+ 'Preserve changed destination.', 'WORKER_DESTINATION_CONFLICT')
215
+ atomic(target, data)
216
+ require(read_file_bytes(target) == data, 'Acquired file verification failed.')
217
+ result = {'reference': payload['reference'], 'workspace_id': payload['workspace_id'],
218
+ 'path': payload['path'], 'last_known': True, 'acquired': True, 'read': False}
219
+ else:
220
+ require(plan['operation'] == 'reply', 'Unknown endpoint plan operation.')
221
+ require(fingerprint(current) == plan['before'], 'Refresh changed the view; prepare a new reply.', 'ENDPOINT_CHANGED')
222
+ source = current['source']
223
+ require(git_source(source['repository'], source['remote'], source['ref'], source['path']) == source,
224
+ 'Transport directory or remote changed.', 'EXCHANGE_SOURCE_CHANGED')
225
+ data = read_file_bytes(safe(self.meta, 'packets/' + payload['packet_sha256'] + '.zip'), MAX_PACKET)
226
+ inspect(data, payload['packet_sha256'])
227
+ destination = normal(payload['destination'])
228
+ before = sha(read_file_bytes(destination, MAX_PACKET)) if destination.exists() else None
229
+ require(before in {payload['before'], payload['packet_sha256']}, 'Preserve changed outgoing file.', 'EXCHANGE_OUTPUT_CHANGED')
230
+ # The outgoing packet contains frozen selected bytes, not a claim about later edits.
231
+ atomic(destination, data, replace=True)
232
+ require(sha(read_file_bytes(destination, MAX_PACKET)) == payload['packet_sha256'], 'Outgoing verification failed.')
233
+ result = {'packet_sha256': payload['packet_sha256'], 'path': str(destination),
234
+ 'git_published': False, 'governor_received': False, 'view_id': payload['view_id']}
235
+ result['effects_executed'] = True
236
+ atomic(safe(self.meta, 'receipts/' + plan_id + '.json'), packed(result))
237
+ return result
238
+
239
+ def workspace(self, config, view, task_id, workspace_id, action):
240
+ require(any(x['task_id'] == task_id and x['workspace_id'] == workspace_id and action in x['write_actions']
241
+ for x in view['binding']['assignments']), 'This cached role does not assign this action.', 'WORKER_SCOPE_DENIED')
242
+ mapping = next((x for x in config['workspaces'] if x['workspace_id'] == workspace_id), None)
243
+ require(mapping is not None, 'Map the selected local workspace explicitly.')
244
+ root = normal(mapping['path'])
245
+ require(root.is_dir() and [root.stat().st_dev, root.stat().st_ino] == mapping['identity'], 'The mapped local directory changed.')
246
+ return root
247
+
248
+ def reply(self, selected, handbacks, reads, preservations, output_path, experience_feedback=None):
249
+ config, view, _ = self.view()
250
+ require(len(selected) <= 64 and len(handbacks) <= 64 and len(reads) <= 64 and len(preservations) <= 64,
251
+ 'Keep an outgoing reply bounded.')
252
+ body = {k: view[k] for k in ('project_id', 'binding_id', 'invitation_id', 'invitation_revision', 'view_id')}
253
+ body.update(kind='reply', sources=[], handbacks=[], reads=[], preservations=[])
254
+ if experience_feedback is not None:
255
+ from .experience_exchange import validate_reply
256
+ validate_reply(view, experience_feedback)
257
+ for value in experience_feedback:
258
+ self.workspace(config, view, value['task_id'], value['workspace_id'], 'experience_feedback')
259
+ body['experience_feedback'] = experience_feedback
260
+ objects = {}
261
+ for selection in selected:
262
+ require(set(selection) <= {'reference_id', 'revision', 'task_id', 'workspace_id', 'path', 'visibility', 'media_type'},
263
+ 'Unsupported source selection.')
264
+ root = self.workspace(config, view, selection['task_id'], selection['workspace_id'], 'handback')
265
+ path = validate_relative_path(root, selection['path'], allow_missing=False)
266
+ data = read_file_bytes(path)
267
+ visibility = selection.get('visibility', 'self')
268
+ require(visibility != 'project' or view['binding']['share_project'], 'Project sharing is not granted.')
269
+ value = validate_record('source', {'contract_version': 1, 'project_id': view['project_id'],
270
+ 'revision': selection['revision'], 'reference_id': selection['reference_id'],
271
+ 'owner_binding_id': view['binding_id'], 'task_id': selection['task_id'], 'state': 'active',
272
+ 'visibility': visibility, 'media_type': selection.get('media_type', 'text/markdown'),
273
+ 'content_sha256': sha(data), 'size': len(data), 'origin': {'kind': 'artifact',
274
+ 'artifact_id': selection['reference_id'], 'artifact_revision': selection['revision']}})
275
+ objects[sha(data)] = data
276
+ body['sources'].append({'record': value, 'workspace_id': selection['workspace_id']})
277
+ for records, kind, field in ((handbacks, 'handback', 'handbacks'), (reads, 'read_receipt', 'reads')):
278
+ for value in records:
279
+ record = validate_record(kind, value)
280
+ require(record['project_id'] == view['project_id'] and record['binding_id'] == view['binding_id'],
281
+ 'Only this member can author the outgoing record.', 'WORKER_ACTOR_MISMATCH')
282
+ if kind == 'handback':
283
+ self.workspace(config, view, record['task_id'], record['workspace_id'], 'handback')
284
+ task = next((x for x in view['sections']['tasks'] if x['task_id'] == record['task_id']), None)
285
+ require(task and record['basis'] == {'binding_revision': view['binding']['revision'],
286
+ 'task_fingerprint': task['task_fingerprint']}, 'Handback does not use the selected view.')
287
+ body[field].append(record)
288
+ for selection in preservations:
289
+ require(set(selection) == {'task_id', 'workspace_id', 'paths'}, 'Select exact checkpoint paths.')
290
+ root = self.workspace(config, view, selection['task_id'], selection['workspace_id'], 'checkpoint')
291
+ require(isinstance(selection['paths'], list) and 1 <= len(selection['paths']) <= 100, 'Select bounded files.')
292
+ probe = _git(root, 'rev-parse', '--verify', 'HEAD', check=False)
293
+ head = probe.stdout.decode().strip() if probe.returncode == 0 else None
294
+ is_git = _git(root, 'rev-parse', '--is-inside-work-tree', check=False).returncode == 0
295
+ captured = {'task_id': selection['task_id'], 'workspace_id': selection['workspace_id'], 'head_commit': head, 'files': []}
296
+ for relative in selection['paths']:
297
+ path = validate_relative_path(root, relative)
298
+ entry = {'path': relative}
299
+ for layer in ('head', 'index', 'worktree'):
300
+ item = ((read_file_bytes(path), '100755' if path.stat().st_mode & 0o111 else '100644')
301
+ if layer == 'worktree' and path.exists() else
302
+ git_layer(root, relative, layer) if (layer == 'head' and head or layer == 'index' and is_git) else None)
303
+ if item is None:
304
+ entry[layer] = None
305
+ else:
306
+ data, mode = item; objects[sha(data)] = data
307
+ entry[layer] = {'sha256': sha(data), 'size': len(data), 'mode': mode}
308
+ captured['files'].append(entry)
309
+ # Re-read only the selected layers. Do not scan unrelated work or
310
+ # accept a mixed capture if an editor/Git process changed them.
311
+ for entry in captured['files']:
312
+ path = validate_relative_path(root, entry['path'])
313
+ for layer in ('head', 'index', 'worktree'):
314
+ item = ((read_file_bytes(path), '100755' if path.stat().st_mode & 0o111 else '100644')
315
+ if layer == 'worktree' and path.exists() else
316
+ git_layer(root, entry['path'], layer) if (layer == 'head' and head or layer == 'index' and is_git) else None)
317
+ check = {'sha256': sha(item[0]), 'size': len(item[0]), 'mode': item[1]} if item is not None else None
318
+ require(check == entry[layer], 'Selected layers changed during capture.', 'ENDPOINT_CAPTURE_CHANGED')
319
+ final_head = _git(root, 'rev-parse', '--verify', 'HEAD', check=False)
320
+ require((final_head.stdout.decode().strip() if final_head.returncode == 0 else None) == head,
321
+ 'HEAD changed during preservation.', 'ENDPOINT_CAPTURE_CHANGED')
322
+ validate_preservation(captured, objects)
323
+ body['preservations'].append(captured)
324
+ require(any(body.get(x) for x in ('sources', 'handbacks', 'reads', 'preservations', 'experience_feedback')), 'No outgoing work selected.')
325
+ data = build(body, objects)
326
+ destination = validate_relative_path(Path(config['source']['repository']), output_path)
327
+ require(destination.parent.is_dir(), 'Create the selected output directory first.')
328
+ before = sha(read_file_bytes(destination, MAX_PACKET)) if destination.exists() else None
329
+ atomic(safe(self.meta, 'packets/' + sha(data) + '.zip'), data)
330
+ return self._plan('reply', {'packet_sha256': sha(data), 'destination': str(destination), 'before': before,
331
+ 'view_id': view['view_id']}, {'packet_sha256': sha(data), 'view_id': view['view_id'],
332
+ 'counts': {key: len(body[key]) for key in ('sources', 'handbacks', 'reads', 'preservations', 'experience_feedback') if key in body},
333
+ 'last_known': True, 'central_acceptance': 'Pending current scope/version checks at governor.'})
334
+
335
+ def brief(self, section='overview', limit=5, cursor=None):
336
+ _, view, _ = self.view()
337
+ require(type(limit) is int and 1 <= limit <= 20, 'Use a page limit from 1 to 20.')
338
+ stamp = view['view_id']; selection = fingerprint([view['binding_id'], section])
339
+ after = WorkerChannel._cursor(cursor, selection, stamp) if cursor else 0
340
+ require(type(after) is int and after >= 0, 'Invalid endpoint directory cursor.')
341
+ result = {'project_id': view['project_id'], 'binding_id': view['binding_id'], 'view_id': stamp,
342
+ 'last_known': True, 'observed_at': view['created_at'], 'live_governor_checked': False,
343
+ 'read_acknowledged': False, 'effects_executed': False, 'section': section}
344
+ if section == 'overview':
345
+ return {**result, 'overview': view['overview'], 'coverage': view['coverage']}
346
+ rows = view['sources'] if section == 'sources' else view['sections'].get(section)
347
+ require(isinstance(rows, list), 'Unknown cached directory section.')
348
+ items = rows[after:after + limit]
349
+ while items:
350
+ end = after + len(items)
351
+ response = {**result, 'items': items, 'total': len(rows), 'returned': len(items), 'has_more': end < len(rows),
352
+ 'next_cursor': WorkerChannel._encode(selection, stamp, end) if end < len(rows) else None}
353
+ try:
354
+ WorkerChannel._budget(response); return response
355
+ except GovernanceError as exc:
356
+ if exc.code != 'WORKER_RESPONSE_TOO_LARGE' or len(items) == 1:
357
+ raise
358
+ items.pop()
359
+ return {**result, 'items': [], 'total': len(rows), 'returned': 0, 'has_more': False, 'next_cursor': None}
360
+
361
+ def read(self, reference, cursor=None, max_bytes=4096):
362
+ _, view, objects = self.view()
363
+ require(type(max_bytes) is int and 256 <= max_bytes <= 4096, 'Use a bounded source read.')
364
+ source = next((x for x in view['sources'] if {k: x[k] for k in ('reference_id', 'revision', 'content_sha256')} == reference), None)
365
+ require(source is not None, 'Source is not part of the selected cached view.', 'WORKER_SOURCE_UNAVAILABLE')
366
+ # Reuse the exact text pagination implementation; only the trusted source
367
+ # lookup changes to this pinned last-known cache.
368
+ class Reader:
369
+ actor = view['binding_id']
370
+ _cursor = staticmethod(WorkerChannel._cursor)
371
+ _encode = staticmethod(WorkerChannel._encode)
372
+ def _source(self, ref): return source
373
+ def _bytes(self, value): return objects[value['content_sha256']]
374
+ result = WorkerChannel.source_read(Reader(), reference, cursor, max_bytes)
375
+ result.update(last_known=True, view_id=view['view_id'], live_governor_checked=False)
376
+ WorkerChannel._budget(result)
377
+ return result
@@ -0,0 +1,142 @@
1
+ """Selected immutable exchange media. No extraction, checkout or authority import."""
2
+ from __future__ import annotations
3
+
4
+ import hashlib
5
+ import io
6
+ import json
7
+ import re
8
+ import zipfile
9
+
10
+ from .core import validate_relative_path
11
+ from .remote_transfer import _git, _out, _repository, _identity, _remote_url
12
+ from .store import GovernanceError
13
+ from .worker_channel import packed
14
+
15
+ SCHEMA = 'taskcarry.collaboration-packet.v1'
16
+ EXPERIENCE_SCHEMA = 'taskcarry.collaboration-packet.v2'
17
+ MAX_OBJECT = 32 * 1024 * 1024
18
+ MAX_PACKET = 32 * 1024 * 1024
19
+ MAX_MANIFEST = 1024 * 1024
20
+ MAX_OBJECTS = 256
21
+
22
+
23
+ def require(condition, message, code='EXCHANGE_INVALID'):
24
+ if not condition:
25
+ raise GovernanceError(code, message)
26
+
27
+
28
+ def sha(data):
29
+ return hashlib.sha256(data).hexdigest()
30
+
31
+
32
+ def _unique(pairs):
33
+ result = {}
34
+ for key, value in pairs:
35
+ require(key not in result, 'Duplicate JSON keys are not accepted.')
36
+ result[key] = value
37
+ return result
38
+
39
+
40
+ def parse(data):
41
+ try:
42
+ return json.loads(data.decode('utf-8'), object_pairs_hook=_unique,
43
+ parse_constant=lambda value: require(False, 'Nonfinite JSON number.'))
44
+ except (ValueError, UnicodeError, RecursionError) as exc:
45
+ raise GovernanceError('EXCHANGE_INVALID', 'Invalid UTF-8 JSON.') from exc
46
+
47
+
48
+ def build(body, objects):
49
+ require(isinstance(body, dict) and body.get('kind') in {'view', 'reply'}, 'Choose a view or reply packet.')
50
+ require(len(objects) <= MAX_OBJECTS, 'Too many selected objects.')
51
+ for key, data in objects.items():
52
+ require(key == sha(data) and len(data) <= MAX_OBJECT, 'Invalid object digest or size.')
53
+ manifest = {'schema': packet_schema(body), 'body': body,
54
+ 'objects': [{'sha256': key, 'size': len(data)} for key, data in sorted(objects.items())]}
55
+ raw = packed(manifest)
56
+ require(len(raw) <= MAX_MANIFEST and len(raw) + sum(map(len, objects.values())) <= MAX_PACKET,
57
+ 'Select a smaller exchange batch.')
58
+ buffer = io.BytesIO()
59
+ # Stored entries make the byte/space limit independent of compression ratios.
60
+ with zipfile.ZipFile(buffer, 'w', compression=zipfile.ZIP_STORED) as archive:
61
+ for name, data in [('manifest.json', raw), *[('objects/' + k, v) for k, v in sorted(objects.items())]]:
62
+ info = zipfile.ZipInfo(name, date_time=(2020, 1, 1, 0, 0, 0))
63
+ info.external_attr = 0o100600 << 16
64
+ archive.writestr(info, data)
65
+ result = buffer.getvalue()
66
+ require(len(result) <= MAX_PACKET, 'Packet exceeds the transfer limit.')
67
+ return result
68
+
69
+
70
+ def packet_schema(body):
71
+ # An older endpoint rejects v2 rather than silently discarding experience.
72
+ return EXPERIENCE_SCHEMA if 'experience' in body or 'experience_feedback' in body else SCHEMA
73
+
74
+
75
+ def inspect(data, expected_sha256=None):
76
+ require(len(data) <= MAX_PACKET, 'Packet exceeds the transfer limit.')
77
+ if expected_sha256 is not None:
78
+ require(sha(data) == expected_sha256, 'Packet differs from its expected digest.', 'EXCHANGE_CHANGED')
79
+ try:
80
+ with zipfile.ZipFile(io.BytesIO(data)) as archive:
81
+ members = archive.infolist()
82
+ require(len(members) <= MAX_OBJECTS + 1, 'Too many archive members.')
83
+ names = [x.filename for x in members]
84
+ require(len(names) == len(set(names)) and 'manifest.json' in names, 'Invalid archive directory.')
85
+ require(all(x.compress_type == zipfile.ZIP_STORED and not x.flag_bits & 1
86
+ and not x.is_dir() and x.file_size <= MAX_OBJECT for x in members),
87
+ 'Only bounded, unencrypted ordinary stored entries are accepted.')
88
+ require(archive.getinfo('manifest.json').file_size <= MAX_MANIFEST, 'Manifest too large.')
89
+ manifest = parse(archive.read('manifest.json'))
90
+ require(set(manifest) == {'schema', 'body', 'objects'} and manifest['schema'] in {SCHEMA, EXPERIENCE_SCHEMA},
91
+ 'Unsupported packet format.')
92
+ require(isinstance(manifest['body'], dict) and manifest['body'].get('kind') in {'view', 'reply'},
93
+ 'Unknown packet direction.')
94
+ require(manifest['schema'] == packet_schema(manifest['body']), 'Packet capabilities and version disagree.')
95
+ descriptors = manifest['objects']
96
+ require(isinstance(descriptors, list) and len(descriptors) <= MAX_OBJECTS, 'Invalid object list.')
97
+ objects = {}
98
+ for item in descriptors:
99
+ require(isinstance(item, dict) and set(item) == {'sha256', 'size'}, 'Invalid object descriptor.')
100
+ key = item['sha256']
101
+ require(isinstance(key, str) and re.fullmatch('[0-9a-f]{64}', key)
102
+ and key not in objects and type(item['size']) is int
103
+ and 0 <= item['size'] <= MAX_OBJECT, 'Invalid object identity.')
104
+ blob = archive.read('objects/' + key)
105
+ require(len(blob) == item['size'] and sha(blob) == key, 'Object bytes do not match the manifest.')
106
+ objects[key] = blob
107
+ require(set(names) == {'manifest.json', *('objects/' + key for key in objects)},
108
+ 'Unselected paths in packet.')
109
+ return manifest['body'], objects
110
+ except (KeyError, TypeError, ValueError, zipfile.BadZipFile, NotImplementedError) as exc:
111
+ raise GovernanceError('EXCHANGE_INVALID', 'Malformed selected-content packet.') from exc
112
+
113
+
114
+ def git_source(repository, remote, ref, path):
115
+ root = _repository(repository)
116
+ require(isinstance(ref, str) and ref.startswith('refs/') and
117
+ _git(root, 'check-ref-format', ref, check=False).returncode == 0, 'Use an exact Git ref.')
118
+ validate_relative_path(root, path)
119
+ return {'repository': str(root), 'identity': _identity(root), 'remote': remote,
120
+ 'url': _remote_url(root, remote), 'ref': ref, 'path': path}
121
+
122
+
123
+ def read_git(source, commit):
124
+ current = git_source(source['repository'], source['remote'], source['ref'], source['path'])
125
+ require(current == source, 'The pinned repository or remote changed.', 'EXCHANGE_SOURCE_CHANGED')
126
+ require(isinstance(commit, str) and re.fullmatch('[0-9a-f]{40}|[0-9a-f]{64}', commit),
127
+ 'Select a complete Git commit identity.')
128
+ root = source['repository']
129
+ require(_out(root, 'cat-file', '-t', commit) == 'commit', 'The selected object is not a commit.')
130
+ tip = _out(root, 'rev-parse', '--verify', source['ref'] + '^{commit}')
131
+ require(_git(root, 'merge-base', '--is-ancestor', commit, tip, check=False).returncode == 0,
132
+ 'Commit is not reachable from the invited input ref.', 'EXCHANGE_REF_MISMATCH')
133
+ entry = _git(root, 'ls-tree', '-z', commit, '--', source['path']).stdout.rstrip(b'\0')
134
+ require(bool(entry), 'Selected packet is absent from this commit.')
135
+ meta, path = entry.split(b'\t', 1)
136
+ mode, kind, oid = meta.decode().split()
137
+ require(path.decode('utf-8') == source['path'] and mode in {'100644', '100755'} and kind == 'blob',
138
+ 'Select an exact ordinary packet file, not a link or tree.')
139
+ require(int(_out(root, 'cat-file', '-s', oid)) <= MAX_PACKET, 'Git packet exceeds the transfer limit.')
140
+ data = _git(root, 'cat-file', 'blob', oid).stdout
141
+ inspect(data)
142
+ return data, {'commit': commit, 'blob': oid, 'observed_ref': tip, 'sha256': sha(data), 'bytes': len(data)}