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,824 @@
1
+ """Portable selected recovery sets and independent, inert restored replicas.
2
+
3
+ The media is an ordinary local directory suitable for a static offsite copy.
4
+ No live SQLite synchronization, remote writer fencing, credential copying or
5
+ host configuration is implied by a successful local recovery receipt.
6
+ """
7
+ from contextlib import closing
8
+ import copy
9
+ import json
10
+ import os
11
+ from pathlib import Path
12
+ import sqlite3
13
+ import sys
14
+ import uuid
15
+
16
+ from . import __version__
17
+ from .core import Core, _id, read_file_bytes
18
+ from .store import Store, GovernanceError, now
19
+ from .state_format import inspect_state
20
+ from . import recovery_git as rg
21
+ from .recovery_files import (MAX_BYTES, MAX_FILE, MAX_FILES, SHA, atomic, digest, disjoint,
22
+ encoded, get, lock, normal, put, read_json, relative, safe, write_json)
23
+
24
+ SCHEMA = 'taskcarry.project-recovery.v1'
25
+ PLAN_SCHEMA = 'taskcarry.recovery-plan.v1'
26
+
27
+
28
+ def _baseline_recovery(binding, components, registered, prior=None):
29
+ """Resolve an executable baseline only through its exact captured identity."""
30
+ if not binding:
31
+ if prior and prior.get('status') == 'REBIND_REQUIRED':
32
+ return {'status': 'REBIND_REQUIRED', 'component': None,
33
+ 'reason': 'The captured replica already requires a reviewed baseline recovery.'}
34
+ return {'status': 'NOT_BOUND', 'component': None}
35
+ matches = [c for c in components if c['kind'] == 'git'
36
+ and normal(c['source']) == normal(binding.get('path', ''))
37
+ and c.get('git', {}).get('branch') == binding.get('branch')
38
+ and any(w.get('identity') == binding for w in registered.values())]
39
+ if len(matches) == 1:
40
+ return {'status': 'MAPPED', 'component': matches[0]['name']}
41
+ return {'status': 'REBIND_REQUIRED', 'component': None,
42
+ 'reason': 'The bound baseline has no unique selected Git component with its registered source identity and branch.'}
43
+
44
+
45
+ def _complete_scope(value, baseline):
46
+ return (baseline.get('status') != 'REBIND_REQUIRED'
47
+ and not any(value.get(k) for k in ('missing_workspace_payloads', 'missing_artifact_payloads', 'missing_history_dependencies')))
48
+
49
+
50
+ def _state_references(rows):
51
+ for collection, key, value in rows:
52
+ if collection == 'checkpoints':
53
+ yield from _refs(value.get('files', []))
54
+ elif collection == 'preservation':
55
+ yield from _refs([value.get('index_before'), value.get('index_after')])
56
+ elif (collection == 'worker_sources' or
57
+ collection == 'worker_versions' and key.startswith('source:')):
58
+ # Published sources and their earlier revisions are immutable
59
+ # payloads, including revoked versions retained as history.
60
+ yield {'sha256': value['content_sha256'], 'size': value['size']}
61
+ elif collection in {'worker_plans', 'worker_connection_materials', 'worker_exchange_views',
62
+ 'worker_exchange_imports', 'worker_remote_checkpoints'}:
63
+ # Explicit packet/manifest/layer refs only. A bare hash string is
64
+ # not enough to claim preservation of the corresponding payload.
65
+ yield from _refs(value)
66
+ elif collection == 'recovery_history' and isinstance(value, dict):
67
+ # Older recovery generations retain checkpoint/plan objects too.
68
+ yield from _state_references([(value.get('original_collection'), value.get('original_key'), value.get('record', {}))])
69
+
70
+
71
+ def _state_rows(path):
72
+ try:
73
+ with closing(sqlite3.connect(normal(path).as_uri() + '?mode=ro&immutable=1', uri=True)) as db:
74
+ if db.execute('PRAGMA integrity_check').fetchone()[0] != 'ok':
75
+ raise GovernanceError('RECOVERY_STATE_CORRUPT', 'The governance snapshot failed SQLite integrity checking.')
76
+ inspected = inspect_state(db)
77
+ if inspected['state'] == 'unsupported':
78
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'The snapshot governance schema is unsupported.')
79
+ if inspected['state'] != 'compatible':
80
+ raise GovernanceError('RECOVERY_STATE_CORRUPT', 'The snapshot is not a complete supported TaskCarry state database.',
81
+ {'reason': inspected['reason']})
82
+ if db.execute("SELECT 1 FROM sqlite_master WHERE name='experience_schema' AND type='table'").fetchone():
83
+ if db.execute('SELECT version FROM experience_schema').fetchone() != (1,):
84
+ raise GovernanceError('EXPERIENCE_SCHEMA_UNSUPPORTED', 'This snapshot needs a compatible conditional-experience runtime.')
85
+ return [(c, k, json.loads(v)) for c, k, v in db.execute('SELECT collection,key,value FROM records')]
86
+ except (sqlite3.Error, ValueError, TypeError, UnicodeError) as exc:
87
+ raise GovernanceError('RECOVERY_STATE_CORRUPT', 'The governance snapshot cannot be read safely.') from exc
88
+
89
+
90
+ def _state_fingerprint(store):
91
+ with store._connect(readonly=True) as db:
92
+ records = list(db.execute('SELECT collection,key,value FROM records ORDER BY collection,key'))
93
+ events = list(db.execute('SELECT sequence,created_at,kind,payload FROM events ORDER BY sequence'))
94
+ return {'records_sha256': digest(encoded(records)), 'events_sha256': digest(encoded(events)),
95
+ 'records': len(records), 'events': len(events)}
96
+
97
+
98
+ def _archive(store, restore_id, collection, key, record):
99
+ store.put('recovery_history', restore_id + ':' + collection + ':' + key,
100
+ {'original_collection': collection, 'original_key': key, 'record': record,
101
+ 'restore_id': restore_id, 'executable': False})
102
+
103
+
104
+ def _refs(value):
105
+ """Find only structurally explicit content-store references."""
106
+ if isinstance(value, dict):
107
+ if set(('sha256', 'size')).issubset(value):
108
+ yield {'sha256': value['sha256'], 'size': value['size']}
109
+ for child in value.values():
110
+ yield from _refs(child)
111
+ elif isinstance(value, list):
112
+ for child in value:
113
+ yield from _refs(child)
114
+
115
+
116
+ def _payload_refs(value):
117
+ return _refs({'snapshot': value['state']['snapshot'], 'objects': value['state']['objects'],
118
+ 'components': value['components']})
119
+
120
+
121
+ def _manifest(path, expected=None):
122
+ try:
123
+ return _manifest_data(path, expected)
124
+ except (KeyError, TypeError, AttributeError, IndexError, RecursionError) as exc:
125
+ raise GovernanceError('RECOVERY_MANIFEST', 'Recovery manifest structure is incomplete or invalid.') from exc
126
+
127
+
128
+ def _manifest_data(path, expected=None):
129
+ value, checksum = read_json(path)
130
+ if expected is not None and checksum != expected:
131
+ raise GovernanceError('RECOVERY_MANIFEST_MISMATCH', 'The recovery manifest differs from the reviewed digest.')
132
+ if not isinstance(value, dict) or value.get('schema') != SCHEMA:
133
+ raise GovernanceError('RECOVERY_SCHEMA_UNSUPPORTED', 'Use a compatible project recovery reader.')
134
+ if value.get('state', {}).get('schema_version') != 1 or type(value['state']['schema_version']) is not int:
135
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'The captured governance schema is unsupported.')
136
+ if value.get('runtime', {}).get('python_minimum') != '3.11' or value['runtime'].get('recovery_schema') != 1:
137
+ raise GovernanceError('RECOVERY_SCHEMA_UNSUPPORTED', 'The recovery runtime requirements are unsupported.')
138
+ _id(value.get('set_id'), 'Recovery set')
139
+ targets, names, count = [], set(), 0
140
+ components = value.get('components')
141
+ if not isinstance(components, list) or len(components) > 200:
142
+ raise GovernanceError('RECOVERY_MANIFEST', 'Invalid recovery component list.')
143
+ for component in components:
144
+ _id(component.get('name'), 'Recovery component')
145
+ target = relative(component.get('target')).as_posix()
146
+ if target != 'control' and not target.startswith(('workspaces/', 'payloads/')):
147
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsupported recovery target.')
148
+ if component['name'].casefold() in names or any(target.casefold() == t or target.casefold().startswith(t + '/') or t.startswith(target.casefold() + '/') for t in targets):
149
+ raise GovernanceError('RECOVERY_MANIFEST', 'Recovery component identities or destinations overlap.')
150
+ names.add(component['name'].casefold()); targets.append(target.casefold())
151
+ if component.get('kind') not in ('git', 'files') or not isinstance(component.get('files'), list):
152
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsupported component kind or file list.')
153
+ seen = set()
154
+ for item in component['files']:
155
+ name = relative(item.get('path')).as_posix()
156
+ if name.split('/')[0].casefold() == '.taskcarry-disabled-host':
157
+ raise GovernanceError('RECOVERY_MANIFEST', 'A selected input collides with the recovery host-quarantine namespace.')
158
+ # Reject internal metadata, secret filenames, symlinks and aliases on import too.
159
+ from .core import validate_relative_path
160
+ validate_relative_path(Path(path).parent / 'validation-only', name)
161
+ if name.casefold() in seen:
162
+ raise GovernanceError('RECOVERY_MANIFEST', 'Duplicate recovery file path.')
163
+ seen.add(name.casefold()); count += 1
164
+ if not item.get('missing') and item.get('mode') not in ('100644', '100755'):
165
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsupported recovery file mode.')
166
+ if component['kind'] == 'git':
167
+ info = component.get('git', {})
168
+ if info.get('object_format') not in ('sha1', 'sha256'):
169
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsupported Git object format.')
170
+ if info.get('branch') is not None and info.get('branch') not in info.get('refs', {}):
171
+ raise GovernanceError('RECOVERY_MANIFEST', 'The current branch is not in the preserved refs.')
172
+ for name, target in info.get('symbolic_refs', {}).items():
173
+ if name not in info.get('refs', {}) or target not in info['refs']:
174
+ raise GovernanceError('RECOVERY_MANIFEST', 'Symbolic refs require their selected target dependencies.')
175
+ for oid in [info.get('head'), *[i.get('oid') for i in info.get('index', [])]]:
176
+ if not isinstance(oid, str) or len(oid) not in (40, 64) or any(c not in '0123456789abcdef' for c in oid):
177
+ raise GovernanceError('RECOVERY_MANIFEST', 'Invalid Git object identity.')
178
+ for name, oid in info.get('refs', {}).items():
179
+ if not name.startswith('refs/') or any(c in name for c in '\0\r\n :~^?*[') or '..' in name or '@{' in name:
180
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsafe Git ref in recovery manifest.')
181
+ if not isinstance(oid, str) or len(oid) not in (40, 64) or any(c not in '0123456789abcdef' for c in oid):
182
+ raise GovernanceError('RECOVERY_MANIFEST', 'Invalid Git object identity.')
183
+ for item in info.get('index', []):
184
+ validate_relative_path(Path(path).parent / 'validation-only', item.get('path'))
185
+ if item.get('mode') not in ('100644', '100755'):
186
+ raise GovernanceError('RECOVERY_MANIFEST', 'Unsupported index mode.')
187
+ if count > MAX_FILES * 4:
188
+ raise GovernanceError('RECOVERY_BUDGET', 'Recovery manifest exceeds the selected file budget.')
189
+ refs = list(_payload_refs(value))
190
+ unique = {}
191
+ for ref in refs:
192
+ if not isinstance(ref['sha256'], str) or not SHA.fullmatch(ref['sha256']) or type(ref['size']) is not int or not 0 <= ref['size'] <= MAX_BYTES:
193
+ raise GovernanceError('RECOVERY_MANIFEST', 'Invalid payload identity.')
194
+ if ref['sha256'] in unique and unique[ref['sha256']] != ref['size']:
195
+ raise GovernanceError('RECOVERY_MANIFEST', 'Contradictory content-addressed payload sizes.')
196
+ unique[ref['sha256']] = ref['size']
197
+ if sum(unique.values()) > MAX_BYTES * 4:
198
+ raise GovernanceError('RECOVERY_BUDGET', 'Recovery set exceeds the aggregate byte budget.')
199
+ return value, checksum
200
+
201
+
202
+ class ProjectRecovery(Core):
203
+ def __init__(self, project):
204
+ # Verification and disaster restore must work without the original state.
205
+ self.root = normal(project)
206
+ self.store = None
207
+ if (self.root / '.taskcarry' / 'state.sqlite3').is_file():
208
+ super().__init__(project)
209
+ self.ledger = self.root / ('.taskcarry/recovery' if self.store is not None else '.taskcarry-recovery')
210
+
211
+ def _require_store(self):
212
+ if self.store is None:
213
+ raise GovernanceError('RECOVERY_STATE_REQUIRED', 'Backup and writer handoff require an existing governance state.')
214
+
215
+ def _plan_path(self, plan_id):
216
+ return safe(self.ledger, _id(plan_id, 'Recovery plan') + '.json')
217
+
218
+ def _load_plan(self, plan_id, kind=None):
219
+ try:
220
+ value, _ = read_json(self._plan_path(plan_id))
221
+ except FileNotFoundError as exc:
222
+ raise GovernanceError('RECOVERY_PLAN_NOT_FOUND', 'Read or create the exact recovery plan first.') from exc
223
+ if value.get('schema') != PLAN_SCHEMA or value.get('plan_id') != plan_id or kind and value.get('kind') != kind:
224
+ raise GovernanceError('RECOVERY_PLAN_MISMATCH', 'This plan is not compatible with the requested recovery action.')
225
+ return value
226
+
227
+ def recovery(self, action, destination=None, plan_id=None, manifest=None, expected_sha256=None,
228
+ workspaces=None, payloads=None, authorization=None, old_writer_stopped=False,
229
+ native_evidence=None, old_replica_id=None, collection=None, local_id=None, cursor=None, limit=20):
230
+ allowed = {'backup_plan': {'destination', 'workspaces', 'payloads'}, 'backup_execute': {'plan_id'},
231
+ 'verify': {'manifest', 'expected_sha256'}, 'status': {'plan_id'},
232
+ 'restore_plan': {'manifest', 'destination', 'expected_sha256'}, 'restore_execute': {'plan_id'},
233
+ 'activation_plan': set(), 'activate': {'plan_id', 'authorization', 'old_writer_stopped', 'native_evidence', 'old_replica_id'},
234
+ 'history': {'collection', 'local_id', 'cursor'}}
235
+ provided = {k for k, v in {'destination': destination, 'plan_id': plan_id, 'manifest': manifest,
236
+ 'expected_sha256': expected_sha256, 'workspaces': workspaces, 'payloads': payloads,
237
+ 'authorization': authorization, 'native_evidence': native_evidence,
238
+ 'old_replica_id': old_replica_id, 'collection': collection,
239
+ 'local_id': local_id, 'cursor': cursor}.items() if v is not None}
240
+ if old_writer_stopped:
241
+ provided.add('old_writer_stopped')
242
+ if action not in allowed or provided - allowed[action]:
243
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Use only the arguments for this action; execution consumes the exact saved plan.')
244
+ if action == 'backup_plan':
245
+ return self._backup_plan(destination, workspaces or [], payloads or [])
246
+ if action == 'backup_execute':
247
+ return self._backup_execute(self._load_plan(plan_id, 'backup'))
248
+ if action == 'verify':
249
+ return self._verify(manifest, expected_sha256)
250
+ if action == 'restore_plan':
251
+ return self._restore_plan(manifest, destination, expected_sha256)
252
+ if action == 'restore_execute':
253
+ return self._restore_execute(self._load_plan(plan_id, 'restore'))
254
+ if action == 'status':
255
+ plan = self._load_plan(plan_id)
256
+ receipt = self._plan_path(plan_id).with_suffix('.receipt.json')
257
+ result = {'plan': plan, 'receipt': read_json(receipt)[0] if receipt.exists() else None,
258
+ 'effect_may_exist_without_receipt': not receipt.exists(), 'status_is_read_only': True}
259
+ if plan['kind'] == 'restore' and (Path(plan['destination']) / 'control' / '.taskcarry' / 'state.sqlite3').is_file():
260
+ value, _ = _manifest(plan['manifest'], plan['manifest_sha256'])
261
+ result['observed_effect'] = self._restore_effect(value, plan)
262
+ return result
263
+ if action in ('activation_plan', 'activate'):
264
+ return self._activation(action, plan_id, authorization, old_writer_stopped, native_evidence, old_replica_id)
265
+ if action == 'history':
266
+ self._require_store()
267
+ if type(limit) is not int or not 1 <= limit <= 100:
268
+ raise GovernanceError('RECOVERY_ARGUMENT', 'History page size must be 1-100.')
269
+ conditions, params = ['collection=?', 'key>?'], ['recovery_history', cursor or '']
270
+ for field, selected in (('original_collection', collection), ('original_key', local_id)):
271
+ if selected is not None:
272
+ conditions.append("json_extract(value,'$." + field + "')=?")
273
+ params.append(selected)
274
+ with self.store._connect(readonly=True) as db:
275
+ rows = db.execute('SELECT key,value FROM records WHERE ' + ' AND '.join(conditions)
276
+ + ' ORDER BY key LIMIT ?', [*params, limit + 1]).fetchall()
277
+ return {'items': [dict(json.loads(v), history_id=k) for k, v in rows[:limit]],
278
+ 'next_cursor': rows[limit - 1][0] if len(rows) > limit else None, 'read_only': True}
279
+ raise GovernanceError('RECOVERY_ACTION', 'Unknown project recovery action.')
280
+
281
+ def _backup_plan(self, destination, workspaces, payloads):
282
+ self._require_store()
283
+ if not destination:
284
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Select an independent local recovery directory.')
285
+ destination = normal(destination)
286
+ disjoint(destination, self.root)
287
+ if destination.exists() and (not destination.is_dir() or any(destination.iterdir())):
288
+ raise GovernanceError('RECOVERY_DESTINATION_NOT_EMPTY', 'Use an absent or empty recovery directory.')
289
+ registered = {w['name']: w for w in self.store.list('workspaces')}
290
+ components, names, roots = [], set(), []
291
+ for category, selections in (('workspaces', workspaces), ('payloads', payloads)):
292
+ for spec in selections:
293
+ name = _id(spec.get('name'), 'Recovery component')
294
+ if name.casefold() in names:
295
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Recovery component names must be unique.')
296
+ names.add(name.casefold())
297
+ raw = spec.get('path') or registered.get(name, {}).get('path')
298
+ if not raw:
299
+ raise GovernanceError('WORKSPACE_UNKNOWN', 'Select an explicit source or registered workspace.', {'name': name})
300
+ source = normal(raw)
301
+ if not source.is_dir():
302
+ raise GovernanceError('RECOVERY_SOURCE_MISSING', 'The selected source directory is unavailable.')
303
+ disjoint(destination, source)
304
+ if any(source == p for p in roots):
305
+ raise GovernanceError('RECOVERY_ARGUMENT', 'A source directory can have only one recovery component.')
306
+ roots.append(source)
307
+ kind = spec.get('kind', 'git' if category == 'workspaces' else 'files')
308
+ paths = spec.get('paths', [])
309
+ if kind not in ('git', 'files') or not isinstance(paths, list) or kind == 'files' and not paths:
310
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Plain payloads need exact file paths; Git components include tracked work by default.')
311
+ selected = rg.inventory(source, kind, paths, spec.get('refs'))
312
+ selected.update(name=name, target='control' if source == self.root else category + '/' + name,
313
+ selected_paths=paths, selected_refs=spec.get('refs'))
314
+ components.append(selected)
315
+ config = self.store.get('config', 'project')
316
+ missing_artifacts = self._missing_artifacts(self.store.list('artifacts'), components)
317
+ baseline = _baseline_recovery(self.store.get('settings', 'integration_baseline'), components, registered,
318
+ self.store.get('settings', 'integration_baseline_recovery'))
319
+ plan_id = 'backup-' + uuid.uuid4().hex
320
+ plan = {'schema': PLAN_SCHEMA, 'plan_id': plan_id, 'kind': 'backup', 'created_at': now(),
321
+ 'source_control': str(self.root), 'destination': str(destination), 'components': components,
322
+ 'project_id': config.get('project_id') or 'project-' + uuid.uuid4().hex,
323
+ 'legacy_identity_upgrade_on_restore': not bool(config.get('project_id')),
324
+ 'registered_workspaces': registered,
325
+ 'missing_workspace_payloads': sorted(set(registered) - {c['name'] for c in components}),
326
+ 'missing_artifact_payloads': missing_artifacts,
327
+ 'integration_baseline_recovery': baseline,
328
+ 'scope': 'One coherent state snapshot and referenced objects; separately stable selected source components, not a global transaction.',
329
+ 'exclusions': ['Unselected ordinary, ignored and external files; credentials and native host configuration.',
330
+ 'Filesystem ACLs, alternate streams, links, submodules, unsaved editor buffers and reflogs.',
331
+ 'Live schedules, installed runtime and any offsite transport or encryption.'],
332
+ 'state_capture_time': 'First execute seals one SQLite snapshot; retries reuse that snapshot and the original selected source batch.'}
333
+ write_json(self._plan_path(plan_id), plan)
334
+ return plan
335
+
336
+ @staticmethod
337
+ def _missing_artifacts(artifacts, components):
338
+ selected = {str(normal(Path(c['source']) / item['path'])): item.get('sha256')
339
+ for c in components for item in c['files'] if not item.get('missing')}
340
+ return [{'artifact_id': a['artifact_id'], 'path': a['path'], 'sha256': a['sha256'],
341
+ 'reason': 'Registered required artifact is outside the selected payload or its recorded bytes changed.'}
342
+ for a in artifacts if a.get('decision') not in ('ignore', 'dismiss', 'no_backup_needed')
343
+ and selected.get(str(normal(a['path']))) != a['sha256']]
344
+
345
+ def _state_capture(self, media, plan, scratch):
346
+ scratch.mkdir(parents=True, exist_ok=True)
347
+ snapshot = scratch / 'state.sqlite3'
348
+ # Freeze database pages under the cooperating writer lock, release before
349
+ # copying immutable objects or building Git bundles.
350
+ with self.store.guard(), self.store._connect(readonly=True) as db, closing(sqlite3.connect(snapshot)) as target:
351
+ db.backup(target)
352
+ rows = _state_rows(snapshot)
353
+ config = next(v for c, k, v in rows if (c, k) == ('config', 'project'))
354
+ if type(config.get('schema_version')) is not int or config['schema_version'] != 1:
355
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Cannot export an unsupported governance state.')
356
+ objects = {}
357
+ # Checkpoints and preservation use Core's object store. Artifact SHA
358
+ # values describe external files; they are not implicit copy requests.
359
+ for ref in _state_references(rows):
360
+ if not SHA.fullmatch(str(ref.get('sha256', ''))):
361
+ raise GovernanceError('RECOVERY_STATE_CORRUPT', 'Invalid state object identity.')
362
+ try:
363
+ data = read_file_bytes(normal(self.store.directory / 'objects' / ref['sha256']), MAX_BYTES)
364
+ except FileNotFoundError as exc:
365
+ raise GovernanceError('RECOVERY_OBJECT_MISSING', 'A referenced governance object is absent.', ref) from exc
366
+ if len(data) != ref['size'] or digest(data) != ref['sha256']:
367
+ raise GovernanceError('RECOVERY_OBJECT_MISMATCH', 'A referenced governance object has changed.', ref)
368
+ objects[ref['sha256']] = put(media, data)
369
+ return {'schema_version': 1, 'snapshot': put(media, read_file_bytes(snapshot, MAX_BYTES)),
370
+ 'objects': sorted(objects.values(), key=lambda x: x['sha256']), 'record_count': len(rows),
371
+ 'project_id': config.get('project_id') or plan['project_id'], 'old_replica_id': config.get('replica_id'),
372
+ 'source_aliases': config.get('source_aliases', []), 'captured_at': now(),
373
+ 'registered_workspaces': {v['name']: v for c, _, v in rows if c == 'workspaces'},
374
+ 'integration_baseline': next((v for c, k, v in rows if (c, k) == ('settings', 'integration_baseline')), None),
375
+ 'integration_baseline_recovery': next((v for c, k, v in rows if (c, k) == ('settings', 'integration_baseline_recovery')), None),
376
+ 'artifacts': [v for c, _, v in rows if c == 'artifacts'],
377
+ 'accepted_history_dependencies': [{'stage_id': k, 'baseline': v['accepted_baseline'], 'commit': v['accepted_commit']}
378
+ for c, k, v in rows if c == 'stages' and v.get('accepted_baseline') and v.get('accepted_commit')],
379
+ 'stage_history_dependencies': [{'stage_id': k, 'workspace': v.get('workspace'),
380
+ 'commits': sorted({v[x] for x in ('base', 'commit') if v.get(x)})}
381
+ for c, k, v in rows if c == 'stages']}
382
+
383
+ def _backup_execute(self, plan):
384
+ self._require_store()
385
+ if str(self.root) != plan['source_control']:
386
+ raise GovernanceError('RECOVERY_PLAN_MISMATCH', 'Backup source control differs from the saved plan.')
387
+ media = normal(plan['destination'])
388
+ disjoint(media, self.root)
389
+ media.mkdir(parents=True, exist_ok=True)
390
+ with lock(media / 'batch.lock'):
391
+ if not (media / 'intent.json').exists() and any(p.name != 'batch.lock' for p in media.iterdir()):
392
+ raise GovernanceError('RECOVERY_DESTINATION_CHANGED', 'Unowned files appeared at the selected backup destination; preserved for review.')
393
+ write_json(media / 'intent.json', plan)
394
+ manifest_path = media / 'manifest.json'
395
+ if manifest_path.exists():
396
+ verified = self._verify(str(manifest_path))
397
+ if verified['set_id'] != plan['plan_id']:
398
+ raise GovernanceError('RECOVERY_CONFLICT', 'Existing manifest belongs to another batch.')
399
+ if not verified['verified']:
400
+ raise GovernanceError('RECOVERY_VERIFY_FAILED', 'Existing recovery effects failed verification.', verified)
401
+ result = {'plan_id': plan['plan_id'], 'manifest': str(manifest_path),
402
+ 'manifest_sha256': verified['manifest_sha256'], 'state': 'COMPLETE',
403
+ 'reused_original_batch': True, 'verification': verified}
404
+ self._receipt(plan, result)
405
+ return result
406
+ sealed_state = media / 'state.capture.json'
407
+ if sealed_state.exists():
408
+ state, _ = read_json(sealed_state)
409
+ for ref in _refs([state['snapshot'], state['objects']]):
410
+ get(media, ref)
411
+ else:
412
+ state = self._state_capture(media, plan, media / ('scratch-' + uuid.uuid4().hex))
413
+ write_json(sealed_state, state)
414
+ if state.get('registered_workspaces') != plan['registered_workspaces']:
415
+ raise GovernanceError('RECOVERY_SOURCE_CHANGED', 'Workspace registration changed after planning; prepare a fresh recovery plan.')
416
+ components = []
417
+ for selected in plan['components']:
418
+ sealed = media / ('component-' + selected['name'] + '.json')
419
+ if sealed.exists():
420
+ component, _ = read_json(sealed)
421
+ comparison = copy.deepcopy(component)
422
+ comparison.pop('bundle', None)
423
+ for file in comparison['files']:
424
+ file.pop('object', None)
425
+ for item in comparison.get('git', {}).get('index', []):
426
+ item.pop('object', None)
427
+ planned = {k: v for k, v in selected.items() if k not in ('selected_paths', 'selected_refs')}
428
+ if comparison != planned:
429
+ raise GovernanceError('RECOVERY_CONFLICT', 'Sealed component no longer matches the original batch.')
430
+ for ref in _refs(component):
431
+ get(media, ref)
432
+ else:
433
+ component = rg.capture(media, selected, media / ('scratch-' + uuid.uuid4().hex))
434
+ write_json(sealed, component)
435
+ components.append(component)
436
+ missing_artifacts = self._missing_artifacts(state.get('artifacts', []), components)
437
+ baseline = _baseline_recovery(state.get('integration_baseline'), components, state['registered_workspaces'],
438
+ state.get('integration_baseline_recovery'))
439
+ missing_history, history_checks = [], {}
440
+ history_dependencies = list(state.get('stage_history_dependencies', []))
441
+ if baseline['status'] == 'MAPPED':
442
+ history_dependencies.extend({'stage_id': d['stage_id'], 'workspace': baseline['component'],
443
+ 'commits': [d['commit']], 'role': 'accepted_baseline'}
444
+ for d in state.get('accepted_history_dependencies', [])
445
+ if normal(d['baseline']) == normal(state['integration_baseline']['path']))
446
+ for dependency in history_dependencies:
447
+ component = next((c for c in components if c['name'] == dependency['workspace'] and c['kind'] == 'git'), None)
448
+ if component is None:
449
+ missing_history.append(dependency)
450
+ continue
451
+ if component['name'] not in history_checks:
452
+ check_root = media / ('history-check-' + uuid.uuid4().hex[:12])
453
+ check_root.mkdir()
454
+ rg.git(check_root, 'init', '--quiet', '--bare', '--object-format=' + component['git']['object_format'])
455
+ bundle = check_root / 'history.bundle'
456
+ atomic(bundle, get(media, component['bundle']))
457
+ rg.git(check_root, 'fetch', '--quiet', '--no-tags', str(bundle), 'HEAD',
458
+ *['+' + ref + ':' + ref for ref in component['git']['refs']])
459
+ history_checks[component['name']] = check_root
460
+ for commit in dependency['commits']:
461
+ # This only tests history containment in the selected roots,
462
+ # and never creates refs or expands the approved history scope.
463
+ found = rg.git(history_checks[component['name']], 'rev-parse', '--verify', commit + '^{commit}', check=False).decode('ascii').strip()
464
+ if found != commit:
465
+ missing_history.append({**dependency, 'commits': [commit]})
466
+ disabled_host = [{'component': c['name'], 'path': row['path'],
467
+ 'quarantine_path': c['target'] + '/' + rg.quarantine(row['path']),
468
+ 'sha256': row['sha256'], 'reason': 'Old native host bindings/schedules must not execute on a restored replica.'}
469
+ for c in components for row in c['files'] if rg.host_entry(row['path']) and not row.get('missing')]
470
+ value = {'schema': SCHEMA, 'set_id': plan['plan_id'], 'created_at': now(),
471
+ 'source_control': plan['source_control'], 'state': state, 'components': components,
472
+ 'registered_workspaces': plan['registered_workspaces'],
473
+ 'missing_workspace_payloads': plan['missing_workspace_payloads'],
474
+ 'missing_artifact_payloads': missing_artifacts, 'missing_history_dependencies': missing_history,
475
+ 'integration_baseline_recovery': baseline,
476
+ 'disabled_host_files': disabled_host,
477
+ 'runtime': {'core_version': __version__, 'python_minimum': '3.11', 'recovery_schema': 1,
478
+ 'git_required': any(c['kind'] == 'git' for c in components),
479
+ 'core_package_included': False},
480
+ 'dependencies': {'governance_state': ['state.snapshot', 'state.objects'],
481
+ 'workspace_bindings': [c['name'] for c in components],
482
+ 'core_package': 'Install a compatible trusted TaskCarry package separately; never execute a package from unknown backup media.'},
483
+ 'scope': plan['scope'], 'exclusions': plan['exclusions'],
484
+ 'automations_enabled': False, 'offsite_verified': False}
485
+ candidate_manifest = media / ('manifest-' + uuid.uuid4().hex[:12] + '.partial')
486
+ write_json(candidate_manifest, value)
487
+ verified = self._verify(str(candidate_manifest))
488
+ if not verified['verified']:
489
+ raise GovernanceError('RECOVERY_VERIFY_FAILED', 'Recovery publication has incomplete payloads.', verified)
490
+ write_json(manifest_path, value)
491
+ result = {'plan_id': plan['plan_id'], 'manifest': str(manifest_path),
492
+ 'manifest_sha256': verified['manifest_sha256'], 'state': 'COMPLETE',
493
+ 'reused_original_batch': False, 'verification': verified}
494
+ self._receipt(plan, result)
495
+ return result
496
+
497
+ def _receipt(self, plan, result):
498
+ path = self._plan_path(plan['plan_id']).with_suffix('.receipt.json')
499
+ if path.exists():
500
+ old, _ = read_json(path)
501
+ if old.get('manifest_sha256') != result.get('manifest_sha256') or old.get('state') != result.get('state'):
502
+ raise GovernanceError('RECOVERY_CONFLICT', 'Existing recovery receipt conflicts with observed effects.')
503
+ else:
504
+ write_json(path, result)
505
+
506
+ @staticmethod
507
+ def _verify(manifest, expected=None):
508
+ if not manifest:
509
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Select the recovery manifest file.')
510
+ path = normal(manifest)
511
+ value, checksum = _manifest(path, expected)
512
+ failures, seen = [], set()
513
+ for ref in _payload_refs(value):
514
+ if ref['sha256'] in seen:
515
+ continue
516
+ seen.add(ref['sha256'])
517
+ try:
518
+ get(path.parent, ref)
519
+ except (GovernanceError, OSError) as error:
520
+ failures.append({'sha256': ref['sha256'], 'code': getattr(error, 'code', type(error).__name__)})
521
+ state_verified = False
522
+ baseline = {'status': 'UNVERIFIED', 'component': None}
523
+ if not failures:
524
+ rows = _state_rows(safe(path.parent, 'objects/' + value['state']['snapshot']['sha256']))
525
+ config = next(v for c, k, v in rows if (c, k) == ('config', 'project'))
526
+ binding = next((v for c, k, v in rows if (c, k) == ('settings', 'integration_baseline')), None)
527
+ prior = next((v for c, k, v in rows if (c, k) == ('settings', 'integration_baseline_recovery')), None)
528
+ baseline = _baseline_recovery(binding, value['components'], {v['name']: v for c, _, v in rows if c == 'workspaces'}, prior)
529
+ if value.get('integration_baseline_recovery', baseline) != baseline:
530
+ raise GovernanceError('RECOVERY_MANIFEST', 'The baseline recovery declaration differs from the actual governance snapshot.')
531
+ if config.get('project_id') and config['project_id'] != value['state']['project_id']:
532
+ raise GovernanceError('RECOVERY_MANIFEST', 'The manifest project identity differs from the actual state snapshot.')
533
+ declared = {r['sha256']: r['size'] for r in value['state']['objects']}
534
+ for ref in _state_references(rows):
535
+ if declared.get(ref['sha256']) != ref['size']:
536
+ failures.append({'sha256': ref['sha256'], 'code': 'RECOVERY_STATE_REFERENCE_MISSING'})
537
+ state_verified = not failures
538
+ return {'verified': not failures, 'set_id': value['set_id'], 'manifest_sha256': checksum,
539
+ 'trusted_digest_supplied': expected is not None, 'objects': len(seen), 'failures': failures,
540
+ 'missing_workspace_payloads': value.get('missing_workspace_payloads', []),
541
+ 'missing_artifact_payloads': value.get('missing_artifact_payloads', []),
542
+ 'missing_history_dependencies': value.get('missing_history_dependencies', []),
543
+ 'integration_baseline_recovery': baseline,
544
+ 'disabled_host_files': value.get('disabled_host_files', []),
545
+ 'runtime': value['runtime'], 'exclusions': value['exclusions'], 'offsite_verified': False,
546
+ 'state_references_verified': state_verified,
547
+ 'complete_scope': not failures and _complete_scope(value, baseline),
548
+ 'restore_tested': False, 'writer_activated': False}
549
+
550
+ def _restore_plan(self, manifest, destination, expected):
551
+ verified = self._verify(manifest, expected)
552
+ if not verified['verified']:
553
+ raise GovernanceError('RECOVERY_VERIFY_FAILED', 'Required recovery objects are unavailable.', verified)
554
+ value, checksum = _manifest(normal(manifest), verified['manifest_sha256'])
555
+ if not destination:
556
+ raise GovernanceError('RECOVERY_ARGUMENT', 'Select an independent absent or empty restore destination.')
557
+ target = normal(destination)
558
+ disjoint(target, normal(manifest).parent)
559
+ disjoint(target, self.root)
560
+ for source in [value['source_control'], *[c['source'] for c in value['components']]]:
561
+ disjoint(target, source)
562
+ if target.exists() and (not target.is_dir() or any(target.iterdir())):
563
+ raise GovernanceError('RECOVERY_DESTINATION_NOT_EMPTY', 'Restore cannot replace an existing project.')
564
+ plan_id = 'restore-' + uuid.uuid4().hex
565
+ plan = {'schema': PLAN_SCHEMA, 'kind': 'restore', 'plan_id': plan_id, 'created_at': now(),
566
+ 'manifest': str(normal(manifest)), 'manifest_sha256': checksum, 'destination': str(target),
567
+ 'source_set_id': value['set_id'], 'replica_id': 'replica-' + uuid.uuid4().hex,
568
+ 'project_id': value['state']['project_id'], 'old_replica_id': value['state'].get('old_replica_id'),
569
+ 'bindings': [{'name': c['name'], 'source': c['source'], 'target': str(safe(target, c['target']))} for c in value['components']],
570
+ 'control': str(target / 'control'), 'writer_state': 'standby',
571
+ 'missing_workspace_payloads': value.get('missing_workspace_payloads', []),
572
+ 'missing_artifact_payloads': value.get('missing_artifact_payloads', []),
573
+ 'missing_history_dependencies': value.get('missing_history_dependencies', []),
574
+ 'integration_baseline_recovery': verified['integration_baseline_recovery'],
575
+ 'disabled_host_files': value.get('disabled_host_files', []),
576
+ 'next_step': 'Execute the exact plan, reconnect this standby copy in a native host, then explicitly review writer handoff.'}
577
+ write_json(self._plan_path(plan_id), plan)
578
+ return plan
579
+
580
+ def _restore_state(self, media, value, plan, build):
581
+ root = build / 'control'
582
+ root.mkdir(parents=True, exist_ok=True)
583
+ directory = root / '.taskcarry'
584
+ directory.mkdir()
585
+ atomic(directory / 'state.sqlite3', get(media, value['state']['snapshot']))
586
+ for ref in value['state']['objects']:
587
+ atomic(directory / 'objects' / ref['sha256'], get(media, ref))
588
+ store = Store(root)
589
+ with store.recovery_transition(), store.transaction(), store._connect() as db:
590
+ rows = [(c, k, json.loads(v)) for c, k, v in db.execute('SELECT collection,key,value FROM records').fetchall()]
591
+ config = store.get('config', 'project')
592
+ old_config = copy.deepcopy(config)
593
+ from .identification import source
594
+ old_alias = source(value['source_control'])['source_id']
595
+ aliases = [*config.get('source_aliases', []), old_alias]
596
+ if config.get('replica_id'):
597
+ aliases.append(config['replica_id'])
598
+ inert = set(config.get('recovery_inert_plan_ids', []))
599
+ inert_cycles = set(config.get('recovery_inert_cycle_ids', []))
600
+ inert_runs = set(config.get('recovery_inert_run_ids', []))
601
+ plan_collections = {'plans', 'preservation', 'connection_plans', 'identity_plans', 'workbench_plans'}
602
+ runtime_collections = {'governance_cycles', 'cycle_reservations', 'cycle_requests', 'runs',
603
+ 'scan_sources', 'source_scans', 'operations'}
604
+ for collection, key, record in rows:
605
+ # Full original historical object is retained before changing a
606
+ # current projection or removing an executable plan locator.
607
+ if (collection in plan_collections | runtime_collections
608
+ or isinstance(record, dict) and record.get('plan_id') and collection not in ('stages', 'recovery_history')):
609
+ if record.get('plan_id') or collection in plan_collections:
610
+ inert.add(record.get('plan_id', key))
611
+ if collection == 'governance_cycles':
612
+ inert_cycles.add(record.get('cycle_id', key))
613
+ if collection == 'runs':
614
+ inert_runs.add(record.get('run_id', key))
615
+ _archive(store, plan['plan_id'], collection, key, record)
616
+ if collection == 'operations':
617
+ store.put(collection, key, {**record, 'historical_status': record.get('status'),
618
+ 'status': 'SUPERSEDED', 'recovery_inert': True})
619
+ else:
620
+ db.execute('DELETE FROM records WHERE collection=? AND key=?', (collection, key))
621
+ components = {c['name']: c for c in value['components']}
622
+ old_binding = store.get('settings', 'integration_baseline')
623
+ old_recovery_binding = store.get('settings', 'integration_baseline_recovery')
624
+ baseline = _baseline_recovery(old_binding, value['components'],
625
+ {v['name']: v for c, _, v in rows if c == 'workspaces'}, old_recovery_binding)
626
+ if old_binding:
627
+ _archive(store, plan['plan_id'], 'settings', 'integration_baseline', old_binding)
628
+ if old_recovery_binding:
629
+ _archive(store, plan['plan_id'], 'settings', 'integration_baseline_recovery', old_recovery_binding)
630
+ if baseline['status'] == 'MAPPED':
631
+ component = components[baseline['component']]
632
+ target = safe(Path(plan['destination']), component['target'])
633
+ rebound = {'path': str(target), 'common_dir': str(target / '.git'), 'branch': component['git']['branch']}
634
+ store.put('settings', 'integration_baseline', rebound)
635
+ store.put('settings', 'integration_baseline_recovery',
636
+ {**baseline, 'status': 'REBOUND', 'restore_id': plan['plan_id'], 'identity': rebound})
637
+ for stage in store.list('stages'):
638
+ if (stage.get('accepted_baseline') and normal(stage['accepted_baseline']) == normal(old_binding['path'])
639
+ and stage.get('accepted_commit')):
640
+ # Only current projections move. Original acceptance,
641
+ # including its exact old path, remains queryable history.
642
+ found = rg.git(safe(build, component['target']), 'rev-parse', '--verify',
643
+ stage['accepted_commit'] + '^{commit}', check=False).decode('ascii').strip()
644
+ if found == stage['accepted_commit']:
645
+ _archive(store, plan['plan_id'], 'stages', stage['stage_id'], stage)
646
+ store.put('stages', stage['stage_id'],
647
+ {**stage, 'accepted_baseline': str(target),
648
+ 'recovery_original_accepted_baseline': stage['accepted_baseline']})
649
+ elif baseline['status'] == 'REBIND_REQUIRED':
650
+ db.execute("DELETE FROM records WHERE collection='settings' AND key='integration_baseline'")
651
+ store.put('settings', 'integration_baseline_recovery',
652
+ {**baseline, 'restore_id': plan['plan_id'],
653
+ 'next_step': 'Prepare a complete recovery set containing the original registered baseline and restore it to an independent destination.'})
654
+ for workspace in store.list('workspaces'):
655
+ name = workspace['name']
656
+ component = components.get(name)
657
+ target = safe(Path(plan['destination']), component['target'] if component else 'workspaces/' + _id(name, 'Workspace'))
658
+ archived = copy.deepcopy(workspace)
659
+ _archive(store, plan['plan_id'], 'workspaces', name, archived)
660
+ workspace.update(path=str(target), recovery_original_path=archived['path'],
661
+ recovery_available=component is not None,
662
+ identity={'path': str(target), 'common_dir': str(target / '.git'),
663
+ 'branch': component.get('git', {}).get('branch') if component else None})
664
+ store.put('workspaces', name, workspace)
665
+ path_bindings = {str(normal(Path(c['source']) / item['path'])): str(safe(Path(plan['destination']), c['target'] + '/' + item['path']))
666
+ for c in value['components'] for item in c['files'] if not item.get('missing')}
667
+ for artifact in store.list('artifacts'):
668
+ old = copy.deepcopy(artifact)
669
+ _archive(store, plan['plan_id'], 'artifacts', artifact['artifact_id'], old)
670
+ artifact.update(path=path_bindings.get(str(normal(artifact['path'])), str(Path(plan['destination']) / 'unavailable' / artifact['artifact_id'])),
671
+ recovery_original_path=old['path'], recovery_available=str(normal(old['path'])) in path_bindings,
672
+ backup=None, backup_verified=False, backup_available=False)
673
+ store.put('artifacts', artifact['artifact_id'], artifact)
674
+ config.update(project_id=plan['project_id'], replica_id=plan['replica_id'],
675
+ source_aliases=list(dict.fromkeys(aliases)), recovery_writer_state='standby',
676
+ recovery_restore_id=plan['plan_id'], recovery_inert_plan_ids=sorted(inert),
677
+ recovery_inert_cycle_ids=sorted(inert_cycles), recovery_inert_run_ids=sorted(inert_runs),
678
+ recovery_old_replica_id=value['state'].get('old_replica_id'),
679
+ recovery_automation_state='disabled_pending_native_reconfiguration',
680
+ recovery_source_control=value['source_control'], recovery_manifest_sha256=plan['manifest_sha256'])
681
+ _archive(store, plan['plan_id'], 'config', 'project', old_config)
682
+ store.put('config', 'project', config)
683
+ store.put('recovery_restores', plan['plan_id'], {'restore_id': plan['plan_id'], 'manifest_sha256': plan['manifest_sha256'],
684
+ 'destination': plan['destination'], 'replica_id': plan['replica_id'],
685
+ 'writer_state': 'standby', 'created_at': now()})
686
+ store.event('project_restored_standby', {'restore_id': plan['plan_id'], 'project_id': plan['project_id'],
687
+ 'replica_id': plan['replica_id'], 'old_plans_disabled': sorted(inert)})
688
+ with store.recovery_transition():
689
+ store.upgrade()
690
+ return store
691
+
692
+ def _restore_effect(self, value, plan, *, location=None, expected_state=None):
693
+ target = normal(location or plan['destination'])
694
+ control = Core(target / 'control')
695
+ config = control.store.get('config', 'project')
696
+ if (config.get('recovery_restore_id') != plan['plan_id'] or config.get('replica_id') != plan['replica_id']
697
+ or config.get('project_id') != plan['project_id'] or config.get('recovery_manifest_sha256') != plan['manifest_sha256']):
698
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'Restored governance identity does not match the plan.')
699
+ if config.get('recovery_writer_state') == 'active':
700
+ return {'control': str(target / 'control'), 'project_id': plan['project_id'], 'replica_id': plan['replica_id'],
701
+ 'writer_state': 'active', 'state_advanced': True, 'state_verified': False,
702
+ 'git_verified': False, 'replay_permitted': False,
703
+ 'meaning': 'A separately activated replica may have new work; historical restore verification is not a current snapshot.'}
704
+ if expected_state is None:
705
+ prepared, _ = read_json(self._plan_path(plan['plan_id']).with_suffix('.prepared.json'))
706
+ expected_state = prepared['state_fingerprint']
707
+ fingerprint = _state_fingerprint(control.store)
708
+ if fingerprint != expected_state:
709
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'Restored governance records or events changed; preserved without replay.')
710
+ for component in value['components']:
711
+ rg.verify_effect(component, safe(target, component['target']))
712
+ for ref in value['state']['objects']:
713
+ data = read_file_bytes(control.store.directory / 'objects' / ref['sha256'], MAX_BYTES)
714
+ if len(data) != ref['size'] or digest(data) != ref['sha256']:
715
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'Restored governance object differs.')
716
+ return {'control': str(target / 'control'), 'project_id': plan['project_id'], 'replica_id': plan['replica_id'],
717
+ 'writer_state': config.get('recovery_writer_state'), 'workspaces_verified': len(value['components']),
718
+ 'state_objects_verified': len(value['state']['objects']), 'state_verified': True,
719
+ 'state_fingerprint': fingerprint, 'git_verified': True,
720
+ 'complete_scope': _complete_scope(value, plan['integration_baseline_recovery']),
721
+ 'integration_baseline_recovery': control.store.get('settings', 'integration_baseline_recovery') or plan['integration_baseline_recovery'],
722
+ 'disabled_host_files': value.get('disabled_host_files', [])}
723
+
724
+ def _restore_execute(self, plan):
725
+ value, checksum = _manifest(plan['manifest'], plan['manifest_sha256'])
726
+ verified = self._verify(plan['manifest'], checksum)
727
+ if not verified['verified']:
728
+ raise GovernanceError('RECOVERY_VERIFY_FAILED', 'Recovery input changed or became unavailable.', verified)
729
+ target = normal(plan['destination'])
730
+ with lock(self._plan_path(plan['plan_id']).with_suffix('.lock')):
731
+ if target.exists() and any(target.iterdir()):
732
+ effect = self._restore_effect(value, plan)
733
+ if effect.get('state_advanced'):
734
+ return {'plan_id': plan['plan_id'], 'state': 'ADVANCED_NO_REPLAY', 'manifest_sha256': checksum,
735
+ 'effect': effect, 'old_plans_replayed': False}
736
+ result = {'plan_id': plan['plan_id'], 'state': 'RESTORED_STANDBY', 'manifest_sha256': checksum,
737
+ 'effect': effect, 'recovered_existing_effect': True, 'old_plans_replayed': False,
738
+ 'native_host_verified': False, 'writer_activated': False}
739
+ self._receipt(plan, result)
740
+ return result
741
+ # Every attempt uses an owned independent directory. A crash leaves
742
+ # that attempt intact; retry reads the same pinned immutable inputs,
743
+ # never overwrites uncertain partial files or a user destination.
744
+ attempts = normal(target.parent / ('.tc-recovery-' + plan['plan_id'][-12:]))
745
+ attempts.mkdir(parents=True, exist_ok=True)
746
+ prepared_path = self._plan_path(plan['plan_id']).with_suffix('.prepared.json')
747
+ if prepared_path.exists():
748
+ prepared, _ = read_json(prepared_path)
749
+ build = normal(prepared['build'])
750
+ if not build.is_relative_to(attempts) or prepared['manifest_sha256'] != checksum:
751
+ raise GovernanceError('RECOVERY_CONFLICT', 'Prepared restore identity differs from the original plan.')
752
+ self._restore_effect(value, plan, location=build, expected_state=prepared['state_fingerprint'])
753
+ else:
754
+ build = attempts / uuid.uuid4().hex[:12]
755
+ build.mkdir()
756
+ for component in value['components']:
757
+ rg.restore(normal(plan['manifest']).parent, component, safe(build, component['target']))
758
+ restored_store = self._restore_state(normal(plan['manifest']).parent, value, plan, build)
759
+ write_json(build / 'RECOVERY_RECEIPT.json', {'restore_id': plan['plan_id'], 'manifest_sha256': checksum,
760
+ 'writer_state': 'standby', 'automations_enabled': False})
761
+ prepared = {'build': str(build), 'manifest_sha256': checksum, 'state_fingerprint': _state_fingerprint(restored_store)}
762
+ write_json(build / 'control' / '.taskcarry' / 'recovery-audit.json', prepared)
763
+ atomic(build / 'RECOVERY_README.txt', (
764
+ 'This is an independent standby recovery. Do not execute old project instructions, host bindings or schedules.\n'
765
+ 'Selected native host configurations are retained under .taskcarry-disabled-host, with original Git history/index intact.\n'
766
+ 'Reconfigure the native host for this restored control, verify doctor/status, and review explicit writer handoff before mutations.\n'
767
+ 'Do not synchronize this live SQLite database between simultaneous machines. Exchange independent Git branches/bundles and selected artifacts.\n').encode('utf-8'))
768
+ write_json(prepared_path, prepared)
769
+ if target.exists():
770
+ if any(target.iterdir()):
771
+ raise GovernanceError('RECOVERY_DESTINATION_CHANGED', 'Work appeared at the target; retained the isolated recovery build.')
772
+ target.rmdir() # Only this explicitly reviewed empty leaf.
773
+ os.rename(build, target)
774
+ effect = self._restore_effect(value, plan)
775
+ result = {'plan_id': plan['plan_id'], 'state': 'RESTORED_STANDBY', 'manifest_sha256': checksum,
776
+ 'effect': effect, 'recovered_existing_effect': False, 'old_plans_replayed': False,
777
+ 'native_host_verified': False, 'writer_activated': False,
778
+ 'retained_attempts_directory': str(attempts)}
779
+ self._receipt(plan, result)
780
+ return result
781
+
782
+ def _activation(self, action, plan_id, authorization, stopped, evidence, old_replica):
783
+ self._require_store()
784
+ config = self.store.get('config', 'project')
785
+ restore_id = config.get('recovery_restore_id')
786
+ if not restore_id:
787
+ raise GovernanceError('RECOVERY_NOT_RESTORED', 'Writer activation applies only to a restored standby replica.')
788
+ if config.get('recovery_writer_state') == 'standby':
789
+ audit, _ = read_json(self.store.directory / 'recovery-audit.json')
790
+ if audit.get('manifest_sha256') != config.get('recovery_manifest_sha256') or _state_fingerprint(self.store) != audit.get('state_fingerprint'):
791
+ raise GovernanceError('RECOVERY_EFFECT_CHANGED', 'The restored state changed before writer activation; inspect it first.')
792
+ if action == 'activation_plan':
793
+ activation = {'schema': PLAN_SCHEMA, 'kind': 'activation', 'plan_id': 'activate-' + uuid.uuid4().hex,
794
+ 'restore_id': restore_id, 'project_id': config['project_id'], 'replica_id': config['replica_id'],
795
+ 'old_replica_id': config.get('recovery_old_replica_id'), 'control': str(self.root),
796
+ 'required': ['Explicit authorization', 'Old writer stopped declaration for the exact old replica',
797
+ 'Native doctor/status evidence bound to this restored control and replica'],
798
+ 'limitations': 'The engine cannot fence or independently observe a remote old writer. Supplied native evidence is a caller attestation.',
799
+ 'automations_remain_disabled': True}
800
+ write_json(self._plan_path(activation['plan_id']), activation)
801
+ return activation
802
+ plan = self._load_plan(plan_id, 'activation')
803
+ if any(plan[key] != config.get(key) for key in ('project_id', 'replica_id')) or plan['restore_id'] != restore_id:
804
+ raise GovernanceError('RECOVERY_PLAN_MISMATCH', 'Activation identity changed after planning.')
805
+ if not isinstance(authorization, str) or not authorization.strip() or stopped is not True or old_replica != plan['old_replica_id']:
806
+ raise GovernanceError('RECOVERY_HANDOFF_REQUIRED', 'Explicit authorization and an exact old-writer-stopped declaration are required.')
807
+ if (not isinstance(evidence, dict) or evidence.get('source_id') != config['project_id']
808
+ or evidence.get('replica_id') != config['replica_id'] or evidence.get('control') != str(self.root)
809
+ or evidence.get('doctor') is not True or evidence.get('status') is not True or not evidence.get('evidence_ref')):
810
+ raise GovernanceError('RECOVERY_NATIVE_EVIDENCE_REQUIRED', 'Provide native host doctor/status evidence bound to this exact restored replica.')
811
+ receipt = {'plan_id': plan_id, 'restore_id': restore_id, 'project_id': config['project_id'],
812
+ 'replica_id': config['replica_id'], 'old_replica_id': old_replica, 'old_writer_stopped_declared': True,
813
+ 'authorization': authorization, 'native_evidence': evidence, 'native_evidence_independently_verified': False,
814
+ 'old_writer_remotely_fenced': False, 'writer_activated': True, 'automations_enabled': False}
815
+ with self.store.recovery_transition(), self.store.transaction():
816
+ previous = self.store.get('recovery_activations', plan_id)
817
+ if previous is not None and previous != receipt:
818
+ raise GovernanceError('RECOVERY_CONFLICT', 'Activation receipt differs; review the existing handoff.')
819
+ if previous is None:
820
+ config['recovery_writer_state'] = 'active'
821
+ self.store.put('config', 'project', config)
822
+ self.store.put('recovery_activations', plan_id, receipt)
823
+ self.store.event('recovery_writer_activated', {'plan_id': plan_id, 'replica_id': config['replica_id']})
824
+ return receipt