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,669 @@
1
+ """Per-conversation consent and workspace-scoped capture of completed visible turns."""
2
+ import argparse
3
+ from datetime import datetime
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import shlex
9
+ import sqlite3
10
+ import subprocess
11
+ import sys
12
+ import tempfile
13
+ import time
14
+
15
+ from . import codex_capture
16
+ from .agy_turns import MAX_WINDOW, completed_turn, indexed_chats, indexed_pair, indexed_run, transcript_path, workspace_path
17
+ from .core import _linked
18
+ from .governance_cycle import _os_lock
19
+ from .store import GovernanceError, now
20
+ from .worker_channel import Caller, WorkerChannel, channel_epoch, fail, fingerprint
21
+
22
+
23
+ STATES = {'enable': (('available', 'closed'), 'active'), 'pause': (('active',), 'paused'),
24
+ 'resume': (('paused',), 'active'), 'close': (('active', 'paused'), 'closed')}
25
+ PROVIDERS = ('antigravity', 'antigravity-cli', 'antigravity-ide')
26
+ SHARED_TURN_LIMIT = 8
27
+ CODEX_READER_MODE = 'codex_app_server_v2'
28
+
29
+
30
+ def recent_turns(store, session):
31
+ """Newest retained pointers in capture order, without loading conversation text."""
32
+ cid = session['conversation_id']
33
+ with store._connect(readonly=True) as db:
34
+ rows = db.execute("""SELECT value FROM records WHERE collection='capture_turn_index'
35
+ AND key>=? AND key<? AND (json_type(value,'$.sequence')='integer' OR key=?)
36
+ ORDER BY json_extract(value,'$.sequence') DESC,
37
+ json_extract(value,'$.captured_at') DESC, rowid DESC LIMIT ?""",
38
+ (cid + ':', cid + ';', cid + ':' + (session.get('last_turn') or ''), SHARED_TURN_LIMIT))
39
+ return [json.loads(row[0]) for row in rows]
40
+
41
+
42
+ def hook_group(project_id, owner):
43
+ return 'taskcarry-visible-turns-' + fingerprint([project_id, owner])[:16]
44
+
45
+
46
+ def workspace_hook_state(root, name):
47
+ config = root / '.agents' / 'hooks.json'
48
+ if any(_linked(p) for p in (config, config.parent)):
49
+ return 'unavailable'
50
+ try:
51
+ cfg = json.loads(config.read_text(encoding='utf-8-sig'))
52
+ except FileNotFoundError:
53
+ return 'missing'
54
+ except (ValueError, OSError):
55
+ return 'unavailable'
56
+ if not isinstance(cfg, dict):
57
+ return 'unavailable'
58
+ if name not in cfg:
59
+ return 'missing'
60
+ group = cfg[name]
61
+ return ('ready' if isinstance(group, dict) and group.get('enabled', True) is True
62
+ and all(group.get(event) for event in ('PreInvocation', 'Stop')) else 'unavailable')
63
+
64
+
65
+ def atomic_json(path, value):
66
+ if any(_linked(p) for p in (path, *path.parents)):
67
+ raise ValueError('Select an ordinary local path.')
68
+ path.parent.mkdir(parents=True, exist_ok=True)
69
+ with tempfile.NamedTemporaryFile(dir=path.parent, delete=False, mode='w', encoding='utf-8') as tmp:
70
+ try:
71
+ json.dump(value, tmp, ensure_ascii=False, indent=2)
72
+ tmp.write('\n')
73
+ tmp.flush()
74
+ os.fsync(tmp.fileno())
75
+ except BaseException:
76
+ tmp.close()
77
+ Path(tmp.name).unlink(missing_ok=True)
78
+ raise
79
+ try:
80
+ os.replace(tmp.name, path)
81
+ finally:
82
+ Path(tmp.name).unlink(missing_ok=True)
83
+
84
+
85
+ def mark(path):
86
+ try:
87
+ stat = path.stat()
88
+ except FileNotFoundError:
89
+ return [0, 0], 0
90
+ if not path.is_file():
91
+ raise ValueError('Invalid transcript.')
92
+ return [stat.st_dev, stat.st_ino], stat.st_size
93
+
94
+
95
+ def retire_chat(store, cid, successor, task, workspace):
96
+ """Retire capture in the same transaction as the published handoff."""
97
+ epoch = channel_epoch(store)
98
+ store.put('capture_retirements', cid, dict(conversation_id=cid, successor=successor, epoch=epoch,
99
+ task_id=task, workspace_id=workspace))
100
+ s = store.get('capture_sessions', cid)
101
+ if s and s['epoch'] == epoch and (s['task_id'], s['workspace_id']) == (task, workspace) and s['state'] != 'retired':
102
+ s.update(state='retired', generation=s['generation'] + 1, updated_at=now(), waiting_for_start=False)
103
+ s.pop('remote_pending', None)
104
+ s.pop('pending', None)
105
+ store.put('capture_sessions', cid, s)
106
+
107
+
108
+ class Capture:
109
+ def __init__(self, control, home=None, *, caller=None):
110
+ self.channel = WorkerChannel(control, caller)
111
+ self.store = self.channel.store
112
+ self.home = Path(home) if home else Path.home()
113
+
114
+ def member(self, owner, task, workspace):
115
+ channel = WorkerChannel(self.store.root, Caller(owner, 'worker', self.channel.project_id))
116
+ channel._auth('discussion_update')
117
+ if not channel.binding['read_project_shared'] or not channel.binding['share_project']:
118
+ fail('CAPTURE_SCOPE', 'This role cannot share project discussions.')
119
+ return channel._assignment(task, workspace, 'progress')[0]
120
+
121
+ def sessions(self):
122
+ return [{k: s.get(k) for k in ('conversation_id','provider','owner','task_id','workspace_id','state',
123
+ 'generation','updated_at','last_turn','coverage','saved_turns','waiting_for_start')}
124
+ for s in self.store.list('capture_sessions')
125
+ if s['epoch'] == self.channel._epoch()]
126
+
127
+ def options(self):
128
+ """Local board inventory. Finding a chat does not register or enable it."""
129
+ sessions = self.sessions()
130
+ known = {s['conversation_id'] for s in self.store.list('capture_sessions')}
131
+ choices = {}
132
+ connected = set()
133
+ epoch = self.channel._epoch()
134
+ retired = {r['conversation_id'] for r in self.store.list('capture_retirements') if r['epoch'] == epoch}
135
+ roots = {}
136
+ for binding in self.store.list('worker_bindings'):
137
+ owner = binding['binding_id']
138
+ if binding.get('state') != 'active' or binding.get('project_id') != self.channel.project_id:
139
+ continue
140
+ for assignment in binding['assignments']:
141
+ task, workspace = assignment['task_id'], assignment['workspace_id']
142
+ mapping = self.store.get('worker_workspaces', workspace)
143
+ if mapping:
144
+ roots.setdefault(Path(mapping['path']), []).append((owner, task, workspace))
145
+ for intended, assignments in roots.items():
146
+ for owner, task, workspace in assignments:
147
+ try:
148
+ root = self.member(owner, task, workspace)
149
+ except GovernanceError:
150
+ continue
151
+ if root != intended:
152
+ continue
153
+ for provider in (*PROVIDERS, 'codex'):
154
+ if provider == 'codex':
155
+ retired.update(codex_capture.chats(self.home, root, archived=True))
156
+ else:
157
+ retired.update(indexed_chats(self.home, provider, root, archived=True))
158
+ if provider == 'codex':
159
+ if len(assignments) != 1:
160
+ continue
161
+ hook = 'native_reader'
162
+ else:
163
+ hook = workspace_hook_state(root, hook_group(self.channel.project_id, owner))
164
+ if hook == 'unavailable' or (len(assignments) != 1 and hook != 'ready'):
165
+ continue
166
+ if hook == 'ready':
167
+ connected.add(owner)
168
+ ids = codex_capture.chats(self.home, root) if provider == 'codex' else indexed_chats(self.home, provider, root)
169
+ for cid in ids:
170
+ if cid not in known:
171
+ choices.setdefault(cid, []).append(dict(conversation_id=cid, owner=owner,
172
+ task_id=task, workspace_id=workspace, provider=provider, state='available',
173
+ generation=0, saved_turns=0, setup_required=hook == 'missing'))
174
+ # A workspace shared by multiple assignments cannot establish which role owns a chat.
175
+ sessions.extend(items[0] for items in choices.values() if len(items) == 1)
176
+ return {'sessions': [s for s in sessions if s['conversation_id'] not in retired and s['state'] != 'retired'],
177
+ 'connected': sorted(connected)}
178
+
179
+ def new_session(self, cid, provider, owner, task, workspace):
180
+ return dict(conversation_id=cid, provider=provider, owner=owner, task_id=task, workspace_id=workspace,
181
+ state='available', epoch=self.channel._epoch(), generation=0, updated_at=now(), saved_turns=0)
182
+
183
+ def change(self, cid, action, generation, owner=None):
184
+ candidate = None
185
+ if owner and action == 'enable' and generation == 0 and not self.store.get('capture_sessions', cid):
186
+ candidate = next((s for s in self.options()['sessions'] if s['conversation_id'] == cid
187
+ and s['owner'] == owner and s['state'] == 'available'), None)
188
+ selected = self.store.get('capture_sessions', cid) or candidate
189
+ frontier = None
190
+ if selected and selected['provider'] == 'codex' and action in ('enable', 'resume'):
191
+ if (owner and owner != selected['owner']) or selected['generation'] != generation:
192
+ fail('CAPTURE_CHANGED', 'Refresh the selected conversation.')
193
+ root = self.member(selected['owner'], selected['task_id'], selected['workspace_id'])
194
+ if cid not in codex_capture.chats(self.home, root, cid):
195
+ fail('CAPTURE_UNAVAILABLE', 'The selected local Codex conversation is unavailable.')
196
+ recent, _ = codex_capture.turns(codex_capture.reader(self.home), cid, limit=1)
197
+ frontier = recent[0][0] if recent else None
198
+ with self.store.transaction():
199
+ if (self.store.get('capture_retirements', cid) or {}).get('epoch') == self.channel._epoch():
200
+ fail('CAPTURE_UNAVAILABLE', 'This conversation has retired from the workbench.')
201
+ s = self.store.get('capture_sessions', cid)
202
+ if s is None and candidate:
203
+ root = self.member(owner, candidate['task_id'], candidate['workspace_id'])
204
+ provider = candidate['provider']
205
+ ids = codex_capture.chats(self.home, root, cid) if provider == 'codex' else indexed_chats(self.home, provider, root, cid)
206
+ if cid in ids:
207
+ s = self.new_session(cid, provider, owner, candidate['task_id'], candidate['workspace_id'])
208
+ if not s or (owner and owner != s['owner']) or s['epoch'] != self.channel._epoch() or action not in STATES:
209
+ fail('CAPTURE_UNAVAILABLE', 'Select a registered local conversation.')
210
+ before, target = STATES[action]
211
+ if s['generation'] != generation or s['state'] not in before:
212
+ fail('CAPTURE_CHANGED', 'Refresh the conversation before changing its setting.')
213
+ if target == 'active':
214
+ root = self.member(s['owner'], s['task_id'], s['workspace_id'])
215
+ if s['provider'] in PROVIDERS and indexed_chats(self.home, s['provider'], root, cid, archived=True):
216
+ fail('CAPTURE_UNAVAILABLE', 'The selected conversation was archived by its host.')
217
+ if s['provider'] == 'workbuddy-remote':
218
+ # This source belongs to the member's device. Only the board
219
+ # changes consent; never discover or launch a reader on this PC.
220
+ if target == 'active':
221
+ binding = self.store.get('worker_bindings', s['owner'])
222
+ if binding['revision'] != s['binding_revision']:
223
+ fail('CAPTURE_CHANGED', 'Reconnect this conversation with its current membership.')
224
+ s.pop('remote_pending', None)
225
+ s.pop('remote_receipt', None)
226
+ s['coverage'] = 'awaiting_turn' if target == 'active' else 'sharing_off'
227
+ identity, offset = [], 0
228
+ elif s['provider'] == 'codex':
229
+ if target == 'active':
230
+ s.update(reader_mode=CODEX_READER_MODE, frontier=frontier, coverage='awaiting_turn')
231
+ s.pop('pending', None)
232
+ identity, offset = [], 0
233
+ else:
234
+ identity, offset = mark(transcript_path(self.home, s['provider'], cid))
235
+ if target == 'active':
236
+ args = self.store.root, s['owner'], s['task_id'], s['workspace_id']
237
+ plan = install(*args)
238
+ if plan['changed']:
239
+ if plan['group_exists'] and not plan['managed']:
240
+ fail('CAPTURE_HOOK_CHANGED', 'The workspace capture hook has been customized.')
241
+ install(*args, expected=plan['expected'])
242
+ changed_at = now()
243
+ if target == 'active' and s['provider'] in PROVIDERS:
244
+ s['consent_since'] = changed_at
245
+ s.update(state=target, generation=generation+1, identity=identity, cursor=offset, updated_at=changed_at,
246
+ waiting_for_start=(target == 'active' and s['provider'] in PROVIDERS))
247
+ self.store.put('capture_sessions', cid, s)
248
+ if target == 'active' and (s['provider'] == 'codex' or self.has_agy_index(s)):
249
+ try:
250
+ self.start_reader(cid, generation + 1)
251
+ except OSError:
252
+ self.change(cid, 'close', generation + 1, s['owner'])
253
+ fail('CAPTURE_UNAVAILABLE', 'The local reader could not start. Please try again.')
254
+ return {'conversation_id': cid, 'state': target, 'generation': generation+1}
255
+
256
+ def start_reader(self, cid, generation):
257
+ subprocess.Popen([sys.executable, '-I', '-B', '-m', 'taskcarry.conversation_capture',
258
+ '--project', str(self.store.root), 'watch', '--conversation', cid,
259
+ '--generation', str(generation)], stdin=subprocess.DEVNULL,
260
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True,
261
+ start_new_session=os.name != 'nt', creationflags=getattr(subprocess, 'CREATE_NO_WINDOW', 0))
262
+
263
+ def resume_readers(self):
264
+ for session in self.store.list('capture_sessions'):
265
+ if session['state'] != 'active' or session['epoch'] != self.channel._epoch():
266
+ continue
267
+ cid = session['conversation_id']
268
+ if session['provider'] != 'codex':
269
+ if self.has_agy_index(session):
270
+ self.start_reader(cid, session['generation'])
271
+ continue
272
+ if session.get('reader_mode') == 'codex_app_server':
273
+ # Retire the single-turn reader without changing consent or its last processed turn.
274
+ with self.store.transaction():
275
+ session = self.store.get('capture_sessions', cid)
276
+ if (not session or session['state'] != 'active' or session['epoch'] != self.channel._epoch()
277
+ or session.get('reader_mode') != 'codex_app_server'):
278
+ continue
279
+ session['reader_mode'] = CODEX_READER_MODE
280
+ self.store.put('capture_sessions', cid, session)
281
+ if session.get('reader_mode') == CODEX_READER_MODE:
282
+ self.start_reader(cid, session['generation'])
283
+
284
+ def has_agy_index(self, session):
285
+ if session['provider'] not in PROVIDERS:
286
+ return False
287
+ try:
288
+ root = self.member(session['owner'], session['task_id'], session['workspace_id'])
289
+ return indexed_run(self.home, session['provider'], root, session['conversation_id']) is not None
290
+ except (GovernanceError, OSError, ValueError):
291
+ return False
292
+
293
+ def sync_agy(self, cid, generation, inspected=None):
294
+ """Recover a completed visible turn when the App delivered no lifecycle hook."""
295
+ s = self.store.get('capture_sessions', cid)
296
+ if (not s or s['state'] != 'active' or s['generation'] != generation
297
+ or s['provider'] not in PROVIDERS or s['epoch'] != self.channel._epoch()):
298
+ return False
299
+ root = self.member(s['owner'], s['task_id'], s['workspace_id'])
300
+ if indexed_chats(self.home, s['provider'], root, cid, archived=True):
301
+ return False
302
+ path = transcript_path(self.home, s['provider'], cid)
303
+ identity, end = mark(path)
304
+ start = s['cursor']
305
+ if (s['identity'] not in ([0, 0], identity) or end < start):
306
+ # A replacement file is a new boundary. Never import its earlier contents.
307
+ with self.store.transaction():
308
+ live = self.store.get('capture_sessions', cid)
309
+ if live == s and live['epoch'] == self.channel._epoch():
310
+ live.update(identity=identity, cursor=end, consent_since=now(), coverage='file_changed')
311
+ self.store.put('capture_sessions', cid, live)
312
+ return True
313
+ if start == end:
314
+ return True
315
+ run = indexed_run(self.home, s['provider'], root, cid)
316
+ if not run or run[:3] != ('CASCADE_RUN_STATUS_IDLE', 0, 0):
317
+ return True
318
+ try:
319
+ began = datetime.fromisoformat(run[3])
320
+ consent = datetime.fromisoformat(s.get('consent_since') or s['updated_at'])
321
+ if began.tzinfo is None or consent.tzinfo is None or began <= consent:
322
+ return True
323
+ except (ValueError, TypeError):
324
+ return True
325
+ full_path = path.with_name('transcript_full.jsonl')
326
+ full_mtime = full_path.stat().st_mtime_ns if not _linked(full_path) and full_path.is_file() else None
327
+ signature = (start, *identity, end, path.stat().st_mtime_ns, full_mtime, run)
328
+ if inspected is not None and inspected.get('incomplete') == signature:
329
+ return True
330
+ offset = max(start, end - MAX_WINDOW)
331
+ with path.open('rb') as handle:
332
+ handle.seek(offset)
333
+ data = handle.read(end - offset)
334
+ if offset != start:
335
+ data = data.partition(b'\n')[2]
336
+ found = indexed_pair(data, run[4], run[5], full_path)
337
+ if mark(path) != (identity, end) or indexed_run(self.home, s['provider'], root, cid) != run:
338
+ return True
339
+ if not found:
340
+ if inspected is not None:
341
+ inspected['incomplete'] = signature
342
+ return True
343
+ turn, single_user = found
344
+ with self.store.transaction():
345
+ live = self.store.get('capture_sessions', cid)
346
+ if live != s or live['epoch'] != self.channel._epoch():
347
+ return True
348
+ self.member(live['owner'], live['task_id'], live['workspace_id'])
349
+ live.setdefault('consent_since', s['updated_at'])
350
+ self.save_turn(live, start if single_user and offset == start else None, turn)
351
+ live.update(identity=identity, cursor=end, waiting_for_start=False, coverage='visible_pair',
352
+ last_capture_method='agy_indexed_completion', updated_at=now())
353
+ self.store.put('capture_sessions', cid, live)
354
+ return True
355
+
356
+ def watch(self, cid, generation):
357
+ if not codex_capture.valid_id(cid) or type(generation) is not int:
358
+ return
359
+ session = self.store.get('capture_sessions', cid)
360
+ if not session or session['provider'] not in PROVIDERS:
361
+ return self.watch_codex(cid, generation)
362
+ try:
363
+ with _os_lock(self.store.directory, f'capture:agy_index:{cid}:{generation}'):
364
+ inspected = {}
365
+ while True:
366
+ try:
367
+ if not self.sync_agy(cid, generation, inspected):
368
+ return
369
+ except GovernanceError as exc:
370
+ if exc.code not in ('BUSY', 'CYCLE_BUSY'):
371
+ return
372
+ except (OSError, sqlite3.OperationalError):
373
+ pass
374
+ time.sleep(2)
375
+ except GovernanceError as exc:
376
+ if exc.code != 'CYCLE_BUSY':
377
+ raise
378
+
379
+ def codex_grant(self, cid, generation):
380
+ s = self.store.get('capture_sessions', cid)
381
+ if (not s or s['provider'] != 'codex' or s.get('reader_mode') != CODEX_READER_MODE
382
+ or s['state'] != 'active' or s['generation'] != generation or s['epoch'] != self.channel._epoch()):
383
+ return None
384
+ self.member(s['owner'], s['task_id'], s['workspace_id'])
385
+ return s
386
+
387
+ def sync_codex(self, cid, generation):
388
+ session = self.codex_grant(cid, generation)
389
+ if session is None:
390
+ return True
391
+ root = self.member(session['owner'], session['task_id'], session['workspace_id'])
392
+ if cid not in codex_capture.chats(self.home, root, cid):
393
+ fail('CAPTURE_UNAVAILABLE', 'The selected conversation is unavailable in this workspace.')
394
+ host = codex_capture.reader(self.home)
395
+ frontier = session['frontier']
396
+ pending = codex_capture.new_turns(host, cid, frontier)
397
+ for index, (tid, status) in enumerate(pending):
398
+ if status == 'inProgress' or (status == 'interrupted' and index == len(pending) - 1):
399
+ return False
400
+ grant = self.codex_grant(cid, generation)
401
+ if not grant or grant['frontier'] != frontier:
402
+ return False
403
+ turn = codex_capture.visible_pair(host, cid, tid) if status == 'completed' else None
404
+ with self.store.transaction():
405
+ current = self.codex_grant(cid, generation)
406
+ if not current or current['frontier'] != frontier:
407
+ return False
408
+ if turn:
409
+ self.save_turn(current, None, turn)
410
+ current.update(frontier=tid, updated_at=now(), coverage='visible_pair' if turn else 'unconfirmed_gap')
411
+ self.store.put('capture_sessions', cid, current)
412
+ frontier = tid
413
+ return True
414
+
415
+ def watch_codex(self, cid, generation):
416
+ if not codex_capture.valid_id(cid) or type(generation) is not int:
417
+ return
418
+ try:
419
+ with _os_lock(self.store.directory, f'capture:{CODEX_READER_MODE}:{cid}:{generation}'):
420
+ stamp = None
421
+ retry_at = 0
422
+ while True:
423
+ try:
424
+ session = self.codex_grant(cid, generation)
425
+ if not session:
426
+ return
427
+ root = self.member(session['owner'], session['task_id'], session['workspace_id'])
428
+ path = codex_capture.chats(self.home, root, cid).get(cid)
429
+ if not path:
430
+ return
431
+ stat = path.stat()
432
+ current = (stat.st_ino, stat.st_size, stat.st_mtime_ns)
433
+ if stamp != current or (retry_at and time.monotonic() >= retry_at):
434
+ caught_up = self.sync_codex(cid, generation)
435
+ stamp = current
436
+ retry_at = 0 if caught_up else time.monotonic() + 15
437
+ except (OSError, sqlite3.OperationalError, GovernanceError) as exc:
438
+ if isinstance(exc, GovernanceError) and exc.code in (
439
+ 'CAPTURE_SCOPE', 'WORKER_BINDING_REVOKED', 'WORKER_BINDING_INACTIVE',
440
+ 'WORKER_SCOPE_DENIED', 'STALE_REPLICA', 'CAPTURE_HISTORY_CHANGED'):
441
+ return
442
+ time.sleep(5)
443
+ time.sleep(2)
444
+ except GovernanceError as exc:
445
+ if exc.code != 'CYCLE_BUSY':
446
+ raise
447
+
448
+ def hook(self, event, data, owner, task, workspace):
449
+ cid = data.get('conversationId')
450
+ raw_path = data.get('transcriptPath')
451
+ if event not in {'PreInvocation','Stop'} or not isinstance(cid, str) or not isinstance(raw_path, str):
452
+ return
453
+ root = self.member(owner, task, workspace)
454
+ workspaces = data.get('workspacePaths')
455
+ if not isinstance(workspaces, list) or root not in [workspace_path(p) for p in workspaces]:
456
+ return
457
+ actual_path = (Path(raw_path).expanduser() if raw_path.startswith('~') else workspace_path(raw_path))
458
+ provider = next((p for p in PROVIDERS if transcript_path(self.home, p, cid) == actual_path), None)
459
+ if not provider:
460
+ return
461
+ if indexed_chats(self.home, provider, root, cid, archived=True):
462
+ return
463
+ path = transcript_path(self.home, provider, cid)
464
+ s = self.store.get('capture_sessions', cid)
465
+ if s is None:
466
+ with self.store.transaction():
467
+ if self.store.get('capture_sessions', cid) is None:
468
+ self.store.put('capture_sessions', cid, self.new_session(cid, provider, owner, task, workspace))
469
+ return
470
+ if (s['epoch'],s['owner'],s['task_id'],s['workspace_id'],s['provider'],s['state']) != (
471
+ self.channel._epoch(),owner,task,workspace,provider,'active'):
472
+ return
473
+ if s.get('waiting_for_start'):
474
+ if event != 'PreInvocation' or data.get('invocationNum') != 0:
475
+ return
476
+ with self.store.transaction():
477
+ fresh = self.store.get('capture_sessions',cid)
478
+ if fresh['generation'] != s['generation'] or fresh['state'] != 'active':
479
+ return
480
+ self.store.put('capture_sessions',cid,{**fresh,'waiting_for_start':False})
481
+ # A pending entry contains only the original consent generation and file boundary.
482
+ queue = self.store.directory / 'capture-pending' / cid
483
+ if event == 'Stop' and data.get('fullyIdle') is True:
484
+ identity, end = mark(path)
485
+ # A desktop host can deliver Stop while its transcript writer is flushing.
486
+ # Sample only this conversation's newly consented range, outside the write lock.
487
+ if data.get('terminationReason') in ('NO_TOOL_CALL','TERMINAL_STEP_TYPE') and not data.get('error'):
488
+ for _ in range(4):
489
+ fresh = self.store.get('capture_sessions',cid)
490
+ if fresh['generation'] != s['generation'] or fresh['state'] != 'active':
491
+ return
492
+ if s['identity'] in ([0,0],identity) and 0 < end - s['cursor'] <= MAX_WINDOW:
493
+ with path.open('rb') as handle:
494
+ handle.seek(s['cursor'])
495
+ if completed_turn(handle.read(end - s['cursor'])) is not None:
496
+ break
497
+ time.sleep(0.08)
498
+ identity, end = mark(path)
499
+ if end > s['cursor'] or identity != s['identity']:
500
+ pending = queue / f"{s['generation']:012d}-{end:020d}.json"
501
+ terminal = data.get('terminationReason') in ('NO_TOOL_CALL','TERMINAL_STEP_TYPE') and not data.get('error')
502
+ atomic_json(pending, {'generation': s['generation'], 'identity': identity, 'end': end, 'terminal': terminal})
503
+ if queue.is_dir():
504
+ if _linked(queue) or _linked(queue.parent):
505
+ raise ValueError('Invalid local retry directory.')
506
+ for item in sorted(queue.glob('*.json')):
507
+ if _linked(item):
508
+ continue
509
+ try:
510
+ job = json.loads(item.read_text(encoding='utf-8'))
511
+ self.consume(cid, path, job)
512
+ item.unlink(missing_ok=True)
513
+ except FileNotFoundError:
514
+ continue
515
+
516
+ def consume(self, cid, path, job):
517
+ with self.store.transaction():
518
+ s = self.store.get('capture_sessions', cid)
519
+ if (not s or s['state'] != 'active' or s['generation'] != job['generation']
520
+ or self.channel._epoch() != s['epoch']):
521
+ return
522
+ self.member(s['owner'], s['task_id'], s['workspace_id'])
523
+ identity, current_end = mark(path)
524
+ end = job['end']
525
+ if s['identity'] not in ([0,0],identity) or identity != job['identity'] or current_end < end:
526
+ s.update(identity=identity, cursor=current_end, coverage='file_changed', generation=s['generation']+1)
527
+ elif end <= s['cursor']:
528
+ return
529
+ else:
530
+ turn = None
531
+ start = s['cursor']
532
+ if job['terminal'] and end - s['cursor'] <= MAX_WINDOW:
533
+ with path.open('rb') as handle:
534
+ handle.seek(s['cursor'])
535
+ turn = completed_turn(handle.read(end - s['cursor']))
536
+ if turn:
537
+ self.save_turn(s, start, turn)
538
+ s.update(identity=identity, cursor=end, coverage='visible_pair' if turn else 'unconfirmed_gap')
539
+ s['updated_at'] = now()
540
+ self.store.put('capture_sessions', cid, s)
541
+
542
+ def save_turn(self, s, start, turn):
543
+ """Keep the most recent completed exchanges and their current revisions atomically."""
544
+ cid = s['conversation_id']
545
+ key = cid + ':' + turn['turn_id']
546
+ if 'capture_sequence' not in s:
547
+ # An older release exposed only last_turn. Carry forward just that shared pointer.
548
+ s['capture_sequence'] = 0
549
+ old_key = cid + ':' + (s.get('last_turn') or '')
550
+ last = self.store.get('capture_turn_index', old_key)
551
+ if last:
552
+ self.store.put('capture_turn_index', old_key, {**last, 'sequence': 0})
553
+ prior = self.store.get('capture_turn_index', key)
554
+ if prior and prior.get('sequence') is None:
555
+ prior = None
556
+ digest = fingerprint(turn)
557
+ revision = prior['revision'] if prior else 0
558
+ if not prior or digest != prior['sha256']:
559
+ revision += 1
560
+ if prior is None:
561
+ s['capture_sequence'] += 1
562
+ self.store.put('capture_turn_versions', f'{key}:{revision}', turn)
563
+ self.store.put('capture_turn_index', key, {'turn_id': turn['turn_id'], 'revision': revision,
564
+ 'sha256': digest, 'captured_at': prior.get('captured_at') if prior else now(),
565
+ 'sequence': prior.get('sequence') if prior else s['capture_sequence'], 'omissions': turn['omissions']})
566
+ retained = recent_turns(self.store, s)
567
+ keys = [cid + ':' + entry['turn_id'] for entry in retained]
568
+ versions = [f"{name}:{entry['revision']}" for name, entry in zip(keys, retained)]
569
+ db = self.store._local.connection
570
+ placeholders = ','.join('?' for _ in retained)
571
+ for collection, keep in (('capture_turn_index', keys), ('capture_turn_versions', versions)):
572
+ db.execute(f'DELETE FROM records WHERE collection=? AND key>=? AND key<? AND key NOT IN ({placeholders})',
573
+ (collection, cid + ':', cid + ';', *keep))
574
+ s['saved_turns'] = len(retained)
575
+ s['last_turn'] = retained[0]['turn_id']
576
+ for link in self.store.list('capture_topic_requests'):
577
+ same_turn = (link.get('turn_id') == turn['turn_id'] if s['provider'] == 'codex'
578
+ else start is not None and link.get('start') == start)
579
+ if same_turn and (link['conversation_id'], link['generation']) == (cid, s['generation']):
580
+ self.store.put('discussion_turn_links', f"{link['topic']}:{link['revision']}",
581
+ {'conversation_id':cid,'turn_id':turn['turn_id'],'revision':revision,'sha256':digest})
582
+
583
+
584
+
585
+ def install(control, owner, task, workspace, expected=None):
586
+ capture = Capture(control)
587
+ root = capture.member(owner, task, workspace)
588
+ config = root / '.agents' / 'hooks.json'
589
+ if any(_linked(p) for p in (config, config.parent)):
590
+ raise ValueError('Select an ordinary workspace hook file.')
591
+ previous = config.read_bytes() if config.exists() else b''
592
+ digest = hashlib.sha256(previous).hexdigest()
593
+ cfg = json.loads(previous.decode('utf-8-sig')) if previous else {}
594
+ if not isinstance(cfg, dict):
595
+ raise ValueError('Unexpected hook configuration.')
596
+ executable = Path(sys.executable)
597
+ if os.name == 'nt' and executable.name.lower() == 'pythonw.exe':
598
+ executable = executable.with_name('python.exe')
599
+ args = [str(executable), '-I', '-m', 'taskcarry.conversation_capture', '--project', str(capture.store.root),
600
+ '--owner', owner, '--task', task, '--workspace', workspace, 'hook']
601
+ name = hook_group(capture.channel.project_id, owner)
602
+ hook = {}
603
+ for event in ('PreInvocation', 'Stop'):
604
+ command_args = [*args, '--event', event]
605
+ command = (subprocess.list2cmdline([arg.replace('\\', '/') for arg in command_args])
606
+ if os.name == 'nt' else shlex.join(command_args))
607
+ hook[event] = [{'type':'command', 'command':command, 'timeout':8}]
608
+ existing = cfg.get(name)
609
+ # A previous installation can differ only in its Python path. Retain user-edited hooks.
610
+ managed = isinstance(existing, dict) and set(existing) == set(hook)
611
+ for event, commands in hook.items():
612
+ if not managed:
613
+ break
614
+ previous_commands = existing[event]
615
+ if not isinstance(previous_commands, list) or len(previous_commands) != 1 or not isinstance(previous_commands[0], dict):
616
+ managed = False
617
+ break
618
+ previous_command = previous_commands[0].get('command')
619
+ suffix = ' -I -m taskcarry.conversation_capture '
620
+ managed = (isinstance(previous_command, str) and suffix in previous_command
621
+ and previous_command.partition(suffix)[2] == commands[0]['command'].partition(suffix)[2]
622
+ and {**previous_commands[0], 'command': commands[0]['command']} == commands[0])
623
+ result = {'path': str(config), 'expected': digest, 'changed': existing != hook, 'group_exists': name in cfg,
624
+ 'managed': managed}
625
+ if expected is not None:
626
+ if expected != digest:
627
+ fail('CAPTURE_CHANGED', 'Review the updated workspace hook file first.')
628
+ if result['changed']:
629
+ atomic_json(config, {**cfg, name: hook})
630
+ return result
631
+
632
+
633
+ def main(argv=None):
634
+ parser = argparse.ArgumentParser(description='Manage visible-turn capture for selected local conversations.')
635
+ parser.add_argument('--project', required=True)
636
+ for key in ('owner','task','workspace'):
637
+ parser.add_argument('--' + key)
638
+ parser.add_argument('action', choices=['install','status','hook','watch',*STATES])
639
+ parser.add_argument('--expected')
640
+ parser.add_argument('--conversation')
641
+ parser.add_argument('--event', choices=('PreInvocation', 'Stop'))
642
+ parser.add_argument('--generation', type=int)
643
+ args = parser.parse_args(argv)
644
+ if args.action == 'watch':
645
+ Capture(args.project).watch(args.conversation, args.generation)
646
+ return
647
+ if args.action == 'hook':
648
+ try:
649
+ raw = sys.stdin.buffer.read(1024*1024 + 1)
650
+ if len(raw) <= 1024*1024:
651
+ data = json.loads(raw)
652
+ event = data.get('hookEventName') or args.event
653
+ if not args.event or event == args.event:
654
+ Capture(args.project).hook(event, data, args.owner, args.task, args.workspace)
655
+ except (ValueError, OSError, GovernanceError, TypeError) as error:
656
+ print(getattr(error,'code',type(error).__name__), file=sys.stderr)
657
+ print('{}')
658
+ return
659
+ if args.action == 'install':
660
+ value = install(args.project,args.owner,args.task,args.workspace,args.expected)
661
+ elif args.action == 'status':
662
+ value = Capture(args.project).sessions()
663
+ else:
664
+ value = Capture(args.project).change(args.conversation,args.action,args.generation)
665
+ print(json.dumps(value, ensure_ascii=True))
666
+
667
+
668
+ if __name__ == '__main__':
669
+ main()