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,356 @@
1
+ """Planned single-ref Git exchange and verified local recovery-media copying.
2
+
3
+ Remote repositories and authentication must already be configured by the user.
4
+ Copy receipts describe local bytes only: they never claim a cloud provider has
5
+ uploaded, retained or downloaded them. A transfer is not governance adoption.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import re
13
+ import subprocess
14
+ from urllib.parse import urlsplit
15
+ import uuid
16
+
17
+ from .core import Core, _id, digest_bytes, read_file_bytes
18
+ from .store import GovernanceError, now
19
+ from .recovery_files import atomic, disjoint, lock, normal, safe, MAX_BYTES
20
+
21
+
22
+ PLAN_SCHEMA = 'taskcarry.transfer-plan.v1'
23
+ RECEIPT_SCHEMA = 'taskcarry.transfer-receipt.v1'
24
+
25
+
26
+ def _hash(value):
27
+ if not isinstance(value, bytes):
28
+ value = json.dumps(value, sort_keys=True, separators=(',', ':'), allow_nan=False).encode('utf-8')
29
+ return digest_bytes(value)
30
+
31
+
32
+ def _git(root, *args, check=True):
33
+ environment = {name: value for name, value in os.environ.items() if not name.startswith('GIT_')}
34
+ environment.update(GIT_TERMINAL_PROMPT='0', GIT_OPTIONAL_LOCKS='0')
35
+ try:
36
+ result = subprocess.run(['git', '-c', 'core.hooksPath=' + os.devnull,
37
+ '-c', 'push.followTags=false', '-c', 'push.recurseSubmodules=no',
38
+ '-C', str(root), *args], stdout=subprocess.PIPE, stderr=subprocess.PIPE,
39
+ env=environment, timeout=120, shell=False,
40
+ creationflags=subprocess.CREATE_NO_WINDOW if os.name == 'nt' else 0)
41
+ except (OSError, subprocess.TimeoutExpired) as exc:
42
+ raise GovernanceError('TRANSFER_TRANSPORT_UNKNOWN', 'The Git command did not provide a reliable completion result.',
43
+ {'exception': type(exc).__name__}) from exc
44
+ if check and result.returncode:
45
+ raise GovernanceError('TRANSFER_GIT_FAILED', 'Git transport or repository inspection failed.',
46
+ {'command': args[0], 'returncode': result.returncode,
47
+ 'stderr': result.stderr.decode('utf-8', 'replace')[:2000]})
48
+ return result
49
+
50
+
51
+ def _out(root, *args):
52
+ return _git(root, *args).stdout.decode('utf-8', 'strict').strip()
53
+
54
+
55
+ def _repository(value):
56
+ if not isinstance(value, str) or not value.strip():
57
+ raise GovernanceError('TRANSFER_ARGUMENT', 'Select an existing exact Git worktree root.')
58
+ root = normal(value)
59
+ if normal(_out(root, 'rev-parse', '--show-toplevel')) != root:
60
+ raise GovernanceError('TRANSFER_REPOSITORY', 'Select the exact Git worktree root.')
61
+ return root
62
+
63
+
64
+ def _identity(root):
65
+ return {'path': str(root), 'git_dir': str(normal(_out(root, 'rev-parse', '--path-format=absolute', '--git-dir'))),
66
+ 'common_dir': str(normal(_out(root, 'rev-parse', '--path-format=absolute', '--git-common-dir')))}
67
+
68
+
69
+ def _snapshot(root):
70
+ index = normal(_out(root, 'rev-parse', '--path-format=absolute', '--git-path', 'index'))
71
+ raw_index = read_file_bytes(index) if index.exists() else None
72
+ status = _git(root, 'status', '--porcelain=v1', '-z', '--untracked-files=all').stdout
73
+ # Untracked bytes are never transported by Git push. Preserve their local
74
+ # size/mtime identity without reading credentials or other unrelated bodies.
75
+ untracked = {}
76
+ for value in _git(root, 'ls-files', '--others', '--exclude-standard', '-z').stdout.split(b'\0'):
77
+ if value:
78
+ relative = value.decode('utf-8', 'strict')
79
+ path = root / relative
80
+ info = path.lstat()
81
+ untracked[relative] = [info.st_size, info.st_mtime_ns, info.st_mode]
82
+ return {'head': _out(root, 'rev-parse', '--verify', 'HEAD'),
83
+ 'branch': _git(root, 'symbolic-ref', '--quiet', 'HEAD', check=False).stdout.decode('utf-8').strip() or None,
84
+ 'index_sha256': _hash(raw_index) if raw_index is not None else None,
85
+ 'status_sha256': _hash(status), 'untracked_metadata': untracked,
86
+ 'work_diff_sha256': _hash(_git(root, 'diff', '--binary', '--no-ext-diff', '--no-textconv', '--').stdout)}
87
+
88
+
89
+ def _remote_url(root, name):
90
+ if not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,99}', name):
91
+ raise GovernanceError('TRANSFER_REMOTE', 'Select one already-configured remote name.')
92
+ urls = _out(root, 'remote', 'get-url', '--push', '--all', name).splitlines()
93
+ if len(urls) != 1:
94
+ raise GovernanceError('TRANSFER_REMOTE', 'A transfer must target exactly one configured push URL.')
95
+ url = urls[0]
96
+ if not url or url.startswith('-') or any(character in url for character in '\0\r\n') or '::' in url:
97
+ raise GovernanceError('TRANSFER_REMOTE', 'This remote transport syntax is not supported.')
98
+ parsed = urlsplit(url)
99
+ if parsed.password is not None or parsed.query or parsed.fragment or (parsed.scheme in ('http', 'https') and parsed.username is not None):
100
+ raise GovernanceError('TRANSFER_REMOTE_CREDENTIALS', 'Use the host credential mechanism instead of credentials or tokens embedded in a remote URL.')
101
+ if '://' in url and parsed.scheme not in ('http', 'https', 'ssh', 'git', 'file'):
102
+ raise GovernanceError('TRANSFER_REMOTE', 'Use an existing Git SSH, HTTPS or local file remote.')
103
+ # Resolve local paths now; a later cwd must not redirect the target.
104
+ if '://' not in url and (':' not in url or re.match(r'^[A-Za-z]:[\\/]', url)):
105
+ local = Path(url)
106
+ url = str(normal(local if local.is_absolute() else root / local))
107
+ return url
108
+
109
+
110
+ def _remote_ref(root, url, ref):
111
+ output = _out(root, 'ls-remote', '--refs', url, ref)
112
+ rows = [line.split('\t', 1) for line in output.splitlines() if line]
113
+ if not rows:
114
+ return None
115
+ if len(rows) != 1 or len(rows[0]) != 2 or rows[0][1] != ref or not re.fullmatch(r'[0-9a-f]{40}|[0-9a-f]{64}', rows[0][0]):
116
+ raise GovernanceError('TRANSFER_REMOTE_RESPONSE', 'The remote did not return one exact requested ref.')
117
+ return rows[0][0]
118
+
119
+
120
+ class RemoteTransfer(Core):
121
+ def transfer(self, action, repository=None, remote=None, ref=None, commit=None,
122
+ plan_id=None, manifest=None, destination=None, expected_sha256=None):
123
+ """Plan/execute one Git ref or a sealed recovery set; verify real effects."""
124
+ if action == 'publish_plan':
125
+ if any(value is not None for value in (plan_id, manifest, destination, expected_sha256)):
126
+ raise GovernanceError('TRANSFER_ARGUMENT', 'A Git publication plan accepts repository, remote, ref and commit only.')
127
+ return self._publish_plan(repository, remote, ref, commit)
128
+ if action == 'copy_plan':
129
+ if any(value is not None for value in (repository, remote, ref, commit, plan_id)):
130
+ raise GovernanceError('TRANSFER_ARGUMENT', 'A recovery copy plan accepts manifest, destination and expected_sha256 only.')
131
+ return self._copy_plan(manifest, destination, expected_sha256)
132
+ if any(value is not None for value in (repository, remote, ref, commit, manifest, destination, expected_sha256)):
133
+ raise GovernanceError('TRANSFER_ARGUMENT', 'Use the exact frozen plan without replacement targets or inputs.')
134
+ plan = self._plan(plan_id)
135
+ if action == 'status':
136
+ return {'plan': plan, 'receipt': self._receipt(plan_id), 'effects_verified_now': False}
137
+ if action == 'verify':
138
+ return self._verify(plan)
139
+ if action not in ('publish_execute', 'copy_execute') or plan['kind'] != action.split('_')[0]:
140
+ raise GovernanceError('TRANSFER_ACTION', 'Choose the execution action matching this plan.')
141
+ self.store.assert_writable()
142
+ config = self.store.get('config', 'project') or {}
143
+ if plan['plan_id'] in config.get('recovery_inert_plan_ids', []):
144
+ raise GovernanceError('RESTORED_PLAN_INERT', 'Historical transfer plans require a new local plan after recovery.')
145
+ resource = plan['repository'] + '\0' + plan['url'] + '\0' + plan['ref'] if plan['kind'] == 'publish' else os.path.normcase(plan['destination'])
146
+ with lock(self.store.directory / ('transfer-' + _hash(resource) + '.lock')):
147
+ return self._publish_execute(plan) if plan['kind'] == 'publish' else self._copy_execute(plan)
148
+
149
+ def _plan(self, plan_id):
150
+ plan_id = _id(plan_id, 'Transfer plan ID')
151
+ plan = self.store.get('transfer_plans', plan_id)
152
+ if plan is None:
153
+ raise GovernanceError('TRANSFER_PLAN_NOT_FOUND', 'Create and review a transfer plan first.')
154
+ if plan.get('schema') != PLAN_SCHEMA or plan.get('plan_id') != plan_id:
155
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible transfer plan reader.')
156
+ fingerprint = _hash({key: value for key, value in plan.items() if key != 'fingerprint'})
157
+ if plan.get('fingerprint') != fingerprint:
158
+ raise GovernanceError('TRANSFER_PLAN_CHANGED', 'The stored transfer plan differs from its frozen content.')
159
+ return plan
160
+
161
+ def _receipt(self, plan_id):
162
+ receipt = self.store.get('transfer_receipts', plan_id)
163
+ if receipt is not None and receipt.get('schema') != RECEIPT_SCHEMA:
164
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible transfer receipt reader.')
165
+ return receipt
166
+
167
+ def _save_plan(self, kind, body):
168
+ plan_id = 'transfer-' + uuid.uuid4().hex
169
+ plan = {'schema': PLAN_SCHEMA, 'plan_id': plan_id, 'kind': kind, 'created_at': now(), **body}
170
+ plan['fingerprint'] = _hash(plan)
171
+ with self.store.transaction():
172
+ self.store.put('transfer_plans', plan_id, plan)
173
+ self.store.event('transfer_planned', {'plan_id': plan_id, 'kind': kind, 'fingerprint': plan['fingerprint']})
174
+ return {'plan': plan, 'execute_required': True, 'effects_applied': False}
175
+
176
+ def _publish_plan(self, repository, remote, ref, selected):
177
+ self.store.assert_writable()
178
+ root = _repository(repository)
179
+ if (not isinstance(ref, str) or not ref.startswith(('refs/heads/', 'refs/tags/'))
180
+ or _git(root, 'check-ref-format', ref, check=False).returncode):
181
+ raise GovernanceError('TRANSFER_REF', 'Select one exact refs/heads/... or refs/tags/... destination.')
182
+ if not isinstance(selected, str) or not selected or selected.startswith('-') or len(selected) > 256:
183
+ raise GovernanceError('TRANSFER_COMMIT', 'Select one exact existing commit or local revision.')
184
+ before = _snapshot(root)
185
+ selected_oid = _out(root, 'rev-parse', '--verify', '--end-of-options', selected + '^{commit}')
186
+ url = _remote_url(root, remote)
187
+ old = _remote_ref(root, url, ref)
188
+ if old and old != selected_oid:
189
+ if ref.startswith('refs/tags/'):
190
+ raise GovernanceError('TRANSFER_TAG_CONFLICT', 'Existing tags are immutable; select a new tag or retain the conflict.')
191
+ ancestry = _git(root, 'merge-base', '--is-ancestor', old, selected_oid, check=False)
192
+ if ancestry.returncode:
193
+ raise GovernanceError('TRANSFER_NOT_FAST_FORWARD', 'The destination history is not a verified ancestor of this commit; inspect or import it before planning.')
194
+ if _snapshot(root) != before:
195
+ raise GovernanceError('TRANSFER_SOURCE_CHANGED', 'Repository state changed while the publication plan was read.')
196
+ return self._save_plan('publish', {'repository': str(root), 'repository_identity': _identity(root),
197
+ 'remote': remote, 'url': url, 'ref': ref, 'commit': selected_oid,
198
+ 'expected_old_ref': old, 'worktree': before,
199
+ 'meaning': 'One exact commit/ref and its reachable history; uncommitted files are not uploaded. Public or private content review remains a host responsibility.'})
200
+
201
+ def _publish_observe(self, plan):
202
+ root = _repository(plan['repository'])
203
+ if _identity(root) != plan['repository_identity'] or _remote_url(root, plan['remote']) != plan['url']:
204
+ raise GovernanceError('TRANSFER_TARGET_CHANGED', 'Repository identity or configured remote URL changed after the plan.')
205
+ actual = _remote_ref(root, plan['url'], plan['ref'])
206
+ return {'verified': actual == plan['commit'], 'actual_ref': actual, 'expected_ref': plan['commit'],
207
+ 'ref': plan['ref'], 'kind': 'git_ref', 'offsite_recovery_verified': False,
208
+ 'meaning': 'The selected ref was read from its configured Git endpoint; full project recovery and cloud retention are separate evidence.'}
209
+
210
+ def _publish_execute(self, plan):
211
+ prior = self._receipt(plan['plan_id'])
212
+ root = _repository(plan['repository'])
213
+ before = _snapshot(root)
214
+ observed = self._publish_observe(plan)
215
+ if observed['verified']:
216
+ if _snapshot(root) != before:
217
+ raise GovernanceError('TRANSFER_WORKTREE_CHANGED', 'Concurrent local changes were observed while verifying the existing effect.', observed)
218
+ return self._finish(plan, observed, prior, effect_reused=True, worktree_unchanged=True)
219
+ if prior:
220
+ raise GovernanceError('TRANSFER_EFFECT_CHANGED', 'The remote no longer matches the retained completed receipt.', observed)
221
+ if observed['actual_ref'] != plan['expected_old_ref']:
222
+ raise GovernanceError('TRANSFER_REMOTE_CHANGED', 'The destination ref changed after planning; preserve it and prepare a new plan.', observed)
223
+ if before != plan['worktree']:
224
+ raise GovernanceError('TRANSFER_SOURCE_CHANGED', 'Local HEAD, index or working state changed after planning; prepare a new plan.')
225
+ # An immutable operation journal precedes the external effect. A crashed
226
+ # call may therefore be resumed by checking the actual remote first.
227
+ self._started(plan)
228
+ transport = None
229
+ try:
230
+ result = _git(root, 'push', '--porcelain', '--no-follow-tags', '--recurse-submodules=no',
231
+ '--force-with-lease=' + plan['ref'] + ':' + (plan['expected_old_ref'] or ''),
232
+ plan['url'], plan['commit'] + ':' + plan['ref'], check=False)
233
+ if result.returncode:
234
+ transport = {'returncode': result.returncode, 'stderr': result.stderr.decode('utf-8', 'replace')[:2000]}
235
+ except GovernanceError as exc:
236
+ transport = {'code': exc.code, 'details': exc.details}
237
+ try:
238
+ observed = self._publish_observe(plan)
239
+ except GovernanceError as exc:
240
+ raise GovernanceError('TRANSFER_EFFECT_UNKNOWN', 'Transmission ended without a verifiable remote result; retry this exact plan to inspect its actual effect first.',
241
+ {'plan_id': plan['plan_id'], 'transport': transport, 'verification_code': exc.code}) from exc
242
+ unchanged = _snapshot(root) == before
243
+ if not unchanged:
244
+ raise GovernanceError('TRANSFER_WORKTREE_CHANGED', 'Concurrent local changes were observed; no reset was attempted.',
245
+ {'remote_effect': observed, 'transport': transport})
246
+ if not observed['verified']:
247
+ raise GovernanceError('TRANSFER_NOT_APPLIED', 'The exact ref has not been verified at its destination; retain this plan and inspect the evidence.',
248
+ {'remote_effect': observed, 'transport': transport})
249
+ return self._finish(plan, observed, prior, effect_reused=False, worktree_unchanged=True,
250
+ transport_warning=transport)
251
+
252
+ def _started(self, plan):
253
+ with self.store.transaction():
254
+ previous = self.store.get('transfer_attempts', plan['plan_id'])
255
+ if previous and previous.get('schema') != 'taskcarry.transfer-attempt.v1':
256
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible transfer attempt reader.')
257
+ value = previous or {'schema': 'taskcarry.transfer-attempt.v1', 'plan_id': plan['plan_id'],
258
+ 'fingerprint': plan['fingerprint'], 'started_at': now(), 'state': 'effect_may_exist'}
259
+ if previous is None:
260
+ self.store.put('transfer_attempts', plan['plan_id'], value)
261
+ self.store.event('transfer_started', {'plan_id': plan['plan_id'], 'kind': plan['kind']})
262
+
263
+ def _finish(self, plan, observed, prior, **details):
264
+ if prior:
265
+ return {'receipt': prior, 'reused': True, 'observed_effect': observed}
266
+ receipt = {'schema': RECEIPT_SCHEMA, 'plan_id': plan['plan_id'], 'kind': plan['kind'],
267
+ 'fingerprint': plan['fingerprint'], 'state': 'VERIFIED', 'verified_at': now(),
268
+ 'observed_effect': observed, **details}
269
+ with self.store.transaction():
270
+ self.store.put('transfer_receipts', plan['plan_id'], receipt)
271
+ self.store.event('transfer_verified', {'plan_id': plan['plan_id'], 'kind': plan['kind'],
272
+ 'fingerprint': plan['fingerprint']})
273
+ return {'receipt': receipt, 'reused': False, 'observed_effect': observed}
274
+
275
+ def _copy_plan(self, manifest, destination, expected):
276
+ from .project_recovery import ProjectRecovery, _manifest, _payload_refs
277
+ self.store.assert_writable()
278
+ if not isinstance(manifest, str) or not isinstance(destination, str):
279
+ raise GovernanceError('TRANSFER_ARGUMENT', 'Select the exact recovery manifest and an independent local destination.')
280
+ source = normal(manifest)
281
+ target = normal(destination)
282
+ disjoint(source.parent, target)
283
+ disjoint(self.root, target)
284
+ verified = ProjectRecovery._verify(str(source), expected)
285
+ if not verified['verified']:
286
+ raise GovernanceError('TRANSFER_SOURCE_INCOMPLETE', 'Verify all selected recovery objects before copying.', verified)
287
+ value, checksum = _manifest(source, verified['manifest_sha256'])
288
+ objects = {item['sha256']: item['size'] for item in _payload_refs(value)}
289
+ files = [{'path': 'objects/' + sha, 'sha256': sha, 'size': size} for sha, size in sorted(objects.items())]
290
+ files.append({'path': 'manifest.json', 'sha256': checksum, 'size': source.stat().st_size})
291
+ if target.exists() and not target.is_dir():
292
+ raise GovernanceError('TRANSFER_DESTINATION_CONFLICT', 'The copy destination must be a directory.')
293
+ self._copy_observe_files(target, files, require_complete=False)
294
+ return self._save_plan('copy', {'manifest': str(source), 'manifest_sha256': checksum,
295
+ 'destination': str(target), 'set_id': value['set_id'], 'files': files,
296
+ 'meaning': 'Copy only this sealed recovery manifest and its selected objects to a local directory. No cloud synchronization or remote retention is asserted.'})
297
+
298
+ @staticmethod
299
+ def _copy_observe_files(target, files, require_complete):
300
+ missing = []
301
+ for item in files:
302
+ path = safe(target, item['path'])
303
+ if not path.exists():
304
+ missing.append(item['path'])
305
+ continue
306
+ data = read_file_bytes(path, MAX_BYTES)
307
+ if len(data) != item['size'] or _hash(data) != item['sha256']:
308
+ raise GovernanceError('TRANSFER_DESTINATION_CONFLICT', 'Different existing destination bytes were preserved.', {'path': item['path']})
309
+ return {'verified': not missing, 'missing': missing, 'files': len(files),
310
+ 'kind': 'local_recovery_copy', 'local_copy_verified': not missing,
311
+ 'cloud_upload_verified': False, 'cloud_download_verified': False,
312
+ 'offsite_recovery_verified': False,
313
+ 'meaning': 'Verified local copied bytes only; provider upload, remote retention and a second-machine restore require separate evidence.'}
314
+
315
+ def _copy_execute(self, plan):
316
+ from .project_recovery import ProjectRecovery
317
+ prior = self._receipt(plan['plan_id'])
318
+ target = normal(plan['destination'])
319
+ observed = self._copy_observe_files(target, plan['files'], require_complete=False)
320
+ if observed['verified']:
321
+ verified = ProjectRecovery._verify(str(target / 'manifest.json'), plan['manifest_sha256'])
322
+ if not verified['verified']:
323
+ raise GovernanceError('TRANSFER_DESTINATION_INCOMPLETE', 'The copied recovery set failed structural verification.', verified)
324
+ return self._finish(plan, observed, prior, effect_reused=True)
325
+ if prior:
326
+ raise GovernanceError('TRANSFER_EFFECT_CHANGED', 'The retained copy receipt no longer matches complete local bytes.', observed)
327
+ # Check the entire source before making any additional destination files.
328
+ verified = ProjectRecovery._verify(plan['manifest'], plan['manifest_sha256'])
329
+ if not verified['verified']:
330
+ raise GovernanceError('TRANSFER_SOURCE_INCOMPLETE', 'The original recovery set is no longer complete.', verified)
331
+ self._started(plan)
332
+ source = normal(plan['manifest'])
333
+ for item in plan['files']:
334
+ path = source if item['path'] == 'manifest.json' else safe(source.parent, item['path'])
335
+ data = read_file_bytes(path, MAX_BYTES)
336
+ if len(data) != item['size'] or _hash(data) != item['sha256']:
337
+ raise GovernanceError('TRANSFER_SOURCE_CHANGED', 'A frozen recovery file changed before its copy.', {'path': item['path']})
338
+ # Objects first, manifest last. Partial transfers are resumable and
339
+ # cannot expose a manifest before all selected payloads are present.
340
+ atomic(safe(target, item['path']), data)
341
+ observed = self._copy_observe_files(target, plan['files'], require_complete=True)
342
+ verified = ProjectRecovery._verify(str(target / 'manifest.json'), plan['manifest_sha256'])
343
+ if not observed['verified'] or not verified['verified']:
344
+ raise GovernanceError('TRANSFER_DESTINATION_INCOMPLETE', 'Read-back verification did not confirm the complete local copy.', observed)
345
+ return self._finish(plan, observed, prior, effect_reused=False)
346
+
347
+ def _verify(self, plan):
348
+ if plan['kind'] == 'publish':
349
+ return {'plan_id': plan['plan_id'], **self._publish_observe(plan)}
350
+ from .project_recovery import ProjectRecovery
351
+ observed = self._copy_observe_files(normal(plan['destination']), plan['files'], require_complete=True)
352
+ if observed['verified']:
353
+ structural = ProjectRecovery._verify(str(Path(plan['destination']) / 'manifest.json'), plan['manifest_sha256'])
354
+ observed['verified'] = structural['verified']
355
+ observed['state_references_verified'] = structural['state_references_verified']
356
+ return {'plan_id': plan['plan_id'], **observed}
@@ -0,0 +1,215 @@
1
+ """Reviewed stable-role launch materials, preserving unrelated client settings."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ import sys
6
+ import tomllib
7
+ from pathlib import Path
8
+
9
+ from .core import _id, read_file_bytes
10
+ from .exchange_packets import require, sha
11
+ from .member_routing import member_load_step, member_server, read_configuration, read_route, route_path, workspace_rule
12
+ from .setup import mcp_launch_args, safe_target, atomic_write, validate_server_name, skill_files, codex_trust_step
13
+ from .worker_channel import Caller, WorkerChannel, allowed_tools, packed, fingerprint
14
+
15
+
16
+ def launch(control, binding_id=None, role=None, project_id=None, offline=False):
17
+ args = mcp_launch_args(control)
18
+ if offline:
19
+ args[-1:-1] = ['--offline']
20
+ else:
21
+ args[-1:-1] = ['--binding', binding_id, '--role', role, '--project-id', project_id]
22
+ return {'command': sys.executable, 'args': args}
23
+
24
+
25
+ def fragments(control, server, binding_id=None, role=None, project_id=None, offline=False):
26
+ command = launch(control, binding_id, role, project_id, offline)
27
+ quote = lambda x: json.dumps(x, ensure_ascii=False)
28
+ toml = ('[mcp_servers.' + server + ']\ncommand = ' + quote(command['command']) + '\nargs = ['
29
+ + ', '.join(quote(x) for x in command['args']) + ']\n').encode('utf-8')
30
+ raw = packed({'mcpServers': {server: command}})
31
+ return toml, raw, command
32
+
33
+
34
+ class RoleConnection:
35
+ def __init__(self, channel):
36
+ self.channel, self.store = channel, channel.store
37
+
38
+ def invoke(self, mode, plan_id=None, binding_id=None, workspace_id=None, role=None, server_name=None, client='fragment'):
39
+ self.channel._governor()
40
+ if mode == 'execute':
41
+ return self.channel._execute('worker_connect', plan_id)
42
+ require(mode == 'plan', 'Use plan or execute.')
43
+ _id(binding_id, 'Binding'); _id(workspace_id, 'Workspace')
44
+ previous = self.store.get('worker_connections', binding_id + ':' + workspace_id) or {}
45
+ default_server = member_server(self.channel.project_id, binding_id, client=client)
46
+ legacy_server = member_server(self.channel.project_id, binding_id)
47
+ if server_name is None:
48
+ original = previous.get('server') if previous.get('client') == client else None
49
+ server_name = default_server if not original or original == legacy_server else original
50
+ validate_server_name(server_name)
51
+ require(role in {'governor', 'worker', 'reader'}, 'Choose an explicit role ceiling.')
52
+ member = WorkerChannel(self.channel.core.root, Caller(binding_id, role, self.channel.project_id))
53
+ member.core.store = member.store = self.store; member._auth('identify')
54
+ require(member.binding['role'] == role, 'Role ceiling exceeds the effective assigned role.')
55
+ assignment = next((x for x in member.binding['assignments'] if x['workspace_id'] == workspace_id), None)
56
+ require(assignment is not None, 'The target directory must be assigned to this member.')
57
+ root, _ = member._assignment(assignment['task_id'], workspace_id)
58
+ require(root != Path.home().resolve() and root.name.casefold() != '.codex', 'Choose a project directory, not user-level configuration.')
59
+ route = dict(project_id=self.channel.project_id, binding_id=binding_id, role=role, transport='stdio',
60
+ workspace_id=workspace_id)
61
+ retiring = None
62
+ if client == 'antigravity':
63
+ require(all(len(f'mcp_{server_name}_taskcarry_{action}') <= 64 for action in allowed_tools(member.caller)),
64
+ 'The connection name is too long for the qualified Antigravity tool names. Use the generated name or a shorter alias.',
65
+ 'CONNECTION_NAME_TOO_LONG')
66
+ if (server_name == default_server
67
+ and read_route(root, legacy_server) == {**route, 'server': legacy_server}):
68
+ retiring = legacy_server
69
+ toml, raw, command = fragments(self.channel.core.root, server_name, binding_id, role, self.channel.project_id)
70
+ prefix = '.taskcarry/member-' + binding_id + '/'
71
+ files = {prefix + 'codex.mcp.toml': toml, prefix + 'mcp.json': raw,
72
+ route_path(server_name): packed({**route, 'server': server_name}),
73
+ prefix + 'JOIN.md': ('# Join the existing project\n\n'
74
+ 'Use the generated connection for this member; keep the original conversation and task.\n'
75
+ f'Project: {self.channel.project_id}\nMember: {binding_id}\nRole ceiling: {role}\n\n'
76
+ f'If you use Codex, follow these steps. {codex_trust_step(root)}\n'
77
+ f'使用 Codex 时,请将邀请指定的工作目录 `{root}` 作为项目打开。若提示信任此文件夹,'
78
+ f'请选择信任,再回到原对话调用 `{server_name}` 核对自己的岗位。如果仍找不到服务,'
79
+ '重新加载项目连接后再试。\n\n'
80
+ 'After applying the connection and any required client reload, call native identify, worker_brief '
81
+ '(role/tasks/sources), and source_read for the exact current sources. Report actual returned identities '
82
+ 'and missing evidence. Configuration files alone do not prove native loading.\n'
83
+ 'Assignments are checked on each call; ordinary task changes do not require client configuration edits.\n'
84
+ 'Work inside assigned directories. Preserve existing task, staged files and work in progress. '
85
+ 'Share selected exact sources, hand back their revisions, then read the governor disposition. '
86
+ 'A checkpoint is not delivery; receipt is not business acceptance. User drives work; scheduling is optional.\n').encode('utf-8')}
87
+ # Skills come from this selected package, with their original paths. Never
88
+ # overwrite a user's modified copy just to generate a role connection.
89
+ skills = skill_files()
90
+ files.update(skills)
91
+ file_records = []
92
+ preserved_skills = []
93
+ for relative, data in files.items():
94
+ target = safe_target(root, relative)
95
+ before = read_file_bytes(target) if target.exists() else None
96
+ prior_hash = previous.get('files', {}).get(relative)
97
+ if retiring and relative in skills and before not in (None, data) and prior_hash != sha(before):
98
+ preserved_skills.append(relative)
99
+ continue
100
+ require(before is None or before == data or prior_hash == sha(before),
101
+ 'A generated file has user changes; preserve it and review the conflict.', 'CONNECTION_CONFLICT')
102
+ file_records.append({'path': relative, 'before': sha(before) if before is not None else None,
103
+ 'object': self.channel.core._snapshot(data)})
104
+ if client == 'codex':
105
+ target = safe_target(root, '.codex/config.toml')
106
+ before = read_file_bytes(target, 1024 * 1024) if target.exists() else b''
107
+ try:
108
+ existing = tomllib.loads(before.decode('utf-8-sig')) if before else {}
109
+ servers = existing.get('mcp_servers', {})
110
+ require(isinstance(servers, dict), 'Invalid MCP table.', 'CONNECTION_CONFLICT')
111
+ if server_name not in servers:
112
+ after = before + (b'\n' if before and not before.endswith(b'\n') else b'') + toml
113
+ elif servers[server_name] == command:
114
+ after = before
115
+ else:
116
+ old_fragment = previous.get('fragment', '').encode('utf-8')
117
+ require(old_fragment and before.count(old_fragment) == 1 and previous.get('server') == server_name,
118
+ 'The existing server block is not an unchanged managed block.', 'CONNECTION_CONFLICT')
119
+ after = before.replace(old_fragment, toml, 1)
120
+ expected = {**existing, 'mcp_servers': {**servers, server_name: command}}
121
+ require(tomllib.loads(after.decode('utf-8-sig')) == expected,
122
+ 'Connection merge would change other settings.', 'CONNECTION_CONFLICT')
123
+ except (ValueError, UnicodeError) as exc:
124
+ from .store import GovernanceError
125
+ raise GovernanceError('CONNECTION_CONFLICT', 'Keep the existing invalid or incompatible TOML unchanged.') from exc
126
+ file_records.append({'path': '.codex/config.toml', 'before': sha(before) if target.exists() else None,
127
+ 'object': self.channel.core._snapshot(after)})
128
+ elif client == 'antigravity':
129
+ relative = '.agents/mcp_config.json'
130
+ target = safe_target(root, relative)
131
+ before = read_file_bytes(target, 1024 * 1024) if target.exists() else None
132
+ existing = read_configuration(target)
133
+ servers = existing.setdefault('mcpServers', {})
134
+ renamed = retiring in servers
135
+ if renamed:
136
+ prior_commands = tomllib.loads(previous.get('fragment', '')).get('mcp_servers', {})
137
+ require(servers[retiring] == command or servers[retiring] == prior_commands.get(retiring),
138
+ 'The old workspace connection was customized. Preserve it and review the rename.',
139
+ 'CONNECTION_CONFLICT')
140
+ del servers[retiring]
141
+ if server_name in servers and servers[server_name] != command:
142
+ old = tomllib.loads(previous.get('fragment', '')).get('mcp_servers', {}).get(server_name)
143
+ require(old is not None and old == servers[server_name],
144
+ 'The existing workspace connector differs. Preserve it and review the conflict.', 'CONNECTION_CONFLICT')
145
+ if not renamed and servers.get(server_name) == command:
146
+ after = before
147
+ else:
148
+ servers[server_name] = command
149
+ after = packed(existing) + b'\n'
150
+ file_records.append({'path': relative, 'before': sha(before) if before is not None else None,
151
+ 'object': self.channel.core._snapshot(after)})
152
+ else:
153
+ require(client == 'fragment', 'Choose a project Codex/Antigravity connection or portable fragments.')
154
+ if client in ('codex', 'antigravity'):
155
+ target = safe_target(root, 'AGENTS.md')
156
+ before = read_file_bytes(target, 1024 * 1024) if target.exists() else None
157
+ file_records.append({'path': 'AGENTS.md', 'before': sha(before) if before is not None else None,
158
+ 'object': self.channel.core._snapshot(workspace_rule(before, server_name, previous_server=retiring))})
159
+ payload = {'binding_id': binding_id, 'workspace_id': workspace_id, 'task_id': assignment['task_id'],
160
+ 'role': role, 'server': server_name, 'client': client, 'files': file_records, 'fragment': toml.decode()}
161
+ # Large skill payloads stay in the selected object store, not MCP text.
162
+ manifest = self.channel.core._snapshot(packed(payload))
163
+ self.store.put('worker_connection_materials', manifest['sha256'], {'manifest': manifest,
164
+ 'files': file_records})
165
+ result = self.channel._plan('worker_connect', {'manifest': manifest, 'binding_id': binding_id,
166
+ 'workspace_id': workspace_id, 'client': client, 'file_count': len(file_records)},
167
+ {'member_revision': member.binding['revision']})
168
+ result['files'] = [{'path': x['path'], 'before': x['before'],
169
+ 'after': x['object']} for x in file_records]
170
+ result.update(server=server_name, project_id=self.channel.project_id,
171
+ project_name=self.store.get('config', 'project')['name'], role=role,
172
+ display_name=member.binding.get('display_name') or binding_id, binding_id=binding_id,
173
+ task_id=assignment['task_id'], workspace=str(root), client=client)
174
+ if preserved_skills:
175
+ result['preserved_skills'] = preserved_skills
176
+ return result
177
+
178
+ def apply(self, payload, guards):
179
+ from .exchange_packets import parse
180
+ blob = read_file_bytes(self.store.directory / 'objects' / payload['manifest']['sha256'])
181
+ require(sha(blob) == payload['manifest']['sha256'], 'Connection material manifest changed.')
182
+ plan = parse(blob)
183
+ member = WorkerChannel(self.channel.core.root, Caller(plan['binding_id'], plan['role'], self.channel.project_id))
184
+ member.core.store = member.store = self.store; member._auth('identify')
185
+ require(member.binding['revision'] == guards['member_revision'], 'Member changed after connection planning.', 'WORKER_BINDING_CHANGED')
186
+ root, _ = member._assignment(plan['task_id'], plan['workspace_id'])
187
+ # Check every destination before any write. Exact already-applied files
188
+ # allow an interrupted filesystem effect to finish its missing receipt.
189
+ for entry in plan['files']:
190
+ target = safe_target(root, entry['path'])
191
+ current = sha(read_file_bytes(target, 1024 * 1024)) if target.exists() else None
192
+ require(current in {entry['before'], entry['object']['sha256']},
193
+ 'Preserve changes made after the connection plan.', 'CONNECTION_CONFIG_CHANGED')
194
+ for entry in plan['files']:
195
+ target = safe_target(root, entry['path'])
196
+ data = read_file_bytes(self.store.directory / 'objects' / entry['object']['sha256'])
197
+ require(sha(data) == entry['object']['sha256'] and len(data) == entry['object']['size'], 'Connection object mismatch.')
198
+ current = sha(read_file_bytes(target, 1024 * 1024)) if target.exists() else None
199
+ require(current in {entry['before'], entry['object']['sha256']}, 'Target changed during merge.', 'CONNECTION_CONFIG_CHANGED')
200
+ if current != entry['object']['sha256']:
201
+ target.parent.mkdir(parents=True, exist_ok=True); safe_target(root, entry['path'])
202
+ atomic_write(target, data)
203
+ require(sha(read_file_bytes(target, 1024 * 1024)) == entry['object']['sha256'], 'Connection file verification failed.')
204
+ result = {'binding_id': plan['binding_id'], 'workspace_id': plan['workspace_id'], 'server': plan['server'],
205
+ 'client': plan['client'], 'files': {x['path']: x['object']['sha256'] for x in plan['files']},
206
+ 'fragment': plan['fragment']}
207
+ self.store.put('worker_connections', plan['binding_id'] + ':' + plan['workspace_id'], result)
208
+ next_step = member_load_step(plan['server'], 'native worker_brief (role)')
209
+ if plan['client'] == 'codex':
210
+ next_step = codex_trust_step(root) + ' ' + next_step
211
+ elif plan['client'] == 'fragment':
212
+ next_step = 'Apply the connection in your AI tool. If you use Codex, ' + codex_trust_step(root) + ' ' + next_step
213
+ return {k: v for k, v in {**result, 'effects_executed': True, 'native_loading_verified': False,
214
+ 'next_step': next_step}.items()
215
+ if k not in {'fragment', 'files'}}