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,466 @@
1
+ """Read a bounded, project-shared view for the human at the local computer."""
2
+ from __future__ import annotations
3
+
4
+ from contextlib import contextmanager
5
+ import base64
6
+ from functools import lru_cache
7
+ import hashlib
8
+ import json
9
+ import re
10
+
11
+ from . import experience_storage
12
+ from .core import _linked
13
+ from .experience_notes import ExperienceNotes
14
+ from .feishu.display import document_title
15
+ from .identification import source
16
+ from .project_collaboration import ProjectCollaboration
17
+ from .store import GovernanceError
18
+ from .worker_channel import WorkerChannel, fail
19
+
20
+
21
+ PAGE = 12
22
+ PREVIEW_LIMIT = 64 * 1024
23
+ IMAGE_LIMIT = 4 * 1024 * 1024
24
+ TEXT_TYPES = {"text/plain", "text/markdown", "application/json"}
25
+ SOURCE_FLAGS = "json_extract(value,'$.visibility')='project' AND json_extract(value,'$.state')='active'"
26
+ SECTIONS = ("tasks", "members", "sources", "reviews", "experience")
27
+ STATES = {"tasks": {"open", "active", "waiting", "paused", "complete"},
28
+ "experience": {"current", "proposed", "active", "paused", "retired"},
29
+ "reviews": {"open", "pending", "needs_revision", "needs_decision", "received", "technically_received"}}
30
+ OPEN_REVIEW = "(verdict IS NULL OR verdict IN ('needs_revision','needs_decision'))"
31
+
32
+ # Older publishers record individual source events. A matching batch supersedes those rows.
33
+ SHARE_FEED = """WITH batched AS (
34
+ SELECT e.sequence seq,e.created_at at,j.key pos,json_extract(j.value,'$.reference_id') id,
35
+ json_extract(j.value,'$.revision') rev,json_extract(j.value,'$.content_sha256') sha
36
+ FROM events e JOIN json_each(e.payload,'$.references') j
37
+ WHERE e.kind='project_sources_shared' AND json_extract(e.payload,'$.project_id')=?),
38
+ shares AS (SELECT * FROM batched UNION ALL
39
+ SELECT e.sequence,e.created_at,0,json_extract(e.payload,'$.id'),json_extract(e.payload,'$.revision'),NULL
40
+ FROM events e LEFT JOIN batched b ON b.id=json_extract(e.payload,'$.id') AND b.rev=json_extract(e.payload,'$.revision')
41
+ WHERE e.kind='worker_source' AND b.seq IS NULL),
42
+ visible AS (SELECT s.*,v.value FROM shares s CROSS JOIN records c ON c.collection='worker_sources' AND c.key=s.id
43
+ CROSS JOIN records v ON v.collection='worker_versions' AND v.key='source:'||s.id||':'||s.rev
44
+ WHERE json_extract(c.value,'$.project_id')=? AND json_extract(c.value,'$.project_id')=json_extract(v.value,'$.project_id')
45
+ AND (s.sha IS NULL OR s.sha=json_extract(v.value,'$.content_sha256'))
46
+ AND json_extract(c.value,'$.visibility')='project' AND json_extract(c.value,'$.state')='active'
47
+ AND json_extract(v.value,'$.visibility')='project' AND json_extract(v.value,'$.state')='active') """
48
+
49
+
50
+ def fields(value, *names):
51
+ return {name: value.get(name) for name in names}
52
+
53
+
54
+ def source_fields(value):
55
+ return fields(value, "reference_id", "revision", "content_sha256", "display_title",
56
+ "task_id", "owner_binding_id", "media_type", "size")
57
+
58
+ def raster_dimensions(data, mime):
59
+ if mime == "image/png" and data.startswith(b"\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR") and len(data) >= 24:
60
+ return int.from_bytes(data[16:20], "big"), int.from_bytes(data[20:24], "big")
61
+ if mime == "image/jpeg" and data.startswith(b"\xff\xd8"):
62
+ pos = 2
63
+ while pos + 4 <= len(data) and data[pos] == 255:
64
+ marker = data[pos + 1]
65
+ if marker == 255:
66
+ pos += 1
67
+ continue
68
+ size = int.from_bytes(data[pos+2:pos+4], "big")
69
+ if size < 2 or pos + 2 + size > len(data) or marker in (0xDA, 0xD9):
70
+ break
71
+ if marker in (0xC0, 0xC1, 0xC2) and size >= 8:
72
+ return int.from_bytes(data[pos+7:pos+9], "big"), int.from_bytes(data[pos+5:pos+7], "big")
73
+ pos += 2 + size
74
+ return 0, 0
75
+
76
+
77
+ class SharedChannel(WorkerChannel):
78
+ """Use the original source/version rules, with project visibility at both ends."""
79
+ def _source(self, reference):
80
+ original = super()._source(reference)
81
+ current = self.store.get("worker_sources", reference["reference_id"])
82
+ if any(r.get("visibility") != "project" or r.get("state") != "active" or
83
+ r.get("project_id") != self.project_id for r in (original, current)):
84
+ fail("BOARD_SOURCE_UNAVAILABLE", "This revision is unavailable in the project board.")
85
+ return original
86
+
87
+
88
+ class BoardExperience(ExperienceNotes):
89
+ def feedback_visible(self, record):
90
+ return record.get("visibility", "task") != "self" and super().feedback_visible(record)
91
+
92
+
93
+ class BoardData:
94
+ def __init__(self, project):
95
+ self.channel = SharedChannel(project)
96
+ self.channel._auth("source_read")
97
+ self.store = self.channel.store
98
+ self.identity = self.channel.core.source()
99
+ self.project_id = self.identity["source_id"]
100
+ @lru_cache(maxsize=256)
101
+ def shared_title(digest, mime, size):
102
+ return document_title(self.store.root, {"content_sha256": digest, "media_type": mime, "size": size})
103
+ self.shared_title = shared_title
104
+
105
+ @staticmethod
106
+ def _task_title(db, task_id):
107
+ row = db.execute("SELECT json_extract(value,'$.title') FROM records WHERE collection='tasks' AND key=?",
108
+ (task_id,)).fetchone()
109
+ return row[0] if row and row[0] else task_id
110
+
111
+ def _source_fields(self, value, db=None):
112
+ info = source_fields(value)
113
+ if not info["display_title"]:
114
+ info["display_title"] = self.shared_title(info["content_sha256"], info["media_type"], info["size"]) or None
115
+ if db is not None:
116
+ info["task_title"] = self._task_title(db, info["task_id"])
117
+ return info
118
+
119
+ def _search_title(self, raw):
120
+ record = json.loads(raw)
121
+ if (record.get("project_id") == self.project_id and record.get("visibility") == "project"
122
+ and record.get("state") == "active" and record.get("reference_id")):
123
+ return (self._source_fields(record)["display_title"] or "").casefold()
124
+ return ""
125
+
126
+ @contextmanager
127
+ def snapshot(self):
128
+ with self.store._connect(readonly=True) as db:
129
+ self.store._local.connection = db
130
+ try:
131
+ cfg = self.store.get("config", "project") or {}
132
+ ident = source(self.store.root, cfg)
133
+ if (cfg.get("schema_version") != 1 or ident["source_id"] != self.project_id or
134
+ ident.get("replica_id") != self.identity.get("replica_id")):
135
+ fail("BOARD_PROJECT_CHANGED", "Reopen the intended project.")
136
+ yield db, cfg
137
+ finally:
138
+ self.store._local.connection = None
139
+
140
+ def brief(self, section=None, page=0, stamp=None, *, query="", owner="", state=""):
141
+ if section is not None and section not in SECTIONS or not 0 <= page <= 1_000_000:
142
+ raise ValueError("Invalid page")
143
+ if len(query) > 160 or len(owner) > 160 or ((query or owner) and section != "sources"):
144
+ raise ValueError("Invalid search")
145
+ if state and state not in STATES.get(section, ()):
146
+ raise ValueError("Invalid state")
147
+ with self.snapshot() as (db, cfg):
148
+ last = db.execute("SELECT sequence,created_at FROM events ORDER BY sequence DESC LIMIT 1").fetchone()
149
+ sequence, updated = last or (0, None)
150
+ if stamp is not None and stamp != sequence:
151
+ fail("BOARD_CHANGED", "Refresh to read the latest project snapshot.")
152
+ if section:
153
+ return self._section(db, section, page, query.strip(), owner, state)
154
+ result = {"project": cfg["name"], "standby": cfg.get("recovery_writer_state") == "standby",
155
+ "updated_at": updated, "stamp": sequence}
156
+ for name in SECTIONS:
157
+ result[name] = self._section(db, name, 0)
158
+ result["recent"] = self._recent(db, result["sources"]["items"])
159
+ result["owners"] = [dict(id=key, name=name or key) for key, name in db.execute("""
160
+ SELECT DISTINCT json_extract(s.value,'$.owner_binding_id'),json_extract(b.value,'$.display_name')
161
+ FROM records s LEFT JOIN records b ON b.collection='worker_bindings'
162
+ AND b.key=json_extract(s.value,'$.owner_binding_id')
163
+ WHERE s.collection='worker_sources' AND json_extract(s.value,'$.project_id')=?
164
+ AND json_extract(s.value,'$.state')='active' AND json_extract(s.value,'$.visibility')='project'
165
+ ORDER BY 2,1""", [self.project_id])]
166
+ return result
167
+
168
+ def _recent(self, db, fallback):
169
+ # Group only the members of the same committed share event, including its exact older versions.
170
+ rows = db.execute(SHARE_FEED + """, batches AS (SELECT DISTINCT seq FROM visible ORDER BY seq DESC LIMIT 5)
171
+ SELECT seq,at,value FROM visible JOIN batches USING(seq) ORDER BY seq DESC,pos""",
172
+ [self.project_id, self.project_id])
173
+ groups = {}
174
+ for seq, at, raw in rows:
175
+ groups.setdefault(seq, {"at": at, "items": []})["items"].append(self._source_fields(json.loads(raw), db))
176
+ result = list(groups.values())
177
+ for item in fallback:
178
+ if len(result) >= 5:
179
+ break
180
+ if not item["published_at"]:
181
+ result.append({"at": None, "items": [item]})
182
+ return result
183
+
184
+ def _section(self, db, section, page, query="", owner="", state=""):
185
+ if section == "reviews":
186
+ return self._reviews(db, page, state)
187
+ collection = {"sources": "worker_sources", "members": "worker_bindings",
188
+ "tasks": "tasks", "experience": "experience_notes"}[section]
189
+ where = "r.collection=?"
190
+ params = [collection]
191
+ if section != "tasks":
192
+ where += " AND json_extract(r.value,'$.project_id')=?"
193
+ params.append(self.project_id)
194
+ if section == "sources":
195
+ where += " AND " + SOURCE_FLAGS
196
+ if query:
197
+ db.create_function("board_search_title", 1, self._search_title)
198
+ where += " AND (instr(lower(r.key),lower(?)) OR instr(board_search_title(r.value),?))"
199
+ params.extend([query, query.casefold()])
200
+ if owner:
201
+ where += " AND json_extract(r.value,'$.owner_binding_id')=?"
202
+ params.append(owner)
203
+ if state == "open":
204
+ where += " AND json_extract(r.value,'$.state') IN ('active','waiting')"
205
+ elif state == "current":
206
+ where += " AND json_extract(r.value,'$.state')!='retired'"
207
+ elif state:
208
+ where += " AND json_extract(r.value,'$.state')=?"
209
+ params.append(state)
210
+ total = db.execute("SELECT count(*) FROM records r WHERE " + where, params).fetchone()[0]
211
+ metadata = {"total": total, "page": page, "more": (page + 1) * PAGE < total, "items": []}
212
+ if section == "experience":
213
+ try:
214
+ index_ready = experience_storage.ready(self.store)
215
+ except GovernanceError as exc:
216
+ if exc.code not in ("EXPERIENCE_INDEX_INCOMPLETE", "EXPERIENCE_SCHEMA_UNSUPPORTED"):
217
+ raise
218
+ index_ready = False
219
+ if not index_ready:
220
+ return {**metadata, "available": False}
221
+ if section == "sources":
222
+ # Old projects may predate the committed shared-event feed.
223
+ query = SHARE_FEED + """, published AS (SELECT id,rev,max(seq) seq,at FROM visible GROUP BY id,rev)
224
+ SELECT r.value,p.at FROM records r LEFT JOIN published p ON
225
+ p.id=r.key AND p.rev=json_extract(r.value,'$.revision')
226
+ WHERE """ + where + " ORDER BY p.seq DESC,r.key"
227
+ params = [self.project_id, self.project_id, *params]
228
+ else:
229
+ ordering = ("CASE json_extract(r.value,'$.state') WHEN 'active' THEN 0 WHEN 'waiting' THEN 1 "
230
+ "WHEN 'proposed' THEN 1 WHEN 'paused' THEN 2 ELSE 3 END, " if section in ("tasks", "experience") else "")
231
+ query = "SELECT r.value,NULL FROM records r WHERE " + where + " ORDER BY " + ordering + "r.key"
232
+ rows = db.execute(query + " LIMIT ? OFFSET ?", [*params, PAGE, page * PAGE]).fetchall()
233
+ records = [(json.loads(raw), published_at) for raw, published_at in rows]
234
+ if section == "members":
235
+ unnamed = {v["binding_id"] for v, _ in records if not v.get("display_name")}
236
+ legacy_names = ProjectCollaboration(self.channel).published_role_labels(db, unnamed)
237
+ for value, published_at in records:
238
+ if section == "tasks":
239
+ item = fields(value, "task_id", "title", "state", "latest_checkpoint", "next_step", "workstream")
240
+ elif section == "members":
241
+ item = fields(value, "binding_id", "display_name", "role", "state")
242
+ key = item["binding_id"]
243
+ item["role_label"] = item["display_name"] or legacy_names.get(key, key)
244
+ item["tasks"] = [a["task_id"] for a in value["assignments"]]
245
+ item["task_titles"] = [self._task_title(db, task_id) for task_id in item["tasks"]]
246
+ elif section == "sources":
247
+ item = {**self._source_fields(value, db), "published_at": published_at}
248
+ else:
249
+ item = self._experience(db, value)
250
+ metadata["items"].append(item)
251
+ return metadata
252
+
253
+ def _public_refs(self, record, db=None):
254
+ refs = record.get("sources", [])
255
+ if not refs:
256
+ return None
257
+ try:
258
+ return [self._source_fields(self.channel._source(ref), db) for ref in refs]
259
+ except GovernanceError:
260
+ return None
261
+
262
+ def _reviews(self, db, page, state=""):
263
+ # Select visible handbacks before counting/pagination. A later private revision
264
+ # or withdrawal also removes the reference from historical review summaries.
265
+ sql = """SELECT r.value FROM records r WHERE r.collection='worker_handbacks'
266
+ AND json_extract(r.value,'$.project_id')=? AND json_extract(r.value,'$.state')='submitted'
267
+ AND json_array_length(r.value,'$.sources')>0 AND NOT EXISTS (
268
+ SELECT 1 FROM json_each(r.value,'$.sources') j WHERE NOT EXISTS (
269
+ SELECT 1 FROM records c JOIN records v ON v.collection='worker_versions' AND
270
+ v.key='source:'||c.key||':'||json_extract(j.value,'$.revision')
271
+ WHERE c.collection='worker_sources' AND c.key=json_extract(j.value,'$.reference_id')
272
+ AND json_extract(c.value,'$.project_id')=json_extract(r.value,'$.project_id')
273
+ AND json_extract(v.value,'$.project_id')=json_extract(r.value,'$.project_id')
274
+ AND json_extract(c.value,'$.visibility')='project' AND json_extract(c.value,'$.state')='active'
275
+ AND json_extract(v.value,'$.visibility')='project' AND json_extract(v.value,'$.state')='active'
276
+ AND json_extract(v.value,'$.content_sha256')=json_extract(j.value,'$.content_sha256')))"""
277
+ with_status = """WITH visible AS (""" + sql + """), matched AS (
278
+ SELECT h.value,(SELECT json_extract(d.value,'$.verdict') FROM records d
279
+ WHERE d.collection='worker_dispositions'
280
+ AND json_extract(d.value,'$.project_id')=json_extract(h.value,'$.project_id')
281
+ AND json_extract(d.value,'$.handback_id')=json_extract(h.value,'$.handback_id')
282
+ AND json_extract(d.value,'$.handback_revision')=json_extract(h.value,'$.revision')
283
+ ORDER BY d.key LIMIT 1) verdict FROM visible h) """
284
+ selection = {"open": " WHERE " + OPEN_REVIEW, "pending": " WHERE verdict IS NULL"}.get(state)
285
+ params = [self.project_id]
286
+ if selection is None:
287
+ selection = " WHERE verdict=?" if state else ""
288
+ if state:
289
+ params.append(state)
290
+ count, pending = db.execute(with_status + "SELECT count(*),count(*) FILTER (WHERE " + OPEN_REVIEW +
291
+ ") FROM matched" + selection, params).fetchone()
292
+ rows = db.execute(with_status + "SELECT value,verdict FROM matched" + selection + " ORDER BY "
293
+ + OPEN_REVIEW + " DESC, "
294
+ "json_extract(value,'$.handback_id') LIMIT ? OFFSET ?",
295
+ [*params, PAGE, page * PAGE]).fetchall()
296
+ items = []
297
+ for raw, verdict in rows:
298
+ record = json.loads(raw)
299
+ previous = db.execute("""SELECT value FROM records WHERE collection='worker_versions'
300
+ AND key GLOB 'disposition:*'
301
+ AND json_extract(value,'$.project_id')=? AND json_extract(value,'$.handback_id')=?
302
+ AND json_extract(value,'$.handback_revision')<? AND json_extract(value,'$.verdict')
303
+ IN ('received','technically_received') AND NOT EXISTS (
304
+ SELECT 1 FROM records newer WHERE newer.collection='worker_versions'
305
+ AND newer.key GLOB 'disposition:*'
306
+ AND json_extract(newer.value,'$.disposition_id')=json_extract(records.value,'$.disposition_id')
307
+ AND json_extract(newer.value,'$.handback_revision')=json_extract(records.value,'$.handback_revision')
308
+ AND json_extract(newer.value,'$.revision')>json_extract(records.value,'$.revision'))
309
+ ORDER BY json_extract(value,'$.handback_revision') DESC LIMIT 1""",
310
+ [self.project_id, record["handback_id"], record["revision"]]).fetchone()
311
+ prior = None
312
+ if previous:
313
+ old = json.loads(previous[0])
314
+ history = self.store.get("worker_versions", "handback:" + record["handback_id"] + ":" + str(old["handback_revision"]))
315
+ if history and self._public_refs(history):
316
+ prior = fields(old, "handback_revision", "verdict")
317
+ items.append({**fields(record, "handback_id", "binding_id", "task_id", "revision", "next_step", "summary"),
318
+ "task_title": self._task_title(db, record["task_id"]),
319
+ "sources": self._public_refs(record, db), "verdict": verdict, "previous": prior})
320
+ return {"total": count, "pending": pending, "page": page, "more": (page + 1) * PAGE < count, "items": items}
321
+
322
+ def history(self, ref, page, stamp):
323
+ if not 0 <= page <= 1_000_000:
324
+ raise ValueError("Invalid history page")
325
+ with self.snapshot() as (db, _):
326
+ self.channel._source(ref)
327
+ if stamp != db.execute("SELECT coalesce(max(sequence),0) FROM events").fetchone()[0]:
328
+ fail("BOARD_CHANGED", "Refresh to read the latest project snapshot.")
329
+ rows = db.execute("""SELECT value FROM records WHERE collection='worker_versions'
330
+ AND key GLOB 'source:*' AND json_extract(value,'$.reference_id')=?
331
+ AND json_extract(value,'$.project_id')=? AND """ + SOURCE_FLAGS +
332
+ " ORDER BY json_extract(value,'$.revision') DESC LIMIT ? OFFSET ?",
333
+ [ref["reference_id"], self.project_id, PAGE + 1, page * PAGE]).fetchall()
334
+ items = [self._source_fields(json.loads(row[0]), db) for row in rows[:PAGE]]
335
+ by_revision = {(s["revision"], s["content_sha256"]): s for s in items}
336
+ for item in items:
337
+ item["receipts"] = []
338
+ if items:
339
+ # The source revision and the handback revision are independent counters.
340
+ records = db.execute("""SELECT h.value,json_extract(j.value,'$.revision'),json_extract(j.value,'$.content_sha256')
341
+ FROM records h JOIN json_each(h.value,'$.sources') j
342
+ WHERE h.collection='worker_versions' AND h.key GLOB 'handback:*'
343
+ AND json_extract(h.value,'$.project_id')=? AND json_extract(h.value,'$.state')='submitted'
344
+ AND json_extract(j.value,'$.reference_id')=?
345
+ AND json_extract(j.value,'$.revision') BETWEEN ? AND ?
346
+ ORDER BY json_extract(h.value,'$.revision') DESC,h.key""",
347
+ [self.project_id, ref["reference_id"], items[-1]["revision"], items[0]["revision"]])
348
+ for raw, rev, sha in records:
349
+ entry = by_revision.get((rev, sha))
350
+ if entry is None:
351
+ continue
352
+ handback = json.loads(raw)
353
+ hid = handback["handback_id"]
354
+ current = self.store.get("worker_handbacks", hid)
355
+ if not current or current["state"] != "submitted" or not self._public_refs(current) or not self._public_refs(handback):
356
+ continue
357
+ if len(entry["receipts"]) >= PAGE:
358
+ entry["more_receipts"] = True
359
+ continue
360
+ match = db.execute("""SELECT json_extract(value,'$.verdict') FROM records
361
+ WHERE collection='worker_versions' AND key GLOB 'disposition:*'
362
+ AND json_extract(value,'$.project_id')=? AND json_extract(value,'$.handback_id')=?
363
+ AND json_extract(value,'$.handback_revision')=? ORDER BY json_extract(value,'$.revision') DESC LIMIT 1""",
364
+ [self.project_id, hid, handback["revision"]]).fetchone()
365
+ entry["receipts"].append({"handback_id": hid, "revision": handback["revision"],
366
+ "verdict": match[0] if match else None})
367
+ return {"items": items, "more": len(rows) > PAGE, "page": page}
368
+
369
+ def _experience(self, db, note):
370
+ engine = BoardExperience(self.channel)
371
+ assessed = engine.assessed(note, {})
372
+ if assessed.get("content_withheld"):
373
+ return {**fields(note, "experience_id", "state", "revision"),
374
+ "withheld": True, "applicability": "unknown"}
375
+ basis = []
376
+ for ref in note.get("bound_versions", []):
377
+ historical = self.channel._source(ref)
378
+ current = self.store.get("worker_sources", ref["reference_id"])
379
+ basis.append({**self._source_fields(historical), "current_revision": current["revision"]})
380
+ readable = db.execute("""SELECT value FROM records WHERE collection='experience_feedback'
381
+ AND json_extract(value,'$.experience_id')=? AND json_extract(value,'$.note_revision')=?
382
+ AND coalesce(json_extract(value,'$.visibility'),'task')!='self' ORDER BY key LIMIT 65""",
383
+ [note["experience_id"], note["revision"]]).fetchall()
384
+ feedback = [record for (value,) in readable[:64] if engine.feedback_readable(record := json.loads(value))]
385
+ return {**fields(note, "experience_id", "state", "scope", "task_id", "revision", "problem", "suggestion",
386
+ "applies_when", "exclusions", "exclusion_groups", "reevaluate_when"),
387
+ **fields(assessed, "applicability", "review_needed", "reason_codes", "feedback_warning", "missing_evidence"),
388
+ "basis": basis,
389
+ "feedback_count": len(feedback),
390
+ "feedback": [fields(item, "owner_binding_id", "outcome", "summary") for item in feedback[:5]],
391
+ "feedback_limited": len(readable) > 64}
392
+
393
+ def _related_lessons(self, db, ref):
394
+ found = db.execute("""SELECT n.value FROM records n WHERE n.collection='experience_notes'
395
+ AND json_extract(n.value,'$.project_id')=? AND json_extract(n.value,'$.state')='active'
396
+ AND EXISTS (SELECT 1 FROM json_each(n.value,'$.bound_versions') b
397
+ WHERE json_extract(b.value,'$.reference_id')=?
398
+ UNION ALL SELECT 1 FROM json_each(n.value,'$.evidence_refs') e
399
+ WHERE json_extract(e.value,'$.reference_id')=?) ORDER BY n.key""",
400
+ [self.project_id, ref["reference_id"], ref["reference_id"]])
401
+ result = []
402
+ for (raw,) in found:
403
+ note = json.loads(raw)
404
+ info = self._experience(db, note)
405
+ if not info.get("withheld"):
406
+ cited = sorted({r["revision"] for r in [*note.get("bound_versions", []), *note.get("evidence_refs", [])]
407
+ if r["reference_id"] == ref["reference_id"]})
408
+ result.append({"note": info, "cited_revisions": cited})
409
+ if len(result) == 5:
410
+ break
411
+ return result
412
+
413
+ def preview(self, ref, offset=0):
414
+ if (not isinstance(ref.get("reference_id"), str) or type(ref.get("revision")) is not int
415
+ or ref["revision"] < 1 or not re.fullmatch(r"[0-9a-f]{64}", ref.get("content_sha256", ""))
416
+ or not 0 <= offset < PREVIEW_LIMIT):
417
+ raise ValueError("Invalid source reference")
418
+ with self.snapshot() as (db, _):
419
+ info = self.channel._source(ref)
420
+ current = self.store.get("worker_sources", ref["reference_id"])
421
+ related = self._related_lessons(db, ref)
422
+ meta = {**self._source_fields(info, db), "current": self._source_fields(current, db), "related": related,
423
+ "text": None, "next": None, "limited": False}
424
+ image = info["media_type"] in ("image/png", "image/jpeg")
425
+ if image and info["size"] > IMAGE_LIMIT:
426
+ return {**meta, "image_unavailable": "size"}
427
+ if not image and info["media_type"] not in TEXT_TYPES:
428
+ return meta
429
+ limit = IMAGE_LIMIT if image else PREVIEW_LIMIT
430
+ path = self.store.directory / "objects" / ref["content_sha256"]
431
+ if _linked(path.parent) or _linked(path) or not path.is_file() or path.stat().st_size != info["size"]:
432
+ fail("BOARD_SOURCE_UNAVAILABLE", "The exact source is unavailable.")
433
+ digest = hashlib.sha256()
434
+ excerpt = bytearray()
435
+ size = 0
436
+ with path.open("rb") as stream:
437
+ for block in iter(lambda: stream.read(65536), b""):
438
+ size += len(block)
439
+ if size > info["size"]:
440
+ fail("BOARD_SOURCE_UNAVAILABLE", "The source changed.")
441
+ digest.update(block)
442
+ if len(excerpt) < limit:
443
+ excerpt.extend(block[:limit-len(excerpt)])
444
+ if size != info["size"] or digest.hexdigest() != ref["content_sha256"]:
445
+ fail("BOARD_SOURCE_UNAVAILABLE", "The exact source could not be verified.")
446
+ with self.snapshot():
447
+ self.channel._source(ref)
448
+ if image:
449
+ width, height = raster_dimensions(excerpt, info["media_type"])
450
+ if offset or not (0 < width * height <= 16_777_216):
451
+ return {**meta, "image_unavailable": "format"}
452
+ return {**meta, "image": base64.b64encode(excerpt).decode("ascii"), "width": width, "height": height}
453
+ if offset > len(excerpt):
454
+ raise ValueError("Invalid preview offset")
455
+ end = min(len(excerpt), offset + 4096)
456
+ segment = bytes(excerpt[offset:end])
457
+ try:
458
+ text = segment.decode("utf-8")
459
+ except UnicodeDecodeError as exc:
460
+ if exc.reason != "unexpected end of data" or end == size:
461
+ fail("BOARD_SOURCE_UNAVAILABLE", "The source is not UTF-8 text.")
462
+ end = offset + exc.start
463
+ text = segment[:exc.start].decode("utf-8")
464
+ has_next = end < len(excerpt) and (len(excerpt) < PREVIEW_LIMIT or end < PREVIEW_LIMIT - 3)
465
+ return {**meta, "text": text, "next": end if has_next else None, "limited": not has_next and end < size}
466
+
@@ -0,0 +1,157 @@
1
+ """Project-local intake of explicit, observed chat-join receipts during a governance cycle."""
2
+ import json
3
+ from pathlib import Path, PurePosixPath
4
+
5
+ from .core import _id, digest_bytes, read_file_bytes, validate_relative_path
6
+ from .store import GovernanceError
7
+ from .workbench import Workbench
8
+
9
+
10
+ def require_join_scope(cycle):
11
+ if 'chat-joins' not in cycle['scope']:
12
+ raise GovernanceError('CYCLE_SCOPE_MISMATCH', 'Reserve chat-joins before handling project chat intake.')
13
+
14
+
15
+ def _receipt_error(message):
16
+ return GovernanceError('JOIN_RECEIPT_INVALID', message)
17
+
18
+
19
+ def _is_join(observation):
20
+ return PurePosixPath(observation['source_ref']).name == 'JOIN_RECEIPT.json'
21
+
22
+
23
+ def _observed_source_key(owner, observation):
24
+ fields = [observation[k] for k in ('workspace', 'task_id', 'source_ref', 'source_revision')]
25
+ return owner + ':source:' + digest_bytes(json.dumps(fields).encode())
26
+
27
+
28
+ def _same_binding(prior, item):
29
+ if prior and (prior['workspace'], prior['task_id']) != (item['workspace'], item['task_id']):
30
+ raise _receipt_error('The joined chat already belongs to another workspace or task; review the binding.')
31
+ return bool(prior)
32
+
33
+
34
+ def _summary_text(value, label):
35
+ if not isinstance(value, str) or len(value) > 8192:
36
+ raise _receipt_error(f'Use bounded text for {label}.')
37
+ return value
38
+
39
+
40
+ def _verified_join(engine, owner, observation):
41
+ path = validate_relative_path(engine.root, observation['source_ref'], allow_missing=False)
42
+ raw = read_file_bytes(path, max_bytes=256 * 1024)
43
+ if digest_bytes(raw) != observation['source_revision']:
44
+ raise _receipt_error('The join receipt differs from the observed SHA-256.')
45
+ try:
46
+ receipt = json.loads(raw)
47
+ except (ValueError, RecursionError) as exc:
48
+ raise _receipt_error('The join receipt is not readable JSON.') from exc
49
+ if not isinstance(receipt, dict) or receipt.get('schema') != 'taskcarry.chat-join-receipt.v1':
50
+ raise _receipt_error('Expected a project chat-join receipt v1.')
51
+ project = engine.source()
52
+ if (receipt.get('project_id') != project['source_id'] or not isinstance(receipt.get('control'), str)
53
+ or Path(receipt['control']) != engine.root):
54
+ raise _receipt_error('The project or control directory does not match this receiver.')
55
+ pending = receipt.get('pending_governance')
56
+ if not isinstance(pending, dict) or not isinstance(pending.get('owner_thread'), str):
57
+ raise _receipt_error('The receipt must identify its original governance chat.')
58
+ if pending['owner_thread'] != owner:
59
+ return None
60
+ if pending.get('status', 'pending_governance_absorption') != 'pending_governance_absorption':
61
+ raise _receipt_error('The receipt does not request governance intake.')
62
+ thread = _id(receipt.get('thread_id'), 'Chat ID')
63
+ task_id = _id(receipt.get('task_id'), 'Joined task')
64
+ workspace = _id(receipt.get('workspace'), 'Joined workspace')
65
+ if (observation.get('task_id'), observation.get('workspace')) != (task_id, workspace):
66
+ raise _receipt_error('The observed workspace and task must match the receipt.')
67
+ task = engine._task(task_id)
68
+ workbench = receipt.get('workbench')
69
+ if not isinstance(workbench, dict):
70
+ raise _receipt_error('A published and consumed chat entry is required.')
71
+ cid = _id(workbench.get('consumption_id'), 'Consumption ID')
72
+ view = _id(workbench.get('view_id'), 'View ID')
73
+ proof = engine.store.get('workbench_consumption', cid) or {}
74
+ expected = {'view_id': view, 'thread_id': thread, 'task_id': task_id, 'workspace': workspace}
75
+ if any(proof.get(k) != v for k, v in expected.items()):
76
+ raise _receipt_error('The consumption record does not match this exact chat, task and view.')
77
+ proof_file = validate_relative_path(engine.root, proof['evidence_path'], allow_missing=False)
78
+ if digest_bytes(read_file_bytes(proof_file)) != proof['evidence_sha256']:
79
+ raise _receipt_error('The evidence for the consumed view has changed.')
80
+ current = Workbench(engine.root).workbench('status', workspace=workspace, thread_id=thread)['items']
81
+ if not any(item.get('thread_id') == thread and item.get('task_id') == task_id
82
+ and item.get('state') == 'PUBLISHED' and not item.get('finalization_pending') for item in current):
83
+ raise _receipt_error('The chat no longer has a verified current entry for this task.')
84
+ progress = receipt.get('business_progress', {})
85
+ if not isinstance(progress, dict):
86
+ raise _receipt_error('Expected a business_progress object.')
87
+ return {'join_id': digest_bytes(json.dumps([project['source_id'], owner, thread]).encode()), 'thread_id': thread,
88
+ 'owner': owner, 'workspace': workspace, 'task_id': task_id, 'state': task['state'],
89
+ 'responsibility': _summary_text(receipt.get('responsibility', task['title']), 'responsibility'),
90
+ 'progress': _summary_text(progress.get('progress', progress.get('draft', '')), 'progress'),
91
+ 'waiting_for': _summary_text(progress.get('waiting_for', ''), 'waiting_for'),
92
+ 'next_step': _summary_text(progress.get('next_step', task.get('next_step', '')), 'next_step'),
93
+ 'observation_id': observation['observation_id'], 'source_ref': observation['source_ref'],
94
+ 'source_revision': observation['source_revision'], 'consumption_id': cid}
95
+
96
+
97
+ def join_inbox(engine, cycle, data, limit, cursor):
98
+ require_join_scope(cycle)
99
+ engine._fields(data, ('queue',))
100
+ owner = cycle['owner']
101
+ if data['queue'] == 'pending_report':
102
+ page = engine._page('chat_joins', prefix=owner + ':', cursor=cursor, limit=limit)
103
+ return {'items': [row for row in page['items'] if not row.get('delivery')],
104
+ 'needs_review': [], 'next_cursor': page['next_cursor']}
105
+ if data['queue'] != 'new':
106
+ raise _receipt_error('Choose the new or pending_report queue.')
107
+ page = engine._page('observations', cursor=cursor, limit=limit)
108
+ items, needs_review = {}, []
109
+ for observation in page['items']:
110
+ if not _is_join(observation):
111
+ continue
112
+ if engine.store.get('chat_join_observations', _observed_source_key(owner, observation)):
113
+ continue
114
+ try:
115
+ item = _verified_join(engine, owner, observation)
116
+ if item:
117
+ identity = item['join_id']
118
+ prior = items.get(identity) or engine.store.get('chat_joins', owner + ':' + identity)
119
+ if not _same_binding(prior, item):
120
+ items[identity] = item
121
+ except (GovernanceError, OSError) as exc:
122
+ needs_review.append({'observation_id': observation['observation_id'], 'error': str(exc)})
123
+ return {'items': list(items.values()), 'needs_review': needs_review, 'next_cursor': page['next_cursor']}
124
+
125
+
126
+ def absorb_join(engine, cycle, data):
127
+ require_join_scope(cycle)
128
+ engine._fields(data, ('observation_id', 'source_revision'))
129
+ oid = _id(data['observation_id'], 'Receipt observation ID')
130
+ observation = engine.store.get('observations', oid)
131
+ if not observation or not _is_join(observation) or observation['source_revision'] != data['source_revision']:
132
+ raise _receipt_error('Read the current observed join receipt before confirming it.')
133
+ item = _verified_join(engine, cycle['owner'], observation)
134
+ if item is None:
135
+ raise _receipt_error('The receipt is addressed to another governance chat.')
136
+ key = cycle['owner'] + ':' + item['join_id']
137
+ prior = engine.store.get('chat_joins', key)
138
+ if not _same_binding(prior, item):
139
+ engine.store.put('chat_joins', key, {**item, 'absorbed_in': cycle['cycle_id']})
140
+ engine.store.put('chat_join_observations', _observed_source_key(cycle['owner'], observation),
141
+ {'source_revision': data['source_revision'], 'join_id': item['join_id']})
142
+ return {'join_id': item['join_id'], 'newly_absorbed': prior is None}
143
+
144
+
145
+ def mark_joins_reported(engine, cycle, delivery):
146
+ require_join_scope(cycle)
147
+ ids = delivery['join_ids']
148
+ if (not isinstance(ids, list) or not 1 <= len(ids) <= 100
149
+ or any(not isinstance(value, str) for value in ids) or len(set(ids)) != len(ids)):
150
+ raise _receipt_error('List the distinct join IDs included in this delivered report.')
151
+ delivered = {field: delivery[field] for field in ('report_id', 'receipt_ref', 'delivered_at')}
152
+ for identity in ids:
153
+ key = cycle['owner'] + ':' + _id(identity, 'Reported join ID')
154
+ item = engine.store.get('chat_joins', key)
155
+ if not item or (item.get('delivery') and item['delivery'] != delivered):
156
+ raise _receipt_error('A join is missing or was already included in another delivered report.')
157
+ engine.store.put('chat_joins', key, {**item, 'delivery': delivered})