taskcarry 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- taskcarry/__init__.py +3 -0
- taskcarry/__main__.py +4 -0
- taskcarry/adapter_contracts.py +166 -0
- taskcarry/agy_turns.py +282 -0
- taskcarry/api.py +111 -0
- taskcarry/board.py +313 -0
- taskcarry/board_assets/board.css +1087 -0
- taskcarry/board_assets/board.js +1187 -0
- taskcarry/board_assets/browse.js +214 -0
- taskcarry/board_assets/index.html +43 -0
- taskcarry/board_assets/taskcarry-icon.ico +0 -0
- taskcarry/board_assets/taskcarry-mark.svg +28 -0
- taskcarry/board_data.py +466 -0
- taskcarry/chat_joins.py +157 -0
- taskcarry/cli.py +119 -0
- taskcarry/codex_capture.py +184 -0
- taskcarry/codex_host.py +293 -0
- taskcarry/collaboration_exchange.py +316 -0
- taskcarry/connection.py +159 -0
- taskcarry/continuity.py +300 -0
- taskcarry/contracts.py +165 -0
- taskcarry/conversation_capture.py +669 -0
- taskcarry/core.py +896 -0
- taskcarry/cycle_contracts.py +73 -0
- taskcarry/discovery.py +434 -0
- taskcarry/discovery_contracts.py +52 -0
- taskcarry/exchange_contracts.py +67 -0
- taskcarry/exchange_endpoint.py +377 -0
- taskcarry/exchange_packets.py +142 -0
- taskcarry/experience_contracts.py +129 -0
- taskcarry/experience_exchange.py +214 -0
- taskcarry/experience_notes.py +433 -0
- taskcarry/experience_storage.py +125 -0
- taskcarry/experience_tools.py +26 -0
- taskcarry/feishu/__init__.py +1 -0
- taskcarry/feishu/display.py +122 -0
- taskcarry/feishu/project_watch.py +145 -0
- taskcarry/feishu/review_sets.py +80 -0
- taskcarry/feishu/sender.py +42 -0
- taskcarry/feishu/subscription.py +193 -0
- taskcarry/feishu/windows_agent.py +287 -0
- taskcarry/feishu/windows_secret.py +34 -0
- taskcarry/gitops.py +170 -0
- taskcarry/governance.py +88 -0
- taskcarry/governance_cycle.py +775 -0
- taskcarry/identification.py +82 -0
- taskcarry/integration.py +663 -0
- taskcarry/maintenance.py +118 -0
- taskcarry/mcp.py +183 -0
- taskcarry/member_join.py +184 -0
- taskcarry/member_routing.py +145 -0
- taskcarry/onboarding.py +272 -0
- taskcarry/onboarding_complete.py +252 -0
- taskcarry/path_batches.py +19 -0
- taskcarry/preservation.py +257 -0
- taskcarry/project_collaboration.py +453 -0
- taskcarry/project_history.py +166 -0
- taskcarry/project_identity.py +51 -0
- taskcarry/project_recovery.py +824 -0
- taskcarry/recovery_contracts.py +25 -0
- taskcarry/recovery_files.py +153 -0
- taskcarry/recovery_git.py +234 -0
- taskcarry/remote_capture.py +89 -0
- taskcarry/remote_transfer.py +356 -0
- taskcarry/role_connection.py +215 -0
- taskcarry/setup.py +597 -0
- taskcarry/shared_workbench.py +480 -0
- taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
- taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
- taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
- taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
- taskcarry/source_review_set.py +80 -0
- taskcarry/state_format.py +47 -0
- taskcarry/store.py +472 -0
- taskcarry/task_context.py +141 -0
- taskcarry/text_handback.py +98 -0
- taskcarry/transfer_contracts.py +18 -0
- taskcarry/updates.py +351 -0
- taskcarry/workbench.py +625 -0
- taskcarry/workbench_contracts.py +32 -0
- taskcarry/workbuddy_capture.py +451 -0
- taskcarry/workbuddy_setup.py +212 -0
- taskcarry/worker_channel.py +859 -0
- taskcarry/worker_contracts.py +190 -0
- taskcarry/worker_storage.py +60 -0
- taskcarry/worker_tools.py +111 -0
- taskcarry-0.3.2.dist-info/METADATA +203 -0
- taskcarry-0.3.2.dist-info/RECORD +105 -0
- taskcarry-0.3.2.dist-info/WHEEL +5 -0
- taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
- taskcarry-0.3.2.dist-info/top_level.txt +2 -0
- taskcarry_https/__init__.py +1 -0
- taskcarry_https/consent.py +207 -0
- taskcarry_https/reader.py +132 -0
- taskcarry_https/review.py +116 -0
- taskcarry_https/server.py +163 -0
- taskcarry_https/team.py +335 -0
- taskcarry_https/team_host.py +109 -0
- taskcarry_https/web_host.py +82 -0
taskcarry/core.py
ADDED
|
@@ -0,0 +1,896 @@
|
|
|
1
|
+
"""Project-local task memory, exact checkpoints and conditional experience.
|
|
2
|
+
|
|
3
|
+
Records describe saved evidence, never business acceptance or model internals.
|
|
4
|
+
"""
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import base64
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path, PurePosixPath, PureWindowsPath
|
|
12
|
+
import re
|
|
13
|
+
import stat
|
|
14
|
+
import subprocess
|
|
15
|
+
import uuid
|
|
16
|
+
|
|
17
|
+
from .store import Store, GovernanceError, now, TERMINAL_STATES
|
|
18
|
+
from .path_batches import path_batches
|
|
19
|
+
|
|
20
|
+
MAX_FILE_BYTES = 32 * 1024 * 1024
|
|
21
|
+
MAX_CHECKPOINT_BYTES = 128 * 1024 * 1024
|
|
22
|
+
MAX_PATHS = 500
|
|
23
|
+
CURRENT_COLLECTIONS = ('tasks', 'stages', 'operations', 'workspaces', 'artifacts', 'checkpoints')
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def digest_bytes(data):
|
|
27
|
+
return hashlib.sha256(data).hexdigest()
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _linked(path):
|
|
31
|
+
if path.is_symlink():
|
|
32
|
+
return True
|
|
33
|
+
try:
|
|
34
|
+
return bool(getattr(path.lstat(), 'st_file_attributes', 0) & 0x400)
|
|
35
|
+
except FileNotFoundError:
|
|
36
|
+
return False
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def validate_relative_path(root, value, allow_missing=True):
|
|
40
|
+
if not isinstance(value, str) or not value or '\x00' in value or '\\' in value:
|
|
41
|
+
raise GovernanceError('UNSAFE_PATH', 'Use an explicit relative path with forward slashes.')
|
|
42
|
+
relative = PurePosixPath(value)
|
|
43
|
+
if relative.is_absolute() or PureWindowsPath(value).drive or any(p in ('..', '.') for p in value.split('/')):
|
|
44
|
+
raise GovernanceError('UNSAFE_PATH', 'Absolute paths and parent traversal are not allowed.')
|
|
45
|
+
for part in relative.parts:
|
|
46
|
+
low = part.casefold()
|
|
47
|
+
if re.fullmatch(r'(con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?', low):
|
|
48
|
+
raise GovernanceError('UNSAFE_PATH', 'Reserved device filenames are not portable file paths.')
|
|
49
|
+
if low in ('.git', '.taskcarry') or ':' in part or part.endswith((' ', '.')):
|
|
50
|
+
raise GovernanceError('RESERVED_PATH', 'Repository and governance metadata cannot be captured.')
|
|
51
|
+
if (low in ('.env', 'credentials', 'credentials.json', 'id_rsa', 'id_ed25519')
|
|
52
|
+
or low.startswith('.env.') and low not in ('.env.example', '.env.sample', '.env.template')
|
|
53
|
+
or low.endswith(('.pfx', '.p12', '.key', '.pem'))):
|
|
54
|
+
raise GovernanceError('SECRET_PATH', 'This filename may contain credentials; it is excluded by default.')
|
|
55
|
+
root = Path(root).resolve()
|
|
56
|
+
candidate = root.joinpath(*relative.parts)
|
|
57
|
+
check = root
|
|
58
|
+
for part in relative.parts:
|
|
59
|
+
check = check / part
|
|
60
|
+
if _linked(check):
|
|
61
|
+
raise GovernanceError('SYMLINK_PATH', 'Symbolic links and junctions cannot be captured.')
|
|
62
|
+
if not candidate.resolve().is_relative_to(root):
|
|
63
|
+
raise GovernanceError('UNSAFE_PATH', 'The path resolves outside its workspace.')
|
|
64
|
+
if candidate.exists() and not candidate.is_file():
|
|
65
|
+
raise GovernanceError('NOT_FILE', 'Checkpoint paths must name individual regular files.')
|
|
66
|
+
if not allow_missing and not candidate.is_file():
|
|
67
|
+
raise GovernanceError('MISSING_FILE', 'The requested file does not exist.', {'path': value})
|
|
68
|
+
return candidate
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def read_file_bytes(path, max_bytes=MAX_FILE_BYTES):
|
|
72
|
+
path = Path(path)
|
|
73
|
+
if _linked(path):
|
|
74
|
+
raise GovernanceError('SYMLINK_PATH', 'Symbolic links and junctions are not supported.')
|
|
75
|
+
before = path.stat()
|
|
76
|
+
if not stat.S_ISREG(before.st_mode):
|
|
77
|
+
raise GovernanceError('NOT_FILE', 'Only regular files can be read.')
|
|
78
|
+
if before.st_size > max_bytes:
|
|
79
|
+
raise GovernanceError('FILE_TOO_LARGE', 'Use an artifact reference for files exceeding the snapshot limit.')
|
|
80
|
+
with path.open('rb') as stream:
|
|
81
|
+
content = stream.read(max_bytes + 1)
|
|
82
|
+
after = path.stat()
|
|
83
|
+
if len(content) > max_bytes or (before.st_size, before.st_mtime_ns, before.st_ino) != (after.st_size, after.st_mtime_ns, after.st_ino):
|
|
84
|
+
raise GovernanceError('SOURCE_CHANGED', 'The file changed during capture; no checkpoint was published.')
|
|
85
|
+
return content
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def git(root, *args, input_bytes=None, check=True):
|
|
89
|
+
environment = os.environ.copy()
|
|
90
|
+
for key in list(environment):
|
|
91
|
+
if key.startswith('GIT_'):
|
|
92
|
+
environment.pop(key)
|
|
93
|
+
environment.update(GIT_TERMINAL_PROMPT='0', GIT_OPTIONAL_LOCKS='0', GIT_CONFIG_NOSYSTEM='1')
|
|
94
|
+
try:
|
|
95
|
+
result = subprocess.run(['git', '--literal-pathspecs', '-c', 'core.hooksPath=' + os.devnull, '-c', 'core.autocrlf=false', '-c', 'commit.gpgSign=false', '-C', str(root), *args],
|
|
96
|
+
input=input_bytes, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
97
|
+
env=environment, timeout=60, check=False)
|
|
98
|
+
except FileNotFoundError as exc:
|
|
99
|
+
raise GovernanceError('GIT_UNAVAILABLE', 'Git is required for this operation.') from exc
|
|
100
|
+
except subprocess.TimeoutExpired as exc:
|
|
101
|
+
raise GovernanceError('GIT_TIMEOUT', 'The bounded Git operation timed out.') from exc
|
|
102
|
+
if check and result.returncode:
|
|
103
|
+
raise GovernanceError('GIT_ERROR', 'Git could not complete the operation.',
|
|
104
|
+
{'command': args[0] if args else '', 'stderr': result.stderr.decode('utf-8', 'replace')[:2000]})
|
|
105
|
+
return result
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _id(value, label):
|
|
109
|
+
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,99}', value):
|
|
110
|
+
raise GovernanceError('INVALID_ID', f'{label} must be 1-100 ASCII letters, digits, dots, underscores or hyphens.')
|
|
111
|
+
return value
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _checkpoint_uses_git(workspace):
|
|
115
|
+
"""Plain files need no Git; repository-shaped paths require verification.
|
|
116
|
+
|
|
117
|
+
Inspect ancestors as well as the selected directory so a missing or broken
|
|
118
|
+
Git executable cannot silently discard a repository's HEAD/index layers.
|
|
119
|
+
lstat preserves dangling markers and propagates unreadable metadata instead
|
|
120
|
+
of treating either as proof that this is a plain directory.
|
|
121
|
+
"""
|
|
122
|
+
def present(path):
|
|
123
|
+
try:
|
|
124
|
+
path.lstat()
|
|
125
|
+
except FileNotFoundError:
|
|
126
|
+
return False
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
for parent in (workspace, *workspace.parents):
|
|
131
|
+
if present(parent / '.git'):
|
|
132
|
+
break
|
|
133
|
+
head = present(parent / 'HEAD')
|
|
134
|
+
objects = present(parent / 'objects')
|
|
135
|
+
refs = present(parent / 'refs') or present(parent / 'packed-refs')
|
|
136
|
+
common = present(parent / 'commondir')
|
|
137
|
+
# Include split metadata and damaged bare repositories without HEAD.
|
|
138
|
+
if (head and (objects or refs or common)) or (objects and refs):
|
|
139
|
+
break
|
|
140
|
+
else:
|
|
141
|
+
return False
|
|
142
|
+
except OSError as exc:
|
|
143
|
+
raise GovernanceError('GIT_WORKSPACE_UNVERIFIED',
|
|
144
|
+
'Could not inspect the workspace Git boundary.') from exc
|
|
145
|
+
|
|
146
|
+
try:
|
|
147
|
+
result = git(workspace, 'rev-parse', '--is-inside-work-tree')
|
|
148
|
+
except OSError as exc:
|
|
149
|
+
raise GovernanceError('GIT_UNAVAILABLE', 'Git could not be executed for this workspace.') from exc
|
|
150
|
+
if result.stdout.strip() != b'true':
|
|
151
|
+
raise GovernanceError('GIT_WORKSPACE_ROOT', 'Use a Git working tree root, not repository metadata.')
|
|
152
|
+
return True
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class Core:
|
|
156
|
+
def __init__(self, project):
|
|
157
|
+
self.store = Store(project)
|
|
158
|
+
self.root = self.store.root
|
|
159
|
+
config = self.store.get('config', 'project')
|
|
160
|
+
if not config or type(config.get('schema_version')) is not int or config.get('schema_version') != 1:
|
|
161
|
+
raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible toolkit version for this project state.')
|
|
162
|
+
|
|
163
|
+
@classmethod
|
|
164
|
+
def identify(cls, project):
|
|
165
|
+
from .identification import identify
|
|
166
|
+
return identify(project)
|
|
167
|
+
|
|
168
|
+
def source(self):
|
|
169
|
+
from .identification import source
|
|
170
|
+
return source(self.root, self.store.get('config', 'project'))
|
|
171
|
+
|
|
172
|
+
def context(self, task_id, limit=20, cursor=None, previous_fingerprint=None,
|
|
173
|
+
issue_ids=None, fix_ids=None):
|
|
174
|
+
from .task_context import read_context
|
|
175
|
+
return read_context(self, task_id, limit, cursor, previous_fingerprint, issue_ids, fix_ids)
|
|
176
|
+
|
|
177
|
+
@classmethod
|
|
178
|
+
def initialize(cls, project, name='TaskCarry project'):
|
|
179
|
+
from .identification import identify, require_initializable
|
|
180
|
+
store = Store(project, create=True)
|
|
181
|
+
with store.guard():
|
|
182
|
+
# Recheck before opening the publishing write transaction too.
|
|
183
|
+
require_initializable(identify(store.root, initializing=True))
|
|
184
|
+
with store.transaction():
|
|
185
|
+
config = store.get('config', 'project')
|
|
186
|
+
if config is not None and (type(config.get('schema_version')) is not int or config.get('schema_version') != 1):
|
|
187
|
+
raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Initialization cannot downgrade existing project state.')
|
|
188
|
+
if config is None:
|
|
189
|
+
from .identification import source
|
|
190
|
+
config = {'name': name, 'schema_version': 1, 'created_at': now(), 'synthetic': False,
|
|
191
|
+
'project_id': 'project-' + uuid.uuid4().hex,
|
|
192
|
+
'replica_id': 'replica-' + uuid.uuid4().hex,
|
|
193
|
+
'source_aliases': [source(store.root)['source_id']]}
|
|
194
|
+
store.put('config', 'project', config)
|
|
195
|
+
store.put('experience', 'receipt-recovery-v1', {
|
|
196
|
+
'rule_id': 'receipt-recovery-v1', 'code': 'EFFECT_PRESENT_RECEIPT_MISSING',
|
|
197
|
+
'operation': 'reconcile', 'action': 'verify_and_finalize', 'task_id': None,
|
|
198
|
+
'version': '1', 'enabled': True, 'updated_at': now()})
|
|
199
|
+
store.event('project_initialized', {'name': name})
|
|
200
|
+
return {'initialized': True, 'project': str(store.root), 'config': config}
|
|
201
|
+
|
|
202
|
+
def _task(self, task_id):
|
|
203
|
+
task = self.store.get('tasks', _id(task_id, 'Task ID'))
|
|
204
|
+
if task is None:
|
|
205
|
+
raise GovernanceError('TASK_NOT_FOUND', 'Create the task before capturing or delivering work.', {'task_id': task_id})
|
|
206
|
+
return task
|
|
207
|
+
|
|
208
|
+
def task(self, task_id, title=None, workstream=None, state=None):
|
|
209
|
+
task_id = _id(task_id, 'Task ID')
|
|
210
|
+
if state is not None and state not in ('active', 'paused', 'waiting', 'complete'):
|
|
211
|
+
raise GovernanceError('INVALID_STATE', 'Task state must be active, paused, waiting or complete.')
|
|
212
|
+
with self.store.transaction():
|
|
213
|
+
previous = self.store.get('tasks', task_id)
|
|
214
|
+
result = dict(previous or {'task_id': task_id, 'title': title or task_id, 'workstream': workstream or task_id,
|
|
215
|
+
'state': 'active', 'created_at': now()})
|
|
216
|
+
for key, value in (('title', title), ('workstream', workstream), ('state', state)):
|
|
217
|
+
if value is not None:
|
|
218
|
+
result[key] = value
|
|
219
|
+
if result != previous:
|
|
220
|
+
result['updated_at'] = now()
|
|
221
|
+
self.store.put('tasks', task_id, result)
|
|
222
|
+
self.store.event('task_changed', result)
|
|
223
|
+
return result
|
|
224
|
+
|
|
225
|
+
def status(self):
|
|
226
|
+
supporting = ('observations', 'runs', 'issues', 'fixes')
|
|
227
|
+
records = self.store.snapshot(CURRENT_COLLECTIONS + supporting)
|
|
228
|
+
result = self._current_view(records)
|
|
229
|
+
result['continuity'] = {name: records[name] for name in supporting}
|
|
230
|
+
result['storage'] = self.store.storage_status()
|
|
231
|
+
result['source'] = self.source()
|
|
232
|
+
return result
|
|
233
|
+
|
|
234
|
+
def upgrade(self):
|
|
235
|
+
"""Opt in to the indexed agenda without rewriting project evidence."""
|
|
236
|
+
return self.store.upgrade()
|
|
237
|
+
|
|
238
|
+
@staticmethod
|
|
239
|
+
def _current_view(records):
|
|
240
|
+
tasks, stages, operations, workspaces = (records[x] for x in ('tasks', 'stages', 'operations', 'workspaces'))
|
|
241
|
+
terminal = TERMINAL_STATES
|
|
242
|
+
pending_stages = [s for s in stages if str(s.get('state', s.get('status', 'queued'))).lower() not in terminal]
|
|
243
|
+
# Submission validates cumulative ancestry. Project that declaration here
|
|
244
|
+
# without pretending that the older stage already has a terminal receipt.
|
|
245
|
+
stage_index = {s.get('stage_id'): s for s in stages if s.get('stage_id')}
|
|
246
|
+
covered_pending = {}
|
|
247
|
+
for successor in stages:
|
|
248
|
+
if (str(successor.get('status', successor.get('state', ''))).lower() not in ('queued', 'conflict')
|
|
249
|
+
or successor.get('relation') != 'cumulative'
|
|
250
|
+
or not successor.get('task_id') or not successor.get('workspace')
|
|
251
|
+
or not successor.get('stage_id')):
|
|
252
|
+
continue
|
|
253
|
+
remaining, visited = list(successor.get('supersedes', [])), {successor['stage_id']}
|
|
254
|
+
while remaining:
|
|
255
|
+
old_id = remaining.pop()
|
|
256
|
+
if old_id in visited:
|
|
257
|
+
continue
|
|
258
|
+
visited.add(old_id)
|
|
259
|
+
old = stage_index.get(old_id)
|
|
260
|
+
if not old or old.get('task_id') != successor['task_id'] or old.get('workspace') != successor['workspace']:
|
|
261
|
+
continue
|
|
262
|
+
if str(old.get('status', old.get('state', ''))).lower() == 'queued':
|
|
263
|
+
covered_pending[old_id] = successor['stage_id']
|
|
264
|
+
if old.get('relation') == 'cumulative':
|
|
265
|
+
remaining.extend(old.get('supersedes', []))
|
|
266
|
+
pending_stages = [s for s in pending_stages if s.get('stage_id') not in covered_pending]
|
|
267
|
+
pending_operations = [o for o in operations if str(o.get('state', o.get('status', 'pending'))).lower() not in terminal]
|
|
268
|
+
artifacts = records['artifacts']
|
|
269
|
+
return {'tasks': tasks, 'stages': stages, 'operations': operations, 'workspaces': workspaces,
|
|
270
|
+
'actionable': {'stages': pending_stages, 'operations': pending_operations,
|
|
271
|
+
'artifacts': [a for a in artifacts if a.get('decision') not in ('ignore', 'dismiss', 'no_backup_needed') and not a.get('backup_verified')]},
|
|
272
|
+
'retained_task_state': [t for t in tasks if t['state'] in ('paused', 'waiting')],
|
|
273
|
+
'covered_pending_stages': [{'stage_id': sid, 'awaiting_successor': successor}
|
|
274
|
+
for sid, successor in sorted(covered_pending.items())],
|
|
275
|
+
'checkpoints': records['checkpoints'], 'artifacts': artifacts,
|
|
276
|
+
'history_counts': {'terminal_stages': sum(str(s.get('state', s.get('status', 'queued'))).lower() in terminal for s in stages),
|
|
277
|
+
'terminal_operations': len(operations) - len(pending_operations)},
|
|
278
|
+
'meaning': 'Task state and checkpoint retention do not create a delivery obligation or imply business acceptance.'}
|
|
279
|
+
|
|
280
|
+
def agenda(self, limit=20, previous_fingerprint=None, cursor=None):
|
|
281
|
+
"""Select a page of recorded current work; never execute or acknowledge it.
|
|
282
|
+
|
|
283
|
+
The limit bounds returned items. Indexed projects load current records
|
|
284
|
+
and their linked dependencies, not unrelated terminal history. Cursor
|
|
285
|
+
state is returned rather than written into the governance database.
|
|
286
|
+
"""
|
|
287
|
+
if type(limit) is not int or not 1 <= limit <= 100:
|
|
288
|
+
raise GovernanceError('INVALID_ARGUMENT', 'Agenda limit must be an integer from 1 to 100.')
|
|
289
|
+
if previous_fingerprint is not None and (
|
|
290
|
+
not isinstance(previous_fingerprint, str)
|
|
291
|
+
or not re.fullmatch(r'[0-9a-f]{64}', previous_fingerprint)):
|
|
292
|
+
raise GovernanceError('INVALID_ARGUMENT', 'The previous agenda fingerprint must be a SHA-256 value.')
|
|
293
|
+
cursor_data = None
|
|
294
|
+
if cursor is not None:
|
|
295
|
+
try:
|
|
296
|
+
if not isinstance(cursor, str) or not 1 <= len(cursor) <= 1024:
|
|
297
|
+
raise ValueError('Invalid cursor size')
|
|
298
|
+
raw = base64.b64decode(cursor + '=' * (-len(cursor) % 4), altchars=b'-_', validate=True)
|
|
299
|
+
cursor_data = json.loads(raw)
|
|
300
|
+
if (not isinstance(cursor_data, dict)
|
|
301
|
+
or set(cursor_data) != {'version', 'offset', 'fingerprint'}
|
|
302
|
+
or type(cursor_data['version']) is not int or cursor_data['version'] != 1
|
|
303
|
+
or type(cursor_data['offset']) is not int or cursor_data['offset'] < 1
|
|
304
|
+
or not isinstance(cursor_data['fingerprint'], str)
|
|
305
|
+
or not re.fullmatch(r'[0-9a-f]{64}', cursor_data['fingerprint'])):
|
|
306
|
+
raise ValueError('Invalid cursor contents')
|
|
307
|
+
except (ValueError, TypeError, UnicodeError) as exc:
|
|
308
|
+
raise GovernanceError('AGENDA_CURSOR_INVALID', 'Use an unchanged next_cursor from an agenda result.') from exc
|
|
309
|
+
|
|
310
|
+
records = self.store.snapshot_current()
|
|
311
|
+
plans = {plan.get('plan_id'): plan for plan in records['plans']}
|
|
312
|
+
current = self._current_view(records)
|
|
313
|
+
current['actionable']['issues'] = [r for r in records['issues'] if r.get('state') != 'resolved']
|
|
314
|
+
current['actionable']['runs'] = [r for r in records['runs'] if r.get('state') != 'COMPLETED']
|
|
315
|
+
# Observation timestamps are not new work; evidence, outcomes and inputs are.
|
|
316
|
+
def content(record):
|
|
317
|
+
return {key: value for key, value in record.items()
|
|
318
|
+
if key not in {'created_at', 'updated_at', 'accepted_at', 'completed_at'}}
|
|
319
|
+
|
|
320
|
+
def fingerprint(value):
|
|
321
|
+
return digest_bytes(json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
322
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8'))
|
|
323
|
+
|
|
324
|
+
items, inputs = [], []
|
|
325
|
+
selected_stages, referenced_workspaces = set(), set()
|
|
326
|
+
kinds = (('operation', 'operations', 'operation_id'),
|
|
327
|
+
('stage', 'stages', 'stage_id'), ('artifact', 'artifacts', 'artifact_id'),
|
|
328
|
+
('issue', 'issues', 'issue_id'), ('run', 'runs', 'run_id'))
|
|
329
|
+
for kind, collection, id_key in kinds:
|
|
330
|
+
for record in sorted(current['actionable'][collection], key=lambda value: value.get(id_key, '')):
|
|
331
|
+
record_id = record.get(id_key)
|
|
332
|
+
if not isinstance(record_id, str) or not record_id:
|
|
333
|
+
raise GovernanceError('STATE_RECORD_INVALID', 'An actionable record has no stable identity.',
|
|
334
|
+
{'collection': collection})
|
|
335
|
+
state = str(record.get('state', record.get('status', 'recorded')))
|
|
336
|
+
operation = record.get('kind') if kind == 'operation' else 'reconcile' if kind == 'stage' else 'artifact'
|
|
337
|
+
code = record.get('code')
|
|
338
|
+
# A recorded effect may justify inspecting this recovery rule;
|
|
339
|
+
# only the original executor can verify the actual Git effect.
|
|
340
|
+
if not code and operation == 'reconcile' and state.upper() == 'EFFECT_APPLIED' and record.get('candidate'):
|
|
341
|
+
code = 'EFFECT_PRESENT_RECEIPT_MISSING'
|
|
342
|
+
matches = self._experience_matches(records['experience'], code, operation, record.get('task_id')) if code else []
|
|
343
|
+
suggestions = []
|
|
344
|
+
for rule in matches:
|
|
345
|
+
suggestion = {**content(rule), 'requires_current_evidence': True,
|
|
346
|
+
'execution': 'candidate_only'}
|
|
347
|
+
if rule['action'] == 'refresh_plan':
|
|
348
|
+
# A new plan is a proposal, never permission to replay an
|
|
349
|
+
# effect. Derive its arguments from the original plan.
|
|
350
|
+
plan = plans.get(record.get('plan_id'), {})
|
|
351
|
+
if (kind == 'operation' and not record.get('candidate')
|
|
352
|
+
and not record.get('stash')
|
|
353
|
+
and record.get('effect_state') == 'NOT_APPLIED'
|
|
354
|
+
and plan.get('kind') == operation
|
|
355
|
+
and operation in {'adopt', 'reconcile'}):
|
|
356
|
+
fields = ('workspace', 'baseline') if operation == 'adopt' else ('baseline',)
|
|
357
|
+
if all(isinstance(plan.get(key), str) and plan[key] for key in fields):
|
|
358
|
+
args = {key: plan[key] for key in fields}
|
|
359
|
+
if operation == 'reconcile':
|
|
360
|
+
args['limit'] = plan.get('selection', {}).get('limit', 20)
|
|
361
|
+
suggestion['plan_request'] = {'action': operation,
|
|
362
|
+
'arguments': {**args, 'execute': False}}
|
|
363
|
+
suggestion['execution'] = 'proposal_only'
|
|
364
|
+
suggestion['requires_new_plan_review'] = True
|
|
365
|
+
suggestions.append(suggestion)
|
|
366
|
+
item_input = {'record': content(record), 'experience_candidates': suggestions}
|
|
367
|
+
inputs.append({'kind': kind, 'id': record_id, **item_input})
|
|
368
|
+
item = {'kind': kind, 'id': kind + ':' + record_id, 'record_id': record_id,
|
|
369
|
+
'task_id': record.get('task_id'), 'workspace': record.get('workspace'),
|
|
370
|
+
'state': state, 'code': code, 'input_fingerprint': fingerprint(item_input),
|
|
371
|
+
'experience_candidates': suggestions}
|
|
372
|
+
if kind == 'operation':
|
|
373
|
+
item['next_step'] = 'Inspect the original operation and verify actual effects before continuing its missing step.'
|
|
374
|
+
if record.get('stage_id'):
|
|
375
|
+
selected_stages.add(record['stage_id'])
|
|
376
|
+
elif kind == 'stage':
|
|
377
|
+
item['next_step'] = 'Review the frozen delivery and its current reconciliation plan.'
|
|
378
|
+
selected_stages.add(record_id)
|
|
379
|
+
elif kind == 'artifact':
|
|
380
|
+
item['next_step'] = 'Review the retained artifact relationship, decision and backup evidence.'
|
|
381
|
+
elif kind == 'issue':
|
|
382
|
+
item['next_step'] = 'Review this recorded condition and its resolution evidence; an issue record never replaces an operation receipt.'
|
|
383
|
+
else:
|
|
384
|
+
item['next_step'] = 'Inspect the frozen run selection and continue only its unfinished operations or receipt.'
|
|
385
|
+
items.append(item)
|
|
386
|
+
referenced_workspaces.update(record[name] for name in ('workspace', 'baseline')
|
|
387
|
+
if isinstance(record.get(name), str))
|
|
388
|
+
|
|
389
|
+
# A received predecessor may affect the next delta. Include only such
|
|
390
|
+
# dependencies, not unrelated completed history, in the current fingerprint.
|
|
391
|
+
stage_index = {stage.get('stage_id'): stage for stage in current['stages']}
|
|
392
|
+
dependencies, remaining = {}, list(selected_stages)
|
|
393
|
+
while remaining:
|
|
394
|
+
stage_id = remaining.pop()
|
|
395
|
+
if stage_id in dependencies or stage_id not in stage_index:
|
|
396
|
+
continue
|
|
397
|
+
stage = stage_index[stage_id]
|
|
398
|
+
dependencies[stage_id] = content(stage)
|
|
399
|
+
referenced_workspaces.update(stage[name] for name in ('workspace', 'accepted_baseline')
|
|
400
|
+
if isinstance(stage.get(name), str))
|
|
401
|
+
remaining.extend(stage.get('supersedes', []))
|
|
402
|
+
active_tasks = [content(task) for task in current['tasks'] if task.get('state') != 'complete']
|
|
403
|
+
workspace_inputs = [content(workspace) for workspace in current['workspaces']
|
|
404
|
+
if workspace.get('name') in referenced_workspaces
|
|
405
|
+
or workspace.get('path') in referenced_workspaces]
|
|
406
|
+
from .experience_storage import legacy_pointer
|
|
407
|
+
experience_pointer = legacy_pointer(self)
|
|
408
|
+
input_fingerprint = fingerprint({'project': str(self.root), 'items': inputs,
|
|
409
|
+
'conditional_experience': experience_pointer,
|
|
410
|
+
'tasks': active_tasks, 'workspaces': workspace_inputs,
|
|
411
|
+
'stage_dependencies': dependencies,
|
|
412
|
+
'run_dependencies': {
|
|
413
|
+
'observations': [o for o in records['observations'] if o.get('observation_id') in
|
|
414
|
+
{key for r in current['actionable']['runs'] for key in r.get('observation_ids', [])}],
|
|
415
|
+
'stages': [s for s in records['stages'] if s.get('stage_id') in
|
|
416
|
+
{key for r in current['actionable']['runs'] for key in r.get('stage_ids', [])}],
|
|
417
|
+
'operations': [o for o in records['operations'] if o.get('operation_id') in
|
|
418
|
+
{key for r in current['actionable']['runs'] for key in r.get('operation_ids', [])}]}})
|
|
419
|
+
if cursor_data and cursor_data['fingerprint'] != input_fingerprint:
|
|
420
|
+
raise GovernanceError('AGENDA_CURSOR_STALE', 'Recorded work changed; read a fresh first page.',
|
|
421
|
+
{'current_fingerprint': input_fingerprint})
|
|
422
|
+
offset = cursor_data['offset'] if cursor_data else 0
|
|
423
|
+
if cursor_data and offset >= len(items):
|
|
424
|
+
raise GovernanceError('AGENDA_CURSOR_INVALID', 'The cursor offset is outside the current agenda.')
|
|
425
|
+
page = items[offset:offset + limit]
|
|
426
|
+
end = offset + len(page)
|
|
427
|
+
next_cursor = None
|
|
428
|
+
if end < len(items):
|
|
429
|
+
next_cursor = base64.urlsafe_b64encode(json.dumps(
|
|
430
|
+
{'version': 1, 'offset': end, 'fingerprint': input_fingerprint},
|
|
431
|
+
sort_keys=True, separators=(',', ':'),
|
|
432
|
+
).encode('utf-8')).decode('ascii').rstrip('=')
|
|
433
|
+
counts = {collection: len(current['actionable'][collection]) for _, collection, _ in kinds}
|
|
434
|
+
counts.update(retained_tasks=len(current['retained_task_state']),
|
|
435
|
+
covered_stages=len(current['covered_pending_stages']))
|
|
436
|
+
return {'source': self.source(), 'items': page, 'counts': counts, 'total': len(items), 'returned': len(page),
|
|
437
|
+
'conditional_experience': experience_pointer,
|
|
438
|
+
'offset': offset, 'truncated': len(items) - end, 'next_cursor': next_cursor,
|
|
439
|
+
'fingerprint': input_fingerprint,
|
|
440
|
+
'storage': records['_storage'],
|
|
441
|
+
'changed': previous_fingerprint is None or previous_fingerprint != input_fingerprint,
|
|
442
|
+
'selection_only': True, 'effects_executed': False, 'project_complete': None,
|
|
443
|
+
'meaning': 'This is a bounded selection of recorded work, not an execution, retry, acknowledgment or proof of project completion. Verify live conditions before acting.'}
|
|
444
|
+
|
|
445
|
+
def _snapshot(self, data):
|
|
446
|
+
digest = digest_bytes(data)
|
|
447
|
+
directory = self.store.directory / 'objects'
|
|
448
|
+
if _linked(directory):
|
|
449
|
+
raise GovernanceError('UNSAFE_METADATA', 'Snapshot storage cannot be a symbolic link.')
|
|
450
|
+
directory.mkdir(exist_ok=True)
|
|
451
|
+
target = directory / digest
|
|
452
|
+
if target.exists():
|
|
453
|
+
if digest_bytes(read_file_bytes(target)) != digest:
|
|
454
|
+
raise GovernanceError('SNAPSHOT_CORRUPT', 'An existing immutable snapshot failed verification.')
|
|
455
|
+
else:
|
|
456
|
+
try:
|
|
457
|
+
with target.open('xb') as stream:
|
|
458
|
+
stream.write(data)
|
|
459
|
+
stream.flush()
|
|
460
|
+
os.fsync(stream.fileno())
|
|
461
|
+
except FileExistsError:
|
|
462
|
+
if digest_bytes(read_file_bytes(target)) != digest:
|
|
463
|
+
raise GovernanceError('SNAPSHOT_CORRUPT', 'A concurrent snapshot failed verification.')
|
|
464
|
+
return {'sha256': digest, 'size': len(data)}
|
|
465
|
+
|
|
466
|
+
def _blob(self, workspace, oid, mode):
|
|
467
|
+
if mode not in ('100644', '100755'):
|
|
468
|
+
raise GovernanceError('UNSUPPORTED_GIT_ENTRY', 'Links, submodules, directories and unmerged entries are not checkpoint files.')
|
|
469
|
+
size = int(git(workspace, 'cat-file', '-s', oid).stdout.strip())
|
|
470
|
+
if size > MAX_FILE_BYTES:
|
|
471
|
+
raise GovernanceError('FILE_TOO_LARGE', 'A Git blob exceeds the checkpoint file limit.')
|
|
472
|
+
data = git(workspace, 'cat-file', 'blob', oid).stdout
|
|
473
|
+
return {**self._snapshot(data), 'mode': mode, 'git_oid': oid}
|
|
474
|
+
|
|
475
|
+
def checkpoint(self, task_id, workspace, paths, next_step, decision='', paused=False):
|
|
476
|
+
if (not isinstance(paths, list) or not paths or len(paths) > MAX_PATHS
|
|
477
|
+
or any(not isinstance(p, str) for p in paths)
|
|
478
|
+
or len({p.casefold() for p in paths}) != len(paths)):
|
|
479
|
+
raise GovernanceError('INVALID_PATHS', 'Provide 1-500 unique explicit file paths.')
|
|
480
|
+
raw_workspace = Path(workspace).expanduser().absolute()
|
|
481
|
+
if any(_linked(p) for p in (raw_workspace, *raw_workspace.parents)):
|
|
482
|
+
raise GovernanceError('SYMLINK_PATH', 'Workspace cannot traverse symbolic links or junctions.')
|
|
483
|
+
workspace = raw_workspace.resolve()
|
|
484
|
+
if not workspace.is_dir():
|
|
485
|
+
raise GovernanceError('MISSING_WORKSPACE', 'The source workspace does not exist.')
|
|
486
|
+
for path in paths:
|
|
487
|
+
validate_relative_path(workspace, path)
|
|
488
|
+
with self.store.guard():
|
|
489
|
+
task = self._task(task_id)
|
|
490
|
+
is_git = _checkpoint_uses_git(workspace)
|
|
491
|
+
if is_git and Path(git(workspace, 'rev-parse', '--show-toplevel').stdout.decode().strip()).resolve() != workspace:
|
|
492
|
+
raise GovernanceError('GIT_WORKSPACE_ROOT', 'Use the Git worktree root and paths relative to that root.')
|
|
493
|
+
head = git(workspace, 'rev-parse', '--verify', 'HEAD', check=False).stdout.decode().strip() if is_git else None
|
|
494
|
+
def selected_index():
|
|
495
|
+
return b''.join(git(workspace, 'ls-files', '--stage', '-z', '--', *batch).stdout
|
|
496
|
+
for batch in path_batches(paths))
|
|
497
|
+
index_before = selected_index() if is_git else b''
|
|
498
|
+
files, total = [], 0
|
|
499
|
+
index = {}
|
|
500
|
+
for entry in index_before.split(b'\x00'):
|
|
501
|
+
if not entry:
|
|
502
|
+
continue
|
|
503
|
+
metadata, encoded_path = entry.split(b'\t', 1)
|
|
504
|
+
mode, oid, stage = metadata.decode().split()
|
|
505
|
+
if stage != '0':
|
|
506
|
+
raise GovernanceError('UNMERGED_INDEX', 'Resolve or separately preserve merge-conflict stages before checkpointing.')
|
|
507
|
+
index[encoded_path.decode('utf-8')] = (mode, oid)
|
|
508
|
+
for path in paths:
|
|
509
|
+
source = validate_relative_path(workspace, path)
|
|
510
|
+
record = {'path': path, 'head': None, 'index': None, 'worktree': None}
|
|
511
|
+
if is_git and head:
|
|
512
|
+
entry = git(workspace, 'ls-tree', '-z', head, '--', path).stdout.rstrip(b'\x00')
|
|
513
|
+
if entry:
|
|
514
|
+
meta, _ = entry.split(b'\t', 1)
|
|
515
|
+
mode, kind, oid = meta.decode().split()
|
|
516
|
+
record['head'] = self._blob(workspace, oid, mode)
|
|
517
|
+
if path in index:
|
|
518
|
+
mode, oid = index[path]
|
|
519
|
+
record['index'] = self._blob(workspace, oid, mode)
|
|
520
|
+
if source.exists():
|
|
521
|
+
data = read_file_bytes(source)
|
|
522
|
+
record['worktree'] = {**self._snapshot(data), 'mode': '100755' if source.stat().st_mode & stat.S_IXUSR else '100644'}
|
|
523
|
+
if all(record[layer] is None for layer in ('head', 'index', 'worktree')):
|
|
524
|
+
raise GovernanceError('MISSING_FILE', 'A selected path has no Git or filesystem content.', {'path': path})
|
|
525
|
+
total += sum(record[layer]['size'] for layer in ('head', 'index', 'worktree') if record[layer])
|
|
526
|
+
if total > MAX_CHECKPOINT_BYTES:
|
|
527
|
+
raise GovernanceError('CHECKPOINT_TOO_LARGE', 'The checkpoint exceeds its total snapshot limit.')
|
|
528
|
+
files.append(record)
|
|
529
|
+
if is_git:
|
|
530
|
+
if index_before != selected_index() or head != git(workspace, 'rev-parse', '--verify', 'HEAD', check=False).stdout.decode().strip():
|
|
531
|
+
raise GovernanceError('SOURCE_CHANGED', 'Git HEAD or selected index entries changed during capture.')
|
|
532
|
+
for record in files:
|
|
533
|
+
source = validate_relative_path(workspace, record['path'])
|
|
534
|
+
frozen = record['worktree']
|
|
535
|
+
if (source.exists() != (frozen is not None)) or (frozen and digest_bytes(read_file_bytes(source)) != frozen['sha256']):
|
|
536
|
+
raise GovernanceError('SOURCE_CHANGED', 'A selected worktree file changed during capture.')
|
|
537
|
+
if not is_git and _checkpoint_uses_git(workspace):
|
|
538
|
+
raise GovernanceError('SOURCE_CHANGED', 'The plain workspace became a Git repository during capture.')
|
|
539
|
+
checkpoint_id = 'cp-' + uuid.uuid4().hex
|
|
540
|
+
result = {'checkpoint_id': checkpoint_id, 'task_id': task_id, 'workspace': str(workspace),
|
|
541
|
+
'git': is_git, 'original_head': head or None, 'files': files, 'next_step': next_step,
|
|
542
|
+
'decision': decision, 'created_at': now(), 'scope': 'selected_files_only',
|
|
543
|
+
'delivery': False, 'total_layer_bytes': total}
|
|
544
|
+
# Immutable objects may exist before publication, but the checkpoint,
|
|
545
|
+
# task pointer and its evidence event become visible together.
|
|
546
|
+
with self.store.transaction():
|
|
547
|
+
self.store.put('checkpoints', checkpoint_id, result)
|
|
548
|
+
task.update(latest_checkpoint=checkpoint_id, next_step=next_step, updated_at=now())
|
|
549
|
+
if paused:
|
|
550
|
+
task['state'] = 'paused'
|
|
551
|
+
self.store.put('tasks', task_id, task)
|
|
552
|
+
self.store.event('checkpoint_saved', {'checkpoint_id': checkpoint_id, 'task_id': task_id})
|
|
553
|
+
return result
|
|
554
|
+
|
|
555
|
+
def _snapshot_bytes(self, reference):
|
|
556
|
+
digest = reference.get('sha256', '')
|
|
557
|
+
if not re.fullmatch(r'[0-9a-f]{64}', digest):
|
|
558
|
+
raise GovernanceError('SNAPSHOT_CORRUPT', 'Invalid snapshot object identity.')
|
|
559
|
+
source = self.store.directory / 'objects' / digest
|
|
560
|
+
if _linked(source.parent) or _linked(source) or not source.is_file():
|
|
561
|
+
raise GovernanceError('SNAPSHOT_CORRUPT', 'Snapshot object is missing or unsafe.')
|
|
562
|
+
data = read_file_bytes(source)
|
|
563
|
+
if digest_bytes(data) != digest or len(data) != reference['size']:
|
|
564
|
+
raise GovernanceError('SNAPSHOT_CORRUPT', 'Snapshot digest or size verification failed.')
|
|
565
|
+
return data
|
|
566
|
+
|
|
567
|
+
@staticmethod
|
|
568
|
+
def _restore_digest(value):
|
|
569
|
+
return digest_bytes(json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
570
|
+
separators=(',', ':'), allow_nan=False).encode('utf-8'))
|
|
571
|
+
|
|
572
|
+
@staticmethod
|
|
573
|
+
def _restore_directory_identity(destination):
|
|
574
|
+
if _linked(destination):
|
|
575
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restore destination became a link.')
|
|
576
|
+
info = destination.stat()
|
|
577
|
+
if not stat.S_ISDIR(info.st_mode):
|
|
578
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restore destination is not a directory.')
|
|
579
|
+
return {'device': info.st_dev, 'inode': info.st_ino,
|
|
580
|
+
'birthtime_ns': getattr(info, 'st_birthtime_ns', None)}
|
|
581
|
+
|
|
582
|
+
@staticmethod
|
|
583
|
+
def _restore_metadata(metadata):
|
|
584
|
+
"""Bounded evidence for the newly created repository, without links."""
|
|
585
|
+
records, total, pending = {}, 0, [metadata]
|
|
586
|
+
while pending:
|
|
587
|
+
directory = pending.pop()
|
|
588
|
+
with os.scandir(directory) as entries:
|
|
589
|
+
for entry in entries:
|
|
590
|
+
path = Path(entry.path)
|
|
591
|
+
relative = path.relative_to(metadata).as_posix()
|
|
592
|
+
if _linked(path):
|
|
593
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git metadata contains a link.')
|
|
594
|
+
if entry.is_dir(follow_symlinks=False):
|
|
595
|
+
records[relative] = {'directory': True}
|
|
596
|
+
pending.append(path)
|
|
597
|
+
else:
|
|
598
|
+
content = read_file_bytes(path, max_bytes=MAX_CHECKPOINT_BYTES)
|
|
599
|
+
total += len(content)
|
|
600
|
+
records[relative] = {'sha256': digest_bytes(content), 'size': len(content),
|
|
601
|
+
'mode': stat.S_IMODE(path.stat().st_mode)}
|
|
602
|
+
if len(records) > MAX_PATHS * 8 or total > MAX_CHECKPOINT_BYTES * 2:
|
|
603
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git metadata exceeds verification limits.')
|
|
604
|
+
return records
|
|
605
|
+
|
|
606
|
+
def _restore_effect(self, checkpoint, destination, expected_git=None):
|
|
607
|
+
"""Read exact restored layers, including absence, without repairing them."""
|
|
608
|
+
expected = {record['path']: record['worktree'] for record in checkpoint['files']
|
|
609
|
+
if record['worktree'] is not None}
|
|
610
|
+
directories = {str(parent) for path in expected for parent in PurePosixPath(path).parents
|
|
611
|
+
if str(parent) != '.'}
|
|
612
|
+
files, seen_directories, pending = {}, set(), [destination]
|
|
613
|
+
while pending:
|
|
614
|
+
directory = pending.pop()
|
|
615
|
+
with os.scandir(directory) as entries:
|
|
616
|
+
for entry in entries:
|
|
617
|
+
path = Path(entry.path)
|
|
618
|
+
relative = path.relative_to(destination).as_posix()
|
|
619
|
+
if _linked(path):
|
|
620
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'A restored path became a link.', {'path': relative})
|
|
621
|
+
if relative == '.git' and checkpoint['git']:
|
|
622
|
+
if not entry.is_dir(follow_symlinks=False):
|
|
623
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git metadata was replaced.')
|
|
624
|
+
continue
|
|
625
|
+
if entry.is_dir(follow_symlinks=False):
|
|
626
|
+
if relative not in directories:
|
|
627
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'An extra directory exists in the restored workspace.', {'path': relative})
|
|
628
|
+
seen_directories.add(relative)
|
|
629
|
+
pending.append(path)
|
|
630
|
+
continue
|
|
631
|
+
if relative not in expected:
|
|
632
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'An extra path exists in the restored workspace.', {'path': relative})
|
|
633
|
+
content = read_file_bytes(path)
|
|
634
|
+
reference = expected[relative]
|
|
635
|
+
mode = '100755' if path.stat().st_mode & stat.S_IXUSR else '100644'
|
|
636
|
+
if (digest_bytes(content) != reference['sha256'] or len(content) != reference['size']
|
|
637
|
+
or os.name != 'nt' and mode != reference['mode']):
|
|
638
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored file content or mode changed.', {'path': relative})
|
|
639
|
+
files[relative] = {'sha256': digest_bytes(content), 'size': len(content), 'mode': mode}
|
|
640
|
+
if set(files) != set(expected) or seen_directories != directories:
|
|
641
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored files or directories are missing.')
|
|
642
|
+
result = {'directory_identity': self._restore_directory_identity(destination),
|
|
643
|
+
'files': files, 'directories': sorted(seen_directories), 'git': None}
|
|
644
|
+
if checkpoint['git']:
|
|
645
|
+
metadata = destination / '.git'
|
|
646
|
+
metadata_identity = self._restore_directory_identity(metadata)
|
|
647
|
+
metadata_files = self._restore_metadata(metadata)
|
|
648
|
+
if expected_git is not None and (metadata_identity != expected_git.get('metadata_identity')
|
|
649
|
+
or metadata_files != expected_git.get('metadata_files')):
|
|
650
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git metadata changed; no Git commands executed.')
|
|
651
|
+
if (Path(git(destination, 'rev-parse', '--show-toplevel').stdout.decode().strip()).resolve() != destination
|
|
652
|
+
or Path(git(destination, 'rev-parse', '--absolute-git-dir').stdout.decode().strip()).resolve() != metadata):
|
|
653
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git repository identity changed.')
|
|
654
|
+
if (metadata / 'commondir').exists() or _linked(metadata / 'commondir'):
|
|
655
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git metadata was redirected.')
|
|
656
|
+
head = git(destination, 'rev-parse', '--verify', 'HEAD').stdout.decode().strip()
|
|
657
|
+
index = git(destination, 'ls-files', '--stage', '-z').stdout
|
|
658
|
+
tree = git(destination, 'ls-tree', '-r', '-z', '--full-tree', 'HEAD').stdout
|
|
659
|
+
for layer, entries in (('head', tree), ('index', index)):
|
|
660
|
+
wanted = {record['path']: record[layer] for record in checkpoint['files'] if record[layer] is not None}
|
|
661
|
+
actual = {}
|
|
662
|
+
for entry in entries.split(b'\0'):
|
|
663
|
+
if not entry:
|
|
664
|
+
continue
|
|
665
|
+
fields, name = entry.split(b'\t', 1)
|
|
666
|
+
fields = fields.decode().split()
|
|
667
|
+
mode, oid = (fields[0], fields[2]) if layer == 'head' else (fields[0], fields[1])
|
|
668
|
+
relative = name.decode('utf-8')
|
|
669
|
+
if (relative not in wanted or mode != wanted[relative]['mode']
|
|
670
|
+
or layer == 'index' and fields[2] != '0' or relative in actual):
|
|
671
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git layer differs from its checkpoint.')
|
|
672
|
+
size = int(git(destination, 'cat-file', '-s', oid).stdout.strip())
|
|
673
|
+
if size != wanted[relative]['size'] or size > MAX_FILE_BYTES:
|
|
674
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git blob size changed.')
|
|
675
|
+
if digest_bytes(git(destination, 'cat-file', 'blob', oid).stdout) != wanted[relative]['sha256']:
|
|
676
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Restored Git blob content changed.')
|
|
677
|
+
actual[relative] = oid
|
|
678
|
+
if set(actual) != set(wanted):
|
|
679
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'A restored Git layer has missing paths.')
|
|
680
|
+
result['git'] = {'head': head, 'index_entries_sha256': digest_bytes(index),
|
|
681
|
+
'index_file_sha256': digest_bytes(read_file_bytes(metadata / 'index')),
|
|
682
|
+
'head_file_sha256': digest_bytes(read_file_bytes(metadata / 'HEAD')),
|
|
683
|
+
'config_sha256': digest_bytes(read_file_bytes(metadata / 'config')),
|
|
684
|
+
'metadata_identity': metadata_identity, 'metadata_files': metadata_files}
|
|
685
|
+
return result
|
|
686
|
+
|
|
687
|
+
def _restore_finalize(self, checkpoint, destination, operation):
|
|
688
|
+
"""A known complete effect permits receipt publication, never replay."""
|
|
689
|
+
oid = operation['operation_id']
|
|
690
|
+
try:
|
|
691
|
+
actual = self._restore_effect(checkpoint, destination, operation.get('effect_fingerprint', {}).get('git'))
|
|
692
|
+
except (OSError, GovernanceError) as exc:
|
|
693
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED',
|
|
694
|
+
'The recorded restore effect cannot be verified; destination preserved.',
|
|
695
|
+
{'operation_id': oid, 'reason': getattr(exc, 'code', type(exc).__name__)}) from exc
|
|
696
|
+
if (actual != operation.get('effect_fingerprint')
|
|
697
|
+
or self._restore_digest(actual) != operation.get('effect_sha256')
|
|
698
|
+
or actual['directory_identity'] != operation.get('destination_identity')):
|
|
699
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restored destination changed; no effects replayed.',
|
|
700
|
+
{'operation_id': oid})
|
|
701
|
+
result = {'checkpoint_id': operation['checkpoint_id'], 'destination': str(destination), 'restored': True,
|
|
702
|
+
'synthetic_git_baseline': checkpoint['git'], 'original_head': checkpoint['original_head'],
|
|
703
|
+
'scope': 'selected_files_only', 'original_workspace_modified': False, 'operation_id': oid}
|
|
704
|
+
receipt = {'operation_id': oid, 'checkpoint_id': operation['checkpoint_id'], 'destination': str(destination),
|
|
705
|
+
'checkpoint_sha256': operation['checkpoint_sha256'],
|
|
706
|
+
'effect_sha256': operation['effect_sha256'], 'verified': True, 'result': result}
|
|
707
|
+
if operation['status'] == 'COMPLETED':
|
|
708
|
+
if self.store.get('restore_receipts', oid) != receipt:
|
|
709
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The completed restore receipt is inconsistent.', {'operation_id': oid})
|
|
710
|
+
return {**result, 'reused': True}
|
|
711
|
+
with self.store.transaction():
|
|
712
|
+
self.store.put('operations', oid, {**operation, 'status': 'COMPLETED', 'effect_state': 'VERIFIED', 'completed_at': now()})
|
|
713
|
+
self.store.put('restore_receipts', oid, receipt)
|
|
714
|
+
self.store.event('checkpoint_restored', result)
|
|
715
|
+
return {**result, 'reused': False}
|
|
716
|
+
|
|
717
|
+
def restore(self, checkpoint_id, destination):
|
|
718
|
+
with self.store.guard():
|
|
719
|
+
checkpoint = self.store.get('checkpoints', checkpoint_id)
|
|
720
|
+
if checkpoint is None:
|
|
721
|
+
raise GovernanceError('CHECKPOINT_NOT_FOUND', 'The checkpoint does not exist.')
|
|
722
|
+
raw = Path(destination).expanduser().absolute()
|
|
723
|
+
for ancestor in (raw, *raw.parents):
|
|
724
|
+
if _linked(ancestor):
|
|
725
|
+
raise GovernanceError('SYMLINK_PATH', 'Restore destination cannot traverse symbolic links or junctions.')
|
|
726
|
+
destination = raw.resolve()
|
|
727
|
+
source = Path(checkpoint['workspace']).resolve()
|
|
728
|
+
if destination == self.root or destination.is_relative_to(self.root) or self.root.is_relative_to(destination) or destination == source or destination.is_relative_to(source) or source.is_relative_to(destination):
|
|
729
|
+
raise GovernanceError('RESTORE_NOT_INDEPENDENT', 'Restore into an independent directory outside source and governance workspaces.')
|
|
730
|
+
checkpoint_hash = self._restore_digest(checkpoint)
|
|
731
|
+
oid = 'restore-' + self._restore_digest([checkpoint_id, os.path.normcase(str(destination))])[:24]
|
|
732
|
+
operation = self.store.get('operations', oid)
|
|
733
|
+
if operation is not None:
|
|
734
|
+
if any(type(operation.get(key)) is not int or operation[key] != 1
|
|
735
|
+
for key in ('operation_protocol', 'restore_protocol')):
|
|
736
|
+
raise GovernanceError('OPERATION_PROTOCOL_UNSUPPORTED', 'Use a compatible toolkit for this restore operation.')
|
|
737
|
+
if (operation.get('kind') != 'restore' or operation.get('checkpoint_sha256') != checkpoint_hash
|
|
738
|
+
or operation.get('checkpoint_id') != checkpoint_id or operation.get('destination') != str(destination)):
|
|
739
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restore intent no longer matches its input.', {'operation_id': oid})
|
|
740
|
+
if operation.get('status') in ('EFFECT_APPLIED', 'COMPLETED'):
|
|
741
|
+
return self._restore_finalize(checkpoint, destination, operation)
|
|
742
|
+
if operation.get('status') != 'PREPARED' or operation.get('effect_state') != 'NOT_APPLIED':
|
|
743
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED',
|
|
744
|
+
'An interrupted restore has uncertain or partial effects; inspect the retained destination. No effects replayed.',
|
|
745
|
+
{'operation_id': oid, 'destination': str(destination), 'status': operation.get('status')})
|
|
746
|
+
if destination.exists() and (not destination.is_dir() or any(destination.iterdir())):
|
|
747
|
+
raise GovernanceError('RESTORE_NOT_EMPTY', 'Restore destination must be absent or empty.')
|
|
748
|
+
# Validate every object before creating or writing the destination.
|
|
749
|
+
contents = {}
|
|
750
|
+
if (not isinstance(checkpoint.get('files'), list) or not 1 <= len(checkpoint['files']) <= MAX_PATHS
|
|
751
|
+
or type(checkpoint.get('git')) is not bool):
|
|
752
|
+
raise GovernanceError('CHECKPOINT_CORRUPT', 'Restore requires a bounded checkpoint file manifest.')
|
|
753
|
+
paths, total = set(), 0
|
|
754
|
+
for record in checkpoint['files']:
|
|
755
|
+
validate_relative_path(destination, record['path'])
|
|
756
|
+
if record['path'].casefold() in paths:
|
|
757
|
+
raise GovernanceError('CHECKPOINT_CORRUPT', 'Checkpoint file paths must be unique.')
|
|
758
|
+
paths.add(record['path'].casefold())
|
|
759
|
+
for layer in ('head', 'index', 'worktree'):
|
|
760
|
+
if record[layer]:
|
|
761
|
+
if record[layer].get('mode') not in ('100644', '100755'):
|
|
762
|
+
raise GovernanceError('CHECKPOINT_CORRUPT', 'Checkpoint layers must be regular files.')
|
|
763
|
+
contents[(record['path'], layer)] = self._snapshot_bytes(record[layer])
|
|
764
|
+
total += len(contents[(record['path'], layer)])
|
|
765
|
+
if total > MAX_CHECKPOINT_BYTES:
|
|
766
|
+
raise GovernanceError('CHECKPOINT_TOO_LARGE', 'The restore exceeds the checkpoint byte limit.')
|
|
767
|
+
if operation is None:
|
|
768
|
+
operation = {'operation_id': oid, 'kind': 'restore', 'operation_protocol': 1, 'restore_protocol': 1,
|
|
769
|
+
'task_id': checkpoint['task_id'], 'checkpoint_id': checkpoint_id,
|
|
770
|
+
'checkpoint_sha256': checkpoint_hash, 'destination': str(destination),
|
|
771
|
+
'status': 'PREPARED', 'effect_state': 'NOT_APPLIED', 'created_at': now()}
|
|
772
|
+
self.store.put('operations', oid, operation)
|
|
773
|
+
operation = {**operation, 'status': 'APPLYING', 'effect_state': 'UNKNOWN'}
|
|
774
|
+
self.store.put('operations', oid, operation)
|
|
775
|
+
destination.mkdir(parents=True, exist_ok=True)
|
|
776
|
+
operation['destination_identity'] = self._restore_directory_identity(destination)
|
|
777
|
+
self.store.put('operations', oid, operation)
|
|
778
|
+
if any(destination.iterdir()):
|
|
779
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'Work appeared at the restore destination; it was preserved.', {'operation_id': oid})
|
|
780
|
+
if checkpoint['git']:
|
|
781
|
+
git(destination, 'init', '--quiet')
|
|
782
|
+
git(destination, 'config', 'user.name', 'TaskCarry synthetic restore')
|
|
783
|
+
git(destination, 'config', 'user.email', 'restore@example.invalid')
|
|
784
|
+
for record in checkpoint['files']:
|
|
785
|
+
if record['head']:
|
|
786
|
+
data = contents[(record['path'], 'head')]
|
|
787
|
+
blob_oid = git(destination, 'hash-object', '-w', '--stdin', input_bytes=data).stdout.decode().strip()
|
|
788
|
+
git(destination, 'update-index', '--add', '--cacheinfo', record['head']['mode'], blob_oid, record['path'])
|
|
789
|
+
git(destination, 'commit', '--allow-empty', '--quiet', '-m',
|
|
790
|
+
'TaskCarry synthetic restore baseline; original HEAD: ' + str(checkpoint['original_head']))
|
|
791
|
+
for record in checkpoint['files']:
|
|
792
|
+
if record['index']:
|
|
793
|
+
blob_oid = git(destination, 'hash-object', '-w', '--stdin', input_bytes=contents[(record['path'], 'index')]).stdout.decode().strip()
|
|
794
|
+
git(destination, 'update-index', '--add', '--cacheinfo', record['index']['mode'], blob_oid, record['path'])
|
|
795
|
+
else:
|
|
796
|
+
git(destination, 'update-index', '--force-remove', '--', record['path'])
|
|
797
|
+
for record in checkpoint['files']:
|
|
798
|
+
if record['worktree']:
|
|
799
|
+
if self._restore_directory_identity(destination) != operation['destination_identity']:
|
|
800
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restore destination was replaced.')
|
|
801
|
+
target = validate_relative_path(destination, record['path'])
|
|
802
|
+
target.parent.mkdir(parents=True, exist_ok=True)
|
|
803
|
+
with target.open('xb') as stream:
|
|
804
|
+
stream.write(contents[(record['path'], 'worktree')])
|
|
805
|
+
stream.flush()
|
|
806
|
+
os.fsync(stream.fileno())
|
|
807
|
+
if os.name != 'nt':
|
|
808
|
+
target.chmod(0o755 if record['worktree']['mode'] == '100755' else 0o644)
|
|
809
|
+
fingerprint = self._restore_effect(checkpoint, destination)
|
|
810
|
+
if fingerprint['directory_identity'] != operation['destination_identity']:
|
|
811
|
+
raise GovernanceError('RESTORE_REVIEW_REQUIRED', 'The restore destination was replaced.')
|
|
812
|
+
operation.update(status='EFFECT_APPLIED', effect_state='VERIFIED', effect_fingerprint=fingerprint,
|
|
813
|
+
effect_sha256=self._restore_digest(fingerprint))
|
|
814
|
+
self.store.put('operations', oid, operation)
|
|
815
|
+
return self._restore_finalize(checkpoint, destination, operation)
|
|
816
|
+
|
|
817
|
+
def artifact(self, task_id, path, role='input', backup=None, decision=None):
|
|
818
|
+
if decision not in (None, 'ignore', 'dismiss', 'no_backup_needed', 'retain'):
|
|
819
|
+
raise GovernanceError('INVALID_DECISION', 'Artifact decision must be ignore, dismiss, no_backup_needed or retain.')
|
|
820
|
+
self._task(task_id)
|
|
821
|
+
raw = Path(path).expanduser().absolute()
|
|
822
|
+
if any(part.casefold() in ('.git', '.taskcarry') for part in raw.parts):
|
|
823
|
+
raise GovernanceError('RESERVED_PATH', 'Git and governance metadata cannot become artifacts.')
|
|
824
|
+
# Artifact reads are explicitly named, but metadata/secret/link exclusions still apply.
|
|
825
|
+
for ancestor in (raw, *raw.parents):
|
|
826
|
+
if _linked(ancestor):
|
|
827
|
+
raise GovernanceError('SYMLINK_PATH', 'Artifact paths cannot traverse symbolic links or junctions.')
|
|
828
|
+
validate_relative_path(raw.parent, raw.name, allow_missing=False)
|
|
829
|
+
digest = hashlib.sha256()
|
|
830
|
+
before = raw.stat()
|
|
831
|
+
with raw.open('rb') as stream:
|
|
832
|
+
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
|
833
|
+
digest.update(block)
|
|
834
|
+
after = raw.stat()
|
|
835
|
+
if (before.st_size, before.st_mtime_ns) != (after.st_size, after.st_mtime_ns):
|
|
836
|
+
raise GovernanceError('SOURCE_CHANGED', 'The artifact changed during hashing.')
|
|
837
|
+
checksum = digest.hexdigest()
|
|
838
|
+
artifact_id = 'ar-' + digest_bytes((task_id + '\x00' + str(raw.resolve())).encode())[:32]
|
|
839
|
+
old = self.store.get('artifacts', artifact_id)
|
|
840
|
+
if backup is None and old and old['sha256'] == checksum:
|
|
841
|
+
backup = old.get('backup')
|
|
842
|
+
verified = False
|
|
843
|
+
backup_path = None
|
|
844
|
+
if backup is not None:
|
|
845
|
+
backup_path = Path(backup).expanduser().absolute()
|
|
846
|
+
if backup_path.resolve() == raw.resolve() or backup_path.exists() and os.path.samefile(backup_path, raw):
|
|
847
|
+
raise GovernanceError('BACKUP_NOT_INDEPENDENT', 'The original file is not an independent backup.')
|
|
848
|
+
for ancestor in (backup_path, *backup_path.parents):
|
|
849
|
+
if _linked(ancestor):
|
|
850
|
+
raise GovernanceError('SYMLINK_PATH', 'Backup paths cannot traverse symbolic links or junctions.')
|
|
851
|
+
validate_relative_path(backup_path.parent, backup_path.name, allow_missing=True)
|
|
852
|
+
if backup_path.is_file():
|
|
853
|
+
backup_stat = backup_path.stat()
|
|
854
|
+
backup_digest = hashlib.sha256()
|
|
855
|
+
with backup_path.open('rb') as stream:
|
|
856
|
+
for block in iter(lambda: stream.read(1024 * 1024), b''):
|
|
857
|
+
backup_digest.update(block)
|
|
858
|
+
backup_after = backup_path.stat()
|
|
859
|
+
verified = (backup_digest.hexdigest() == checksum and backup_stat.st_size == before.st_size
|
|
860
|
+
and (backup_stat.st_size, backup_stat.st_mtime_ns) == (backup_after.st_size, backup_after.st_mtime_ns))
|
|
861
|
+
with self.store.transaction():
|
|
862
|
+
old = self.store.get('artifacts', artifact_id)
|
|
863
|
+
same = old and old['sha256'] == checksum
|
|
864
|
+
result = {'artifact_id': artifact_id, 'task_id': task_id, 'path': str(raw.resolve()), 'role': role,
|
|
865
|
+
'sha256': checksum, 'size': before.st_size, 'decision': decision if decision is not None else old.get('decision') if same else None,
|
|
866
|
+
'backup': str(backup_path) if backup_path else None, 'backup_verified': verified,
|
|
867
|
+
'backup_available': bool(backup_path and backup_path.is_file()),
|
|
868
|
+
'updated_at': now(), 'content_changed': bool(old and not same)}
|
|
869
|
+
self.store.put('artifacts', artifact_id, result)
|
|
870
|
+
self.store.event('artifact_observed', result)
|
|
871
|
+
return result
|
|
872
|
+
|
|
873
|
+
def experience(self, rule_id, code, operation, action, task_id=None, version='1', enabled=True):
|
|
874
|
+
rule_id = _id(rule_id, 'Rule ID')
|
|
875
|
+
if action not in ('verify_and_finalize', 'refresh_plan'):
|
|
876
|
+
raise GovernanceError('UNSUPPORTED_EXPERIENCE_ACTION', 'Experience may only select a defined recovery action, never arbitrary code.')
|
|
877
|
+
if task_id:
|
|
878
|
+
self._task(task_id)
|
|
879
|
+
if not isinstance(enabled, bool):
|
|
880
|
+
raise GovernanceError('INVALID_EXPERIENCE', 'Experience enabled must be a boolean.')
|
|
881
|
+
result = {'rule_id': rule_id, 'code': code, 'operation': operation, 'action': action,
|
|
882
|
+
'task_id': task_id, 'version': str(version), 'enabled': enabled, 'updated_at': now()}
|
|
883
|
+
with self.store.transaction():
|
|
884
|
+
self.store.put('experience', rule_id, result)
|
|
885
|
+
self.store.event('experience_registered', result)
|
|
886
|
+
return result
|
|
887
|
+
|
|
888
|
+
def match_experience(self, code, operation, task_id=None):
|
|
889
|
+
matches = self._experience_matches(self.store.list('experience'), code, operation, task_id)
|
|
890
|
+
return {'matches': matches, 'code': code, 'operation': operation, 'task_id': task_id,
|
|
891
|
+
'execution': 'A match is a candidate action; the executor must verify current evidence before applying it.'}
|
|
892
|
+
|
|
893
|
+
@staticmethod
|
|
894
|
+
def _experience_matches(rules, code, operation, task_id):
|
|
895
|
+
return [r for r in rules if r['enabled'] and r['version'] == '1'
|
|
896
|
+
and r['code'] == code and r['operation'] == operation and r['task_id'] in (None, task_id)]
|