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,859 @@
1
+ """Server-bound project membership, selected content and durable handback.
2
+
3
+ This is an application authorization boundary, not a sandbox for other processes
4
+ running under the same OS account. The unrestricted local API remains an admin
5
+ interface. Bound endpoints never accept their identity from tool arguments.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import base64
10
+ from dataclasses import dataclass
11
+ import hashlib
12
+ import json
13
+ from pathlib import Path
14
+
15
+ from .core import Core, _id, _linked, _checkpoint_uses_git, git, read_file_bytes, validate_relative_path
16
+ from .store import GovernanceError, now
17
+ from .worker_contracts import COLLECTIONS, validate_record
18
+ from .worker_tools import GOVERNOR_ACTIONS, WORKER_ACTIONS, READ_ACTIONS
19
+ from . import worker_storage as index
20
+
21
+ MAX_RESULT_BYTES = 7000 # Leaves room for the MCP text + structured envelopes.
22
+ MEDIA = {'text/markdown', 'text/plain', 'application/json', 'application/octet-stream',
23
+ 'image/png', 'image/jpeg', 'image/webp', 'image/svg+xml', 'application/pdf'}
24
+
25
+
26
+ def packed(value):
27
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8')
28
+
29
+
30
+ def fingerprint(value):
31
+ return hashlib.sha256(packed(value)).hexdigest()
32
+
33
+
34
+ def wire_size(value):
35
+ envelope = {'ok': True, 'result': value}
36
+ result = {'content': [{'type': 'text', 'text': packed(envelope).decode('utf-8')}],
37
+ 'structuredContent': envelope, 'isError': False}
38
+ return len(json.dumps(result, ensure_ascii=False).encode('utf-8')) + 256
39
+
40
+
41
+ def fail(code, message):
42
+ raise GovernanceError(code, message)
43
+
44
+
45
+ @dataclass(frozen=True)
46
+ class Caller:
47
+ binding_id: str
48
+ role_ceiling: str = 'reader'
49
+ project_id: str | None = None
50
+ expected_binding_revision: int | None = None
51
+
52
+ def __post_init__(self):
53
+ _id(self.binding_id, 'Binding')
54
+ if self.role_ceiling not in {'reader', 'worker', 'governor'}:
55
+ fail('WORKER_ROLE_INVALID', 'Use reader, worker or governor.')
56
+ if self.expected_binding_revision is not None and (type(self.expected_binding_revision) is not int
57
+ or self.expected_binding_revision < 1):
58
+ fail('WORKER_BINDING_CHANGED', 'Pin an exact positive member revision.')
59
+
60
+
61
+ def allowed_tools(caller):
62
+ if caller is None or caller.role_ceiling == 'governor':
63
+ return GOVERNOR_ACTIONS
64
+ return WORKER_ACTIONS if caller.role_ceiling == 'worker' else READ_ACTIONS
65
+
66
+
67
+ def channel_epoch(store):
68
+ config = store.get('config', 'project')
69
+ return fingerprint({'control': str(store.root.resolve()), 'replica_id': config.get('replica_id'),
70
+ 'restore_id': config.get('recovery_restore_id')})
71
+
72
+
73
+ class WorkerChannel:
74
+ def __init__(self, project, caller=None):
75
+ self.core = Core(project)
76
+ self.store = self.core.store
77
+ self.caller = caller
78
+ self.project_id = self.core.source()['source_id']
79
+ self.actor = caller.binding_id if caller else 'local-governor'
80
+ self.binding = None
81
+
82
+ def _epoch(self):
83
+ return channel_epoch(self.store)
84
+
85
+ def _auth(self, action):
86
+ if self.caller is None:
87
+ self.binding = {'binding_id': self.actor, 'revision': 0, 'role': 'governor',
88
+ 'read_project_shared': True, 'share_project': True, 'assignments': []}
89
+ else:
90
+ if self.caller.project_id and self.caller.project_id != self.project_id:
91
+ fail('WORKER_PROJECT_CHANGED', 'The endpoint no longer identifies the bound project.')
92
+ binding = self.store.get(COLLECTIONS['binding'], self.actor)
93
+ if not binding or binding['state'] != 'active' or binding['project_id'] != self.project_id:
94
+ fail('WORKER_BINDING_INACTIVE', 'The server binding is unknown or revoked.')
95
+ if self.caller.expected_binding_revision is not None and binding['revision'] != self.caller.expected_binding_revision:
96
+ fail('WORKER_BINDING_CHANGED', 'This invitation no longer has the member revision it was granted.')
97
+ if self.store.get('worker_binding_epochs', self.actor) != {'epoch': self._epoch()}:
98
+ fail('WORKER_REBIND_REQUIRED', 'This restored or relocated replica needs an explicit local member binding.')
99
+ rank = {'reader': 0, 'worker': 1, 'governor': 2}
100
+ effective = min(rank[binding['role']], rank[self.caller.role_ceiling])
101
+ self.binding = {**binding, 'role': ('reader', 'worker', 'governor')[effective]}
102
+ allowed = (GOVERNOR_ACTIONS if self.binding['role'] == 'governor' else
103
+ WORKER_ACTIONS if self.binding['role'] == 'worker' else READ_ACTIONS)
104
+ if action not in allowed:
105
+ fail('WORKER_ACTION_DENIED', 'This server binding cannot perform that action.')
106
+
107
+ def invoke(self, action, args):
108
+ self._auth(action)
109
+ if args.get('mode') == 'execute' and set(args) - {'mode', 'plan_id'}:
110
+ fail('INVALID_ARGUMENT', 'Execute only the exact saved plan; do not supply replacement fields.')
111
+ write = args.get('mode') in {'plan', 'execute'}
112
+ if write:
113
+ with self.store.transaction():
114
+ self._auth(action) # Fresh scope inside the same transaction as publication.
115
+ if action == 'worker_binding':
116
+ index.install(self.store)
117
+ result = self._dispatch(action, args)
118
+ self._budget(result) # Failure rolls back records/events, not just the response.
119
+ else:
120
+ with self.store._connect(readonly=True) as db:
121
+ self.store._local.connection = db
122
+ try:
123
+ self._auth(action)
124
+ result = self._dispatch(action, args)
125
+ self._budget(result)
126
+ finally:
127
+ self.store._local.connection = None
128
+ return result
129
+
130
+ @staticmethod
131
+ def _budget(value):
132
+ if len(packed(value)) > MAX_RESULT_BYTES or wire_size(value) > 16384:
133
+ fail('WORKER_RESPONSE_TOO_LARGE', 'Narrow the page or use an immutable source for large content.')
134
+
135
+ def _dispatch(self, action, args):
136
+ if action in {'member_lookup', 'project_history', 'project_overview', 'overview_publish', 'discussion', 'discussion_update', 'turn_read'}:
137
+ from .project_collaboration import ProjectCollaboration
138
+ return getattr(ProjectCollaboration(self), action)(**args)
139
+ if action in {'experience_note', 'experience_feedback', 'experience_query'}:
140
+ from .experience_notes import ExperienceNotes
141
+ return ExperienceNotes(self).invoke(action, **args)
142
+ if action == 'source_share_set':
143
+ from .source_review_set import SourceReviewSet
144
+ return SourceReviewSet(self).invoke(**args)
145
+ if action == 'worker_submit_text':
146
+ from .text_handback import TextHandback
147
+ return TextHandback(self).invoke(**args)
148
+ if action == 'worker_connect':
149
+ from .role_connection import RoleConnection
150
+ return RoleConnection(self).invoke(**args)
151
+ if action == 'worker_exchange':
152
+ from .collaboration_exchange import CollaborationExchange
153
+ return CollaborationExchange(self).invoke(**args)
154
+ if action in {'identify', 'doctor'}:
155
+ from . import __version__
156
+ return {'project_id': self.project_id, 'project_name': self.store.get('config', 'project')['name'],
157
+ 'binding_id': self.actor, 'binding_revision': self.binding['revision'],
158
+ 'effective_role': self.binding['role'], 'toolkit_version': __version__,
159
+ 'channel_version': 1, 'channel_ready': index.ready(self.store),
160
+ 'conditional_experience_contract': 1,
161
+ 'read_only': True, 'effects_executed': False}
162
+ if action in {'status', 'agenda', 'context'}:
163
+ return self.worker_brief(section='handbacks' if action == 'agenda' else 'tasks',
164
+ task_id=args.get('task_id'), limit=min(args.get('limit', 5), 20),
165
+ cursor=args.get('cursor'), previous_fingerprint=args.get('previous_fingerprint'),
166
+ pending_only=action == 'agenda')
167
+ return getattr(self, action)(**args)
168
+
169
+ def _apply_worker_exchange(self, payload, guards):
170
+ from .collaboration_exchange import CollaborationExchange
171
+ return CollaborationExchange(self).apply(payload, guards)
172
+
173
+ def _apply_overview_publish(self, payload, guards):
174
+ from .project_collaboration import ProjectCollaboration
175
+ return ProjectCollaboration(self).apply_overview(payload, guards)
176
+
177
+ def _apply_discussion_update(self, payload, guards):
178
+ from .project_collaboration import ProjectCollaboration
179
+ return ProjectCollaboration(self).apply_discussion(payload, guards)
180
+
181
+ def _apply_experience_note(self, payload, guards):
182
+ from .experience_notes import ExperienceNotes
183
+ return ExperienceNotes(self).apply('note', payload, guards)
184
+
185
+ def _apply_experience_feedback(self, payload, guards):
186
+ from .experience_notes import ExperienceNotes
187
+ return ExperienceNotes(self).apply('feedback', payload, guards)
188
+
189
+ def _apply_source_share_set(self, payload, guards):
190
+ from .source_review_set import SourceReviewSet
191
+ return SourceReviewSet(self).apply(payload, guards)
192
+
193
+ def _apply_worker_submit_text(self, payload, guards):
194
+ from .text_handback import TextHandback
195
+ return TextHandback(self).apply(payload, guards)
196
+
197
+ def _apply_worker_connect(self, payload, guards):
198
+ from .role_connection import RoleConnection
199
+ return RoleConnection(self).apply(payload, guards)
200
+
201
+ def _governor(self):
202
+ if self.binding['role'] != 'governor':
203
+ fail('WORKER_ACTION_DENIED', 'Only the project governor can change this record.')
204
+
205
+ def _assignment(self, task_id, workspace_id, action=None):
206
+ task = self.core._task(task_id)
207
+ _id(workspace_id, 'Workspace')
208
+ if self.binding['role'] != 'governor':
209
+ found = next((a for a in self.binding['assignments']
210
+ if (a['task_id'], a['workspace_id']) == (task_id, workspace_id)), None)
211
+ if not found or (action and action not in found['write_actions']):
212
+ fail('WORKER_SCOPE_DENIED', 'The task/workspace/action is not assigned to this member.')
213
+ mapping = self.store.get('worker_workspaces', workspace_id)
214
+ if not mapping:
215
+ fail('WORKER_WORKSPACE_UNKNOWN', 'A governor must register this workspace.')
216
+ if mapping.get('epoch') != self._epoch():
217
+ fail('WORKER_REBIND_REQUIRED', 'Register a workspace for this replica before using local files.')
218
+ root = Path(mapping['path']).absolute()
219
+ if not root.is_dir() or any(_linked(p) for p in (root, *root.parents)):
220
+ fail('WORKER_WORKSPACE_CHANGED', 'The registered workspace is missing or traverses a link.')
221
+ if (root.stat().st_dev, root.stat().st_ino) != tuple(mapping['identity']):
222
+ fail('WORKER_WORKSPACE_CHANGED', 'The registered directory identity changed.')
223
+ return root, task
224
+
225
+ def _task_hash(self, task_id):
226
+ return fingerprint({k: v for k, v in self.core._task(task_id).items()
227
+ if k not in {'created_at', 'updated_at'}})
228
+
229
+ def _record(self, kind, supplied, expected_revision):
230
+ value = validate_record(kind, supplied)
231
+ if value['project_id'] != self.project_id:
232
+ fail('WORKER_PROJECT_CHANGED', 'Record project identity differs from this endpoint.')
233
+ key_field = {'binding': 'binding_id', 'source': 'reference_id', 'handback': 'handback_id',
234
+ 'disposition': 'disposition_id', 'read_receipt': 'receipt_id'}[kind]
235
+ key = value[key_field]
236
+ prior = self.store.get(COLLECTIONS[kind], key)
237
+ actual = prior['revision'] if prior else 0
238
+ if type(expected_revision) is not int or expected_revision != actual or value['revision'] != actual + 1:
239
+ fail('WORKER_REVISION_CONFLICT', 'Read the latest record and propose its next revision.')
240
+ return value, key
241
+
242
+ def _save_record(self, kind, key, value):
243
+ self.store.put(COLLECTIONS[kind], key, value)
244
+ self.store.put('worker_versions', kind + ':' + key + ':' + str(value['revision']), value)
245
+ self.store.event('worker_' + kind, {'id': key, 'revision': value['revision'], 'actor': self.actor})
246
+
247
+ def _plan(self, action, payload, guards):
248
+ body = {'action': action, 'actor': self.actor, 'project_id': self.project_id,
249
+ 'binding_revision': self.binding['revision'], 'epoch': self._epoch(),
250
+ 'payload': payload, 'guards': guards}
251
+ pid = 'wp-' + fingerprint(body)
252
+ old = self.store.get('worker_plans', pid)
253
+ if old is None:
254
+ self.store.put('worker_plans', pid, {**body, 'plan_id': pid, 'state': 'planned'})
255
+ return {'plan_id': pid, 'state': old['state'] if old else 'planned', 'action': action,
256
+ 'binding_revision': self.binding['revision'], 'effects_executed': False,
257
+ 'review': payload}
258
+
259
+ def _execute(self, action, plan_id, *, review_set_shares=None):
260
+ config = self.store.get('config', 'project')
261
+ if plan_id in config.get('recovery_inert_plan_ids', []):
262
+ fail('RESTORED_PLAN_INERT', 'Historical plans cannot execute in the restored replica.')
263
+ plan = self.store.get('worker_plans', _id(plan_id, 'Plan'))
264
+ if not plan or plan['actor'] != self.actor or plan['action'] != action or plan['project_id'] != self.project_id:
265
+ fail('WORKER_PLAN_DENIED', 'Use your own plan for this action and project.')
266
+ if plan.get('epoch') != self._epoch():
267
+ fail('WORKER_PLAN_INERT', 'The plan belongs to another replica; prepare a fresh local plan.')
268
+ if plan['state'] == 'completed':
269
+ return {**plan['result'], 'reused': True, 'effects_executed': False}
270
+ if plan['binding_revision'] != self.binding['revision']:
271
+ fail('WORKER_BINDING_CHANGED', 'The assignment changed; prepare a fresh plan.')
272
+ result = getattr(self, '_apply_' + action)(plan['payload'], plan['guards'])
273
+ self._budget(result)
274
+ self.store.put('worker_plans', plan_id, {**plan, 'state': 'completed', 'result': result})
275
+ if action == 'source_share' and result['published'] and result['visibility'] == 'project':
276
+ item = {**result['reference'], 'task_id': plan['payload']['record']['task_id']}
277
+ if review_set_shares is None:
278
+ self.record_project_shares([item])
279
+ else:
280
+ review_set_shares.append(item)
281
+ return result
282
+
283
+ def record_project_shares(self, references):
284
+ """One notification fact for a committed publication or atomic review set."""
285
+ if references:
286
+ payload = {'project_id': self.project_id, 'actor': self.actor, 'references': references}
287
+ self.store.event('project_sources_shared', {'event_id': fingerprint(payload), **payload})
288
+
289
+ def worker_binding(self, mode, plan_id=None, binding_id=None, expected_revision=None, record=None, workspaces=None):
290
+ self._governor()
291
+ if mode == 'get':
292
+ return self.store.get('worker_bindings', _id(binding_id, 'Binding'))
293
+ if mode == 'execute':
294
+ return self._execute('worker_binding', plan_id)
295
+ value, key = self._record('binding', record, expected_revision)
296
+ self._check_binding_sources(value)
297
+ mappings = []
298
+ for item in workspaces or []:
299
+ _id(item['workspace_id'], 'Workspace')
300
+ root = Path(item['path']).absolute()
301
+ if not root.is_dir() or any(_linked(p) for p in (root, *root.parents)) or root.is_relative_to(self.store.directory):
302
+ fail('WORKER_WORKSPACE_INVALID', 'Use an existing ordinary workspace outside governance metadata.')
303
+ previous = self.store.get('worker_workspaces', item['workspace_id'])
304
+ candidate = {'workspace_id': item['workspace_id'], 'path': str(root),
305
+ 'identity': [root.stat().st_dev, root.stat().st_ino], 'epoch': self._epoch()}
306
+ if previous and previous != candidate:
307
+ fail('WORKER_WORKSPACE_REBIND', 'Register a new workspace identity instead of moving an active mapping.')
308
+ mappings.append(candidate)
309
+ known = {w['workspace_id'] for w in mappings}
310
+ for assignment in value['assignments']:
311
+ self.core._task(assignment['task_id'])
312
+ if assignment['workspace_id'] not in known and not self.store.get('worker_workspaces', assignment['workspace_id']):
313
+ fail('WORKER_WORKSPACE_UNKNOWN', 'Register every assigned workspace explicitly.')
314
+ return self._plan('worker_binding', {'record': value, 'workspaces': mappings}, {'expected': expected_revision})
315
+
316
+ def _apply_worker_binding(self, payload, guards):
317
+ value, key = self._record('binding', payload['record'], guards['expected'])
318
+ self._check_binding_sources(value)
319
+ for mapping in payload['workspaces']:
320
+ root = Path(mapping['path'])
321
+ if not root.is_dir() or any(_linked(p) for p in (root, *root.parents)) or list((root.stat().st_dev, root.stat().st_ino)) != mapping['identity']:
322
+ fail('WORKER_WORKSPACE_CHANGED', 'The planned workspace identity changed.')
323
+ prior = self.store.get('worker_workspaces', mapping['workspace_id'])
324
+ if prior and prior != mapping:
325
+ fail('WORKER_WORKSPACE_CHANGED', 'The workspace mapping changed.')
326
+ self.store.put('worker_workspaces', mapping['workspace_id'], mapping)
327
+ for assignment in value['assignments']:
328
+ self.core._task(assignment['task_id'])
329
+ self._save_record('binding', key, value)
330
+ self.store.put('worker_binding_epochs', key, {'epoch': self._epoch()})
331
+ return {'binding_id': key, 'revision': value['revision'], 'effects_executed': True}
332
+
333
+ def _check_binding_sources(self, binding):
334
+ if binding['state'] == 'active':
335
+ for line in binding.get('overview_roles', ()):
336
+ if 'task_id' in line:
337
+ self.core._task(line['task_id'])
338
+ for ref in binding.get('read_references', ()):
339
+ source = self._source(ref)
340
+ current = self.store.get('worker_sources', ref['reference_id'])
341
+ if current['visibility'] != 'project' or source['visibility'] != 'project':
342
+ fail('WORKER_SOURCE_DENIED', 'Select a version explicitly shared with the project.')
343
+ self._bytes(source)
344
+
345
+ def _source(self, reference):
346
+ if set(reference) != {'reference_id', 'revision', 'content_sha256'}:
347
+ fail('WORKER_REFERENCE_INVALID', 'Use the exact versioned source reference.')
348
+ key = _id(reference['reference_id'], 'Reference')
349
+ current = self.store.get('worker_sources', key)
350
+ if not current or current['state'] != 'active':
351
+ fail('WORKER_SOURCE_UNAVAILABLE', 'The source is unknown or revoked.')
352
+ selected = reference in self.binding.get('read_references', ())
353
+ if self.binding['role'] != 'governor' and current['owner_binding_id'] != self.actor and not (
354
+ current['visibility'] == 'project' and (self.binding['read_project_shared'] or selected)):
355
+ fail('WORKER_SOURCE_DENIED', 'The current source policy does not grant this member access.')
356
+ version = self.store.get('worker_versions', 'source:' + key + ':' + str(reference['revision']))
357
+ if not version or version.get('state') != 'active' or version['content_sha256'] != reference['content_sha256']:
358
+ fail('WORKER_SOURCE_VERSION', 'The requested source revision/hash is not registered.')
359
+ if (version['visibility'] != 'project' and self.binding['role'] != 'governor'
360
+ and (selected or current['owner_binding_id'] != self.actor)):
361
+ fail('WORKER_SOURCE_DENIED', 'Only the approved shared version is available.')
362
+ return version
363
+
364
+ def _bytes(self, source):
365
+ obj = self.store.directory / 'objects' / source['content_sha256']
366
+ if _linked(obj.parent) or not obj.is_file():
367
+ fail('WORKER_PAYLOAD_MISSING', 'The registered payload is unavailable; no replacement was inferred.')
368
+ data = read_file_bytes(obj)
369
+ if hashlib.sha256(data).hexdigest() != source['content_sha256'] or len(data) != source['size']:
370
+ fail('WORKER_PAYLOAD_CORRUPT', 'The immutable payload failed verification.')
371
+ return data
372
+
373
+ def _selected(self, root, path, commit=None):
374
+ selected = validate_relative_path(root, path, allow_missing=bool(commit))
375
+ if commit:
376
+ import re
377
+ if not re.fullmatch(r'(?:[0-9a-f]{40}|[0-9a-f]{64})', commit):
378
+ fail('WORKER_GIT_IDENTITY', 'Use a complete Git commit identity.')
379
+ if git(root, 'cat-file', '-t', commit).stdout.strip() != b'commit':
380
+ fail('WORKER_GIT_IDENTITY', 'The Git source must name a commit.')
381
+ entry = git(root, 'ls-tree', '-z', commit, '--', path).stdout.rstrip(b'\0')
382
+ if not entry:
383
+ fail('WORKER_SOURCE_UNAVAILABLE', 'The selected path is absent from this commit.')
384
+ meta, actual = entry.split(b'\t', 1)
385
+ mode, kind, oid = meta.decode().split()
386
+ if actual.decode('utf-8') != path or kind != 'blob' or mode not in {'100644', '100755'}:
387
+ fail('WORKER_SOURCE_TYPE', 'Git sources must be exact ordinary files.')
388
+ if int(git(root, 'cat-file', '-s', oid).stdout) > 32 * 1024 * 1024:
389
+ fail('FILE_TOO_LARGE', 'The selected file exceeds the source limit.')
390
+ return git(root, 'cat-file', 'blob', oid).stdout
391
+ data = read_file_bytes(selected)
392
+ # Revalidate the complete path after opening too. This does not claim an
393
+ # OS sandbox against another process with the same filesystem authority.
394
+ validate_relative_path(root, path, allow_missing=False)
395
+ return data
396
+
397
+ def source_share(self, mode, plan_id=None, reference_id=None, task_id=None, workspace_id=None,
398
+ path=None, visibility='self', expected_revision=None, media_type='text/markdown', git_commit=None,
399
+ revoke=False, display_title=None):
400
+ if mode == 'execute':
401
+ return self._execute('source_share', plan_id)
402
+ prior = self.store.get('worker_sources', _id(reference_id, 'Reference'))
403
+ if mode == 'get':
404
+ if not prior:
405
+ fail('WORKER_SOURCE_UNAVAILABLE', 'Unknown source.')
406
+ return self._source({k: prior[k] for k in ('reference_id', 'revision', 'content_sha256')})
407
+ if prior and prior['owner_binding_id'] != self.actor and self.binding['role'] != 'governor':
408
+ fail('WORKER_SOURCE_DENIED', 'Only the owner or governor may revise this source.')
409
+ if visibility == 'project' and not self.binding['share_project'] and self.binding['role'] != 'governor':
410
+ fail('WORKER_SHARE_DENIED', 'This binding has not been granted project sharing.')
411
+ if revoke:
412
+ if not prior:
413
+ fail('WORKER_SOURCE_UNAVAILABLE', 'Unknown source.')
414
+ value = {**prior, 'revision': prior['revision'] + 1, 'state': 'revoked'}
415
+ value, _ = self._record('source', value, expected_revision)
416
+ return self._plan('source_share', {'record': value, 'revoke': True}, {'expected': expected_revision})
417
+ root, _ = self._assignment(task_id, workspace_id, 'handback')
418
+ data = self._selected(root, path, git_commit)
419
+ if media_type not in MEDIA:
420
+ fail('WORKER_SOURCE_TYPE', 'Unsupported content type.')
421
+ value = {'contract_version': 1, 'project_id': self.project_id, 'revision': (prior['revision'] if prior else 0) + 1,
422
+ 'reference_id': reference_id, 'owner_binding_id': prior['owner_binding_id'] if prior else self.actor,
423
+ 'task_id': task_id, 'visibility': visibility, 'state': 'active',
424
+ 'content_sha256': hashlib.sha256(data).hexdigest(), 'size': len(data), 'media_type': media_type,
425
+ 'origin': {'kind': 'git', 'commit': git_commit, 'path': path} if git_commit else
426
+ {'kind': 'artifact', 'artifact_id': reference_id, 'artifact_revision': (prior['revision'] if prior else 0) + 1}}
427
+ if display_title is None and prior and prior['visibility'] == visibility and prior['task_id'] == task_id:
428
+ display_title = prior.get('display_title')
429
+ if display_title is not None:
430
+ value['display_title'] = display_title
431
+ value, _ = self._record('source', value, expected_revision)
432
+ return self._plan('source_share', {'record': value, 'workspace_id': workspace_id, 'path': path},
433
+ {'expected': expected_revision, 'task': self._task_hash(task_id)})
434
+
435
+ def _apply_source_share(self, payload, guards):
436
+ value, key = self._record('source', payload['record'], guards['expected'])
437
+ if not payload.get('revoke'):
438
+ root, _ = self._assignment(value['task_id'], payload['workspace_id'], 'handback')
439
+ if self._task_hash(value['task_id']) != guards['task']:
440
+ fail('WORKER_TASK_CHANGED', 'The task changed since this publication was planned.')
441
+ data = self._selected(root, payload['path'], value['origin'].get('commit'))
442
+ if hashlib.sha256(data).hexdigest() != value['content_sha256'] or len(data) != value['size']:
443
+ fail('WORKER_SOURCE_CHANGED', 'The selected content changed; prepare a fresh plan.')
444
+ self.core._snapshot(data)
445
+ self._save_record('source', key, value)
446
+ return {'reference': {k: value[k] for k in ('reference_id', 'revision', 'content_sha256')},
447
+ 'state': value['state'], 'visibility': value['visibility'], 'effects_executed': True,
448
+ 'published': value['state'] == 'active', 'acquired': False, 'read': False}
449
+
450
+ def source_read(self, reference, cursor=None, max_bytes=4096):
451
+ source = self._source(reference)
452
+ data = self._bytes(source)
453
+ is_text = source['media_type'].startswith('text/') or source['media_type'] in {'application/json', 'image/svg+xml'}
454
+ result = {'reference': reference, 'size': len(data), 'media_type': source['media_type'],
455
+ 'read_only': True, 'effects_executed': False, 'read_acknowledged': False}
456
+ if not is_text:
457
+ return {**result, 'binary': True, 'next_step': 'Use source_acquire for a local file and view it with your AI tool.'}
458
+ try:
459
+ data.decode('utf-8')
460
+ except UnicodeDecodeError:
461
+ fail('WORKER_SOURCE_ENCODING', 'This source is not UTF-8; acquire the binary file instead.')
462
+ selection = fingerprint({'actor': self.actor, 'reference': reference})
463
+ start = self._cursor(cursor, selection, selection) if cursor else 0
464
+ if type(start) is not int or not 0 <= start <= len(data):
465
+ fail('WORKER_CURSOR_INVALID', 'Use the exact returned cursor.')
466
+ end = min(len(data), start + max_bytes)
467
+ while end > start:
468
+ try:
469
+ text = data[start:end].decode('utf-8')
470
+ break
471
+ except UnicodeDecodeError as exc:
472
+ if exc.start == 0 and start and data[start] & 0xC0 == 0x80:
473
+ fail('WORKER_CURSOR_INVALID', 'The cursor must be at a UTF-8 boundary.')
474
+ end -= 1
475
+ else:
476
+ text = ''
477
+ result.update(text=text, offset=start, end=end, complete=end == len(data),
478
+ next_cursor=self._encode(selection, selection, end) if end < len(data) else None)
479
+ # Quotes/newlines expand in JSON and again in MCP. Keep all returned text
480
+ # within the wire budget; pagination must never silently drop a byte.
481
+ while (len(packed(result)) > MAX_RESULT_BYTES - 512 or wire_size(result) > 16000) and end > start:
482
+ end -= 1
483
+ while end > start and data[end] & 0xC0 == 0x80:
484
+ end -= 1
485
+ result.update(text=data[start:end].decode('utf-8'), end=end, complete=False,
486
+ next_cursor=self._encode(selection, selection, end))
487
+ return result
488
+
489
+ @staticmethod
490
+ def _encode(selection, version, after):
491
+ return base64.urlsafe_b64encode(packed({'s': selection, 'v': version, 'a': after})).decode().rstrip('=')
492
+
493
+ @staticmethod
494
+ def _cursor(cursor, selection, version):
495
+ try:
496
+ if len(cursor) > 2048:
497
+ raise ValueError()
498
+ value = json.loads(base64.b64decode(cursor + '=' * (-len(cursor) % 4), altchars=b'-_', validate=True))
499
+ if set(value) != {'s', 'v', 'a'} or value['s'] != selection:
500
+ raise ValueError()
501
+ except (ValueError, TypeError, UnicodeError):
502
+ fail('WORKER_CURSOR_INVALID', 'Use an unchanged cursor for this selection and binding.')
503
+ if value['v'] != version:
504
+ fail('WORKER_CURSOR_STALE', 'The directory changed; start a fresh page.')
505
+ return value['a']
506
+
507
+ def source_acquire(self, mode, plan_id=None, reference=None, task_id=None, workspace_id=None, path=None):
508
+ if mode == 'execute':
509
+ return self._execute('source_acquire', plan_id)
510
+ if mode != 'plan':
511
+ fail('INVALID_ARGUMENT', 'Acquire supports plan and execute.')
512
+ source = self._source(reference)
513
+ root, _ = self._assignment(task_id, workspace_id, 'handback')
514
+ target = validate_relative_path(root, path)
515
+ if not target.parent.is_dir():
516
+ fail('WORKER_DESTINATION_MISSING', 'Create the destination directory in your own workspace first.')
517
+ if target.exists() and hashlib.sha256(read_file_bytes(target)).hexdigest() != source['content_sha256']:
518
+ fail('WORKER_DESTINATION_CONFLICT', 'The destination already contains different user content.')
519
+ return self._plan('source_acquire', {'reference': reference, 'task_id': task_id,
520
+ 'workspace_id': workspace_id, 'path': path}, {'task': self._task_hash(task_id)})
521
+
522
+ def _apply_source_acquire(self, payload, guards):
523
+ source = self._source(payload['reference'])
524
+ root, _ = self._assignment(payload['task_id'], payload['workspace_id'], 'handback')
525
+ if self._task_hash(payload['task_id']) != guards['task']:
526
+ fail('WORKER_TASK_CHANGED', 'The task changed since acquisition was planned.')
527
+ target = validate_relative_path(root, payload['path'])
528
+ data = self._bytes(source)
529
+ reused = target.exists()
530
+ if reused:
531
+ if read_file_bytes(target) != data:
532
+ fail('WORKER_DESTINATION_CONFLICT', 'The destination changed; no file was overwritten.')
533
+ else:
534
+ # Exclusive creation: a failed receipt can retry by verifying exactly
535
+ # matching bytes. Different or incomplete content is never replaced.
536
+ with target.open('xb') as stream:
537
+ stream.write(data)
538
+ stream.flush()
539
+ import os
540
+ os.fsync(stream.fileno())
541
+ if read_file_bytes(target) != data:
542
+ fail('WORKER_DESTINATION_CHANGED', 'The destination changed before verification.')
543
+ return {'reference': payload['reference'], 'workspace_id': payload['workspace_id'], 'path': payload['path'],
544
+ 'acquired': True, 'read': False, 'file_reused': reused, 'effects_executed': True}
545
+
546
+ def worker_brief(self, section='overview', limit=5, cursor=None, task_id=None,
547
+ pending_only=False, previous_fingerprint=None):
548
+ version = index.revision(self.store)
549
+ from . import experience_storage
550
+ experience_version = experience_storage.version(self.store) if section in {'overview', 'tasks'} else None
551
+ shared = self.binding['role'] == 'governor' or self.binding['read_project_shared']
552
+ assignments = self.binding['assignments']
553
+ assigned_tasks = [a['task_id'] for a in assignments]
554
+ if task_id:
555
+ self.core._task(task_id)
556
+ if not shared and task_id not in assigned_tasks:
557
+ fail('WORKER_SCOPE_DENIED', 'The task is not visible to this member.')
558
+ selection = fingerprint({'actor': self.actor, 'section': section, 'task_id': task_id,
559
+ 'pending': pending_only})
560
+ sharing = None
561
+ if section == 'role' and self.caller is not None and shared and self.binding['role'] in ('worker', 'governor'):
562
+ from .project_collaboration import sharing_state
563
+ sharing = sharing_state(self.store, self._epoch(), self.actor)
564
+ stamp = fingerprint({'project': self.project_id, 'revision': version,
565
+ 'binding': self.binding['revision'], 'selection': selection,
566
+ 'experience_revision': experience_version, **({'conversation_sharing': sharing} if sharing else {})})
567
+ after = self._cursor(cursor, selection, stamp) if cursor else ''
568
+ if not isinstance(after, str):
569
+ fail('WORKER_CURSOR_INVALID', 'This directory uses an identity cursor.')
570
+ result = {'project_id': self.project_id, 'binding_id': self.actor,
571
+ 'binding_revision': self.binding['revision'], 'effective_role': self.binding['role'],
572
+ 'section': section, 'fingerprint': stamp, 'changed': previous_fingerprint != stamp,
573
+ 'read_only': True, 'effects_executed': False, 'read_acknowledged': False,
574
+ 'storage': 'worker_index_v1', 'project_complete': None}
575
+ if section == 'project_map':
576
+ roles = self.binding.get('overview_roles')
577
+ if not roles:
578
+ fail('WORKER_SCOPE_DENIED', 'This binding has no project overview grant.')
579
+ # Only governor-approved labels and current task states cross the boundary.
580
+ # Other paths, task notes, checkpoints and linked project history are separate grants.
581
+ rows = []
582
+ for line in roles:
583
+ entry = {'role': line['role'], 'responsibility': line['responsibility']}
584
+ if 'task_id' in line:
585
+ entry['state'] = self.core._task(line['task_id'])['state']
586
+ entry['source'] = 'project_task'
587
+ else:
588
+ entry.update(state=None, source='separate_project')
589
+ rows.append((line['role'], entry))
590
+ rows.sort(key=lambda item: item[0])
591
+ total = len(rows)
592
+ rows = [(key, entry) for key, entry in rows if key > after][:limit + 1]
593
+ result['project_name'] = self.store.get('config', 'project')['name']
594
+ elif section == 'overview':
595
+ config = self.store.get('config', 'project')
596
+ return {**result, 'project_name': config['name'], 'assignment_count': len(assignments),
597
+ 'experience': experience_storage.pointer(self, task_id),
598
+ 'directory_sections': ['tasks', 'role', 'sources', 'handbacks', 'dispositions', 'read_reports'],
599
+ 'project_reading': ['project_overview', 'project_history', 'discussion', 'turn_read'],
600
+ 'role_card': assignments[:3], 'more_assignments': len(assignments) > 3,
601
+ 'visibility': 'project directory and explicitly shared content' if shared else 'assigned tasks and own content',
602
+ 'coverage': 'Directory only. Read section pages and exact sources; no implied complete history or external project access.'}
603
+ elif section == 'role':
604
+ if sharing is not None:
605
+ result['conversation_sharing'] = sharing
606
+ if 'read_references' in self.binding:
607
+ refs = sorted(self.binding['read_references'], key=lambda item: (item['reference_id'], item['revision']))
608
+ result['source_scope'] = {'mode': 'selected_versions', 'references_fingerprint': fingerprint(refs),
609
+ 'share_project': self.binding['share_project']}
610
+ rows = sorted([(a['task_id'] + ':' + a['workspace_id'], a) for a in assignments])
611
+ total = len(rows)
612
+ rows = [(k, v) for k, v in rows if k > after][:limit + 1]
613
+ else:
614
+ collection = {'tasks': 'tasks', 'sources': 'worker_sources', 'handbacks': 'worker_handbacks',
615
+ 'dispositions': 'worker_dispositions', 'read_reports': 'worker_reads'}[section]
616
+ where, params = '1', []
617
+ projection = 'value'
618
+ if section == 'tasks':
619
+ projection = "json_object('task_id',key,'title',substr(json_extract(value,'$.title'),1,180),'state',json_extract(value,'$.state'),'workstream',json_extract(value,'$.workstream'),'latest_checkpoint',json_extract(value,'$.latest_checkpoint'),'next_step',substr(json_extract(value,'$.next_step'),1,300))"
620
+ if not shared:
621
+ where += ' AND key IN (' + ','.join('?' for _ in assigned_tasks) + ')'
622
+ params.extend(assigned_tasks)
623
+ elif section == 'sources':
624
+ where += " AND json_extract(value,'$.state')='active'"
625
+ if self.binding['role'] != 'governor':
626
+ where += " AND (json_extract(value,'$.owner_binding_id')=?"
627
+ params.append(self.actor)
628
+ if shared:
629
+ where += " OR json_extract(value,'$.visibility')='project'"
630
+ where += ')'
631
+ elif section in {'handbacks', 'read_reports'}:
632
+ if not shared:
633
+ where += " AND json_extract(value,'$.binding_id')=?"
634
+ params.append(self.actor)
635
+ if section == 'handbacks' and pending_only:
636
+ where += " AND json_extract(value,'$.state')='submitted' AND NOT EXISTS (SELECT 1 FROM records d WHERE d.collection='worker_dispositions' AND json_extract(d.value,'$.handback_id')=r.key AND json_extract(d.value,'$.handback_revision')=json_extract(r.value,'$.revision') AND json_extract(d.value,'$.verdict') IN ('received','technically_received'))"
637
+ elif section == 'dispositions' and not shared:
638
+ where += " AND EXISTS(SELECT 1 FROM records h WHERE h.collection='worker_handbacks' AND h.key=json_extract(r.value,'$.handback_id') AND json_extract(h.value,'$.binding_id')=?)"
639
+ params.append(self.actor)
640
+ if task_id:
641
+ if section in {'tasks', 'sources', 'handbacks'}:
642
+ where += " AND json_extract(value,'$.task_id')=?"
643
+ params.append(task_id)
644
+ elif section == 'dispositions':
645
+ where += " AND EXISTS(SELECT 1 FROM records h WHERE h.collection='worker_handbacks' AND h.key=json_extract(r.value,'$.handback_id') AND json_extract(h.value,'$.task_id')=?)"
646
+ params.append(task_id)
647
+ else:
648
+ where += " AND EXISTS(SELECT 1 FROM records s WHERE s.collection='worker_sources' AND s.key=json_extract(r.value,'$.reference.reference_id') AND json_extract(s.value,'$.task_id')=?)"
649
+ params.append(task_id)
650
+ total, rows = index.select(self.store, collection, where, params, after, limit, projection)
651
+ items, last = [], after
652
+ result.update(items=items, total=total, returned=0, next_cursor=None, has_more=False)
653
+ for key, value in rows[:limit]:
654
+ if section == 'tasks':
655
+ value['task_fingerprint'] = self._task_hash(value['task_id'])
656
+ value['detail_scope'] = 'compact directory; use shared sources for full original content'
657
+ value['experience'] = experience_storage.pointer(self, value['task_id'])
658
+ # Large record summaries remain retrievable via exact get / source;
659
+ # directory entries are intentionally compact and explicitly labeled.
660
+ if len(packed(value)) > 3500:
661
+ value = {k: v for k, v in value.items() if k not in {'sources', 'summary', 'next_step', 'evidence_refs'}}
662
+ value['details_omitted'] = True
663
+ candidate = {**result, 'items': items + [value]}
664
+ if len(packed(candidate)) > MAX_RESULT_BYTES - 600 or wire_size(candidate) > 15500:
665
+ break
666
+ items.append(value)
667
+ last = key
668
+ more = len(rows) > len(items)
669
+ if rows and not items:
670
+ fail('WORKER_RESPONSE_TOO_LARGE', 'One directory item exceeds the response budget.')
671
+ result.update(returned=len(items), has_more=more, loaded_records=len(rows),
672
+ next_cursor=self._encode(selection, stamp, last) if more else None)
673
+ return result
674
+
675
+ def _own(self, value, field='binding_id'):
676
+ if value[field] != self.actor:
677
+ fail('WORKER_ACTOR_MISMATCH', 'A member may report only its own work and reads.')
678
+
679
+ def _sources(self, sources):
680
+ for ref in sources:
681
+ source = self._source(ref)
682
+ self._bytes(source)
683
+
684
+ def _visible_handback(self, key):
685
+ value = self.store.get('worker_handbacks', _id(key, 'Handback'))
686
+ if not value:
687
+ fail('WORKER_HANDBACK_UNKNOWN', 'Unknown handback.')
688
+ if value['binding_id'] != self.actor and not self.binding['read_project_shared'] and self.binding['role'] != 'governor':
689
+ fail('WORKER_SCOPE_DENIED', 'This handback is not visible to the member.')
690
+ return value
691
+
692
+ def worker_handback(self, mode, plan_id=None, handback_id=None, record=None, expected_revision=None):
693
+ if mode == 'execute':
694
+ return self._execute('worker_handback', plan_id)
695
+ if mode == 'get':
696
+ return self._visible_handback(handback_id)
697
+ value, key = self._record('handback', record, expected_revision)
698
+ self._own(value)
699
+ prior = self.store.get('worker_handbacks', key)
700
+ if prior and (prior['binding_id'], prior['task_id'], prior['workspace_id']) != (self.actor, value['task_id'], value['workspace_id']):
701
+ fail('WORKER_SCOPE_DENIED', 'A handback identity cannot move to another member or assignment.')
702
+ self._assignment(value['task_id'], value['workspace_id'], 'handback')
703
+ if value['basis'] != {'binding_revision': self.binding['revision'], 'task_fingerprint': self._task_hash(value['task_id'])}:
704
+ fail('WORKER_BASIS_CHANGED', 'Read the current role/task card before handing work back.')
705
+ self._sources(value['sources'])
706
+ return self._plan('worker_handback', {'record': value}, {'expected': expected_revision})
707
+
708
+ def _apply_worker_handback(self, payload, guards):
709
+ value, key = self._record('handback', payload['record'], guards['expected'])
710
+ self._own(value)
711
+ root, _ = self._assignment(value['task_id'], value['workspace_id'], 'handback')
712
+ if self._task_hash(value['task_id']) != value['basis']['task_fingerprint']:
713
+ fail('WORKER_TASK_CHANGED', 'The task changed before handback; prepare a fresh version.')
714
+ self._sources(value['sources'])
715
+ stage = None
716
+ if value['kind'] == 'code' and value['state'] == 'submitted':
717
+ from .integration import Integration
718
+ engine = Integration(self.store.root)
719
+ engine.store = self.store # One atomic record transaction and guard.
720
+ if engine._ws(value['workspace_id']) != root.resolve():
721
+ fail('WORKER_WORKSPACE_CHANGED', 'The Git workspace differs from the member mapping.')
722
+ stage = engine.submit(value['task_id'], value['workspace_id'], **value['code'],
723
+ stage_id='wh-' + fingerprint([key, value['revision']])[:40])
724
+ self._save_record('handback', key, value)
725
+ return {'handback_id': key, 'revision': value['revision'], 'state': value['state'],
726
+ 'stage_id': stage['stage']['stage_id'] if stage else None, 'effects_executed': True,
727
+ 'business_accepted': False}
728
+
729
+ def worker_disposition(self, mode, plan_id=None, disposition_id=None, record=None, expected_revision=None):
730
+ self._governor()
731
+ if mode == 'execute':
732
+ return self._execute('worker_disposition', plan_id)
733
+ if mode == 'get':
734
+ return self.store.get('worker_dispositions', _id(disposition_id, 'Disposition'))
735
+ value, key = self._record('disposition', record, expected_revision)
736
+ self._own(value, 'actor_binding_id')
737
+ handback = self._visible_handback(value['handback_id'])
738
+ if handback['revision'] != value['handback_revision']:
739
+ fail('WORKER_HANDBACK_CHANGED', 'Disposition must name the current exact handback revision.')
740
+ self._sources(value['sources'])
741
+ # One disposition identity per handback. Revisions preserve history and
742
+ # prevent conflicting parallel dispositions from silently closing work.
743
+ existing, _ = index.select(self.store, 'worker_dispositions',
744
+ "json_extract(value,'$.handback_id')=? AND key<>?", (handback['handback_id'], key))
745
+ if existing:
746
+ fail('WORKER_DISPOSITION_EXISTS', 'Revise the existing disposition instead of creating a competing decision.')
747
+ return self._plan('worker_disposition', {'record': value}, {'expected': expected_revision})
748
+
749
+ def _apply_worker_disposition(self, payload, guards):
750
+ value, key = self._record('disposition', payload['record'], guards['expected'])
751
+ handback = self._visible_handback(value['handback_id'])
752
+ if handback['revision'] != value['handback_revision']:
753
+ fail('WORKER_HANDBACK_CHANGED', 'A newer handback arrived; the old decision cannot close it.')
754
+ existing, _ = index.select(self.store, 'worker_dispositions',
755
+ "json_extract(value,'$.handback_id')=? AND key<>?", (handback['handback_id'], key))
756
+ if existing:
757
+ fail('WORKER_DISPOSITION_EXISTS', 'A disposition already exists; read and revise it.')
758
+ self._sources(value['sources'])
759
+ if value['verdict'] == 'technically_received':
760
+ if handback['kind'] != 'code':
761
+ fail('WORKER_TECHNICAL_RECEIPT_MISSING', 'Document receipt does not imply Git technical reception.')
762
+ stage_id = 'wh-' + fingerprint([handback['handback_id'], handback['revision']])[:40]
763
+ stage = self.store.get('stages', stage_id)
764
+ if not stage or stage.get('status') != 'COMMITTED':
765
+ fail('WORKER_TECHNICAL_RECEIPT_MISSING', 'The original integration engine has not committed this stage.')
766
+ self._save_record('disposition', key, value)
767
+ return {'disposition_id': key, 'revision': value['revision'], 'verdict': value['verdict'],
768
+ 'handback_id': handback['handback_id'], 'handback_revision': handback['revision'],
769
+ 'business_accepted': False, 'effects_executed': True}
770
+
771
+ def worker_read(self, mode, plan_id=None, receipt_id=None, record=None, expected_revision=None):
772
+ if mode == 'execute':
773
+ return self._execute('worker_read', plan_id)
774
+ if mode == 'get':
775
+ value = self.store.get('worker_reads', _id(receipt_id, 'Receipt'))
776
+ if value and value['binding_id'] != self.actor and self.binding['role'] != 'governor':
777
+ fail('WORKER_SCOPE_DENIED', 'Only the author or governor can inspect this receipt directly.')
778
+ return value
779
+ value, key = self._record('read_receipt', record, expected_revision)
780
+ self._own(value)
781
+ prior = self.store.get('worker_reads', key)
782
+ if prior and prior['binding_id'] != self.actor:
783
+ fail('WORKER_SCOPE_DENIED', 'Another member owns this receipt.')
784
+ source = self._source(value['reference'])
785
+ if self.binding['role'] != 'governor' and not any('read_receipt' in a['write_actions'] for a in self.binding['assignments']):
786
+ fail('WORKER_SCOPE_DENIED', 'This member cannot record read reports.')
787
+ self._bytes(source)
788
+ return self._plan('worker_read', {'record': value}, {'expected': expected_revision})
789
+
790
+ def _apply_worker_read(self, payload, guards):
791
+ value, key = self._record('read_receipt', payload['record'], guards['expected'])
792
+ self._sources([value['reference']])
793
+ self._save_record('read_receipt', key, value)
794
+ return {'receipt_id': key, 'revision': value['revision'], 'phase': value['phase'],
795
+ 'evidence_scope': 'member report; not proof of comprehension or business acceptance', 'effects_executed': True}
796
+
797
+ def worker_report(self, mode, plan_id=None, report_id=None, task_id=None, workspace_id=None,
798
+ kind=None, summary=None, next_step=None, state=None, paths=None):
799
+ if mode == 'execute':
800
+ return self._execute('worker_report', plan_id)
801
+ if mode == 'get':
802
+ value = self.store.get('worker_reports', _id(report_id, 'Report'))
803
+ if value and value['binding_id'] != self.actor and self.binding['role'] != 'governor':
804
+ fail('WORKER_SCOPE_DENIED', 'Another member owns this report.')
805
+ return value
806
+ _id(report_id, 'Report')
807
+ if kind not in {'progress', 'checkpoint'} or not summary or not next_step:
808
+ fail('INVALID_ARGUMENT', 'A report needs kind, summary and next_step.')
809
+ root, _ = self._assignment(task_id, workspace_id, kind)
810
+ if self.store.get('worker_reports', report_id):
811
+ fail('WORKER_REPORT_EXISTS', 'Use the existing report/plan or a new report identity for new progress.')
812
+ selected = []
813
+ if kind == 'checkpoint':
814
+ if not paths:
815
+ fail('INVALID_ARGUMENT', 'Select exact checkpoint files.')
816
+ for path in paths:
817
+ target = validate_relative_path(root, path)
818
+ selected.append({'path': path, 'sha256': hashlib.sha256(read_file_bytes(target)).hexdigest() if target.exists() else None})
819
+ payload = {'report_id': report_id, 'binding_id': self.actor, 'task_id': task_id,
820
+ 'workspace_id': workspace_id, 'kind': kind, 'summary': summary, 'next_step': next_step,
821
+ 'state': state, 'files': selected}
822
+ if len(packed(payload)) > 4096:
823
+ fail('WORKER_RECORD_TOO_LARGE', 'Keep report metadata compact; share the full body separately.')
824
+ return self._plan('worker_report', payload, {'task': self._task_hash(task_id),
825
+ 'git_layers': self._git_layers(root, paths) if kind == 'checkpoint' else None})
826
+
827
+ @staticmethod
828
+ def _git_layers(root, paths):
829
+ if not _checkpoint_uses_git(root):
830
+ return None
831
+ return {'head': git(root, 'rev-parse', '--verify', 'HEAD', check=False).stdout.decode().strip(),
832
+ 'selected_index_sha256': hashlib.sha256(git(root, 'ls-files', '--stage', '-z', '--', *paths).stdout).hexdigest()}
833
+
834
+ def _apply_worker_report(self, payload, guards):
835
+ root, task = self._assignment(payload['task_id'], payload['workspace_id'], payload['kind'])
836
+ if self._task_hash(task['task_id']) != guards['task'] or self.store.get('worker_reports', payload['report_id']):
837
+ fail('WORKER_TASK_CHANGED', 'The task/report changed since planning.')
838
+ checkpoint_id = None
839
+ if payload['kind'] == 'checkpoint':
840
+ if self._git_layers(root, [f['path'] for f in payload['files']]) != guards['git_layers']:
841
+ fail('WORKER_SOURCE_CHANGED', 'Selected Git layers changed since checkpoint planning.')
842
+ for item in payload['files']:
843
+ path = validate_relative_path(root, item['path'])
844
+ current = hashlib.sha256(read_file_bytes(path)).hexdigest() if path.exists() else None
845
+ if current != item['sha256']:
846
+ fail('WORKER_SOURCE_CHANGED', 'A checkpoint source changed since planning.')
847
+ checkpoint = self.core.checkpoint(task['task_id'], str(root), [f['path'] for f in payload['files']],
848
+ payload['next_step'], decision=payload['summary'], paused=payload['state'] == 'paused')
849
+ checkpoint_id = checkpoint['checkpoint_id']
850
+ else:
851
+ task.update(next_step=payload['next_step'], updated_at=now())
852
+ if payload['state']:
853
+ task['state'] = payload['state']
854
+ self.store.put('tasks', task['task_id'], task)
855
+ record = {**payload, 'checkpoint_id': checkpoint_id, 'created_at': now()}
856
+ self.store.put('worker_reports', payload['report_id'], record)
857
+ self.store.event('worker_progress', {'report_id': payload['report_id'], 'actor': self.actor, 'task_id': task['task_id']})
858
+ return {'report_id': payload['report_id'], 'checkpoint_id': checkpoint_id,
859
+ 'effects_executed': True, 'delivery': False}