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,41 @@
|
|
|
1
|
+
# Work as an assigned project member
|
|
2
|
+
|
|
3
|
+
Use this route when native `worker_brief`, `source_share`, `worker_handback` and role-bound tools are present. Read native `identify` and the current role/task/source pages first. Keep the original task and conversation. Do not initialize a second control or bypass a denied worker operation with the unrestricted CLI. Ordinary assignment changes take effect on each call without editing client configuration.
|
|
4
|
+
|
|
5
|
+
## Read and review
|
|
6
|
+
|
|
7
|
+
An ordinary message continuing the project in the existing working chat triggers the update check. On that work turn, read the current assignment and the workbench or relevant shared-source revisions using the connected project's tools. If a relevant revision changed, open the new original before acting and mention the change when it affects the user's work. If the last-read revision is still current, continue directly. The HTTPS team entry exposes `taskcarry_assignment.current_workbench` and the live `membership` term; the stdio entry exposes `worker_brief` and exact shared sources. A source pinned in an older assignment keeps its historical version. A personal chat diary provides local continuity; an authorized project share makes the selected work available to colleagues. Idle chats need no polling or separate wake-up.
|
|
8
|
+
|
|
9
|
+
Default to the project's exact shared sources: `reference_id`, `revision`, `content_sha256`. Read text pages to the needed coverage; acquire images into your assigned directory and actually view them. Project visibility does not grant unrestricted filesystem access to every member's drafts. Explicit user-authorized local review can be valid, but label its origin; it is not proof that a remote collaborator can obtain the file. A checkpoint alone does not publish its files.
|
|
10
|
+
|
|
11
|
+
When work is ready for the requested user/colleague review, share the selected material within existing project-sharing authorization in the same work turn. Do not wait for governor approval, a scheduled round or user relay merely to expose a requested review draft. Select files deliberately; never publish an entire workspace or checkpoint by default. If scope was not granted or publication failed, report that actual condition.
|
|
12
|
+
|
|
13
|
+
Use `source_share` for one file, or `source_share_set` when available for a selected multi-file review set. Each uses plan, review, execute. Inspect all plan pages for exact paths, revisions and hashes. A set applies atomically; a changed member file or revision rejects the whole unpublished set. A failed receipt can retry the same plan after checking actual effects. When the set tool is absent, individual shares remain supported; do not claim the installed client has a tool it does not list.
|
|
14
|
+
|
|
15
|
+
Keep the same `reference_id` and advance `revision` for revisions of the same logical document/image. Distinct alternatives that coexist can have distinct IDs. Read current revision rather than inventing a new ID to evade a conflict. Historical exact bytes and earlier decisions remain available subject to current access policy.
|
|
16
|
+
|
|
17
|
+
## Hand back before or after final drafting
|
|
18
|
+
|
|
19
|
+
When the share or draft tool offers `display_title`, name the artifact in the team's working language, for example “Entrance signage layout” or “Reviewer comments on the visitor guide”. Use a title suitable for the project's notification group. Each item in a review set can have its own title. Keep the stable reference for later revisions.
|
|
20
|
+
|
|
21
|
+
`worker_handback` can submit a review request; it does not require final copy. Use `state=submitted` when governor action is requested, with summary and next step stating what needs review or decision. A `draft` record is saved work and is not the submitted pending queue. Preserve a stable handback identity and revise it for subsequent rounds. Reference exact source versions. Do not overwrite a previous governor disposition to make the latest draft appear received.
|
|
22
|
+
|
|
23
|
+
For code, keep the exact base/commit/changed paths; the existing Git submit and receiving engine still checks actual objects. For documents and images, Git is not a prerequisite. Save progress or selected checkpoints through `worker_report`; a checkpoint is neither a delivery nor business acceptance.
|
|
24
|
+
|
|
25
|
+
After governor review, read the exact disposition and its sources. Report acquired/read evidence only for this actual conversation; never attest for another AI. Do not equate published, transferred, read, received and business accepted. Users drive the work in their original chats. Scheduling is optional and is not autonomous control of other AI windows.
|
|
26
|
+
|
|
27
|
+
## Team discussions and project history
|
|
28
|
+
|
|
29
|
+
For a connected team, start with the latest project brief from `project_overview`. Use `project_history` to follow a specific decision or previous version. In an active work chat, find team discussions by participant and topic with `discussion`. Read the memo first. Use the returned source and turn pointers when a question calls for the original wording.
|
|
30
|
+
|
|
31
|
+
Share a substantive discussion with `discussion_update` on your own task and workspace. Keep the topic ID for follow-up replies, cite the revision, and distinguish open proposals from registered decisions. A reply can request attention through the project's chosen group notification settings. In a conversation the owner has enabled for visible-turn capture, `include_current_turn` links the memo to the final turn when the source completes it.
|
|
32
|
+
|
|
33
|
+
The owner controls **Save transcript** separately for each supported local manager or worker chat under **Tasks & people → Members**. Once enabled, the adapter shares complete user questions and final replies. Each chat retains its last 8 shared exchanges. Turning it off stops new sharing and keeps the existing exchanges available. Check your role brief or call `taskcarry_turn_read` for your sharing settings. Use `owner` to find a colleague’s shared chats, `conversation_id` to list the turn pointers, and the turn ID and revision to read the exact exchange. Preserve durable conclusions in a discussion note or project decision.
|
|
34
|
+
|
|
35
|
+
## Offline Git member
|
|
36
|
+
|
|
37
|
+
An offline endpoint is a last-known view plus an outbox, not another project task/decision ledger. Join a governor-approved exact project/member/view from a pinned Git source, using an independently confirmed packet SHA-256 and explicit local workspace mappings. Use `endpoint` join/refresh plan then execute in a separate existing directory. `--offline mcp` exposes cached reads and selected outgoing work. The governor checks current authority, task basis and revisions when importing the exact reply commit.
|
|
38
|
+
|
|
39
|
+
Fetch/push only the configured authorized ref and selected packet, using the existing Git/transfer procedures. Do not sync active SQLite, entire `.git`, credentials or an arbitrary folder. Selected local HEAD/index/worktree preservation is immutable file-layer content; it is not another task ledger or proof of a whole repository recovery. Cached previously granted bytes cannot be remotely erased; revocation prevents future central access/import.
|
|
40
|
+
|
|
41
|
+
中文:待评审就共享选定成果;回交可以请求评审,同稿递增版本、不同备选分别留存。保存、共享、提交评审、治理收录和业务验收分别记录。新工具未安装时沿用现有入口,不以目录存在冒充通道接通。
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
"""Atomic publication of an explicitly selected review set, with paged plans."""
|
|
2
|
+
from .core import _id, read_file_bytes
|
|
3
|
+
from .exchange_packets import require, parse, sha
|
|
4
|
+
from .worker_channel import packed, fingerprint, WorkerChannel
|
|
5
|
+
from .store import GovernanceError
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class SourceReviewSet:
|
|
9
|
+
def __init__(self, channel):
|
|
10
|
+
self.channel, self.store = channel, channel.store
|
|
11
|
+
|
|
12
|
+
def manifest(self, payload):
|
|
13
|
+
ref = payload['manifest']
|
|
14
|
+
data = read_file_bytes(self.store.directory / 'objects' / ref['sha256'])
|
|
15
|
+
require(sha(data) == ref['sha256'] and len(data) == ref['size'], 'Review set manifest changed.')
|
|
16
|
+
return parse(data)
|
|
17
|
+
|
|
18
|
+
def invoke(self, mode, plan_id=None, files=None, limit=5, cursor=None):
|
|
19
|
+
if mode == 'execute':
|
|
20
|
+
return self.channel._execute('source_share_set', plan_id)
|
|
21
|
+
if mode == 'plan':
|
|
22
|
+
require(isinstance(files, list) and 1 <= len(files) <= 64, 'Select between 1 and 64 exact files.')
|
|
23
|
+
require(len({x['reference_id'] for x in files}) == len(files), 'One revision per source in a review set.')
|
|
24
|
+
children = []
|
|
25
|
+
for selection in files:
|
|
26
|
+
# Same ownership, role, revision, bytes and path rules as the
|
|
27
|
+
# single-source operation. No implicit directory expansion.
|
|
28
|
+
child = self.channel.source_share(mode='plan', **selection)
|
|
29
|
+
children.append(child['plan_id'])
|
|
30
|
+
ref = self.channel.core._snapshot(packed(children))
|
|
31
|
+
result = self.channel._plan('source_share_set', {'manifest': ref, 'file_count': len(children)}, {})
|
|
32
|
+
return {**result, **self.page(result['plan_id'], limit, cursor)}
|
|
33
|
+
require(mode == 'get', 'Use plan, get or execute.')
|
|
34
|
+
return self.page(plan_id, limit, cursor)
|
|
35
|
+
|
|
36
|
+
def page(self, plan_id, limit, cursor):
|
|
37
|
+
plan = self.store.get('worker_plans', _id(plan_id, 'Plan'))
|
|
38
|
+
require(plan and plan['actor'] == self.channel.actor and plan['action'] == 'source_share_set'
|
|
39
|
+
and plan['project_id'] == self.channel.project_id, 'Use your own review set plan.', 'WORKER_PLAN_DENIED')
|
|
40
|
+
children = self.manifest(plan['payload'])
|
|
41
|
+
stamp = fingerprint(children)
|
|
42
|
+
offset = WorkerChannel._cursor(cursor, plan_id, stamp) if cursor else 0
|
|
43
|
+
require(type(offset) is int and 0 <= offset <= len(children), 'Invalid review set cursor.')
|
|
44
|
+
require(type(limit) is int and 1 <= limit <= 20, 'Use a bounded review page.')
|
|
45
|
+
rows = []
|
|
46
|
+
for key in children[offset:offset + limit]:
|
|
47
|
+
child = self.store.get('worker_plans', key)
|
|
48
|
+
require(child and child['actor'] == self.channel.actor and child['action'] == 'source_share',
|
|
49
|
+
'Review set member plan is missing.')
|
|
50
|
+
value = child['payload']['record']
|
|
51
|
+
rows.append({k: value[k] for k in ('reference_id', 'revision', 'content_sha256', 'size',
|
|
52
|
+
'media_type', 'task_id', 'visibility')} | {'path': child['payload']['path'],
|
|
53
|
+
'workspace_id': child['payload']['workspace_id']})
|
|
54
|
+
if 'display_title' in value:
|
|
55
|
+
rows[-1]['display_title'] = value['display_title']
|
|
56
|
+
while True:
|
|
57
|
+
end = offset + len(rows)
|
|
58
|
+
result = {'plan_id': plan_id, 'state': plan['state'], 'manifest': plan['payload']['manifest'],
|
|
59
|
+
'files': rows, 'total': len(children), 'returned': len(rows), 'has_more': end < len(children),
|
|
60
|
+
'next_cursor': WorkerChannel._encode(plan_id, stamp, end) if end < len(children) else None,
|
|
61
|
+
'effects_executed': False}
|
|
62
|
+
try:
|
|
63
|
+
require(len(packed(result)) <= 6200, 'Narrow the review page.', 'WORKER_RESPONSE_TOO_LARGE')
|
|
64
|
+
self.channel._budget(result)
|
|
65
|
+
return result
|
|
66
|
+
except GovernanceError as exc:
|
|
67
|
+
if exc.code != 'WORKER_RESPONSE_TOO_LARGE' or len(rows) <= 1:
|
|
68
|
+
raise
|
|
69
|
+
rows.pop()
|
|
70
|
+
|
|
71
|
+
def apply(self, payload, guards):
|
|
72
|
+
children = self.manifest(payload)
|
|
73
|
+
# The caller holds one database transaction. If any member has changed,
|
|
74
|
+
# all source records/events roll back; old published versions stay valid.
|
|
75
|
+
shared = []
|
|
76
|
+
for key in children:
|
|
77
|
+
self.channel._execute('source_share', key, review_set_shares=shared)
|
|
78
|
+
self.channel.record_project_shares(shared)
|
|
79
|
+
return {'file_count': len(children), 'manifest': payload['manifest'], 'published': True,
|
|
80
|
+
'effects_executed': True, 'acquired': False, 'read': False, 'business_accepted': False}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""Shared read-only recognition of supported persistent governance formats.
|
|
2
|
+
|
|
3
|
+
The program version is not the database schema version. Original schema-1
|
|
4
|
+
databases have SQLite's default application_id=0; recognizing them must not
|
|
5
|
+
stamp, migrate or rewrite their evidence. The marker alone proves no origin.
|
|
6
|
+
Callers own safe connection handling and any full integrity verification.
|
|
7
|
+
"""
|
|
8
|
+
import json
|
|
9
|
+
|
|
10
|
+
APPLICATION_ID = 1413693785
|
|
11
|
+
STATE_SCHEMA = 1
|
|
12
|
+
INDEX_SCHEMA = 1
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
def inspect_state(db):
|
|
16
|
+
"""Inspect structure/config/index versions without writes or new journals."""
|
|
17
|
+
application_id = db.execute('PRAGMA application_id').fetchone()[0]
|
|
18
|
+
if application_id not in (0, APPLICATION_ID):
|
|
19
|
+
return {'state': 'unknown', 'reason': 'foreign_application_id'}
|
|
20
|
+
tables = {row[0] for row in db.execute("SELECT name FROM sqlite_master WHERE type='table'")}
|
|
21
|
+
layouts = {
|
|
22
|
+
'records': ({'collection', 'key', 'value'}, ['collection', 'key']),
|
|
23
|
+
'events': ({'sequence', 'created_at', 'kind', 'payload'}, ['sequence']),
|
|
24
|
+
}
|
|
25
|
+
for table, (required, primary_key) in layouts.items():
|
|
26
|
+
if table not in tables:
|
|
27
|
+
return {'state': 'unknown', 'reason': 'not_taskcarry_tables'}
|
|
28
|
+
columns = list(db.execute('PRAGMA table_info(' + table + ')'))
|
|
29
|
+
keys = [row[1] for row in sorted(columns, key=lambda row: row[5]) if row[5]]
|
|
30
|
+
if not required.issubset({row[1] for row in columns}) or keys != primary_key:
|
|
31
|
+
return {'state': 'unknown', 'reason': 'not_taskcarry_table_layout'}
|
|
32
|
+
row = db.execute("SELECT value FROM records WHERE collection='config' AND key='project'").fetchone()
|
|
33
|
+
if row is None:
|
|
34
|
+
return ({'state': 'incomplete', 'reason': 'initialization_not_published'}
|
|
35
|
+
if application_id == APPLICATION_ID else
|
|
36
|
+
{'state': 'unknown', 'reason': 'missing_project_identity'})
|
|
37
|
+
config = json.loads(row[0])
|
|
38
|
+
if not isinstance(config, dict) or type(config.get('schema_version')) is not int:
|
|
39
|
+
return {'state': 'corrupt', 'reason': 'invalid_project_config'}
|
|
40
|
+
if config['schema_version'] != STATE_SCHEMA:
|
|
41
|
+
return {'state': 'unsupported', 'reason': 'state_schema_version', 'config': config}
|
|
42
|
+
for table in ('store_schema', 'context_schema'):
|
|
43
|
+
if table in tables:
|
|
44
|
+
versions = [row[0] for row in db.execute('SELECT version FROM ' + table)]
|
|
45
|
+
if (table == 'context_schema' and not versions) or any(version != INDEX_SCHEMA for version in versions):
|
|
46
|
+
return {'state': 'unsupported', 'reason': 'index_schema_version', 'config': config}
|
|
47
|
+
return {'state': 'compatible', 'config': config}
|
taskcarry/store.py
ADDED
|
@@ -0,0 +1,472 @@
|
|
|
1
|
+
"""Durable local records and a nonblocking operating-system mutation guard."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
from contextlib import contextmanager, closing
|
|
5
|
+
from datetime import datetime, timezone
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import sqlite3
|
|
10
|
+
import threading
|
|
11
|
+
import uuid
|
|
12
|
+
|
|
13
|
+
from .state_format import APPLICATION_ID
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
TERMINAL_STATES = frozenset(('accepted', 'committed', 'complete', 'completed', 'superseded',
|
|
17
|
+
'cancelled', 'dismissed', 'finalized', 'adopted'))
|
|
18
|
+
CURRENT_PROJECTION_VERSION = 1
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
class GovernanceError(Exception):
|
|
22
|
+
def __init__(self, code, message, details=None):
|
|
23
|
+
super().__init__(message)
|
|
24
|
+
self.code, self.message, self.details = code, message, details
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def now():
|
|
28
|
+
return datetime.now(timezone.utc).isoformat()
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _linked(path):
|
|
32
|
+
try:
|
|
33
|
+
return path.is_symlink() or bool(getattr(path.lstat(), 'st_file_attributes', 0) & 0x400)
|
|
34
|
+
except FileNotFoundError:
|
|
35
|
+
return False
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Store:
|
|
39
|
+
def __init__(self, project, create=False):
|
|
40
|
+
raw_root = Path(project).expanduser().absolute()
|
|
41
|
+
if any(_linked(p) for p in (raw_root, *raw_root.parents)):
|
|
42
|
+
raise GovernanceError('UNSAFE_METADATA', 'The project location cannot traverse symbolic links or junctions.')
|
|
43
|
+
self.root = raw_root.resolve()
|
|
44
|
+
self.directory = self.root / '.taskcarry'
|
|
45
|
+
self.path = self.directory / 'state.sqlite3'
|
|
46
|
+
self._mutex = threading.RLock()
|
|
47
|
+
self._depth = 0
|
|
48
|
+
self._lock_handle = None
|
|
49
|
+
self._local = threading.local()
|
|
50
|
+
if _linked(self.directory):
|
|
51
|
+
raise GovernanceError('UNSAFE_METADATA', 'Governance metadata cannot be a symbolic link.')
|
|
52
|
+
if create:
|
|
53
|
+
from .identification import identify, require_initializable
|
|
54
|
+
require_initializable(identify(self.root))
|
|
55
|
+
self.root.mkdir(parents=True, exist_ok=True)
|
|
56
|
+
self.directory.mkdir(exist_ok=True)
|
|
57
|
+
with self.guard():
|
|
58
|
+
require_initializable(identify(self.root, initializing=True))
|
|
59
|
+
fresh = not self.path.exists()
|
|
60
|
+
if _linked(self.path):
|
|
61
|
+
raise GovernanceError('UNSAFE_METADATA', 'The state database cannot be a symbolic link.')
|
|
62
|
+
# Existing compatible databases must not be journal-migrated or
|
|
63
|
+
# repaired by initialization. Upgrades are a separate action.
|
|
64
|
+
if not fresh:
|
|
65
|
+
return
|
|
66
|
+
with closing(sqlite3.connect(self.path, timeout=0)) as db:
|
|
67
|
+
db.execute('PRAGMA application_id=' + str(APPLICATION_ID))
|
|
68
|
+
db.execute('PRAGMA journal_mode=WAL')
|
|
69
|
+
db.execute('PRAGMA synchronous=FULL')
|
|
70
|
+
db.executescript('''
|
|
71
|
+
CREATE TABLE IF NOT EXISTS records (
|
|
72
|
+
collection TEXT NOT NULL, key TEXT NOT NULL,
|
|
73
|
+
value TEXT NOT NULL, PRIMARY KEY(collection,key));
|
|
74
|
+
CREATE TABLE IF NOT EXISTS events (
|
|
75
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
76
|
+
created_at TEXT NOT NULL, kind TEXT NOT NULL, payload TEXT NOT NULL);
|
|
77
|
+
''')
|
|
78
|
+
if fresh:
|
|
79
|
+
with db:
|
|
80
|
+
self._create_projection(db)
|
|
81
|
+
self._create_context_index(db)
|
|
82
|
+
elif not self.path.is_file():
|
|
83
|
+
raise GovernanceError('NOT_INITIALIZED', 'Initialize this project before using governance.')
|
|
84
|
+
if _linked(self.path):
|
|
85
|
+
raise GovernanceError('UNSAFE_METADATA', 'The state database cannot be a symbolic link.')
|
|
86
|
+
|
|
87
|
+
@contextmanager
|
|
88
|
+
def _connect(self, readonly=False):
|
|
89
|
+
if _linked(self.directory) or _linked(self.path):
|
|
90
|
+
raise GovernanceError('UNSAFE_METADATA', 'Metadata changed to a symbolic link or junction.')
|
|
91
|
+
current = getattr(self._local, 'connection', None)
|
|
92
|
+
if current is not None:
|
|
93
|
+
# A getter inside a mutation sees that mutation's uncommitted state.
|
|
94
|
+
# Only the transaction owner may commit, roll back or close it.
|
|
95
|
+
yield current
|
|
96
|
+
return
|
|
97
|
+
mode = 'ro' if readonly else 'rw'
|
|
98
|
+
connection = None
|
|
99
|
+
try:
|
|
100
|
+
connection = sqlite3.connect(self.path.as_uri() + '?mode=' + mode, uri=True, timeout=0)
|
|
101
|
+
if readonly:
|
|
102
|
+
connection.execute('PRAGMA query_only=ON')
|
|
103
|
+
connection.execute('BEGIN')
|
|
104
|
+
else:
|
|
105
|
+
connection.execute('PRAGMA synchronous=FULL')
|
|
106
|
+
with connection:
|
|
107
|
+
yield connection
|
|
108
|
+
except sqlite3.OperationalError as exc:
|
|
109
|
+
# WAL/schema setup can briefly contend before a guarded write even
|
|
110
|
+
# begins. Preserve nonblocking semantics and the same retry signal
|
|
111
|
+
# as the OS mutation guard; never classify unrelated I/O as BUSY.
|
|
112
|
+
if getattr(exc, 'sqlite_errorcode', 0) & 0xff in {sqlite3.SQLITE_BUSY, sqlite3.SQLITE_LOCKED}:
|
|
113
|
+
raise GovernanceError('BUSY', 'The project database is busy; inspect the saved plan and retry after the other operation completes.') from exc
|
|
114
|
+
raise
|
|
115
|
+
finally:
|
|
116
|
+
if connection is not None:
|
|
117
|
+
connection.close()
|
|
118
|
+
|
|
119
|
+
@contextmanager
|
|
120
|
+
def recovery_transition(self):
|
|
121
|
+
"""Internal scoped write bypass for a verified restore/activation only."""
|
|
122
|
+
previous = getattr(self._local, 'recovery_transition', False)
|
|
123
|
+
self._local.recovery_transition = True
|
|
124
|
+
try:
|
|
125
|
+
yield self
|
|
126
|
+
finally:
|
|
127
|
+
self._local.recovery_transition = previous
|
|
128
|
+
|
|
129
|
+
def assert_writable(self):
|
|
130
|
+
if getattr(self._local, 'recovery_transition', False) or not self.path.exists():
|
|
131
|
+
return
|
|
132
|
+
config = self.get('config', 'project') or {}
|
|
133
|
+
if config.get('recovery_writer_state') == 'standby':
|
|
134
|
+
raise GovernanceError('RECOVERY_STANDBY',
|
|
135
|
+
'This restored replica is read-only until an explicit verified writer handoff.',
|
|
136
|
+
{'restore_id': config.get('recovery_restore_id')})
|
|
137
|
+
|
|
138
|
+
@contextmanager
|
|
139
|
+
def transaction(self):
|
|
140
|
+
"""Atomically publish related local records and events.
|
|
141
|
+
|
|
142
|
+
This deliberately differs from guard(): the latter protects external Git
|
|
143
|
+
work whose effect journal must survive an exception. Nested transactions
|
|
144
|
+
are savepoints, so a caught inner failure cannot publish partial rows.
|
|
145
|
+
"""
|
|
146
|
+
with self.guard():
|
|
147
|
+
self.assert_writable()
|
|
148
|
+
current = getattr(self._local, 'connection', None)
|
|
149
|
+
if current is not None:
|
|
150
|
+
depth = getattr(self._local, 'savepoint_depth', 0) + 1
|
|
151
|
+
self._local.savepoint_depth = depth
|
|
152
|
+
name = 'taskcarry_' + str(depth)
|
|
153
|
+
current.execute('SAVEPOINT ' + name)
|
|
154
|
+
try:
|
|
155
|
+
yield self
|
|
156
|
+
except BaseException:
|
|
157
|
+
current.execute('ROLLBACK TO SAVEPOINT ' + name)
|
|
158
|
+
current.execute('RELEASE SAVEPOINT ' + name)
|
|
159
|
+
raise
|
|
160
|
+
else:
|
|
161
|
+
current.execute('RELEASE SAVEPOINT ' + name)
|
|
162
|
+
finally:
|
|
163
|
+
self._local.savepoint_depth = depth - 1
|
|
164
|
+
else:
|
|
165
|
+
with self._connect() as db:
|
|
166
|
+
db.execute('BEGIN IMMEDIATE')
|
|
167
|
+
self._local.connection = db
|
|
168
|
+
try:
|
|
169
|
+
yield self
|
|
170
|
+
finally:
|
|
171
|
+
self._local.connection = None
|
|
172
|
+
|
|
173
|
+
@contextmanager
|
|
174
|
+
def guard(self):
|
|
175
|
+
if not self._mutex.acquire(blocking=False):
|
|
176
|
+
raise GovernanceError('BUSY', 'Another operation is changing this project; retry after it completes.')
|
|
177
|
+
acquired = False
|
|
178
|
+
try:
|
|
179
|
+
if self._depth == 0:
|
|
180
|
+
lock_path = self.directory / 'mutation.lock'
|
|
181
|
+
if _linked(self.directory) or _linked(lock_path):
|
|
182
|
+
raise GovernanceError('UNSAFE_METADATA', 'The mutation guard cannot be a symbolic link.')
|
|
183
|
+
self._lock_handle = open(lock_path, 'a+b')
|
|
184
|
+
self._lock_handle.seek(0, os.SEEK_END)
|
|
185
|
+
if self._lock_handle.tell() == 0:
|
|
186
|
+
self._lock_handle.write(b'0')
|
|
187
|
+
self._lock_handle.flush()
|
|
188
|
+
self._lock_handle.seek(0)
|
|
189
|
+
try:
|
|
190
|
+
if os.name == 'nt':
|
|
191
|
+
import msvcrt
|
|
192
|
+
msvcrt.locking(self._lock_handle.fileno(), msvcrt.LK_NBLCK, 1)
|
|
193
|
+
else:
|
|
194
|
+
import fcntl
|
|
195
|
+
fcntl.flock(self._lock_handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
|
196
|
+
except (OSError, BlockingIOError) as exc:
|
|
197
|
+
self._lock_handle.close()
|
|
198
|
+
self._lock_handle = None
|
|
199
|
+
raise GovernanceError('BUSY', 'Another process holds the project mutation guard.') from exc
|
|
200
|
+
self._depth += 1
|
|
201
|
+
acquired = True
|
|
202
|
+
yield self
|
|
203
|
+
finally:
|
|
204
|
+
if acquired:
|
|
205
|
+
self._depth -= 1
|
|
206
|
+
if self._depth == 0 and self._lock_handle is not None:
|
|
207
|
+
try:
|
|
208
|
+
self._lock_handle.seek(0)
|
|
209
|
+
if os.name == 'nt':
|
|
210
|
+
import msvcrt
|
|
211
|
+
msvcrt.locking(self._lock_handle.fileno(), msvcrt.LK_UNLCK, 1)
|
|
212
|
+
else:
|
|
213
|
+
import fcntl
|
|
214
|
+
fcntl.flock(self._lock_handle, fcntl.LOCK_UN)
|
|
215
|
+
finally:
|
|
216
|
+
self._lock_handle.close()
|
|
217
|
+
self._lock_handle = None
|
|
218
|
+
self._mutex.release()
|
|
219
|
+
|
|
220
|
+
def get(self, collection, key, default=None):
|
|
221
|
+
with self._connect(readonly=True) as db:
|
|
222
|
+
row = db.execute('SELECT value FROM records WHERE collection=? AND key=?', (collection, key)).fetchone()
|
|
223
|
+
return json.loads(row[0]) if row else default
|
|
224
|
+
|
|
225
|
+
def put(self, collection, key, value):
|
|
226
|
+
serialized = json.dumps(value, ensure_ascii=False, sort_keys=True, allow_nan=False)
|
|
227
|
+
with self.guard(), self._connect() as db:
|
|
228
|
+
self.assert_writable()
|
|
229
|
+
if not db.in_transaction:
|
|
230
|
+
db.execute('BEGIN IMMEDIATE')
|
|
231
|
+
projected = self._projection_ready(db)
|
|
232
|
+
already_dirty = self._projection_dirty(db) if projected else False
|
|
233
|
+
db.execute('INSERT INTO records(collection,key,value) VALUES(?,?,?) '
|
|
234
|
+
'ON CONFLICT(collection,key) DO UPDATE SET value=excluded.value',
|
|
235
|
+
(collection, key, serialized))
|
|
236
|
+
if projected:
|
|
237
|
+
self._project_record(db, collection, key, value)
|
|
238
|
+
if not already_dirty:
|
|
239
|
+
# Clear only this write's invalidation. An older client or
|
|
240
|
+
# direct database edit must still force an explicit rebuild.
|
|
241
|
+
db.execute("UPDATE store_schema SET dirty=0 WHERE name='current_records'")
|
|
242
|
+
return value
|
|
243
|
+
|
|
244
|
+
@staticmethod
|
|
245
|
+
def _projection_ready(db):
|
|
246
|
+
exists = db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='store_schema'").fetchone()
|
|
247
|
+
if not exists:
|
|
248
|
+
return False
|
|
249
|
+
row = db.execute("SELECT version FROM store_schema WHERE name='current_records'").fetchone()
|
|
250
|
+
if row and row[0] != CURRENT_PROJECTION_VERSION:
|
|
251
|
+
raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'The current-record index requires a compatible toolkit version.')
|
|
252
|
+
return row is not None
|
|
253
|
+
|
|
254
|
+
@staticmethod
|
|
255
|
+
def _projection_dirty(db):
|
|
256
|
+
return bool(db.execute("SELECT dirty FROM store_schema WHERE name='current_records'").fetchone()[0])
|
|
257
|
+
|
|
258
|
+
@staticmethod
|
|
259
|
+
def _create_projection(db):
|
|
260
|
+
# execute(), not executescript(): an upgrade must retain its surrounding
|
|
261
|
+
# transaction, including rollback if backfilling any record fails.
|
|
262
|
+
db.execute('CREATE TABLE IF NOT EXISTS store_schema (name TEXT PRIMARY KEY, version INTEGER NOT NULL, dirty INTEGER NOT NULL DEFAULT 0)')
|
|
263
|
+
db.execute('''CREATE TABLE IF NOT EXISTS current_records (
|
|
264
|
+
collection TEXT NOT NULL, key TEXT NOT NULL, active INTEGER NOT NULL,
|
|
265
|
+
state TEXT NOT NULL, task_id TEXT, workspace TEXT, plan_id TEXT,
|
|
266
|
+
PRIMARY KEY(collection,key))''')
|
|
267
|
+
db.execute('CREATE INDEX IF NOT EXISTS current_records_selection ON current_records(collection,active,key)')
|
|
268
|
+
db.execute("INSERT INTO store_schema(name,version) VALUES('current_records',?)",
|
|
269
|
+
(CURRENT_PROJECTION_VERSION,))
|
|
270
|
+
for operation in ('INSERT', 'UPDATE', 'DELETE'):
|
|
271
|
+
db.execute('CREATE TRIGGER current_records_dirty_' + operation.lower() +
|
|
272
|
+
' AFTER ' + operation + ' ON records BEGIN '
|
|
273
|
+
"UPDATE store_schema SET dirty=1 WHERE name='current_records'; END")
|
|
274
|
+
|
|
275
|
+
@staticmethod
|
|
276
|
+
def _project_record(db, collection, key, value):
|
|
277
|
+
record = value if isinstance(value, dict) else {}
|
|
278
|
+
default = 'queued' if collection == 'stages' else 'pending'
|
|
279
|
+
state = str(record.get('state', record.get('status', default))).lower()
|
|
280
|
+
if collection in ('stages', 'operations', 'runs'):
|
|
281
|
+
active = state not in TERMINAL_STATES
|
|
282
|
+
elif collection == 'issues':
|
|
283
|
+
active = state != 'resolved'
|
|
284
|
+
elif collection == 'tasks':
|
|
285
|
+
active = record.get('state') != 'complete'
|
|
286
|
+
elif collection == 'artifacts':
|
|
287
|
+
active = (record.get('decision') not in ('ignore', 'dismiss', 'no_backup_needed')
|
|
288
|
+
and not record.get('backup_verified'))
|
|
289
|
+
else:
|
|
290
|
+
active = True
|
|
291
|
+
db.execute('''INSERT INTO current_records(collection,key,active,state,task_id,workspace,plan_id)
|
|
292
|
+
VALUES(?,?,?,?,?,?,?) ON CONFLICT(collection,key) DO UPDATE SET
|
|
293
|
+
active=excluded.active,state=excluded.state,task_id=excluded.task_id,
|
|
294
|
+
workspace=excluded.workspace,plan_id=excluded.plan_id''',
|
|
295
|
+
(collection, key, int(active), state, record.get('task_id'),
|
|
296
|
+
record.get('workspace'), record.get('plan_id')))
|
|
297
|
+
|
|
298
|
+
@staticmethod
|
|
299
|
+
def _context_ready(db):
|
|
300
|
+
row = db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name='context_schema'").fetchone()
|
|
301
|
+
if not row:
|
|
302
|
+
return False
|
|
303
|
+
version = db.execute('SELECT version FROM context_schema').fetchone()
|
|
304
|
+
if version is None or version[0] != 1:
|
|
305
|
+
raise GovernanceError('SCHEMA_VERSION_UNSUPPORTED', 'Use a compatible context index reader.')
|
|
306
|
+
return bool(db.execute("SELECT 1 FROM sqlite_master WHERE type='index' AND name='current_records_task'").fetchone())
|
|
307
|
+
|
|
308
|
+
@staticmethod
|
|
309
|
+
def _create_context_index(db):
|
|
310
|
+
db.execute('CREATE INDEX IF NOT EXISTS current_records_task ON current_records(task_id,collection,key)')
|
|
311
|
+
db.execute('CREATE TABLE IF NOT EXISTS context_schema(version INTEGER NOT NULL, generation TEXT NOT NULL)')
|
|
312
|
+
db.execute('DELETE FROM context_schema')
|
|
313
|
+
db.execute('INSERT INTO context_schema VALUES(1,?)', (uuid.uuid4().hex,))
|
|
314
|
+
db.execute('CREATE TABLE IF NOT EXISTS context_revisions(task_id TEXT PRIMARY KEY, revision INTEGER NOT NULL)')
|
|
315
|
+
db.execute('DELETE FROM context_revisions')
|
|
316
|
+
db.execute('CREATE TABLE IF NOT EXISTS context_record_revisions(collection TEXT NOT NULL, key TEXT NOT NULL, revision INTEGER NOT NULL, PRIMARY KEY(collection,key))')
|
|
317
|
+
db.execute('DELETE FROM context_record_revisions')
|
|
318
|
+
db.execute('INSERT INTO context_revisions SELECT DISTINCT task_id,1 FROM current_records WHERE task_id IS NOT NULL')
|
|
319
|
+
# SQL triggers also cover compatible older clients: a reader never
|
|
320
|
+
# depends on an in-memory cache or silently repairs this derived index.
|
|
321
|
+
collections = "('tasks','checkpoints','observations','stages','operations','artifacts','issues','fixes','runs')"
|
|
322
|
+
for operation, sources in (('insert', ('NEW',)), ('update', ('OLD', 'NEW')), ('delete', ('OLD',))):
|
|
323
|
+
db.execute('DROP TRIGGER IF EXISTS context_revision_' + operation)
|
|
324
|
+
statements = []
|
|
325
|
+
for source in sources:
|
|
326
|
+
statements.append('INSERT INTO context_record_revisions(collection,key,revision) SELECT ' + source +
|
|
327
|
+
'.collection,' + source + '.key,1 WHERE ' + source + '.collection IN ' + collections +
|
|
328
|
+
' ON CONFLICT(collection,key) DO UPDATE SET revision=revision+1;')
|
|
329
|
+
statements.append("INSERT INTO context_revisions(task_id,revision) SELECT json_extract(" + source +
|
|
330
|
+
".value,'$.task_id'),1 WHERE " + source + '.collection IN ' + collections +
|
|
331
|
+
" AND json_type(" + source + ".value,'$.task_id')='text' "
|
|
332
|
+
'ON CONFLICT(task_id) DO UPDATE SET revision=revision+1;')
|
|
333
|
+
condition = ' WHEN OLD.value IS NOT NEW.value' if operation == 'update' else ''
|
|
334
|
+
db.execute('CREATE TRIGGER context_revision_' + operation + ' AFTER ' + operation.upper() +
|
|
335
|
+
' ON records' + condition + ' BEGIN ' + ' '.join(statements) + ' END')
|
|
336
|
+
|
|
337
|
+
def upgrade(self):
|
|
338
|
+
"""Explicit, atomic index migration. Existing evidence is never rewritten."""
|
|
339
|
+
with self.transaction(), self._connect() as db:
|
|
340
|
+
ready = self._projection_ready(db)
|
|
341
|
+
context_ready = self._context_ready(db)
|
|
342
|
+
if ready and not self._projection_dirty(db) and context_ready:
|
|
343
|
+
return {'upgraded': False, 'current_projection_version': CURRENT_PROJECTION_VERSION,
|
|
344
|
+
'records_rewritten': 0, 'events_rewritten': 0}
|
|
345
|
+
if ready:
|
|
346
|
+
db.execute('DELETE FROM current_records')
|
|
347
|
+
else:
|
|
348
|
+
self._create_projection(db)
|
|
349
|
+
count = 0
|
|
350
|
+
for collection, key, serialized in db.execute('SELECT collection,key,value FROM records ORDER BY collection,key'):
|
|
351
|
+
self._project_record(db, collection, key, json.loads(serialized))
|
|
352
|
+
count += 1
|
|
353
|
+
db.execute("UPDATE store_schema SET dirty=0 WHERE name='current_records'")
|
|
354
|
+
self._create_context_index(db)
|
|
355
|
+
return {'upgraded': True, 'current_projection_version': CURRENT_PROJECTION_VERSION,
|
|
356
|
+
'indexed_records': count, 'records_rewritten': 0, 'events_rewritten': 0}
|
|
357
|
+
|
|
358
|
+
def storage_status(self):
|
|
359
|
+
with self._connect(readonly=True) as db:
|
|
360
|
+
ready = self._projection_ready(db)
|
|
361
|
+
dirty = self._projection_dirty(db) if ready else False
|
|
362
|
+
context_ready = ready and not dirty and self._context_ready(db)
|
|
363
|
+
return {'mode': 'indexed_current_v1' if ready and not dirty else 'legacy_full_scan',
|
|
364
|
+
'upgrade_required': not ready or dirty, 'index_rebuild_required': dirty,
|
|
365
|
+
'context_ready': context_ready, 'context_upgrade_required': not context_ready}
|
|
366
|
+
|
|
367
|
+
def snapshot_current(self):
|
|
368
|
+
"""Read agenda inputs using the index, plus explicitly linked ancestors.
|
|
369
|
+
|
|
370
|
+
This bounds history loading, not the number of genuinely current items.
|
|
371
|
+
Legacy projects remain readable until the caller explicitly upgrades.
|
|
372
|
+
"""
|
|
373
|
+
names = ('tasks', 'stages', 'operations', 'workspaces', 'artifacts',
|
|
374
|
+
'checkpoints', 'experience', 'plans', 'issues', 'runs', 'observations')
|
|
375
|
+
result = {name: [] for name in names}
|
|
376
|
+
with self._connect(readonly=True) as db:
|
|
377
|
+
ready = self._projection_ready(db)
|
|
378
|
+
dirty = self._projection_dirty(db) if ready else False
|
|
379
|
+
if not ready or dirty:
|
|
380
|
+
placeholders = ','.join('?' for _ in names)
|
|
381
|
+
rows = db.execute('SELECT collection,value FROM records WHERE collection IN (' +
|
|
382
|
+
placeholders + ') ORDER BY collection,key', names).fetchall()
|
|
383
|
+
for collection, serialized in rows:
|
|
384
|
+
result[collection].append(json.loads(serialized))
|
|
385
|
+
result['_storage'] = {'mode': 'legacy_full_scan', 'upgrade_required': True,
|
|
386
|
+
'index_rebuild_required': dirty, 'loaded_records': len(rows)}
|
|
387
|
+
return result
|
|
388
|
+
loaded = 0
|
|
389
|
+
for collection in ('tasks', 'stages', 'operations', 'artifacts', 'issues', 'runs'):
|
|
390
|
+
rows = db.execute('''SELECT r.value FROM current_records AS c
|
|
391
|
+
JOIN records AS r ON r.collection=c.collection AND r.key=c.key
|
|
392
|
+
WHERE c.collection=? AND c.active=1 ORDER BY c.key''', (collection,)).fetchall()
|
|
393
|
+
result[collection] = [json.loads(row[0]) for row in rows]
|
|
394
|
+
loaded += len(rows)
|
|
395
|
+
for collection in ('workspaces', 'experience'):
|
|
396
|
+
rows = db.execute('SELECT value FROM records WHERE collection=? ORDER BY key', (collection,)).fetchall()
|
|
397
|
+
result[collection] = [json.loads(row[0]) for row in rows]
|
|
398
|
+
loaded += len(rows)
|
|
399
|
+
# Unfinished runs depend on the latest receipts and observations
|
|
400
|
+
# for their frozen selection, even after an effect has completed.
|
|
401
|
+
for collection, id_key, reference in (('operations', 'operation_id', 'operation_ids'),
|
|
402
|
+
('stages', 'stage_id', 'stage_ids'),
|
|
403
|
+
('observations', 'observation_id', 'observation_ids')):
|
|
404
|
+
known = {item.get(id_key) for item in result[collection]}
|
|
405
|
+
for identity in sorted({key for run in result['runs'] for key in run.get(reference, [])} - known):
|
|
406
|
+
row = db.execute('SELECT value FROM records WHERE collection=? AND key=?', (collection, identity)).fetchone()
|
|
407
|
+
if row is not None:
|
|
408
|
+
result[collection].append(json.loads(row[0]))
|
|
409
|
+
loaded += 1
|
|
410
|
+
stages = {item.get('stage_id'): item for item in result['stages'] if item.get('stage_id')}
|
|
411
|
+
pending = [ancestor for item in result['stages'] for ancestor in item.get('supersedes', [])]
|
|
412
|
+
pending.extend(item['stage_id'] for item in result['operations'] if item.get('stage_id'))
|
|
413
|
+
visited = set()
|
|
414
|
+
while pending:
|
|
415
|
+
identity = pending.pop()
|
|
416
|
+
if identity in visited:
|
|
417
|
+
continue
|
|
418
|
+
visited.add(identity)
|
|
419
|
+
stage = stages.get(identity)
|
|
420
|
+
if stage is None:
|
|
421
|
+
row = db.execute("SELECT value FROM records WHERE collection='stages' AND key=?", (identity,)).fetchone()
|
|
422
|
+
if row is None:
|
|
423
|
+
continue
|
|
424
|
+
stage = json.loads(row[0])
|
|
425
|
+
stages[identity] = stage
|
|
426
|
+
result['stages'].append(stage)
|
|
427
|
+
loaded += 1
|
|
428
|
+
pending.extend(stage.get('supersedes', []))
|
|
429
|
+
for identity in sorted({item['plan_id'] for item in result['operations'] if item.get('plan_id')}):
|
|
430
|
+
row = db.execute("SELECT value FROM records WHERE collection='plans' AND key=?", (identity,)).fetchone()
|
|
431
|
+
if row is not None:
|
|
432
|
+
result['plans'].append(json.loads(row[0]))
|
|
433
|
+
loaded += 1
|
|
434
|
+
result['stages'].sort(key=lambda item: item.get('stage_id', ''))
|
|
435
|
+
result['_storage'] = {'mode': 'indexed_current_v1', 'upgrade_required': False,
|
|
436
|
+
'index_rebuild_required': False, 'loaded_records': loaded}
|
|
437
|
+
return result
|
|
438
|
+
|
|
439
|
+
def list(self, collection):
|
|
440
|
+
with self._connect(readonly=True) as db:
|
|
441
|
+
rows = db.execute('SELECT value FROM records WHERE collection=? ORDER BY key', (collection,)).fetchall()
|
|
442
|
+
return [json.loads(row[0]) for row in rows]
|
|
443
|
+
|
|
444
|
+
def snapshot(self, collections):
|
|
445
|
+
"""Read related collections at one durable database point, without a writer lock."""
|
|
446
|
+
names = tuple(dict.fromkeys(collections))
|
|
447
|
+
if any(not isinstance(name, str) for name in names):
|
|
448
|
+
raise ValueError('Snapshot collection names must be strings.')
|
|
449
|
+
result = {name: [] for name in names}
|
|
450
|
+
if not names:
|
|
451
|
+
return result
|
|
452
|
+
placeholders = ','.join('?' for _ in names)
|
|
453
|
+
with self._connect(readonly=True) as db:
|
|
454
|
+
rows = db.execute(
|
|
455
|
+
'SELECT collection,value FROM records WHERE collection IN (' + placeholders + ') ORDER BY collection,key',
|
|
456
|
+
names,
|
|
457
|
+
).fetchall()
|
|
458
|
+
for collection, value in rows:
|
|
459
|
+
result[collection].append(json.loads(value))
|
|
460
|
+
return result
|
|
461
|
+
|
|
462
|
+
def event(self, kind, payload):
|
|
463
|
+
with self.guard(), self._connect() as db:
|
|
464
|
+
self.assert_writable()
|
|
465
|
+
cursor = db.execute('INSERT INTO events(created_at,kind,payload) VALUES(?,?,?)',
|
|
466
|
+
(now(), kind, json.dumps(payload, ensure_ascii=False, sort_keys=True, allow_nan=False)))
|
|
467
|
+
return cursor.lastrowid
|
|
468
|
+
|
|
469
|
+
def events(self):
|
|
470
|
+
with self._connect(readonly=True) as db:
|
|
471
|
+
rows = db.execute('SELECT sequence,created_at,kind,payload FROM events ORDER BY sequence').fetchall()
|
|
472
|
+
return [dict(sequence=r[0], created_at=r[1], kind=r[2], payload=json.loads(r[3])) for r in rows]
|