taskcarry 0.3.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- taskcarry/__init__.py +3 -0
- taskcarry/__main__.py +4 -0
- taskcarry/adapter_contracts.py +166 -0
- taskcarry/agy_turns.py +282 -0
- taskcarry/api.py +111 -0
- taskcarry/board.py +313 -0
- taskcarry/board_assets/board.css +1087 -0
- taskcarry/board_assets/board.js +1187 -0
- taskcarry/board_assets/browse.js +214 -0
- taskcarry/board_assets/index.html +43 -0
- taskcarry/board_assets/taskcarry-icon.ico +0 -0
- taskcarry/board_assets/taskcarry-mark.svg +28 -0
- taskcarry/board_data.py +466 -0
- taskcarry/chat_joins.py +157 -0
- taskcarry/cli.py +119 -0
- taskcarry/codex_capture.py +184 -0
- taskcarry/codex_host.py +293 -0
- taskcarry/collaboration_exchange.py +316 -0
- taskcarry/connection.py +159 -0
- taskcarry/continuity.py +300 -0
- taskcarry/contracts.py +165 -0
- taskcarry/conversation_capture.py +669 -0
- taskcarry/core.py +896 -0
- taskcarry/cycle_contracts.py +73 -0
- taskcarry/discovery.py +434 -0
- taskcarry/discovery_contracts.py +52 -0
- taskcarry/exchange_contracts.py +67 -0
- taskcarry/exchange_endpoint.py +377 -0
- taskcarry/exchange_packets.py +142 -0
- taskcarry/experience_contracts.py +129 -0
- taskcarry/experience_exchange.py +214 -0
- taskcarry/experience_notes.py +433 -0
- taskcarry/experience_storage.py +125 -0
- taskcarry/experience_tools.py +26 -0
- taskcarry/feishu/__init__.py +1 -0
- taskcarry/feishu/display.py +122 -0
- taskcarry/feishu/project_watch.py +145 -0
- taskcarry/feishu/review_sets.py +80 -0
- taskcarry/feishu/sender.py +42 -0
- taskcarry/feishu/subscription.py +193 -0
- taskcarry/feishu/windows_agent.py +287 -0
- taskcarry/feishu/windows_secret.py +34 -0
- taskcarry/gitops.py +170 -0
- taskcarry/governance.py +88 -0
- taskcarry/governance_cycle.py +775 -0
- taskcarry/identification.py +82 -0
- taskcarry/integration.py +663 -0
- taskcarry/maintenance.py +118 -0
- taskcarry/mcp.py +183 -0
- taskcarry/member_join.py +184 -0
- taskcarry/member_routing.py +145 -0
- taskcarry/onboarding.py +272 -0
- taskcarry/onboarding_complete.py +252 -0
- taskcarry/path_batches.py +19 -0
- taskcarry/preservation.py +257 -0
- taskcarry/project_collaboration.py +453 -0
- taskcarry/project_history.py +166 -0
- taskcarry/project_identity.py +51 -0
- taskcarry/project_recovery.py +824 -0
- taskcarry/recovery_contracts.py +25 -0
- taskcarry/recovery_files.py +153 -0
- taskcarry/recovery_git.py +234 -0
- taskcarry/remote_capture.py +89 -0
- taskcarry/remote_transfer.py +356 -0
- taskcarry/role_connection.py +215 -0
- taskcarry/setup.py +597 -0
- taskcarry/shared_workbench.py +480 -0
- taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
- taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
- taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
- taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
- taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
- taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
- taskcarry/source_review_set.py +80 -0
- taskcarry/state_format.py +47 -0
- taskcarry/store.py +472 -0
- taskcarry/task_context.py +141 -0
- taskcarry/text_handback.py +98 -0
- taskcarry/transfer_contracts.py +18 -0
- taskcarry/updates.py +351 -0
- taskcarry/workbench.py +625 -0
- taskcarry/workbench_contracts.py +32 -0
- taskcarry/workbuddy_capture.py +451 -0
- taskcarry/workbuddy_setup.py +212 -0
- taskcarry/worker_channel.py +859 -0
- taskcarry/worker_contracts.py +190 -0
- taskcarry/worker_storage.py +60 -0
- taskcarry/worker_tools.py +111 -0
- taskcarry-0.3.2.dist-info/METADATA +203 -0
- taskcarry-0.3.2.dist-info/RECORD +105 -0
- taskcarry-0.3.2.dist-info/WHEEL +5 -0
- taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
- taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
- taskcarry-0.3.2.dist-info/top_level.txt +2 -0
- taskcarry_https/__init__.py +1 -0
- taskcarry_https/consent.py +207 -0
- taskcarry_https/reader.py +132 -0
- taskcarry_https/review.py +116 -0
- taskcarry_https/server.py +163 -0
- taskcarry_https/team.py +335 -0
- taskcarry_https/team_host.py +109 -0
- taskcarry_https/web_host.py +82 -0
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Standalone schemas for bounded governance evidence tools."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def _string(description='', **values):
|
|
5
|
+
return {'type': 'string', 'description': description, **values}
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def _object(properties=None, required=()):
|
|
9
|
+
return {'type': 'object', 'properties': properties or {}, 'required': list(required), 'additionalProperties': False}
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def _integer(description, minimum=1, maximum=100):
|
|
13
|
+
return {'type': 'integer', 'description': description, 'minimum': minimum, 'maximum': maximum}
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
SCHEMAS = {
|
|
17
|
+
'cycle': _object({
|
|
18
|
+
'action': _string(enum=['list', 'status', 'start', 'resume', 'effect_plan', 'effect_result',
|
|
19
|
+
'source', 'health', 'question_check', 'question_delivered',
|
|
20
|
+
'question_response', 'report_delivered', 'join_inbox', 'join_absorb', 'finish']),
|
|
21
|
+
'cycle_id': _string('Original finite cycle identity.'),
|
|
22
|
+
'owner': _string('Original owner; for project chat intake use the original governance thread ID and include chat-joins in scope.'),
|
|
23
|
+
'task_id': _string('Existing task; required at start, never a new task authority.'),
|
|
24
|
+
'scope': {'type': 'array', 'items': _string(), 'minItems': 1, 'maxItems': 100, 'uniqueItems': True,
|
|
25
|
+
'description': 'Exact shared resource identities, immutable for this cycle; required at start/resume.'},
|
|
26
|
+
'request_id': _string('Immutable idempotency key for evidence mutations, required after start/resume.'),
|
|
27
|
+
'data': {'type': 'object', 'additionalProperties': True,
|
|
28
|
+
'description': 'Action payload. effect_plan: effect_id/kind/resource/expected. effect_result: effect_id/outcome(confirmed,rejected,deferred,failed)/evidence_ref/statement. source: source_id/source_revision/phase(observed,understood,published,consumed)/evidence_ref/statement and target for published/consumed. health: dimension/status/observed_at/freshness_seconds/evidence_ref. question_check: question_id and optional local_date. question_delivered/report_delivered: question_id or report_id, receipt_ref/delivered_at/utc_offset_minutes/local_date; question may set max_distinct_dates (default 2). question_response: question_id/receipt_ref/statement. finish: state(completed,waiting)/next_step.'},
|
|
29
|
+
'limit': _integer('Maximum list records per page.'), 'cursor': _string('Opaque list cursor.'),
|
|
30
|
+
}, ('action',)),
|
|
31
|
+
'facts': _object({
|
|
32
|
+
'action': _string(enum=['get', 'list', 'history', 'record']),
|
|
33
|
+
'fact_id': _string('Stable fact identity within its source; required except for list.'),
|
|
34
|
+
'source_id': _string('Stable source namespace; defaults to the project logical identity.'),
|
|
35
|
+
'source_revision': _string('Exact reviewed source revision; required for record.'),
|
|
36
|
+
'task_id': _string('Existing task; required for record.'),
|
|
37
|
+
'kind': _string(enum=['decision', 'artifact', 'relationship', 'alias', 'status']),
|
|
38
|
+
'statement': _string('Retained source statement, not an implicit AI inference.'),
|
|
39
|
+
'evidence': _object({'reference': _string(), 'summary': _string()}, ('reference', 'summary')),
|
|
40
|
+
'judgment': _object({'statement': _string(), 'basis': _string()}, ('statement', 'basis')),
|
|
41
|
+
'relations': {'type': 'array', 'maxItems': 100, 'items': _object({
|
|
42
|
+
'source_id': _string(), 'fact_id': _string(), 'relation': _string()}, ('source_id', 'fact_id', 'relation'))},
|
|
43
|
+
'aliases': {'type': 'array', 'items': _string(), 'maxItems': 100, 'uniqueItems': True},
|
|
44
|
+
'standing': _string(enum=['current', 'superseded', 'historical', 'disputed']),
|
|
45
|
+
'expected_revision': _integer('Current fact revision required when replacing content.', 1, 2147483647),
|
|
46
|
+
'limit': _integer('Maximum facts or history records per page.'), 'cursor': _string('Opaque selection cursor.'),
|
|
47
|
+
}, ('action',)),
|
|
48
|
+
'source_scan': _object({
|
|
49
|
+
'action': _string(enum=['register', 'registry', 'start', 'status', 'page']),
|
|
50
|
+
'source_id': _string('Stable source namespace, not an automatically discovered project.'),
|
|
51
|
+
'root': _string('Existing explicitly authorized local metadata source; required for register.'),
|
|
52
|
+
'authorization_ref': _string('User or policy authorization reference for this root.'),
|
|
53
|
+
'exclusions': {'type': 'array', 'items': _string(), 'maxItems': 100,
|
|
54
|
+
'description': 'Relative excluded subtrees; .git and .taskcarry are always excluded.'},
|
|
55
|
+
'expected_revision': _integer('Current registration revision required for configuration changes.', 1, 2147483647),
|
|
56
|
+
'scan_id': _string('Finite scan identity, required for start/status/page.'),
|
|
57
|
+
'cursor': _string('Exact next_cursor returned by start/page; repeated cursors reuse the retained page.'),
|
|
58
|
+
'max_entries': _integer('Processed entries per page; default 200.', 1, 1000),
|
|
59
|
+
'max_directory_entries': _integer('Bounded directory name snapshot; oversized directories are incomplete.', 1, 10000),
|
|
60
|
+
'max_directories': _integer('Directories per scan; default 1000.', 1, 2000),
|
|
61
|
+
'max_total_entries': _integer('Entries per scan; default 100000.', 1, 100000),
|
|
62
|
+
}, ('action', 'source_id')),
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
DESCRIPTIONS = {
|
|
66
|
+
'cycle': 'Record finite governance cycles, actual effects, source phases and delivery receipts over existing tasks. Frozen owner/resource reservations survive interruption; ordinary calls hold OS locks only during the call. The Python cycle_session context holds real locks for a whole live process session. No effect, scheduling, delivery or acceptance is performed by this tool.',
|
|
67
|
+
'facts': 'Read or retain source-qualified decisions, artifacts and relationships with immutable history and revision CAS. Source evidence and AI interpretation remain distinct; aliases do not merge sources or tasks automatically. Reads are bounded and do not change project state.',
|
|
68
|
+
'source_scan': 'Register an authorized local root and enumerate metadata through repeatable bounded pages. Sources are never written and file bodies are never read. Exclusions, budgets, directory watermarks and explicit incomplete states prevent partial scans from becoming deletion claims.',
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
SCHEMAS['cycle']['properties']['data']['description'] += (
|
|
72
|
+
' join_inbox: queue (new or pending_report), read all pages; absorb each page before advancing or combine by join_id. join_absorb: observation_id/source_revision '
|
|
73
|
+
'from new. During report_delivered include optional join_ids for the pending joins in the actual report.')
|
taskcarry/discovery.py
ADDED
|
@@ -0,0 +1,434 @@
|
|
|
1
|
+
"""Resumable metadata inventory without creating a governance database.
|
|
2
|
+
|
|
3
|
+
The caller supplies authorized index pages and AI candidate groups. Nothing in
|
|
4
|
+
this module scans a host, executes source text, reads chat bodies or accepts a
|
|
5
|
+
project. Immutable revisions make interrupted writes inspectable and repeatable.
|
|
6
|
+
"""
|
|
7
|
+
from contextlib import contextmanager
|
|
8
|
+
import hashlib
|
|
9
|
+
import json
|
|
10
|
+
import os
|
|
11
|
+
from pathlib import Path
|
|
12
|
+
import re
|
|
13
|
+
import tempfile
|
|
14
|
+
|
|
15
|
+
from .discovery_contracts import DRAFT, PLAN
|
|
16
|
+
from .store import GovernanceError, _linked
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
MAX_BYTES = 512 * 1024
|
|
20
|
+
MAX_REVISIONS = 4096
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def encoded(value):
|
|
24
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(',', ':'),
|
|
25
|
+
allow_nan=False).encode('utf-8')
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def fingerprint(value):
|
|
29
|
+
return hashlib.sha256(encoded(value)).hexdigest()
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def fail(code, message, details=None):
|
|
33
|
+
raise GovernanceError('DISCOVERY_' + code, message, details)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def check_text(value):
|
|
37
|
+
if isinstance(value, str):
|
|
38
|
+
if not value.strip() or len(value) > 2048 or '\0' in value:
|
|
39
|
+
fail('BOUNDS', 'Metadata strings must be nonempty, NUL-free and at most 2048 characters.')
|
|
40
|
+
elif isinstance(value, dict):
|
|
41
|
+
for item in value.values():
|
|
42
|
+
check_text(item)
|
|
43
|
+
elif isinstance(value, list):
|
|
44
|
+
for item in value:
|
|
45
|
+
check_text(item)
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def identity(value):
|
|
49
|
+
if not isinstance(value, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,63}', value):
|
|
50
|
+
fail('ID', 'Use a 1-64 character ID containing letters, digits, underscores and hyphens.')
|
|
51
|
+
if value.upper() in {'CON', 'PRN', 'AUX', 'NUL', *(f'COM{n}' for n in range(1, 10)), *(f'LPT{n}' for n in range(1, 10))}:
|
|
52
|
+
fail('ID', 'Use a portable ID rather than a reserved device name.')
|
|
53
|
+
return value
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def member_key(value):
|
|
57
|
+
return value['source_id'], value['thread_id']
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def publish_file(temporary, path):
|
|
61
|
+
# Windows rename is atomic and refuses an existing destination. POSIX
|
|
62
|
+
# rename replaces, so use atomic hardlink publication there instead.
|
|
63
|
+
if os.name == 'nt':
|
|
64
|
+
os.rename(temporary, path)
|
|
65
|
+
else:
|
|
66
|
+
os.link(temporary, path)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def normalize(draft):
|
|
70
|
+
from .contracts import validate
|
|
71
|
+
try:
|
|
72
|
+
validate(draft, DRAFT, 'draft')
|
|
73
|
+
except ValueError as error:
|
|
74
|
+
fail('ARGUMENT', str(error))
|
|
75
|
+
check_text(draft)
|
|
76
|
+
if len(encoded(draft)) > MAX_BYTES:
|
|
77
|
+
fail('BOUNDS', 'Keep the metadata draft within 512 KiB; continue another bounded discovery if needed.')
|
|
78
|
+
result = json.loads(encoded(draft))
|
|
79
|
+
source_ids, threads = set(), {}
|
|
80
|
+
for source in result['sources']:
|
|
81
|
+
sid = identity(source['source_id'])
|
|
82
|
+
if sid in source_ids:
|
|
83
|
+
fail('DUPLICATE', 'Source IDs must be unique; equal titles do not identify a project.')
|
|
84
|
+
source_ids.add(sid)
|
|
85
|
+
pages, cursors, expected = [], {}, None
|
|
86
|
+
for page in source['pages']:
|
|
87
|
+
cursor = page['cursor']
|
|
88
|
+
if cursor in cursors:
|
|
89
|
+
if cursors[cursor] != page:
|
|
90
|
+
fail('PAGE_CONFLICT', 'A repeated cursor has different content; retain the old scan and use a new source ID.')
|
|
91
|
+
continue
|
|
92
|
+
if cursor != expected or (pages and expected is None):
|
|
93
|
+
fail('CURSOR', 'Pages must start at null and follow the preceding next_cursor without gaps or cycles.')
|
|
94
|
+
if page['next_cursor'] is not None and (page['next_cursor'] == cursor or page['next_cursor'] in cursors):
|
|
95
|
+
fail('CURSOR', 'A pagination cursor cycle cannot prove source coverage.')
|
|
96
|
+
cursors[cursor] = page
|
|
97
|
+
expected = page['next_cursor']
|
|
98
|
+
pages.append(page)
|
|
99
|
+
for thread in page['threads']:
|
|
100
|
+
key = sid, thread['thread_id']
|
|
101
|
+
if key in threads and threads[key] != thread:
|
|
102
|
+
fail('THREAD_CONFLICT', 'The same source/thread identity changed within this scan; use a fresh source ID.')
|
|
103
|
+
threads[key] = thread
|
|
104
|
+
source['pages'] = pages
|
|
105
|
+
if source['coverage'] == 'exhausted' and (not pages or expected is not None or source['archive_scope'] == 'unknown'):
|
|
106
|
+
fail('COVERAGE', 'Exhausted means the explicitly selected active or archived index ended at a null cursor.')
|
|
107
|
+
if source['coverage'] == 'unavailable' and pages:
|
|
108
|
+
fail('COVERAGE', 'An unavailable source has no inspected pages; retain partial coverage for interrupted reads.')
|
|
109
|
+
if len(threads) > 500:
|
|
110
|
+
fail('BOUNDS', 'A discovery draft supports at most 500 distinct source-qualified threads.')
|
|
111
|
+
candidates = {}
|
|
112
|
+
for candidate in result['candidates']:
|
|
113
|
+
cid = identity(candidate['candidate_id'])
|
|
114
|
+
if cid in candidates:
|
|
115
|
+
fail('DUPLICATE', 'Candidate IDs must be unique even when display names match.')
|
|
116
|
+
members = [member_key(m) for m in candidate['members']]
|
|
117
|
+
if len(set(members)) != len(members) or any(m not in threads for m in members):
|
|
118
|
+
fail('MEMBER', 'Every candidate member must be a distinct source-qualified discovered thread.')
|
|
119
|
+
candidates[cid] = candidate
|
|
120
|
+
selection = result.get('selection')
|
|
121
|
+
selected_hash = None
|
|
122
|
+
if selection:
|
|
123
|
+
candidate = candidates.get(selection['candidate_id'])
|
|
124
|
+
if not candidate:
|
|
125
|
+
fail('SELECTION', 'Select an existing AI-proposed candidate after user review.')
|
|
126
|
+
selected_hash = fingerprint({'candidate': candidate,
|
|
127
|
+
'threads': [{'source_id': m['source_id'], **threads[member_key(m)]}
|
|
128
|
+
for m in candidate['members']]})
|
|
129
|
+
if result.get('onboarding') and not selection:
|
|
130
|
+
fail('SELECTION', 'Choose a project before linking its later onboarding.')
|
|
131
|
+
return result, selected_hash, len(threads)
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
class Discovery:
|
|
135
|
+
def __init__(self, project):
|
|
136
|
+
raw = Path(project).expanduser().absolute()
|
|
137
|
+
if any(_linked(p) for p in (raw, *raw.parents)) or not raw.is_dir():
|
|
138
|
+
fail('PATH', 'Use an existing directory without symlink or reparse-point ancestors.')
|
|
139
|
+
self.root = raw.resolve()
|
|
140
|
+
|
|
141
|
+
def safe(self, relative, directory=False, pending_link=False):
|
|
142
|
+
path = self.root / relative
|
|
143
|
+
for candidate in (path, *path.parents):
|
|
144
|
+
if candidate == self.root.parent:
|
|
145
|
+
break
|
|
146
|
+
if _linked(candidate):
|
|
147
|
+
fail('PATH', 'Discovery refuses symlinks and reparse points in managed paths.')
|
|
148
|
+
if candidate != path and candidate.exists() and not candidate.is_dir():
|
|
149
|
+
fail('CONFLICT', 'A discovery parent path is an existing file and was preserved.')
|
|
150
|
+
if not path.resolve().is_relative_to(self.root):
|
|
151
|
+
fail('PATH', 'Discovery metadata must stay within its selected governance directory.')
|
|
152
|
+
if path.exists():
|
|
153
|
+
if (directory and not path.is_dir()) or (not directory and not path.is_file()):
|
|
154
|
+
fail('CONFLICT', 'An existing managed path has a different file type; it was preserved.')
|
|
155
|
+
if not directory and path.stat().st_nlink > 1:
|
|
156
|
+
# If the process died between no-replace publication and
|
|
157
|
+
# unlinking its temporary name, both local names are the same
|
|
158
|
+
# immutable revision. Permit only this exact two-link effect.
|
|
159
|
+
info = path.stat()
|
|
160
|
+
matches = []
|
|
161
|
+
if pending_link and info.st_nlink == 2:
|
|
162
|
+
for other in path.parent.iterdir():
|
|
163
|
+
if other != path and not _linked(other) and other.is_file():
|
|
164
|
+
same = (other.stat().st_dev, other.stat().st_ino) == (info.st_dev, info.st_ino)
|
|
165
|
+
pair = ((re.fullmatch(r'[0-9]{8}\.json', path.name) and re.fullmatch(r'\.taskcarry-discovery-[A-Za-z0-9_-]+\.tmp', other.name))
|
|
166
|
+
or (re.fullmatch(r'[0-9]{8}\.json', other.name) and re.fullmatch(r'\.taskcarry-discovery-[A-Za-z0-9_-]+\.tmp', path.name)))
|
|
167
|
+
if same and pair:
|
|
168
|
+
matches.append(other)
|
|
169
|
+
if len(matches) != 1:
|
|
170
|
+
fail('PATH', 'Discovery refuses multiply-linked metadata files outside its interrupted atomic publication.')
|
|
171
|
+
return path
|
|
172
|
+
|
|
173
|
+
def root_identity(self):
|
|
174
|
+
info = self.root.stat()
|
|
175
|
+
# Host MCP clients may use IEEE-754 JSON numbers; preserve large file
|
|
176
|
+
# IDs exactly rather than losing bits during a plan round trip.
|
|
177
|
+
return {'device': str(info.st_dev), 'inode': str(info.st_ino)}
|
|
178
|
+
|
|
179
|
+
def state_binding(self, writable=False):
|
|
180
|
+
from .core import Core
|
|
181
|
+
result = Core.identify(self.root)
|
|
182
|
+
if result['state'] == 'uninitialized':
|
|
183
|
+
return None
|
|
184
|
+
if result['state'] != 'compatible':
|
|
185
|
+
fail('STATE', 'Inspect existing governance metadata before saving a discovery draft.', result)
|
|
186
|
+
if writable and result['source'].get('writer_state') == 'standby':
|
|
187
|
+
raise GovernanceError('RECOVERY_STANDBY', 'A restored standby cannot save discovery revisions before writer activation.')
|
|
188
|
+
return {k: result['source'].get(k) for k in ('source_id', 'replica_id', 'identity_scope', 'writer_state')}
|
|
189
|
+
|
|
190
|
+
def current(self, discovery_id):
|
|
191
|
+
relative = '.taskcarry-onboarding/discovery/' + identity(discovery_id)
|
|
192
|
+
directory = self.safe(relative, directory=True)
|
|
193
|
+
if not directory.exists():
|
|
194
|
+
return None
|
|
195
|
+
entries = []
|
|
196
|
+
for index, path in enumerate(directory.iterdir()):
|
|
197
|
+
if index >= MAX_REVISIONS * 2:
|
|
198
|
+
fail('BOUNDS', 'Discovery file enumeration exceeds its bounded limit.')
|
|
199
|
+
# A process crash can leave its own random temporary file. It is
|
|
200
|
+
# not a committed revision and is never adopted or deleted here.
|
|
201
|
+
if re.fullmatch(r'\.taskcarry-discovery-[A-Za-z0-9_-]+\.tmp', path.name):
|
|
202
|
+
self.safe(relative + '/' + path.name, pending_link=True)
|
|
203
|
+
continue
|
|
204
|
+
if not re.fullmatch(r'[0-9]{8}\.json', path.name):
|
|
205
|
+
fail('CONFLICT', 'An unrecognized discovery file was preserved; inspect it before proceeding.')
|
|
206
|
+
entries.append(path.name)
|
|
207
|
+
if len(entries) > MAX_REVISIONS:
|
|
208
|
+
fail('BOUNDS', 'Discovery revision history exceeds its bounded limit.')
|
|
209
|
+
if not entries:
|
|
210
|
+
return None
|
|
211
|
+
entries.sort()
|
|
212
|
+
if entries != [f'{n:08d}.json' for n in range(1, len(entries) + 1)]:
|
|
213
|
+
fail('HISTORY', 'Discovery revision history has a gap; do not reinterpret an older selection as current.')
|
|
214
|
+
path = self.safe(relative + '/' + entries[-1], pending_link=True)
|
|
215
|
+
if path.stat().st_size > MAX_BYTES + 16384:
|
|
216
|
+
fail('BOUNDS', 'The discovery record exceeds its bounded size.')
|
|
217
|
+
try:
|
|
218
|
+
record = json.loads(path.read_bytes())
|
|
219
|
+
plan = record['plan']
|
|
220
|
+
self.check_plan(plan)
|
|
221
|
+
if (set(record) != {'format', 'revision', 'plan'} or record['format'] != 1
|
|
222
|
+
or record['revision'] != len(entries) or plan['expected_revision'] != len(entries) - 1
|
|
223
|
+
or plan['discovery_id'] != discovery_id):
|
|
224
|
+
raise ValueError('Invalid revision record')
|
|
225
|
+
except (ValueError, KeyError, TypeError) as error:
|
|
226
|
+
fail('RECORD', 'The current discovery record is invalid and was preserved.', str(error))
|
|
227
|
+
return record
|
|
228
|
+
|
|
229
|
+
def check_plan(self, plan):
|
|
230
|
+
from .contracts import validate
|
|
231
|
+
try:
|
|
232
|
+
validate(plan, PLAN, 'plan')
|
|
233
|
+
except ValueError as error:
|
|
234
|
+
fail('PLAN', str(error))
|
|
235
|
+
check_text(plan)
|
|
236
|
+
if len(encoded(plan)) > MAX_BYTES + 8192:
|
|
237
|
+
fail('BOUNDS', 'The complete plan exceeds its bounded size.')
|
|
238
|
+
body = {k: v for k, v in plan.items() if k != 'plan_id'}
|
|
239
|
+
if plan['plan_id'] != 'discovery-' + fingerprint(body):
|
|
240
|
+
fail('PLAN', 'Execute the complete unchanged plan returned by discovery plan.')
|
|
241
|
+
normalized, selected_hash, _ = normalize(plan['draft'])
|
|
242
|
+
if normalized != plan['draft'] or selected_hash != plan['selection_fingerprint']:
|
|
243
|
+
fail('PLAN', 'The planned metadata or selected scope fingerprint does not match.')
|
|
244
|
+
|
|
245
|
+
def check_binding(self, plan):
|
|
246
|
+
if (plan['root'] != str(self.root) or plan['root_identity'] != self.root_identity()
|
|
247
|
+
or plan['state_binding'] != self.state_binding(writable=True)):
|
|
248
|
+
fail('BINDING', 'The selected root, local replica or initialization state changed; prepare a new local plan.')
|
|
249
|
+
|
|
250
|
+
def link(self, draft, selected_hash):
|
|
251
|
+
link = draft.get('onboarding')
|
|
252
|
+
if not link:
|
|
253
|
+
return None
|
|
254
|
+
from .core import Core
|
|
255
|
+
if link['selection_fingerprint'] != selected_hash:
|
|
256
|
+
fail('ONBOARDING', 'The onboarding link belongs to a different selected discovery scope.')
|
|
257
|
+
state = Core(self.root)
|
|
258
|
+
record = state.store.get('onboarding', identity(link['onboarding_id']))
|
|
259
|
+
if not record or record['scope_fingerprint'] != link['scope_fingerprint']:
|
|
260
|
+
fail('ONBOARDING', 'Read the actual onboarding and bind its current scope fingerprint.')
|
|
261
|
+
candidate = next(c for c in draft['candidates'] if c['candidate_id'] == draft['selection']['candidate_id'])
|
|
262
|
+
selected = {member_key(m) for m in candidate['members']}
|
|
263
|
+
mappings = link['windows']
|
|
264
|
+
if ({member_key(m) for m in mappings} != selected or len(mappings) != len(selected)
|
|
265
|
+
or len({m['window_thread_id'] for m in mappings}) != len(mappings)):
|
|
266
|
+
fail('ONBOARDING', 'Map every selected source/thread once to distinct actual onboarding windows.')
|
|
267
|
+
actual = {w['thread_id']: w['source_ref'] for w in record['scope']['windows']}
|
|
268
|
+
if any(actual.get(m['window_thread_id']) != m['source_ref'] for m in mappings):
|
|
269
|
+
fail('ONBOARDING', 'The mapped window and source reference must match actual onboarding scope.')
|
|
270
|
+
return {'onboarding_id': link['onboarding_id'], 'scope_fingerprint': record['scope_fingerprint'],
|
|
271
|
+
'binding_current': True, 'acceptance_inherited': False}
|
|
272
|
+
|
|
273
|
+
@contextmanager
|
|
274
|
+
def lock(self, discovery_id):
|
|
275
|
+
relative = '.taskcarry-onboarding/discovery'
|
|
276
|
+
directory = self.safe(relative, directory=True)
|
|
277
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
278
|
+
path = self.safe(relative + '/' + discovery_id + '.lock')
|
|
279
|
+
with path.open('a+b') as stream:
|
|
280
|
+
if os.name == 'nt':
|
|
281
|
+
import msvcrt
|
|
282
|
+
stream.seek(0, os.SEEK_END)
|
|
283
|
+
if stream.tell() == 0:
|
|
284
|
+
stream.write(b'0')
|
|
285
|
+
stream.flush()
|
|
286
|
+
stream.seek(0)
|
|
287
|
+
try:
|
|
288
|
+
msvcrt.locking(stream.fileno(), msvcrt.LK_NBLCK, 1)
|
|
289
|
+
except OSError as error:
|
|
290
|
+
fail('BUSY', 'Another process is saving this discovery; inspect status before retrying.', str(error))
|
|
291
|
+
else:
|
|
292
|
+
import fcntl
|
|
293
|
+
try:
|
|
294
|
+
fcntl.flock(stream.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
295
|
+
except OSError as error:
|
|
296
|
+
fail('BUSY', 'Another process is saving this discovery; inspect status before retrying.', str(error))
|
|
297
|
+
yield
|
|
298
|
+
|
|
299
|
+
def publish(self, relative, data):
|
|
300
|
+
path = self.safe(relative)
|
|
301
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
302
|
+
descriptor, temporary = tempfile.mkstemp(prefix='.taskcarry-discovery-', suffix='.tmp', dir=path.parent)
|
|
303
|
+
try:
|
|
304
|
+
with os.fdopen(descriptor, 'wb') as stream:
|
|
305
|
+
stream.write(data)
|
|
306
|
+
stream.flush()
|
|
307
|
+
os.fsync(stream.fileno())
|
|
308
|
+
# Atomic no-replace publication: never overwrite a user file, even
|
|
309
|
+
# if a non-cooperating writer ignores our advisory lock.
|
|
310
|
+
try:
|
|
311
|
+
publish_file(temporary, path)
|
|
312
|
+
except FileExistsError:
|
|
313
|
+
fail('CONFLICT', 'The revision destination appeared during saving; inspect its actual effect.')
|
|
314
|
+
if os.name != 'nt':
|
|
315
|
+
descriptor = os.open(path.parent, os.O_RDONLY)
|
|
316
|
+
try:
|
|
317
|
+
os.fsync(descriptor)
|
|
318
|
+
finally:
|
|
319
|
+
os.close(descriptor)
|
|
320
|
+
finally:
|
|
321
|
+
if os.path.exists(temporary):
|
|
322
|
+
os.unlink(temporary)
|
|
323
|
+
|
|
324
|
+
def report(self, discovery_id, record, effects=False, reused=False):
|
|
325
|
+
if not record:
|
|
326
|
+
return {'discovery_id': discovery_id, 'revision': 0, 'state': 'NOT_STARTED',
|
|
327
|
+
'effects_executed': False, 'control_initialized_by_discovery': False}
|
|
328
|
+
plan = record['plan']
|
|
329
|
+
draft, selected_hash, count = normalize(plan['draft'])
|
|
330
|
+
link = None
|
|
331
|
+
if draft.get('onboarding'):
|
|
332
|
+
try:
|
|
333
|
+
link = self.link(draft, selected_hash)
|
|
334
|
+
except GovernanceError as error:
|
|
335
|
+
link = {'binding_current': False, 'acceptance_inherited': False, 'error': {'code': error.code, 'message': error.message}}
|
|
336
|
+
local_binding = plan['root'] == str(self.root) and plan['root_identity'] == self.root_identity()
|
|
337
|
+
if local_binding and plan['state_binding'] is not None:
|
|
338
|
+
try:
|
|
339
|
+
local_binding = plan['state_binding'] == self.state_binding()
|
|
340
|
+
except GovernanceError:
|
|
341
|
+
local_binding = False
|
|
342
|
+
if link and not local_binding:
|
|
343
|
+
link = {'binding_current': False, 'acceptance_inherited': False,
|
|
344
|
+
'error': {'code': 'DISCOVERY_BINDING', 'message': 'Review this copied or changed local replica before using its historical onboarding link.'}}
|
|
345
|
+
return {'discovery_id': discovery_id, 'revision': record['revision'], 'fingerprint': fingerprint(record),
|
|
346
|
+
'state': 'REVIEW_REQUIRED' if not local_binding else 'SELECTED' if selected_hash else 'AWAITING_SELECTION' if draft['candidates'] else 'DISCOVERING',
|
|
347
|
+
'draft': draft, 'selection_fingerprint': selected_hash, 'distinct_threads': count,
|
|
348
|
+
'onboarding_link': link, 'local_binding_matches': local_binding,
|
|
349
|
+
'selection_current': bool(selected_hash and local_binding),
|
|
350
|
+
'effects_executed': effects, 'reused': reused, 'control_initialized_by_discovery': False,
|
|
351
|
+
'source_text_is_instruction': False, 'chat_bodies_read': False,
|
|
352
|
+
'coverage_scope': 'caller_supplied_index_pages_only', 'all_chats_verified': False,
|
|
353
|
+
'acceptance_inherited': False, 'native_acceptance_verified': False,
|
|
354
|
+
'next_step': 'Review the copied or changed local replica and obtain a fresh user selection before reading selected history.'
|
|
355
|
+
if not local_binding else 'Read only the user-selected sources, then prepare or resume their actual onboarding.'
|
|
356
|
+
if selected_hash else 'Continue saved source cursors and ask the user to choose an AI-proposed project.'}
|
|
357
|
+
|
|
358
|
+
def discovery(self, discovery_id, action='status', expected_revision=None, draft=None, plan=None):
|
|
359
|
+
identity(discovery_id)
|
|
360
|
+
if action == 'status':
|
|
361
|
+
if any(v is not None for v in (expected_revision, draft, plan)):
|
|
362
|
+
fail('ARGUMENT', 'Status only accepts discovery_id.')
|
|
363
|
+
return self.report(discovery_id, self.current(discovery_id))
|
|
364
|
+
if action == 'plan':
|
|
365
|
+
if plan is not None or expected_revision is None:
|
|
366
|
+
fail('ARGUMENT', 'Plan requires a complete bounded draft and the current expected_revision, initially zero.')
|
|
367
|
+
current = self.current(discovery_id)
|
|
368
|
+
revision = current['revision'] if current else 0
|
|
369
|
+
if expected_revision != revision or revision >= MAX_REVISIONS:
|
|
370
|
+
fail('CHANGED', 'Read discovery status before planning the next revision.', {'revision': revision})
|
|
371
|
+
normalized, selected_hash, _ = normalize(draft)
|
|
372
|
+
selection_guard = None
|
|
373
|
+
binding = self.state_binding()
|
|
374
|
+
if current:
|
|
375
|
+
previous = current['plan']
|
|
376
|
+
if previous['draft'].get('selection'):
|
|
377
|
+
selection_guard = {key: previous[key] for key in ('selection_fingerprint', 'root', 'root_identity', 'state_binding')}
|
|
378
|
+
selection_guard['confirmation_ref'] = previous['draft']['selection']['confirmation_ref']
|
|
379
|
+
else:
|
|
380
|
+
selection_guard = previous['selection_guard']
|
|
381
|
+
if (previous['root'] != str(self.root) or previous['root_identity'] != self.root_identity()
|
|
382
|
+
or (previous['state_binding'] is not None and previous['state_binding'] != self.state_binding())):
|
|
383
|
+
if normalized.get('onboarding') or (normalized.get('selection') and normalized['selection'].get('confirmation_ref') == previous['draft'].get('selection', {}).get('confirmation_ref')):
|
|
384
|
+
fail('BINDING', 'A copied discovery needs a fresh local user selection and a separately verified onboarding link.')
|
|
385
|
+
prior_sources = {s['source_id']: s for s in previous['draft']['sources']}
|
|
386
|
+
for source in normalized['sources']:
|
|
387
|
+
prior = prior_sources.pop(source['source_id'], None)
|
|
388
|
+
if prior and (source['label'] != prior['label'] or source['archive_scope'] != prior['archive_scope']
|
|
389
|
+
or source['pages'][:len(prior['pages'])] != prior['pages']):
|
|
390
|
+
fail('PAGE_CONFLICT', 'Retain already recorded pages; use a new source ID for a refreshed index.')
|
|
391
|
+
if prior_sources:
|
|
392
|
+
fail('PAGE_CONFLICT', 'Retain prior source coverage when continuing this discovery.')
|
|
393
|
+
new_selection = normalized.get('selection')
|
|
394
|
+
if selection_guard and new_selection:
|
|
395
|
+
same_scope = selection_guard['selection_fingerprint'] == selected_hash
|
|
396
|
+
same_local = (selection_guard['root'] == str(self.root) and selection_guard['root_identity'] == self.root_identity()
|
|
397
|
+
and (selection_guard['state_binding'] is None or selection_guard['state_binding'] == binding))
|
|
398
|
+
if (not same_scope or not same_local) and selection_guard['confirmation_ref'] == new_selection['confirmation_ref']:
|
|
399
|
+
fail('CONFIRMATION', 'A changed or copied selection needs a new user confirmation reference, including after an unselected draft.')
|
|
400
|
+
self.link(normalized, selected_hash)
|
|
401
|
+
body = {'format': 1, 'root': str(self.root), 'root_identity': self.root_identity(),
|
|
402
|
+
'state_binding': binding, 'discovery_id': discovery_id,
|
|
403
|
+
'expected_revision': revision, 'expected_fingerprint': fingerprint(current) if current else None,
|
|
404
|
+
'draft': normalized, 'selection_fingerprint': selected_hash, 'selection_guard': selection_guard}
|
|
405
|
+
result = {**body, 'plan_id': 'discovery-' + fingerprint(body)}
|
|
406
|
+
return {'plan': result, 'effects_executed': False, 'control_initialized_by_discovery': False,
|
|
407
|
+
'selection_fingerprint': selected_hash, 'acceptance_inherited': False}
|
|
408
|
+
if action != 'execute' or plan is None or expected_revision is not None or draft is not None:
|
|
409
|
+
fail('ARGUMENT', 'Execute only accepts discovery_id and the complete unchanged plan.')
|
|
410
|
+
self.check_plan(plan)
|
|
411
|
+
if discovery_id != plan['discovery_id']:
|
|
412
|
+
fail('PLAN', 'The plan belongs to a different discovery ID.')
|
|
413
|
+
self.check_binding(plan)
|
|
414
|
+
with self.lock(discovery_id):
|
|
415
|
+
self.check_binding(plan)
|
|
416
|
+
current = self.current(discovery_id)
|
|
417
|
+
if current and current['plan'] == plan:
|
|
418
|
+
return self.report(discovery_id, current, reused=True)
|
|
419
|
+
if ((current['revision'] if current else 0) != plan['expected_revision']
|
|
420
|
+
or (fingerprint(current) if current else None) != plan['expected_fingerprint']):
|
|
421
|
+
fail('CHANGED', 'The discovery changed after planning; read current status before proceeding.')
|
|
422
|
+
reviewed = self.discovery(discovery_id, 'plan', plan['expected_revision'], plan['draft'])['plan']
|
|
423
|
+
if reviewed != plan:
|
|
424
|
+
fail('PLAN', 'The plan no longer matches its current metadata, selection or local bindings.')
|
|
425
|
+
if current and all(current['plan'][key] == plan[key] for key in
|
|
426
|
+
('root', 'root_identity', 'state_binding', 'draft', 'selection_fingerprint')):
|
|
427
|
+
return self.report(discovery_id, current, reused=True)
|
|
428
|
+
record = {'format': 1, 'revision': plan['expected_revision'] + 1, 'plan': plan}
|
|
429
|
+
relative = f'.taskcarry-onboarding/discovery/{discovery_id}/{record["revision"]:08d}.json'
|
|
430
|
+
self.publish(relative, encoded(record))
|
|
431
|
+
observed = self.current(discovery_id)
|
|
432
|
+
if observed != record:
|
|
433
|
+
fail('EFFECT', 'Inspect the actual saved revision before retrying an uncertain save.')
|
|
434
|
+
return self.report(discovery_id, observed, effects=True)
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""Metadata-only, pre-initialization discovery contracts."""
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
def obj(properties, required=()):
|
|
5
|
+
return {'type': 'object', 'properties': properties, 'required': list(required),
|
|
6
|
+
'additionalProperties': False}
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
TEXT = {'type': 'string'}
|
|
10
|
+
CURSOR = {'type': ['string', 'null']}
|
|
11
|
+
MEMBER = obj({'source_id': TEXT, 'thread_id': TEXT}, ['source_id', 'thread_id'])
|
|
12
|
+
THREAD = obj({'thread_id': TEXT, 'title': TEXT, 'cwd': TEXT}, ['thread_id', 'title'])
|
|
13
|
+
PAGE = obj({'cursor': CURSOR, 'next_cursor': CURSOR, 'receipt_ref': TEXT,
|
|
14
|
+
'threads': {'type': 'array', 'maxItems': 100, 'items': THREAD}},
|
|
15
|
+
['cursor', 'next_cursor', 'receipt_ref', 'threads'])
|
|
16
|
+
SOURCE = obj({'source_id': TEXT, 'label': TEXT,
|
|
17
|
+
'archive_scope': {'type': 'string', 'enum': ['active', 'archived', 'unknown']},
|
|
18
|
+
'coverage': {'type': 'string', 'enum': ['partial', 'exhausted', 'unavailable', 'unknown']},
|
|
19
|
+
'pages': {'type': 'array', 'maxItems': 50, 'items': PAGE}},
|
|
20
|
+
['source_id', 'label', 'archive_scope', 'coverage', 'pages'])
|
|
21
|
+
CANDIDATE = obj({'candidate_id': TEXT, 'label': TEXT, 'reason': TEXT,
|
|
22
|
+
'members': {'type': 'array', 'minItems': 1, 'maxItems': 100, 'items': MEMBER}},
|
|
23
|
+
['candidate_id', 'label', 'reason', 'members'])
|
|
24
|
+
LINK = obj({'onboarding_id': TEXT, 'scope_fingerprint': TEXT, 'selection_fingerprint': TEXT,
|
|
25
|
+
'windows': {'type': 'array', 'minItems': 1, 'maxItems': 100, 'items': obj({
|
|
26
|
+
'source_id': TEXT, 'thread_id': TEXT, 'window_thread_id': TEXT, 'source_ref': TEXT},
|
|
27
|
+
['source_id', 'thread_id', 'window_thread_id', 'source_ref'])}},
|
|
28
|
+
['onboarding_id', 'scope_fingerprint', 'selection_fingerprint', 'windows'])
|
|
29
|
+
DRAFT = obj({'sources': {'type': 'array', 'maxItems': 20, 'items': SOURCE},
|
|
30
|
+
'candidates': {'type': 'array', 'maxItems': 100, 'items': CANDIDATE},
|
|
31
|
+
'selection': obj({'candidate_id': TEXT, 'confirmation_ref': TEXT},
|
|
32
|
+
['candidate_id', 'confirmation_ref']),
|
|
33
|
+
'onboarding': LINK}, ['sources', 'candidates'])
|
|
34
|
+
ROOT_IDENTITY = obj({'device': TEXT, 'inode': TEXT}, ['device', 'inode'])
|
|
35
|
+
STATE_BINDING = {'type': ['object', 'null'], 'additionalProperties': True}
|
|
36
|
+
SELECTION_GUARD = {**obj({'selection_fingerprint': TEXT, 'confirmation_ref': TEXT, 'root': TEXT,
|
|
37
|
+
'root_identity': ROOT_IDENTITY, 'state_binding': STATE_BINDING},
|
|
38
|
+
['selection_fingerprint', 'confirmation_ref', 'root', 'root_identity', 'state_binding']),
|
|
39
|
+
'type': ['object', 'null']}
|
|
40
|
+
PLAN = obj({'format': {'type': 'integer', 'enum': [1]}, 'root': TEXT,
|
|
41
|
+
'root_identity': ROOT_IDENTITY, 'state_binding': STATE_BINDING,
|
|
42
|
+
'discovery_id': TEXT, 'expected_revision': {'type': 'integer', 'minimum': 0, 'maximum': 4095},
|
|
43
|
+
'expected_fingerprint': CURSOR, 'draft': DRAFT, 'selection_fingerprint': CURSOR,
|
|
44
|
+
'selection_guard': SELECTION_GUARD,
|
|
45
|
+
'plan_id': TEXT},
|
|
46
|
+
['format', 'root', 'root_identity', 'state_binding', 'discovery_id', 'expected_revision',
|
|
47
|
+
'expected_fingerprint', 'draft', 'selection_fingerprint', 'selection_guard', 'plan_id'])
|
|
48
|
+
SCHEMAS = {'discovery': obj({'discovery_id': TEXT,
|
|
49
|
+
'action': {'type': 'string', 'enum': ['status', 'plan', 'execute']},
|
|
50
|
+
'expected_revision': {'type': 'integer', 'minimum': 0, 'maximum': 4095},
|
|
51
|
+
'draft': DRAFT, 'plan': PLAN}, ['discovery_id'])}
|
|
52
|
+
DESCRIPTIONS = {'discovery': 'Read, plan or execute a bounded metadata-only discovery draft before control initialization. AI proposes projects; recorded user selection binds later onboarding. Does not scan chats, read bodies, initialize, activate or prove acceptance.'}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Public cache/outbox interface; project authority stays at the governor."""
|
|
2
|
+
from .worker_tools import schema, string, REF, RECORD
|
|
3
|
+
|
|
4
|
+
SCHEMAS = {'endpoint': schema({
|
|
5
|
+
'action': string(enum=['join_plan', 'refresh_plan', 'reply_plan', 'acquire_plan', 'execute', 'inspect', 'read']),
|
|
6
|
+
'plan_id': string(), 'repository': string(), 'remote': string(), 'input_ref': string(), 'packet_path': string(),
|
|
7
|
+
'commit': string(), 'expected_sha256': string(), 'project_id': string(), 'binding_id': string(),
|
|
8
|
+
'invitation_id': string(), 'output_path': string(),
|
|
9
|
+
'task_id': string(), 'workspace_id': string(), 'path': string(),
|
|
10
|
+
'workspaces': {'type': 'array', 'maxItems': 64, 'items': schema({'workspace_id': string(), 'path': string()}, ['workspace_id', 'path'])},
|
|
11
|
+
'sources': {'type': 'array', 'maxItems': 64, 'items': RECORD},
|
|
12
|
+
'handbacks': {'type': 'array', 'maxItems': 64, 'items': RECORD},
|
|
13
|
+
'reads': {'type': 'array', 'maxItems': 64, 'items': RECORD},
|
|
14
|
+
'preservations': {'type': 'array', 'maxItems': 64, 'items': RECORD},
|
|
15
|
+
'experience_feedback': {'type': 'array', 'maxItems': 32, 'items': RECORD},
|
|
16
|
+
'section': string(enum=['overview', 'tasks', 'role', 'sources', 'handbacks', 'dispositions']),
|
|
17
|
+
'reference': REF, 'cursor': string(), 'limit': {'type': 'integer', 'minimum': 1, 'maximum': 20},
|
|
18
|
+
'max_bytes': {'type': 'integer', 'minimum': 256, 'maximum': 4096}}, ['action'])}
|
|
19
|
+
|
|
20
|
+
DESCRIPTIONS = {'endpoint': 'Plan/review/execute a local Git collaboration cache and selected outbox. No task database is created. Join/refresh pins an independently reviewed exact project/member/view digest and existing Git source. Replies retain last-known basis and are subject to current governor checks; not centrally received until import. No network publication or Git worktree changes.'}
|
|
21
|
+
OFFLINE_ACTIONS = frozenset({'identify', 'doctor', 'worker_brief', 'source_read', 'source_acquire', 'endpoint', 'experience_query'})
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def offline_invoke(project, action, arguments, **kwargs):
|
|
25
|
+
from .contracts import validate, action_schema
|
|
26
|
+
from .exchange_endpoint import ExchangeEndpoint
|
|
27
|
+
from .exchange_packets import require
|
|
28
|
+
from .worker_channel import WorkerChannel
|
|
29
|
+
require(action in OFFLINE_ACTIONS, 'This cached endpoint cannot mutate central governance.', 'WORKER_ACTION_DENIED')
|
|
30
|
+
validate(arguments, action_schema(action))
|
|
31
|
+
endpoint = ExchangeEndpoint(project)
|
|
32
|
+
config = endpoint.config()
|
|
33
|
+
if action in {'identify', 'doctor'}:
|
|
34
|
+
from . import __version__
|
|
35
|
+
result = {'project_id': config['project_id'], 'binding_id': config['binding_id'],
|
|
36
|
+
'toolkit_version': __version__, 'last_known': True, 'live_governor_checked': False,
|
|
37
|
+
'effective_role': 'worker', 'second_control_created': False, 'effects_executed': False}
|
|
38
|
+
result['conditional_experience_available'] = 'experience' in endpoint.view()[1]
|
|
39
|
+
elif action == 'experience_query':
|
|
40
|
+
from .experience_exchange import CachedExperience
|
|
41
|
+
_, view, objects = endpoint.view()
|
|
42
|
+
result = CachedExperience(view, objects).read(view, **arguments)
|
|
43
|
+
elif action == 'worker_brief':
|
|
44
|
+
require(not any(k not in {'section', 'limit', 'cursor'} for k in arguments),
|
|
45
|
+
'Cached directory supports section, limit and cursor; fetch a newer view for current decisions.')
|
|
46
|
+
result = endpoint.brief(**arguments)
|
|
47
|
+
elif action == 'source_read':
|
|
48
|
+
result = endpoint.read(**arguments)
|
|
49
|
+
elif action == 'source_acquire':
|
|
50
|
+
data = dict(arguments)
|
|
51
|
+
mode = data.pop('mode')
|
|
52
|
+
require(mode in {'plan', 'execute'}, 'Use plan or execute for cache acquisition.')
|
|
53
|
+
if mode == 'execute':
|
|
54
|
+
from .core import _id
|
|
55
|
+
plan = endpoint._json('plans/' + _id(data.get('plan_id'), 'Plan') + '.json')
|
|
56
|
+
require(plan and plan['operation'] == 'acquire', 'Use the exact acquisition plan.', 'WORKER_ACTION_DENIED')
|
|
57
|
+
result = endpoint.invoke(action='acquire_plan' if mode == 'plan' else 'execute', **data)
|
|
58
|
+
else:
|
|
59
|
+
require(arguments.get('action') in {'inspect', 'read', 'reply_plan', 'execute'},
|
|
60
|
+
'Join and refresh are explicit local connection operations.', 'WORKER_ACTION_DENIED')
|
|
61
|
+
if arguments['action'] == 'execute':
|
|
62
|
+
from .core import _id
|
|
63
|
+
plan = endpoint._json('plans/' + _id(arguments.get('plan_id'), 'Plan') + '.json')
|
|
64
|
+
require(plan and plan['operation'] == 'reply', 'This endpoint can execute only its outgoing reply plans.', 'WORKER_ACTION_DENIED')
|
|
65
|
+
result = endpoint.invoke(**arguments)
|
|
66
|
+
WorkerChannel._budget(result)
|
|
67
|
+
return result
|