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/workbench.py ADDED
@@ -0,0 +1,625 @@
1
+ """Versioned, private workbench navigation through the shared governance engine.
2
+
3
+ Views are derived guidance, never a second task database. Publication, evidence
4
+ of consumption, code adoption and business acceptance remain separate facts.
5
+ The Codex adapter changes only one protected instruction section; the generic
6
+ publication engine also supports ignored navigation files without a host.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ import base64
11
+ import json
12
+ import os
13
+ from pathlib import Path, PurePosixPath
14
+ import re
15
+ import tomllib
16
+ import uuid
17
+
18
+ from .core import Core, _id, _linked, digest_bytes, git, read_file_bytes, validate_relative_path
19
+ from .gitops import git as repository_git
20
+ from .store import GovernanceError, now
21
+
22
+ MAX_BYTES = 256 * 1024
23
+ MAX_PLAN_BYTES = 8 * 1024 * 1024
24
+ SOURCE_COLLECTIONS = {"tasks", "workspaces", "checkpoints", "stages", "operations", "issues", "fixes", "experience", "runs", "observations",
25
+ "governance_facts", "governance_cycles", "scan_sources"}
26
+
27
+
28
+ def canonical(value):
29
+ return (json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False) + "\n").encode("utf-8")
30
+
31
+
32
+ def fail(message, code="WORKBENCH_CONFLICT"):
33
+ raise GovernanceError(code, message)
34
+
35
+
36
+ def _hash(data):
37
+ return digest_bytes(data) if data is not None else None
38
+
39
+
40
+ def _links(path):
41
+ path = Path(path).absolute()
42
+ if any(_linked(p) for p in (path, *path.parents)):
43
+ fail("Workbench paths cannot traverse links or junctions.", "UNSAFE_PATH")
44
+ return path
45
+
46
+
47
+ def _read(path, maximum=MAX_BYTES):
48
+ path = _links(path)
49
+ try:
50
+ return read_file_bytes(path, maximum)
51
+ except FileNotFoundError:
52
+ return None
53
+
54
+
55
+ def atomic_write(path, content):
56
+ """The final name is never visible with a partially written body."""
57
+ path = _links(path)
58
+ path.parent.mkdir(parents=True, exist_ok=True)
59
+ _links(path)
60
+ temporary = path.with_name(path.name + ".tmp-" + uuid.uuid4().hex)
61
+ try:
62
+ with temporary.open("xb") as stream:
63
+ stream.write(content)
64
+ stream.flush()
65
+ os.fsync(stream.fileno())
66
+ _links(path)
67
+ os.replace(temporary, path)
68
+ finally:
69
+ try:
70
+ temporary.unlink()
71
+ except FileNotFoundError:
72
+ pass
73
+
74
+
75
+ def immutable(path, content):
76
+ """Called under Store.guard; durable intent precedes every publication."""
77
+ existing = _read(path, MAX_PLAN_BYTES)
78
+ if existing is not None:
79
+ if existing != content:
80
+ fail("An immutable workbench object differs; preserve it for review.")
81
+ return
82
+ atomic_write(path, content)
83
+
84
+
85
+ def managed_section(original, section_id, text):
86
+ _id(section_id, "Section ID")
87
+ original = original or b""
88
+ original.decode("utf-8-sig")
89
+ if not isinstance(text, str) or len(text.encode()) > MAX_BYTES:
90
+ fail("Managed text exceeds the bounded text limit.", "INVALID_ARGUMENT")
91
+ start = ("<!-- taskcarry:" + section_id + ":begin -->").encode()
92
+ end = ("<!-- taskcarry:" + section_id + ":end -->").encode()
93
+ if b"<!-- taskcarry:" in text.encode():
94
+ fail("Managed text cannot contain nested TaskCarry markers.")
95
+ newline = b"\r\n" if b"\r\n" in original else b"\n"
96
+ body = text.replace("\r\n", "\n").strip("\n").encode().replace(b"\n", newline)
97
+ block = start + newline + body + newline + end
98
+ if original.count(start) == original.count(end) == 0:
99
+ separator = b"" if not original or original.endswith((b"\n", b"\r")) else newline
100
+ return original + separator + block + newline
101
+ if original.count(start) != 1 or original.count(end) != 1:
102
+ fail("Managed markers are incomplete or duplicated.")
103
+ first, last = original.index(start), original.index(end)
104
+ if last < first or (first and original[first - 1:first] != b"\n"):
105
+ fail("Managed markers must be ordered and start on their own line.")
106
+ tail = last + len(end)
107
+ if original[tail:tail + 1] not in (b"", b"\r", b"\n"):
108
+ fail("Managed markers must end on their own line.")
109
+ if b"<!-- taskcarry:" in original[first + len(start):last]:
110
+ fail("Managed sections cannot nest.")
111
+ return original[:first] + block + original[tail:]
112
+
113
+
114
+ def _string_end(text, start):
115
+ """Locate one TOML string value; tomllib validates its actual semantics."""
116
+ if start >= len(text) or text[start] not in "\"'":
117
+ return None
118
+ quote = text[start]
119
+ delimiter = quote * 3 if text.startswith(quote * 3, start) else quote
120
+ index = start + len(delimiter)
121
+ while index < len(text):
122
+ if quote == '"' and text[index] == "\\":
123
+ index += 2
124
+ elif text.startswith(delimiter, index):
125
+ end = index + len(delimiter)
126
+ if len(delimiter) == 3:
127
+ while end < len(text) and text[end] == quote:
128
+ end += 1
129
+ return end
130
+ else:
131
+ index += 1
132
+ return None
133
+
134
+
135
+ def codex_instructions(original, instructions):
136
+ """Preserve bytes outside the instruction value, and custom text inside it.
137
+
138
+ Candidate locations are accepted only if parsing proves that replacing the
139
+ token changes the top-level developer_instructions field and nothing else.
140
+ This also excludes key-looking text inside other multiline strings/tables.
141
+ """
142
+ original = original or b""
143
+ text = original.decode("utf-8-sig")
144
+ try:
145
+ before = tomllib.loads(text)
146
+ except tomllib.TOMLDecodeError as exc:
147
+ fail("Existing Codex configuration is invalid TOML: " + str(exc))
148
+ previous = before.get("developer_instructions", "")
149
+ if not isinstance(previous, str):
150
+ fail("developer_instructions must be a string.")
151
+ updated = managed_section(previous.encode(), "workbench-entry", instructions).decode()
152
+ encoded = json.dumps(updated, ensure_ascii=False)
153
+ expected = dict(before, developer_instructions=updated)
154
+ if "developer_instructions" not in before:
155
+ newline = "\r\n" if "\r\n" in text else "\n"
156
+ result = "developer_instructions = " + encoded + newline + text
157
+ else:
158
+ result = None
159
+ pattern = r"(?m)^[ \t]*(?:developer_instructions|\"developer_instructions\"|'developer_instructions')[ \t]*=[ \t]*"
160
+ for match in re.finditer(pattern, text):
161
+ end = _string_end(text, match.end())
162
+ if end is None:
163
+ continue
164
+ candidate = text[:match.end()] + encoded + text[end:]
165
+ try:
166
+ if tomllib.loads(candidate) == expected:
167
+ if result is not None:
168
+ fail("Ambiguous developer instruction field; preserve it for manual review.")
169
+ result = candidate
170
+ except tomllib.TOMLDecodeError:
171
+ continue
172
+ if result is None:
173
+ fail("Cannot safely locate the top-level instruction value.")
174
+ if tomllib.loads(result) != expected:
175
+ fail("Codex adapter would change unrelated configuration.")
176
+ return (b"\xef\xbb\xbf" if original.startswith(b"\xef\xbb\xbf") else b"") + result.encode()
177
+
178
+
179
+ def git_snapshot(root):
180
+ """No refresh or write: preserve HEAD, index bytes and existing WIP."""
181
+ root = _links(root)
182
+ output = lambda *args: git(root, *args).stdout.decode("utf-8").strip()
183
+ if Path(output("rev-parse", "--show-toplevel")).resolve() != root.resolve():
184
+ fail("Use the registered Git worktree root.")
185
+ index = Path(output("rev-parse", "--path-format=absolute", "--git-path", "index"))
186
+ return {"root": str(root), "common_dir": output("rev-parse", "--path-format=absolute", "--git-common-dir"),
187
+ "branch": output("symbolic-ref", "--quiet", "HEAD"), "head": output("rev-parse", "HEAD"),
188
+ "index_sha256": _hash(_read(index, 32 * 1024 * 1024))}
189
+
190
+
191
+ def private_target(root, relative):
192
+ if not isinstance(relative, str) or PurePosixPath(relative).as_posix() != relative:
193
+ fail("Use a canonical relative target path.", "UNSAFE_PATH")
194
+ path = validate_relative_path(root, relative)
195
+ if git(root, "ls-files", "-z", "--", relative).stdout or git(root, "ls-tree", "-z", "HEAD", "--", relative).stdout:
196
+ fail("Private workbench entries must not be tracked or staged: " + relative, "WORKBENCH_PUBLIC_PATH")
197
+ # check-ignore accepts literal filenames but rejects Git's global literal
198
+ # pathspec mode, so use the bounded helper without that global switch.
199
+ if repository_git(root, "--no-optional-locks", "check-ignore", "--no-index", "--quiet", "--", relative, check=False).returncode != 0:
200
+ fail("Private workbench targets must already be Git-ignored: " + relative, "WORKBENCH_PRIVATE_PATH_REQUIRED")
201
+ return path
202
+
203
+
204
+ class Workbench(Core):
205
+ def _path(self, *parts):
206
+ return _links(self.store.directory.joinpath("workbench", *parts))
207
+
208
+ def _source_ids(self):
209
+ current = self.source()
210
+ return {current["source_id"], *current.get("aliases", [])}
211
+
212
+ def _same_local_source(self, recorded):
213
+ """Only a same-location legacy identity adoption can cross an alias.
214
+
215
+ Replica changes and path moves need new plans. Older immutable objects
216
+ stay unchanged; a registered alias is not cross-host write authority.
217
+ """
218
+ current = self.source()
219
+ if not isinstance(recorded, dict) or recorded.get("control") != current["control"]:
220
+ return False
221
+ if recorded.get("source_id") == current["source_id"]:
222
+ return recorded.get("replica_id") == current.get("replica_id")
223
+ return (recorded.get("identity_scope") == "resolved_local_path"
224
+ and recorded.get("replica_id") is None
225
+ and recorded.get("source_id") in current.get("aliases", []))
226
+
227
+ @staticmethod
228
+ def _sha(value, label):
229
+ if not isinstance(value, str) or re.fullmatch(r"[a-f0-9]{64}", value) is None:
230
+ fail(label + " must be a SHA-256 identifier.", "INVALID_ARGUMENT")
231
+ return value
232
+
233
+ def _object(self, collection, key, value):
234
+ prior = self.store.get(collection, key)
235
+ if prior is not None:
236
+ if prior != value:
237
+ fail("Immutable workbench record differs: " + key)
238
+ return False
239
+ self.store.put(collection, key, value)
240
+ self.store.event(collection, {"id": key})
241
+ return True
242
+
243
+ def _source_revision(self, source):
244
+ if source.get("collection"):
245
+ if source["source_id"] not in self._source_ids() or source["collection"] not in SOURCE_COLLECTIONS:
246
+ fail("Record sources must refer to this control and a supported collection.", "WORKBENCH_SOURCE_MISMATCH")
247
+ local_id = source.get("local_id")
248
+ # These are bounded record keys, not task IDs or filesystem paths.
249
+ # Source-qualified fact keys include a namespace hash and colon.
250
+ if not isinstance(local_id, str) or re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.:-]{0,255}", local_id) is None:
251
+ fail("Source local ID must be a bounded exact record key.", "INVALID_ARGUMENT")
252
+ record = self.store.get(source["collection"], local_id)
253
+ return _hash(canonical(record)) if record is not None else None
254
+ if source.get("path"):
255
+ return _hash(_read(validate_relative_path(self.root, source["path"])))
256
+ return None
257
+
258
+ def _freshness(self, view):
259
+ result = []
260
+ for source in view["manifest"]["sources"]:
261
+ try:
262
+ revision = self._source_revision(source)
263
+ state = "UNVERIFIED_REFERENCE" if not (source.get("path") or source.get("collection")) else (
264
+ "MATCHES" if revision == source["revision"] else "CHANGED_OR_MISSING")
265
+ result.append({"source_id": source["source_id"], "state": state, "revision": source["revision"], "observed_revision": revision})
266
+ except (GovernanceError, OSError, ValueError) as exc:
267
+ result.append({"source_id": source["source_id"], "state": "UNREADABLE", "error": str(exc)[:300]})
268
+ return result
269
+
270
+ def _freeze(self, body, sources):
271
+ if not isinstance(body, str) or not body.strip() or len(body.encode()) > MAX_BYTES:
272
+ fail("Freeze requires 1-256 KiB of nonempty view text.", "INVALID_ARGUMENT")
273
+ if not isinstance(sources, list) or not 1 <= len(sources) <= 50:
274
+ fail("Freeze requires 1-50 explicit source revisions.", "INVALID_ARGUMENT")
275
+ normalized = []
276
+ for source in sources:
277
+ if not isinstance(source, dict) or set(source) - {"source_id", "revision", "collection", "local_id", "path"}:
278
+ fail("Unsupported source fields.", "INVALID_ARGUMENT")
279
+ if any(not isinstance(source.get(key), str) or not source[key].strip() or len(source[key]) > 500 for key in ("source_id", "revision")):
280
+ fail("Each source needs bounded identity and revision.", "INVALID_ARGUMENT")
281
+ if bool(source.get("collection")) != bool(source.get("local_id")) or (source.get("path") and source.get("collection")):
282
+ fail("Use a record reference, file reference or explicit external revision.", "INVALID_ARGUMENT")
283
+ observed = self._source_revision(source)
284
+ if (source.get("path") or source.get("collection")) and observed != source["revision"]:
285
+ fail("A source no longer matches its declared revision.", "WORKBENCH_SOURCE_CHANGED")
286
+ normalized.append(dict(source))
287
+ manifest = {"schema": "taskcarry.workbench.view.v1", "source": self.source(), "sources": normalized,
288
+ "body_sha256": digest_bytes(body.encode()), "body_bytes": len(body.encode()),
289
+ "meaning": "Derived navigation; query Core for current task state."}
290
+ view_id = digest_bytes(canonical(manifest))
291
+ record = {"manifest": manifest, "body": body}
292
+ with self.store.guard():
293
+ with self.store.transaction():
294
+ created = self._object("workbench_views", view_id, record)
295
+ immutable(self._path("views", view_id, "view.md"), body.encode())
296
+ immutable(self._path("views", view_id, "manifest.json"), canonical(manifest))
297
+ return {"view_id": view_id, "created": created, "view_path": str(self._path("views", view_id, "view.md")),
298
+ "manifest_path": str(self._path("views", view_id, "manifest.json")), "sources": self._freshness(record)}
299
+
300
+ def _view(self, view_id):
301
+ self._sha(view_id, "View ID")
302
+ record = self.store.get("workbench_views", view_id)
303
+ if not record or record.get("manifest", {}).get("schema") != "taskcarry.workbench.view.v1":
304
+ fail("View is missing or has an unsupported schema.")
305
+ manifest = record["manifest"]
306
+ if not self._same_local_source(manifest.get("source")):
307
+ fail("This view belongs to another control or replica; freeze a local view.")
308
+ if (digest_bytes(canonical(manifest)) != view_id or _hash(record["body"].encode()) != manifest["body_sha256"]
309
+ or len(record["body"].encode()) != manifest["body_bytes"]
310
+ or _read(self._path("views", view_id, "manifest.json")) != canonical(manifest)
311
+ or _read(self._path("views", view_id, "view.md")) != record["body"].encode()):
312
+ fail("View integrity check failed; repeat the original freeze only for missing publication steps.")
313
+ return record
314
+
315
+ def _binding(self, workspace, task_id):
316
+ from .integration import Integration
317
+ self._task(task_id)
318
+ workspace = _id(workspace, "Workspace")
319
+ root = Integration(self.root)._ws(workspace)
320
+ if root != self.root and _links(root / ".taskcarry" / "state.sqlite3").exists():
321
+ fail("This workbench already has a separate control.")
322
+ for relative in (".taskcarry/workbench.json", ".taskcarry/setup-manifest.json"):
323
+ raw = _read(root / relative)
324
+ if raw is not None:
325
+ try:
326
+ record = json.loads(raw)
327
+ binding = record.get("binding") if relative.endswith("setup-manifest.json") else record
328
+ except (ValueError, AttributeError):
329
+ fail("Existing connection binding cannot be read.")
330
+ if binding and any(binding.get(key) != value for key, value in (
331
+ ("control", str(self.root)), ("target", str(root)), ("workspace", workspace), ("task_id", task_id))):
332
+ fail("Keep the workbench's original task/control binding.", "WORKBENCH_BINDING_MISMATCH")
333
+ return root
334
+
335
+ def _pointer(self, workspace):
336
+ raw = _read(self._path("current", workspace + ".json"))
337
+ if raw is None:
338
+ return None
339
+ try:
340
+ pointer = json.loads(raw)
341
+ receipt = self.store.get("workbench_receipts", pointer["receipt_id"])
342
+ if (pointer.get("schema") != "taskcarry.workbench.current.v1" or pointer.get("workspace") != workspace
343
+ or pointer.get("source_id") not in self._source_ids() or not receipt
344
+ or any(pointer.get(key) != receipt.get(key) for key in ("workspace", "task_id", "plan_id", "view_id", "source_id"))
345
+ or raw != canonical(pointer)):
346
+ fail("Current pointer does not match its immutable publication receipt.")
347
+ return pointer
348
+ except (ValueError, KeyError, TypeError) as exc:
349
+ fail("Current pointer is invalid: " + str(exc))
350
+
351
+ def _instructions(self, row, view_id):
352
+ return ("Read the TaskCarry current entry at " + str(self._path("current", row["workspace"] + ".json")) + ".\n"
353
+ "Published view: " + str(self._path("views", view_id, "view.md")) + ".\n"
354
+ "Keep workspace " + row["workspace"] + ", original task " + row["task_id"] + ", and the same control " + str(self.root) + ".\n"
355
+ "Use Core to check the latest task and checkpoint. This versioned view is guidance, not live task state.\n"
356
+ "Continue your existing responsibility and WIP. A navigation update does not initialize, receive, adopt or release work.\n"
357
+ "Report actual host loading and source differences; publication alone does not prove consumption.")
358
+
359
+ def _plan(self, view_id, targets):
360
+ self._view(view_id)
361
+ if not isinstance(targets, list) or not 1 <= len(targets) <= 24:
362
+ fail("Plan requires 1-24 explicit workbenches.", "INVALID_ARGUMENT")
363
+ rows, seen, roots = [], set(), set()
364
+ with self.store.guard():
365
+ for target in targets:
366
+ if not isinstance(target, dict) or set(target) - {"workspace", "task_id", "thread_id", "source_id", "host", "code_assessment", "writes"}:
367
+ fail("Unsupported target fields.", "INVALID_ARGUMENT")
368
+ workspace, task_id = target.get("workspace"), target.get("task_id")
369
+ root = self._binding(workspace, task_id)
370
+ if workspace in seen or os.path.normcase(str(root)) in roots:
371
+ fail("Duplicate workspace or root in a plan.", "INVALID_ARGUMENT")
372
+ seen.add(workspace)
373
+ roots.add(os.path.normcase(str(root)))
374
+ _id(target.get("thread_id"), "Thread ID")
375
+ if target.get("source_id", self.source()["source_id"]) not in self._source_ids():
376
+ fail("Workbench task belongs to another source.", "WORKBENCH_SOURCE_MISMATCH")
377
+ previous = self._pointer(workspace)
378
+ from .shared_workbench import assert_chat_identity
379
+ assert_chat_identity(self, target['thread_id'], workspace, task_id)
380
+ if previous and previous["task_id"] != task_id:
381
+ fail("A workbench entry must retain its original task.", "WORKBENCH_BINDING_MISMATCH")
382
+ if previous and self.store.get("workbench_receipts", previous["receipt_id"])["thread_id"] != target["thread_id"]:
383
+ fail("Another original chat already owns this single entry; use explicit shared routing.", "WORKBENCH_BINDING_MISMATCH")
384
+ for other in self.store.list("workspaces"):
385
+ if (other['name'] != workspace and os.path.normcase(other['path']) == os.path.normcase(str(root))
386
+ and self._pointer(other['name']) is not None):
387
+ fail("Another workspace entry uses this directory; retain it and use shared routing.", "WORKBENCH_BINDING_MISMATCH")
388
+ assessment = target.get("code_assessment")
389
+ if (not isinstance(assessment, dict) or set(assessment) != {"status", "reason"}
390
+ or assessment.get("status") not in {"NO_CODE_DEPENDENCY", "ALREADY_CONTAINS", "SEPARATE_CODE_PLAN_REQUIRED"}
391
+ or not isinstance(assessment.get("reason"), str) or not 1 <= len(assessment["reason"].strip()) <= 2000):
392
+ fail("Each workbench needs an explicit bounded code-dependency assessment.", "INVALID_ARGUMENT")
393
+ host = target.get("host", "codex")
394
+ if host not in ("codex", "none"):
395
+ fail("Unsupported workbench host.", "INVALID_ARGUMENT")
396
+ row = {"workspace": workspace, "task_id": task_id, "thread_id": target["thread_id"],
397
+ "source_id": self.source()["source_id"], "root": str(root), "host": host,
398
+ "code_assessment": assessment, "git": git_snapshot(root), "previous": previous, "writes": []}
399
+ specs = target.get("writes", [])
400
+ if not isinstance(specs, list) or len(specs) > 16:
401
+ fail("At most 16 explicit navigation writes per workbench.", "INVALID_ARGUMENT")
402
+ paths = set()
403
+ if host == "codex":
404
+ path = private_target(root, ".codex/config.toml")
405
+ old = _read(path)
406
+ row["writes"].append(self._write_record(".codex/config.toml", old, codex_instructions(old, self._instructions(row, view_id))))
407
+ paths.add(".codex/config.toml")
408
+ for spec in specs:
409
+ if not isinstance(spec, dict) or set(spec) - {"path", "mode", "section_id", "text", "expected_sha256"}:
410
+ fail("Unsupported write fields.", "INVALID_ARGUMENT")
411
+ relative = spec.get("path")
412
+ path = private_target(root, relative)
413
+ if relative.casefold() in paths:
414
+ fail("Duplicate or case-colliding target path.", "INVALID_ARGUMENT")
415
+ paths.add(relative.casefold())
416
+ old = _read(path)
417
+ text = spec.get("text")
418
+ if not isinstance(text, str) or len(text.encode()) > MAX_BYTES:
419
+ fail("Navigation text must be bounded UTF-8.", "INVALID_ARGUMENT")
420
+ mode = spec.get("mode", "managed_section")
421
+ if relative == ".codex/config.toml":
422
+ fail("Use the Codex adapter for its configuration field.")
423
+ if mode == "managed_section":
424
+ new = managed_section(old, spec.get("section_id", "navigation"), text)
425
+ elif mode == "exact" and "expected_sha256" in spec and spec["expected_sha256"] == _hash(old):
426
+ new = text.encode()
427
+ else:
428
+ fail("Exact writes need the current expected hash, including null for an absent file.")
429
+ row["writes"].append(self._write_record(relative, old, new))
430
+ if not row["writes"]:
431
+ fail("A publication must name at least one private entry.", "INVALID_ARGUMENT")
432
+ rows.append(row)
433
+ plan = {"schema": "taskcarry.workbench.plan.v1", "view_id": view_id, "source": self.source(), "targets": rows}
434
+ if len(canonical(plan)) > MAX_PLAN_BYTES:
435
+ fail("Split this workbench plan into smaller batches.", "INVALID_ARGUMENT")
436
+ plan_id = digest_bytes(canonical(plan))
437
+ with self.store.transaction():
438
+ self._object("workbench_plans", plan_id, plan)
439
+ immutable(self._path("plans", plan_id + ".json"), canonical(plan))
440
+ return {"plan_id": plan_id, "view_id": view_id, "plan_path": str(self._path("plans", plan_id + ".json")),
441
+ "targets": [{**{k: row[k] for k in ("workspace", "task_id", "thread_id", "host", "code_assessment", "git")},
442
+ "writes": [{k: value for k, value in write.items() if k != "content"} for write in row["writes"]]} for row in rows],
443
+ "effects_executed": False, "next_step": "Review the exact private plan, then execute its plan_id."}
444
+
445
+ @staticmethod
446
+ def _write_record(path, old, new):
447
+ if len(new) > MAX_BYTES:
448
+ fail("Resulting entry exceeds the bounded text limit.", "INVALID_ARGUMENT")
449
+ return {"path": path, "before": _hash(old), "after": _hash(new), "content": base64.b64encode(new).decode()}
450
+
451
+ def _load_plan(self, plan_id):
452
+ self._sha(plan_id, "Plan ID")
453
+ plan = self.store.get("workbench_plans", plan_id)
454
+ if not plan or plan.get("schema") != "taskcarry.workbench.plan.v1" or digest_bytes(canonical(plan)) != plan_id:
455
+ fail("Plan is missing, changed or has an unsupported schema.")
456
+ if not self._same_local_source(plan.get("source")):
457
+ fail("This plan belongs to another control or replica; make a new local plan.")
458
+ return plan
459
+
460
+ def _execute_target(self, plan_id, plan, row):
461
+ workspace = row["workspace"]
462
+ root = self._binding(workspace, row["task_id"])
463
+ from .shared_workbench import assert_chat_identity
464
+ assert_chat_identity(self, row['thread_id'], workspace, row['task_id'])
465
+ receipt_id = plan_id + "." + workspace
466
+ existing = self.store.get("workbench_receipts", receipt_id)
467
+ pointer = {"schema": "taskcarry.workbench.current.v1", "workspace": workspace, "task_id": row["task_id"],
468
+ "source_id": row["source_id"], "view_id": plan["view_id"], "plan_id": plan_id, "receipt_id": receipt_id}
469
+ current = self._pointer(workspace)
470
+ if current not in (row["previous"], pointer):
471
+ return {"workspace": workspace, "status": "SUPERSEDED", "current_plan_id": current["plan_id"] if current else None}
472
+ if git_snapshot(root) != row["git"]:
473
+ fail("Git identity, HEAD or index changed after planning; preserve work and make a fresh plan.")
474
+ for write in row["writes"]:
475
+ actual = _hash(_read(private_target(root, write["path"])))
476
+ if actual != write["after"] and (existing is not None or actual != write["before"]):
477
+ fail("A planned file was modified; preserve it and make a fresh plan: " + write["path"])
478
+ for write in row["writes"]:
479
+ path = private_target(root, write["path"])
480
+ actual = _hash(_read(path))
481
+ if actual == write["after"]:
482
+ continue
483
+ if actual != write["before"]:
484
+ fail("Target changed during publication: " + write["path"])
485
+ atomic_write(path, base64.b64decode(write["content"], validate=True))
486
+ if git_snapshot(root) != row["git"]:
487
+ fail("Git state changed concurrently; effects are retained for inspection, not declared complete.")
488
+ if any(_hash(_read(private_target(root, w["path"]))) != w["after"] for w in row["writes"]):
489
+ fail("Published entry verification failed; inspect actual effects before retrying.")
490
+ if existing is None:
491
+ existing = {"schema": "taskcarry.workbench.receipt.v1", "receipt_id": receipt_id,
492
+ **{key: pointer[key] for key in ("workspace", "task_id", "source_id", "view_id", "plan_id")},
493
+ "thread_id": row["thread_id"], "published_at": now(), "status": "PUBLISHED",
494
+ "git_before": row["git"], "git_after": row["git"], "code_assessment": row["code_assessment"],
495
+ "writes": [{"path": w["path"], "sha256": w["after"]} for w in row["writes"]],
496
+ "consumer_state": "NOT_VERIFIED", "meaning": "Publication is not host consumption, code adoption or business acceptance."}
497
+ with self.store.transaction():
498
+ self._object("workbench_receipts", receipt_id, existing)
499
+ immutable(self._path("receipts", receipt_id + ".json"), canonical(existing))
500
+ if current != pointer:
501
+ atomic_write(self._path("current", workspace + ".json"), canonical(pointer))
502
+ with self.store.transaction():
503
+ if self.store.get("workbench_current", workspace) != pointer:
504
+ self.store.put("workbench_current", workspace, pointer)
505
+ self.store.event("workbench_published", pointer)
506
+ return {"workspace": workspace, "status": "PUBLISHED", "receipt_id": receipt_id,
507
+ "view_id": plan["view_id"], "consumer_state": "NOT_VERIFIED"}
508
+
509
+ def _execute(self, plan_id):
510
+ results = []
511
+ with self.store.guard():
512
+ plan = self._load_plan(plan_id)
513
+ self._view(plan["view_id"])
514
+ immutable(self._path("plans", plan_id + ".json"), canonical(plan))
515
+ for row in plan["targets"]:
516
+ try:
517
+ results.append(self._execute_target(plan_id, plan, row))
518
+ except (GovernanceError, OSError, ValueError) as exc:
519
+ results.append({"workspace": row["workspace"], "status": "CONFLICT" if isinstance(exc, GovernanceError) else "IO_ERROR",
520
+ "code": getattr(exc, "code", type(exc).__name__), "error": str(exc)[:1000],
521
+ "next_step": "Inspect actual effects; resume this exact plan for missing steps, or re-plan changed files."})
522
+ return {"plan_id": plan_id, "status": "COMPLETED" if all(r["status"] == "PUBLISHED" for r in results) else "PARTIAL",
523
+ "results": results, "source_freshness": self._freshness(self._view(plan["view_id"])), "business_accepted": False}
524
+
525
+ def _consume(self, proof):
526
+ keys = {"workspace", "plan_id", "view_id", "task_id", "source_id", "thread_id", "turn_id", "evidence_path", "evidence_sha256", "reviewer", "observed_at"}
527
+ if not isinstance(proof, dict) or set(proof) != keys or any(not isinstance(v, str) or not v.strip() or len(v) > 1000 for v in proof.values()):
528
+ fail("Consumption requires exact bounded identity and reviewed evidence fields.", "INVALID_ARGUMENT")
529
+ plan_id, workspace = self._sha(proof["plan_id"], "Plan ID"), _id(proof["workspace"], "Workspace")
530
+ with self.store.guard():
531
+ plan = self._load_plan(plan_id)
532
+ row = next((r for r in plan["targets"] if r["workspace"] == workspace), None)
533
+ receipt_id = plan_id + "." + workspace
534
+ receipt = self.store.get("workbench_receipts", receipt_id)
535
+ if not row or not receipt or any(proof[key] != receipt[key] for key in ("view_id", "task_id", "source_id", "thread_id")):
536
+ fail("Consumption evidence must match an actual publication and its original task/thread.")
537
+ evidence = validate_relative_path(self.root, proof["evidence_path"], allow_missing=False)
538
+ if _hash(_read(evidence)) != self._sha(proof["evidence_sha256"], "Evidence hash"):
539
+ fail("Reviewed consumption evidence is missing or changed.")
540
+ record = {"schema": "taskcarry.workbench.consumption.v1", **proof, "receipt_id": receipt_id,
541
+ "meaning": "Caller-reviewed evidence reference; not an independent assertion of understanding, native loading or business acceptance."}
542
+ consumption_id = digest_bytes(canonical(record))
543
+ with self.store.transaction():
544
+ self._object("workbench_consumption", consumption_id, record)
545
+ self.store.put("workbench_consumed", receipt_id, {"consumption_id": consumption_id})
546
+ immutable(self._path("consumption", consumption_id + ".json"), canonical(record))
547
+ from .shared_workbench import chat_key
548
+ shared_key = chat_key(proof['thread_id'])
549
+ shared_current = (self.store.get('workbench_chat_current', shared_key) is not None
550
+ or self._path('chats', shared_key + '.json').exists())
551
+ return {"consumption_id": consumption_id, "receipt_id": receipt_id, "consumer_state": "REVIEWED_EVIDENCE_RECORDED",
552
+ "current_view": not shared_current and bool((self._pointer(workspace) or {}).get("plan_id") == plan_id),
553
+ "native_acceptance_verified": False}
554
+
555
+ def _status(self, workspace, limit, cursor):
556
+ if type(limit) is not int or not 1 <= limit <= 100:
557
+ fail("Status limit must be 1-100.", "INVALID_ARGUMENT")
558
+ if workspace is not None:
559
+ _id(workspace, "Workspace")
560
+ if cursor is not None:
561
+ _id(cursor, "Cursor")
562
+ with self.store._connect(readonly=True) as db:
563
+ if workspace:
564
+ rows = db.execute("SELECT key FROM records WHERE collection='workspaces' AND key=?", (workspace,)).fetchall()
565
+ else:
566
+ rows = db.execute("SELECT key FROM records WHERE collection='workspaces' AND key>? ORDER BY key LIMIT ?", (cursor or "", limit + 1)).fetchall()
567
+ result = []
568
+ for (name,) in rows[:limit]:
569
+ try:
570
+ pointer = self._pointer(name)
571
+ if pointer is None:
572
+ result.append({"workspace": name, "state": "NOT_PUBLISHED"})
573
+ continue
574
+ view = self._view(pointer["view_id"])
575
+ selected = self.store.get("workbench_consumed", pointer["receipt_id"], {})
576
+ consumption = self.store.get("workbench_consumption", selected.get("consumption_id", ""))
577
+ consumer_state = "NOT_VERIFIED"
578
+ if consumption:
579
+ evidence = validate_relative_path(self.root, consumption["evidence_path"])
580
+ consumer_state = "REVIEWED_EVIDENCE_RECORDED" if _hash(_read(evidence)) == consumption["evidence_sha256"] else "EVIDENCE_CHANGED_OR_MISSING"
581
+ plan = self._load_plan(pointer["plan_id"])
582
+ target = next(r for r in plan["targets"] if r["workspace"] == name)
583
+ root = self._binding(name, pointer["task_id"])
584
+ if str(root) != target["root"]:
585
+ fail("The registered workspace moved; regenerate its local entry in the new location.")
586
+ entry_matches = all(_hash(_read(private_target(root, w["path"]))) == w["after"] for w in target["writes"])
587
+ result.append({**pointer, "state": "PUBLISHED" if entry_matches else "ENTRY_CHANGED",
588
+ "thread_id": target["thread_id"],
589
+ "finalization_pending": self.store.get("workbench_current", name) != pointer,
590
+ "source_freshness": self._freshness(view), "consumer_state": consumer_state,
591
+ "consumption_id": selected.get("consumption_id"),
592
+ "view_path": str(self._path("views", pointer["view_id"], "view.md")),
593
+ "current_path": str(self._path("current", name + ".json")), "native_acceptance_verified": False})
594
+ except (GovernanceError, OSError, ValueError, StopIteration) as exc:
595
+ result.append({"workspace": name, "state": "UNVERIFIED", "error": str(exc)[:1000]})
596
+ return {"source": self.source(), "items": result, "next_cursor": rows[limit - 1][0] if len(rows) > limit else None,
597
+ "read_only": True, "meaning": "Current publication and reviewed evidence are separate; query Core for the latest task/checkpoint."}
598
+
599
+ def workbench(self, action="status", body=None, sources=None, view_id=None, targets=None, plan_id=None,
600
+ workspace=None, proof=None, limit=20, cursor=None, routing=None, thread_id=None):
601
+ if routing not in (None, 'shared') or (routing is not None and action not in ('plan', 'status')):
602
+ fail("Shared routing selects a new plan or status; execution uses its saved schema.", "INVALID_ARGUMENT")
603
+ if thread_id is not None and action != 'status':
604
+ fail("thread_id filters status only; targets/proof carry publication identities.", "INVALID_ARGUMENT")
605
+ from .shared_workbench import SharedWorkbench, PLAN
606
+ if action == 'plan' and routing == 'shared':
607
+ return SharedWorkbench(self.root).plan_shared(view_id, targets)
608
+ saved_id = plan_id if action == 'execute' else proof.get('plan_id') if action == 'consume' and isinstance(proof, dict) else None
609
+ if saved_id and (self.store.get('workbench_plans', saved_id) or {}).get('schema') == PLAN:
610
+ shared = SharedWorkbench(self.root)
611
+ return shared.execute_shared(saved_id) if action == 'execute' else shared.consume_shared(proof)
612
+ if action == 'status' and (routing == 'shared' or thread_id is not None
613
+ or self.store.list('workbench_directory_current')):
614
+ return SharedWorkbench(self.root).status_shared(workspace, thread_id, limit, cursor)
615
+ if action == "freeze":
616
+ return self._freeze(body, sources)
617
+ if action == "plan":
618
+ return self._plan(view_id, targets)
619
+ if action == "execute":
620
+ return self._execute(plan_id)
621
+ if action == "consume":
622
+ return self._consume(proof)
623
+ if action == "status":
624
+ return self._status(workspace, limit, cursor)
625
+ fail("Unknown workbench action.", "INVALID_ARGUMENT")