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.
- taskcarry/__init__.py +3 -0
- taskcarry/__main__.py +4 -0
- taskcarry/adapter_contracts.py +166 -0
- taskcarry/agy_turns.py +282 -0
- taskcarry/api.py +111 -0
- taskcarry/board.py +313 -0
- taskcarry/board_assets/board.css +1087 -0
- taskcarry/board_assets/board.js +1187 -0
- taskcarry/board_assets/browse.js +214 -0
- taskcarry/board_assets/index.html +43 -0
- taskcarry/board_assets/taskcarry-icon.ico +0 -0
- taskcarry/board_assets/taskcarry-mark.svg +28 -0
- taskcarry/board_data.py +466 -0
- taskcarry/chat_joins.py +157 -0
- taskcarry/cli.py +119 -0
- taskcarry/codex_capture.py +184 -0
- taskcarry/codex_host.py +293 -0
- taskcarry/collaboration_exchange.py +316 -0
- taskcarry/connection.py +159 -0
- taskcarry/continuity.py +300 -0
- taskcarry/contracts.py +165 -0
- taskcarry/conversation_capture.py +669 -0
- taskcarry/core.py +896 -0
- taskcarry/cycle_contracts.py +73 -0
- taskcarry/discovery.py +434 -0
- taskcarry/discovery_contracts.py +52 -0
- taskcarry/exchange_contracts.py +67 -0
- taskcarry/exchange_endpoint.py +377 -0
- taskcarry/exchange_packets.py +142 -0
- taskcarry/experience_contracts.py +129 -0
- taskcarry/experience_exchange.py +214 -0
- taskcarry/experience_notes.py +433 -0
- taskcarry/experience_storage.py +125 -0
- taskcarry/experience_tools.py +26 -0
- taskcarry/feishu/__init__.py +1 -0
- taskcarry/feishu/display.py +122 -0
- taskcarry/feishu/project_watch.py +145 -0
- taskcarry/feishu/review_sets.py +80 -0
- taskcarry/feishu/sender.py +42 -0
- taskcarry/feishu/subscription.py +193 -0
- taskcarry/feishu/windows_agent.py +287 -0
- taskcarry/feishu/windows_secret.py +34 -0
- taskcarry/gitops.py +170 -0
- taskcarry/governance.py +88 -0
- taskcarry/governance_cycle.py +775 -0
- taskcarry/identification.py +82 -0
- taskcarry/integration.py +663 -0
- taskcarry/maintenance.py +118 -0
- taskcarry/mcp.py +183 -0
- taskcarry/member_join.py +184 -0
- taskcarry/member_routing.py +145 -0
- taskcarry/onboarding.py +272 -0
- taskcarry/onboarding_complete.py +252 -0
- taskcarry/path_batches.py +19 -0
- taskcarry/preservation.py +257 -0
- taskcarry/project_collaboration.py +453 -0
- taskcarry/project_history.py +166 -0
- taskcarry/project_identity.py +51 -0
- taskcarry/project_recovery.py +824 -0
- taskcarry/recovery_contracts.py +25 -0
- taskcarry/recovery_files.py +153 -0
- taskcarry/recovery_git.py +234 -0
- taskcarry/remote_capture.py +89 -0
- taskcarry/remote_transfer.py +356 -0
- taskcarry/role_connection.py +215 -0
- taskcarry/setup.py +597 -0
- taskcarry/shared_workbench.py +480 -0
- taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
- taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
- taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
- taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
- taskcarry/source_review_set.py +80 -0
- taskcarry/state_format.py +47 -0
- taskcarry/store.py +472 -0
- taskcarry/task_context.py +141 -0
- taskcarry/text_handback.py +98 -0
- taskcarry/transfer_contracts.py +18 -0
- taskcarry/updates.py +351 -0
- taskcarry/workbench.py +625 -0
- taskcarry/workbench_contracts.py +32 -0
- taskcarry/workbuddy_capture.py +451 -0
- taskcarry/workbuddy_setup.py +212 -0
- taskcarry/worker_channel.py +859 -0
- taskcarry/worker_contracts.py +190 -0
- taskcarry/worker_storage.py +60 -0
- taskcarry/worker_tools.py +111 -0
- taskcarry-0.3.2.dist-info/METADATA +203 -0
- taskcarry-0.3.2.dist-info/RECORD +105 -0
- taskcarry-0.3.2.dist-info/WHEEL +5 -0
- taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
- taskcarry-0.3.2.dist-info/top_level.txt +2 -0
- taskcarry_https/__init__.py +1 -0
- taskcarry_https/consent.py +207 -0
- taskcarry_https/reader.py +132 -0
- taskcarry_https/review.py +116 -0
- taskcarry_https/server.py +163 -0
- taskcarry_https/team.py +335 -0
- taskcarry_https/team_host.py +109 -0
- taskcarry_https/web_host.py +82 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
"""Governor-mediated Git exchange using the same versioned worker records."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
|
|
6
|
+
from .core import _id, read_file_bytes, validate_relative_path
|
|
7
|
+
from .exchange_packets import build, inspect, sha, require, git_source, read_git, MAX_PACKET
|
|
8
|
+
from .setup import atomic_write
|
|
9
|
+
from .store import now, GovernanceError
|
|
10
|
+
from .worker_channel import Caller, WorkerChannel, fingerprint
|
|
11
|
+
from .worker_contracts import COLLECTIONS, validate_record
|
|
12
|
+
from . import worker_storage as index
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class CollaborationExchange:
|
|
16
|
+
def __init__(self, channel):
|
|
17
|
+
self.channel = channel
|
|
18
|
+
self.store = channel.store
|
|
19
|
+
|
|
20
|
+
def member(self, binding_id):
|
|
21
|
+
member = WorkerChannel(self.channel.core.root, Caller(binding_id, 'worker', self.channel.project_id))
|
|
22
|
+
member.core.store = member.store = self.store
|
|
23
|
+
member._auth('worker_brief')
|
|
24
|
+
require(member.binding['role'] == 'worker', 'Exchange invites require an active worker binding.')
|
|
25
|
+
return member
|
|
26
|
+
|
|
27
|
+
def invitation(self, key):
|
|
28
|
+
value = self.store.get('worker_exchange_invitations', _id(key, 'Invitation'))
|
|
29
|
+
require(value and value['state'] == 'active', 'Invitation is absent or revoked.', 'EXCHANGE_INVITATION_INACTIVE')
|
|
30
|
+
require(value['epoch'] == self.channel._epoch(), 'Restored invitations require local re-approval.', 'EXCHANGE_REBIND_REQUIRED')
|
|
31
|
+
self.member(value['binding_id'])
|
|
32
|
+
return value
|
|
33
|
+
|
|
34
|
+
def invoke(self, mode, operation=None, plan_id=None, invitation_id=None, binding_id=None,
|
|
35
|
+
expected_revision=None, repository=None, remote=None, input_ref=None,
|
|
36
|
+
packet_path=None, output_path=None, references=None, commit=None, revoke=False,
|
|
37
|
+
experience_references=None):
|
|
38
|
+
self.channel._governor()
|
|
39
|
+
if mode == 'execute':
|
|
40
|
+
return self.channel._execute('worker_exchange', plan_id)
|
|
41
|
+
if mode == 'get':
|
|
42
|
+
if plan_id:
|
|
43
|
+
return self.export_status(plan_id)
|
|
44
|
+
value = self.invitation(invitation_id)
|
|
45
|
+
return {k: v for k, v in value.items() if k not in {'source', 'epoch'}}
|
|
46
|
+
if operation == 'invite':
|
|
47
|
+
key = _id(invitation_id, 'Invitation')
|
|
48
|
+
previous = self.store.get('worker_exchange_invitations', key)
|
|
49
|
+
require(type(expected_revision) is int and expected_revision == (previous['revision'] if previous else 0),
|
|
50
|
+
'Read the invitation revision before updating it.', 'EXCHANGE_REVISION_CONFLICT')
|
|
51
|
+
if revoke:
|
|
52
|
+
require(previous is not None, 'Cannot revoke an unknown invitation.')
|
|
53
|
+
value = {**previous, 'revision': previous['revision'] + 1, 'state': 'revoked'}
|
|
54
|
+
else:
|
|
55
|
+
member = self.member(binding_id)
|
|
56
|
+
source = git_source(repository, remote, input_ref, packet_path)
|
|
57
|
+
value = {'invitation_id': key, 'revision': expected_revision + 1, 'state': 'active',
|
|
58
|
+
'project_id': self.channel.project_id, 'binding_id': member.actor,
|
|
59
|
+
'source': source, 'epoch': self.channel._epoch()}
|
|
60
|
+
return self.channel._plan('worker_exchange', {'operation': operation, 'invitation': value},
|
|
61
|
+
{'expected': expected_revision})
|
|
62
|
+
invitation = self.invitation(invitation_id)
|
|
63
|
+
member = self.member(invitation['binding_id'])
|
|
64
|
+
guards = {'invitation': fingerprint(invitation), 'member_revision': member.binding['revision']}
|
|
65
|
+
if operation == 'export':
|
|
66
|
+
require(isinstance(references, list) and 1 <= len(references) <= 64,
|
|
67
|
+
'Select the exact shared sources for this view.')
|
|
68
|
+
require(len({r['reference_id'] for r in references}) == len(references), 'Duplicate selected sources.')
|
|
69
|
+
objects, sources = {}, []
|
|
70
|
+
for reference in references:
|
|
71
|
+
record = member._source(reference)
|
|
72
|
+
objects[record['content_sha256']] = member._bytes(record)
|
|
73
|
+
sources.append(record)
|
|
74
|
+
sections = {}
|
|
75
|
+
for section in ('tasks', 'role', 'handbacks', 'dispositions'):
|
|
76
|
+
items, cursor = [], None
|
|
77
|
+
while True:
|
|
78
|
+
page = member.worker_brief(section=section, limit=20, cursor=cursor)
|
|
79
|
+
items.extend(page['items'])
|
|
80
|
+
require(len(items) <= 256, 'Export a smaller project directory.')
|
|
81
|
+
cursor = page['next_cursor']
|
|
82
|
+
if not cursor:
|
|
83
|
+
break
|
|
84
|
+
sections[section] = items
|
|
85
|
+
body = {'kind': 'view', 'project_id': member.project_id, 'binding_id': member.actor,
|
|
86
|
+
'invitation_id': invitation_id, 'invitation_revision': invitation['revision'],
|
|
87
|
+
'binding': member.binding, 'overview': member.worker_brief(), 'sections': sections,
|
|
88
|
+
'sources': sources, 'created_at': now(), 'coverage': 'Selected shared sources and compact directory; last-known off-line view.'}
|
|
89
|
+
if experience_references is not None:
|
|
90
|
+
from .experience_exchange import export_selected
|
|
91
|
+
body['experience'] = export_selected(member, experience_references, sources, objects)
|
|
92
|
+
from .experience_storage import version
|
|
93
|
+
guards['experience_revision'] = version(self.store)
|
|
94
|
+
body['view_id'] = fingerprint(body)
|
|
95
|
+
data = build(body, objects)
|
|
96
|
+
destination = validate_relative_path(Path(invitation['source']['repository']), output_path)
|
|
97
|
+
require(destination.parent.is_dir(), 'Create the chosen output parent before planning.')
|
|
98
|
+
before = sha(read_file_bytes(destination, max_bytes=MAX_PACKET)) if destination.exists() else None
|
|
99
|
+
packet = self.channel.core._snapshot(data)
|
|
100
|
+
packet_hash = packet['sha256']
|
|
101
|
+
require(packet_hash == sha(data), 'Packet snapshot mismatch.')
|
|
102
|
+
return self.channel._plan('worker_exchange', {'operation': operation, 'invitation_id': invitation_id,
|
|
103
|
+
'view_id': body['view_id'], 'packet_sha256': packet_hash, 'packet': packet,
|
|
104
|
+
'output_repository': invitation['source']['repository'], 'output_path': output_path},
|
|
105
|
+
{**guards, 'before': before, 'index_revision': index.revision(self.store)})
|
|
106
|
+
require(operation == 'import', 'Use invite, export or import.')
|
|
107
|
+
data, origin = read_git(invitation['source'], commit)
|
|
108
|
+
body, objects = inspect(data)
|
|
109
|
+
self._check_reply(invitation, body, objects)
|
|
110
|
+
packet = self.channel.core._snapshot(data)
|
|
111
|
+
packet_hash = packet['sha256']
|
|
112
|
+
return self.channel._plan('worker_exchange', {'operation': operation, 'invitation_id': invitation_id,
|
|
113
|
+
'packet_sha256': packet_hash, 'packet': packet, 'origin': origin}, guards)
|
|
114
|
+
|
|
115
|
+
def export_status(self, plan_id):
|
|
116
|
+
"""Recover the real file/registration split using the durable frozen plan."""
|
|
117
|
+
plan = self.store.get('worker_plans', _id(plan_id, 'Plan'))
|
|
118
|
+
require(plan and plan['actor'] == self.channel.actor and plan['project_id'] == self.channel.project_id
|
|
119
|
+
and plan['action'] == 'worker_exchange' and plan['payload'].get('operation') == 'export',
|
|
120
|
+
'Read your own export plan.', 'WORKER_PLAN_DENIED')
|
|
121
|
+
payload, guards = plan['payload'], plan['guards']
|
|
122
|
+
require(payload.get('output_repository'), 'This older export plan has no fixed output location.', 'EXCHANGE_RECOVERY_PROOF_MISSING')
|
|
123
|
+
destination = validate_relative_path(Path(payload['output_repository']), payload['output_path'])
|
|
124
|
+
actual = sha(read_file_bytes(destination, max_bytes=MAX_PACKET)) if destination.exists() else None
|
|
125
|
+
registered = self.store.get('worker_exchange_views', payload['view_id'])
|
|
126
|
+
registered = bool(registered and registered['epoch'] == self.channel._epoch()
|
|
127
|
+
and registered['packet_sha256'] == payload['packet_sha256'])
|
|
128
|
+
matches = actual == payload['packet_sha256']
|
|
129
|
+
state = ('registered' if registered else 'file_only_unregistered') if matches else (
|
|
130
|
+
'not_written' if actual == guards['before'] else 'output_changed')
|
|
131
|
+
invitation = self.store.get('worker_exchange_invitations', payload['invitation_id'])
|
|
132
|
+
member = self.store.get('worker_bindings', invitation['binding_id']) if invitation else None
|
|
133
|
+
resumable = (plan['state'] == 'planned' and plan.get('epoch') == self.channel._epoch()
|
|
134
|
+
and plan['binding_revision'] == self.channel.binding['revision']
|
|
135
|
+
and fingerprint(invitation) == guards['invitation']
|
|
136
|
+
and member and member['revision'] == guards['member_revision']
|
|
137
|
+
and index.revision(self.store) == guards['index_revision']
|
|
138
|
+
and state != 'output_changed')
|
|
139
|
+
if 'experience_revision' in guards:
|
|
140
|
+
from .experience_storage import version
|
|
141
|
+
resumable = resumable and version(self.store) == guards['experience_revision']
|
|
142
|
+
authorized = False
|
|
143
|
+
if matches and registered:
|
|
144
|
+
try:
|
|
145
|
+
invitation = self.invitation(payload['invitation_id'])
|
|
146
|
+
member = self.member(invitation['binding_id'])
|
|
147
|
+
require(fingerprint(invitation) == guards['invitation']
|
|
148
|
+
and member.binding['revision'] == guards['member_revision'],
|
|
149
|
+
'The current recipient no longer matches this export.', 'EXCHANGE_SCOPE_CHANGED')
|
|
150
|
+
data = read_file_bytes(destination, max_bytes=MAX_PACKET)
|
|
151
|
+
body, _ = inspect(data, payload['packet_sha256'])
|
|
152
|
+
for source in body['sources']:
|
|
153
|
+
member._source({k: source[k] for k in ('reference_id', 'revision', 'content_sha256')})
|
|
154
|
+
if 'experience' in body:
|
|
155
|
+
from .experience_notes import ExperienceNotes
|
|
156
|
+
engine = ExperienceNotes(member)
|
|
157
|
+
for note in body['experience']['notes'] + body['experience']['current_notes']:
|
|
158
|
+
engine.note(note['experience_id'], note['revision'])
|
|
159
|
+
for feedback in body['experience']['feedback']:
|
|
160
|
+
engine.feedback_record(feedback['feedback_id'], feedback['revision'])
|
|
161
|
+
authorized = True
|
|
162
|
+
except GovernanceError:
|
|
163
|
+
pass
|
|
164
|
+
return {'plan_id': plan_id, 'state': state, 'plan_state': plan['state'],
|
|
165
|
+
'packet_sha256': payload['packet_sha256'], 'output_sha256': actual,
|
|
166
|
+
'view_registered': registered, 'recipient_authorized_now': authorized,
|
|
167
|
+
'ready_for_git_publication': matches and registered and authorized,
|
|
168
|
+
'can_resume_same_plan': bool(resumable), 'read_only': True, 'effects_executed': False,
|
|
169
|
+
'next_step': 'Resume only if can_resume_same_plan; otherwise review a fresh export plan. Preserve later output edits.'}
|
|
170
|
+
|
|
171
|
+
def apply(self, payload, guards):
|
|
172
|
+
operation = payload['operation']
|
|
173
|
+
if operation == 'invite':
|
|
174
|
+
value = payload['invitation']; key = value['invitation_id']
|
|
175
|
+
previous = self.store.get('worker_exchange_invitations', key)
|
|
176
|
+
require((previous['revision'] if previous else 0) == guards['expected'],
|
|
177
|
+
'Invitation changed before execution.', 'EXCHANGE_REVISION_CONFLICT')
|
|
178
|
+
if value['state'] == 'active':
|
|
179
|
+
self.member(value['binding_id'])
|
|
180
|
+
source = value['source']
|
|
181
|
+
require(git_source(source['repository'], source['remote'], source['ref'], source['path']) == source,
|
|
182
|
+
'Invited source changed.', 'EXCHANGE_SOURCE_CHANGED')
|
|
183
|
+
self.store.put('worker_exchange_invitations', key, value)
|
|
184
|
+
self.store.event('worker_exchange_invited', {'invitation_id': key, 'revision': value['revision'], 'state': value['state']})
|
|
185
|
+
return {'invitation_id': key, 'revision': value['revision'], 'state': value['state'], 'effects_executed': True}
|
|
186
|
+
invitation = self.invitation(payload['invitation_id'])
|
|
187
|
+
member = self.member(invitation['binding_id'])
|
|
188
|
+
require(fingerprint(invitation) == guards['invitation'] and member.binding['revision'] == guards['member_revision'],
|
|
189
|
+
'Invitation or member scope changed before execution.', 'EXCHANGE_SCOPE_CHANGED')
|
|
190
|
+
data = read_file_bytes(self.store.directory / 'objects' / payload['packet_sha256'], max_bytes=MAX_PACKET)
|
|
191
|
+
body, objects = inspect(data, payload['packet_sha256'])
|
|
192
|
+
if operation == 'export':
|
|
193
|
+
require(index.revision(self.store) == guards['index_revision'], 'Project view changed; prepare a new export.', 'EXCHANGE_VIEW_CHANGED')
|
|
194
|
+
if 'experience' in body:
|
|
195
|
+
from .experience_storage import version
|
|
196
|
+
require(version(self.store) == guards['experience_revision'], 'Experience changed; prepare a new export.', 'EXCHANGE_VIEW_CHANGED')
|
|
197
|
+
for source in body['sources']:
|
|
198
|
+
member._source({k: source[k] for k in ('reference_id', 'revision', 'content_sha256')})
|
|
199
|
+
destination = validate_relative_path(Path(invitation['source']['repository']), payload['output_path'])
|
|
200
|
+
current = sha(read_file_bytes(destination, max_bytes=MAX_PACKET)) if destination.exists() else None
|
|
201
|
+
require(current in {guards['before'], payload['packet_sha256']}, 'Preserve later output edits.', 'EXCHANGE_OUTPUT_CHANGED')
|
|
202
|
+
if current != payload['packet_sha256']:
|
|
203
|
+
atomic_write(destination, data)
|
|
204
|
+
require(sha(read_file_bytes(destination, max_bytes=MAX_PACKET)) == payload['packet_sha256'], 'Output verification failed.')
|
|
205
|
+
self.store.put('worker_exchange_views', body['view_id'], {'body': body, 'epoch': self.channel._epoch(),
|
|
206
|
+
'packet_sha256': payload['packet_sha256'], 'packet': payload['packet']})
|
|
207
|
+
self.store.event('worker_exchange_exported', {'view_id': body['view_id'], 'packet_sha256': payload['packet_sha256']})
|
|
208
|
+
return {'view_id': body['view_id'], 'packet_sha256': payload['packet_sha256'], 'output_path': str(destination),
|
|
209
|
+
'effects_executed': True, 'git_published': False, 'read': False}
|
|
210
|
+
actual, origin = read_git(invitation['source'], payload['origin']['commit'])
|
|
211
|
+
require(sha(actual) == payload['packet_sha256'], 'Selected Git packet changed.')
|
|
212
|
+
self._check_reply(invitation, body, objects)
|
|
213
|
+
previous = self.store.get('worker_exchange_imports', payload['packet_sha256'])
|
|
214
|
+
if previous:
|
|
215
|
+
return {**previous, 'reused': True, 'effects_executed': False}
|
|
216
|
+
result = self._import(member, body, objects)
|
|
217
|
+
receipt = {'packet_sha256': payload['packet_sha256'], 'binding_id': member.actor, 'view_id': body['view_id'],
|
|
218
|
+
'origin': origin, 'packet': payload['packet'], **result, 'effects_executed': True, 'business_accepted': False,
|
|
219
|
+
'provenance': 'Governor-approved pinned Git source; packet author text is not individual authentication.'}
|
|
220
|
+
self.store.put('worker_exchange_imports', payload['packet_sha256'], receipt)
|
|
221
|
+
self.store.event('worker_exchange_imported', {'packet_sha256': payload['packet_sha256'], 'binding_id': member.actor})
|
|
222
|
+
return receipt
|
|
223
|
+
|
|
224
|
+
def _check_reply(self, invitation, body, objects):
|
|
225
|
+
fields = {'kind', 'project_id', 'binding_id', 'invitation_id', 'invitation_revision',
|
|
226
|
+
'view_id', 'sources', 'handbacks', 'reads', 'preservations'}
|
|
227
|
+
require(set(body) in (fields, fields | {'experience_feedback'}), 'Unknown reply fields.')
|
|
228
|
+
require(body['kind'] == 'reply' and body['project_id'] == invitation['project_id']
|
|
229
|
+
and body['binding_id'] == invitation['binding_id']
|
|
230
|
+
and body['invitation_id'] == invitation['invitation_id']
|
|
231
|
+
and body['invitation_revision'] == invitation['revision'], 'Packet is not for this invitation.', 'EXCHANGE_MEMBER_MISMATCH')
|
|
232
|
+
view = self.store.get('worker_exchange_views', _id(body['view_id'], 'View'))
|
|
233
|
+
require(view and view['epoch'] == self.channel._epoch() and view['body']['binding_id'] == body['binding_id']
|
|
234
|
+
and view['body']['invitation_id'] == body['invitation_id']
|
|
235
|
+
and view['body']['project_id'] == body['project_id']
|
|
236
|
+
and view['body']['invitation_revision'] == body['invitation_revision'],
|
|
237
|
+
'Unknown, superseded or inert input view.', 'EXCHANGE_VIEW_UNKNOWN')
|
|
238
|
+
if 'experience_feedback' in body:
|
|
239
|
+
from .experience_exchange import validate_reply
|
|
240
|
+
validate_reply(view['body'], body['experience_feedback'])
|
|
241
|
+
for key in ('sources', 'handbacks', 'reads', 'preservations'):
|
|
242
|
+
require(isinstance(body[key], list) and len(body[key]) <= 64, 'Reply lists must be bounded.')
|
|
243
|
+
for entry in body['sources']:
|
|
244
|
+
require(set(entry) == {'record', 'workspace_id'}, 'Invalid source entry.')
|
|
245
|
+
source = validate_record('source', entry['record'])
|
|
246
|
+
require(source['state'] == 'active' and source['content_sha256'] in objects
|
|
247
|
+
and len(objects[source['content_sha256']]) == source['size'], 'Source bytes are missing or differ.')
|
|
248
|
+
return view['body']
|
|
249
|
+
|
|
250
|
+
def _same(self, kind, value):
|
|
251
|
+
field = {'source': 'reference_id', 'handback': 'handback_id', 'read_receipt': 'receipt_id'}[kind]
|
|
252
|
+
key = value[field]
|
|
253
|
+
historical = self.store.get('worker_versions', kind + ':' + key + ':' + str(value['revision']))
|
|
254
|
+
if historical is not None:
|
|
255
|
+
require(historical == value, 'Same record revision has different contents.', 'EXCHANGE_RECORD_CONFLICT')
|
|
256
|
+
return True
|
|
257
|
+
return False
|
|
258
|
+
|
|
259
|
+
def _import(self, member, body, objects):
|
|
260
|
+
view = self.store.get('worker_exchange_views', body['view_id'])['body']
|
|
261
|
+
require(member.binding['revision'] == view['binding']['revision'], 'Refresh the changed member assignment.', 'EXCHANGE_SCOPE_CHANGED')
|
|
262
|
+
tasks = {item['task_id']: item for item in view['sections']['tasks']}
|
|
263
|
+
counts = {'sources': 0, 'handbacks': 0, 'reads': 0, 'preservations': 0, 'reused_records': 0}
|
|
264
|
+
for entry in body['sources']:
|
|
265
|
+
value = validate_record('source', entry['record']); key = value['reference_id']
|
|
266
|
+
require(value['owner_binding_id'] == member.actor, 'A reply cannot publish for another member.', 'WORKER_ACTOR_MISMATCH')
|
|
267
|
+
member._assignment(value['task_id'], entry['workspace_id'], 'handback')
|
|
268
|
+
require(value['visibility'] != 'project' or member.binding['share_project'], 'Project sharing is not granted.')
|
|
269
|
+
prior = self.store.get('worker_sources', key)
|
|
270
|
+
require(not prior or prior['owner_binding_id'] == member.actor and prior['task_id'] == value['task_id'],
|
|
271
|
+
'A source identity belongs to another member/task.', 'WORKER_SOURCE_DENIED')
|
|
272
|
+
if self._same('source', value):
|
|
273
|
+
counts['reused_records'] += 1; continue
|
|
274
|
+
require(value['task_id'] in tasks and member._task_hash(value['task_id']) == tasks[value['task_id']]['task_fingerprint'],
|
|
275
|
+
'The assigned task changed; refresh and review the reply.', 'WORKER_TASK_CHANGED')
|
|
276
|
+
member._record('source', value, value['revision'] - 1)
|
|
277
|
+
member.core._snapshot(objects[value['content_sha256']])
|
|
278
|
+
member._save_record('source', key, value); counts['sources'] += 1
|
|
279
|
+
for field, kind, action in [('handbacks', 'handback', 'worker_handback'), ('reads', 'read_receipt', 'worker_read')]:
|
|
280
|
+
for record in body[field]:
|
|
281
|
+
value = validate_record(kind, record)
|
|
282
|
+
member._own(value)
|
|
283
|
+
if self._same(kind, value):
|
|
284
|
+
counts['reused_records'] += 1; continue
|
|
285
|
+
plan = getattr(member, action)(mode='plan', record=value, expected_revision=value['revision'] - 1)
|
|
286
|
+
member._execute(action, plan['plan_id']); counts[field] += 1
|
|
287
|
+
if 'experience_feedback' in body:
|
|
288
|
+
from .experience_notes import ExperienceNotes
|
|
289
|
+
from .experience_contracts import validate_record as validate_experience
|
|
290
|
+
engine = ExperienceNotes(member)
|
|
291
|
+
counts['experience_feedback'] = 0
|
|
292
|
+
for supplied in body['experience_feedback']:
|
|
293
|
+
value = validate_experience('feedback', supplied)
|
|
294
|
+
old = self.store.get('experience_feedback_versions', engine.version_key(value['feedback_id'], value['revision']))
|
|
295
|
+
if old is not None:
|
|
296
|
+
require(old == value, 'Same feedback revision differs.', 'EXCHANGE_RECORD_CONFLICT')
|
|
297
|
+
counts['reused_records'] += 1
|
|
298
|
+
continue
|
|
299
|
+
plan = member.invoke('experience_feedback', {'mode': 'plan', 'record': value, 'expected_revision': value['revision'] - 1})
|
|
300
|
+
member.invoke('experience_feedback', {'mode': 'execute', 'plan_id': plan['plan_id']})
|
|
301
|
+
counts['experience_feedback'] += 1
|
|
302
|
+
from .exchange_endpoint import validate_preservation
|
|
303
|
+
for preservation in body['preservations']:
|
|
304
|
+
validate_preservation(preservation, objects)
|
|
305
|
+
member._assignment(preservation['task_id'], preservation['workspace_id'], 'checkpoint')
|
|
306
|
+
identity = fingerprint([member.actor, body['view_id'], preservation])
|
|
307
|
+
if self.store.get('worker_remote_checkpoints', identity):
|
|
308
|
+
counts['reused_records'] += 1; continue
|
|
309
|
+
for entry in preservation['files']:
|
|
310
|
+
for layer in ('head', 'index', 'worktree'):
|
|
311
|
+
if entry[layer] is not None:
|
|
312
|
+
member.core._snapshot(objects[entry[layer]['sha256']])
|
|
313
|
+
self.store.put('worker_remote_checkpoints', identity, {'binding_id': member.actor, 'view_id': body['view_id'],
|
|
314
|
+
'preservation': preservation, 'delivery': False, 'business_accepted': False})
|
|
315
|
+
counts['preservations'] += 1
|
|
316
|
+
return counts
|
taskcarry/connection.py
ADDED
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
"""Plan and merge only a generated project MCP block, retaining other settings."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
import tomllib
|
|
7
|
+
|
|
8
|
+
from .core import Core, _id, digest_bytes, read_file_bytes
|
|
9
|
+
from .setup import atomic_write, check_binding, codex_trust_step, project_root, read_manifest, safe_target, workbench_binding
|
|
10
|
+
from .store import GovernanceError, now
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class Connection(Core):
|
|
14
|
+
def _materials(self, root, binding, fragment):
|
|
15
|
+
if safe_target(root, '.taskcarry/setup-intent.json').exists():
|
|
16
|
+
raise GovernanceError('CONNECTION_SETUP_PENDING', 'Finish the existing setup intent before connecting.')
|
|
17
|
+
manifest = read_manifest(root)
|
|
18
|
+
if not manifest.get('server_name'):
|
|
19
|
+
raise GovernanceError('CONNECTION_SETUP_REQUIRED', 'Install and verify setup materials before connecting.')
|
|
20
|
+
check_binding(manifest, None, binding)
|
|
21
|
+
if manifest.get('binding') != binding:
|
|
22
|
+
raise GovernanceError('CONNECTION_BINDING_CHANGED', 'Install setup materials with this exact workbench binding before connecting.')
|
|
23
|
+
if manifest['files'].get('.taskcarry/codex.mcp.toml') != digest_bytes(fragment):
|
|
24
|
+
raise GovernanceError('CONNECTION_FRAGMENT_CHANGED', 'Regenerate or review the modified setup fragment.')
|
|
25
|
+
return manifest
|
|
26
|
+
|
|
27
|
+
def _target(self, target, workspace, task_id, binding_mode="task"):
|
|
28
|
+
root = project_root(target or self.root)
|
|
29
|
+
if root == Path.home().resolve() or root.name.casefold() == '.codex':
|
|
30
|
+
raise GovernanceError('PROJECT_CONFIG_REQUIRED', 'Select a project directory, not user-level configuration.')
|
|
31
|
+
if target is not None:
|
|
32
|
+
workbench_binding(self.root, root, workspace, task_id, binding_mode=binding_mode)
|
|
33
|
+
elif workspace is not None or task_id is not None:
|
|
34
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Workbench identity requires its explicit target.')
|
|
35
|
+
return root
|
|
36
|
+
|
|
37
|
+
def _merge(self, root, before, fragment, server):
|
|
38
|
+
try:
|
|
39
|
+
config = tomllib.loads(before.decode('utf-8-sig')) if before else {}
|
|
40
|
+
requested = tomllib.loads(fragment.decode('utf-8'))['mcp_servers'][server]
|
|
41
|
+
except (UnicodeError, ValueError, KeyError) as exc:
|
|
42
|
+
raise GovernanceError('CONNECTION_CONFIG_INVALID', 'Preserve the existing file and review its TOML syntax.') from exc
|
|
43
|
+
if not isinstance(config.get('mcp_servers', {}), dict):
|
|
44
|
+
raise GovernanceError('CONNECTION_CONFIG_INVALID', 'mcp_servers must be a TOML table.')
|
|
45
|
+
existing = config.get('mcp_servers', {}).get(server)
|
|
46
|
+
if existing == requested:
|
|
47
|
+
return before
|
|
48
|
+
if existing is None:
|
|
49
|
+
merged = before + (b'\n' if before and not before.endswith(b'\n') else b'') + fragment
|
|
50
|
+
else:
|
|
51
|
+
previous = self.store.get('connections', digest_bytes(str(root).encode()))
|
|
52
|
+
old = (previous or {}).get('fragment', '').encode('utf-8')
|
|
53
|
+
if not old or before.count(old) != 1 or (previous or {}).get('server') != server:
|
|
54
|
+
raise GovernanceError('CONNECTION_CONFLICT', 'The existing service differs from the generated block. '
|
|
55
|
+
'Preserve it and review the specific configuration conflict.', {'server': server})
|
|
56
|
+
merged = before.replace(old, fragment, 1)
|
|
57
|
+
try:
|
|
58
|
+
parsed = tomllib.loads(merged.decode('utf-8-sig'))
|
|
59
|
+
except (ValueError, UnicodeError) as exc:
|
|
60
|
+
raise GovernanceError('CONNECTION_CONFLICT', 'This TOML layout cannot accept the generated block additively; '
|
|
61
|
+
'preserve the file and review its table layout.') from exc
|
|
62
|
+
check = dict(config)
|
|
63
|
+
check['mcp_servers'] = {**config.get('mcp_servers', {}), server: requested}
|
|
64
|
+
if parsed != check:
|
|
65
|
+
raise GovernanceError('CONNECTION_CONFLICT', 'The merge would change unrelated configuration.')
|
|
66
|
+
return merged
|
|
67
|
+
|
|
68
|
+
def connect(self, action='plan', target=None, workspace=None, task_id=None, plan_id=None, binding_mode="task"):
|
|
69
|
+
if action not in ('plan', 'execute', 'status'):
|
|
70
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Use plan, execute or status.')
|
|
71
|
+
if action == 'plan':
|
|
72
|
+
if plan_id is not None:
|
|
73
|
+
raise GovernanceError('INVALID_ARGUMENT', 'A new plan does not take a plan ID.')
|
|
74
|
+
if binding_mode not in ('task', 'directory') or (binding_mode == 'directory' and target is None):
|
|
75
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Directory connection needs its registered target and workspace.')
|
|
76
|
+
root = self._target(target, workspace, task_id, binding_mode)
|
|
77
|
+
fragment = read_file_bytes(safe_target(root, '.taskcarry/codex.mcp.toml'), max_bytes=65536)
|
|
78
|
+
binding = workbench_binding(self.root, root, workspace, task_id, binding_mode=binding_mode) if target is not None else None
|
|
79
|
+
manifest = self._materials(root, binding, fragment)
|
|
80
|
+
server = manifest['server_name']
|
|
81
|
+
try:
|
|
82
|
+
command = tomllib.loads(fragment.decode('utf-8'))['mcp_servers'][server]
|
|
83
|
+
args = command['args']
|
|
84
|
+
if args[:3] != ['-I', '-X', 'utf8'] or args[-3:] != ['--project', str(self.root), 'mcp']:
|
|
85
|
+
raise ValueError('Incorrect launch binding')
|
|
86
|
+
except (KeyError, TypeError, ValueError, UnicodeError) as exc:
|
|
87
|
+
raise GovernanceError('CONNECTION_BINDING_CHANGED', 'The fragment must isolate the selected package and bind this control.') from exc
|
|
88
|
+
destination = safe_target(root, '.codex/config.toml')
|
|
89
|
+
before = read_file_bytes(destination, max_bytes=1024*1024) if destination.exists() else b''
|
|
90
|
+
with self.store.transaction():
|
|
91
|
+
merged = self._merge(root, before, fragment, server)
|
|
92
|
+
body = {'target': str(root), 'workspace': workspace, 'task_id': task_id,
|
|
93
|
+
'server': server, 'before': digest_bytes(before), 'after': digest_bytes(merged),
|
|
94
|
+
'fragment': fragment.decode('utf-8'), 'existed': destination.exists()}
|
|
95
|
+
if binding_mode == 'directory':
|
|
96
|
+
body['binding_mode'] = binding_mode
|
|
97
|
+
key = 'connection-' + digest_bytes(json.dumps(body, sort_keys=True).encode())[:24]
|
|
98
|
+
prior = self.store.get('connection_plans', key)
|
|
99
|
+
if prior is None:
|
|
100
|
+
prior = dict(body, plan_id=key, state='PLANNED', created_at=now())
|
|
101
|
+
self.store.put('connection_plans', key, prior)
|
|
102
|
+
self.store.event('connection_planned', {'plan_id': key, 'target': str(root)})
|
|
103
|
+
return self._result(prior)
|
|
104
|
+
if any(value is not None for value in (target, workspace, task_id)) or binding_mode != 'task':
|
|
105
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Execute the exact saved plan without new target arguments.')
|
|
106
|
+
key = _id(plan_id, 'Connection plan ID')
|
|
107
|
+
with self.store.guard():
|
|
108
|
+
plan = self.store.get('connection_plans', key)
|
|
109
|
+
if not plan:
|
|
110
|
+
raise GovernanceError('PLAN_NOT_FOUND', 'Read an existing connection plan first.')
|
|
111
|
+
if action == 'status':
|
|
112
|
+
return self._result(plan)
|
|
113
|
+
root = self._target(plan['target'] if plan['workspace'] is not None else None,
|
|
114
|
+
plan['workspace'], plan['task_id'], plan.get('binding_mode', 'task'))
|
|
115
|
+
if str(root) != plan['target']:
|
|
116
|
+
raise GovernanceError('CONNECTION_BINDING_CHANGED', 'The saved target binding changed.')
|
|
117
|
+
destination = safe_target(root, '.codex/config.toml')
|
|
118
|
+
current = read_file_bytes(destination, max_bytes=1024*1024) if destination.exists() else b''
|
|
119
|
+
digest = digest_bytes(current)
|
|
120
|
+
if digest == plan['after']:
|
|
121
|
+
written = False
|
|
122
|
+
elif digest == plan['before'] and destination.exists() == plan['existed'] and plan['state'] != 'COMPLETED':
|
|
123
|
+
fragment = plan['fragment'].encode('utf-8')
|
|
124
|
+
live = read_file_bytes(safe_target(root, '.taskcarry/codex.mcp.toml'), max_bytes=65536)
|
|
125
|
+
if live != fragment:
|
|
126
|
+
raise GovernanceError('CONNECTION_FRAGMENT_CHANGED', 'The setup changed after planning.')
|
|
127
|
+
binding = (workbench_binding(self.root, root, plan['workspace'], plan['task_id'],
|
|
128
|
+
binding_mode=plan.get('binding_mode', 'task')) if plan['workspace'] is not None else None)
|
|
129
|
+
manifest = self._materials(root, binding, live)
|
|
130
|
+
if manifest['server_name'] != plan['server']:
|
|
131
|
+
raise GovernanceError('CONNECTION_BINDING_CHANGED', 'The setup service changed after planning.')
|
|
132
|
+
merged = self._merge(root, current, fragment, plan['server'])
|
|
133
|
+
if digest_bytes(merged) != plan['after']:
|
|
134
|
+
raise GovernanceError('CONNECTION_CONFLICT', 'The planned merge is no longer reproducible.')
|
|
135
|
+
with self.store.transaction():
|
|
136
|
+
self.store.put('connection_plans', key, dict(plan, state='PREPARED'))
|
|
137
|
+
latest = read_file_bytes(destination, max_bytes=1024*1024) if destination.exists() else b''
|
|
138
|
+
if latest != current or destination.exists() != plan['existed']:
|
|
139
|
+
raise GovernanceError('CONNECTION_CONFIG_CHANGED', 'The target changed before writing; preserve it.')
|
|
140
|
+
atomic_write(destination, merged)
|
|
141
|
+
written = True
|
|
142
|
+
else:
|
|
143
|
+
raise GovernanceError('CONNECTION_CONFIG_CHANGED', 'Preserve later user edits and prepare a new reviewed plan.')
|
|
144
|
+
if digest_bytes(read_file_bytes(destination, max_bytes=1024*1024)) != plan['after']:
|
|
145
|
+
raise GovernanceError('CONNECTION_CONFIG_CHANGED', 'The target changed while verifying the merge.')
|
|
146
|
+
with self.store.transaction():
|
|
147
|
+
if plan['state'] != 'COMPLETED':
|
|
148
|
+
plan = dict(plan, state='COMPLETED', completed_at=now())
|
|
149
|
+
self.store.put('connection_plans', key, plan)
|
|
150
|
+
self.store.put('connections', digest_bytes(str(root).encode()), plan)
|
|
151
|
+
self.store.event('connection_saved', {'plan_id': key, 'sha256': plan['after']})
|
|
152
|
+
return dict(self._result(plan), file_written=written)
|
|
153
|
+
|
|
154
|
+
@staticmethod
|
|
155
|
+
def _result(plan):
|
|
156
|
+
# Never return unrelated existing configuration, which can contain secrets.
|
|
157
|
+
return {'plan': {k: v for k, v in plan.items() if k != 'fragment'},
|
|
158
|
+
'host_loading_verified': False, 'native_acceptance_verified': False,
|
|
159
|
+
'next_step': codex_trust_step(plan['target']) + ' Then call native doctor/status in that chat.'}
|