taskcarry 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. taskcarry/__init__.py +3 -0
  2. taskcarry/__main__.py +4 -0
  3. taskcarry/adapter_contracts.py +166 -0
  4. taskcarry/agy_turns.py +282 -0
  5. taskcarry/api.py +111 -0
  6. taskcarry/board.py +313 -0
  7. taskcarry/board_assets/board.css +1087 -0
  8. taskcarry/board_assets/board.js +1187 -0
  9. taskcarry/board_assets/browse.js +214 -0
  10. taskcarry/board_assets/index.html +43 -0
  11. taskcarry/board_assets/taskcarry-icon.ico +0 -0
  12. taskcarry/board_assets/taskcarry-mark.svg +28 -0
  13. taskcarry/board_data.py +466 -0
  14. taskcarry/chat_joins.py +157 -0
  15. taskcarry/cli.py +119 -0
  16. taskcarry/codex_capture.py +184 -0
  17. taskcarry/codex_host.py +293 -0
  18. taskcarry/collaboration_exchange.py +316 -0
  19. taskcarry/connection.py +159 -0
  20. taskcarry/continuity.py +300 -0
  21. taskcarry/contracts.py +165 -0
  22. taskcarry/conversation_capture.py +669 -0
  23. taskcarry/core.py +896 -0
  24. taskcarry/cycle_contracts.py +73 -0
  25. taskcarry/discovery.py +434 -0
  26. taskcarry/discovery_contracts.py +52 -0
  27. taskcarry/exchange_contracts.py +67 -0
  28. taskcarry/exchange_endpoint.py +377 -0
  29. taskcarry/exchange_packets.py +142 -0
  30. taskcarry/experience_contracts.py +129 -0
  31. taskcarry/experience_exchange.py +214 -0
  32. taskcarry/experience_notes.py +433 -0
  33. taskcarry/experience_storage.py +125 -0
  34. taskcarry/experience_tools.py +26 -0
  35. taskcarry/feishu/__init__.py +1 -0
  36. taskcarry/feishu/display.py +122 -0
  37. taskcarry/feishu/project_watch.py +145 -0
  38. taskcarry/feishu/review_sets.py +80 -0
  39. taskcarry/feishu/sender.py +42 -0
  40. taskcarry/feishu/subscription.py +193 -0
  41. taskcarry/feishu/windows_agent.py +287 -0
  42. taskcarry/feishu/windows_secret.py +34 -0
  43. taskcarry/gitops.py +170 -0
  44. taskcarry/governance.py +88 -0
  45. taskcarry/governance_cycle.py +775 -0
  46. taskcarry/identification.py +82 -0
  47. taskcarry/integration.py +663 -0
  48. taskcarry/maintenance.py +118 -0
  49. taskcarry/mcp.py +183 -0
  50. taskcarry/member_join.py +184 -0
  51. taskcarry/member_routing.py +145 -0
  52. taskcarry/onboarding.py +272 -0
  53. taskcarry/onboarding_complete.py +252 -0
  54. taskcarry/path_batches.py +19 -0
  55. taskcarry/preservation.py +257 -0
  56. taskcarry/project_collaboration.py +453 -0
  57. taskcarry/project_history.py +166 -0
  58. taskcarry/project_identity.py +51 -0
  59. taskcarry/project_recovery.py +824 -0
  60. taskcarry/recovery_contracts.py +25 -0
  61. taskcarry/recovery_files.py +153 -0
  62. taskcarry/recovery_git.py +234 -0
  63. taskcarry/remote_capture.py +89 -0
  64. taskcarry/remote_transfer.py +356 -0
  65. taskcarry/role_connection.py +215 -0
  66. taskcarry/setup.py +597 -0
  67. taskcarry/shared_workbench.py +480 -0
  68. taskcarry/skill_data/taskcarry-experience-recovery/SKILL.md +37 -0
  69. taskcarry/skill_data/taskcarry-governance-reconcile/SKILL.md +47 -0
  70. taskcarry/skill_data/taskcarry-governance-reconcile/references/daily-governance.md +72 -0
  71. taskcarry/skill_data/taskcarry-project-setup/SKILL.md +48 -0
  72. taskcarry/skill_data/taskcarry-project-setup/references/onboarding.md +198 -0
  73. taskcarry/skill_data/taskcarry-task-delivery/SKILL.md +32 -0
  74. taskcarry/skill_data/taskcarry-task-delivery/references/conditional-experience.md +93 -0
  75. taskcarry/skill_data/taskcarry-task-delivery/references/worker-channel.md +41 -0
  76. taskcarry/source_review_set.py +80 -0
  77. taskcarry/state_format.py +47 -0
  78. taskcarry/store.py +472 -0
  79. taskcarry/task_context.py +141 -0
  80. taskcarry/text_handback.py +98 -0
  81. taskcarry/transfer_contracts.py +18 -0
  82. taskcarry/updates.py +351 -0
  83. taskcarry/workbench.py +625 -0
  84. taskcarry/workbench_contracts.py +32 -0
  85. taskcarry/workbuddy_capture.py +451 -0
  86. taskcarry/workbuddy_setup.py +212 -0
  87. taskcarry/worker_channel.py +859 -0
  88. taskcarry/worker_contracts.py +190 -0
  89. taskcarry/worker_storage.py +60 -0
  90. taskcarry/worker_tools.py +111 -0
  91. taskcarry-0.3.2.dist-info/METADATA +203 -0
  92. taskcarry-0.3.2.dist-info/RECORD +105 -0
  93. taskcarry-0.3.2.dist-info/WHEEL +5 -0
  94. taskcarry-0.3.2.dist-info/entry_points.txt +5 -0
  95. taskcarry-0.3.2.dist-info/licenses/LICENSE +21 -0
  96. taskcarry-0.3.2.dist-info/licenses/LICENSE_SCOPE.md +31 -0
  97. taskcarry-0.3.2.dist-info/top_level.txt +2 -0
  98. taskcarry_https/__init__.py +1 -0
  99. taskcarry_https/consent.py +207 -0
  100. taskcarry_https/reader.py +132 -0
  101. taskcarry_https/review.py +116 -0
  102. taskcarry_https/server.py +163 -0
  103. taskcarry_https/team.py +335 -0
  104. taskcarry_https/team_host.py +109 -0
  105. taskcarry_https/web_host.py +82 -0
@@ -0,0 +1,141 @@
1
+ """Task-scoped, paginated context with bounded payload reads and no receipts."""
2
+ import base64
3
+ import json
4
+ import re
5
+
6
+ from .core import _id, digest_bytes
7
+ from .store import GovernanceError
8
+
9
+ COLLECTIONS = ('observations', 'stages', 'operations', 'artifacts', 'issues', 'fixes', 'runs')
10
+ MAX_RECORD_BYTES = 16384
11
+
12
+
13
+ def _hash(value):
14
+ return digest_bytes(json.dumps(value, sort_keys=True, ensure_ascii=False,
15
+ separators=(',', ':'), allow_nan=False).encode('utf-8'))
16
+
17
+
18
+ def _selection(values, label):
19
+ if values is None:
20
+ return []
21
+ if not isinstance(values, list) or len(values) > 50:
22
+ raise GovernanceError('INVALID_ARGUMENT', label + ' must contain at most 50 exact identities.')
23
+ result = [_id(item, label) for item in values]
24
+ if len(result) != len(set(result)):
25
+ raise GovernanceError('INVALID_ARGUMENT', label + ' cannot contain duplicates.')
26
+ return sorted(result)
27
+
28
+
29
+ def read_context(core, task_id, limit, cursor, previous_fingerprint, issue_ids, fix_ids):
30
+ task_id = _id(task_id, 'Task ID')
31
+ if type(limit) is not int or not 1 <= limit <= 100:
32
+ raise GovernanceError('INVALID_ARGUMENT', 'Context limit must be an integer from 1 to 100.')
33
+ if previous_fingerprint is not None and (not isinstance(previous_fingerprint, str)
34
+ or not re.fullmatch('[0-9a-f]{64}', previous_fingerprint)):
35
+ raise GovernanceError('INVALID_ARGUMENT', 'Use a SHA-256 previous fingerprint.')
36
+ issue_ids, fix_ids = _selection(issue_ids, 'issue_ids'), _selection(fix_ids, 'fix_ids')
37
+ source = core.source()
38
+ selection = _hash({'source': source, 'task_id': task_id, 'issue_ids': issue_ids, 'fix_ids': fix_ids})
39
+ decoded = None
40
+ if cursor is not None:
41
+ try:
42
+ if not isinstance(cursor, str) or not 1 <= len(cursor) <= 2048:
43
+ raise ValueError()
44
+ decoded = json.loads(base64.b64decode(cursor + '=' * (-len(cursor) % 4), altchars=b'-_', validate=True))
45
+ if (set(decoded) != {'version', 'selection', 'fingerprint', 'after'}
46
+ or type(decoded['version']) is not int or decoded['version'] != 1
47
+ or decoded['selection'] != selection
48
+ or not isinstance(decoded['fingerprint'], str)
49
+ or not re.fullmatch('[0-9a-f]{64}', decoded['fingerprint'])
50
+ or not isinstance(decoded['after'], list) or len(decoded['after']) != 2
51
+ or decoded['after'][0] not in COLLECTIONS
52
+ or not isinstance(decoded['after'][1], str) or len(decoded['after'][1]) > 256):
53
+ raise ValueError()
54
+ except (ValueError, TypeError, KeyError, UnicodeError):
55
+ raise GovernanceError('CONTEXT_CURSOR_INVALID', 'Use the returned cursor with the same source, task and selections.')
56
+
57
+ missing, loaded = [], 0
58
+ with core.store._connect(readonly=True) as db:
59
+ if (not core.store._projection_ready(db) or core.store._projection_dirty(db)
60
+ or not core.store._context_ready(db)):
61
+ raise GovernanceError('CONTEXT_INDEX_REQUIRED', 'Run the explicit upgrade action, then retry context; this read changed nothing.')
62
+
63
+ def load(collection, key):
64
+ nonlocal loaded
65
+ row = db.execute('''SELECT length(CAST(value AS BLOB)),
66
+ CASE WHEN length(CAST(value AS BLOB))<=? THEN value ELSE NULL END
67
+ FROM records WHERE collection=? AND key=?''', (MAX_RECORD_BYTES, collection, key)).fetchone()
68
+ if row is None:
69
+ missing.append({'collection': collection, 'local_id': key, 'reason': 'record_missing'})
70
+ return None
71
+ loaded += 1
72
+ if row[1] is None:
73
+ missing.append({'collection': collection, 'local_id': key, 'reason': 'record_exceeds_context_limit',
74
+ 'bytes': row[0]})
75
+ return {'payload_omitted': True, 'bytes': row[0]}
76
+ return json.loads(row[1])
77
+
78
+ task = load('tasks', task_id)
79
+ if task is None:
80
+ raise GovernanceError('TASK_NOT_FOUND', 'Create or select an existing task before reading its context.')
81
+ # Fetch only small scalar pointers when a task's large prose is omitted.
82
+ pointer = db.execute("SELECT json_extract(value,'$.latest_checkpoint') FROM records WHERE collection='tasks' AND key=?",
83
+ (task_id,)).fetchone()[0]
84
+ latest = load('checkpoints', pointer) if isinstance(pointer, str) else None
85
+ if latest and not latest.get('payload_omitted') and latest.get('task_id') != task_id:
86
+ missing.append({'collection': 'checkpoints', 'local_id': pointer, 'reason': 'task_scope_mismatch'})
87
+ latest = None
88
+ selected, selected_revisions = [], []
89
+ for collection, identities in (('issues', issue_ids), ('fixes', fix_ids)):
90
+ for key in identities:
91
+ data = load(collection, key)
92
+ selected_revisions.append(db.execute('SELECT revision FROM context_record_revisions WHERE collection=? AND key=?',
93
+ (collection, key)).fetchone())
94
+ selected.append({'source_id': source['source_id'], 'collection': collection, 'local_id': key,
95
+ 'selection_basis': 'explicit_caller_reference', 'record': data})
96
+ revision = db.execute('SELECT revision FROM context_revisions WHERE task_id=?', (task_id,)).fetchone()
97
+ generation = db.execute('SELECT generation FROM context_schema').fetchone()[0]
98
+ from .experience_storage import legacy_pointer
99
+ experience_pointer = legacy_pointer(core, task_id, db)
100
+ fingerprint = _hash({'selection': selection, 'generation': generation,
101
+ 'conditional_experience': experience_pointer,
102
+ 'revision': revision[0] if revision else 0, 'selected': selected,
103
+ 'selected_revisions': selected_revisions})
104
+ if decoded and decoded['fingerprint'] != fingerprint:
105
+ raise GovernanceError('CONTEXT_CURSOR_STALE', 'Task evidence changed; read a fresh first page.',
106
+ {'current_fingerprint': fingerprint})
107
+ after = decoded['after'] if decoded else ['', '']
108
+ marks = ','.join('?' for _ in COLLECTIONS)
109
+ rows = db.execute('''SELECT c.collection,c.key,length(CAST(r.value AS BLOB)),
110
+ CASE WHEN length(CAST(r.value AS BLOB))<=? THEN r.value ELSE NULL END
111
+ FROM current_records AS c INDEXED BY current_records_task
112
+ JOIN records AS r ON r.collection=c.collection AND r.key=c.key
113
+ WHERE c.task_id=? AND c.collection IN (''' + marks + ''')
114
+ AND (c.collection,c.key)>(?,?) ORDER BY c.collection,c.key LIMIT ?''',
115
+ (MAX_RECORD_BYTES, task_id, *COLLECTIONS, *after, limit + 1)).fetchall()
116
+ total = db.execute('SELECT count(*) FROM current_records INDEXED BY current_records_task '
117
+ 'WHERE task_id=? AND collection IN (' + marks + ')', (task_id, *COLLECTIONS)).fetchone()[0]
118
+ page = []
119
+ for collection, key, size, payload in rows[:limit]:
120
+ data = json.loads(payload) if payload is not None else {'payload_omitted': True, 'bytes': size}
121
+ if payload is None:
122
+ missing.append({'collection': collection, 'local_id': key, 'reason': 'record_exceeds_context_limit', 'bytes': size})
123
+ page.append({'source_id': source['source_id'], 'collection': collection, 'local_id': key, 'record': data})
124
+ loaded += len(rows)
125
+ next_cursor = None
126
+ if len(rows) > limit:
127
+ next_cursor = base64.urlsafe_b64encode(json.dumps({'version': 1, 'selection': selection,
128
+ 'fingerprint': fingerprint, 'after': [page[-1]['collection'], page[-1]['local_id']]},
129
+ separators=(',', ':')).encode('utf-8')).decode('ascii').rstrip('=')
130
+ return {'source': source, 'task_id': task_id, 'task': task, 'latest_checkpoint': latest,
131
+ 'conditional_experience': experience_pointer,
132
+ 'items': page, 'selected_references': selected, 'missing': missing, 'total': total,
133
+ 'returned': len(page), 'has_more': next_cursor is not None, 'next_cursor': next_cursor,
134
+ 'fingerprint': fingerprint, 'changed': previous_fingerprint != fingerprint,
135
+ 'storage': {'mode': 'indexed_task_context_v1', 'loaded_records': loaded,
136
+ 'max_record_bytes': MAX_RECORD_BYTES, 'payload_read_bound': limit + 103},
137
+ 'coverage': {'task_records': list(COLLECTIONS), 'checkpoint': 'latest_only',
138
+ 'issues_and_fixes': 'task-scoped or explicitly selected; unscoped project records are not inferred',
139
+ 'history': 'observation revisions are current; prior revisions and events are not scanned',
140
+ 'external_effects_reverified': False},
141
+ 'read_only': True, 'effects_executed': False, 'project_complete': None}
@@ -0,0 +1,98 @@
1
+ """Share a member's Markdown and submit its exact source for review atomically."""
2
+ import hashlib
3
+
4
+ from .core import _id
5
+ from .worker_channel import fail
6
+ from .worker_contracts import valid_display_name
7
+
8
+
9
+ MAX_TEXT_BYTES = 12 * 1024
10
+
11
+
12
+ class TextHandback:
13
+ def __init__(self, channel):
14
+ self.channel = channel
15
+
16
+ def _check(self, payload, expected, *, allow_replay=False):
17
+ ch = self.channel
18
+ task, workspace = payload['task_id'], payload['workspace_id']
19
+ ch._assignment(task, workspace, 'handback')
20
+ if not ch.binding['share_project']:
21
+ fail('WORKER_SHARE_DENIED', 'This member cannot share drafts with the project.')
22
+ if payload['basis'] != {'binding_revision': ch.binding['revision'], 'task_fingerprint': ch._task_hash(task)}:
23
+ fail('WORKER_BASIS_CHANGED', 'Read the current assignment before submitting.')
24
+ ref = payload['reference']
25
+ old = ch.store.get('worker_sources', ref['reference_id'])
26
+ prior = ch.store.get('worker_handbacks', payload['handback_id'])
27
+ if old and (old['owner_binding_id'] != ch.actor or old['task_id'] != task or old['state'] != 'active'):
28
+ fail('WORKER_SOURCE_DENIED', 'The selected draft slot is unavailable.')
29
+ if prior and (prior['binding_id'], prior['task_id'], prior['workspace_id']) != (ch.actor, task, workspace):
30
+ fail('WORKER_SCOPE_DENIED', 'This handback belongs to another assignment.')
31
+ if bool(old) != bool(prior):
32
+ fail('WORKER_REVISION_CONFLICT', 'Select a new slot or review the existing source and handback.')
33
+ if old:
34
+ live_ref = {k: old[k] for k in ('reference_id', 'revision', 'content_sha256')}
35
+ if (prior['kind'] != 'document' or prior['state'] != 'submitted' or prior['sources'] != [live_ref]
36
+ or prior['revision'] != old['revision']):
37
+ fail('WORKER_REVISION_CONFLICT', 'The current source and handback no longer form this draft.')
38
+ if allow_replay and ref == live_ref and prior['basis'] == payload['basis']:
39
+ return True
40
+ if (old['revision'] if old else 0) != expected:
41
+ fail('WORKER_REVISION_CONFLICT', 'Read the latest draft revision before resubmitting.')
42
+ return False
43
+
44
+ def invoke(self, mode, plan_id=None, task_id=None, workspace_id=None, reference_id=None, handback_id=None,
45
+ expected_revision=None, basis=None, text=None, display_title=None):
46
+ if mode == 'execute':
47
+ return self.channel._execute('worker_submit_text', plan_id)
48
+ if type(expected_revision) is not int or expected_revision < 0:
49
+ fail('INVALID_ARGUMENT', 'Provide the current revision, or zero for a new draft.')
50
+ if not isinstance(text, str) or not text.strip() or '\x00' in text:
51
+ fail('INVALID_ARGUMENT', 'Provide nonempty Markdown text without NUL.')
52
+ try:
53
+ data = text.encode('utf-8')
54
+ except UnicodeEncodeError:
55
+ fail('INVALID_ARGUMENT', 'The draft must be valid UTF-8.')
56
+ if len(data) > MAX_TEXT_BYTES:
57
+ fail('FILE_TOO_LARGE', 'The UTF-8 draft exceeds the 12 KiB limit.')
58
+ ref = {'reference_id': _id(reference_id, 'Reference'), 'revision': expected_revision + 1,
59
+ 'content_sha256': hashlib.sha256(data).hexdigest()}
60
+ payload = {'task_id': _id(task_id, 'Task'), 'workspace_id': _id(workspace_id, 'Workspace'),
61
+ 'handback_id': _id(handback_id, 'Handback'), 'reference': ref,
62
+ 'size': len(data), 'basis': basis}
63
+ if display_title is not None:
64
+ if not valid_display_name(display_title):
65
+ fail('INVALID_ARGUMENT', 'Use one short, printable title suitable for a group notification.')
66
+ payload['display_title'] = display_title
67
+ replay = self._check(payload, expected_revision, allow_replay=True)
68
+ # Plans retain private immutable bytes. Publication, the review queue and the
69
+ # notification event become visible together only when the plan executes.
70
+ self.channel.core._snapshot(data)
71
+ plan = self.channel._plan('worker_submit_text', payload, {'expected': expected_revision})
72
+ if replay and plan['state'] != 'completed':
73
+ fail('WORKER_REVISION_CONFLICT', 'This revision was created by a different operation.')
74
+ return plan
75
+
76
+ def apply(self, payload, guards):
77
+ ch = self.channel
78
+ expected = guards['expected']
79
+ self._check(payload, expected)
80
+ ref = payload['reference']
81
+ base = {'contract_version': 1, 'project_id': ch.project_id, 'revision': ref['revision'],
82
+ 'task_id': payload['task_id']}
83
+ prior = ch.store.get('worker_sources', ref['reference_id']) if expected else None
84
+ title = payload.get('display_title') or (prior.get('display_title') if prior and prior['visibility'] == 'project' else None)
85
+ source_fields = {'display_title': title} if title else {}
86
+ source, source_id = ch._record('source', {**base, **ref, **source_fields, 'owner_binding_id': ch.actor,
87
+ 'visibility': 'project', 'state': 'active', 'media_type': 'text/markdown', 'size': payload['size'],
88
+ 'origin': {'kind': 'artifact', 'artifact_id': ref['reference_id'], 'artifact_revision': ref['revision']}}, expected)
89
+ ch._bytes(source)
90
+ ch._save_record('source', source_id, source)
91
+ handback = {**base, 'handback_id': payload['handback_id'], 'binding_id': ch.actor,
92
+ 'workspace_id': payload['workspace_id'], 'kind': 'document', 'state': 'submitted',
93
+ 'summary': 'Submitted Markdown for project review.', 'next_step': 'Governor review.',
94
+ 'basis': payload['basis'], 'sources': [ref]}
95
+ plan = ch.worker_handback('plan', record=handback, expected_revision=expected)
96
+ result = ch._execute('worker_handback', plan['plan_id'])
97
+ ch.record_project_shares([{**ref, 'task_id': payload['task_id']}])
98
+ return {**result, 'reference': ref, 'size': payload['size'], 'visibility': 'project'}
@@ -0,0 +1,18 @@
1
+ """Independent contracts for explicit remote and local-media transfer plans."""
2
+
3
+ SCHEMAS = {'transfer': {
4
+ 'type': 'object', 'additionalProperties': False, 'required': ['action'],
5
+ 'properties': {
6
+ 'action': {'type': 'string', 'enum': ['publish_plan', 'publish_execute', 'copy_plan', 'copy_execute', 'verify', 'status']},
7
+ 'repository': {'type': 'string', 'description': 'Exact existing Git worktree root, only for publish_plan.'},
8
+ 'remote': {'type': 'string', 'description': 'Already-configured single push remote, only for publish_plan.'},
9
+ 'ref': {'type': 'string', 'description': 'One exact refs/heads/... or new refs/tags/... destination.'},
10
+ 'commit': {'type': 'string', 'description': 'One existing commit or local revision, frozen to its exact commit object.'},
11
+ 'plan_id': {'type': 'string', 'description': 'Exact reviewed transfer plan for execution/status/verification.'},
12
+ 'manifest': {'type': 'string', 'description': 'Exact sealed local project-recovery manifest, only for copy_plan.'},
13
+ 'destination': {'type': 'string', 'description': 'Independent local media or synchronized-directory destination, only for copy_plan.'},
14
+ 'expected_sha256': {'type': 'string', 'description': 'Independently reviewed manifest SHA-256 when available.'},
15
+ },
16
+ }}
17
+
18
+ DESCRIPTIONS = {'transfer': 'Plan and verify one exact Git ref at an already-configured endpoint, using an expected-old-ref lease and actual-effect recovery after ambiguous transport. Existing tags and unrelated refs are preserved. Copy sealed recovery sets to explicitly selected local directories with hash verification; local copies never imply cloud upload, retention or second-machine recovery.'}
taskcarry/updates.py ADDED
@@ -0,0 +1,351 @@
1
+ """Official release discovery and explicit, host-reviewed adoption decisions.
2
+
3
+ Network reads never install packages or change local state. Saved assessments
4
+ are not installation or host-loading receipts.
5
+ """
6
+ from __future__ import annotations
7
+
8
+ import hashlib
9
+ import json
10
+ from pathlib import PurePosixPath
11
+ import re
12
+ import socket
13
+ import time
14
+ import urllib.error
15
+ import urllib.parse
16
+ import urllib.request
17
+
18
+ from . import __version__
19
+ from .core import Core
20
+ from .maintenance import _revision
21
+ from .store import GovernanceError, now
22
+
23
+
24
+ REPOSITORY = 'bryan123466/taskcarry'
25
+ RELEASES_URL = 'https://github.com/' + REPOSITORY + '/releases'
26
+ API_ROOT = 'https://api.github.com/repos/' + REPOSITORY
27
+ MANIFEST_NAME = 'taskcarry-release.json'
28
+ MAX_RESPONSE = 2 * 1024 * 1024
29
+ VERSION = re.compile(r'^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)(?:rc([1-9][0-9]*))?$')
30
+ SHA256 = re.compile(r'^[0-9a-f]{64}$')
31
+ COMMIT = re.compile(r'^[0-9a-f]{40}$')
32
+ DECISIONS = ('prioritize', 'plan', 'keep', 'wait', 'reject')
33
+
34
+
35
+ def _fingerprint(value):
36
+ try:
37
+ data = json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=False,
38
+ allow_nan=False).encode('utf-8')
39
+ except (ValueError, TypeError) as exc:
40
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Update records require finite JSON data.') from exc
41
+ if len(data) > MAX_RESPONSE:
42
+ raise GovernanceError('UPDATE_OUTPUT_LIMIT', 'Update record exceeds its byte limit.')
43
+ return hashlib.sha256(data).hexdigest()
44
+
45
+
46
+ def _version(value):
47
+ match = VERSION.fullmatch(value) if isinstance(value, str) else None
48
+ if match is None:
49
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Expected a release version such as 1.2.3 or 1.2.3rc1.')
50
+ major, minor, patch, rc = match.groups()
51
+ return int(major), int(minor), int(patch), 1 if rc is None else 0, int(rc or 0)
52
+
53
+
54
+ def _artifacts(value):
55
+ if not isinstance(value, list) or len(value) > 20:
56
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Expected at most 20 explicit artifacts.')
57
+ names = set()
58
+ result = []
59
+ for item in value:
60
+ if not isinstance(item, dict):
61
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Artifact metadata must be an object.')
62
+ name, digest, size = item.get('name'), item.get('sha256'), item.get('size')
63
+ if (not isinstance(name, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,159}', name)
64
+ or PurePosixPath(name).name != name or name in names or name == MANIFEST_NAME
65
+ or not isinstance(digest, str) or not SHA256.fullmatch(digest)
66
+ or isinstance(size, bool) or not isinstance(size, int) or size < 0):
67
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Artifact name, size or SHA-256 is invalid.')
68
+ names.add(name)
69
+ result.append({'name': name, 'sha256': digest, 'size': size})
70
+ return sorted(result, key=lambda item: item['name'])
71
+
72
+
73
+ def build_release_manifest(version, source_commit, artifacts, required_actions=None,
74
+ python_min='3.11', state_schema=1):
75
+ """Build after final packages; the manifest deliberately excludes itself."""
76
+ parsed = _version(version)
77
+ if not isinstance(source_commit, str) or not COMMIT.fullmatch(source_commit):
78
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'source_commit must be a full Git SHA.')
79
+ files = _artifacts(artifacts)
80
+ if not files:
81
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'A release manifest needs final artifacts.')
82
+ actions = [] if required_actions is None else required_actions
83
+ if (not isinstance(actions, list) or len(actions) > 20
84
+ or any(not isinstance(item, str) or not item.strip() or len(item) > 2000 for item in actions)):
85
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'required_actions must contain bounded text.')
86
+ if (not isinstance(python_min, str) or not re.fullmatch(r'3\.[0-9]+', python_min)
87
+ or type(state_schema) is not int or state_schema != 1):
88
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Unsupported compatibility metadata.')
89
+ return {'schema': 1, 'repository': REPOSITORY, 'version': version,
90
+ 'channel': 'stable' if parsed[3] else 'rc', 'source_commit': source_commit,
91
+ 'artifacts': files, 'compatibility': {'python_min': python_min, 'state_schema': state_schema},
92
+ 'required_actions': actions, 'release_url': RELEASES_URL + '/tag/v' + version}
93
+
94
+
95
+ def validate_manifest(manifest):
96
+ if not isinstance(manifest, dict) or type(manifest.get('schema')) is not int or manifest['schema'] != 1:
97
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Unsupported release manifest schema.')
98
+ compat = manifest.get('compatibility')
99
+ if not isinstance(compat, dict):
100
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Missing compatibility metadata.')
101
+ expected = build_release_manifest(manifest.get('version'), manifest.get('source_commit'),
102
+ manifest.get('artifacts'), manifest.get('required_actions'),
103
+ compat.get('python_min'), compat.get('state_schema'))
104
+ if manifest != expected:
105
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release manifest fields or canonical identity do not match.')
106
+ return expected
107
+
108
+
109
+ class _Redirect(urllib.request.HTTPRedirectHandler):
110
+ def redirect_request(self, request, fp, code, message, headers, newurl):
111
+ _allowed_url(newurl)
112
+ return super().redirect_request(request, fp, code, message, headers, newurl)
113
+
114
+
115
+ def _allowed_url(url):
116
+ try:
117
+ parsed = urllib.parse.urlsplit(url)
118
+ port = parsed.port
119
+ except (TypeError, ValueError) as exc:
120
+ raise GovernanceError('UPDATE_SOURCE_REJECTED', 'The response has an invalid release URL.') from exc
121
+ if (parsed.scheme != 'https' or parsed.username or parsed.password or port not in (None, 443)
122
+ or parsed.hostname not in ('api.github.com', 'github.com', 'release-assets.githubusercontent.com',
123
+ 'objects.githubusercontent.com')):
124
+ raise GovernanceError('UPDATE_SOURCE_REJECTED', 'The response redirected outside the official release hosts.')
125
+
126
+
127
+ def _fetch_json(url, timeout=10):
128
+ _allowed_url(url)
129
+ request = urllib.request.Request(url, headers={'Accept': 'application/vnd.github+json',
130
+ 'User-Agent': 'TaskCarry-release-check/1'})
131
+ opener = urllib.request.build_opener(_Redirect())
132
+ with opener.open(request, timeout=timeout) as response:
133
+ _allowed_url(response.geturl())
134
+ deadline = time.monotonic() + timeout
135
+ chunks, total = [], 0
136
+ while True:
137
+ if time.monotonic() >= deadline:
138
+ raise GovernanceError('UPDATE_TIMEOUT', 'Official release response exceeded its time limit.')
139
+ block = response.read1(min(65536, MAX_RESPONSE + 1 - total))
140
+ if not block:
141
+ break
142
+ total += len(block)
143
+ if total > MAX_RESPONSE:
144
+ raise GovernanceError('UPDATE_OUTPUT_LIMIT', 'Official release response exceeded its byte limit.')
145
+ chunks.append(block)
146
+ content = b''.join(chunks)
147
+ try:
148
+ return json.loads(content), hashlib.sha256(content).hexdigest()
149
+ except (UnicodeDecodeError, ValueError) as exc:
150
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Official release response is not valid JSON.') from exc
151
+
152
+
153
+ class Updates(Core):
154
+ def update_source(self, channel='rc', current_version=None, current_artifacts=None,
155
+ method_refs=None, maintenance='review', expected_revision=None):
156
+ if channel not in ('rc', 'stable') or maintenance not in ('review', 'authorized_maintenance'):
157
+ raise GovernanceError('INVALID_ARGUMENT', 'Select rc/stable and review/authorized_maintenance.')
158
+ version = current_version or __version__
159
+ _version(version)
160
+ artifacts = _artifacts(current_artifacts or [])
161
+ refs = method_refs or []
162
+ if (not isinstance(refs, list) or len(refs) > 30
163
+ or any(not isinstance(ref, str) or not ref.strip() or len(ref) > 2000 for ref in refs)):
164
+ raise GovernanceError('INVALID_ARGUMENT', 'method_refs must be bounded evidence references.')
165
+ body = {'repository': REPOSITORY, 'release_source': RELEASES_URL, 'channel': channel,
166
+ 'current_version': version, 'current_artifacts': artifacts, 'method_refs': refs,
167
+ 'current_identity_scope': 'host_reviewed_reference', 'maintenance': maintenance,
168
+ 'automatic_install': False}
169
+ with self.store.transaction():
170
+ old = self.store.get('update_sources', 'official')
171
+ if old and all(old.get(key) == value for key, value in body.items()):
172
+ return {'source': old, 'reused': True}
173
+ revision = _revision(expected_revision, old)
174
+ record = dict(body, revision=revision, updated_at=now(),
175
+ created_at=old['created_at'] if old else now())
176
+ self.store.put('update_sources', 'official', record)
177
+ self.store.put('update_sources_history', 'official.' + str(revision), record)
178
+ self.store.event('update_source_recorded', record)
179
+ return {'source': record, 'reused': False}
180
+
181
+ def _candidate(self, release):
182
+ version = release['tag_name'][1:]
183
+ assets = release.get('assets')
184
+ if not isinstance(assets, list) or len(assets) > 30:
185
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release assets are missing or oversized.')
186
+ if any(not isinstance(item, dict) or not isinstance(item.get('name'), str)
187
+ or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_.-]{0,159}', item['name']) for item in assets):
188
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release assets contain invalid names.')
189
+ by_name = {item['name']: item for item in assets}
190
+ if len(by_name) != len(assets):
191
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release assets contain duplicate names.')
192
+ asset = by_name.get(MANIFEST_NAME)
193
+ if asset is None:
194
+ return {'version': version, 'release_url': RELEASES_URL + '/tag/v' + version,
195
+ 'status': 'LEGACY_REVIEW_REQUIRED', 'reason': 'No structured release manifest.',
196
+ 'identity_verified': False}
197
+ url = RELEASES_URL + '/download/v' + version + '/' + MANIFEST_NAME
198
+ if asset.get('browser_download_url') != url:
199
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Manifest download URL does not match the release.')
200
+ manifest, digest = _fetch_json(url)
201
+ if asset.get('digest') != 'sha256:' + digest:
202
+ raise GovernanceError('UPDATE_IDENTITY_MISMATCH', 'Manifest bytes do not match the release asset digest.')
203
+ manifest = validate_manifest(manifest)
204
+ if manifest['version'] != version or release.get('prerelease') != (manifest['channel'] == 'rc'):
205
+ raise GovernanceError('UPDATE_IDENTITY_MISMATCH', 'Release channel/version differs from its manifest.')
206
+ # Pin a tag to its actual commit, resolving annotated tags once, never
207
+ # treating target_commitish (which may be a moving branch) as a SHA.
208
+ reference, _ = _fetch_json(API_ROOT + '/git/ref/tags/v' + version)
209
+ obj = reference.get('object', {}) if isinstance(reference, dict) else {}
210
+ if not isinstance(obj, dict):
211
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release tag object must be an object.')
212
+ if obj.get('type') == 'tag' and isinstance(obj.get('sha'), str) and COMMIT.fullmatch(obj['sha']):
213
+ tag, _ = _fetch_json(API_ROOT + '/git/tags/' + obj['sha'])
214
+ obj = tag.get('object', {}) if isinstance(tag, dict) else {}
215
+ if not isinstance(obj, dict):
216
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Annotated tag object must be an object.')
217
+ if obj.get('type') != 'commit' or obj.get('sha') != manifest['source_commit']:
218
+ raise GovernanceError('UPDATE_IDENTITY_MISMATCH', 'Release tag does not resolve to the manifest commit.')
219
+ for file in manifest['artifacts']:
220
+ published = by_name.get(file['name'], {})
221
+ expected_url = RELEASES_URL + '/download/v' + version + '/' + file['name']
222
+ if (published.get('digest') != 'sha256:' + file['sha256'] or published.get('size') != file['size']
223
+ or published.get('browser_download_url') != expected_url):
224
+ raise GovernanceError('UPDATE_IDENTITY_MISMATCH', 'Release artifact metadata disagrees with the manifest.',
225
+ {'artifact': file['name']})
226
+ return {'version': version, 'release_url': manifest['release_url'], 'status': 'CANDIDATE',
227
+ 'manifest': manifest, 'manifest_sha256': digest, 'identity': _fingerprint(manifest),
228
+ 'identity_verified': True, 'verification_scope': 'official_manifest_tag_and_asset_metadata',
229
+ 'artifact_bytes_downloaded': False, 'installation_performed': False}
230
+
231
+ def update_check(self, channel=None):
232
+ source = self.store.get('update_sources', 'official')
233
+ if source is None:
234
+ raise GovernanceError('UPDATE_SOURCE_MISSING', 'Register the official source and current identity first.')
235
+ return self._check_official(source, channel)
236
+
237
+ def check_running_release(self):
238
+ """Inspect the stable channel without registering or modifying this project."""
239
+ recorded = self.store.get('update_sources', 'official') or {}
240
+ same_version = recorded.get('current_version') == __version__
241
+ current = {'channel': 'stable', 'revision': recorded.get('revision'), 'current_version': __version__,
242
+ 'current_artifacts': recorded.get('current_artifacts', []) if same_version else []}
243
+ return self._check_official(current, 'stable')
244
+
245
+ def _check_official(self, source, channel):
246
+ channel = channel or source['channel']
247
+ if channel not in ('rc', 'stable'):
248
+ raise GovernanceError('INVALID_ARGUMENT', 'channel must be rc or stable.')
249
+ result = {'repository': REPOSITORY, 'release_source': RELEASES_URL, 'channel': channel,
250
+ 'source_revision': source['revision'], 'current_version': source['current_version'],
251
+ 'current_artifacts': source['current_artifacts'], 'checked_at': now(),
252
+ 'network_read_only': True, 'local_state_written': False, 'installation_performed': False,
253
+ 'coverage': {'release_limit': 40, 'pages_max': 2, 'complete': False}, 'candidate': None}
254
+ try:
255
+ releases = []
256
+ for page in (1, 2):
257
+ values, _ = _fetch_json(API_ROOT + '/releases?per_page=20&page=' + str(page))
258
+ if not isinstance(values, list) or len(values) > 20:
259
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Invalid release-list page.')
260
+ releases.extend(values)
261
+ if len(values) < 20:
262
+ result['coverage']['complete'] = True
263
+ break
264
+ choices = []
265
+ for release in releases:
266
+ if not isinstance(release, dict) or release.get('draft') is not False:
267
+ continue
268
+ tag = release.get('tag_name', '')
269
+ if not isinstance(tag, str) or not tag.startswith('v') or not VERSION.fullmatch(tag[1:]):
270
+ continue
271
+ key = _version(tag[1:])
272
+ if not isinstance(release.get('prerelease'), bool) or release['prerelease'] != (key[3] == 0):
273
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'Release tag and prerelease flag disagree.')
274
+ if channel == 'stable' and release['prerelease']:
275
+ continue
276
+ choices.append((key, release))
277
+ if not choices:
278
+ result.update(status='NO_RELEASE_IN_WINDOW', latest_verified=False)
279
+ else:
280
+ key, release = max(choices, key=lambda item: item[0])
281
+ if key < _version(source['current_version']):
282
+ result.update(status='NO_NEWER_RELEASE_IN_WINDOW', latest_verified=False)
283
+ else:
284
+ candidate = self._candidate(release)
285
+ result['candidate'] = candidate
286
+ result['status'] = candidate['status']
287
+ result['latest_verified'] = result['coverage']['complete'] and candidate['identity_verified']
288
+ if candidate['identity_verified'] and key == _version(source['current_version']):
289
+ expected = {item['name']: item for item in candidate['manifest']['artifacts']}
290
+ if not source['current_artifacts']:
291
+ result['status'] = 'CURRENT_IDENTITY_INCOMPLETE'
292
+ elif all(expected.get(item['name']) == item for item in source['current_artifacts']):
293
+ result['status'] = 'CURRENT_MATCHES'
294
+ else:
295
+ result['status'] = 'SAME_VERSION_CONFLICT'
296
+ except (GovernanceError, urllib.error.URLError, OSError, TimeoutError, socket.timeout) as exc:
297
+ result.update(status='UNVERIFIED', latest_verified=False,
298
+ error={'code': getattr(exc, 'code', 'UPDATE_NETWORK_UNAVAILABLE'), 'message': str(exc),
299
+ 'details': getattr(exc, 'details', None)})
300
+ result['fingerprint'] = _fingerprint({key: value for key, value in result.items()
301
+ if key not in ('checked_at', 'fingerprint')})
302
+ return result
303
+
304
+ def update_assess(self, check, decision, reason, evidence_refs=None, expected_revision=None):
305
+ if not isinstance(check, dict) or check.get('repository') != REPOSITORY:
306
+ raise GovernanceError('INVALID_ARGUMENT', 'Provide an official update-check result.')
307
+ if (check.get('candidate') is not None and not isinstance(check['candidate'], dict)):
308
+ raise GovernanceError('UPDATE_METADATA_INVALID', 'The checked candidate must be an object or null.')
309
+ candidate = check.get('candidate') or {}
310
+ if candidate.get('identity_verified') is True:
311
+ manifest = validate_manifest(candidate.get('manifest'))
312
+ if candidate.get('identity') != _fingerprint(manifest) or candidate.get('version') != manifest['version']:
313
+ raise GovernanceError('UPDATE_IDENTITY_MISMATCH', 'The checked candidate identity does not match its manifest.')
314
+ calculated = _fingerprint({key: value for key, value in check.items() if key not in ('checked_at', 'fingerprint')})
315
+ if check.get('fingerprint') != calculated:
316
+ raise GovernanceError('UPDATE_CHECK_CHANGED', 'Check content no longer matches its fingerprint.')
317
+ if decision not in DECISIONS or not isinstance(reason, str) or not reason.strip() or len(reason) > 4000:
318
+ raise GovernanceError('INVALID_ARGUMENT', 'Supply a supported decision and bounded reason.')
319
+ if decision in ('prioritize', 'plan') and (check.get('status') not in ('CANDIDATE', 'CURRENT_MATCHES')
320
+ or not (check.get('candidate') or {}).get('identity_verified')):
321
+ raise GovernanceError('UPDATE_REVIEW_REQUIRED', 'Resolve the missing or conflicting identity before planning adoption.')
322
+ refs = evidence_refs or []
323
+ if (not isinstance(refs, list) or len(refs) > 30
324
+ or any(not isinstance(ref, str) or not ref.strip() or len(ref) > 2000 for ref in refs)):
325
+ raise GovernanceError('INVALID_ARGUMENT', 'evidence_refs must be bounded references.')
326
+ body = {'check_fingerprint': calculated, 'check': {k: v for k, v in check.items() if k != 'checked_at'},
327
+ 'decision': decision, 'reason': reason, 'evidence_refs': refs,
328
+ 'evidence_scope': 'host_reviewed_reference', 'installation_performed': False,
329
+ 'host_loading_verified': False}
330
+ with self.store.transaction():
331
+ source = self.store.get('update_sources', 'official')
332
+ if not source or source['revision'] != check.get('source_revision'):
333
+ raise GovernanceError('UPDATE_SOURCE_CHANGED', 'The registered source changed; check again.')
334
+ old = self.store.get('update_assessments', calculated)
335
+ if old and all(old.get(key) == value for key, value in body.items()):
336
+ return {'assessment': old, 'reused': True}
337
+ candidate = check.get('candidate') or {}
338
+ if candidate.get('identity_verified'):
339
+ key = candidate['version']
340
+ previous = self.store.get('update_release_identities', key)
341
+ if previous and previous['identity'] != candidate['identity']:
342
+ raise GovernanceError('UPDATE_IDENTITY_CONFLICT', 'The same release version now has different content.',
343
+ {'previous_identity': previous['identity'], 'candidate_identity': candidate['identity']})
344
+ if previous is None:
345
+ self.store.put('update_release_identities', key, candidate)
346
+ revision = _revision(expected_revision, old)
347
+ record = dict(body, revision=revision, updated_at=now(), created_at=old['created_at'] if old else now())
348
+ self.store.put('update_assessments', calculated, record)
349
+ self.store.put('update_assessments_history', calculated + '.' + str(revision), record)
350
+ self.store.event('update_assessed', record)
351
+ return {'assessment': record, 'reused': False}