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.
- taskcarry/__init__.py +3 -0
- taskcarry/__main__.py +4 -0
- taskcarry/adapter_contracts.py +166 -0
- taskcarry/agy_turns.py +282 -0
- taskcarry/api.py +111 -0
- taskcarry/board.py +313 -0
- taskcarry/board_assets/board.css +1087 -0
- taskcarry/board_assets/board.js +1187 -0
- taskcarry/board_assets/browse.js +214 -0
- taskcarry/board_assets/index.html +43 -0
- taskcarry/board_assets/taskcarry-icon.ico +0 -0
- taskcarry/board_assets/taskcarry-mark.svg +28 -0
- taskcarry/board_data.py +466 -0
- taskcarry/chat_joins.py +157 -0
- taskcarry/cli.py +119 -0
- taskcarry/codex_capture.py +184 -0
- taskcarry/codex_host.py +293 -0
- taskcarry/collaboration_exchange.py +316 -0
- taskcarry/connection.py +159 -0
- taskcarry/continuity.py +300 -0
- taskcarry/contracts.py +165 -0
- taskcarry/conversation_capture.py +669 -0
- taskcarry/core.py +896 -0
- taskcarry/cycle_contracts.py +73 -0
- taskcarry/discovery.py +434 -0
- taskcarry/discovery_contracts.py +52 -0
- taskcarry/exchange_contracts.py +67 -0
- taskcarry/exchange_endpoint.py +377 -0
- taskcarry/exchange_packets.py +142 -0
- taskcarry/experience_contracts.py +129 -0
- taskcarry/experience_exchange.py +214 -0
- taskcarry/experience_notes.py +433 -0
- taskcarry/experience_storage.py +125 -0
- taskcarry/experience_tools.py +26 -0
- taskcarry/feishu/__init__.py +1 -0
- taskcarry/feishu/display.py +122 -0
- taskcarry/feishu/project_watch.py +145 -0
- taskcarry/feishu/review_sets.py +80 -0
- taskcarry/feishu/sender.py +42 -0
- taskcarry/feishu/subscription.py +193 -0
- taskcarry/feishu/windows_agent.py +287 -0
- taskcarry/feishu/windows_secret.py +34 -0
- taskcarry/gitops.py +170 -0
- taskcarry/governance.py +88 -0
- taskcarry/governance_cycle.py +775 -0
- taskcarry/identification.py +82 -0
- taskcarry/integration.py +663 -0
- taskcarry/maintenance.py +118 -0
- taskcarry/mcp.py +183 -0
- taskcarry/member_join.py +184 -0
- taskcarry/member_routing.py +145 -0
- taskcarry/onboarding.py +272 -0
- taskcarry/onboarding_complete.py +252 -0
- taskcarry/path_batches.py +19 -0
- taskcarry/preservation.py +257 -0
- taskcarry/project_collaboration.py +453 -0
- taskcarry/project_history.py +166 -0
- taskcarry/project_identity.py +51 -0
- taskcarry/project_recovery.py +824 -0
- taskcarry/recovery_contracts.py +25 -0
- taskcarry/recovery_files.py +153 -0
- taskcarry/recovery_git.py +234 -0
- taskcarry/remote_capture.py +89 -0
- taskcarry/remote_transfer.py +356 -0
- taskcarry/role_connection.py +215 -0
- taskcarry/setup.py +597 -0
- taskcarry/shared_workbench.py +480 -0
- taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
- taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
- taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
- taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
- taskcarry/source_review_set.py +80 -0
- taskcarry/state_format.py +47 -0
- taskcarry/store.py +472 -0
- taskcarry/task_context.py +141 -0
- taskcarry/text_handback.py +98 -0
- taskcarry/transfer_contracts.py +18 -0
- taskcarry/updates.py +351 -0
- taskcarry/workbench.py +625 -0
- taskcarry/workbench_contracts.py +32 -0
- taskcarry/workbuddy_capture.py +451 -0
- taskcarry/workbuddy_setup.py +212 -0
- taskcarry/worker_channel.py +859 -0
- taskcarry/worker_contracts.py +190 -0
- taskcarry/worker_storage.py +60 -0
- taskcarry/worker_tools.py +111 -0
- taskcarry-0.3.2.dist-info/METADATA +203 -0
- taskcarry-0.3.2.dist-info/RECORD +105 -0
- taskcarry-0.3.2.dist-info/WHEEL +5 -0
- taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
- taskcarry-0.3.2.dist-info/top_level.txt +2 -0
- taskcarry_https/__init__.py +1 -0
- taskcarry_https/consent.py +207 -0
- taskcarry_https/reader.py +132 -0
- taskcarry_https/review.py +116 -0
- taskcarry_https/server.py +163 -0
- taskcarry_https/team.py +335 -0
- taskcarry_https/team_host.py +109 -0
- taskcarry_https/web_host.py +82 -0
|
@@ -0,0 +1,453 @@
|
|
|
1
|
+
"""Curated snapshots, team discussions and targeted reads of consented turns."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from unicodedata import normalize
|
|
7
|
+
from datetime import datetime, timedelta, timezone
|
|
8
|
+
|
|
9
|
+
from .conversation_capture import SHARED_TURN_LIMIT, recent_turns
|
|
10
|
+
from .core import _id
|
|
11
|
+
from .project_history import ProjectHistory, bounded_text, detail_page, list_page, readable, teamscope
|
|
12
|
+
from .store import now
|
|
13
|
+
from .worker_channel import fail, fingerprint, packed
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def unavailable():
|
|
17
|
+
fail('COLLABORATION_UNAVAILABLE', 'The requested material is unavailable to this member.')
|
|
18
|
+
|
|
19
|
+
def sharing_state(store, epoch, owner):
|
|
20
|
+
with store._connect(readonly=True) as db:
|
|
21
|
+
enabled, generation = db.execute("""SELECT coalesce(sum(json_extract(value,'$.state')='active'),0),
|
|
22
|
+
coalesce(sum(json_extract(value,'$.generation')),0) FROM records WHERE collection='capture_sessions'
|
|
23
|
+
AND json_extract(value,'$.owner')=? AND json_extract(value,'$.epoch')=?""", (owner, epoch)).fetchone()
|
|
24
|
+
return {'mode':'recent_turns', 'retention_limit':SHARED_TURN_LIMIT, 'enabled_chats':enabled, 'settings_revision':generation,
|
|
25
|
+
'lookup':'taskcarry_turn_read'}
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def check_fields(record, allowed):
|
|
29
|
+
if not isinstance(record, dict) or set(record) - set(allowed.split()):
|
|
30
|
+
fail('COLLABORATION_INVALID', 'Unexpected collaboration record fields.')
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
class ProjectCollaboration:
|
|
34
|
+
def __init__(self, channel):
|
|
35
|
+
self.channel = channel
|
|
36
|
+
self.store = channel.store
|
|
37
|
+
self.history = ProjectHistory(channel)
|
|
38
|
+
|
|
39
|
+
def project_history(self, **args):
|
|
40
|
+
return self.history.read(**args)
|
|
41
|
+
|
|
42
|
+
def member_lookup(self, query, limit=8, cursor=None):
|
|
43
|
+
"""Resolve a label without loading any chat or revealing another project's roster."""
|
|
44
|
+
if not teamscope(self.channel):
|
|
45
|
+
unavailable()
|
|
46
|
+
name = bounded_text(query, 'member name', 160)
|
|
47
|
+
needle = normalize('NFKC', name).casefold()
|
|
48
|
+
with self.store._connect(readonly=True) as db:
|
|
49
|
+
members = db.execute("""SELECT key, json_extract(value,'$.display_name'), json_extract(value,'$.role')
|
|
50
|
+
FROM records WHERE collection='worker_bindings' AND json_extract(value,'$.project_id')=?
|
|
51
|
+
AND json_extract(value,'$.state')='active' ORDER BY key""", (self.channel.project_id,)).fetchall()
|
|
52
|
+
published = self.published_role_labels(db, {key for key, label, _ in members if not label})
|
|
53
|
+
candidates = {}
|
|
54
|
+
for key, display_name, role in members:
|
|
55
|
+
label = display_name or published.get(key, key)
|
|
56
|
+
item = {'binding_id': key, 'display_name': label, 'role': role}
|
|
57
|
+
if name == key:
|
|
58
|
+
candidates = {key: item}
|
|
59
|
+
break
|
|
60
|
+
names = {key, label, label.partition(' · ')[0]}
|
|
61
|
+
short = re.match(r'^([a-z]+\d+)-', key, re.I)
|
|
62
|
+
if short:
|
|
63
|
+
names.add(short[1])
|
|
64
|
+
if any(normalize('NFKC', value.strip()).casefold() == needle for value in names):
|
|
65
|
+
candidates[key] = item
|
|
66
|
+
count = len(candidates)
|
|
67
|
+
state = 'not_found' if not count else ('matched' if count == 1 else 'ambiguous')
|
|
68
|
+
return list_page(self.channel, lambda after: ((k, v) for k, v in candidates.items() if k > after),
|
|
69
|
+
['member_lookup', needle, list(candidates.values())], cursor, limit,
|
|
70
|
+
state=state, total=count, raw_turns_loaded=0)
|
|
71
|
+
|
|
72
|
+
def published_role_labels(self, db, unnamed):
|
|
73
|
+
"""Recover an older role's label only from an unambiguous published workline."""
|
|
74
|
+
if not unnamed:
|
|
75
|
+
return {}
|
|
76
|
+
entries = self.store.get("project_snapshots", "current", {}).get("entries", [])
|
|
77
|
+
if not entries:
|
|
78
|
+
return {}
|
|
79
|
+
owners = {}
|
|
80
|
+
for (key,) in db.execute("SELECT key FROM records WHERE collection='worker_bindings' "
|
|
81
|
+
"AND json_extract(value,'$.project_id')=?", (self.channel.project_id,)):
|
|
82
|
+
owners.setdefault(key.casefold(), set()).add(key)
|
|
83
|
+
short = re.match(r"^([a-z]+\d+)-", key, re.I)
|
|
84
|
+
if short:
|
|
85
|
+
owners.setdefault(short[1].casefold(), set()).add(key)
|
|
86
|
+
labels = {}
|
|
87
|
+
for entry in entries:
|
|
88
|
+
owner = entry.get("owner", "").strip().casefold()
|
|
89
|
+
keys = owners.get(owner, set())
|
|
90
|
+
if entry["kind"] != "workline" or len(keys) != 1 or keys.isdisjoint(unnamed):
|
|
91
|
+
continue
|
|
92
|
+
prefix, separator, name = entry["title"].partition(" · ")
|
|
93
|
+
if separator and name.strip() and prefix.strip().casefold() == owner and self.visible(entry):
|
|
94
|
+
key, = keys
|
|
95
|
+
labels.setdefault(key, set()).add(entry["title"])
|
|
96
|
+
return {key: next(iter(titles)) for key, titles in labels.items() if len(titles) == 1}
|
|
97
|
+
|
|
98
|
+
def ref_list(self, value):
|
|
99
|
+
if not isinstance(value, list) or len(value) > 16:
|
|
100
|
+
fail('COLLABORATION_INVALID', 'Select up to 16 exact shared sources.')
|
|
101
|
+
for ref in value:
|
|
102
|
+
if not isinstance(ref, dict) or set(ref) != {'reference_id','revision','content_sha256'}:
|
|
103
|
+
fail('COLLABORATION_INVALID', 'Supply exact source references.')
|
|
104
|
+
version = self.channel._source(ref)
|
|
105
|
+
current = self.store.get('worker_sources', ref['reference_id'])
|
|
106
|
+
if any(s['state'] != 'active' or s['visibility'] != 'project' for s in (current, version)):
|
|
107
|
+
unavailable()
|
|
108
|
+
return value
|
|
109
|
+
|
|
110
|
+
def visible(self, record):
|
|
111
|
+
refs = record.get('sources', [])
|
|
112
|
+
if not readable(self.channel, refs):
|
|
113
|
+
return False
|
|
114
|
+
return teamscope(self.channel) or (record.get('audience') == 'selected' and bool(refs)
|
|
115
|
+
and all(ref in self.channel.binding.get('read_references', ()) for ref in refs))
|
|
116
|
+
|
|
117
|
+
def decision(self, pointer, *, current=False):
|
|
118
|
+
if not isinstance(pointer, dict) or set(pointer) != {'kind','key','sha256'} or pointer['kind'] != 'decision':
|
|
119
|
+
fail('COLLABORATION_DECISION_REQUIRED', 'Link the exact registered decision and fingerprint.')
|
|
120
|
+
item = self.history.exact('decision', pointer['key'], pointer['sha256'])
|
|
121
|
+
if current:
|
|
122
|
+
base, _, _ = pointer['key'].rpartition(':')
|
|
123
|
+
latest = self.store.get('governance_facts', base)
|
|
124
|
+
if not latest or latest['revision'] != item['revision'] or latest['standing'] != 'current':
|
|
125
|
+
fail('COLLABORATION_DECISION_REQUIRED', 'Use the effective decision revision.')
|
|
126
|
+
return pointer
|
|
127
|
+
|
|
128
|
+
def entry(self, data):
|
|
129
|
+
check_fields(data, 'id kind title summary owner state task_id sources decision audience')
|
|
130
|
+
result = {'id': _id(data.get('id'), 'Entry'), 'kind': data.get('kind'),
|
|
131
|
+
'title': bounded_text(data.get('title'), 'title', 100),
|
|
132
|
+
'summary': bounded_text(data.get('summary'), 'summary', 440),
|
|
133
|
+
'audience': data.get('audience', 'internal'),
|
|
134
|
+
'sources': self.ref_list(data.get('sources', []))}
|
|
135
|
+
if result['kind'] not in ('workline','milestone','decision') or result['audience'] not in ('internal','selected'):
|
|
136
|
+
fail('COLLABORATION_INVALID', 'Unknown entry kind or audience.')
|
|
137
|
+
if result['audience'] == 'selected' and (not result['sources'] or data.get('decision')):
|
|
138
|
+
fail('COLLABORATION_SCOPE_DENIED', 'An external entry needs approved source versions only.')
|
|
139
|
+
for key in ('owner','state'):
|
|
140
|
+
if key in data:
|
|
141
|
+
result[key] = bounded_text(data[key], key, 120)
|
|
142
|
+
if 'task_id' in data:
|
|
143
|
+
self.channel.core._task(data['task_id'])
|
|
144
|
+
result['task_id'] = data['task_id']
|
|
145
|
+
if 'decision' in data:
|
|
146
|
+
result['decision'] = self.decision(data['decision'])
|
|
147
|
+
return result
|
|
148
|
+
|
|
149
|
+
def overview_publish(self, mode, expected_revision=None, entries=None, plan_id=None):
|
|
150
|
+
self.channel._governor()
|
|
151
|
+
if mode == 'execute':
|
|
152
|
+
return self.channel._execute('overview_publish', plan_id)
|
|
153
|
+
if mode != 'plan' or not isinstance(entries, list) or len(entries) > 128:
|
|
154
|
+
fail('COLLABORATION_INVALID', 'Plan a snapshot with up to 128 entries.')
|
|
155
|
+
rows = [self.entry(entry) for entry in entries]
|
|
156
|
+
if len({row['id'] for row in rows}) != len(rows):
|
|
157
|
+
fail('COLLABORATION_INVALID', 'Snapshot entry IDs must be unique.')
|
|
158
|
+
head = self.store.get('project_snapshots', 'current') or {}
|
|
159
|
+
if expected_revision != head.get('revision', 0):
|
|
160
|
+
fail('WORKER_REVISION_CONFLICT', 'Read the current snapshot before updating it.')
|
|
161
|
+
result = self.channel._plan('overview_publish', {'entries': rows}, {'expected': expected_revision})
|
|
162
|
+
result['review'] = {'entry_count': len(rows), 'entries_sha256': fingerprint(rows), 'expected_revision': expected_revision}
|
|
163
|
+
return result
|
|
164
|
+
|
|
165
|
+
def apply_overview(self, payload, guards):
|
|
166
|
+
self.channel._governor()
|
|
167
|
+
rows = [self.entry(row) for row in payload['entries']]
|
|
168
|
+
head = self.store.get('project_snapshots', 'current') or {}
|
|
169
|
+
if head.get('revision', 0) != guards['expected']:
|
|
170
|
+
fail('WORKER_REVISION_CONFLICT', 'The snapshot has changed.')
|
|
171
|
+
digest = fingerprint(rows)
|
|
172
|
+
if head.get('sha256') == digest:
|
|
173
|
+
return {'revision': head['revision'], 'sha256': digest, 'effects_executed': False}
|
|
174
|
+
snap = {'revision': guards['expected'] + 1, 'entries': rows, 'sha256': digest, 'updated_at': now()}
|
|
175
|
+
snap['event_position'] = self.store._local.connection.execute('SELECT coalesce(max(sequence),0) FROM events').fetchone()[0]
|
|
176
|
+
self.store.put('project_snapshots', str(snap['revision']), snap)
|
|
177
|
+
self.store.put('project_snapshots', 'current', snap)
|
|
178
|
+
self.store.event('project_snapshot_published', {'revision': snap['revision'], 'sha256': digest})
|
|
179
|
+
return {'revision': snap['revision'], 'sha256': digest, 'effects_executed': True}
|
|
180
|
+
|
|
181
|
+
def project_overview(self, revision=None, entry_id=None, limit=8, cursor=None):
|
|
182
|
+
full = teamscope(self.channel)
|
|
183
|
+
if revision is not None and not full:
|
|
184
|
+
unavailable()
|
|
185
|
+
head = self.store.get('project_snapshots', 'current') or {'revision': 0, 'entries': []}
|
|
186
|
+
snap = head if revision is None else self.store.get('project_snapshots', str(revision))
|
|
187
|
+
if snap is None:
|
|
188
|
+
unavailable()
|
|
189
|
+
def projected(row):
|
|
190
|
+
if not self.visible(row):
|
|
191
|
+
return False
|
|
192
|
+
if revision is not None:
|
|
193
|
+
live = by_id.get(row['id'])
|
|
194
|
+
return live is None or self.visible(live)
|
|
195
|
+
return True
|
|
196
|
+
by_id = {row['id']: row for row in head['entries']}
|
|
197
|
+
shown = sorted((row for row in snap['entries'] if projected(row)), key=lambda row: row['id'])
|
|
198
|
+
stamp = fingerprint(shown)
|
|
199
|
+
info = {'view_sha256': stamp, 'entry_count': len(shown),
|
|
200
|
+
'project': self.store.get('config', 'project')['name']}
|
|
201
|
+
if full:
|
|
202
|
+
info.update(revision=snap['revision'], updated_at=snap.get('updated_at'), published=bool(snap['revision']))
|
|
203
|
+
if snap.get('event_position') is not None:
|
|
204
|
+
with self.store._connect(readonly=True) as db:
|
|
205
|
+
info['later_evidence'] = bool(db.execute("SELECT 1 FROM events WHERE sequence>? AND kind IN "
|
|
206
|
+
"('governance_fact_recorded','worker_handback','worker_disposition','stage_received') LIMIT 1",
|
|
207
|
+
(snap['event_position'],)).fetchone())
|
|
208
|
+
if entry_id:
|
|
209
|
+
entry = next((row for row in shown if row['id'] == entry_id), None)
|
|
210
|
+
if not entry:
|
|
211
|
+
unavailable()
|
|
212
|
+
return {**info, 'entry': entry}
|
|
213
|
+
def rows(after):
|
|
214
|
+
for row in shown:
|
|
215
|
+
if row['id'] > after:
|
|
216
|
+
yield row['id'], {k: row[k] for k in ('id','title','kind','summary','owner','state') if k in row}
|
|
217
|
+
return list_page(self.channel, rows, ['snapshot', stamp], cursor, limit, **info)
|
|
218
|
+
|
|
219
|
+
def _topic(self, topic_id, revision=None):
|
|
220
|
+
head = self.store.get('discussion_topics', _id(topic_id, 'Topic'))
|
|
221
|
+
if not head or not self.visible(head):
|
|
222
|
+
unavailable()
|
|
223
|
+
if revision is None:
|
|
224
|
+
return head
|
|
225
|
+
item = self.store.get('discussion_versions', f'{topic_id}:{revision}')
|
|
226
|
+
if not item or not self.visible(item):
|
|
227
|
+
unavailable()
|
|
228
|
+
return item
|
|
229
|
+
|
|
230
|
+
def discussion(self, topic_id=None, revision=None, state=None, task_id=None, participant=None,
|
|
231
|
+
query=None, since=None, until=None, limit=8, cursor=None, offset=None):
|
|
232
|
+
if topic_id:
|
|
233
|
+
topic = self._topic(topic_id, revision)
|
|
234
|
+
pointer = self.store.get('discussion_turn_links', f"{topic_id}:{topic['revision']}")
|
|
235
|
+
if pointer:
|
|
236
|
+
session = self.store.get('capture_sessions', pointer['conversation_id'])
|
|
237
|
+
entries = self.turn_index(session) if teamscope(self.channel) else []
|
|
238
|
+
if not any(all(entry[k] == pointer[k] for k in ('turn_id','revision','sha256')) for entry in entries):
|
|
239
|
+
pointer = None
|
|
240
|
+
result = {'topic': topic, 'turn': pointer, 'sha256': fingerprint(topic), 'raw_turns_loaded': 0}
|
|
241
|
+
if offset is not None or len(packed(result)) > 6000:
|
|
242
|
+
return detail_page(packed(result), offset or 0, topic_id=topic_id, revision=topic['revision'],
|
|
243
|
+
sha256=fingerprint(topic), raw_turns_loaded=0)
|
|
244
|
+
return result
|
|
245
|
+
if revision is not None:
|
|
246
|
+
unavailable()
|
|
247
|
+
needle = (query or '').strip().casefold()
|
|
248
|
+
recent = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat()
|
|
249
|
+
def rows(after):
|
|
250
|
+
with self.store._connect(readonly=True) as db:
|
|
251
|
+
sql = ("SELECT key,value FROM records WHERE collection='discussion_topics' ORDER BY "
|
|
252
|
+
"json_extract(value,'$.updated_at') DESC,key")
|
|
253
|
+
for id_, raw in db.execute(sql):
|
|
254
|
+
item = json.loads(raw)
|
|
255
|
+
# Inverting timestamp digits gives a sortable key for newest-first pagination.
|
|
256
|
+
order = item['updated_at'].translate(str.maketrans('0123456789','9876543210')) + '|' + id_
|
|
257
|
+
if order <= after or not self.visible(item):
|
|
258
|
+
continue
|
|
259
|
+
if (state and item['state'] != state) or (not state and item['state'] == 'archived'):
|
|
260
|
+
continue
|
|
261
|
+
if not state and item['state'] == 'resolved' and item['updated_at'] < recent:
|
|
262
|
+
continue
|
|
263
|
+
if task_id and item['task_id'] != task_id or participant and participant not in item['participants']:
|
|
264
|
+
continue
|
|
265
|
+
if since and item['updated_at'] < since or until and item['updated_at'] > until:
|
|
266
|
+
continue
|
|
267
|
+
if needle and needle not in (item['title'] + ' ' + item['summary'] + ' ' + id_).casefold():
|
|
268
|
+
continue
|
|
269
|
+
preview = {k: item[k] for k in ('topic_id','task_id','title','state','revision','owner','author','updated_at')}
|
|
270
|
+
yield order, {**preview, 'summary': item['summary'][:220]}
|
|
271
|
+
return list_page(self.channel, rows, ['topics',state,task_id,participant,needle,since,until], cursor, limit,
|
|
272
|
+
raw_turns_loaded=0)
|
|
273
|
+
|
|
274
|
+
def discussion_update(self, mode, topic_id=None, task_id=None, workspace_id=None, expected_revision=None,
|
|
275
|
+
record=None, plan_id=None):
|
|
276
|
+
if mode == 'execute':
|
|
277
|
+
return self.channel._execute('discussion_update', plan_id)
|
|
278
|
+
if mode != 'plan':
|
|
279
|
+
fail('COLLABORATION_INVALID', 'Use discussion to read a topic.')
|
|
280
|
+
payload = {'topic_id': topic_id, 'task_id': task_id, 'workspace_id': workspace_id, 'record': record}
|
|
281
|
+
topic = self.prepare_topic(payload, expected_revision)
|
|
282
|
+
guards = {'expected': expected_revision}
|
|
283
|
+
if record.get('include_current_turn'):
|
|
284
|
+
cid = topic['conversation_id']
|
|
285
|
+
session = self.store.get('capture_sessions', cid)
|
|
286
|
+
capture = {'conversation_id': cid, 'generation': session['generation'], 'start': session['cursor']}
|
|
287
|
+
if session['provider'] == 'codex':
|
|
288
|
+
from pathlib import Path
|
|
289
|
+
from . import codex_capture
|
|
290
|
+
root = self.channel._assignment(task_id, workspace_id, 'progress')[0]
|
|
291
|
+
if cid not in codex_capture.chats(Path.home(), root, cid):
|
|
292
|
+
unavailable()
|
|
293
|
+
rows, _ = codex_capture.turns(codex_capture.reader(Path.home()), cid, limit=1)
|
|
294
|
+
if (not rows or rows[0][0] == session.get('frontier')
|
|
295
|
+
or rows[0][1] not in ('inProgress', 'interrupted')):
|
|
296
|
+
fail('CAPTURE_UNAVAILABLE', 'Start a new turn in the selected chat after enabling capture.')
|
|
297
|
+
capture['turn_id'] = rows[0][0]
|
|
298
|
+
guards['capture'] = capture
|
|
299
|
+
result = self.channel._plan('discussion_update', payload, guards)
|
|
300
|
+
result['review'] = {k:topic[k] for k in ('topic_id','title','action','revision','summary','audience')}
|
|
301
|
+
return result
|
|
302
|
+
|
|
303
|
+
def prepare_topic(self, payload, expected):
|
|
304
|
+
self.channel._assignment(payload['task_id'], payload['workspace_id'], 'progress')
|
|
305
|
+
if not teamscope(self.channel) or not self.channel.binding.get('share_project'):
|
|
306
|
+
unavailable()
|
|
307
|
+
tid = _id(payload['topic_id'], 'Topic')
|
|
308
|
+
record = payload['record']
|
|
309
|
+
check_fields(record, 'action title summary sources decision conversation_id include_current_turn notify audience')
|
|
310
|
+
prior = self.store.get('discussion_topics', tid)
|
|
311
|
+
if prior and not self.visible(prior):
|
|
312
|
+
unavailable()
|
|
313
|
+
if type(expected) is not int or expected != (prior['revision'] if prior else 0):
|
|
314
|
+
fail('WORKER_REVISION_CONFLICT', 'Read the current topic before replying.')
|
|
315
|
+
action = record.get('action')
|
|
316
|
+
if (not prior and action != 'open') or (prior and action not in ('update','reply','resolve','archive','reopen')):
|
|
317
|
+
fail('COLLABORATION_INVALID', 'Use open for a new topic and an explicit action for a revision.')
|
|
318
|
+
actor = self.channel.actor
|
|
319
|
+
if prior and (action != 'reply' or 'title' in record) and prior['owner'] != actor:
|
|
320
|
+
self.channel._governor()
|
|
321
|
+
if prior and prior['state'] != 'open' and action not in ('reopen','archive'):
|
|
322
|
+
fail('COLLABORATION_INVALID', 'Reopen the topic before continuing the discussion.')
|
|
323
|
+
audience = record.get('audience', prior['audience'] if prior else 'internal')
|
|
324
|
+
if audience not in ('selected','internal'):
|
|
325
|
+
fail('COLLABORATION_INVALID', 'Unknown audience.')
|
|
326
|
+
if audience == 'selected' or prior and audience != prior['audience']:
|
|
327
|
+
self.channel._governor()
|
|
328
|
+
sources = self.ref_list(record.get('sources', prior.get('sources', []) if prior else []))
|
|
329
|
+
if prior and any(ref not in sources for ref in prior['sources']) and action == 'reply':
|
|
330
|
+
fail('COLLABORATION_SCOPE_DENIED', 'A reply must retain its parent source scope.')
|
|
331
|
+
if audience == 'selected' and (not sources or (prior and prior['audience'] == 'internal')
|
|
332
|
+
or record.get('conversation_id') or record.get('include_current_turn') or action == 'resolve'):
|
|
333
|
+
fail('COLLABORATION_SCOPE_DENIED', 'Externally selected topics may cite approved source versions only.')
|
|
334
|
+
decision = None
|
|
335
|
+
if action == 'resolve':
|
|
336
|
+
decision = self.decision(record.get('decision'), current=True)
|
|
337
|
+
elif 'decision' in record:
|
|
338
|
+
fail('COLLABORATION_INVALID', 'Attach the effective decision when resolving the topic.')
|
|
339
|
+
conversation = record.get('conversation_id', prior.get('conversation_id') if prior else None)
|
|
340
|
+
attach = record.get('include_current_turn', False)
|
|
341
|
+
if type(attach) is not bool:
|
|
342
|
+
fail('COLLABORATION_INVALID', 'include_current_turn must be boolean.')
|
|
343
|
+
if attach:
|
|
344
|
+
choices = [s for s in self.store.list('capture_sessions') if s['owner'] == actor
|
|
345
|
+
and s['task_id'] == payload['task_id'] and s['state'] == 'active'
|
|
346
|
+
and s['epoch'] == self.channel._epoch()
|
|
347
|
+
and (not record.get('conversation_id') or s['conversation_id'] == record['conversation_id'])]
|
|
348
|
+
if not choices:
|
|
349
|
+
fail('CAPTURE_UNAVAILABLE', 'Open Tasks & people on the local board and turn on Save transcript '
|
|
350
|
+
'for this chat on the member card. Then retry the discussion update in a new turn.')
|
|
351
|
+
if len(choices) > 1:
|
|
352
|
+
fail('CAPTURE_UNAVAILABLE', 'Several chats have capture enabled for this role. '
|
|
353
|
+
'Supply the current conversation_id to attach this turn.')
|
|
354
|
+
conversation = choices[0]['conversation_id']
|
|
355
|
+
if conversation and (not prior or conversation != prior.get('conversation_id')):
|
|
356
|
+
session = self.store.get('capture_sessions', _id(conversation, 'Conversation'))
|
|
357
|
+
if not session or session['owner'] != actor or session['task_id'] != payload['task_id']:
|
|
358
|
+
unavailable()
|
|
359
|
+
if 'notify' in record and type(record['notify']) is not bool:
|
|
360
|
+
fail('COLLABORATION_INVALID', 'notify must be a boolean.')
|
|
361
|
+
title = bounded_text(record.get('title', prior['title'] if prior else None), 'title', 96)
|
|
362
|
+
return {'topic_id': tid, 'revision': expected + 1, 'parent_revision': expected or None,
|
|
363
|
+
'task_id': prior['task_id'] if prior else payload['task_id'], 'reply_task_id': payload['task_id'],
|
|
364
|
+
'owner': prior['owner'] if prior else actor, 'author': actor, 'title': title, 'audience': audience,
|
|
365
|
+
'participants': sorted(set((prior['participants'] if prior else []) + [actor])),
|
|
366
|
+
'action': action, 'summary': bounded_text(record.get('summary'), 'memo', 1200), 'sources': sources,
|
|
367
|
+
'state': {'resolve':'resolved','archive':'archived','reopen':'open'}.get(action, 'open'),
|
|
368
|
+
'decision': decision or (prior.get('decision') if prior and action == 'archive' else None),
|
|
369
|
+
'conversation_id': conversation}
|
|
370
|
+
|
|
371
|
+
def apply_discussion(self, payload, guards):
|
|
372
|
+
item = self.prepare_topic(payload, guards['expected'])
|
|
373
|
+
capture = guards.get('capture')
|
|
374
|
+
if payload['record'].get('include_current_turn'):
|
|
375
|
+
cid = item['conversation_id']
|
|
376
|
+
session = self.store.get('capture_sessions', cid)
|
|
377
|
+
if (not capture or capture['conversation_id'] != cid or capture['generation'] != session['generation']
|
|
378
|
+
or (session['provider'] != 'codex' and capture['start'] != session['cursor'])):
|
|
379
|
+
fail('CAPTURE_CHANGED', 'The selected turn changed. Prepare a new discussion update.')
|
|
380
|
+
item['updated_at'] = now()
|
|
381
|
+
key = item['topic_id']
|
|
382
|
+
self.store.put('discussion_versions', f"{key}:{item['revision']}", item)
|
|
383
|
+
self.store.put('discussion_topics', key, item)
|
|
384
|
+
if capture:
|
|
385
|
+
self.store.put('capture_topic_requests', f"{cid}:{key}:{item['revision']}",
|
|
386
|
+
{**capture, 'topic': key, 'revision': item['revision']})
|
|
387
|
+
if capture.get('turn_id'):
|
|
388
|
+
meta = self.store.get('capture_turn_index', cid + ':' + capture['turn_id'])
|
|
389
|
+
if meta:
|
|
390
|
+
self.store.put('discussion_turn_links', f"{key}:{item['revision']}",
|
|
391
|
+
{'conversation_id': cid, 'turn_id': capture['turn_id'],
|
|
392
|
+
'revision': meta['revision'], 'sha256': meta['sha256']})
|
|
393
|
+
event = {'project_id': self.channel.project_id, 'topic_id': key, 'revision': item['revision'],
|
|
394
|
+
'actor': self.channel.actor, 'sha256': fingerprint(item)}
|
|
395
|
+
self.store.event('discussion_shared', event)
|
|
396
|
+
if payload['record'].get('notify'):
|
|
397
|
+
self.store.event('discussion_attention', event)
|
|
398
|
+
return {**event, 'state': item['state'], 'effects_executed': True}
|
|
399
|
+
|
|
400
|
+
def turn_index(self, session):
|
|
401
|
+
if not session or session.get('epoch') != self.channel._epoch():
|
|
402
|
+
return []
|
|
403
|
+
return recent_turns(self.store, session)
|
|
404
|
+
|
|
405
|
+
def turn_read(self, conversation_id=None, turn_id=None, revision=None, limit=8, cursor=None, offset=0, owner=None):
|
|
406
|
+
if not teamscope(self.channel):
|
|
407
|
+
unavailable()
|
|
408
|
+
owner = _id(owner, 'Member') if owner is not None else None
|
|
409
|
+
epoch = self.channel._epoch()
|
|
410
|
+
if conversation_id is None:
|
|
411
|
+
if turn_id is not None or revision is not None or offset:
|
|
412
|
+
unavailable()
|
|
413
|
+
member = owner or self.channel.actor
|
|
414
|
+
scope = sharing_state(self.store, epoch, member)
|
|
415
|
+
def sessions(after):
|
|
416
|
+
with self.store._connect(readonly=True) as db:
|
|
417
|
+
for cid, raw in db.execute("""SELECT key,value FROM records WHERE collection='capture_sessions'
|
|
418
|
+
AND json_extract(value,'$.epoch')=? AND json_extract(value,'$.owner')=? AND key>? ORDER BY key""",
|
|
419
|
+
(epoch, member, after)):
|
|
420
|
+
s = json.loads(raw)
|
|
421
|
+
entries = self.turn_index(s)
|
|
422
|
+
if member != self.channel.actor and not entries:
|
|
423
|
+
continue
|
|
424
|
+
yield cid, {'conversation_id':cid, 'sharing':'on' if s['state']=='active' else 'off',
|
|
425
|
+
'latest':entries[0] if entries else None, 'retained_turns':len(entries)}
|
|
426
|
+
return list_page(self.channel, sessions, ['sharing',member,epoch,scope['settings_revision']], cursor, limit,
|
|
427
|
+
owner=member, **scope, raw_turns_loaded=0)
|
|
428
|
+
cid = _id(conversation_id, 'Conversation')
|
|
429
|
+
session = self.store.get('capture_sessions', cid)
|
|
430
|
+
if not session or session['epoch'] != epoch or (owner and session['owner'] != owner):
|
|
431
|
+
unavailable()
|
|
432
|
+
entries = self.turn_index(session)
|
|
433
|
+
if turn_id:
|
|
434
|
+
key = cid + ':' + _id(turn_id, 'Turn')
|
|
435
|
+
meta = next((entry for entry in entries if entry['turn_id'] == turn_id), None)
|
|
436
|
+
if not meta or revision not in (None,meta['revision']):
|
|
437
|
+
unavailable()
|
|
438
|
+
rev = meta['revision']
|
|
439
|
+
item = self.store.get('capture_turn_versions', f'{key}:{rev}')
|
|
440
|
+
if not item:
|
|
441
|
+
unavailable()
|
|
442
|
+
return detail_page(packed(item), offset, conversation_id=cid, turn_id=turn_id, revision=rev,
|
|
443
|
+
sha256=fingerprint(item))
|
|
444
|
+
if offset or revision is not None:
|
|
445
|
+
unavailable()
|
|
446
|
+
def rows(after):
|
|
447
|
+
for rank, entry in enumerate(entries, 1):
|
|
448
|
+
key = str(rank).zfill(2)
|
|
449
|
+
if key > after:
|
|
450
|
+
yield key, entry
|
|
451
|
+
return list_page(self.channel, rows, ['recent-turns',cid,epoch,fingerprint(entries)], cursor, limit,
|
|
452
|
+
raw_turns_loaded=0, mode='recent_turns', retention_limit=SHARED_TURN_LIMIT,
|
|
453
|
+
sharing='on' if session['state']=='active' else 'off')
|
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
"""Version-addressed, permission-filtered reading on the existing project ledger."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import json
|
|
5
|
+
|
|
6
|
+
from .store import GovernanceError
|
|
7
|
+
from .worker_channel import fail, fingerprint, packed, wire_size
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
KINDS = {
|
|
11
|
+
'decision': ('governance_fact_history', ''),
|
|
12
|
+
'observation': ('observation_history', ''),
|
|
13
|
+
'checkpoint': ('checkpoints', ''),
|
|
14
|
+
'source': ('worker_versions', 'source:'),
|
|
15
|
+
'handback': ('worker_versions', 'handback:'),
|
|
16
|
+
'disposition': ('worker_versions', 'disposition:'),
|
|
17
|
+
'stage': ('stages', ''),
|
|
18
|
+
'task': ('tasks', ''),
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def bounded_text(value, label, maximum=240):
|
|
23
|
+
if not isinstance(value, str) or not value.strip() or '\x00' in value or len(value) > maximum:
|
|
24
|
+
fail('COLLABORATION_INVALID', 'Invalid ' + label + '.')
|
|
25
|
+
return value.strip()
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def teamscope(channel):
|
|
29
|
+
return channel.binding['role'] == 'governor' or channel.binding['read_project_shared']
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def reference(source):
|
|
33
|
+
return {k: source[k] for k in ('reference_id', 'revision', 'content_sha256')}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def readable(channel, refs):
|
|
37
|
+
try:
|
|
38
|
+
for ref in refs:
|
|
39
|
+
channel._source(ref)
|
|
40
|
+
return True
|
|
41
|
+
except GovernanceError:
|
|
42
|
+
return False
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def detail_page(data, offset, **metadata):
|
|
46
|
+
"""Return UTF-8 pages sized for the double-encoded MCP envelope."""
|
|
47
|
+
if type(offset) is not int or not 0 <= offset <= len(data):
|
|
48
|
+
fail('COLLABORATION_PAGE_INVALID', 'Use the returned byte offset.')
|
|
49
|
+
if offset < len(data) and data[offset] & 0xc0 == 0x80:
|
|
50
|
+
fail('COLLABORATION_PAGE_INVALID', 'The offset is not a UTF-8 boundary.')
|
|
51
|
+
length = min(3072, len(data) - offset)
|
|
52
|
+
while True:
|
|
53
|
+
end = offset + length
|
|
54
|
+
while end < len(data) and end > offset and data[end] & 0xc0 == 0x80:
|
|
55
|
+
end -= 1
|
|
56
|
+
result = dict(metadata, text=data[offset:end].decode('utf-8'), offset=offset, end=end,
|
|
57
|
+
next_offset=end if end < len(data) else None, complete=end == len(data), size=len(data))
|
|
58
|
+
if wire_size(result) <= 15500 and len(packed(result)) <= 6600:
|
|
59
|
+
return result
|
|
60
|
+
if length < 4:
|
|
61
|
+
fail('COLLABORATION_PAGE_INVALID', 'Metadata exceeds the page budget.')
|
|
62
|
+
length //= 2
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def list_page(channel, rows, selection, cursor, limit, **metadata):
|
|
66
|
+
signature = fingerprint([channel.project_id, channel.actor, channel.binding['revision'], selection])
|
|
67
|
+
after = channel._cursor(cursor, signature, signature) if cursor else ''
|
|
68
|
+
if not isinstance(after, str):
|
|
69
|
+
fail('WORKER_CURSOR_INVALID', 'Invalid collaboration cursor.')
|
|
70
|
+
result = dict(metadata, items=[], has_more=False, next_cursor=None, read_only=True)
|
|
71
|
+
for key, item in rows(after):
|
|
72
|
+
candidate = {**result, 'items': result['items'] + [item]}
|
|
73
|
+
if len(result['items']) >= limit or len(packed(candidate)) > 6200 or wire_size(candidate) > 14000:
|
|
74
|
+
if not result['items']:
|
|
75
|
+
fail('WORKER_RESPONSE_TOO_LARGE', 'Select a smaller item.')
|
|
76
|
+
result.update(has_more=True, next_cursor=channel._encode(signature, signature, last))
|
|
77
|
+
break
|
|
78
|
+
result['items'].append(item)
|
|
79
|
+
last = key
|
|
80
|
+
result['returned'] = len(result['items'])
|
|
81
|
+
return result
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _fields(value, names):
|
|
85
|
+
return {name: value[name] for name in names.split() if name in value}
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ProjectHistory:
|
|
89
|
+
def __init__(self, channel):
|
|
90
|
+
self.channel = channel
|
|
91
|
+
self.store = channel.store
|
|
92
|
+
|
|
93
|
+
def project(self, kind, value):
|
|
94
|
+
"""Project only business evidence. Checkpoint file layers and private source bytes stay in their tools."""
|
|
95
|
+
full = teamscope(self.channel)
|
|
96
|
+
if kind == 'source':
|
|
97
|
+
ref = reference(value)
|
|
98
|
+
if value.get('state') != 'active' or not readable(self.channel, [ref]):
|
|
99
|
+
return None
|
|
100
|
+
return _fields(value, 'reference_id revision display_title content_sha256 media_type size task_id owner_binding_id')
|
|
101
|
+
if not full:
|
|
102
|
+
return None
|
|
103
|
+
if kind == 'decision':
|
|
104
|
+
return value if value.get('kind') == 'decision' else None
|
|
105
|
+
if kind in ('handback', 'disposition'):
|
|
106
|
+
refs = list(value.get('sources', []))
|
|
107
|
+
if kind == 'disposition':
|
|
108
|
+
base = self.store.get('worker_versions', 'handback:{}:{}'.format(
|
|
109
|
+
value['handback_id'], value['handback_revision']))
|
|
110
|
+
if not base:
|
|
111
|
+
return None
|
|
112
|
+
refs += base.get('sources', [])
|
|
113
|
+
value = {**value, 'task_id': base['task_id']}
|
|
114
|
+
if not readable(self.channel, refs):
|
|
115
|
+
return None
|
|
116
|
+
return _fields(value, 'task_id binding_id actor_binding_id handback_id handback_revision disposition_id revision kind state verdict summary next_step sources')
|
|
117
|
+
fields = {
|
|
118
|
+
'task': 'task_id title workstream state latest_checkpoint next_step updated_at',
|
|
119
|
+
'checkpoint': 'checkpoint_id task_id state decision next_step created_at',
|
|
120
|
+
'observation': 'observation_id task_id source_ref source_revision revision summary relations fingerprint recorded_at',
|
|
121
|
+
'stage': 'stage_id task_id state status summary base commit created_at updated_at',
|
|
122
|
+
}
|
|
123
|
+
return _fields(value, fields[kind])
|
|
124
|
+
|
|
125
|
+
def exact(self, kind, key, sha=None):
|
|
126
|
+
if kind not in KINDS or not isinstance(key, str) or not 0 < len(key) <= 650:
|
|
127
|
+
fail('COLLABORATION_UNAVAILABLE', 'The selected record is unavailable.')
|
|
128
|
+
collection, prefix = KINDS[kind]
|
|
129
|
+
value = self.store.get(collection, key) if key.startswith(prefix) else None
|
|
130
|
+
item = self.project(kind, value) if value else None
|
|
131
|
+
if item is None or (sha is not None and fingerprint(item) != sha):
|
|
132
|
+
fail('COLLABORATION_UNAVAILABLE', 'The selected record is unavailable.')
|
|
133
|
+
return item
|
|
134
|
+
|
|
135
|
+
def read(self, kind=None, key=None, sha256=None, task_id=None, query=None, cursor=None, limit=8, offset=0):
|
|
136
|
+
if key is not None:
|
|
137
|
+
item = self.exact(kind, key, sha256)
|
|
138
|
+
return detail_page(packed(item), offset, kind=kind, key=key, sha256=fingerprint(item))
|
|
139
|
+
if sha256 or offset:
|
|
140
|
+
fail('COLLABORATION_INVALID', 'Select one version to read its content.')
|
|
141
|
+
needle = (query or '').strip().casefold()
|
|
142
|
+
def rows(after):
|
|
143
|
+
for category in sorted([kind] if kind else KINDS):
|
|
144
|
+
if not teamscope(self.channel) and category != 'source':
|
|
145
|
+
continue
|
|
146
|
+
collection, prefix = KINDS[category]
|
|
147
|
+
previous, _, start = after.partition('|')
|
|
148
|
+
if after and category < previous:
|
|
149
|
+
continue
|
|
150
|
+
with self.store._connect(readonly=True) as db:
|
|
151
|
+
records = db.execute('SELECT key,value FROM records WHERE collection=? AND key GLOB ? '
|
|
152
|
+
'AND key>? ORDER BY key', (collection, prefix + '*', start if previous == category else ''))
|
|
153
|
+
for rid, raw in records:
|
|
154
|
+
item = self.project(category, json.loads(raw))
|
|
155
|
+
if item is None or (task_id and item.get('task_id') != task_id):
|
|
156
|
+
continue
|
|
157
|
+
if needle and needle not in (rid + ' ' + json.dumps(item, ensure_ascii=False)).casefold():
|
|
158
|
+
continue
|
|
159
|
+
title = next((item[k] for k in ('statement','display_title','title','summary','decision','next_step')
|
|
160
|
+
if isinstance(item.get(k), str) and item[k]), rid)
|
|
161
|
+
yield category + '|' + rid, {
|
|
162
|
+
'kind': category, 'key': rid, 'sha256': fingerprint(item), 'title': title[:190],
|
|
163
|
+
**_fields(item, 'task_id fact_id source_id source_revision revision standing verdict state'),
|
|
164
|
+
}
|
|
165
|
+
return list_page(self.channel, rows, ['history', kind, task_id, needle], cursor, limit,
|
|
166
|
+
scope='authorized project records', project_id=self.channel.project_id)
|