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
taskcarry/setup.py ADDED
@@ -0,0 +1,597 @@
1
+ """Additive project-scoped Codex setup. Never edits global or live Codex config."""
2
+ from __future__ import annotations
3
+
4
+ from contextlib import contextmanager
5
+ import hashlib
6
+ import json
7
+ import os
8
+ from pathlib import Path
9
+ import re
10
+ import stat
11
+ import sys
12
+ import tempfile
13
+ import uuid
14
+
15
+
16
+ class SetupError(ValueError):
17
+ def __init__(self, code, message, details=None):
18
+ super().__init__(message)
19
+ self.code, self.message, self.details = code, message, details
20
+
21
+
22
+ def digest(data):
23
+ return hashlib.sha256(data).hexdigest()
24
+
25
+
26
+ def safe_target(root, relative):
27
+ path = root / relative
28
+ if Path(relative).is_absolute() or ".." in Path(relative).parts:
29
+ raise SetupError("SETUP_PATH_ESCAPE", "Managed path is outside the project")
30
+ current = path
31
+ while current != root:
32
+ if is_link(current):
33
+ raise SetupError("SETUP_LINK", "Setup refuses links in managed paths", {"path": relative})
34
+ current = current.parent
35
+ if not path.resolve().is_relative_to(root):
36
+ raise SetupError("SETUP_PATH_ESCAPE", "Managed path escapes the project")
37
+ return path
38
+
39
+
40
+ def is_link(path):
41
+ if path.is_symlink():
42
+ return True
43
+ try:
44
+ return bool(getattr(path.lstat(), "st_file_attributes", 0) & getattr(stat, "FILE_ATTRIBUTE_REPARSE_POINT", 0))
45
+ except FileNotFoundError:
46
+ return False
47
+
48
+
49
+ def skill_sources():
50
+ package = Path(__file__).resolve().parent
51
+ for candidate in (package / "skill_data", package.parent / "skills"):
52
+ if candidate.is_dir():
53
+ sources = sorted(candidate.glob("*/SKILL.md"))
54
+ if len(sources) == 4:
55
+ return sources
56
+ raise SetupError("SKILLS_NOT_PACKAGED", "Four public skills were not found in the installed package")
57
+
58
+
59
+ def validate_server_name(value):
60
+ if not isinstance(value, str) or not re.fullmatch(r"[A-Za-z][A-Za-z0-9_-]{0,63}", value):
61
+ raise SetupError("SETUP_SERVER_NAME", "server_name must start with a letter and contain at most 64 letters, digits, underscores or hyphens")
62
+ return value
63
+
64
+
65
+ def mcp_launch_args(root):
66
+ """Pin the selected installation (or explicit source checkout), not cwd.
67
+
68
+ Isolated mode ignores PYTHONPATH and user site packages. The explicit path
69
+ also supports unpacked/source development without an editable installation.
70
+ If that package disappears, fail rather than fall back to another copy.
71
+ """
72
+ package_parent = Path(__file__).resolve().parent.parent
73
+ bootstrap = (
74
+ "import importlib.util, pathlib, runpy, sys\n"
75
+ "root = pathlib.Path(sys.argv.pop(1)).resolve()\n"
76
+ "sys.path.insert(0, str(root))\n"
77
+ "spec = importlib.util.find_spec('taskcarry')\n"
78
+ "if spec is None or spec.origin is None or pathlib.Path(spec.origin).resolve() != root / 'taskcarry' / '__init__.py':\n"
79
+ " raise SystemExit('Selected TaskCarry package is unavailable; regenerate setup with the intended runtime')\n"
80
+ "runpy.run_module('taskcarry', run_name='__main__', alter_sys=True)\n"
81
+ )
82
+ return ["-I", "-X", "utf8", "-c", bootstrap, str(package_parent),
83
+ "--project", str(root), "mcp"]
84
+
85
+
86
+ def skill_files():
87
+ """Copy the four public skills and their explicitly scoped Markdown references."""
88
+ files = {}
89
+ for source in skill_sources():
90
+ base = source.parent
91
+ if is_link(base):
92
+ raise SetupError("SETUP_LINK", "Skill directories cannot be links")
93
+ paths = [source]
94
+ references = base / "references"
95
+ if is_link(references):
96
+ raise SetupError("SETUP_LINK", "Skill references cannot be links")
97
+ if references.exists():
98
+ if not references.is_dir():
99
+ raise SetupError("SKILLS_NOT_PACKAGED", "Skill references must be a directory")
100
+ for path in sorted(references.rglob("*")):
101
+ if is_link(path):
102
+ raise SetupError("SETUP_LINK", "Skill references cannot contain links")
103
+ if path.is_file() and path.suffix == ".md":
104
+ paths.append(path)
105
+ for path in paths:
106
+ relative = path.relative_to(base).as_posix()
107
+ safe_target(base, relative)
108
+ files[f".agents/skills/{base.name}/{relative}"] = path.read_bytes()
109
+ return files
110
+
111
+
112
+ def planned_files(root, server_name="taskcarry", binding=None):
113
+ server_name = validate_server_name(server_name)
114
+ files = skill_files()
115
+ quote = lambda value: json.dumps(str(value), ensure_ascii=False)
116
+ args = mcp_launch_args(root)
117
+ fragment = (
118
+ "# Generated project-specific MCP fragment. This is NOT loaded automatically.\n"
119
+ "# Review and add this section to the appropriate Codex configuration.\n"
120
+ "# Do not copy this fragment to another machine: regenerate it there.\n"
121
+ "# Isolated UTF-8 startup pins the package selected during setup.\n"
122
+ f"[mcp_servers.{server_name}]\n"
123
+ f"command = {quote(sys.executable)}\n"
124
+ f"args = {json.dumps(args, ensure_ascii=False)}\n"
125
+ )
126
+ files[".taskcarry/codex.mcp.toml"] = fragment.encode("utf-8")
127
+ if binding and binding.get("scope") == "directory":
128
+ files[".taskcarry/workbench.json"] = encoded(dict(binding, format=2, server_name=server_name,
129
+ skills_directory=".agents/skills", mcp_fragment=".taskcarry/codex.mcp.toml",
130
+ host_loading_verified=False, native_acceptance_verified=False))
131
+ files[".taskcarry/workbench.md"] = (
132
+ "# TaskCarry shared directory connection\n\n"
133
+ "This directory shares one control connection; it does not select a chat's task.\n"
134
+ f"- Control: {quote(binding['control'])}\n"
135
+ f"- Directory: {quote(binding['target'])}\n"
136
+ f"- Workspace: {quote(binding['workspace'])}\n"
137
+ "Read the shared workbench routing entry using the original, verified chat ID.\n"
138
+ "Keep each chat's task, checkpoint and consumption evidence separate. Never select the first route when identity is unknown.\n"
139
+ f"{codex_trust_step(binding['target'])}\n"
140
+ "Verify native doctor/status in each active chat.\n"
141
+ ).encode("utf-8")
142
+ return files
143
+ if binding:
144
+ files[".taskcarry/workbench.json"] = encoded(dict(binding, format=1, server_name=server_name,
145
+ skills_directory=".agents/skills", mcp_fragment=".taskcarry/codex.mcp.toml",
146
+ host_loading_verified=False, native_acceptance_verified=False))
147
+ instructions = (
148
+ "# TaskCarry workbench binding\n\n"
149
+ "These are generated connection materials, not a second governance database.\n"
150
+ "Keep these machine-specific paths and identities private.\n\n"
151
+ f"- Control: {quote(binding['control'])}\n"
152
+ f"- Workbench directory: {quote(binding['target'])}\n"
153
+ f"- Workspace: {quote(binding['workspace'])}\n"
154
+ f"- Task: {quote(binding['task_id'])}\n"
155
+ f"- MCP server: {quote(server_name)}\n\n"
156
+ "The four Skills and their public Markdown references are in `.agents/skills`.\n"
157
+ "Read `taskcarry-project-setup/SKILL.md` there to continue onboarding.\n\n"
158
+ "1. Review `.taskcarry/codex.mcp.toml` and explicitly merge its server section into the host configuration, preserving existing settings.\n"
159
+ f"2. {codex_trust_step(binding['target'])}\n"
160
+ "3. In this workbench, call the native `taskcarry_doctor` and `taskcarry_status` tools on the named server. Check the control, registered workspace/task, checkpoint, interpreter and module path.\n"
161
+ "4. Record the actual native result and any remaining step in the existing governance records. A CLI or standalone stdio check is separate evidence.\n\n"
162
+ "Do not initialize another control, change task state, receive a delivery, upgrade the runtime, or activate a schedule merely to finish setup.\n"
163
+ )
164
+ files[".taskcarry/workbench.md"] = instructions.encode("utf-8")
165
+ return files
166
+
167
+
168
+ def read_manifest(root):
169
+ path = safe_target(root, ".taskcarry/setup-manifest.json")
170
+ if not path.exists():
171
+ return {"format": 1, "files": {}}
172
+ try:
173
+ result = json.loads(path.read_text(encoding="utf-8"))
174
+ except (ValueError, OSError) as exc:
175
+ raise SetupError("SETUP_MANIFEST_INVALID", "Setup manifest cannot be read") from exc
176
+ return validate_manifest(result, root)
177
+
178
+
179
+ def validate_manifest(result, root):
180
+ if not isinstance(result, dict) or result.get("format") not in (1, 2) or not isinstance(result.get("files"), dict):
181
+ raise SetupError("SETUP_MANIFEST_INVALID", "Setup manifest has an unsupported format")
182
+ for name, value in result["files"].items():
183
+ if not isinstance(name, str) or not isinstance(value, str) or not re.fullmatch(r"[0-9a-f]{64}", value):
184
+ raise SetupError("SETUP_MANIFEST_INVALID", "Invalid managed file record")
185
+ parts = Path(name).parts
186
+ skill_path = (len(parts) >= 4 and parts[:2] == (".agents", "skills")
187
+ and parts[2].startswith("taskcarry-")
188
+ and (parts[3:] == ("SKILL.md",)
189
+ or (len(parts) >= 5 and parts[3] == "references" and parts[-1].endswith(".md"))))
190
+ if not (name in {".taskcarry/codex.mcp.toml", ".taskcarry/workbench.json", ".taskcarry/workbench.md"} or skill_path):
191
+ raise SetupError("SETUP_MANIFEST_INVALID", "Manifest includes a path outside the managed setup scope")
192
+ safe_target(root, name)
193
+ if "server_name" in result:
194
+ validate_server_name(result["server_name"])
195
+ if "project" in result and result["project"] != str(root):
196
+ raise SetupError("SETUP_MANIFEST_INVALID", "Setup manifest belongs to a different project")
197
+ if "installation_id" in result and not re.fullmatch(r"[0-9a-f]{32}", str(result["installation_id"])):
198
+ raise SetupError("SETUP_MANIFEST_INVALID", "Invalid setup installation identity")
199
+ if "runtime" in result and not valid_runtime(result["runtime"]):
200
+ raise SetupError("SETUP_MANIFEST_INVALID", "Invalid managed runtime record")
201
+ if "binding" in result:
202
+ binding = result["binding"]
203
+ directory = result.get("format") == 2
204
+ fields = {"control", "target", "workspace", "scope"} if directory else {"control", "target", "workspace", "task_id"}
205
+ if (not isinstance(binding, dict) or set(binding) != fields
206
+ or binding.get("target") != str(root)
207
+ or not isinstance(binding.get("control"), str) or not Path(binding["control"]).is_absolute()
208
+ or not valid_identity(binding.get("workspace"))
209
+ or (binding.get("scope") != "directory" if directory else not valid_identity(binding.get("task_id")))):
210
+ raise SetupError("SETUP_MANIFEST_INVALID", "Invalid workbench binding")
211
+ elif result.get("format") == 2:
212
+ raise SetupError("SETUP_MANIFEST_INVALID", "Directory setup requires its explicit binding")
213
+ return result
214
+
215
+
216
+ @contextmanager
217
+ def setup_lock(root):
218
+ directory = safe_target(root, ".taskcarry")
219
+ directory.mkdir(parents=True, exist_ok=True)
220
+ path = safe_target(root, ".taskcarry/setup.lock")
221
+ stream = path.open("a+b")
222
+ try:
223
+ if os.name == "nt":
224
+ import msvcrt
225
+ stream.seek(0, os.SEEK_END)
226
+ if stream.tell() == 0:
227
+ stream.write(b"0")
228
+ stream.flush()
229
+ stream.seek(0)
230
+ try:
231
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
232
+ except OSError as exc:
233
+ raise SetupError("SETUP_BUSY", "Another setup process holds the project setup lock") from exc
234
+ else:
235
+ import fcntl
236
+ try:
237
+ fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
238
+ except OSError as exc:
239
+ raise SetupError("SETUP_BUSY", "Another setup process holds the project setup lock") from exc
240
+ yield
241
+ finally:
242
+ stream.close()
243
+
244
+
245
+ def atomic_write(path, content):
246
+ path.parent.mkdir(parents=True, exist_ok=True)
247
+ descriptor, temporary = tempfile.mkstemp(prefix=".taskcarry-", suffix=".tmp", dir=path.parent)
248
+ try:
249
+ with os.fdopen(descriptor, "wb") as stream:
250
+ stream.write(content)
251
+ stream.flush()
252
+ os.fsync(stream.fileno())
253
+ os.replace(temporary, path)
254
+ finally:
255
+ if os.path.exists(temporary):
256
+ os.unlink(temporary)
257
+
258
+
259
+ def encoded(value):
260
+ return json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False).encode("utf-8")
261
+
262
+
263
+ def file_hash(path):
264
+ if not path.exists():
265
+ return None
266
+ if not path.is_file():
267
+ raise SetupError("SETUP_CONFLICT", "A managed target is not a regular file", {"path": str(path)})
268
+ return digest(path.read_bytes())
269
+
270
+
271
+ def loaded_runtime():
272
+ # Import metadata identifies this process's package location and version
273
+ # label. The hash reads source files on disk, not already loaded bytecode;
274
+ # a long-lived process must restart after a package change.
275
+ from . import __version__
276
+ package = Path(__file__).resolve().parent
277
+ source = {p.name: digest(p.read_bytes()) for p in sorted(package.glob("*.py"))}
278
+ return {"version": __version__, "module_root": str(package),
279
+ "interpreter": sys.executable, "source_sha256": digest(encoded(source)),
280
+ "source_fingerprint_scope": "on_disk", "loaded_code_verified": False,
281
+ "requires_restart_after_package_change": True}
282
+
283
+
284
+ def valid_runtime(value):
285
+ return (isinstance(value, dict)
286
+ and all(isinstance(value.get(key), str) and value[key] for key in ("version", "module_root", "interpreter"))
287
+ and re.fullmatch(r"[0-9a-f]{64}", str(value.get("source_sha256"))) is not None)
288
+
289
+
290
+ def read_intent(root):
291
+ path = safe_target(root, ".taskcarry/setup-intent.json")
292
+ if not path.exists():
293
+ return None
294
+ try:
295
+ intent = json.loads(path.read_text(encoding="utf-8"))
296
+ body = {key: value for key, value in intent.items() if key != "intent_id"}
297
+ if (intent.get("format") != 1 or intent.get("action") != "install"
298
+ or intent.get("project") != str(root)
299
+ or intent.get("intent_id") != digest(encoded(body))
300
+ or not re.fullmatch(r"[0-9a-f]{32}", str(intent.get("installation_id")))
301
+ or not valid_runtime(intent.get("runtime"))
302
+ or not isinstance(intent.get("files"), dict)
303
+ or "manifest_before_sha256" not in intent
304
+ or (intent["manifest_before_sha256"] is not None
305
+ and not re.fullmatch(r"[0-9a-f]{64}", str(intent["manifest_before_sha256"])))
306
+ or not isinstance(intent.get("manifest_after"), dict)):
307
+ raise ValueError("Invalid setup intent")
308
+ validate_manifest(intent["manifest_after"], root)
309
+ validate_server_name(intent["server_name"])
310
+ for name, row in intent["files"].items():
311
+ safe_target(root, name)
312
+ if (not isinstance(row, dict)
313
+ or not re.fullmatch(r"[0-9a-f]{64}", str(row.get("after")))
314
+ or (row.get("before") is not None and not re.fullmatch(r"[0-9a-f]{64}", str(row["before"])))):
315
+ raise ValueError("Invalid setup file proof")
316
+ return intent
317
+ except (ValueError, TypeError, KeyError, AttributeError, OSError) as exc:
318
+ if isinstance(exc, SetupError):
319
+ raise
320
+ raise SetupError("SETUP_INTENT_INVALID", "Pending setup intent cannot be verified") from exc
321
+
322
+
323
+ def project_root(project):
324
+ supplied = Path(project).expanduser().absolute()
325
+ if any(is_link(p) for p in (supplied, *supplied.parents)):
326
+ raise SetupError("SETUP_LINK", "Setup requires a concrete project directory")
327
+ root = supplied.resolve()
328
+ if not root.is_dir():
329
+ raise SetupError("PROJECT_NOT_FOUND", "Setup requires an existing project directory")
330
+ return root
331
+
332
+
333
+ def valid_identity(value):
334
+ return isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]{0,99}", value) is not None
335
+
336
+
337
+ def workbench_binding(control, target, workspace, task_id, verify=True, binding_mode="task"):
338
+ if binding_mode not in ("task", "directory"):
339
+ raise SetupError("SETUP_BINDING_REQUIRED", "Use task or directory binding mode")
340
+ directory = binding_mode == "directory"
341
+ if not valid_identity(workspace) or (task_id is not None if directory else not valid_identity(task_id)):
342
+ raise SetupError("SETUP_BINDING_REQUIRED", "Workbench setup requires target, workspace and task_id together, with valid registered identities")
343
+ if target != control and safe_target(target, ".taskcarry/state.sqlite3").exists():
344
+ raise SetupError("SETUP_CONTROL_CONFLICT", "The target already contains a governance database; preserve its separate control")
345
+ binding = {"control": str(control), "target": str(target), "workspace": workspace,
346
+ **({"scope": "directory"} if directory else {"task_id": task_id})}
347
+ if verify:
348
+ from .integration import Integration
349
+ from .store import GovernanceError
350
+ try:
351
+ integration = Integration(control)
352
+ if not directory and integration.store.get("tasks", task_id) is None:
353
+ raise SetupError("SETUP_TASK_UNKNOWN", "Register the existing task in this control before workbench setup", {"task_id": task_id})
354
+ registered = integration._ws(workspace)
355
+ if registered != target:
356
+ raise SetupError("SETUP_WORKSPACE_MISMATCH", "The registered workspace does not match the target directory",
357
+ {"workspace": workspace, "registered": str(registered), "target": str(target)})
358
+ except GovernanceError as exc:
359
+ raise SetupError(exc.code, exc.message, exc.details) from exc
360
+ return binding
361
+
362
+
363
+ def check_binding(manifest, intent, binding):
364
+ recorded = (intent["manifest_after"] if intent else manifest).get("binding")
365
+ if (intent is None and recorded and binding and binding.get("scope") == "directory"
366
+ and "task_id" in recorded
367
+ and all(recorded.get(k) == binding.get(k) for k in ("control", "target", "workspace"))):
368
+ return # Explicit directory-mode preview/install; the old bytes are archived before mutation.
369
+ if recorded is not None and recorded != binding:
370
+ raise SetupError("SETUP_BINDING_CONFLICT", "This setup belongs to another workbench identity; use its recorded control, target, workspace and task_id",
371
+ {"recorded": recorded, "requested": binding})
372
+
373
+
374
+ def codex_trust_step(root):
375
+ return (f"Open {root} as a project in Codex and trust this folder if prompted. "
376
+ "Return to the original chat. If its MCP server is missing, reload the connection and check again.")
377
+
378
+
379
+ def connection_result(result, control, root, binding):
380
+ installed = result["mode"] == "install"
381
+ removed = result["mode"] == "uninstall"
382
+ return dict(result, control=str(control), target=str(root), workspace=binding["workspace"] if binding else None,
383
+ task_id=binding.get("task_id") if binding else None,
384
+ binding_mode="directory" if binding and binding.get("scope") == "directory" else "task",
385
+ registration_verified=bool(binding) and not removed,
386
+ connection_state={"materials": "removed_or_preserved_modified" if removed else ("generated" if installed else "preview"),
387
+ "host_loading": "not_verified", "native_acceptance": "not_verified"},
388
+ host_loading_verified=False, native_acceptance_verified=False,
389
+ next_steps=(["Manually activated host configuration remains user managed."] if removed else [
390
+ "Review the planned file list, resolve conflicts, then run setup with mode=install and the same binding." if not installed else
391
+ "Review the generated MCP fragment and explicitly merge it into the host configuration, preserving existing settings.",
392
+ codex_trust_step(root),
393
+ "Call native taskcarry_doctor and taskcarry_status on this server in the target workbench; verify control, workspace, task, checkpoint and runtime.",
394
+ "Record actual native results and the next unfinished step in the existing control; generated materials do not attest host acceptance."]))
395
+
396
+
397
+ def pending_matches(root, intent, files, runtime, server_name):
398
+ # A changed source tree requires completing the pending operation with its
399
+ # original package, rather than silently rebasing a partly applied install.
400
+ if (intent["runtime"] != runtime or intent["server_name"] != server_name
401
+ or set(intent["files"]) != set(files)
402
+ or any(intent["files"][name]["after"] != digest(content) for name, content in files.items())):
403
+ raise SetupError("SETUP_PENDING_SOURCE_CHANGED", "Resume pending setup with its original package and server name; project files were preserved")
404
+ after = intent["manifest_after"]
405
+ if (after.get("format") not in (1, 2) or after.get("project") != str(root)
406
+ or after.get("installation_id") != intent["installation_id"]
407
+ or after.get("server_name") != server_name or after.get("runtime") != runtime
408
+ or not isinstance(after.get("files"), dict)
409
+ or any(after["files"].get(name) != row["after"] for name, row in intent["files"].items())):
410
+ raise SetupError("SETUP_INTENT_INVALID", "Pending setup has an inconsistent target manifest")
411
+ actual = file_hash(safe_target(root, ".taskcarry/setup-manifest.json"))
412
+ if actual not in {intent["manifest_before_sha256"], digest(encoded(after))}:
413
+ raise SetupError("SETUP_MANIFEST_CHANGED", "Setup manifest changed since the pending installation")
414
+
415
+
416
+ def preview(root, files, manifest, intent=None):
417
+ changes, conflicts = [], []
418
+ for name, content in files.items():
419
+ path = safe_target(root, name)
420
+ current = digest(path.read_bytes()) if path.is_file() else None
421
+ if path.exists() and not path.is_file():
422
+ conflicts.append({"path": name, "reason": "not_a_regular_file"})
423
+ elif intent and current not in {intent["files"][name]["before"], intent["files"][name]["after"]}:
424
+ conflicts.append({"path": name, "reason": "changed_since_install_intent"})
425
+ elif not intent and path.exists() and current != manifest["files"].get(name):
426
+ conflicts.append({"path": name, "reason": "unmanaged_or_modified"})
427
+ else:
428
+ changes.append({"path": name, "action": "unchanged" if current == digest(content) else ("update" if path.exists() else "create"), "sha256": digest(content)})
429
+ return {"mode": "preview", "project": str(root), "files": changes, "conflicts": conflicts,
430
+ "activation": "The TOML fragment is not active configuration. Review it and explicitly configure Codex; generated skills are project scoped.",
431
+ "pending_installation": intent is not None,
432
+ "global_config_changed": False, "agents_md_changed": False}
433
+
434
+
435
+ def configure(project, mode="preview", server_name=None, target=None, workspace=None, task_id=None, binding_mode="task"):
436
+ if mode not in {"preview", "install", "uninstall"}:
437
+ raise SetupError("SETUP_MODE", "mode must be preview, install or uninstall")
438
+ control = project_root(project)
439
+ if binding_mode not in ("task", "directory") or (binding_mode == "directory" and target is None):
440
+ raise SetupError("SETUP_BINDING_REQUIRED", "Directory mode needs its registered target and workspace")
441
+ if target is None and (workspace is not None or task_id is not None):
442
+ raise SetupError("SETUP_BINDING_REQUIRED", "Workbench setup requires target, workspace and task_id together")
443
+ root = project_root(target) if target is not None else control
444
+ binding = workbench_binding(control, root, workspace, task_id, verify=mode != "uninstall", binding_mode=binding_mode) if target is not None else None
445
+ # Metadata is local to the workbench, while every generated MCP command
446
+ # points to the existing control. No setup mode initializes governance.
447
+ make_files = lambda selected: planned_files(control, selected, binding) if binding else planned_files(control, selected)
448
+ finish = lambda result: connection_result(result, control, root, binding)
449
+ if server_name is not None:
450
+ validate_server_name(server_name)
451
+ if mode == "preview":
452
+ manifest, intent = read_manifest(root), read_intent(root)
453
+ check_binding(manifest, intent, binding)
454
+ selected = server_name or (intent or manifest).get("server_name", "taskcarry")
455
+ files, runtime = make_files(selected), loaded_runtime()
456
+ if intent:
457
+ pending_matches(root, intent, files, runtime, selected)
458
+ return finish(dict(preview(root, files, manifest, intent), server_name=selected, runtime=runtime))
459
+ if binding_mode == "directory":
460
+ from .core import Core
461
+ Core(control).store.assert_writable()
462
+ with setup_lock(root):
463
+ manifest = read_manifest(root)
464
+ manifest_path = safe_target(root, ".taskcarry/setup-manifest.json")
465
+ intent_path = safe_target(root, ".taskcarry/setup-intent.json")
466
+ intent = read_intent(root)
467
+ check_binding(manifest, intent, binding)
468
+ if mode == "uninstall":
469
+ if intent:
470
+ raise SetupError("SETUP_PENDING", "Complete the pending installation before uninstalling its managed files")
471
+ removed, preserved, remaining = [], [], {}
472
+ for name, original in manifest["files"].items():
473
+ path = safe_target(root, name)
474
+ if not path.exists():
475
+ continue
476
+ if path.is_file() and digest(path.read_bytes()) == original:
477
+ path.unlink()
478
+ removed.append(name)
479
+ else:
480
+ preserved.append(name)
481
+ remaining[name] = original
482
+ if remaining:
483
+ updated = dict(manifest, files=remaining)
484
+ if file_hash(manifest_path) != digest(encoded(updated)):
485
+ atomic_write(manifest_path, encoded(updated))
486
+ elif manifest_path.exists():
487
+ manifest_path.unlink()
488
+ return finish({"mode": mode, "removed": removed, "preserved_modified": preserved,
489
+ "global_config_changed": False, "agents_md_changed": False,
490
+ "note": "Any configuration section manually activated in Codex remains user managed. Governance state and user files are retained."})
491
+ selected = server_name or (intent or manifest).get("server_name", "taskcarry")
492
+ files, runtime = make_files(selected), loaded_runtime()
493
+ if intent:
494
+ pending_matches(root, intent, files, runtime, selected)
495
+ result = preview(root, files, manifest, intent)
496
+ if result["conflicts"]:
497
+ raise SetupError("SETUP_CONFLICT", "Existing unmanaged or changed files are preserved", result)
498
+ resumed = intent is not None
499
+ if intent is None:
500
+ manifest_after = dict(manifest, format=2 if binding_mode == "directory" else 1, project=str(root), server_name=selected,
501
+ runtime=runtime, installation_id=manifest.get("installation_id") or uuid.uuid4().hex,
502
+ files={**manifest["files"], **{name: digest(content) for name, content in files.items()}})
503
+ if binding:
504
+ manifest_after["binding"] = binding
505
+ if all(row["action"] == "unchanged" for row in result["files"]) and manifest == manifest_after:
506
+ return finish(dict(result, mode="install", server_name=selected, runtime=runtime,
507
+ resumed=False, files_written=0, manifest_written=False))
508
+ body = {"format": 1, "action": "install", "project": str(root),
509
+ "installation_id": manifest_after["installation_id"], "server_name": selected,
510
+ "runtime": runtime, "manifest_before_sha256": file_hash(manifest_path),
511
+ "manifest_after": manifest_after,
512
+ "files": {name: {"before": file_hash(safe_target(root, name)), "after": digest(content)}
513
+ for name, content in files.items()}}
514
+ if read_manifest(root) != manifest:
515
+ raise SetupError("SETUP_MANIFEST_CHANGED", "Setup manifest changed during preparation")
516
+ for name, proof in body["files"].items():
517
+ if proof["before"] is not None and proof["before"] != manifest["files"].get(name):
518
+ raise SetupError("SETUP_CONFLICT", "A target changed during installation preparation", {"path": name})
519
+ if binding_mode == "directory" and manifest.get("binding", {}).get("task_id"):
520
+ from .shared_workbench import archive_setup
521
+ manifest_after["previous_setup"] = archive_setup(root, control, body["manifest_before_sha256"])
522
+ intent = dict(body, intent_id=digest(encoded(body)))
523
+ atomic_write(intent_path, encoded(intent))
524
+ writes = 0
525
+ for name, content in files.items():
526
+ path = safe_target(root, name)
527
+ current, proof = file_hash(path), intent["files"][name]
528
+ if current == proof["after"]:
529
+ continue
530
+ if current != proof["before"]:
531
+ raise SetupError("SETUP_CONFLICT", "Managed file changed after installation was planned", {"path": name})
532
+ atomic_write(path, content)
533
+ writes += 1
534
+ if binding:
535
+ workbench_binding(control, root, workspace, task_id, binding_mode=binding_mode)
536
+ pending_matches(root, intent, make_files(selected), loaded_runtime(), selected)
537
+ if any(file_hash(safe_target(root, name)) != proof["after"] for name, proof in intent["files"].items()):
538
+ raise SetupError("SETUP_CONFLICT", "Managed file changed before installation could be recorded")
539
+ target_manifest = encoded(intent["manifest_after"])
540
+ manifest_written = file_hash(manifest_path) != digest(target_manifest)
541
+ if manifest_written:
542
+ atomic_write(manifest_path, target_manifest)
543
+ if file_hash(intent_path) != digest(encoded(intent)):
544
+ raise SetupError("SETUP_INTENT_CHANGED", "Setup intent changed before completion")
545
+ intent_path.unlink()
546
+ return finish(dict(result, mode="install", server_name=selected, runtime=runtime, resumed=resumed,
547
+ pending_installation=False, files_written=writes, manifest_written=manifest_written))
548
+
549
+
550
+ def runtime_info(project):
551
+ """Inspect import metadata, on-disk source and setup; never attest loaded code."""
552
+ result = {"loaded_runtime": None, "setup_status": "not_installed",
553
+ "managed_setup_version": None, "server_name": None, "pending_installation": False,
554
+ "managed_files_match": None, "generated_files_match": None,
555
+ "managed_runtime_matches_disk": None, "source_fingerprint_scope": "on_disk",
556
+ "loaded_code_verified": False, "requires_restart_after_package_change": True,
557
+ "host_loading_verified": False, "package_upgrade_performed": False}
558
+ try:
559
+ runtime = loaded_runtime()
560
+ result["loaded_runtime"] = runtime
561
+ root = project_root(project)
562
+ manifest, intent = read_manifest(root), read_intent(root)
563
+ result["pending_installation"] = intent is not None
564
+ result["managed_setup_version"] = manifest.get("runtime", {}).get("version")
565
+ result["server_name"] = (intent or manifest).get("server_name", "taskcarry")
566
+ if intent:
567
+ result["pending_runtime_version"] = intent.get("runtime", {}).get("version")
568
+ binding = (intent["manifest_after"] if intent else manifest).get("binding")
569
+ control = Path(binding["control"]) if binding else root
570
+ result.update(control=str(control), target=str(root), binding=binding)
571
+ files = planned_files(control, result["server_name"], binding) if binding else planned_files(root, result["server_name"])
572
+ details = []
573
+ for name in sorted(set(files) | set(manifest["files"])):
574
+ current = file_hash(safe_target(root, name))
575
+ expected = digest(files[name]) if name in files else None
576
+ details.append({"path": name, "current_sha256": current,
577
+ "managed_sha256": manifest["files"].get(name), "generated_sha256": expected,
578
+ "matches_managed": name in manifest["files"] and current == manifest["files"][name],
579
+ "matches_generated": expected is not None and current == expected})
580
+ result["files"] = details
581
+ result["managed_files_match"] = bool(manifest["files"]) and all(
582
+ row["matches_managed"] for row in details if row["path"] in manifest["files"])
583
+ result["generated_files_match"] = all(row["matches_generated"] for row in details if row["path"] in files)
584
+ result["managed_runtime_matches_disk"] = manifest.get("runtime") == runtime if manifest.get("runtime") else None
585
+ if intent:
586
+ result["setup_status"] = "pending"
587
+ result["pending_source_matches_disk"] = intent.get("runtime") == runtime and all(
588
+ intent.get("files", {}).get(name, {}).get("after") == digest(content) for name, content in files.items())
589
+ elif manifest["files"]:
590
+ result["setup_status"] = "installed" if result["managed_files_match"] else "modified"
591
+ return result
592
+ except (SetupError, OSError, ValueError, TypeError, KeyError) as exc:
593
+ error = {"code": getattr(exc, "code", "SETUP_DIAGNOSTIC_ERROR"),
594
+ "type": type(exc).__name__, "message": str(exc)}
595
+ if isinstance(exc, OSError):
596
+ error.update(errno=exc.errno, filename=exc.filename)
597
+ return dict(result, setup_status="unavailable", error=error)