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,775 @@
1
+ """Bounded governance evidence, resource reservations and read-only inventories.
2
+
3
+ The host supplies reviewed evidence; this module does not read chat history,
4
+ execute scheduled work, or turn a report into task/business acceptance. A durable
5
+ reservation survives process exit. Only ``cycle_session`` holds a real OS lock
6
+ between calls, and it releases that lock on exit, including exceptional exit.
7
+ """
8
+ from __future__ import annotations
9
+
10
+ from contextlib import contextmanager, ExitStack
11
+ from datetime import datetime, timedelta, timezone
12
+ import json
13
+ import os
14
+ from pathlib import Path, PurePosixPath
15
+ import stat
16
+ import threading
17
+
18
+ from .core import Core, _id, digest_bytes
19
+ from .chat_joins import absorb_join, join_inbox, mark_joins_reported
20
+ from .store import GovernanceError, _linked, now
21
+
22
+
23
+ def _hash(value):
24
+ return digest_bytes(json.dumps(value, sort_keys=True, ensure_ascii=False,
25
+ separators=(',', ':'), allow_nan=False).encode('utf-8'))
26
+
27
+
28
+ def _text(value, name, maximum=2048):
29
+ if not isinstance(value, str) or not value.strip() or len(value) > maximum or '\0' in value:
30
+ raise GovernanceError('INVALID_EVIDENCE', f'{name} must be nonempty text of at most {maximum} characters.')
31
+ return value
32
+
33
+
34
+ def _integer(value, name, low=1, high=1000):
35
+ if type(value) is not int or not low <= value <= high:
36
+ raise GovernanceError('INVALID_BUDGET', f'{name} must be an integer from {low} to {high}.')
37
+ return value
38
+
39
+
40
+ def _record(value, schema):
41
+ if value is not None and (not isinstance(value, dict) or value.get('schema') != schema):
42
+ raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible toolkit for this evidence record.',
43
+ {'expected_schema': schema})
44
+ return value
45
+
46
+
47
+ def _stamp(value, name):
48
+ _text(value, name, 128)
49
+ try:
50
+ result = datetime.fromisoformat(value.replace('Z', '+00:00'))
51
+ if result.utcoffset() is None:
52
+ raise ValueError('Timezone required')
53
+ return result
54
+ except ValueError as exc:
55
+ raise GovernanceError('INVALID_TIME', f'{name} needs an ISO timestamp with a timezone.') from exc
56
+
57
+
58
+ def _scope(values):
59
+ if not isinstance(values, list) or not 1 <= len(values) <= 100:
60
+ raise GovernanceError('INVALID_SCOPE', 'Declare between 1 and 100 exact resource identities.')
61
+ values = [_text(value, 'Resource identity', 256) for value in values]
62
+ if len(set(values)) != len(values):
63
+ raise GovernanceError('INVALID_SCOPE', 'Resource identities must be unique.')
64
+ return sorted(values)
65
+
66
+
67
+ @contextmanager
68
+ def _os_lock(directory, resource):
69
+ path = directory / ('cycle-' + _hash(resource) + '.lock')
70
+ if _linked(directory) or _linked(path):
71
+ raise GovernanceError('UNSAFE_METADATA', 'A cycle lock cannot traverse a link.')
72
+ handle = open(path, 'a+b')
73
+ held = False
74
+ try:
75
+ handle.seek(0, os.SEEK_END)
76
+ if handle.tell() == 0:
77
+ handle.write(b'0')
78
+ handle.flush()
79
+ handle.seek(0)
80
+ try:
81
+ if os.name == 'nt':
82
+ import msvcrt
83
+ msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
84
+ else:
85
+ import fcntl
86
+ fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
87
+ except OSError as exc:
88
+ raise GovernanceError('CYCLE_BUSY', 'A live process holds this cycle resource lock.',
89
+ {'resource': resource}) from exc
90
+ held = True
91
+ yield
92
+ finally:
93
+ try:
94
+ if held:
95
+ handle.seek(0)
96
+ if os.name == 'nt':
97
+ import msvcrt
98
+ msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1)
99
+ else:
100
+ import fcntl
101
+ fcntl.flock(handle, fcntl.LOCK_UN)
102
+ finally:
103
+ handle.close()
104
+
105
+
106
+ class GovernanceCycle(Core):
107
+ """Evidence over existing tasks, without a second task state machine."""
108
+
109
+ def __init__(self, project):
110
+ super().__init__(project)
111
+ self._cycle_local = threading.local()
112
+
113
+ @contextmanager
114
+ def _resource_guard(self, cycle_id, owner, scope):
115
+ active = getattr(self._cycle_local, 'session', None)
116
+ if active is not None:
117
+ if active != (cycle_id, owner, scope):
118
+ raise GovernanceError('CYCLE_SESSION_MISMATCH', 'This live session belongs to another exact cycle, owner or scope.')
119
+ yield
120
+ return
121
+ with ExitStack() as stack:
122
+ for resource in scope:
123
+ stack.enter_context(_os_lock(self.store.directory, resource))
124
+ yield
125
+
126
+ @contextmanager
127
+ def cycle_session(self, cycle_id, owner, scope, task_id=None, resume=False):
128
+ """Hold real resource locks for a live host process, not a database lock.
129
+
130
+ An unfinished reservation survives EOF/crash; another process must use
131
+ the same cycle/owner/scope to resume. There is no TTL lock stealing.
132
+ ``finish`` closes the reservation, but OS locks last until context exit.
133
+ """
134
+ cycle_id, owner, scope = _id(cycle_id, 'Cycle ID'), _id(owner, 'Owner'), _scope(scope)
135
+ if getattr(self._cycle_local, 'session', None) is not None:
136
+ raise GovernanceError('CYCLE_SESSION_MISMATCH', 'Nested cycle sessions are not supported.')
137
+ with self._resource_guard(cycle_id, owner, scope):
138
+ self._cycle_local.session = (cycle_id, owner, scope)
139
+ try:
140
+ self.cycle('resume' if resume else 'start', cycle_id=cycle_id,
141
+ owner=owner, scope=scope, task_id=task_id)
142
+ yield self
143
+ finally:
144
+ self._cycle_local.session = None
145
+
146
+ def _read(self, collection, key, schema):
147
+ return _record(self.store.get(collection, key), schema)
148
+
149
+ def _page(self, collection, prefix='', cursor=None, limit=20):
150
+ _integer(limit, 'Limit', 1, 100)
151
+ if cursor is not None:
152
+ _text(cursor, 'Cursor', 1024)
153
+ if not cursor.startswith(prefix):
154
+ raise GovernanceError('INVALID_CURSOR', 'The cursor belongs to another selection.')
155
+ with self.store._connect(readonly=True) as db:
156
+ rows = db.execute('SELECT key,value FROM records WHERE collection=? AND key>=? AND key<? '
157
+ 'AND key>? ORDER BY key LIMIT ?',
158
+ (collection, prefix, prefix + '\U0010ffff', cursor or '', limit + 1)).fetchall()
159
+ return {'items': [json.loads(value) for _, value in rows[:limit]],
160
+ 'next_cursor': rows[limit - 1][0] if len(rows) > limit else None}
161
+
162
+ def _cycle_status(self, value):
163
+ result = dict(value)
164
+ if 'chat-joins' in value['scope']:
165
+ result['chat_join_intake'] = ('Read every join_inbox new page, then join_absorb each authorized receipt. '
166
+ 'Report slots also read pending_report; acknowledge the included join_ids only after actual report delivery.')
167
+ result['lock'] = {'durable_reservation': value['state'] != 'completed',
168
+ 'os_lock_held_by_this_session': getattr(self._cycle_local, 'session', None) ==
169
+ (value['cycle_id'], value['owner'], value['scope']),
170
+ 'meaning': 'Ordinary calls hold OS locks only during that call; use cycle_session for a whole live process session.'}
171
+ current = datetime.now(timezone.utc)
172
+ result['health'] = {}
173
+ for name, health in value.get('health', {}).items():
174
+ age = (current - _stamp(health['observed_at'], 'Observed time')).total_seconds()
175
+ result['health'][name] = {**health, 'age_seconds': age,
176
+ 'effective_status': health['status'] if 0 <= age <= health['freshness_seconds'] else 'unknown'}
177
+ return result
178
+
179
+ def cycle(self, action, cycle_id=None, owner=None, task_id=None, scope=None,
180
+ request_id=None, data=None, limit=20, cursor=None):
181
+ """Start/resume a finite reserved cycle or record reviewed effects/receipts.
182
+
183
+ Mutation payloads are supplied in ``data``; ``request_id`` is an immutable
184
+ idempotency key scoped to the cycle. This method never executes an effect.
185
+ """
186
+ if action == 'list':
187
+ page = self._page('governance_cycles', cursor=cursor, limit=limit)
188
+ page['items'] = [self._cycle_status(_record(item, 'taskcarry.cycle.v1')) for item in page['items']]
189
+ return page
190
+ cycle_id = _id(cycle_id, 'Cycle ID')
191
+ if action not in ('status', 'question_check', 'join_inbox') and cycle_id in (
192
+ self.store.get('config', 'project') or {}).get('recovery_inert_cycle_ids', []):
193
+ raise GovernanceError('RESTORED_RUN_INERT', 'Historical cycles cannot be replayed on a recovered replica.')
194
+ record = self._read('governance_cycles', cycle_id, 'taskcarry.cycle.v1')
195
+ if action == 'status':
196
+ if record is None:
197
+ raise GovernanceError('CYCLE_NOT_FOUND', 'Start this cycle before reading it.')
198
+ return {'cycle': self._cycle_status(record)}
199
+ owner = _id(owner, 'Owner')
200
+ if action in ('start', 'resume'):
201
+ declared = _scope(scope)
202
+ if action == 'start':
203
+ task_id = _id(task_id, 'Task ID')
204
+ with self._resource_guard(cycle_id, owner, declared), self.store.transaction():
205
+ record = self._read('governance_cycles', cycle_id, 'taskcarry.cycle.v1')
206
+ if record:
207
+ if record['owner'] != owner or record['scope'] != declared or (task_id is not None and record['task_id'] != task_id):
208
+ raise GovernanceError('CYCLE_ID_CONFLICT', 'Resume requires the original owner, task and exact resource scope.')
209
+ return {'cycle': self._cycle_status(record), 'reused': True}
210
+ if action == 'resume':
211
+ raise GovernanceError('CYCLE_NOT_FOUND', 'No retained cycle exists to resume.')
212
+ self._task(task_id)
213
+ for resource in declared:
214
+ prior = self._read('cycle_reservations', _hash(resource), 'taskcarry.cycle_reservation.v1')
215
+ if prior and prior.get('state', 'reserved') != 'released' and prior['cycle_id'] != cycle_id:
216
+ raise GovernanceError('CYCLE_RESERVED', 'An unfinished cycle retains this resource; inspect and resume it.', prior)
217
+ record = {'schema': 'taskcarry.cycle.v1', 'cycle_id': cycle_id, 'owner': owner,
218
+ 'task_id': task_id, 'scope': declared, 'state': 'active', 'created_at': now(),
219
+ 'effects': {}, 'sources': {}, 'health': {}, 'questions': {}, 'reports': {}, 'revision': 1}
220
+ for resource in declared:
221
+ self.store.put('cycle_reservations', _hash(resource), {'schema': 'taskcarry.cycle_reservation.v1',
222
+ 'resource': resource, 'cycle_id': cycle_id, 'owner': owner, 'task_id': task_id, 'state': 'reserved'})
223
+ self.store.put('governance_cycles', cycle_id, record)
224
+ self.store.event('cycle_started', {'cycle_id': cycle_id, 'owner': owner, 'task_id': task_id, 'scope': declared})
225
+ return {'cycle': self._cycle_status(record), 'reused': False}
226
+ if record is None:
227
+ raise GovernanceError('CYCLE_NOT_FOUND', 'Start this cycle before recording evidence.')
228
+ if owner != record['owner']:
229
+ raise GovernanceError('CYCLE_OWNER_MISMATCH', 'Continue using the original cycle owner.')
230
+ if task_id is not None and task_id != record['task_id']:
231
+ raise GovernanceError('CYCLE_ID_CONFLICT', 'A cycle cannot move to another task.')
232
+ if scope is not None and _scope(scope) != record['scope']:
233
+ raise GovernanceError('CYCLE_ID_CONFLICT', 'A cycle cannot change its declared resources.')
234
+ data = {} if data is None else data
235
+ if not isinstance(data, dict) or len(json.dumps(data, allow_nan=False)) > 65536:
236
+ raise GovernanceError('INVALID_EVIDENCE', 'Cycle payload must be an object of at most 64 KiB.')
237
+ if action == 'question_check':
238
+ return self._question_check(data)
239
+ if action == 'join_inbox':
240
+ return join_inbox(self, record, data, limit, cursor)
241
+ request_id = _id(request_id, 'Request ID')
242
+ request_key = cycle_id + ':' + request_id
243
+ fingerprint = _hash({'action': action, 'owner': owner, 'data': data})
244
+ with self._resource_guard(cycle_id, owner, record['scope']), self.store.transaction():
245
+ record = self._read('governance_cycles', cycle_id, 'taskcarry.cycle.v1')
246
+ previous = self._read('cycle_requests', request_key, 'taskcarry.cycle_request.v1')
247
+ if previous:
248
+ if previous['fingerprint'] != fingerprint:
249
+ raise GovernanceError('IDEMPOTENCY_CONFLICT', 'An idempotency key cannot describe a different effect or receipt.')
250
+ return {'cycle': self._cycle_status(record), 'receipt': previous, 'reused': True}
251
+ if record['state'] == 'completed':
252
+ raise GovernanceError('CYCLE_CLOSED', 'A completed cycle cannot accept new mutations.')
253
+ outcome = self._cycle_apply(record, action, data)
254
+ record['revision'] += 1
255
+ record['updated_at'] = now()
256
+ receipt = {'schema': 'taskcarry.cycle_request.v1', 'cycle_id': cycle_id,
257
+ 'request_id': request_id, 'fingerprint': fingerprint, 'action': action,
258
+ 'cycle_revision': record['revision'], 'recorded_at': now(), 'result': outcome}
259
+ self.store.put('governance_cycles', cycle_id, record)
260
+ self.store.put('cycle_requests', request_key, receipt)
261
+ self.store.event('cycle_evidence_recorded', {'cycle_id': cycle_id, 'request_id': request_id,
262
+ 'action': action, 'revision': record['revision'], 'task_id': record['task_id']})
263
+ return {'cycle': self._cycle_status(record), 'receipt': receipt, 'reused': False}
264
+
265
+ @staticmethod
266
+ def _fields(data, required, optional=()):
267
+ if set(data) - set(required) - set(optional) or set(required) - set(data):
268
+ raise GovernanceError('INVALID_EVIDENCE', 'Payload fields do not match this action.',
269
+ {'required': list(required), 'optional': list(optional)})
270
+
271
+ @staticmethod
272
+ def _bounded(mapping, key, maximum=100):
273
+ if key not in mapping and len(mapping) >= maximum:
274
+ raise GovernanceError('CYCLE_CAPACITY', 'Close this finite cycle before adding further distinct evidence.')
275
+
276
+ def _cycle_apply(self, record, action, data):
277
+ if action == 'join_absorb':
278
+ return absorb_join(self, record, data)
279
+ if action == 'effect_plan':
280
+ self._fields(data, ('effect_id', 'kind', 'resource', 'expected'))
281
+ identity = _id(data['effect_id'], 'Effect ID')
282
+ _text(data['kind'], 'Effect kind', 100)
283
+ _text(data['expected'], 'Expected observable outcome', 8192)
284
+ if data['resource'] not in record['scope']:
285
+ raise GovernanceError('CYCLE_SCOPE_MISMATCH', 'The effect resource is outside the frozen cycle scope.')
286
+ self._bounded(record['effects'], identity)
287
+ existing = record['effects'].get(identity)
288
+ if existing and existing['plan'] != data:
289
+ raise GovernanceError('EFFECT_CONFLICT', 'A planned effect cannot be redefined.')
290
+ record['effects'].setdefault(identity, {'plan': data, 'outcome': 'pending'})
291
+ return record['effects'][identity]
292
+ if action == 'effect_result':
293
+ self._fields(data, ('effect_id', 'outcome', 'evidence_ref', 'statement'))
294
+ identity = _id(data['effect_id'], 'Effect ID')
295
+ effect = record['effects'].get(identity)
296
+ if effect is None:
297
+ raise GovernanceError('EFFECT_NOT_PLANNED', 'Record the expected effect before its result.')
298
+ if data['outcome'] not in ('confirmed', 'rejected', 'deferred', 'failed'):
299
+ raise GovernanceError('INVALID_EVIDENCE', 'Unsupported effect outcome.')
300
+ _text(data['evidence_ref'], 'Evidence reference')
301
+ _text(data['statement'], 'Verified effect statement', 8192)
302
+ if effect['outcome'] in ('confirmed', 'rejected') and effect.get('result') != data:
303
+ raise GovernanceError('EFFECT_TERMINAL', 'A terminal effect receipt cannot be rewritten.')
304
+ effect.update(outcome=data['outcome'], result=data)
305
+ return effect
306
+ if action == 'source':
307
+ self._fields(data, ('source_id', 'source_revision', 'phase', 'evidence_ref', 'statement'), ('target',))
308
+ for name in ('source_id', 'source_revision'):
309
+ _text(data[name], name, 512)
310
+ _text(data['evidence_ref'], 'Evidence reference')
311
+ _text(data['statement'], 'Source interpretation', 8192)
312
+ phases = ('observed', 'understood', 'published', 'consumed')
313
+ if data['phase'] not in phases:
314
+ raise GovernanceError('INVALID_EVIDENCE', 'Unsupported source phase.')
315
+ if data['phase'] in ('published', 'consumed'):
316
+ _text(data.get('target'), 'Exact target')
317
+ elif 'target' in data:
318
+ raise GovernanceError('INVALID_EVIDENCE', 'Observed and understood phases do not name a delivery target.')
319
+ identity = _hash([data['source_id'], data['source_revision']])
320
+ self._bounded(record['sources'], identity)
321
+ source = record['sources'].setdefault(identity, {'source_id': data['source_id'],
322
+ 'source_revision': data['source_revision'], 'phases': {}})
323
+ target_key = data['phase'] + (':' + data['target'] if 'target' in data else '')
324
+ index = phases.index(data['phase'])
325
+ predecessor = phases[index - 1] + (':' + data['target'] if data['phase'] == 'consumed' else '') if index else None
326
+ if predecessor and predecessor not in source['phases']:
327
+ raise GovernanceError('SOURCE_PHASE_MISSING', 'Record the preceding source phase for this exact revision and target.')
328
+ self._bounded(source['phases'], target_key)
329
+ prior = source['phases'].get(target_key)
330
+ if prior and prior != data:
331
+ raise GovernanceError('SOURCE_PHASE_CONFLICT', 'Source evidence is immutable for each revision, phase and target.')
332
+ source['phases'][target_key] = data
333
+ return source
334
+ if action == 'health':
335
+ self._fields(data, ('dimension', 'status', 'observed_at', 'freshness_seconds', 'evidence_ref'))
336
+ dimension = _text(data['dimension'], 'Health dimension', 128)
337
+ _text(data['evidence_ref'], 'Evidence reference')
338
+ if data['status'] not in ('healthy', 'degraded', 'failed', 'unknown'):
339
+ raise GovernanceError('INVALID_EVIDENCE', 'Unsupported health status.')
340
+ timestamp = _stamp(data['observed_at'], 'Observation time')
341
+ if timestamp > datetime.now(timezone.utc) + timedelta(minutes=5):
342
+ raise GovernanceError('INVALID_TIME', 'A health observation cannot be in the future.')
343
+ _integer(data['freshness_seconds'], 'Freshness seconds', 1, 2678400)
344
+ self._bounded(record['health'], dimension)
345
+ prior = record['health'].get(dimension)
346
+ if prior and timestamp < _stamp(prior['observed_at'], 'Previous observation time'):
347
+ raise GovernanceError('HEALTH_STALE_WRITE', 'An older observation cannot replace a newer health observation.')
348
+ record['health'][dimension] = data
349
+ return data
350
+ if action in ('question_delivered', 'report_delivered', 'question_response'):
351
+ return self._delivery(record, action, data)
352
+ if action == 'finish':
353
+ self._fields(data, ('state', 'next_step'))
354
+ if data['state'] not in ('completed', 'waiting'):
355
+ raise GovernanceError('INVALID_EVIDENCE', 'Finish state must be completed or waiting.')
356
+ _text(data['next_step'], 'Next step', 8192)
357
+ unresolved = [key for key, effect in record['effects'].items() if effect['outcome'] not in ('confirmed', 'rejected')]
358
+ if data['state'] == 'completed' and unresolved:
359
+ raise GovernanceError('CYCLE_EFFECTS_PENDING', 'Verify actual effects before completing this cycle.', {'effects': unresolved})
360
+ record.update(data)
361
+ if data['state'] == 'completed':
362
+ for resource in record['scope']:
363
+ prior = self._read('cycle_reservations', _hash(resource), 'taskcarry.cycle_reservation.v1')
364
+ if not prior or prior['cycle_id'] != record['cycle_id']:
365
+ raise GovernanceError('CYCLE_RESERVATION_CHANGED', 'A reserved resource changed unexpectedly.')
366
+ self.store.put('cycle_reservations', _hash(resource), {**prior, 'state': 'released', 'released_at': now()})
367
+ return {'state': record['state'], 'next_step': record['next_step'], 'unresolved_effects': unresolved,
368
+ 'meaning': 'Cycle evidence closeout; existing task and business acceptance are unchanged.'}
369
+ raise GovernanceError('INVALID_ACTION', 'Unknown cycle action.')
370
+
371
+ def _question_check(self, data):
372
+ self._fields(data, ('question_id',), ('local_date',))
373
+ identity = _text(data['question_id'], 'Question ID', 512)
374
+ record = self._read('cycle_questions', _hash(identity), 'taskcarry.question.v1')
375
+ if record is None:
376
+ return {'question_id': identity, 'answered': False, 'distinct_dates': [], 'stop_proactive': False}
377
+ return {**record, 'stop_proactive': record['answered'] or len(record['distinct_dates']) >= record['max_distinct_dates'],
378
+ 'already_delivered_on_date': data.get('local_date') in record['distinct_dates']}
379
+
380
+ def _delivery(self, cycle, action, data):
381
+ question = action != 'report_delivered'
382
+ name = 'question_id' if question else 'report_id'
383
+ identity = _text(data.get(name), name, 512)
384
+ if action == 'question_response':
385
+ self._fields(data, (name, 'receipt_ref', 'statement'))
386
+ _text(data['receipt_ref'], 'Actual response receipt')
387
+ _text(data['statement'], 'Response statement', 8192)
388
+ record = self._read('cycle_questions', _hash(identity), 'taskcarry.question.v1')
389
+ if record is None:
390
+ raise GovernanceError('QUESTION_NOT_FOUND', 'Record the delivered question before its response.')
391
+ if record.get('response') and record['response'] != data:
392
+ raise GovernanceError('RECEIPT_CONFLICT', 'The retained response receipt cannot be replaced.')
393
+ record.update(answered=True, response=data)
394
+ self.store.put('cycle_questions', _hash(identity), record)
395
+ return record
396
+ self._fields(data, (name, 'receipt_ref', 'delivered_at', 'utc_offset_minutes', 'local_date'),
397
+ ('max_distinct_dates',) if question else ('join_ids',))
398
+ _text(data['receipt_ref'], 'Actual native delivery receipt')
399
+ delivered = _stamp(data['delivered_at'], 'Delivered time')
400
+ offset = _integer(data['utc_offset_minutes'], 'UTC offset minutes', -720, 840)
401
+ if delivered > datetime.now(timezone.utc) + timedelta(minutes=5):
402
+ raise GovernanceError('INVALID_TIME', 'A delivery receipt cannot claim a future delivery.')
403
+ actual_date = delivered.astimezone(timezone(timedelta(minutes=offset))).date().isoformat()
404
+ if data['local_date'] != actual_date:
405
+ raise GovernanceError('DELIVERY_DATE_MISMATCH', 'Use the actual delivery date in the declared timezone.')
406
+ delivery_key = _hash([name, identity, data['receipt_ref']])
407
+ prior_delivery = self._read('cycle_deliveries', delivery_key, 'taskcarry.delivery.v1')
408
+ delivery_body = {key: value for key, value in data.items() if key != 'max_distinct_dates'}
409
+ if prior_delivery and prior_delivery['delivery'] != delivery_body:
410
+ raise GovernanceError('RECEIPT_CONFLICT', 'An actual delivery receipt cannot be assigned another date or content.')
411
+ if prior_delivery is None:
412
+ self.store.put('cycle_deliveries', delivery_key, {'schema': 'taskcarry.delivery.v1', 'delivery': delivery_body})
413
+ if question:
414
+ maximum = _integer(data.get('max_distinct_dates', 2), 'Maximum distinct dates', 1, 10)
415
+ key = _hash(identity)
416
+ record = self._read('cycle_questions', key, 'taskcarry.question.v1') or {
417
+ 'schema': 'taskcarry.question.v1', 'question_id': identity, 'distinct_dates': [],
418
+ 'max_distinct_dates': maximum, 'answered': False}
419
+ if maximum != record['max_distinct_dates']:
420
+ raise GovernanceError('QUESTION_POLICY_CHANGED', 'A question cannot silently reset its reminder policy.')
421
+ dates = sorted(set(record['distinct_dates'] + [actual_date]))
422
+ if len(dates) > 100:
423
+ raise GovernanceError('QUESTION_CAPACITY', 'Question date history has reached its explicit bound.')
424
+ record.update(distinct_dates=dates, last_delivery=data,
425
+ over_limit=len(dates) > maximum,
426
+ stop_proactive=record['answered'] or len(dates) >= maximum)
427
+ self.store.put('cycle_questions', key, record)
428
+ self._bounded(cycle['questions'], identity)
429
+ cycle['questions'][identity] = {'local_date': actual_date, 'receipt_ref': data['receipt_ref']}
430
+ return record
431
+ key = _hash([identity, actual_date])
432
+ prior = self._read('cycle_reports', key, 'taskcarry.report.v1')
433
+ if prior and prior['delivery'] != data:
434
+ raise GovernanceError('REPORT_ALREADY_DELIVERED', 'This report already has a retained receipt on that date.', prior)
435
+ if 'join_ids' in data:
436
+ mark_joins_reported(self, cycle, data)
437
+ record = prior or {'schema': 'taskcarry.report.v1', 'report_id': identity, 'local_date': actual_date, 'delivery': data}
438
+ self.store.put('cycle_reports', key, record)
439
+ self._bounded(cycle['reports'], key)
440
+ cycle['reports'][key] = record
441
+ return record
442
+
443
+ def facts(self, action, fact_id=None, source_id=None, source_revision=None,
444
+ task_id=None, kind=None, statement=None, evidence=None, judgment=None,
445
+ relations=None, aliases=None, standing='current', expected_revision=None,
446
+ limit=20, cursor=None):
447
+ """Source-qualified facts with immutable history and revision CAS.
448
+
449
+ Evidence is the host's source reference; judgment is separately labelled
450
+ interpretation. Neither becomes an independently verified observation.
451
+ """
452
+ source_id = self.source()['source_id'] if source_id is None else _text(source_id, 'Source ID', 512)
453
+ if action == 'list':
454
+ page = self._page('governance_facts', _hash(source_id) + ':', cursor, limit)
455
+ page['items'] = [_record(item, 'taskcarry.fact.v1') for item in page['items']]
456
+ return page
457
+ fact_id = _id(fact_id, 'Fact ID')
458
+ key = _hash(source_id) + ':' + fact_id
459
+ prior = self._read('governance_facts', key, 'taskcarry.fact.v1')
460
+ if action == 'history':
461
+ page = self._page('governance_fact_history', key + ':', cursor, limit)
462
+ page['items'] = [_record(item, 'taskcarry.fact.v1') for item in page['items']]
463
+ return page
464
+ if action == 'get':
465
+ if prior is None:
466
+ raise GovernanceError('FACT_NOT_FOUND', 'No fact exists for this source-qualified identity.')
467
+ return {'fact': prior}
468
+ if action != 'record':
469
+ raise GovernanceError('INVALID_ACTION', 'Unknown facts action.')
470
+ task_id = _id(task_id, 'Task ID')
471
+ _text(source_revision, 'Source revision', 512)
472
+ _text(statement, 'Source statement', 8192)
473
+ if kind not in ('decision', 'artifact', 'relationship', 'alias', 'status'):
474
+ raise GovernanceError('INVALID_EVIDENCE', 'Unsupported fact kind.')
475
+ if standing not in ('current', 'superseded', 'historical', 'disputed'):
476
+ raise GovernanceError('INVALID_EVIDENCE', 'Unsupported current standing.')
477
+ if not isinstance(evidence, dict) or set(evidence) != {'reference', 'summary'}:
478
+ raise GovernanceError('INVALID_EVIDENCE', 'Evidence requires an exact reference and source summary.')
479
+ _text(evidence['reference'], 'Source evidence reference')
480
+ _text(evidence['summary'], 'Source evidence summary', 8192)
481
+ if judgment is not None:
482
+ if not isinstance(judgment, dict) or set(judgment) != {'statement', 'basis'}:
483
+ raise GovernanceError('INVALID_EVIDENCE', 'Judgment requires a separate statement and basis.')
484
+ _text(judgment['statement'], 'AI judgment', 8192)
485
+ _text(judgment['basis'], 'Judgment basis', 8192)
486
+ if expected_revision is not None:
487
+ _integer(expected_revision, 'Expected revision', 1, 2147483647)
488
+ relations = [] if relations is None else relations
489
+ aliases = [] if aliases is None else aliases
490
+ if not isinstance(relations, list) or len(relations) > 100 or not isinstance(aliases, list) or len(aliases) > 100:
491
+ raise GovernanceError('INVALID_RELATION', 'Facts support at most 100 explicit relations and aliases.')
492
+ normalized = []
493
+ for relation in relations:
494
+ if not isinstance(relation, dict) or set(relation) != {'source_id', 'fact_id', 'relation'}:
495
+ raise GovernanceError('INVALID_RELATION', 'Relations require source_id, fact_id and relation.')
496
+ normalized.append({'source_id': _text(relation['source_id'], 'Related source', 512),
497
+ 'fact_id': _id(relation['fact_id'], 'Related fact'),
498
+ 'relation': _text(relation['relation'], 'Relation', 128)})
499
+ if len({_hash(value) for value in normalized}) != len(normalized):
500
+ raise GovernanceError('INVALID_RELATION', 'Relationships must be unique.')
501
+ aliases = sorted(_text(value, 'Alias', 512) for value in aliases)
502
+ if len(set(aliases)) != len(aliases):
503
+ raise GovernanceError('INVALID_RELATION', 'Aliases must be unique.')
504
+ body = {'source_id': source_id, 'fact_id': fact_id, 'source_revision': source_revision,
505
+ 'task_id': task_id, 'kind': kind, 'statement': statement, 'evidence': evidence,
506
+ 'judgment': judgment, 'relations': sorted(normalized, key=_hash), 'aliases': aliases, 'standing': standing}
507
+ fingerprint = _hash(body)
508
+ with self.store.transaction():
509
+ self._task(task_id)
510
+ prior = self._read('governance_facts', key, 'taskcarry.fact.v1')
511
+ if prior and (prior['task_id'] != task_id or prior['kind'] != kind):
512
+ raise GovernanceError('FACT_ID_CONFLICT', 'A fact identity cannot change task or kind.')
513
+ if prior and prior['fingerprint'] == fingerprint:
514
+ return {'fact': prior, 'reused': True}
515
+ if expected_revision != (prior['revision'] if prior else None):
516
+ raise GovernanceError('FACT_CHANGED', 'Reread the current fact before replacing its revision.',
517
+ {'current_revision': prior['revision'] if prior else None})
518
+ for relation in normalized:
519
+ related = self._read('governance_facts', _hash(relation['source_id']) + ':' + relation['fact_id'], 'taskcarry.fact.v1')
520
+ if related is None:
521
+ raise GovernanceError('RELATED_FACT_NOT_FOUND', 'Register the source-qualified related fact first.', relation)
522
+ record = {'schema': 'taskcarry.fact.v1', **body, 'revision': prior['revision'] + 1 if prior else 1,
523
+ 'fingerprint': fingerprint, 'recorded_at': now(), 'host_reviewed': True,
524
+ 'meaning': 'Retained source evidence and separately labelled interpretation; no independent source verification or authorization.'}
525
+ self.store.put('governance_facts', key, record)
526
+ self.store.put('governance_fact_history', key + ':' + str(record['revision']).zfill(10), record)
527
+ self.store.event('governance_fact_recorded', {'source_id': source_id, 'fact_id': fact_id,
528
+ 'task_id': task_id, 'revision': record['revision'], 'fingerprint': fingerprint})
529
+ return {'fact': record, 'reused': False}
530
+
531
+ @staticmethod
532
+ def _source_root(value):
533
+ _text(value, 'Authorized root', 4096)
534
+ path = Path(value).expanduser().absolute()
535
+ if any(_linked(item) for item in (path, *path.parents)) or not path.is_dir():
536
+ raise GovernanceError('SOURCE_UNAVAILABLE', 'The authorized source root must be an existing directory without links.')
537
+ return path.resolve()
538
+
539
+ @staticmethod
540
+ def _exclusions(values):
541
+ if not isinstance(values, list) or len(values) > 100:
542
+ raise GovernanceError('INVALID_SCOPE', 'At most 100 excluded subtrees may be declared.')
543
+ result = {'.git', '.taskcarry'}
544
+ for value in values:
545
+ _text(value, 'Excluded subtree', 1024)
546
+ path = PurePosixPath(value)
547
+ if '\\' in value or ':' in value or path.is_absolute() or any(part in ('.', '..') for part in value.split('/')):
548
+ raise GovernanceError('INVALID_SCOPE', 'Exclusions must be safe relative subtree paths using forward slashes.')
549
+ result.add(path.as_posix().rstrip('/'))
550
+ return sorted(result)
551
+
552
+ @staticmethod
553
+ def _watermark(path):
554
+ info = path.stat(follow_symlinks=False)
555
+ if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400 or not stat.S_ISDIR(info.st_mode):
556
+ raise GovernanceError('SOURCE_CHANGED', 'A source directory became a link or non-directory.')
557
+ return [info.st_dev, info.st_ino, info.st_mtime_ns]
558
+
559
+ def _scan_summary(self, record):
560
+ return {key: value for key, value in record.items() if key not in ('stack', 'watermarks')}
561
+
562
+ def source_scan(self, action, source_id, root=None, authorization_ref=None,
563
+ exclusions=None, expected_revision=None, scan_id=None,
564
+ cursor=None, max_entries=200, max_directory_entries=10000,
565
+ max_directories=1000, max_total_entries=100000):
566
+ """Register an authorized metadata source, then page a frozen scan plan.
567
+
568
+ Metadata only: no file bodies, network calls or source writes. Each
569
+ directory listing is bounded and frozen before paging. Directory changes
570
+ invalidate continuation; oversized directories produce an incomplete
571
+ inventory, never a deletion claim. File metadata observations occur over
572
+ a time window and are explicitly not an atomic filesystem snapshot.
573
+ """
574
+ source_id = _text(source_id, 'Source ID', 512)
575
+ key = _hash(source_id)
576
+ registry = self._read('scan_sources', key, 'taskcarry.scan_source.v1')
577
+ if action == 'register':
578
+ authorized = self._source_root(root)
579
+ if authorized == self.root or authorized in self.root.parents:
580
+ raise GovernanceError('SOURCE_OUTPUT_OVERLAP', 'Keep governance output outside the read-only source root.')
581
+ excluded = self._exclusions([] if exclusions is None else exclusions)
582
+ _text(authorization_ref, 'Root authorization reference')
583
+ if expected_revision is not None:
584
+ _integer(expected_revision, 'Expected source revision', 1, 2147483647)
585
+ body = {'source_id': source_id, 'root': str(authorized), 'exclusions': excluded,
586
+ 'authorization_ref': authorization_ref}
587
+ fingerprint = _hash(body)
588
+ with self.store.transaction():
589
+ registry = self._read('scan_sources', key, 'taskcarry.scan_source.v1')
590
+ if registry and registry['fingerprint'] == fingerprint:
591
+ return {'source': registry, 'reused': True}
592
+ if expected_revision != (registry['revision'] if registry else None):
593
+ raise GovernanceError('SOURCE_REGISTRY_CHANGED', 'Reread the authorized source before replacing its configuration.')
594
+ registry = {'schema': 'taskcarry.scan_source.v1', **body, 'fingerprint': fingerprint,
595
+ 'revision': registry['revision'] + 1 if registry else 1, 'recorded_at': now()}
596
+ self.store.put('scan_sources', key, registry)
597
+ self.store.event('scan_source_registered', {'source_id': source_id, 'revision': registry['revision'],
598
+ 'fingerprint': fingerprint})
599
+ return {'source': registry, 'reused': False}
600
+ if registry is None:
601
+ raise GovernanceError('SOURCE_NOT_REGISTERED', 'Register an explicitly authorized root before scanning.')
602
+ if action == 'registry':
603
+ return {'source': registry}
604
+ scan_id = _id(scan_id, 'Scan ID')
605
+ scan_key = key + ':' + scan_id
606
+ if action == 'start':
607
+ _integer(max_entries, 'Entries per page', 1, 1000)
608
+ _integer(max_directory_entries, 'Entries per directory', 1, 10000)
609
+ _integer(max_directories, 'Directories per scan', 1, 2000)
610
+ _integer(max_total_entries, 'Entries per scan', 1, 100000)
611
+ budget = {'max_entries': max_entries, 'max_directory_entries': max_directory_entries,
612
+ 'max_directories': max_directories, 'max_total_entries': max_total_entries}
613
+ plan = {'source_revision': registry['revision'], 'source_fingerprint': registry['fingerprint'], 'budgets': budget}
614
+ with self.store.transaction():
615
+ prior = self._read('source_scans', scan_key, 'taskcarry.source_scan.v1')
616
+ if prior:
617
+ if prior['plan'] != plan:
618
+ raise GovernanceError('SCAN_ID_CONFLICT', 'A scan ID retains its original source and budgets.')
619
+ return {'scan': self._scan_summary(prior), 'reused': True}
620
+ source_root = self._source_root(registry['root'])
621
+ record = {'schema': 'taskcarry.source_scan.v1', 'source_id': source_id, 'scan_id': scan_id,
622
+ 'source': registry, 'plan': plan, 'state': 'scanning', 'started_at': now(),
623
+ 'next_cursor': scan_id + ':0000000000', 'pages': 0, 'entries_seen': 0,
624
+ 'files_seen': 0, 'directories_seen': 0, 'errors': [], 'skipped_count': 0,
625
+ 'stack': [{'path': '', 'entries': None, 'index': 0}],
626
+ 'watermarks': {'': self._watermark(source_root)},
627
+ 'enumeration_complete': False, 'metadata_only': True,
628
+ 'missing_assessment': 'unknown_until_complete_and_never_deletion_proof',
629
+ 'meaning': 'Metadata observations over a time window, not atomic content identity, user intent, or source deletion proof.'}
630
+ self.store.put('source_scans', scan_key, record)
631
+ self.store.event('source_scan_started', {'source_id': source_id, 'scan_id': scan_id, 'plan': plan})
632
+ return {'scan': self._scan_summary(record), 'reused': False}
633
+ record = self._read('source_scans', scan_key, 'taskcarry.source_scan.v1')
634
+ if record is None:
635
+ raise GovernanceError('SCAN_NOT_FOUND', 'Start this source scan before reading or continuing it.')
636
+ if action == 'status':
637
+ return {'scan': self._scan_summary(record)}
638
+ if action != 'page':
639
+ raise GovernanceError('INVALID_ACTION', 'Unknown source_scan action.')
640
+ _text(cursor, 'Scan continuation cursor', 128)
641
+ if not cursor.startswith(scan_id + ':'):
642
+ raise GovernanceError('SCAN_CURSOR_INVALID', 'This cursor belongs to another scan.')
643
+ page_key = key + ':' + cursor
644
+ with self.store.transaction():
645
+ prior = self._read('source_scan_pages', page_key, 'taskcarry.source_scan_page.v1')
646
+ if prior:
647
+ return {'page': prior, 'reused': True}
648
+ record = self._read('source_scans', scan_key, 'taskcarry.source_scan.v1')
649
+ if cursor != record['next_cursor'] or record['state'] != 'scanning':
650
+ raise GovernanceError('SCAN_CURSOR_INVALID', 'Continue the exact retained cursor or start a new scan.')
651
+ page = self._scan_page(record, cursor)
652
+ self.store.put('source_scan_pages', page_key, page)
653
+ self.store.put('source_scans', scan_key, record)
654
+ self.store.event('source_scan_page_recorded', {'source_id': source_id, 'scan_id': scan_id,
655
+ 'cursor': cursor, 'revision': page['revision'], 'state': record['state']})
656
+ return {'page': page, 'reused': False}
657
+
658
+ def _scan_page(self, record, cursor):
659
+ source = record['source']
660
+ root = Path(source['root'])
661
+ budget = record['plan']['budgets']
662
+ items, skipped, errors = [], [], []
663
+ processed, listed = 0, 0
664
+
665
+ def fail(path, reason):
666
+ error = {'path': path, 'reason': reason}
667
+ errors.append(error)
668
+ record['errors'].append(error)
669
+
670
+ def checked_path(relative):
671
+ current = root
672
+ if any(_linked(item) for item in (root, *root.parents)):
673
+ raise GovernanceError('SOURCE_CHANGED', 'The source root or its ancestor became a link.')
674
+ for part in PurePosixPath(relative).parts:
675
+ current = current / part
676
+ if _linked(current):
677
+ raise GovernanceError('SOURCE_CHANGED', 'A source ancestor became a link.')
678
+ return current
679
+
680
+ def stable_watermarks():
681
+ for relative, watermark in record['watermarks'].items():
682
+ if self._watermark(checked_path(relative)) != watermark:
683
+ raise GovernanceError('SOURCE_CHANGED', 'A directory changed during scan paging.', {'path': relative})
684
+
685
+ try:
686
+ stable_watermarks()
687
+ while record['stack'] and processed < budget['max_entries']:
688
+ if record['entries_seen'] >= budget['max_total_entries']:
689
+ fail('', 'total_entry_budget')
690
+ record['stack'] = []
691
+ break
692
+ node = record['stack'][-1]
693
+ current = checked_path(node['path'])
694
+ if node['entries'] is None:
695
+ if record['directories_seen'] >= budget['max_directories']:
696
+ fail(node['path'], 'directory_budget')
697
+ record['stack'].pop()
698
+ continue
699
+ record['directories_seen'] += 1
700
+ before = self._watermark(current)
701
+ names = []
702
+ try:
703
+ with os.scandir(current) as iterator:
704
+ for entry in iterator:
705
+ listed += 1
706
+ if len(names) >= budget['max_directory_entries']:
707
+ fail(node['path'], 'directory_entry_budget')
708
+ names = None
709
+ break
710
+ names.append(entry.name)
711
+ except OSError as exc:
712
+ fail(node['path'], type(exc).__name__)
713
+ names = None
714
+ after = self._watermark(current)
715
+ if before != after:
716
+ raise GovernanceError('SOURCE_CHANGED', 'A directory changed while its names were frozen.')
717
+ record['watermarks'][node['path']] = after
718
+ if names is None:
719
+ record['stack'].pop()
720
+ continue
721
+ node['entries'] = sorted(names)
722
+ if node['index'] >= len(node['entries']):
723
+ record['stack'].pop()
724
+ continue
725
+ name = node['entries'][node['index']]
726
+ node['index'] += 1
727
+ relative = (PurePosixPath(node['path']) / name).as_posix()
728
+ processed += 1
729
+ record['entries_seen'] += 1
730
+ folded = relative.casefold()
731
+ excluded = any(folded == item.casefold() or folded.startswith(item.casefold() + '/') for item in source['exclusions'])
732
+ # Metadata directory names are excluded at every depth.
733
+ if excluded or name.casefold() in ('.git', '.taskcarry'):
734
+ skipped.append({'path': relative, 'reason': 'policy_excluded'})
735
+ continue
736
+ try:
737
+ path = current / name
738
+ info = path.stat(follow_symlinks=False)
739
+ if stat.S_ISLNK(info.st_mode) or getattr(info, 'st_file_attributes', 0) & 0x400:
740
+ skipped.append({'path': relative, 'reason': 'link'})
741
+ elif stat.S_ISDIR(info.st_mode):
742
+ if len(record['stack']) >= 128:
743
+ fail(relative, 'directory_depth_budget')
744
+ else:
745
+ record['stack'].append({'path': relative, 'entries': None, 'index': 0})
746
+ items.append({'path': relative, 'kind': 'directory'})
747
+ elif stat.S_ISREG(info.st_mode):
748
+ items.append({'path': relative, 'kind': 'file', 'bytes': info.st_size, 'mtime_ns': info.st_mtime_ns})
749
+ record['files_seen'] += 1
750
+ else:
751
+ skipped.append({'path': relative, 'reason': 'nonregular'})
752
+ except OSError as exc:
753
+ fail(relative, type(exc).__name__)
754
+ stable_watermarks()
755
+ except (GovernanceError, OSError) as exc:
756
+ fail('', exc.code if isinstance(exc, GovernanceError) else type(exc).__name__)
757
+ record['state'] = 'invalidated'
758
+ record['stack'] = []
759
+ record['pages'] += 1
760
+ record['skipped_count'] += len(skipped)
761
+ if not record['stack']:
762
+ if record['state'] != 'invalidated':
763
+ record['state'] = 'incomplete' if record['errors'] else 'complete'
764
+ record['enumeration_complete'] = record['state'] == 'complete'
765
+ record['next_cursor'] = None
766
+ record['finished_at'] = now()
767
+ record['missing_assessment'] = ('not_observed_is_not_deletion_proof' if record['enumeration_complete'] else 'unknown_due_to_incomplete_scan')
768
+ else:
769
+ record['next_cursor'] = record['scan_id'] + ':' + str(record['pages']).zfill(10)
770
+ body = {'source_id': record['source_id'], 'scan_id': record['scan_id'], 'cursor': cursor,
771
+ 'items': items, 'skipped': skipped, 'errors': errors, 'entries_processed': processed,
772
+ 'directory_entries_listed': listed, 'next_cursor': record['next_cursor'], 'state': record['state'],
773
+ 'enumeration_complete': record['enumeration_complete'], 'metadata_only': True,
774
+ 'missing_assessment': record['missing_assessment']}
775
+ return {'schema': 'taskcarry.source_scan_page.v1', **body, 'revision': _hash(body), 'observed_at': now()}