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,25 @@
1
+ """Recovery contracts kept independent of the shared dispatcher."""
2
+
3
+ def obj(properties, required=()):
4
+ return {'type': 'object', 'properties': properties, 'required': list(required), 'additionalProperties': False}
5
+
6
+
7
+ TEXT = {'type': 'string'}
8
+ TEXTS = {'type': 'array', 'items': TEXT, 'maxItems': 4096, 'uniqueItems': True}
9
+ SOURCE = obj({'name': TEXT, 'path': TEXT, 'kind': {'type': 'string', 'enum': ['git', 'files']},
10
+ 'paths': TEXTS, 'refs': TEXTS}, ['name'])
11
+ SCHEMAS = {'recovery': obj({
12
+ 'action': {'type': 'string', 'enum': ['backup_plan', 'backup_execute', 'verify', 'status', 'history',
13
+ 'restore_plan', 'restore_execute', 'activation_plan', 'activate']},
14
+ 'destination': TEXT, 'plan_id': TEXT, 'manifest': TEXT, 'expected_sha256': TEXT,
15
+ 'workspaces': {'type': 'array', 'items': SOURCE, 'maxItems': 100},
16
+ 'payloads': {'type': 'array', 'items': SOURCE, 'maxItems': 100},
17
+ 'authorization': TEXT, 'old_writer_stopped': {'type': 'boolean'},
18
+ 'native_evidence': obj({'source_id': TEXT, 'replica_id': TEXT, 'control': TEXT,
19
+ 'doctor': {'type': 'boolean'}, 'status': {'type': 'boolean'},
20
+ 'evidence_ref': TEXT}, ['source_id', 'replica_id', 'control', 'doctor', 'status', 'evidence_ref']),
21
+ 'old_replica_id': TEXT,
22
+ 'collection': TEXT, 'local_id': TEXT, 'cursor': TEXT,
23
+ 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 100},
24
+ }, ['action'])}
25
+ DESCRIPTIONS = {'recovery': 'Plan, capture and verify a selected portable recovery set; restore real Git history, index, WIP and governance state into an independent standby copy. Writer activation is a separate explicit handoff, never multiwriter database synchronization.'}
@@ -0,0 +1,153 @@
1
+ """Bounded portable byte storage, atomic records and exclusive batch locks."""
2
+ from contextlib import contextmanager
3
+ import hashlib
4
+ import json
5
+ import os
6
+ from pathlib import Path, PurePosixPath
7
+ import re
8
+ import stat
9
+ import uuid
10
+
11
+ from .core import _linked, read_file_bytes
12
+ from .store import GovernanceError
13
+
14
+ MAX_BYTES = 512 * 1024 * 1024
15
+ MAX_FILE = 64 * 1024 * 1024
16
+ MAX_FILES = 4096
17
+ SHA = re.compile(r'^[0-9a-f]{64}$')
18
+
19
+
20
+ def encoded(value):
21
+ return (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2, allow_nan=False) + '\n').encode('utf-8')
22
+
23
+
24
+ def digest(data):
25
+ return hashlib.sha256(data).hexdigest()
26
+
27
+
28
+ def normal(value):
29
+ p = Path(value).expanduser().absolute()
30
+ if any(_linked(part) for part in (p, *p.parents)):
31
+ raise GovernanceError('RECOVERY_UNSAFE_PATH', 'Linked or reparse paths are not recovery inputs or destinations.')
32
+ return p.resolve()
33
+
34
+
35
+ def relative(value):
36
+ if not isinstance(value, str) or not value:
37
+ raise GovernanceError('RECOVERY_UNSAFE_PATH', 'Use an exact relative file path.')
38
+ p = PurePosixPath(value)
39
+ if (value != p.as_posix() or p.is_absolute() or any(c in value for c in '\\:\0\r\n<>"|?*')
40
+ or any(x in ('.', '..') or x.endswith((' ', '.'))
41
+ or re.fullmatch(r'(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?', x, re.I) for x in p.parts)):
42
+ raise GovernanceError('RECOVERY_UNSAFE_PATH', 'Recovery paths must be portable, relative and traversal-free.')
43
+ return p
44
+
45
+
46
+ def safe(root, name):
47
+ root = normal(root)
48
+ result = normal(root.joinpath(*relative(name).parts))
49
+ if not result.is_relative_to(root):
50
+ raise GovernanceError('RECOVERY_UNSAFE_PATH', 'Recovery path escaped its root.')
51
+ return result
52
+
53
+
54
+ def disjoint(a, b):
55
+ a, b = normal(a), normal(b)
56
+ if a.is_relative_to(b) or b.is_relative_to(a):
57
+ raise GovernanceError('RECOVERY_NOT_INDEPENDENT', 'Recovery media and targets must be independent of their sources.')
58
+
59
+
60
+ def read_json(path, limit=64 * 1024 * 1024):
61
+ data = read_file_bytes(normal(path), limit)
62
+ def pairs(items):
63
+ result = {}
64
+ for key, value in items:
65
+ if key in result:
66
+ raise GovernanceError('RECOVERY_MANIFEST', 'Duplicate JSON member.')
67
+ result[key] = value
68
+ return result
69
+ try:
70
+ value = json.loads(data, object_pairs_hook=pairs)
71
+ except (ValueError, UnicodeError) as exc:
72
+ raise GovernanceError('RECOVERY_MANIFEST', 'Recovery metadata is not valid JSON.') from exc
73
+ return value, digest(data)
74
+
75
+
76
+ def atomic(path, data, *, replace=False):
77
+ path = normal(path)
78
+ if path.exists() and not replace:
79
+ if read_file_bytes(path, max(MAX_FILE, len(data))) != data:
80
+ raise GovernanceError('RECOVERY_CONFLICT', 'Existing immutable recovery bytes differ; preserved for review.', {'path': str(path)})
81
+ return
82
+ path.parent.mkdir(parents=True, exist_ok=True)
83
+ temporary = path.with_name(path.name + '.' + uuid.uuid4().hex + '.partial')
84
+ with temporary.open('xb') as stream:
85
+ stream.write(data)
86
+ stream.flush()
87
+ os.fsync(stream.fileno())
88
+ if path.exists() and not replace:
89
+ if read_file_bytes(path, max(MAX_FILE, len(data))) != data:
90
+ raise GovernanceError('RECOVERY_CONFLICT', 'Concurrent immutable recovery publication differs.')
91
+ temporary.unlink()
92
+ return
93
+ # All cooperating publishers own the batch lock. No partial final file is visible.
94
+ os.replace(temporary, path)
95
+
96
+
97
+ def write_json(path, value, *, replace=False):
98
+ atomic(path, encoded(value), replace=replace)
99
+
100
+
101
+ @contextmanager
102
+ def lock(path):
103
+ path = normal(path)
104
+ path.parent.mkdir(parents=True, exist_ok=True)
105
+ with path.open('a+b') as stream:
106
+ stream.seek(0, 2)
107
+ if not stream.tell():
108
+ stream.write(b'0')
109
+ stream.flush()
110
+ stream.seek(0)
111
+ try:
112
+ if os.name == 'nt':
113
+ import msvcrt
114
+ msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
115
+ else:
116
+ import fcntl
117
+ fcntl.flock(stream, fcntl.LOCK_EX | fcntl.LOCK_NB)
118
+ except OSError as exc:
119
+ raise GovernanceError('RECOVERY_BUSY', 'This recovery batch is in use.') from exc
120
+ try:
121
+ yield
122
+ finally:
123
+ stream.seek(0)
124
+ if os.name == 'nt':
125
+ msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
126
+ else:
127
+ fcntl.flock(stream, fcntl.LOCK_UN)
128
+
129
+
130
+ def put(media, data):
131
+ if len(data) > MAX_BYTES:
132
+ raise GovernanceError('RECOVERY_BUDGET', 'Recovery payload exceeds the bounded byte limit.')
133
+ checksum = digest(data)
134
+ atomic(safe(media, 'objects/' + checksum), data)
135
+ return {'sha256': checksum, 'size': len(data)}
136
+
137
+
138
+ def get(media, ref):
139
+ if (not isinstance(ref, dict) or not isinstance(ref.get('sha256'), str) or not SHA.fullmatch(ref['sha256'])
140
+ or type(ref.get('size')) is not int or not 0 <= ref['size'] <= MAX_BYTES):
141
+ raise GovernanceError('RECOVERY_MANIFEST', 'Invalid recovery object reference.')
142
+ path = safe(media, 'objects/' + ref['sha256'])
143
+ try:
144
+ data = read_file_bytes(path, MAX_BYTES)
145
+ except FileNotFoundError as exc:
146
+ raise GovernanceError('RECOVERY_OBJECT_MISSING', 'A required recovery object is missing.', ref) from exc
147
+ if len(data) != ref['size'] or digest(data) != ref['sha256']:
148
+ raise GovernanceError('RECOVERY_OBJECT_MISMATCH', 'A required recovery object has different bytes.', ref)
149
+ return data
150
+
151
+
152
+ def mode(path):
153
+ return '100755' if os.name != 'nt' and path.stat().st_mode & stat.S_IXUSR else '100644'
@@ -0,0 +1,234 @@
1
+ """Exact selected history plus logical index and regular-file working layers."""
2
+ import copy
3
+ import os
4
+ from pathlib import Path
5
+ import subprocess
6
+
7
+ from .core import read_file_bytes, validate_relative_path
8
+ from .store import GovernanceError
9
+ from .recovery_files import MAX_BYTES, MAX_FILE, MAX_FILES, digest, encoded, normal, put, get, mode, safe, atomic
10
+
11
+
12
+ def host_entry(path):
13
+ name = path.casefold()
14
+ return (name in ('.codex/config.toml', '.codex/taskcarry-routing.json', '.mcp.json', '.claude/settings.json')
15
+ or name.startswith('.codex/automations/') and name.endswith('/automation.toml'))
16
+
17
+
18
+ def quarantine(path):
19
+ return '.taskcarry-disabled-host/' + path
20
+
21
+
22
+ def git(root, *args, data=None, check=True):
23
+ environment = {k: v for k, v in os.environ.items() if not k.startswith('GIT_')}
24
+ environment.update(GIT_CONFIG_NOSYSTEM='1', GIT_CONFIG_GLOBAL=os.devnull,
25
+ GIT_TERMINAL_PROMPT='0', GIT_OPTIONAL_LOCKS='0')
26
+ try:
27
+ result = subprocess.run(['git', '--literal-pathspecs', '-c', 'core.hooksPath=' + os.devnull,
28
+ '-c', 'core.autocrlf=false', '-c', 'core.longpaths=true', '-c', 'commit.gpgSign=false', '-C', str(root), *args],
29
+ input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
30
+ env=environment, timeout=120, check=False)
31
+ except FileNotFoundError as exc:
32
+ raise GovernanceError('GIT_UNAVAILABLE', 'Git is required for selected Git recovery components.') from exc
33
+ except subprocess.TimeoutExpired as exc:
34
+ raise GovernanceError('GIT_TIMEOUT', 'The bounded recovery Git operation timed out.') from exc
35
+ if check and result.returncode:
36
+ raise GovernanceError('RECOVERY_GIT', 'Git recovery operation failed.',
37
+ {'command': args[0], 'stderr': result.stderr.decode('utf-8', 'replace')[:2000]})
38
+ return result.stdout
39
+
40
+
41
+ def decode(data):
42
+ try:
43
+ return data.decode('utf-8')
44
+ except UnicodeError as exc:
45
+ raise GovernanceError('RECOVERY_PATH_ENCODING', 'This portable recovery supports UTF-8 Git paths.') from exc
46
+
47
+
48
+ def observe(root, requested_refs=None):
49
+ root = normal(root)
50
+ if normal(decode(git(root, 'rev-parse', '--show-toplevel')).strip()) != root:
51
+ raise GovernanceError('RECOVERY_GIT_ROOT', 'Select an actual Git worktree root.')
52
+ head = decode(git(root, 'rev-parse', '--verify', 'HEAD', check=False)).strip()
53
+ if not head:
54
+ raise GovernanceError('RECOVERY_GIT_UNBORN', 'Commit the initial Git baseline before history recovery; plain files can be preserved separately.')
55
+ branch = decode(git(root, 'symbolic-ref', '--quiet', 'HEAD', check=False)).strip() or None
56
+ all_refs, all_symbolic = {}, {}
57
+ for line in decode(git(root, 'for-each-ref', '--format=%(refname) %(objectname) %(symref)')).splitlines():
58
+ name, oid, symbolic = line.split(' ', 2)
59
+ all_refs[name] = oid
60
+ if symbolic:
61
+ all_symbolic[name] = symbolic
62
+ names = sorted(all_refs) if requested_refs is None else sorted(set(requested_refs))
63
+ if len(names) > 256 or any(name != 'HEAD' and name not in all_refs for name in names):
64
+ raise GovernanceError('RECOVERY_REFS', 'Select at most 256 existing exact refs or HEAD.')
65
+ refs = {name: all_refs[name] for name in names if name != 'HEAD'}
66
+ pending = list(refs)
67
+ while pending:
68
+ name = pending.pop()
69
+ target = all_symbolic.get(name)
70
+ if target and target not in refs:
71
+ if target not in all_refs or len(refs) >= 256:
72
+ raise GovernanceError('RECOVERY_REFS', 'Selected symbolic refs require a bounded available target chain.')
73
+ refs[target] = all_refs[target]
74
+ pending.append(target)
75
+ # HEAD and its current branch are necessary dependencies, always explicit in the plan.
76
+ if branch:
77
+ refs[branch] = head
78
+ entries = []
79
+ index = git(root, 'ls-files', '--stage', '-z')
80
+ for row in index.split(b'\0'):
81
+ if not row:
82
+ continue
83
+ prefix, name = row.split(b'\t', 1)
84
+ file_mode, oid, stage = prefix.decode('ascii').split()
85
+ path = decode(name)
86
+ validate_relative_path(root, path)
87
+ if file_mode not in ('100644', '100755') or stage != '0':
88
+ raise GovernanceError('RECOVERY_INDEX_UNSUPPORTED', 'Resolve unmerged, symlink or submodule entries before this regular-file recovery.', {'path': path})
89
+ entries.append({'path': path, 'mode': file_mode, 'oid': oid})
90
+ flags = git(root, 'ls-files', '-v', '-z')
91
+ if any(row and row[:1] != b'H' for row in flags.split(b'\0')):
92
+ raise GovernanceError('RECOVERY_INDEX_FLAGS', 'Sparse, assume-unchanged or special index flags require a separate reviewed export.')
93
+ if len(entries) > MAX_FILES:
94
+ raise GovernanceError('RECOVERY_BUDGET', 'The selected Git index exceeds the file-count budget.')
95
+ unknown = [decode(x) for x in git(root, 'ls-files', '--others', '--exclude-standard', '-z').split(b'\0') if x]
96
+ return {'head': head, 'branch': branch, 'refs': refs,
97
+ 'symbolic_refs': {name: target for name, target in all_symbolic.items() if name in refs},
98
+ 'excluded_refs': sorted(set(all_refs) - set(refs)), 'index': entries,
99
+ 'object_format': decode(git(root, 'rev-parse', '--show-object-format')).strip(),
100
+ 'untracked': sorted(unknown), 'index_fingerprint': digest(index)}
101
+
102
+
103
+ def files(root, paths):
104
+ if len(paths) > MAX_FILES or len({p.casefold() for p in paths}) != len(paths):
105
+ raise GovernanceError('RECOVERY_BUDGET', 'File selections must be bounded and case-portably unique.')
106
+ result, total = [], 0
107
+ for name in sorted(paths):
108
+ path = validate_relative_path(root, name)
109
+ if path.exists():
110
+ data = read_file_bytes(path, MAX_FILE)
111
+ total += len(data)
112
+ if total > MAX_BYTES:
113
+ raise GovernanceError('RECOVERY_BUDGET', 'Working files exceed the selected byte budget.')
114
+ result.append({'path': name, 'sha256': digest(data), 'size': len(data), 'mode': mode(path)})
115
+ else:
116
+ result.append({'path': name, 'missing': True})
117
+ return result
118
+
119
+
120
+ def inventory(root, kind, paths, refs=None, *, compact=True):
121
+ result = {'kind': kind, 'source': str(normal(root))}
122
+ if kind == 'git':
123
+ observation = observe(root, refs)
124
+ # Index includes additions. HEAD includes staged deletions whose remaining working bytes matter.
125
+ head_paths = [decode(x) for x in git(root, 'ls-tree', '-r', '--name-only', '-z', observation['head']).split(b'\0') if x]
126
+ selected = sorted(set(head_paths) | {i['path'] for i in observation['index']} | set(paths))
127
+ if any(p.split('/')[0].casefold() == '.taskcarry-disabled-host' for p in selected):
128
+ raise GovernanceError('RECOVERY_RESERVED_PATH', 'The host-quarantine namespace must not collide with selected user files.')
129
+ unknown = observation['untracked']
130
+ excluded = sorted(set(unknown) - set(paths))
131
+ result.update(git=observation, files=files(root, selected), excluded_untracked=excluded)
132
+ # Excluded names are evidence, not selected payloads. Preserve a stable
133
+ # full-list digest/count and bounded examples instead of serializing
134
+ # tens of thousands of names twice into every new plan and manifest.
135
+ if compact and len(unknown) > 1000:
136
+ observation.update(untracked=unknown[:1000], untracked_count=len(unknown),
137
+ untracked_sha256=digest(encoded(unknown)), untracked_listing_truncated=True)
138
+ if compact and len(excluded) > 1000:
139
+ result.update(excluded_untracked=excluded[:1000], excluded_untracked_count=len(excluded),
140
+ excluded_untracked_sha256=digest(encoded(excluded)), excluded_untracked_listing_truncated=True)
141
+ else:
142
+ if any(p.split('/')[0].casefold() == '.taskcarry-disabled-host' for p in paths):
143
+ raise GovernanceError('RECOVERY_RESERVED_PATH', 'The host-quarantine namespace must not collide with selected user files.')
144
+ result['files'] = files(root, paths)
145
+ return result
146
+
147
+
148
+ def capture(media, selected, scratch):
149
+ root = normal(selected['source'])
150
+ # Resume an already frozen legacy plan without changing its bytes or scope.
151
+ # Its original full-name representation is compared exactly; new plans use
152
+ # compact metadata and still detect changes beyond the visible examples.
153
+ legacy = (selected['kind'] == 'git'
154
+ and len(selected.get('git', {}).get('untracked', [])) > 1000
155
+ and 'untracked_sha256' not in selected.get('git', {}))
156
+ before = inventory(root, selected['kind'], selected['selected_paths'], selected.get('selected_refs'), compact=not legacy)
157
+ expected = {k: v for k, v in selected.items() if k not in ('name', 'target', 'selected_paths', 'selected_refs')}
158
+ if before != expected:
159
+ raise GovernanceError('RECOVERY_SOURCE_CHANGED', 'Selected source changed since planning; prepare a fresh plan.')
160
+ result = copy.deepcopy({k: v for k, v in selected.items() if k not in ('selected_paths', 'selected_refs')})
161
+ for item in result['files']:
162
+ if not item.get('missing'):
163
+ data = read_file_bytes(validate_relative_path(root, item['path']), MAX_FILE)
164
+ if digest(data) != item['sha256']:
165
+ raise GovernanceError('RECOVERY_SOURCE_CHANGED', 'A selected file changed during capture.')
166
+ item['object'] = put(media, data)
167
+ if result['kind'] == 'git':
168
+ for entry in result['git']['index']:
169
+ length = int(git(root, 'cat-file', '-s', entry['oid']).strip())
170
+ if length > MAX_FILE:
171
+ raise GovernanceError('RECOVERY_BUDGET', 'Index blob exceeds the selected file limit.')
172
+ entry['object'] = put(media, git(root, 'cat-file', 'blob', entry['oid']))
173
+ scratch.mkdir(parents=True, exist_ok=True)
174
+ bundle = scratch / 'history.bundle'
175
+ git(root, 'bundle', 'create', str(bundle), *result['git']['refs'], 'HEAD')
176
+ result['bundle'] = put(media, read_file_bytes(bundle, MAX_BYTES))
177
+ git(root, 'bundle', 'verify', str(bundle))
178
+ if inventory(root, selected['kind'], selected['selected_paths'], selected.get('selected_refs'), compact=not legacy) != expected:
179
+ raise GovernanceError('RECOVERY_SOURCE_CHANGED', 'Source changed during capture; no component was sealed.')
180
+ return result
181
+
182
+
183
+ def restore(media, component, destination):
184
+ destination.mkdir(parents=True, exist_ok=False)
185
+ if component['kind'] == 'git':
186
+ info = component['git']
187
+ git(destination, 'init', '--quiet', '--object-format=' + info['object_format'])
188
+ bundle = destination / '.git' / 'recovery.bundle'
189
+ atomic(bundle, get(media, component['bundle']))
190
+ refspecs = ['+' + name + ':' + name for name in info['refs']]
191
+ git(destination, 'fetch', '--quiet', '--no-tags', '--update-head-ok', str(bundle), 'HEAD', *refspecs)
192
+ for name, target in info.get('symbolic_refs', {}).items():
193
+ git(destination, 'symbolic-ref', name, target)
194
+ if info['branch']:
195
+ git(destination, 'symbolic-ref', 'HEAD', info['branch'])
196
+ else:
197
+ git(destination, 'update-ref', '--no-deref', 'HEAD', info['head'])
198
+ git(destination, 'read-tree', '--empty')
199
+ index = []
200
+ for entry in info['index']:
201
+ oid = decode(git(destination, 'hash-object', '-w', '--stdin', data=get(media, entry['object']))).strip()
202
+ if oid != entry['oid']:
203
+ raise GovernanceError('RECOVERY_GIT_OBJECT', 'Restored index object identity differs.')
204
+ index.append((entry['mode'] + ' ' + oid + '\t' + entry['path']).encode('utf-8') + b'\0')
205
+ git(destination, 'update-index', '-z', '--index-info', data=b''.join(index))
206
+ bundle.unlink()
207
+ for item in component['files']:
208
+ path = safe(destination, quarantine(item['path']) if host_entry(item['path']) else item['path'])
209
+ if not item.get('missing'):
210
+ atomic(path, get(media, item['object']))
211
+ if os.name != 'nt':
212
+ path.chmod(0o755 if item['mode'] == '100755' else 0o644)
213
+ verify_effect(component, destination)
214
+
215
+
216
+ def verify_effect(component, destination):
217
+ result = files(destination, [x['path'] for x in component['files']])
218
+ expected = [({'path': row['path'], 'missing': True} if host_entry(row['path']) else
219
+ {k: v for k, v in row.items() if k != 'object'}) for row in component['files']]
220
+ if result != expected:
221
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'Restored selected working bytes or modes changed; preserved without replay.')
222
+ for row in component['files']:
223
+ if host_entry(row['path']) and not row.get('missing'):
224
+ quarantined = files(destination, [quarantine(row['path'])])[0]
225
+ if {k: v for k, v in quarantined.items() if k != 'path'} != {k: v for k, v in row.items() if k not in ('path', 'object')}:
226
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'A quarantined native-host configuration changed; preserved for review.')
227
+ if component['kind'] == 'git':
228
+ actual = observe(destination, list(component['git']['refs']))
229
+ wanted = component['git']
230
+ index = [{k: v for k, v in row.items() if k != 'object'} for row in wanted['index']]
231
+ if any(actual[k] != wanted[k] for k in ('head', 'branch', 'refs', 'symbolic_refs', 'object_format')) or actual['index'] != index:
232
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'Restored Git history, refs or index changed; preserved without replay.')
233
+ git(destination, 'fsck', '--full', '--no-reflogs')
234
+ return True
@@ -0,0 +1,89 @@
1
+ """Device-scoped WorkBuddy handoff into the usual consent and recent-turn records."""
2
+ import re
3
+ import secrets
4
+
5
+ from .agy_turns import visible_body
6
+ from .conversation_capture import Capture
7
+ from .store import now
8
+ from .worker_channel import Caller, fail, fingerprint
9
+
10
+
11
+ PROTOCOL = 'taskcarry.workbuddy.visible-turns.v1'
12
+ FIELDS = {
13
+ 'register': set(), 'status': set(), 'begin': {'request_id'},
14
+ 'complete': {'request_id', 'generation', 'ticket', 'user', 'assistant'},
15
+ }
16
+
17
+
18
+ def device_request(invitation, body):
19
+ """Identity, task, workspace and grant version come only from the authenticated service."""
20
+ if not isinstance(body, dict) or not isinstance(body.get('action'), str):
21
+ fail('INVALID_ARGUMENT', 'Invalid device request.')
22
+ action = body['action']
23
+ if action not in FIELDS or set(body) != {'action', 'session'} | FIELDS[action]:
24
+ fail('INVALID_ARGUMENT', 'Unexpected device fields.')
25
+ session = body['session']
26
+ if not isinstance(session, str) or not re.fullmatch('[a-f0-9]{64}', session):
27
+ fail('INVALID_ARGUMENT', 'Expected a scoped session fingerprint.')
28
+ if 'request_id' in body and (not isinstance(body['request_id'], str)
29
+ or not re.fullmatch('[a-f0-9]{32,64}', body['request_id'])):
30
+ fail('INVALID_ARGUMENT', 'Expected a turn identifier.')
31
+ caller = Caller(invitation.binding_id, 'worker', invitation.project_id, invitation.binding_revision)
32
+ capture = Capture(invitation.control, caller=caller)
33
+ channel, store = capture.channel, capture.store
34
+ cid = 'wb-' + fingerprint([invitation.project_id, caller.binding_id, invitation.binding_revision, session])
35
+ context = store._connect(readonly=True) if action == 'status' else store.transaction()
36
+ with context:
37
+ channel._auth('discussion_update')
38
+ if not (channel.binding['read_project_shared'] and channel.binding['share_project']
39
+ and 'source_scope' not in channel.binding and invitation.access_active()):
40
+ fail('CAPTURE_SCOPE', 'This member cannot share a project conversation.')
41
+ channel._assignment(invitation.task_id, invitation.workspace_id, 'progress')
42
+ s = store.get('capture_sessions', cid)
43
+ if s is None and action == 'register':
44
+ s = capture.new_session(cid, 'workbuddy-remote', caller.binding_id,
45
+ invitation.task_id, invitation.workspace_id)
46
+ s.update(binding_revision=invitation.binding_revision, coverage='sharing_off')
47
+ store.put('capture_sessions', cid, s)
48
+ if (not s or s.get('provider') != 'workbuddy-remote' or s.get('binding_revision') != invitation.binding_revision
49
+ or s['epoch'] != channel._epoch() or s['owner'] != caller.binding_id
50
+ or s['task_id'] != invitation.task_id or s['workspace_id'] != invitation.workspace_id):
51
+ fail('CAPTURE_UNAVAILABLE', 'Register the selected conversation on this device.')
52
+ result = dict(conversation_id=cid, state=s['state'], generation=s['generation'])
53
+ if action in {'register', 'status'}:
54
+ return result
55
+ if s['state'] != 'active':
56
+ return {**result, 'accepted': False}
57
+ request_id = body['request_id']
58
+ pending = s.get('remote_pending') or {}
59
+ if action == 'begin':
60
+ if pending.get('request_id') != request_id:
61
+ pending = {'request_id': request_id, 'ticket': secrets.token_hex(24)}
62
+ s['remote_pending'] = pending
63
+ store.put('capture_sessions', cid, s)
64
+ return {**result, 'ticket': pending['ticket']}
65
+
66
+ if type(body['generation']) is not int or body['generation'] != s['generation']:
67
+ return {**result, 'accepted': False}
68
+ ticket = body['ticket']
69
+ if not isinstance(ticket, str) or not re.fullmatch('[a-f0-9]{48}', ticket):
70
+ fail('INVALID_ARGUMENT', 'Invalid turn receipt.')
71
+ prior = s.get('remote_receipt') or {}
72
+ grant = {'request_id': request_id, 'ticket': ticket}
73
+ if pending != grant and prior.get('grant') != grant:
74
+ return {**result, 'accepted': False}
75
+ question, q_gap = visible_body(body['user'])
76
+ final, a_gap = visible_body(body['assistant'])
77
+ if question is None or final is None:
78
+ fail('INVALID_ARGUMENT', 'Provide a complete visible question and final reply.')
79
+ turn = {'turn_id': 'turn-' + request_id, 'user': question, 'assistant': final,
80
+ 'omissions': q_gap or a_gap}
81
+ digest = fingerprint(turn)
82
+ if prior.get('grant') == grant:
83
+ return {**result, 'accepted': prior['sha256'] == digest, 'sha256': prior['sha256']}
84
+ capture.save_turn(s, None, turn)
85
+ s.pop('remote_pending', None)
86
+ s.update(remote_receipt={'grant': grant, 'sha256': digest},
87
+ updated_at=now(), coverage='visible_pair')
88
+ store.put('capture_sessions', cid, s)
89
+ return {**result, 'accepted': True, 'sha256': digest}