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,118 @@
1
+ """Host-reviewed issue and fix records with honest local adoption evidence.
2
+
3
+ These records neither execute repairs nor certify the truth of a supplied
4
+ reference. The host reviews that evidence; the engine preserves its condition
5
+ and revision, and independently inspects project-local setup when asked.
6
+ """
7
+ from __future__ import annotations
8
+
9
+ from .core import Core, _id
10
+ from .setup import runtime_info
11
+ from .store import GovernanceError, now
12
+
13
+
14
+ def _text(value, label):
15
+ if not isinstance(value, str) or not value.strip():
16
+ raise GovernanceError('INVALID_ARGUMENT', label + ' must be nonempty text.')
17
+ return value
18
+
19
+
20
+ def _revision(expected, previous):
21
+ if expected is not None and (isinstance(expected, bool) or not isinstance(expected, int) or expected < 0):
22
+ raise GovernanceError('INVALID_ARGUMENT', 'expected_revision must be a nonnegative integer.')
23
+ actual = previous['revision'] if previous else 0
24
+ if (previous is not None and expected != actual) or (previous is None and expected not in (None, 0)):
25
+ raise GovernanceError('REVISION_CONFLICT', 'The record changed; review its current revision before updating.',
26
+ {'expected_revision': expected, 'actual_revision': actual})
27
+ return actual + 1
28
+
29
+
30
+ class Maintenance(Core):
31
+ def _record(self, collection, key, body, expected_revision):
32
+ """Called inside one transaction, including the matching audit event."""
33
+ if expected_revision is not None and (isinstance(expected_revision, bool) or not isinstance(expected_revision, int) or expected_revision < 0):
34
+ raise GovernanceError('INVALID_ARGUMENT', 'expected_revision must be a nonnegative integer.')
35
+ previous = self.store.get(collection, key)
36
+ if previous and all(previous.get(name) == value for name, value in body.items()):
37
+ # Identical observations are not new work and need no empty event.
38
+ return previous, True
39
+ revision = _revision(expected_revision, previous)
40
+ timestamp = now()
41
+ record = dict(body, revision=revision, created_at=previous['created_at'] if previous else timestamp,
42
+ updated_at=timestamp)
43
+ self.store.put(collection, key, record)
44
+ self.store.put(collection + '_history', key + '.' + str(revision), record)
45
+ self.store.event({'issues': 'issue_recorded', 'fixes': 'fix_recorded'}[collection], record)
46
+ return record, False
47
+
48
+ def issue(self, issue_id, condition, summary, state='open', resolution_ref='', expected_revision=None):
49
+ issue_id = _id(issue_id, 'Issue ID')
50
+ _text(condition, 'condition')
51
+ _text(summary, 'summary')
52
+ if state not in ('open', 'resolved'):
53
+ raise GovernanceError('INVALID_STATE', 'Issue state must be open or resolved.')
54
+ if not isinstance(resolution_ref, str):
55
+ raise GovernanceError('INVALID_ARGUMENT', 'resolution_ref must be text.')
56
+ if state == 'resolved':
57
+ _text(resolution_ref, 'A resolved issue needs a reviewed resolution reference')
58
+ elif resolution_ref:
59
+ raise GovernanceError('INVALID_ARGUMENT', 'An open issue must not retain a current resolution reference.')
60
+ with self.store.transaction():
61
+ previous = self.store.get('issues', issue_id)
62
+ if previous and previous['condition'] != condition and state == 'resolved':
63
+ raise GovernanceError('CONDITION_CHANGED_REOPEN',
64
+ 'A changed condition must be recorded open before a new resolution is reviewed.')
65
+ body = {'issue_id': issue_id, 'condition': condition, 'summary': summary,
66
+ 'state': state, 'resolution_ref': resolution_ref, 'evidence_scope': 'host_reviewed_reference'}
67
+ record, reused = self._record('issues', issue_id, body, expected_revision)
68
+ return {'issue': record, 'reused': reused}
69
+
70
+ def _adoption(self, fix):
71
+ """Check the existing disk/setup evidence; do not install or reload."""
72
+ info = runtime_info(self.root)
73
+ runtime = info.get('loaded_runtime') or {}
74
+ version_matches = info.get('managed_setup_version') == fix['version'] == runtime.get('version')
75
+ reasons = []
76
+ for valid, reason in (
77
+ (info.get('setup_status') == 'installed', 'setup_not_installed'),
78
+ (not info.get('pending_installation'), 'setup_incomplete'),
79
+ (version_matches, 'version_not_matched'),
80
+ (info.get('managed_runtime_matches_disk') is True, 'runtime_disk_not_matched'),
81
+ (info.get('managed_files_match') is True and info.get('generated_files_match') is True,
82
+ 'managed_files_not_matched'),
83
+ ):
84
+ if not valid:
85
+ reasons.append(reason)
86
+ matched = not reasons
87
+ return {'status': 'installed_version_matches' if matched else 'recorded',
88
+ 'installed_version_matches': matched, 'fix_version': fix['version'],
89
+ 'managed_setup_version': info.get('managed_setup_version'),
90
+ 'current_package_version': runtime.get('version'),
91
+ 'source_sha256': runtime.get('source_sha256'), 'source_fingerprint_scope': 'on_disk',
92
+ 'setup_status': info.get('setup_status'), 'reasons': reasons,
93
+ 'host_reload_unverified': True, 'loaded_code_verified': False,
94
+ 'package_upgrade_performed': False, 'repair_execution_verified': False}
95
+
96
+ def fix(self, fix_id, issue_id, version, evidence_refs, summary='', expected_revision=None):
97
+ fix_id = _id(fix_id, 'Fix ID')
98
+ issue_id = _id(issue_id, 'Issue ID')
99
+ _text(version, 'version')
100
+ if not isinstance(summary, str):
101
+ raise GovernanceError('INVALID_ARGUMENT', 'summary must be text.')
102
+ if not isinstance(evidence_refs, list) or not evidence_refs:
103
+ raise GovernanceError('INVALID_ARGUMENT', 'A fix needs at least one reviewed evidence reference.')
104
+ for ref in evidence_refs:
105
+ _text(ref, 'evidence_refs item')
106
+ refs = sorted(set(evidence_refs))
107
+ with self.store.transaction():
108
+ issue = self.store.get('issues', issue_id)
109
+ if not issue:
110
+ raise GovernanceError('ISSUE_NOT_FOUND', 'Register the issue before linking a fix.')
111
+ body = {'fix_id': fix_id, 'issue_id': issue_id, 'condition': issue['condition'],
112
+ 'version': version, 'evidence_refs': refs, 'summary': summary,
113
+ 'evidence_scope': 'host_reviewed_reference'}
114
+ record, reused = self._record('fixes', fix_id, body, expected_revision)
115
+ # Installation is a fresh read, never a persistent claim derived from
116
+ # a past check. Reading the same fix after setup can show new adoption
117
+ # without emitting a duplicate fix event or closing its issue.
118
+ return {'fix': record, 'reused': reused, 'adoption': self._adoption(record)}
taskcarry/mcp.py ADDED
@@ -0,0 +1,183 @@
1
+ """Bounded synchronous MCP stdio server; no network or arbitrary method dispatch."""
2
+ from __future__ import annotations
3
+
4
+ import json
5
+ from pathlib import Path
6
+ import sys
7
+
8
+ from .cli import envelope_error
9
+
10
+ PROTOCOL_VERSIONS = ("2025-11-25", "2025-06-18", "2025-03-26", "2024-11-05")
11
+ MAX_LINE_BYTES = 1024 * 1024
12
+
13
+
14
+ from .contracts import SCHEMAS, validate
15
+
16
+
17
+ DESCRIPTIONS = {
18
+ "identity": "Read a portable project identity or explicitly plan and adopt one for legacy state. Retains previous source aliases; no package update.",
19
+ "codex": "Use a selected supported Codex executable to inspect capabilities, list or read bounded chat history. No turns or messages; host startup may write its own caches.",
20
+ "update_source": "Explicitly register the official release channel and current artifact/method identities. Does not install or schedule.",
21
+ "update_check": "Read bounded official release metadata and compare the selected channel. No local record, installation or claim of host loading.",
22
+ "update_assess": "Explicitly save an applicability assessment for a content-bound release check; reuse unchanged input. Does not install.",
23
+ "onboarding": "Start, read or update a resumable onboarding checklist tied to actual local identities and qualified host evidence.",
24
+ "schedule_plan": "Prepare durable original-chat governance instructions. The host must create/read back its schedule; no scheduler execution here.",
25
+ "preserve": "Plan or execute exact local Git file saving, preserving unrelated staged and working changes. Not submission or remote backup.",
26
+ "connect": "Plan or apply the exact generated MCP block to a project configuration, preserving other settings. Host trust/reload and native acceptance remain separate.",
27
+ "identify": "Read the selected location's state format and source identity without initialization or migration.",
28
+ "context": "Read bounded, source-qualified context for a named task, with pagination and missing evidence. No acknowledgment or execution.",
29
+ "governance": "Inspect package, managed methods and user-rule identities, or explicitly record a content-bound review. No install or host reload.",
30
+ "upgrade": "Explicitly build or repair the derived current-work index. Preserve original records and events; no package update.",
31
+ "observe": "Save host-reviewed evidence references and relationships with revision checks. Does not read chats or grant permissions.",
32
+ "run": "Freeze selected record identities, inspect them, or record their verified terminal state. No Git effects or claim that the whole project is complete.",
33
+ "issue": "Record a concrete condition and its resolution reference. Changed conditions reopen review; never mask an unfinished operation.",
34
+ "fix": "Link a defect to a version and validation references. Compare actual project setup evidence; no installation or claim of host reload.",
35
+ "status": "Read current tasks, deliveries and actionable issues without creating state.",
36
+ "agenda": "Read a bounded, paginated current-work selection for the existing agent. No execution, retry, scheduling or completion claim.",
37
+ "doctor": "Read runtime prerequisites and project support; no installation or repair.",
38
+ "task": "Create or update a task's retained current state. This does not declare a delivery.",
39
+ "checkpoint": "Save exact files and Git work layers for later continuation; not a submission.",
40
+ "restore": "Restore into an empty independent directory, or verify the same recorded destination and finish its missing receipt without replaying effects. Preserve the original and later user changes.",
41
+ "artifact": "Register content identity, task relationship, optional verified backup and decision.",
42
+ "experience": "Register a conditional recovery rule from the fixed allowed actions; no executable shell.",
43
+ "workspace": "Register an existing local Git workspace for bounded governance operations.",
44
+ "submit": "Explicitly deliver exact frozen commit changes. Cumulative replacement needs lineage evidence.",
45
+ "reconcile": "Plan delivery acceptance, or execute an existing plan with exact baseline conditions. No push.",
46
+ "adopt": "Plan or execute an exact baseline adoption while retaining workspace work. No push.",
47
+ }
48
+
49
+ from .cycle_contracts import DESCRIPTIONS as CYCLE_DESCRIPTIONS
50
+ from .workbench_contracts import DESCRIPTIONS as WORKBENCH_DESCRIPTIONS
51
+ from .recovery_contracts import DESCRIPTIONS as RECOVERY_DESCRIPTIONS
52
+ DESCRIPTIONS.update(CYCLE_DESCRIPTIONS)
53
+ DESCRIPTIONS.update(WORKBENCH_DESCRIPTIONS)
54
+ DESCRIPTIONS.update(RECOVERY_DESCRIPTIONS)
55
+ from .transfer_contracts import DESCRIPTIONS as TRANSFER_DESCRIPTIONS
56
+ DESCRIPTIONS.update(TRANSFER_DESCRIPTIONS)
57
+ from .discovery_contracts import DESCRIPTIONS as DISCOVERY_DESCRIPTIONS
58
+ DESCRIPTIONS.update(DISCOVERY_DESCRIPTIONS)
59
+ from .worker_tools import DESCRIPTIONS as WORKER_DESCRIPTIONS
60
+ DESCRIPTIONS.update(WORKER_DESCRIPTIONS)
61
+ from .exchange_contracts import DESCRIPTIONS as EXCHANGE_DESCRIPTIONS, OFFLINE_ACTIONS
62
+ DESCRIPTIONS.update(EXCHANGE_DESCRIPTIONS)
63
+
64
+
65
+ def tools_list(caller=None, offline=False):
66
+ from .worker_channel import allowed_tools
67
+ from .worker_tools import READ_ACTIONS
68
+ return [{"name": "taskcarry_" + action, "description": DESCRIPTIONS[action], "inputSchema": definition,
69
+ "annotations": {"readOnlyHint": action in READ_ACTIONS or action in {"schedule_plan", "update_check"},
70
+ "openWorldHint": action in {"codex", "update_check"}}}
71
+ for action, definition in SCHEMAS.items()
72
+ if (action in OFFLINE_ACTIONS if offline else caller is None or action in allowed_tools(caller))]
73
+
74
+
75
+ def rpc_error(request_id, code, message):
76
+ return {"jsonrpc": "2.0", "id": request_id, "error": {"code": code, "message": message}}
77
+
78
+
79
+ class Server:
80
+ def __init__(self, project, invoke=None, caller=None, offline=False):
81
+ self.project = Path(project).resolve()
82
+ self.initialized = False
83
+ self.invoke = invoke
84
+ self.caller = caller
85
+ self.offline = offline
86
+
87
+ def handle(self, request):
88
+ if not isinstance(request, dict):
89
+ return rpc_error(None, -32600, "JSON-RPC batches and non-object messages are unsupported")
90
+ request_id = request.get("id")
91
+ if request.get("jsonrpc") != "2.0" or not isinstance(request.get("method"), str):
92
+ return rpc_error(request_id, -32600, "Invalid JSON-RPC request")
93
+ if "id" in request and (isinstance(request_id, bool) or not isinstance(request_id, (str, int))):
94
+ return rpc_error(None, -32600, "Request id must be a string or integer")
95
+ method = request["method"]
96
+ # Notifications never invoke tools or change project state.
97
+ if "id" not in request:
98
+ return None
99
+ params = request.get("params", {})
100
+ if not isinstance(params, dict):
101
+ return rpc_error(request_id, -32602, "params must be an object")
102
+ if method == "initialize":
103
+ version = params.get("protocolVersion")
104
+ if not isinstance(version, str) or not isinstance(params.get("capabilities"), dict) or not isinstance(params.get("clientInfo"), dict):
105
+ return rpc_error(request_id, -32602, "initialize requires protocolVersion, capabilities and clientInfo")
106
+ self.initialized = True
107
+ from . import __version__
108
+ result = {"protocolVersion": version if version in PROTOCOL_VERSIONS else PROTOCOL_VERSIONS[0],
109
+ "capabilities": {"tools": {"listChanged": False}},
110
+ "serverInfo": {"name": "taskcarry", "version": __version__},
111
+ "instructions": "Project root is fixed by server startup. Use exact task and file evidence. Plan before execute. Tool availability is not permission to expand user scope."}
112
+ if self.caller is not None and self.caller.role_ceiling == 'worker' and not self.offline:
113
+ result["instructions"] += (
114
+ " When the user returns to this project's work in chat, use taskcarry_worker_brief to check "
115
+ "the current assignment and relevant shared updates. Open changed revisions before acting. "
116
+ "The user's ordinary project request is sufficient; keep idle chats idle.")
117
+ elif method == "ping":
118
+ result = {}
119
+ elif not self.initialized:
120
+ return rpc_error(request_id, -32002, "Initialize the MCP session first")
121
+ elif method == "tools/list":
122
+ if params.get("cursor"):
123
+ return rpc_error(request_id, -32602, "This server has no paginated tool cursor")
124
+ result = {"tools": tools_list(self.caller, self.offline)}
125
+ elif method == "tools/call":
126
+ name = params.get("name")
127
+ if not isinstance(name, str) or name not in {"taskcarry_" + a for a in SCHEMAS}:
128
+ return rpc_error(request_id, -32602, "Unknown tool")
129
+ action = name[len("taskcarry_"):]
130
+ arguments = params.get("arguments", {})
131
+ try:
132
+ validate(arguments, SCHEMAS[action])
133
+ except ValueError as exc:
134
+ return rpc_error(request_id, -32602, str(exc))
135
+ try:
136
+ invoke = self.invoke
137
+ if self.offline:
138
+ from .exchange_contracts import offline_invoke
139
+ invoke = offline_invoke
140
+ if invoke is None:
141
+ from .api import invoke
142
+ value = (invoke(self.project, action, arguments, caller=self.caller)
143
+ if self.caller is not None else invoke(self.project, action, arguments))
144
+ output = {"ok": True, "result": value}
145
+ failed = False
146
+ except Exception as exc:
147
+ output, failed = envelope_error(exc), True
148
+ result = {"content": [{"type": "text", "text": json.dumps(output, ensure_ascii=False, separators=(',', ':'))}], "isError": failed}
149
+ if version_supports_structured(self):
150
+ result["structuredContent"] = output
151
+ else:
152
+ return rpc_error(request_id, -32601, "Method not found")
153
+ if method == "initialize":
154
+ self.protocol = result["protocolVersion"]
155
+ return {"jsonrpc": "2.0", "id": request_id, "result": result}
156
+
157
+
158
+ def version_supports_structured(server):
159
+ return getattr(server, "protocol", "") in {"2025-06-18", "2025-11-25"}
160
+
161
+
162
+ def serve(project, stdin=None, stdout=None, caller=None, offline=False):
163
+ input_stream = stdin or sys.stdin
164
+ output_stream = stdout or sys.stdout
165
+ server = Server(project, caller=caller, offline=offline)
166
+ while True:
167
+ line = input_stream.readline(MAX_LINE_BYTES + 1)
168
+ if not line:
169
+ return 0
170
+ if len(line.encode("utf-8")) > MAX_LINE_BYTES or (len(line) > MAX_LINE_BYTES and not line.endswith("\n")):
171
+ response = rpc_error(None, -32600, "Message exceeds 1 MiB limit")
172
+ output_stream.write(json.dumps(response) + "\n")
173
+ output_stream.flush()
174
+ return 1
175
+ try:
176
+ response = server.handle(json.loads(line))
177
+ except (json.JSONDecodeError, UnicodeError):
178
+ response = rpc_error(None, -32700, "Invalid JSON")
179
+ except Exception:
180
+ response = rpc_error(None, -32603, "Internal protocol error")
181
+ if response is not None:
182
+ output_stream.write(json.dumps(response, ensure_ascii=False) + "\n")
183
+ output_stream.flush()
@@ -0,0 +1,184 @@
1
+ """Set up a local WorkBuddy worker from an invitation issued by its existing project."""
2
+ import hashlib
3
+ from contextlib import ExitStack
4
+ import json
5
+ import re
6
+ import time
7
+ from pathlib import Path
8
+ from urllib.error import HTTPError, URLError
9
+ from urllib.parse import urlsplit
10
+ from urllib.request import HTTPRedirectHandler, ProxyHandler, Request, build_opener
11
+
12
+ from .setup import atomic_write, encoded, safe_target, setup_lock
13
+ from .member_routing import (configuration_bytes, connector_path, host_directory, member_load_step, member_server,
14
+ parse_configuration, read_configuration, read_route, route_path,
15
+ workbuddy_scope, workspace_rule)
16
+
17
+
18
+ def fingerprint(value):
19
+ return hashlib.sha256(encoded(value)).hexdigest()
20
+
21
+
22
+ def checked_url(value):
23
+ if not isinstance(value, str) or not value.isascii() or any(c.isspace() for c in value):
24
+ raise ValueError("Use the HTTPS invitation URL supplied by your project manager.")
25
+ url = urlsplit(value)
26
+ if (url.scheme != "https" or not url.hostname or url.username is not None or url.password is not None
27
+ or url.query or url.fragment or "\\" in value or not re.fullmatch(r"(?:/[A-Za-z0-9_-]+)*/join", url.path)):
28
+ raise ValueError("Use the HTTPS invitation ending in /join supplied by your project manager.")
29
+ return url
30
+
31
+
32
+ class NoRedirect(HTTPRedirectHandler):
33
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
34
+ return None
35
+
36
+
37
+ def exchange(url, confirmation=None):
38
+ parsed = checked_url(url)
39
+ # A tailnet address is reached directly from the admitted device. Keep the
40
+ # host's ordinary proxy selection for other configured HTTPS providers.
41
+ handlers = [NoRedirect()]
42
+ if parsed.hostname.endswith(".ts.net"):
43
+ handlers.append(ProxyHandler({}))
44
+ headers = {"Accept": "application/json"}
45
+ if confirmation:
46
+ headers["TaskCarry-Confirm"] = confirmation
47
+ request = Request(url, headers=headers, data=b"" if confirmation else None)
48
+ try:
49
+ with build_opener(*handlers).open(request, timeout=12) as response:
50
+ raw = response.read(16385)
51
+ if response.headers.get_content_type() != "application/json" or len(raw) > 16384:
52
+ raise ValueError("The address did not return a TaskCarry invitation.")
53
+ return json.loads(raw)
54
+ except HTTPError as exc:
55
+ raise ValueError(f"The project declined this invitation request (HTTP {exc.code}). Check the current invitation and device.") from None
56
+ except (URLError, TimeoutError, OSError):
57
+ raise ValueError("The project invitation is unreachable from this computer.") from None
58
+
59
+
60
+ def join_workspace(workspace, *, invitation, mode="plan", plan_id=None, settings_scope="auto",
61
+ edition="workbuddy", fetch=exchange, home=None):
62
+ """Preview without local writes. Apply only a current plan in the selected workspace."""
63
+ address = checked_url(invitation)
64
+ root = Path(workspace).resolve(strict=True)
65
+ if not root.is_dir() or root in {Path.home().resolve(), Path(root.anchor)} or root.name.casefold() in {".workbuddy", ".codex"}:
66
+ raise ValueError("Select the working chat's project folder.")
67
+ if mode not in {"plan", "execute"} or (mode == "execute" and not plan_id):
68
+ raise ValueError("Preview the invitation, then execute with its plan_id.")
69
+ response = fetch(invitation)
70
+ if not isinstance(response, dict):
71
+ raise ValueError("The project invitation is incomplete.")
72
+ offer = response.get("offer")
73
+ required = {"schema", "project", "project_id", "binding_id", "binding_revision", "role", "role_label", "task_id", "expires_at", "endpoint"}
74
+ if not isinstance(offer, dict):
75
+ raise ValueError("The project invitation is incomplete.")
76
+ schema = offer.get("schema")
77
+ join_by = offer.get("expires_at")
78
+ if schema == "taskcarry.worker-invite.v1":
79
+ if type(join_by) is not int:
80
+ raise ValueError("The temporary project invitation needs an expiration time.")
81
+ work_until = join_by
82
+ elif schema == "taskcarry.worker-invite.v2":
83
+ required.add("membership_expires_at")
84
+ work_until = offer.get("membership_expires_at")
85
+ else:
86
+ raise ValueError("Unrecognized project invitation format.")
87
+ now = time.time()
88
+ if any(t is not None and (type(t) is not int or t <= now) for t in (join_by, work_until)):
89
+ raise ValueError("The invitation or the assigned membership is no longer current.")
90
+ if (set(offer) != required
91
+ or offer.get("role") != "worker" or type(offer.get("binding_revision")) is not int or offer["binding_revision"] < 1
92
+ or not all(isinstance(offer[k], str) and 0 < len(offer[k]) <= 256
93
+ for k in ("project", "project_id", "binding_id", "role_label", "task_id"))
94
+ or offer.get("endpoint") != address._replace(path=address.path[:-4]+"mcp").geturl()
95
+ or response.get("offer_id") != fingerprint(offer)):
96
+ raise ValueError("The invitation does not describe a current worker at this same HTTPS origin.")
97
+ server = member_server(offer["project_id"], offer["binding_id"])
98
+ host = host_directory(edition, home)
99
+ if root == host:
100
+ raise ValueError("Open a work folder separate from the WorkBuddy settings directory.")
101
+ identity = {k: offer[k] for k in ("project_id", "binding_id", "task_id", "role")}
102
+ route_file = safe_target(root, route_path(server))
103
+ rules = safe_target(root, "AGENTS.md")
104
+
105
+ def prepare():
106
+ prior = read_route(root, server)
107
+ if prior and any(prior.get(k) != identity[k] for k in ("project_id", "binding_id", "role")):
108
+ raise ValueError("The workspace route already belongs to a different member.")
109
+ scope, reason = workbuddy_scope(settings_scope, prior, host, server)
110
+ target = connector_path(root, host, scope)
111
+ before_config = configuration_bytes(target)
112
+ config = parse_configuration(before_config)
113
+ other = dict(config)
114
+ other["mcpServers"] = {k: v for k, v in config.get("mcpServers", {}).items() if k != server}
115
+ if rules.exists() and (not rules.is_file() or rules.stat().st_size > 1024 * 1024):
116
+ raise ValueError("Preserve the existing workspace instructions and review their format.")
117
+ before_rule = rules.read_bytes() if rules.exists() else None
118
+ after_rule = workspace_rule(before_rule, server)
119
+ route = dict(identity, server=server, transport="https", settings_scope=scope, edition=edition)
120
+ basis = [str(root), str(target), server, response["offer_id"], other, route, hashlib.sha256(after_rule).hexdigest()]
121
+ return dict(scope=scope, reason=reason, target=target, config=config, before_config=before_config,
122
+ before_rule=before_rule, after_rule=after_rule, route=route, plan_id=fingerprint(basis))
123
+
124
+ prepared = prepare()
125
+ scope, plan = prepared["scope"], prepared["plan_id"]
126
+ summary = {"project": offer["project"], "role": offer["role_label"], "role_ceiling": offer["role"],
127
+ "project_id": offer["project_id"], "binding_id": offer["binding_id"], "task_id": offer["task_id"],
128
+ "expires_at": join_by, "join_expires_at": join_by, "membership_expires_at": work_until,
129
+ "server": server, "settings_scope": scope, "scope_reason": prepared["reason"],
130
+ "configuration_visibility": "all_user_workspaces" if scope == "user" else "this_workspace",
131
+ "target": str(prepared["target"]), "route": route_path(server), "workspace_rule": "AGENTS.md"}
132
+ if response.get("chat_sharing") == "taskcarry.workbuddy.visible-turns.v1":
133
+ summary["conversation_setup"] = {"action":"workbuddy_chat", "server":server,
134
+ "sharing_default":"off", "conversation_id":"auto", "settings_scope":scope,
135
+ "edition":edition}
136
+ if mode == "plan":
137
+ return {**summary, "plan_id": plan, "state": "planned", "effects_executed": False}
138
+ if plan != plan_id:
139
+ raise ValueError("The project invitation or local settings changed. Preview again.")
140
+ approved = fetch(invitation, response["offer_id"])
141
+ if not isinstance(approved, dict) or approved.get("offer_id") != response["offer_id"]:
142
+ raise ValueError("The project invitation changed. Preview again.")
143
+ token = approved.get("access_token")
144
+ if not isinstance(token, str) or not re.fullmatch(r"[A-Za-z0-9_-]{32,128}", token):
145
+ raise ValueError("The project did not issue a valid session credential.")
146
+ entry = {"type": "streamableHttp", "url": offer["endpoint"], "headers": {"Authorization": "Bearer " + token}}
147
+ with ExitStack() as locks:
148
+ locks.enter_context(setup_lock(root))
149
+ if scope == "user":
150
+ locks.enter_context(setup_lock(host))
151
+ current = prepare()
152
+ if current["plan_id"] != plan:
153
+ raise ValueError("Local settings changed. Preview again.")
154
+ target, config, route = current["target"], current["config"], current["route"]
155
+ servers = config.setdefault("mcpServers", {})
156
+ if server in servers and servers[server] != entry:
157
+ raise ValueError("An existing server entry differs. Preserve it and review the connection.")
158
+ changes = []
159
+ if server not in servers:
160
+ servers[server] = entry
161
+ changes.append((target, current["before_config"], encoded(config) + b"\n"))
162
+ if current["before_rule"] != current["after_rule"]:
163
+ changes.append((rules, current["before_rule"], current["after_rule"]))
164
+ if read_route(root, server) != route:
165
+ changes.append((route_file, route_file.read_bytes() if route_file.exists() else None, encoded(route)))
166
+ applied = []
167
+ try:
168
+ for path, before, after in changes:
169
+ if (path.read_bytes() if path.exists() else None) != before:
170
+ raise ValueError("A destination changed. Preview again.")
171
+ atomic_write(path, after)
172
+ applied.append((path, before, after))
173
+ if read_configuration(target) != config or read_route(root, server) != route:
174
+ raise ValueError("The saved member connection changed. Review it before connecting.")
175
+ except Exception:
176
+ for path, before, after in reversed(applied):
177
+ if path.exists() and path.read_bytes() == after:
178
+ if before is None:
179
+ path.unlink()
180
+ else:
181
+ atomic_write(path, before)
182
+ raise
183
+ return {**summary, "state": "configured", "effects_executed": bool(changes), "native_loading_verified": False,
184
+ "next_step": member_load_step(server, "taskcarry_assignment")}
@@ -0,0 +1,145 @@
1
+ """Select and verify the member connection for a working chat."""
2
+ import hashlib
3
+ import json
4
+ import os
5
+ from pathlib import Path
6
+ import re
7
+
8
+ from .setup import encoded, is_link, safe_target, validate_server_name
9
+
10
+
11
+ def member_server(project_id, binding_id, *, client=None):
12
+ digest = hashlib.sha256(encoded([project_id, binding_id])).hexdigest()
13
+ prefix = 'taskcarry-' if client == 'antigravity' else 'taskcarry-member-'
14
+ return prefix + digest[:16]
15
+
16
+
17
+ def route_path(server):
18
+ return '.taskcarry/member-routes/' + validate_server_name(server) + '.json'
19
+
20
+
21
+ def member_load_step(server, native_tool):
22
+ return (f'In the original work folder, call {native_tool} through {server} and compare the project and '
23
+ "role with the toolkit's local member_verify CLI action, passing that native role response "
24
+ 'as observed. A match means you can start work. If the new connection is missing '
25
+ 'or you are unsure it has loaded, fully quit and reopen the AI app (on Windows use Exit in '
26
+ 'the system tray if present; on macOS use Command-Q). Return to the same chat, accept the '
27
+ 'workspace or connection trust prompt if shown, and repeat the native identity check.')
28
+
29
+
30
+ def _route_paragraph(server, *, previous_wording=False):
31
+ verify = ('`member_verify`' if previous_wording else
32
+ "the toolkit's local `member_verify` CLI action with the native role response as `observed`")
33
+ return (f'<!-- taskcarry-member: {server} -->\nWhen this chat is assigned to `{server}`, use only that TaskCarry '
34
+ f'connection. Read `{route_path(server)}` in this workspace. On joining, reloading or '
35
+ f'switching projects, compare the native role readback with this route using {verify} '
36
+ 'before sharing or writing. If it differs, stop and reselect the '
37
+ 'assigned connection. Other visible servers may belong to another chat.\n').encode()
38
+
39
+
40
+ def _replace_route_rule(raw, server, replacement):
41
+ marker = f'<!-- taskcarry-member: {server} -->'.encode()
42
+ if marker not in raw:
43
+ return raw
44
+ newline = b'\r\n' if marker + b'\r\n' in raw else b'\n'
45
+ for wording in (_route_paragraph(server), _route_paragraph(server, previous_wording=True)):
46
+ old = wording.replace(b'\n', newline)
47
+ if raw.count(marker) == 1 and old in raw:
48
+ return raw.replace(old, replacement.replace(b'\n', newline), 1)
49
+ raise ValueError('The existing workspace member rule was edited. Preserve it and review the difference.')
50
+
51
+
52
+ def workspace_rule(raw, server, *, previous_server=None):
53
+ """Replace only a recognized generated paragraph, preserving surrounding user bytes."""
54
+ raw = raw or b''
55
+ raw.decode('utf-8-sig')
56
+ paragraph = _route_paragraph(server)
57
+ marker = paragraph.split(b'\n', 1)[0]
58
+ if previous_server and previous_server != server:
59
+ raw = _replace_route_rule(raw, previous_server, b'' if marker in raw else paragraph)
60
+ if marker in raw:
61
+ return _replace_route_rule(raw, server, paragraph)
62
+ return raw + (b'\n\n' if raw else b'') + paragraph
63
+
64
+
65
+ def host_directory(edition, home=None):
66
+ if edition not in ('workbuddy', 'workbuddy-ai'):
67
+ raise ValueError('Choose the installed WorkBuddy desktop edition.')
68
+ override = os.environ.get('WORKBUDDY_CONFIG_DIR') if home is None else None
69
+ base = Path(override) if override else (Path.home() if home is None else Path(home)) / ('.' + edition)
70
+ if not base.is_absolute() or any(is_link(p) for p in (base, *base.parents)):
71
+ raise ValueError('Choose a regular local WorkBuddy settings directory.')
72
+ return base
73
+
74
+
75
+ def configuration_bytes(target):
76
+ if not target.exists():
77
+ return None
78
+ if not target.is_file() or target.stat().st_size > 1024 * 1024:
79
+ raise ValueError('Existing MCP configuration cannot be safely merged.')
80
+ return target.read_bytes()
81
+
82
+
83
+ def parse_configuration(raw):
84
+ config = json.loads(raw.decode('utf-8-sig')) if raw is not None else {}
85
+ if not isinstance(config, dict) or not isinstance(config.get('mcpServers', {}), dict):
86
+ raise ValueError('Preserve the existing MCP configuration and review its format.')
87
+ return config
88
+
89
+
90
+ def read_configuration(target):
91
+ return parse_configuration(configuration_bytes(target))
92
+
93
+
94
+ def workbuddy_scope(requested, prior, host, server):
95
+ if requested in ('project', 'user'):
96
+ return requested, 'explicit_choice'
97
+ if requested != 'auto':
98
+ raise ValueError('Choose auto, project or user for WorkBuddy settings.')
99
+ if prior.get('settings_scope') in ('project', 'user'):
100
+ return prior['settings_scope'], 'saved_workspace_choice'
101
+ user_config = safe_target(host, 'mcp.json')
102
+ try:
103
+ servers = read_configuration(user_config).get('mcpServers', {})
104
+ except (OSError, ValueError):
105
+ return 'project', 'existing_user_settings_unreadable'
106
+ for name in sorted(servers, key=lambda item: item != server):
107
+ entry = servers[name]
108
+ if (re.fullmatch(r'taskcarry-member-[a-f0-9]{16}', name) and isinstance(entry, dict)
109
+ and entry.get('type') == 'streamableHttp' and str(entry.get('url', '')).startswith('https://')
110
+ and str(entry.get('url')).endswith('/mcp') and isinstance(entry.get('headers'), dict)
111
+ and re.fullmatch(r'Bearer [A-Za-z0-9_-]{32,128}', str(entry['headers'].get('Authorization', '')))):
112
+ if name == server:
113
+ return 'user', 'existing_user_member_connector'
114
+ return 'user', 'previous_member_in_user_settings'
115
+ return 'project', 'workspace_default'
116
+
117
+
118
+ def connector_path(root, host, scope):
119
+ return safe_target(host, 'mcp.json') if scope == 'user' else safe_target(root, '.workbuddy/mcp.json')
120
+
121
+
122
+ def read_route(root, server):
123
+ path = safe_target(root, route_path(server))
124
+ if not path.exists():
125
+ return {}
126
+ if not path.is_file() or path.stat().st_size > 16384:
127
+ raise ValueError('The workspace member route is invalid.')
128
+ data = json.loads(path.read_text(encoding='utf-8-sig'))
129
+ if (not isinstance(data, dict) or data.get('server') != server or
130
+ not all(isinstance(data.get(k), str) and data[k] for k in ('project_id', 'binding_id', 'role'))):
131
+ raise ValueError('The workspace member route is invalid.')
132
+ return data
133
+
134
+
135
+ def verify_member(workspace, *, server, observed):
136
+ route = read_route(Path(workspace).resolve(strict=True), server)
137
+ if not route or not isinstance(observed, dict):
138
+ raise ValueError('Supply the member route and the identity returned by the native connector.')
139
+ fields = {'project_id': observed.get('project_id'), 'binding_id': observed.get('binding_id'),
140
+ 'role': observed.get('effective_role', observed.get('access'))}
141
+ if route.get('transport') == 'https':
142
+ fields['task_id'] = observed.get('task_id')
143
+ if any(route.get(k) != value for k, value in fields.items()):
144
+ raise ValueError('The native readback does not match this workspace member. Select the assigned connection before writing.')
145
+ return {'state': 'matched', 'server': server, **fields, 'read_only': True, 'effects_executed': False}