@clipen/clipen-cli 0.0.0-stage → 1.0.1
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.
- package/LICENSE +21 -0
- package/README.md +89 -2
- package/apps/web/dist/assets/index-D5D2HiB1.js +14 -0
- package/apps/web/dist/assets/index-DIMuOXSu.css +1 -0
- package/apps/web/dist/favicon.svg +1 -0
- package/apps/web/dist/index.html +16 -0
- package/bin/clipen.js +157 -0
- package/clipen +18 -0
- package/install +25 -0
- package/package.json +55 -4
- package/pyproject.toml +44 -0
- package/requirements/asr-runtime.txt +13 -0
- package/requirements/dev.txt +2 -0
- package/requirements/runtime.txt +20 -0
- package/src/clipen/__init__.py +3 -0
- package/src/clipen/analysis/__init__.py +89 -0
- package/src/clipen/analysis/artifacts.py +410 -0
- package/src/clipen/analysis/audio.py +394 -0
- package/src/clipen/analysis/evidence.py +102 -0
- package/src/clipen/analysis/evidence_service.py +929 -0
- package/src/clipen/analysis/image_similarity.py +134 -0
- package/src/clipen/analysis/keyframes.py +159 -0
- package/src/clipen/analysis/models.py +228 -0
- package/src/clipen/analysis/qwen_worker.py +594 -0
- package/src/clipen/analysis/resources.py +22 -0
- package/src/clipen/analysis/runtime.py +62 -0
- package/src/clipen/analysis/service.py +594 -0
- package/src/clipen/analysis/setup.py +921 -0
- package/src/clipen/analysis/setup_cli.py +107 -0
- package/src/clipen/analysis/storage.py +1864 -0
- package/src/clipen/analysis/transcription.py +906 -0
- package/src/clipen/analysis/visual.py +237 -0
- package/src/clipen/annotations/__init__.py +13 -0
- package/src/clipen/annotations/models.py +22 -0
- package/src/clipen/annotations/storage.py +428 -0
- package/src/clipen/annotations/suggestions.py +115 -0
- package/src/clipen/asr_release.py +132 -0
- package/src/clipen/bootstrap.py +978 -0
- package/src/clipen/candidates.py +222 -0
- package/src/clipen/cli.py +84 -0
- package/src/clipen/controller/__init__.py +17 -0
- package/src/clipen/controller/app.py +1657 -0
- package/src/clipen/controller/server.py +533 -0
- package/src/clipen/domain/__init__.py +30 -0
- package/src/clipen/domain/errors.py +5 -0
- package/src/clipen/domain/media_time.py +110 -0
- package/src/clipen/domain/timeline.py +582 -0
- package/src/clipen/domain/validation.py +14 -0
- package/src/clipen/editing/EDITORIAL_REGRESSIONS.md +38 -0
- package/src/clipen/editing/PROGRAM_FORMAT.md +102 -0
- package/src/clipen/editing/README.md +115 -0
- package/src/clipen/editing/REFACTOR_DESIGN.md +241 -0
- package/src/clipen/editing/REFACTOR_HANDOFF.md +73 -0
- package/src/clipen/editing/__init__.py +15 -0
- package/src/clipen/editing/agent.py +13 -0
- package/src/clipen/editing/agent_models.py +127 -0
- package/src/clipen/editing/agent_repository.py +978 -0
- package/src/clipen/editing/agent_tools.py +613 -0
- package/src/clipen/editing/alignment.py +150 -0
- package/src/clipen/editing/alignment_setup.py +156 -0
- package/src/clipen/editing/alignment_worker.py +24 -0
- package/src/clipen/editing/change_report.py +128 -0
- package/src/clipen/editing/compiler.py +40 -0
- package/src/clipen/editing/component_looks.py +131 -0
- package/src/clipen/editing/component_review.py +74 -0
- package/src/clipen/editing/coordinator.py +497 -0
- package/src/clipen/editing/editorial_review.py +309 -0
- package/src/clipen/editing/evidence_jobs.py +552 -0
- package/src/clipen/editing/history_changes.py +192 -0
- package/src/clipen/editing/music_choices.py +18 -0
- package/src/clipen/editing/production_catalog.py +629 -0
- package/src/clipen/editing/production_limits.py +85 -0
- package/src/clipen/editing/production_media.py +435 -0
- package/src/clipen/editing/production_preview.py +373 -0
- package/src/clipen/editing/production_progress.py +236 -0
- package/src/clipen/editing/production_requirements.py +117 -0
- package/src/clipen/editing/production_tools.py +1198 -0
- package/src/clipen/editing/program_audio.py +248 -0
- package/src/clipen/editing/program_direction.py +83 -0
- package/src/clipen/editing/program_story.py +91 -0
- package/src/clipen/editing/program_subtitles.py +232 -0
- package/src/clipen/editing/programme_review.py +121 -0
- package/src/clipen/editing/prompt_history.py +84 -0
- package/src/clipen/editing/recut.py +167 -0
- package/src/clipen/editing/refinement_references.py +278 -0
- package/src/clipen/editing/resolve_export.py +847 -0
- package/src/clipen/editing/resolve_titles.py +291 -0
- package/src/clipen/editing/skill_tools.py +951 -0
- package/src/clipen/editing/source_dialogue.py +192 -0
- package/src/clipen/editing/speech_coverage.py +50 -0
- package/src/clipen/editing/speech_quality.py +11 -0
- package/src/clipen/editing/tool_receipts.py +98 -0
- package/src/clipen/editing/versions.py +219 -0
- package/src/clipen/editing/visual_preview.py +189 -0
- package/src/clipen/editing/workbench.py +136 -0
- package/src/clipen/filesystem.py +25 -0
- package/src/clipen/finishing/README.md +103 -0
- package/src/clipen/finishing/__init__.py +1 -0
- package/src/clipen/finishing/audio.py +188 -0
- package/src/clipen/finishing/catalog.py +264 -0
- package/src/clipen/finishing/models.py +14 -0
- package/src/clipen/finishing/renderer.py +45 -0
- package/src/clipen/mcp_editing/__init__.py +5 -0
- package/src/clipen/mcp_editing/__main__.py +42 -0
- package/src/clipen/mcp_editing/server.py +396 -0
- package/src/clipen/media/__init__.py +50 -0
- package/src/clipen/media/discovery.py +253 -0
- package/src/clipen/media/models.py +349 -0
- package/src/clipen/media/preview.py +137 -0
- package/src/clipen/media/probe.py +418 -0
- package/src/clipen/media/service.py +304 -0
- package/src/clipen/media/storage.py +694 -0
- package/src/clipen/music_vocabulary.py +34 -0
- package/src/clipen/power.py +28 -0
- package/src/clipen/projects/__init__.py +26 -0
- package/src/clipen/projects/agent_schema.py +94 -0
- package/src/clipen/projects/annotation_schema.py +40 -0
- package/src/clipen/projects/deletion.py +256 -0
- package/src/clipen/projects/evidence_schema.py +52 -0
- package/src/clipen/projects/finishing_schema.py +36 -0
- package/src/clipen/projects/models.py +189 -0
- package/src/clipen/projects/picker.py +232 -0
- package/src/clipen/projects/preview_schema.py +29 -0
- package/src/clipen/projects/service.py +159 -0
- package/src/clipen/projects/storage.py +1458 -0
- package/src/clipen/projects/timeline_schema.py +32 -0
- package/src/clipen/projects/validation_schema.py +28 -0
- package/src/clipen/provider_registry.py +77 -0
- package/src/clipen/providers/__init__.py +43 -0
- package/src/clipen/providers/account.py +245 -0
- package/src/clipen/providers/claude.py +409 -0
- package/src/clipen/providers/claude_editing.py +118 -0
- package/src/clipen/providers/codex.py +991 -0
- package/src/clipen/providers/codex_editing.py +91 -0
- package/src/clipen/providers/editing_agent.py +567 -0
- package/src/clipen/providers/errors.py +51 -0
- package/src/clipen/providers/recovery.py +269 -0
- package/src/clipen/py.typed +1 -0
- package/src/clipen/rendering/__init__.py +12 -0
- package/src/clipen/rendering/cover.py +139 -0
- package/src/clipen/rendering/custom_components.py +328 -0
- package/src/clipen/rendering/custom_render.py +218 -0
- package/src/clipen/rendering/fonts/anton-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/bebasneue-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/caveat-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/chenyu-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/delagothicone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/hachimarupop-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/iansui-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/manifest.json +145 -0
- package/src/clipen/rendering/fonts/playfairdisplay-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/rocknrollone-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/yomogi-OFL.txt +94 -0
- package/src/clipen/rendering/fonts/yuseimagic-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenkurenaido-OFL.txt +93 -0
- package/src/clipen/rendering/fonts/zenmarugothic-OFL.txt +93 -0
- package/src/clipen/rendering/production_effects.py +96 -0
- package/src/clipen/rendering/program_components.py +254 -0
- package/src/clipen/rendering/program_creator.py +804 -0
- package/src/clipen/rendering/program_identities.py +350 -0
- package/src/clipen/rendering/program_motion.py +186 -0
- package/src/clipen/rendering/program_studio.py +227 -0
- package/src/clipen/rendering/program_styles.py +321 -0
- package/src/clipen/rendering/program_subtitles.py +89 -0
- package/src/clipen/rendering/renderer.py +737 -0
- package/src/clipen/rendering/storage.py +230 -0
- package/src/clipen/rendering/titles.py +467 -0
- package/src/clipen/skills/__init__.py +5 -0
- package/src/clipen/skills/builtin/SKILL.md +72 -0
- package/src/clipen/skills/builtin/assets/sample-daily-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-event-recap.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-food-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-demo.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-review.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-product-unboxing.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-shorts-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-highlight.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/sample-travel-vlog.mp4 +0 -0
- package/src/clipen/skills/builtin/assets/style-cinema.png +0 -0
- package/src/clipen/skills/builtin/assets/style-editorial.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-daily-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-event-recap.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-food-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-demo.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-review.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-product-unboxing.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-shorts-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-highlight.png +0 -0
- package/src/clipen/skills/builtin/assets/style-tpl-travel-vlog.png +0 -0
- package/src/clipen/skills/builtin/assets/style-variety.png +0 -0
- package/src/clipen/skills/builtin/components.json +133 -0
- package/src/clipen/skills/builtin/font_sources.json +20 -0
- package/src/clipen/skills/builtin/font_styles.json +329 -0
- package/src/clipen/skills/builtin/manifest.json +32 -0
- package/src/clipen/skills/builtin/presets.json +8 -0
- package/src/clipen/skills/builtin/references/captions.md +14 -0
- package/src/clipen/skills/builtin/references/channel-design.md +37 -0
- package/src/clipen/skills/builtin/references/editing.md +30 -0
- package/src/clipen/skills/builtin/references/font-chenyu-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/font-iansui-OFL.txt +93 -0
- package/src/clipen/skills/builtin/references/graphics.md +59 -0
- package/src/clipen/skills/builtin/references/review.md +16 -0
- package/src/clipen/skills/builtin/references/sound.md +8 -0
- package/src/clipen/skills/builtin/references/story.md +7 -0
- package/src/clipen/skills/builtin/skills/travel-program/SKILL.md +27 -0
- package/src/clipen/skills/builtin/skills/travel-program/manifest.json +6 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-daily-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-event-recap/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/SKILL.md +33 -0
- package/src/clipen/skills/builtin/template-skills/clipen-food-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/SKILL.md +35 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-demo/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/SKILL.md +36 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-review/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/SKILL.md +39 -0
- package/src/clipen/skills/builtin/template-skills/clipen-product-unboxing/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/SKILL.md +38 -0
- package/src/clipen/skills/builtin/template-skills/clipen-shorts-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/SKILL.md +34 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-highlight/manifest.json +8 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/SKILL.md +37 -0
- package/src/clipen/skills/builtin/template-skills/clipen-travel-vlog/manifest.json +8 -0
- package/src/clipen/skills/builtin/templates.json +284 -0
- package/src/clipen/skills/builtin/visual_styles.json +1074 -0
- package/src/clipen/skills/catalog.py +314 -0
- package/src/clipen/skills/library.py +137 -0
- package/src/clipen/skills/package.py +254 -0
- package/src/clipen/skills/visual_styles.py +55 -0
- package/src/clipen/workspace.py +181 -0
- package/uninstall +25 -0
|
@@ -0,0 +1,1458 @@
|
|
|
1
|
+
"""Crash-resilient SQLite storage rooted entirely in Clipen-managed directories."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import hashlib
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
import re
|
|
9
|
+
import sqlite3
|
|
10
|
+
import uuid
|
|
11
|
+
from contextlib import contextmanager
|
|
12
|
+
from dataclasses import replace
|
|
13
|
+
from datetime import datetime, timezone
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
from typing import Any, Iterator, Mapping
|
|
16
|
+
|
|
17
|
+
from clipen.filesystem import restrict_permissions
|
|
18
|
+
|
|
19
|
+
from .agent_schema import EDIT_AGENT_SCHEMA, PRODUCTION_SESSION_SCHEMA
|
|
20
|
+
from .annotation_schema import ANNOTATION_SCHEMA
|
|
21
|
+
from .deletion import ProjectDeletion
|
|
22
|
+
from .evidence_schema import EVIDENCE_SCHEMA, OBSERVATION_SCHEMA
|
|
23
|
+
from .finishing_schema import FINISHING_RUNS_SCHEMA, FINISHING_SCHEMA
|
|
24
|
+
from .models import (
|
|
25
|
+
DirectoryReference,
|
|
26
|
+
DirectoryRole,
|
|
27
|
+
ProjectError,
|
|
28
|
+
ProjectSnapshot,
|
|
29
|
+
validate_brief,
|
|
30
|
+
validate_name,
|
|
31
|
+
validate_project_id,
|
|
32
|
+
validate_request_id,
|
|
33
|
+
validate_revision,
|
|
34
|
+
)
|
|
35
|
+
from .preview_schema import PREVIEW_SCHEMA
|
|
36
|
+
from .timeline_schema import TIMELINE_SCHEMA
|
|
37
|
+
from .validation_schema import VALIDATION_WORKFLOW_SCHEMA
|
|
38
|
+
|
|
39
|
+
PROJECT_SCHEMA_VERSION = 19
|
|
40
|
+
# Tables of the retired confirmed-plan flow, children before parents. Version 19
|
|
41
|
+
# archives any rows they still hold beside the database and drops them.
|
|
42
|
+
RETIRED_PLANNING_TABLES = ("current_plan", "plan_revisions", "planning_runs", "plan_command_receipts")
|
|
43
|
+
RETIRED_PLANNING_ARCHIVE = "retired-planning.json"
|
|
44
|
+
_PROJECT_DIRECTORY = re.compile(r"prj_[0-9a-f]{32}\Z")
|
|
45
|
+
|
|
46
|
+
_INVENTORY_SCHEMA = """
|
|
47
|
+
CREATE TABLE inventory_runs (
|
|
48
|
+
run_id TEXT PRIMARY KEY,
|
|
49
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
50
|
+
request_id TEXT NOT NULL UNIQUE,
|
|
51
|
+
project_revision INTEGER NOT NULL CHECK (project_revision >= 1),
|
|
52
|
+
input_fingerprint TEXT NOT NULL,
|
|
53
|
+
roots_json TEXT NOT NULL,
|
|
54
|
+
state TEXT NOT NULL CHECK (
|
|
55
|
+
state IN ('queued', 'running', 'cancelling', 'succeeded', 'failed',
|
|
56
|
+
'cancelled', 'interrupted')
|
|
57
|
+
),
|
|
58
|
+
phase TEXT NOT NULL,
|
|
59
|
+
discovered_count INTEGER NOT NULL DEFAULT 0 CHECK (discovered_count >= 0),
|
|
60
|
+
probed_count INTEGER NOT NULL DEFAULT 0 CHECK (probed_count >= 0),
|
|
61
|
+
usable_count INTEGER NOT NULL DEFAULT 0 CHECK (usable_count >= 0),
|
|
62
|
+
issue_count INTEGER NOT NULL DEFAULT 0 CHECK (issue_count >= 0),
|
|
63
|
+
ignored_count INTEGER NOT NULL DEFAULT 0 CHECK (ignored_count >= 0),
|
|
64
|
+
error_code TEXT,
|
|
65
|
+
created_at TEXT NOT NULL,
|
|
66
|
+
started_at TEXT,
|
|
67
|
+
completed_at TEXT
|
|
68
|
+
);
|
|
69
|
+
CREATE TABLE inventory_command_receipts (
|
|
70
|
+
request_id TEXT PRIMARY KEY,
|
|
71
|
+
command_type TEXT NOT NULL,
|
|
72
|
+
request_hash TEXT NOT NULL,
|
|
73
|
+
run_id TEXT NOT NULL REFERENCES inventory_runs(run_id),
|
|
74
|
+
created_at TEXT NOT NULL
|
|
75
|
+
);
|
|
76
|
+
CREATE TABLE assets (
|
|
77
|
+
asset_id TEXT PRIMARY KEY,
|
|
78
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
79
|
+
role TEXT NOT NULL CHECK (role IN ('source', 'reference')),
|
|
80
|
+
relative_path TEXT NOT NULL,
|
|
81
|
+
first_seen_at TEXT NOT NULL,
|
|
82
|
+
UNIQUE(project_id, role, relative_path)
|
|
83
|
+
);
|
|
84
|
+
CREATE TABLE asset_versions (
|
|
85
|
+
version_id TEXT PRIMARY KEY,
|
|
86
|
+
asset_id TEXT NOT NULL REFERENCES assets(asset_id),
|
|
87
|
+
size_bytes INTEGER NOT NULL CHECK (size_bytes >= 0),
|
|
88
|
+
mtime_ns INTEGER NOT NULL CHECK (mtime_ns >= 0),
|
|
89
|
+
fingerprint TEXT NOT NULL,
|
|
90
|
+
probe_status TEXT NOT NULL CHECK (
|
|
91
|
+
probe_status IN ('pending', 'ready', 'unsupported', 'unreadable',
|
|
92
|
+
'timeout', 'changed', 'internal_error')
|
|
93
|
+
),
|
|
94
|
+
probe_json TEXT,
|
|
95
|
+
created_at TEXT NOT NULL
|
|
96
|
+
);
|
|
97
|
+
CREATE TABLE inventory_items (
|
|
98
|
+
run_id TEXT NOT NULL REFERENCES inventory_runs(run_id) ON DELETE CASCADE,
|
|
99
|
+
asset_id TEXT NOT NULL REFERENCES assets(asset_id),
|
|
100
|
+
version_id TEXT REFERENCES asset_versions(version_id),
|
|
101
|
+
display_name TEXT NOT NULL,
|
|
102
|
+
kind TEXT NOT NULL CHECK (kind IN ('video', 'audio', 'image', 'unknown')),
|
|
103
|
+
status TEXT NOT NULL CHECK (status IN ('usable', 'needs_attention', 'ignored')),
|
|
104
|
+
issue_code TEXT,
|
|
105
|
+
PRIMARY KEY(run_id, asset_id)
|
|
106
|
+
);
|
|
107
|
+
CREATE TABLE media_streams (
|
|
108
|
+
version_id TEXT NOT NULL REFERENCES asset_versions(version_id) ON DELETE CASCADE,
|
|
109
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= 0),
|
|
110
|
+
kind TEXT NOT NULL CHECK (kind IN ('video', 'audio')),
|
|
111
|
+
codec TEXT NOT NULL,
|
|
112
|
+
details_json TEXT NOT NULL,
|
|
113
|
+
PRIMARY KEY(version_id, stream_index)
|
|
114
|
+
);
|
|
115
|
+
CREATE TABLE current_inventory (
|
|
116
|
+
slot INTEGER PRIMARY KEY CHECK (slot = 1),
|
|
117
|
+
run_id TEXT NOT NULL REFERENCES inventory_runs(run_id)
|
|
118
|
+
);
|
|
119
|
+
CREATE INDEX inventory_runs_project_created
|
|
120
|
+
ON inventory_runs(project_id, created_at DESC);
|
|
121
|
+
CREATE INDEX inventory_items_run_status
|
|
122
|
+
ON inventory_items(run_id, status, display_name);
|
|
123
|
+
"""
|
|
124
|
+
|
|
125
|
+
_ANALYSIS_SCHEMA = """
|
|
126
|
+
CREATE TABLE preparation_runs (
|
|
127
|
+
run_id TEXT PRIMARY KEY,
|
|
128
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
129
|
+
request_id TEXT NOT NULL UNIQUE,
|
|
130
|
+
project_revision INTEGER NOT NULL CHECK (project_revision >= 1),
|
|
131
|
+
inventory_run_id TEXT NOT NULL REFERENCES inventory_runs(run_id),
|
|
132
|
+
scope_id TEXT NOT NULL,
|
|
133
|
+
operation_id TEXT NOT NULL,
|
|
134
|
+
attempt_id TEXT NOT NULL,
|
|
135
|
+
attempt_number INTEGER NOT NULL DEFAULT 1 CHECK (attempt_number >= 1),
|
|
136
|
+
input_fingerprint TEXT NOT NULL,
|
|
137
|
+
recipe_json TEXT NOT NULL,
|
|
138
|
+
model_json TEXT,
|
|
139
|
+
state TEXT NOT NULL CHECK (
|
|
140
|
+
state IN ('queued', 'running', 'cancelling', 'succeeded', 'failed',
|
|
141
|
+
'cancelled', 'interrupted')
|
|
142
|
+
),
|
|
143
|
+
phase TEXT NOT NULL,
|
|
144
|
+
total_count INTEGER NOT NULL DEFAULT 0 CHECK (total_count >= 0),
|
|
145
|
+
prepared_count INTEGER NOT NULL DEFAULT 0 CHECK (prepared_count >= 0),
|
|
146
|
+
transcribed_count INTEGER NOT NULL DEFAULT 0 CHECK (transcribed_count >= 0),
|
|
147
|
+
no_audio_count INTEGER NOT NULL DEFAULT 0 CHECK (no_audio_count >= 0),
|
|
148
|
+
no_speech_count INTEGER NOT NULL DEFAULT 0 CHECK (no_speech_count >= 0),
|
|
149
|
+
issue_count INTEGER NOT NULL DEFAULT 0 CHECK (issue_count >= 0),
|
|
150
|
+
error_code TEXT,
|
|
151
|
+
created_at TEXT NOT NULL,
|
|
152
|
+
started_at TEXT,
|
|
153
|
+
completed_at TEXT
|
|
154
|
+
);
|
|
155
|
+
CREATE TABLE preparation_command_receipts (
|
|
156
|
+
request_id TEXT PRIMARY KEY,
|
|
157
|
+
command_type TEXT NOT NULL,
|
|
158
|
+
request_hash TEXT NOT NULL,
|
|
159
|
+
run_id TEXT NOT NULL REFERENCES preparation_runs(run_id),
|
|
160
|
+
created_at TEXT NOT NULL
|
|
161
|
+
);
|
|
162
|
+
CREATE TABLE preparation_items (
|
|
163
|
+
run_id TEXT NOT NULL REFERENCES preparation_runs(run_id) ON DELETE CASCADE,
|
|
164
|
+
version_id TEXT NOT NULL REFERENCES asset_versions(version_id),
|
|
165
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= -1),
|
|
166
|
+
status TEXT NOT NULL CHECK (
|
|
167
|
+
status IN ('pending', 'prepared', 'transcribed', 'no_audio',
|
|
168
|
+
'no_speech', 'failed')
|
|
169
|
+
),
|
|
170
|
+
error_code TEXT,
|
|
171
|
+
checkpoint_json TEXT,
|
|
172
|
+
audio_artifact_id TEXT REFERENCES artifacts(artifact_id),
|
|
173
|
+
transcript_revision_id TEXT REFERENCES transcription_revisions(revision_id),
|
|
174
|
+
review_required INTEGER NOT NULL DEFAULT 0 CHECK (review_required IN (0, 1)),
|
|
175
|
+
PRIMARY KEY(run_id, version_id, stream_index)
|
|
176
|
+
);
|
|
177
|
+
CREATE TABLE operation_events (
|
|
178
|
+
sequence INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
179
|
+
event_id TEXT NOT NULL UNIQUE,
|
|
180
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
181
|
+
operation_id TEXT NOT NULL,
|
|
182
|
+
event_type TEXT NOT NULL,
|
|
183
|
+
payload_json TEXT NOT NULL,
|
|
184
|
+
created_at TEXT NOT NULL
|
|
185
|
+
);
|
|
186
|
+
CREATE TABLE artifacts (
|
|
187
|
+
artifact_id TEXT PRIMARY KEY,
|
|
188
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
189
|
+
kind TEXT NOT NULL CHECK (
|
|
190
|
+
kind IN ('analysis_audio', 'transcript', 'coverage_manifest', 'checkpoint')
|
|
191
|
+
),
|
|
192
|
+
relative_path TEXT NOT NULL,
|
|
193
|
+
sha256 TEXT NOT NULL,
|
|
194
|
+
size_bytes INTEGER NOT NULL CHECK (size_bytes >= 0),
|
|
195
|
+
producer_operation_id TEXT NOT NULL,
|
|
196
|
+
producer_attempt_id TEXT NOT NULL,
|
|
197
|
+
recipe_id TEXT NOT NULL,
|
|
198
|
+
source_span_json TEXT,
|
|
199
|
+
lineage_json TEXT NOT NULL,
|
|
200
|
+
created_at TEXT NOT NULL,
|
|
201
|
+
UNIQUE(project_id, relative_path, artifact_id)
|
|
202
|
+
);
|
|
203
|
+
CREATE TABLE preparation_chunks (
|
|
204
|
+
run_id TEXT NOT NULL,
|
|
205
|
+
version_id TEXT NOT NULL,
|
|
206
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= 0),
|
|
207
|
+
ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
|
|
208
|
+
start_sample INTEGER NOT NULL CHECK (start_sample >= 0),
|
|
209
|
+
end_sample INTEGER NOT NULL CHECK (end_sample > start_sample),
|
|
210
|
+
source_span_json TEXT NOT NULL,
|
|
211
|
+
status TEXT NOT NULL CHECK (status IN ('pending', 'transcribed', 'no_speech')),
|
|
212
|
+
transcript_artifact_id TEXT REFERENCES artifacts(artifact_id),
|
|
213
|
+
result_json TEXT,
|
|
214
|
+
PRIMARY KEY(run_id, version_id, stream_index, ordinal),
|
|
215
|
+
FOREIGN KEY(run_id, version_id, stream_index)
|
|
216
|
+
REFERENCES preparation_items(run_id, version_id, stream_index)
|
|
217
|
+
ON DELETE CASCADE
|
|
218
|
+
);
|
|
219
|
+
CREATE TABLE transcription_revisions (
|
|
220
|
+
revision_id TEXT PRIMARY KEY,
|
|
221
|
+
project_id TEXT NOT NULL REFERENCES project(project_id),
|
|
222
|
+
run_id TEXT NOT NULL REFERENCES preparation_runs(run_id),
|
|
223
|
+
version_id TEXT NOT NULL REFERENCES asset_versions(version_id),
|
|
224
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= 0),
|
|
225
|
+
artifact_id TEXT REFERENCES artifacts(artifact_id),
|
|
226
|
+
parent_revision_id TEXT REFERENCES transcription_revisions(revision_id),
|
|
227
|
+
status TEXT NOT NULL CHECK (
|
|
228
|
+
status IN ('transcribed', 'no_speech_detected', 'failed', 'needs_review')
|
|
229
|
+
),
|
|
230
|
+
language TEXT,
|
|
231
|
+
model_json TEXT NOT NULL,
|
|
232
|
+
recipe_id TEXT NOT NULL,
|
|
233
|
+
source_span_json TEXT NOT NULL,
|
|
234
|
+
created_at TEXT NOT NULL
|
|
235
|
+
);
|
|
236
|
+
CREATE TABLE transcript_segments (
|
|
237
|
+
revision_id TEXT NOT NULL REFERENCES transcription_revisions(revision_id)
|
|
238
|
+
ON DELETE CASCADE,
|
|
239
|
+
segment_id TEXT NOT NULL,
|
|
240
|
+
start_pts TEXT NOT NULL,
|
|
241
|
+
end_pts TEXT NOT NULL,
|
|
242
|
+
text TEXT NOT NULL,
|
|
243
|
+
speaker_id TEXT,
|
|
244
|
+
confidence TEXT,
|
|
245
|
+
ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
|
|
246
|
+
PRIMARY KEY(revision_id, segment_id),
|
|
247
|
+
UNIQUE(revision_id, ordinal)
|
|
248
|
+
);
|
|
249
|
+
CREATE TABLE current_preparation (
|
|
250
|
+
slot INTEGER PRIMARY KEY CHECK (slot = 1),
|
|
251
|
+
run_id TEXT NOT NULL REFERENCES preparation_runs(run_id)
|
|
252
|
+
);
|
|
253
|
+
CREATE INDEX preparation_runs_project_created
|
|
254
|
+
ON preparation_runs(project_id, created_at DESC);
|
|
255
|
+
CREATE UNIQUE INDEX preparation_runs_operation
|
|
256
|
+
ON preparation_runs(operation_id);
|
|
257
|
+
CREATE UNIQUE INDEX preparation_runs_attempt
|
|
258
|
+
ON preparation_runs(attempt_id);
|
|
259
|
+
CREATE INDEX preparation_items_run_status
|
|
260
|
+
ON preparation_items(run_id, status, version_id);
|
|
261
|
+
CREATE INDEX operation_events_project_sequence
|
|
262
|
+
ON operation_events(project_id, sequence);
|
|
263
|
+
CREATE INDEX artifacts_project_kind
|
|
264
|
+
ON artifacts(project_id, kind, created_at);
|
|
265
|
+
CREATE INDEX preparation_chunks_run_status
|
|
266
|
+
ON preparation_chunks(run_id, status, version_id, stream_index, ordinal);
|
|
267
|
+
CREATE INDEX transcription_revisions_version_created
|
|
268
|
+
ON transcription_revisions(version_id, created_at DESC);
|
|
269
|
+
"""
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
def utc_now() -> str:
|
|
273
|
+
return datetime.now(timezone.utc).isoformat(timespec="microseconds")
|
|
274
|
+
|
|
275
|
+
|
|
276
|
+
def command_digest(command: Mapping[str, Any]) -> str:
|
|
277
|
+
encoded = json.dumps(
|
|
278
|
+
command,
|
|
279
|
+
ensure_ascii=False,
|
|
280
|
+
sort_keys=True,
|
|
281
|
+
separators=(",", ":"),
|
|
282
|
+
).encode("utf-8")
|
|
283
|
+
return hashlib.sha256(encoded).hexdigest()
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
class ProjectRepository:
|
|
287
|
+
"""One SQLite database per project, discovered only below a managed root."""
|
|
288
|
+
|
|
289
|
+
def __init__(self, projects_root: Path) -> None:
|
|
290
|
+
projects_root.mkdir(mode=0o700, parents=True, exist_ok=True)
|
|
291
|
+
if projects_root.is_symlink():
|
|
292
|
+
raise ProjectError("storage_unsafe", "Clipen 作品儲存位置不安全。", status_code=500)
|
|
293
|
+
self.root = projects_root.resolve(strict=True)
|
|
294
|
+
if not self.root.is_dir():
|
|
295
|
+
raise ProjectError("storage_unavailable", "Clipen 無法使用作品儲存位置。", status_code=500)
|
|
296
|
+
restrict_permissions(self.root, 0o700)
|
|
297
|
+
self._deletion = ProjectDeletion(self)
|
|
298
|
+
|
|
299
|
+
def create_project(self, request_id: object, name: object) -> ProjectSnapshot:
|
|
300
|
+
normalized_request = validate_request_id(request_id)
|
|
301
|
+
normalized_name = validate_name(name)
|
|
302
|
+
command_hash = command_digest({"name": normalized_name})
|
|
303
|
+
project_id = (
|
|
304
|
+
"prj_" + hashlib.sha256(f"clipen:create-project:v1:{normalized_request}".encode("utf-8")).hexdigest()[:32]
|
|
305
|
+
)
|
|
306
|
+
project_dir = self._project_dir(project_id)
|
|
307
|
+
|
|
308
|
+
if project_dir.exists():
|
|
309
|
+
replay = self.replay_receipt(project_id, normalized_request, "create_project", command_hash)
|
|
310
|
+
if replay is None:
|
|
311
|
+
raise ProjectError(
|
|
312
|
+
"request_conflict",
|
|
313
|
+
"這次建立作品的操作與既有資料衝突。",
|
|
314
|
+
status_code=409,
|
|
315
|
+
)
|
|
316
|
+
return replay
|
|
317
|
+
|
|
318
|
+
staging = self.root / f".staging-{project_id}-{uuid.uuid4().hex}"
|
|
319
|
+
staging.mkdir(mode=0o700)
|
|
320
|
+
try:
|
|
321
|
+
snapshot = self._initialize_project(
|
|
322
|
+
staging / "project.sqlite3",
|
|
323
|
+
project_id,
|
|
324
|
+
normalized_name,
|
|
325
|
+
normalized_request,
|
|
326
|
+
command_hash,
|
|
327
|
+
)
|
|
328
|
+
try:
|
|
329
|
+
staging.rename(project_dir)
|
|
330
|
+
except FileExistsError:
|
|
331
|
+
self._remove_staging(staging)
|
|
332
|
+
replay = self.replay_receipt(project_id, normalized_request, "create_project", command_hash)
|
|
333
|
+
if replay is None:
|
|
334
|
+
raise ProjectError(
|
|
335
|
+
"request_conflict",
|
|
336
|
+
"這次建立作品的操作與既有資料衝突。",
|
|
337
|
+
status_code=409,
|
|
338
|
+
)
|
|
339
|
+
return replay
|
|
340
|
+
return snapshot
|
|
341
|
+
except Exception:
|
|
342
|
+
if staging.exists() and not staging.is_symlink():
|
|
343
|
+
self._remove_staging(staging)
|
|
344
|
+
raise
|
|
345
|
+
|
|
346
|
+
def list_projects(self) -> tuple[ProjectSnapshot, ...]:
|
|
347
|
+
projects: list[ProjectSnapshot] = []
|
|
348
|
+
try:
|
|
349
|
+
entries = tuple(self.root.iterdir())
|
|
350
|
+
except OSError as error:
|
|
351
|
+
raise ProjectError("storage_unavailable", "Clipen 無法讀取作品列表。", status_code=500) from error
|
|
352
|
+
for entry in entries:
|
|
353
|
+
if _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
|
|
354
|
+
continue
|
|
355
|
+
if entry.is_symlink() or not entry.is_dir():
|
|
356
|
+
raise ProjectError("storage_unsafe", "Clipen 偵測到不安全的作品資料。", status_code=500)
|
|
357
|
+
project = self.get_project(entry.name)
|
|
358
|
+
# Activity is derived so editing never changes the metadata revision
|
|
359
|
+
# or invalidates the user's source grants and inventory.
|
|
360
|
+
with self.connect(entry.name) as db:
|
|
361
|
+
activity = db.execute("""SELECT MAX(at) FROM (
|
|
362
|
+
SELECT MAX(created_at) AS at FROM edit_agent_events
|
|
363
|
+
UNION ALL SELECT MAX(created_at) FROM edit_agent_revisions
|
|
364
|
+
UNION ALL SELECT MAX(created_at) FROM operation_events
|
|
365
|
+
UNION ALL SELECT MAX(created_at) FROM inventory_runs
|
|
366
|
+
UNION ALL SELECT MAX(completed_at) FROM preview_renders
|
|
367
|
+
)""").fetchone()[0]
|
|
368
|
+
projects.append(replace(project, last_activity_at=max(project.updated_at, activity or project.updated_at)))
|
|
369
|
+
projects.sort(key=lambda project: project.last_activity_at or project.updated_at, reverse=True)
|
|
370
|
+
return tuple(projects)
|
|
371
|
+
|
|
372
|
+
def get_project(self, project_id: str) -> ProjectSnapshot:
|
|
373
|
+
validate_project_id(project_id)
|
|
374
|
+
with self.connect(project_id) as connection:
|
|
375
|
+
snapshot = self._read_snapshot(connection)
|
|
376
|
+
if snapshot.project_id != project_id:
|
|
377
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
|
|
378
|
+
return snapshot
|
|
379
|
+
|
|
380
|
+
def replay_receipt(
|
|
381
|
+
self,
|
|
382
|
+
project_id: str,
|
|
383
|
+
request_id: str,
|
|
384
|
+
command_type: str,
|
|
385
|
+
request_hash: str,
|
|
386
|
+
) -> ProjectSnapshot | None:
|
|
387
|
+
validate_project_id(project_id)
|
|
388
|
+
validate_request_id(request_id)
|
|
389
|
+
with self.connect(project_id) as connection:
|
|
390
|
+
row = connection.execute(
|
|
391
|
+
"SELECT command_type, request_hash, response_json FROM command_receipts WHERE request_id = ?",
|
|
392
|
+
(request_id,),
|
|
393
|
+
).fetchone()
|
|
394
|
+
if row is None:
|
|
395
|
+
return None
|
|
396
|
+
if row["command_type"] != command_type or row["request_hash"] != request_hash:
|
|
397
|
+
raise ProjectError(
|
|
398
|
+
"request_reused",
|
|
399
|
+
"這次操作的識別資訊已用於不同內容。",
|
|
400
|
+
status_code=409,
|
|
401
|
+
)
|
|
402
|
+
try:
|
|
403
|
+
payload = json.loads(row["response_json"])
|
|
404
|
+
if not isinstance(payload, dict):
|
|
405
|
+
raise ValueError("receipt response must be an object")
|
|
406
|
+
return ProjectSnapshot.from_storage(payload)
|
|
407
|
+
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
|
|
408
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品操作紀錄。", status_code=500) from error
|
|
409
|
+
|
|
410
|
+
def update_details(
|
|
411
|
+
self,
|
|
412
|
+
project_id: str,
|
|
413
|
+
request_id: object,
|
|
414
|
+
expected_revision: object,
|
|
415
|
+
name: object,
|
|
416
|
+
brief: object,
|
|
417
|
+
) -> ProjectSnapshot:
|
|
418
|
+
normalized_request = validate_request_id(request_id)
|
|
419
|
+
revision = validate_revision(expected_revision)
|
|
420
|
+
normalized_name = validate_name(name)
|
|
421
|
+
normalized_brief = validate_brief(brief)
|
|
422
|
+
command = {
|
|
423
|
+
"expected_revision": revision,
|
|
424
|
+
"name": normalized_name,
|
|
425
|
+
"brief": normalized_brief,
|
|
426
|
+
}
|
|
427
|
+
return self._mutate(
|
|
428
|
+
project_id,
|
|
429
|
+
normalized_request,
|
|
430
|
+
"update_details",
|
|
431
|
+
command_digest(command),
|
|
432
|
+
revision,
|
|
433
|
+
lambda connection, now: connection.execute(
|
|
434
|
+
"UPDATE project SET name = ?, brief = ?, revision = revision + 1, updated_at = ? WHERE project_id = ?",
|
|
435
|
+
(normalized_name, normalized_brief, now, project_id),
|
|
436
|
+
),
|
|
437
|
+
)
|
|
438
|
+
|
|
439
|
+
def set_directory(
|
|
440
|
+
self,
|
|
441
|
+
project_id: str,
|
|
442
|
+
request_id: str,
|
|
443
|
+
request_hash: str,
|
|
444
|
+
expected_revision: int,
|
|
445
|
+
reference: DirectoryReference,
|
|
446
|
+
) -> ProjectSnapshot:
|
|
447
|
+
def mutation(connection: sqlite3.Connection, now: str) -> None:
|
|
448
|
+
connection.execute(
|
|
449
|
+
"INSERT INTO project_directories "
|
|
450
|
+
"(role, canonical_path, display_path, display_name, device, inode, saved_at) "
|
|
451
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?) "
|
|
452
|
+
"ON CONFLICT(role) DO UPDATE SET canonical_path = excluded.canonical_path, "
|
|
453
|
+
"display_path = excluded.display_path, display_name = excluded.display_name, "
|
|
454
|
+
"device = excluded.device, inode = excluded.inode, saved_at = excluded.saved_at",
|
|
455
|
+
(
|
|
456
|
+
reference.role.value,
|
|
457
|
+
reference.canonical_path,
|
|
458
|
+
reference.display_path,
|
|
459
|
+
reference.display_name,
|
|
460
|
+
reference.device,
|
|
461
|
+
reference.inode,
|
|
462
|
+
reference.saved_at,
|
|
463
|
+
),
|
|
464
|
+
)
|
|
465
|
+
connection.execute("DELETE FROM current_inventory")
|
|
466
|
+
|
|
467
|
+
return self._mutate(
|
|
468
|
+
project_id,
|
|
469
|
+
request_id,
|
|
470
|
+
"set_directory",
|
|
471
|
+
request_hash,
|
|
472
|
+
expected_revision,
|
|
473
|
+
mutation,
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
def remove_directory(
|
|
477
|
+
self,
|
|
478
|
+
project_id: str,
|
|
479
|
+
request_id: object,
|
|
480
|
+
expected_revision: object,
|
|
481
|
+
role: DirectoryRole,
|
|
482
|
+
) -> ProjectSnapshot:
|
|
483
|
+
normalized_request = validate_request_id(request_id)
|
|
484
|
+
revision = validate_revision(expected_revision)
|
|
485
|
+
command_hash = command_digest({"expected_revision": revision, "role": role.value})
|
|
486
|
+
|
|
487
|
+
def mutation(connection: sqlite3.Connection, _: str) -> None:
|
|
488
|
+
connection.execute("DELETE FROM project_directories WHERE role = ?", (role.value,))
|
|
489
|
+
connection.execute("DELETE FROM current_inventory")
|
|
490
|
+
|
|
491
|
+
return self._mutate(
|
|
492
|
+
project_id,
|
|
493
|
+
normalized_request,
|
|
494
|
+
"remove_directory",
|
|
495
|
+
command_hash,
|
|
496
|
+
revision,
|
|
497
|
+
mutation,
|
|
498
|
+
)
|
|
499
|
+
|
|
500
|
+
def delete_project(
|
|
501
|
+
self,
|
|
502
|
+
project_id: str,
|
|
503
|
+
request_id: object,
|
|
504
|
+
expected_revision: object,
|
|
505
|
+
confirmation_name: object,
|
|
506
|
+
) -> str:
|
|
507
|
+
return self._deletion.delete(
|
|
508
|
+
project_id,
|
|
509
|
+
request_id,
|
|
510
|
+
expected_revision,
|
|
511
|
+
confirmation_name,
|
|
512
|
+
)
|
|
513
|
+
|
|
514
|
+
def _mutate(
|
|
515
|
+
self,
|
|
516
|
+
project_id: str,
|
|
517
|
+
request_id: str,
|
|
518
|
+
command_type: str,
|
|
519
|
+
request_hash: str,
|
|
520
|
+
expected_revision: int,
|
|
521
|
+
mutation,
|
|
522
|
+
) -> ProjectSnapshot:
|
|
523
|
+
validate_project_id(project_id)
|
|
524
|
+
validate_request_id(request_id)
|
|
525
|
+
validate_revision(expected_revision)
|
|
526
|
+
with self.connect(project_id) as connection:
|
|
527
|
+
try:
|
|
528
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
529
|
+
receipt = connection.execute(
|
|
530
|
+
"SELECT command_type, request_hash, response_json FROM command_receipts WHERE request_id = ?",
|
|
531
|
+
(request_id,),
|
|
532
|
+
).fetchone()
|
|
533
|
+
if receipt is not None:
|
|
534
|
+
if receipt["command_type"] != command_type or receipt["request_hash"] != request_hash:
|
|
535
|
+
raise ProjectError(
|
|
536
|
+
"request_reused",
|
|
537
|
+
"這次操作的識別資訊已用於不同內容。",
|
|
538
|
+
status_code=409,
|
|
539
|
+
)
|
|
540
|
+
response = json.loads(receipt["response_json"])
|
|
541
|
+
connection.rollback()
|
|
542
|
+
return ProjectSnapshot.from_storage(response)
|
|
543
|
+
|
|
544
|
+
current = connection.execute(
|
|
545
|
+
"SELECT revision FROM project WHERE project_id = ?", (project_id,)
|
|
546
|
+
).fetchone()
|
|
547
|
+
if current is None:
|
|
548
|
+
raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
|
|
549
|
+
if current["revision"] != expected_revision:
|
|
550
|
+
raise ProjectError(
|
|
551
|
+
"revision_conflict",
|
|
552
|
+
"作品已在其他分頁更新,請重新載入最新內容。",
|
|
553
|
+
status_code=409,
|
|
554
|
+
)
|
|
555
|
+
now = utc_now()
|
|
556
|
+
mutation(connection, now)
|
|
557
|
+
if command_type != "update_details":
|
|
558
|
+
connection.execute(
|
|
559
|
+
"UPDATE project SET revision = revision + 1, updated_at = ? WHERE project_id = ?",
|
|
560
|
+
(now, project_id),
|
|
561
|
+
)
|
|
562
|
+
snapshot = self._read_snapshot(connection)
|
|
563
|
+
response_json = json.dumps(snapshot.to_storage(), ensure_ascii=False, separators=(",", ":"))
|
|
564
|
+
connection.execute(
|
|
565
|
+
"INSERT INTO command_receipts "
|
|
566
|
+
"(request_id, command_type, request_hash, response_json, created_at) "
|
|
567
|
+
"VALUES (?, ?, ?, ?, ?)",
|
|
568
|
+
(request_id, command_type, request_hash, response_json, now),
|
|
569
|
+
)
|
|
570
|
+
connection.commit()
|
|
571
|
+
return snapshot
|
|
572
|
+
except ProjectError:
|
|
573
|
+
connection.rollback()
|
|
574
|
+
raise
|
|
575
|
+
except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
|
|
576
|
+
connection.rollback()
|
|
577
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500) from error
|
|
578
|
+
except sqlite3.Error as error:
|
|
579
|
+
connection.rollback()
|
|
580
|
+
raise ProjectError("storage_failed", "Clipen 無法保存作品。", status_code=500) from error
|
|
581
|
+
|
|
582
|
+
def _initialize_project(
|
|
583
|
+
self,
|
|
584
|
+
database: Path,
|
|
585
|
+
project_id: str,
|
|
586
|
+
name: str,
|
|
587
|
+
request_id: str,
|
|
588
|
+
command_hash: str,
|
|
589
|
+
) -> ProjectSnapshot:
|
|
590
|
+
now = utc_now()
|
|
591
|
+
connection = sqlite3.connect(database, isolation_level=None)
|
|
592
|
+
connection.row_factory = sqlite3.Row
|
|
593
|
+
try:
|
|
594
|
+
self._configure(connection)
|
|
595
|
+
connection.executescript(
|
|
596
|
+
"""
|
|
597
|
+
BEGIN IMMEDIATE;
|
|
598
|
+
CREATE TABLE project (
|
|
599
|
+
project_id TEXT PRIMARY KEY,
|
|
600
|
+
name TEXT NOT NULL,
|
|
601
|
+
brief TEXT NOT NULL,
|
|
602
|
+
stage TEXT NOT NULL CHECK (stage = 'materials'),
|
|
603
|
+
revision INTEGER NOT NULL CHECK (revision >= 1),
|
|
604
|
+
created_at TEXT NOT NULL,
|
|
605
|
+
updated_at TEXT NOT NULL
|
|
606
|
+
);
|
|
607
|
+
CREATE TABLE project_directories (
|
|
608
|
+
role TEXT PRIMARY KEY CHECK (role IN ('source', 'reference')),
|
|
609
|
+
canonical_path TEXT NOT NULL,
|
|
610
|
+
display_path TEXT NOT NULL,
|
|
611
|
+
display_name TEXT NOT NULL,
|
|
612
|
+
device INTEGER NOT NULL,
|
|
613
|
+
inode INTEGER NOT NULL,
|
|
614
|
+
saved_at TEXT NOT NULL
|
|
615
|
+
);
|
|
616
|
+
CREATE TABLE command_receipts (
|
|
617
|
+
request_id TEXT PRIMARY KEY,
|
|
618
|
+
command_type TEXT NOT NULL,
|
|
619
|
+
request_hash TEXT NOT NULL,
|
|
620
|
+
response_json TEXT NOT NULL,
|
|
621
|
+
created_at TEXT NOT NULL
|
|
622
|
+
);
|
|
623
|
+
"""
|
|
624
|
+
+ _INVENTORY_SCHEMA
|
|
625
|
+
+ _ANALYSIS_SCHEMA
|
|
626
|
+
+ EVIDENCE_SCHEMA
|
|
627
|
+
+ OBSERVATION_SCHEMA
|
|
628
|
+
+ VALIDATION_WORKFLOW_SCHEMA
|
|
629
|
+
+ TIMELINE_SCHEMA
|
|
630
|
+
+ ANNOTATION_SCHEMA
|
|
631
|
+
+ PREVIEW_SCHEMA
|
|
632
|
+
+ EDIT_AGENT_SCHEMA
|
|
633
|
+
+ PRODUCTION_SESSION_SCHEMA
|
|
634
|
+
+ FINISHING_SCHEMA
|
|
635
|
+
+ """
|
|
636
|
+
PRAGMA user_version = 19;
|
|
637
|
+
"""
|
|
638
|
+
)
|
|
639
|
+
connection.execute(
|
|
640
|
+
"INSERT INTO project "
|
|
641
|
+
"(project_id, name, brief, stage, revision, created_at, updated_at) "
|
|
642
|
+
"VALUES (?, ?, '', 'materials', 1, ?, ?)",
|
|
643
|
+
(project_id, name, now, now),
|
|
644
|
+
)
|
|
645
|
+
snapshot = self._read_snapshot(connection)
|
|
646
|
+
connection.execute(
|
|
647
|
+
"INSERT INTO command_receipts "
|
|
648
|
+
"(request_id, command_type, request_hash, response_json, created_at) "
|
|
649
|
+
"VALUES (?, 'create_project', ?, ?, ?)",
|
|
650
|
+
(
|
|
651
|
+
request_id,
|
|
652
|
+
command_hash,
|
|
653
|
+
json.dumps(snapshot.to_storage(), ensure_ascii=False, separators=(",", ":")),
|
|
654
|
+
now,
|
|
655
|
+
),
|
|
656
|
+
)
|
|
657
|
+
connection.commit()
|
|
658
|
+
except Exception:
|
|
659
|
+
connection.rollback()
|
|
660
|
+
raise
|
|
661
|
+
finally:
|
|
662
|
+
connection.close()
|
|
663
|
+
restrict_permissions(database, 0o600)
|
|
664
|
+
return snapshot
|
|
665
|
+
|
|
666
|
+
@contextmanager
|
|
667
|
+
def connect(self, project_id: str) -> Iterator[sqlite3.Connection]:
|
|
668
|
+
project_dir = self._project_dir(project_id)
|
|
669
|
+
if project_dir.is_symlink() or not project_dir.is_dir():
|
|
670
|
+
raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
|
|
671
|
+
database = project_dir / "project.sqlite3"
|
|
672
|
+
if database.is_symlink() or not database.is_file():
|
|
673
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
|
|
674
|
+
try:
|
|
675
|
+
connection = sqlite3.connect(database, timeout=5, isolation_level=None)
|
|
676
|
+
connection.row_factory = sqlite3.Row
|
|
677
|
+
self._configure(connection)
|
|
678
|
+
version = connection.execute("PRAGMA user_version").fetchone()[0]
|
|
679
|
+
if version == 1:
|
|
680
|
+
self._migrate_v1_to_v2(connection)
|
|
681
|
+
version = connection.execute("PRAGMA user_version").fetchone()[0]
|
|
682
|
+
if version == 2:
|
|
683
|
+
self._migrate_v2_to_v3(connection)
|
|
684
|
+
version = connection.execute("PRAGMA user_version").fetchone()[0]
|
|
685
|
+
if version == 3:
|
|
686
|
+
self._migrate_v3_to_v4(connection)
|
|
687
|
+
version = connection.execute("PRAGMA user_version").fetchone()[0]
|
|
688
|
+
if version == 4:
|
|
689
|
+
self._migrate_v4_to_v5(connection)
|
|
690
|
+
version = 5
|
|
691
|
+
if version == 5:
|
|
692
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + EVIDENCE_SCHEMA + "\nPRAGMA user_version = 6;\nCOMMIT;")
|
|
693
|
+
version = 6
|
|
694
|
+
if version == 6:
|
|
695
|
+
self._migrate_v6_to_v7(connection)
|
|
696
|
+
version = 7
|
|
697
|
+
if version == 7:
|
|
698
|
+
self._migrate_v7_to_v8(connection)
|
|
699
|
+
version = 8
|
|
700
|
+
if version == 8:
|
|
701
|
+
self._migrate_v8_to_v9(connection)
|
|
702
|
+
version = 9
|
|
703
|
+
if version == 9:
|
|
704
|
+
self._migrate_v9_to_v10(connection)
|
|
705
|
+
version = 10
|
|
706
|
+
if version == 10:
|
|
707
|
+
self._migrate_v10_to_v11(connection)
|
|
708
|
+
version = 11
|
|
709
|
+
if version == 11:
|
|
710
|
+
self._migrate_v11_to_v12(connection)
|
|
711
|
+
version = 12
|
|
712
|
+
if version == 12:
|
|
713
|
+
self._migrate_v12_to_v13(connection)
|
|
714
|
+
version = 13
|
|
715
|
+
if version == 13:
|
|
716
|
+
self._migrate_v13_to_v14(connection)
|
|
717
|
+
version = 14
|
|
718
|
+
if version == 14:
|
|
719
|
+
self._migrate_v14_to_v15(connection)
|
|
720
|
+
version = 15
|
|
721
|
+
if version == 15:
|
|
722
|
+
self._migrate_v15_to_v16(connection)
|
|
723
|
+
version = 16
|
|
724
|
+
if version == 16:
|
|
725
|
+
self._migrate_v16_to_v17(connection)
|
|
726
|
+
version = 17
|
|
727
|
+
if version == 17:
|
|
728
|
+
self._migrate_v17_to_v18(connection)
|
|
729
|
+
version = 18
|
|
730
|
+
if version == 18:
|
|
731
|
+
self._migrate_v18_to_v19(connection, project_dir)
|
|
732
|
+
version = 19
|
|
733
|
+
if version != PROJECT_SCHEMA_VERSION:
|
|
734
|
+
connection.close()
|
|
735
|
+
raise ProjectError(
|
|
736
|
+
"migration_required",
|
|
737
|
+
"這個作品需要其他版本的 Clipen。",
|
|
738
|
+
status_code=409,
|
|
739
|
+
)
|
|
740
|
+
yield connection
|
|
741
|
+
except sqlite3.Error as error:
|
|
742
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500) from error
|
|
743
|
+
finally:
|
|
744
|
+
if "connection" in locals():
|
|
745
|
+
connection.close()
|
|
746
|
+
|
|
747
|
+
@staticmethod
|
|
748
|
+
def _migrate_v17_to_v18(connection: sqlite3.Connection) -> None:
|
|
749
|
+
# Replace the parent table without renaming it: SQLite would otherwise
|
|
750
|
+
# rewrite revision/event FKs to a temporary table name. All child rows
|
|
751
|
+
# and legacy provenance survive; fresh sessions have no base timeline.
|
|
752
|
+
create = EDIT_AGENT_SCHEMA.split("CREATE TABLE edit_agent_revisions", 1)[0]
|
|
753
|
+
create = create.replace("CREATE TABLE edit_agent_runs", "CREATE TABLE edit_agent_runs_v18", 1)
|
|
754
|
+
connection.execute("PRAGMA foreign_keys=OFF")
|
|
755
|
+
try:
|
|
756
|
+
prior_violations = {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")}
|
|
757
|
+
connection.executescript(
|
|
758
|
+
"BEGIN IMMEDIATE;\n" + create + "INSERT INTO edit_agent_runs_v18 SELECT * FROM edit_agent_runs;\n"
|
|
759
|
+
"DROP TABLE edit_agent_runs;\n"
|
|
760
|
+
"ALTER TABLE edit_agent_runs_v18 RENAME TO edit_agent_runs;\n"
|
|
761
|
+
"CREATE INDEX edit_agent_runs_project_created ON edit_agent_runs(project_id,created_at DESC);\n"
|
|
762
|
+
+ PRODUCTION_SESSION_SCHEMA.replace("CREATE TABLE ", "CREATE TABLE IF NOT EXISTS ")
|
|
763
|
+
)
|
|
764
|
+
if {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")} - prior_violations:
|
|
765
|
+
raise sqlite3.DatabaseError("production migration broke foreign keys")
|
|
766
|
+
connection.execute("PRAGMA user_version=18")
|
|
767
|
+
connection.commit()
|
|
768
|
+
except Exception:
|
|
769
|
+
connection.rollback()
|
|
770
|
+
raise
|
|
771
|
+
finally:
|
|
772
|
+
connection.execute("PRAGMA foreign_keys=ON")
|
|
773
|
+
|
|
774
|
+
@staticmethod
|
|
775
|
+
def _migrate_v18_to_v19(connection: sqlite3.Connection, project_dir: Path) -> None:
|
|
776
|
+
"""Drop the retired confirmed-plan tables without losing what they held.
|
|
777
|
+
|
|
778
|
+
Rows still in those tables are first written to a private JSON archive
|
|
779
|
+
beside the database (replaced atomically, so an interrupted migration
|
|
780
|
+
simply writes it again). The drop and the version bump then commit in
|
|
781
|
+
one transaction, and the foreign keys must still hold afterwards.
|
|
782
|
+
"""
|
|
783
|
+
|
|
784
|
+
present = [
|
|
785
|
+
table
|
|
786
|
+
for table in RETIRED_PLANNING_TABLES
|
|
787
|
+
if connection.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone()
|
|
788
|
+
is not None
|
|
789
|
+
]
|
|
790
|
+
archive = {table: [dict(row) for row in connection.execute(f"SELECT * FROM {table}")] for table in present}
|
|
791
|
+
if any(archive.values()):
|
|
792
|
+
target = project_dir / RETIRED_PLANNING_ARCHIVE
|
|
793
|
+
if target.is_symlink():
|
|
794
|
+
raise sqlite3.DatabaseError("unsafe retired planning archive")
|
|
795
|
+
temporary = project_dir / (RETIRED_PLANNING_ARCHIVE + ".tmp")
|
|
796
|
+
temporary.unlink(missing_ok=True)
|
|
797
|
+
descriptor = os.open(temporary, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)
|
|
798
|
+
with os.fdopen(descriptor, "w", encoding="utf-8") as output:
|
|
799
|
+
json.dump({"schema_version": 18, "tables": archive}, output, ensure_ascii=False, indent=1)
|
|
800
|
+
output.flush()
|
|
801
|
+
os.fsync(output.fileno())
|
|
802
|
+
os.replace(temporary, target)
|
|
803
|
+
try:
|
|
804
|
+
connection.execute("BEGIN IMMEDIATE")
|
|
805
|
+
prior_violations = {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")}
|
|
806
|
+
for table in present:
|
|
807
|
+
connection.execute(f"DROP TABLE {table}")
|
|
808
|
+
if {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")} - prior_violations:
|
|
809
|
+
raise sqlite3.DatabaseError("retiring planning tables broke foreign keys")
|
|
810
|
+
connection.execute("PRAGMA user_version = 19")
|
|
811
|
+
connection.commit()
|
|
812
|
+
except Exception:
|
|
813
|
+
connection.rollback()
|
|
814
|
+
raise
|
|
815
|
+
|
|
816
|
+
@staticmethod
|
|
817
|
+
def _migrate_v1_to_v2(connection: sqlite3.Connection) -> None:
|
|
818
|
+
try:
|
|
819
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + _INVENTORY_SCHEMA + "\nPRAGMA user_version = 2;\nCOMMIT;")
|
|
820
|
+
except sqlite3.Error:
|
|
821
|
+
connection.rollback()
|
|
822
|
+
raise
|
|
823
|
+
|
|
824
|
+
@staticmethod
|
|
825
|
+
def _migrate_v6_to_v7(connection: sqlite3.Connection) -> None:
|
|
826
|
+
"""Finish an interrupted observation migration without deleting data."""
|
|
827
|
+
|
|
828
|
+
existing = connection.execute(
|
|
829
|
+
"SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'evidence_observations'"
|
|
830
|
+
).fetchone()
|
|
831
|
+
migration_sql = OBSERVATION_SCHEMA
|
|
832
|
+
if existing is not None:
|
|
833
|
+
observed_sql = existing["sql"]
|
|
834
|
+
expected = " ".join(OBSERVATION_SCHEMA.rstrip(";\n ").split())
|
|
835
|
+
observed = " ".join(observed_sql.rstrip(";\n ").split()) if isinstance(observed_sql, str) else ""
|
|
836
|
+
if observed != expected:
|
|
837
|
+
raise sqlite3.DatabaseError("unexpected evidence observation schema")
|
|
838
|
+
migration_sql = ""
|
|
839
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 7;\nCOMMIT;")
|
|
840
|
+
|
|
841
|
+
@staticmethod
|
|
842
|
+
def _migrate_v7_to_v8(connection: sqlite3.Connection) -> None:
|
|
843
|
+
"""Create or verify the validation workflow after an interrupted migration."""
|
|
844
|
+
|
|
845
|
+
expected_columns = {
|
|
846
|
+
"timeline_validation_reports": (
|
|
847
|
+
"report_id",
|
|
848
|
+
"project_id",
|
|
849
|
+
"timeline_id",
|
|
850
|
+
"capability_profile_id",
|
|
851
|
+
"capability_content_hash",
|
|
852
|
+
"report_digest",
|
|
853
|
+
"status",
|
|
854
|
+
"report_json",
|
|
855
|
+
"created_at",
|
|
856
|
+
),
|
|
857
|
+
"current_timeline_validation": ("slot", "report_id"),
|
|
858
|
+
"timeline_warning_acceptances": (
|
|
859
|
+
"request_id",
|
|
860
|
+
"report_id",
|
|
861
|
+
"report_digest",
|
|
862
|
+
"request_hash",
|
|
863
|
+
"accepted_at",
|
|
864
|
+
),
|
|
865
|
+
}
|
|
866
|
+
observed = {
|
|
867
|
+
row["name"]
|
|
868
|
+
for row in connection.execute(
|
|
869
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
|
|
870
|
+
tuple(expected_columns),
|
|
871
|
+
)
|
|
872
|
+
}
|
|
873
|
+
if observed and observed != set(expected_columns):
|
|
874
|
+
raise sqlite3.DatabaseError("incomplete validation workflow schema")
|
|
875
|
+
if observed:
|
|
876
|
+
for table, expected in expected_columns.items():
|
|
877
|
+
columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
|
|
878
|
+
if columns != expected:
|
|
879
|
+
raise sqlite3.DatabaseError("unexpected validation workflow schema")
|
|
880
|
+
indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
|
|
881
|
+
if "timeline_validation_reports_project_created" not in indexes:
|
|
882
|
+
raise sqlite3.DatabaseError("incomplete validation workflow indexes")
|
|
883
|
+
migration_sql = ""
|
|
884
|
+
else:
|
|
885
|
+
migration_sql = VALIDATION_WORKFLOW_SCHEMA
|
|
886
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 8;\nCOMMIT;")
|
|
887
|
+
|
|
888
|
+
@staticmethod
|
|
889
|
+
def _migrate_v8_to_v9(connection: sqlite3.Connection) -> None:
|
|
890
|
+
"""Version 9 added the retired planning tables; version 19 drops them again."""
|
|
891
|
+
|
|
892
|
+
connection.executescript("BEGIN IMMEDIATE;\nPRAGMA user_version = 9;\nCOMMIT;")
|
|
893
|
+
|
|
894
|
+
@staticmethod
|
|
895
|
+
def _migrate_v9_to_v10(connection: sqlite3.Connection) -> None:
|
|
896
|
+
"""Create or verify immutable timeline tables after interruption."""
|
|
897
|
+
|
|
898
|
+
expected_columns = {
|
|
899
|
+
"edit_timelines": (
|
|
900
|
+
"timeline_id",
|
|
901
|
+
"project_id",
|
|
902
|
+
"plan_id",
|
|
903
|
+
"plan_revision",
|
|
904
|
+
"plan_content_hash",
|
|
905
|
+
"output_preset",
|
|
906
|
+
"frame_rate",
|
|
907
|
+
"payload_digest",
|
|
908
|
+
"payload_json",
|
|
909
|
+
"created_at",
|
|
910
|
+
),
|
|
911
|
+
"current_timeline": ("slot", "timeline_id"),
|
|
912
|
+
"timeline_command_receipts": (
|
|
913
|
+
"request_id",
|
|
914
|
+
"command_type",
|
|
915
|
+
"request_hash",
|
|
916
|
+
"timeline_id",
|
|
917
|
+
"created_at",
|
|
918
|
+
),
|
|
919
|
+
}
|
|
920
|
+
observed = {
|
|
921
|
+
row["name"]
|
|
922
|
+
for row in connection.execute(
|
|
923
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
|
|
924
|
+
tuple(expected_columns),
|
|
925
|
+
)
|
|
926
|
+
}
|
|
927
|
+
if observed and observed != set(expected_columns):
|
|
928
|
+
raise sqlite3.DatabaseError("incomplete timeline schema")
|
|
929
|
+
if observed:
|
|
930
|
+
for table, expected in expected_columns.items():
|
|
931
|
+
columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
|
|
932
|
+
if columns != expected:
|
|
933
|
+
raise sqlite3.DatabaseError("unexpected timeline schema")
|
|
934
|
+
indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
|
|
935
|
+
if "edit_timelines_project_created" not in indexes:
|
|
936
|
+
raise sqlite3.DatabaseError("incomplete timeline indexes")
|
|
937
|
+
migration_sql = ""
|
|
938
|
+
else:
|
|
939
|
+
migration_sql = TIMELINE_SCHEMA
|
|
940
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 10;\nCOMMIT;")
|
|
941
|
+
|
|
942
|
+
@staticmethod
|
|
943
|
+
def _migrate_v10_to_v11(connection: sqlite3.Connection) -> None:
|
|
944
|
+
"""Create or verify user annotation tables after interruption."""
|
|
945
|
+
|
|
946
|
+
expected_columns = {
|
|
947
|
+
"material_annotations": (
|
|
948
|
+
"version_id",
|
|
949
|
+
"revision",
|
|
950
|
+
"people_json",
|
|
951
|
+
"location",
|
|
952
|
+
"trip_day",
|
|
953
|
+
"day_part",
|
|
954
|
+
"note",
|
|
955
|
+
"usage",
|
|
956
|
+
"updated_at",
|
|
957
|
+
),
|
|
958
|
+
"transcript_annotations": (
|
|
959
|
+
"version_id",
|
|
960
|
+
"stream_index",
|
|
961
|
+
"source_revision_id",
|
|
962
|
+
"revision",
|
|
963
|
+
"confirmed",
|
|
964
|
+
"corrections_json",
|
|
965
|
+
"updated_at",
|
|
966
|
+
),
|
|
967
|
+
"annotation_command_receipts": (
|
|
968
|
+
"request_id",
|
|
969
|
+
"command_type",
|
|
970
|
+
"request_hash",
|
|
971
|
+
"response_json",
|
|
972
|
+
"created_at",
|
|
973
|
+
),
|
|
974
|
+
}
|
|
975
|
+
observed = {
|
|
976
|
+
row["name"]
|
|
977
|
+
for row in connection.execute(
|
|
978
|
+
"SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
|
|
979
|
+
tuple(expected_columns),
|
|
980
|
+
)
|
|
981
|
+
}
|
|
982
|
+
if observed and observed != set(expected_columns):
|
|
983
|
+
raise sqlite3.DatabaseError("incomplete annotation schema")
|
|
984
|
+
if observed:
|
|
985
|
+
for table, expected in expected_columns.items():
|
|
986
|
+
columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
|
|
987
|
+
allowed = {expected}
|
|
988
|
+
if table == "transcript_annotations":
|
|
989
|
+
allowed.add(
|
|
990
|
+
(
|
|
991
|
+
"version_id",
|
|
992
|
+
"stream_index",
|
|
993
|
+
"source_revision_id",
|
|
994
|
+
"revision",
|
|
995
|
+
"confirmed",
|
|
996
|
+
"discarded",
|
|
997
|
+
"corrections_json",
|
|
998
|
+
"updated_at",
|
|
999
|
+
)
|
|
1000
|
+
)
|
|
1001
|
+
allowed.add(
|
|
1002
|
+
(
|
|
1003
|
+
"version_id",
|
|
1004
|
+
"stream_index",
|
|
1005
|
+
"source_revision_id",
|
|
1006
|
+
"revision",
|
|
1007
|
+
"confirmed",
|
|
1008
|
+
"corrections_json",
|
|
1009
|
+
"updated_at",
|
|
1010
|
+
"discarded",
|
|
1011
|
+
)
|
|
1012
|
+
)
|
|
1013
|
+
if columns not in allowed:
|
|
1014
|
+
raise sqlite3.DatabaseError("unexpected annotation schema")
|
|
1015
|
+
indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
|
|
1016
|
+
if "material_annotations_updated" not in indexes:
|
|
1017
|
+
raise sqlite3.DatabaseError("incomplete annotation indexes")
|
|
1018
|
+
migration_sql = ""
|
|
1019
|
+
else:
|
|
1020
|
+
migration_sql = ANNOTATION_SCHEMA
|
|
1021
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 11;\nCOMMIT;")
|
|
1022
|
+
|
|
1023
|
+
@staticmethod
|
|
1024
|
+
def _migrate_v11_to_v12(connection: sqlite3.Connection) -> None:
|
|
1025
|
+
"""Add reversible transcript removal without deleting ASR evidence."""
|
|
1026
|
+
|
|
1027
|
+
columns = tuple(row["name"] for row in connection.execute("PRAGMA table_info(transcript_annotations)"))
|
|
1028
|
+
previous = (
|
|
1029
|
+
"version_id",
|
|
1030
|
+
"stream_index",
|
|
1031
|
+
"source_revision_id",
|
|
1032
|
+
"revision",
|
|
1033
|
+
"confirmed",
|
|
1034
|
+
"corrections_json",
|
|
1035
|
+
"updated_at",
|
|
1036
|
+
)
|
|
1037
|
+
current = (
|
|
1038
|
+
"version_id",
|
|
1039
|
+
"stream_index",
|
|
1040
|
+
"source_revision_id",
|
|
1041
|
+
"revision",
|
|
1042
|
+
"confirmed",
|
|
1043
|
+
"discarded",
|
|
1044
|
+
"corrections_json",
|
|
1045
|
+
"updated_at",
|
|
1046
|
+
)
|
|
1047
|
+
migrated = (
|
|
1048
|
+
"version_id",
|
|
1049
|
+
"stream_index",
|
|
1050
|
+
"source_revision_id",
|
|
1051
|
+
"revision",
|
|
1052
|
+
"confirmed",
|
|
1053
|
+
"corrections_json",
|
|
1054
|
+
"updated_at",
|
|
1055
|
+
"discarded",
|
|
1056
|
+
)
|
|
1057
|
+
if columns == previous:
|
|
1058
|
+
migration_sql = (
|
|
1059
|
+
"ALTER TABLE transcript_annotations ADD COLUMN discarded INTEGER NOT NULL "
|
|
1060
|
+
"DEFAULT 0 CHECK (discarded IN (0, 1));"
|
|
1061
|
+
)
|
|
1062
|
+
elif columns in {current, migrated}:
|
|
1063
|
+
migration_sql = ""
|
|
1064
|
+
else:
|
|
1065
|
+
raise sqlite3.DatabaseError("unexpected transcript annotation schema")
|
|
1066
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 12;\nCOMMIT;")
|
|
1067
|
+
|
|
1068
|
+
@staticmethod
|
|
1069
|
+
def _migrate_v12_to_v13(connection: sqlite3.Connection) -> None:
|
|
1070
|
+
"""Create durable rough-cut preview render records."""
|
|
1071
|
+
|
|
1072
|
+
observed = {
|
|
1073
|
+
row["name"]
|
|
1074
|
+
for row in connection.execute(
|
|
1075
|
+
"SELECT name FROM sqlite_master WHERE type='table' "
|
|
1076
|
+
"AND name IN ('preview_renders','current_preview_render')"
|
|
1077
|
+
)
|
|
1078
|
+
}
|
|
1079
|
+
if observed and observed != {"preview_renders", "current_preview_render"}:
|
|
1080
|
+
raise sqlite3.DatabaseError("incomplete preview render schema")
|
|
1081
|
+
connection.executescript(
|
|
1082
|
+
"BEGIN IMMEDIATE;\n" + ("" if observed else PREVIEW_SCHEMA) + "\nPRAGMA user_version = 13;\nCOMMIT;"
|
|
1083
|
+
)
|
|
1084
|
+
|
|
1085
|
+
@staticmethod
|
|
1086
|
+
def _migrate_v13_to_v14(connection: sqlite3.Connection) -> None:
|
|
1087
|
+
"""Create or verify durable AI editing session tables."""
|
|
1088
|
+
|
|
1089
|
+
expected_columns = {
|
|
1090
|
+
"edit_agent_runs": (
|
|
1091
|
+
"run_id",
|
|
1092
|
+
"project_id",
|
|
1093
|
+
"request_id",
|
|
1094
|
+
"base_timeline_id",
|
|
1095
|
+
"state",
|
|
1096
|
+
"phase",
|
|
1097
|
+
"max_tool_calls",
|
|
1098
|
+
"tool_calls",
|
|
1099
|
+
"max_preview_renders",
|
|
1100
|
+
"preview_renders",
|
|
1101
|
+
"current_revision_id",
|
|
1102
|
+
"final_revision_id",
|
|
1103
|
+
"provider",
|
|
1104
|
+
"provider_attempt_id",
|
|
1105
|
+
"usage_json",
|
|
1106
|
+
"error_code",
|
|
1107
|
+
"created_at",
|
|
1108
|
+
"started_at",
|
|
1109
|
+
"completed_at",
|
|
1110
|
+
),
|
|
1111
|
+
"edit_agent_revisions": (
|
|
1112
|
+
"revision_id",
|
|
1113
|
+
"run_id",
|
|
1114
|
+
"ordinal",
|
|
1115
|
+
"parent_revision_id",
|
|
1116
|
+
"payload_digest",
|
|
1117
|
+
"payload_json",
|
|
1118
|
+
"summary",
|
|
1119
|
+
"created_at",
|
|
1120
|
+
),
|
|
1121
|
+
"edit_agent_events": (
|
|
1122
|
+
"event_id",
|
|
1123
|
+
"run_id",
|
|
1124
|
+
"sequence",
|
|
1125
|
+
"event_type",
|
|
1126
|
+
"payload_json",
|
|
1127
|
+
"created_at",
|
|
1128
|
+
),
|
|
1129
|
+
"edit_agent_command_receipts": (
|
|
1130
|
+
"request_id",
|
|
1131
|
+
"command_type",
|
|
1132
|
+
"request_hash",
|
|
1133
|
+
"response_json",
|
|
1134
|
+
"created_at",
|
|
1135
|
+
),
|
|
1136
|
+
}
|
|
1137
|
+
observed = {
|
|
1138
|
+
row["name"]
|
|
1139
|
+
for row in connection.execute(
|
|
1140
|
+
"SELECT name FROM sqlite_master WHERE type='table' "
|
|
1141
|
+
"AND name IN ('edit_agent_runs','edit_agent_revisions',"
|
|
1142
|
+
"'edit_agent_events','edit_agent_command_receipts')"
|
|
1143
|
+
)
|
|
1144
|
+
}
|
|
1145
|
+
if observed and observed != set(expected_columns):
|
|
1146
|
+
raise sqlite3.DatabaseError("incomplete edit agent schema")
|
|
1147
|
+
if observed:
|
|
1148
|
+
for table, expected in expected_columns.items():
|
|
1149
|
+
columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
|
|
1150
|
+
if columns != expected:
|
|
1151
|
+
raise sqlite3.DatabaseError("unexpected edit agent schema")
|
|
1152
|
+
indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='index'")}
|
|
1153
|
+
if not {
|
|
1154
|
+
"edit_agent_runs_project_created",
|
|
1155
|
+
"edit_agent_revisions_run_ordinal",
|
|
1156
|
+
"edit_agent_events_run_sequence",
|
|
1157
|
+
}.issubset(indexes):
|
|
1158
|
+
raise sqlite3.DatabaseError("incomplete edit agent indexes")
|
|
1159
|
+
connection.executescript(
|
|
1160
|
+
"BEGIN IMMEDIATE;\n" + ("" if observed else EDIT_AGENT_SCHEMA) + "\nPRAGMA user_version = 14;\nCOMMIT;"
|
|
1161
|
+
)
|
|
1162
|
+
|
|
1163
|
+
@staticmethod
|
|
1164
|
+
def _migrate_v16_to_v17(connection: sqlite3.Connection) -> None:
|
|
1165
|
+
connection.executescript(
|
|
1166
|
+
"BEGIN IMMEDIATE;\n"
|
|
1167
|
+
"DROP INDEX finishing_runs_created;\n"
|
|
1168
|
+
"ALTER TABLE finishing_runs RENAME TO finishing_runs_v16;\n"
|
|
1169
|
+
+ FINISHING_RUNS_SCHEMA
|
|
1170
|
+
+ "INSERT INTO finishing_runs SELECT * FROM finishing_runs_v16;\n"
|
|
1171
|
+
"DROP TABLE finishing_runs_v16;\n"
|
|
1172
|
+
"CREATE INDEX finishing_runs_created ON finishing_runs(created_at DESC);\n"
|
|
1173
|
+
"PRAGMA user_version=17;\nCOMMIT;"
|
|
1174
|
+
)
|
|
1175
|
+
|
|
1176
|
+
@staticmethod
|
|
1177
|
+
def _migrate_v15_to_v16(connection: sqlite3.Connection) -> None:
|
|
1178
|
+
expected = {
|
|
1179
|
+
"finishing_library": ("role", "directory_json", "assets_json", "issues_json"),
|
|
1180
|
+
"finishing_runs": (
|
|
1181
|
+
"run_id",
|
|
1182
|
+
"request_id",
|
|
1183
|
+
"request_hash",
|
|
1184
|
+
"kind",
|
|
1185
|
+
"state",
|
|
1186
|
+
"phase",
|
|
1187
|
+
"progress",
|
|
1188
|
+
"context_json",
|
|
1189
|
+
"result_json",
|
|
1190
|
+
"usage_json",
|
|
1191
|
+
"error_code",
|
|
1192
|
+
"created_at",
|
|
1193
|
+
"completed_at",
|
|
1194
|
+
),
|
|
1195
|
+
"finishing_draft": ("slot", "revision", "context_json", "payload_json"),
|
|
1196
|
+
}
|
|
1197
|
+
observed = {
|
|
1198
|
+
row["name"]
|
|
1199
|
+
for row in connection.execute(
|
|
1200
|
+
"SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'finishing_%'"
|
|
1201
|
+
)
|
|
1202
|
+
}
|
|
1203
|
+
if observed and observed != set(expected):
|
|
1204
|
+
raise sqlite3.DatabaseError("incomplete finishing schema")
|
|
1205
|
+
for table in observed:
|
|
1206
|
+
if tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})")) != expected[table]:
|
|
1207
|
+
raise sqlite3.DatabaseError("unexpected finishing schema")
|
|
1208
|
+
connection.executescript(
|
|
1209
|
+
"BEGIN IMMEDIATE;\n" + ("" if observed else FINISHING_SCHEMA) + "\nPRAGMA user_version = 16;\nCOMMIT;"
|
|
1210
|
+
)
|
|
1211
|
+
|
|
1212
|
+
@staticmethod
|
|
1213
|
+
def _migrate_v14_to_v15(connection: sqlite3.Connection) -> None:
|
|
1214
|
+
"""Allow previews to reference an immutable AI edit revision.
|
|
1215
|
+
|
|
1216
|
+
Existing rows and the current-render pointer are copied exactly. The
|
|
1217
|
+
referenced payload remains integrity-checked by EditAgentRepository
|
|
1218
|
+
before a render can start.
|
|
1219
|
+
"""
|
|
1220
|
+
|
|
1221
|
+
columns = tuple(row["name"] for row in connection.execute("PRAGMA table_info(preview_renders)"))
|
|
1222
|
+
expected = (
|
|
1223
|
+
"render_id",
|
|
1224
|
+
"project_id",
|
|
1225
|
+
"timeline_id",
|
|
1226
|
+
"request_id",
|
|
1227
|
+
"state",
|
|
1228
|
+
"progress",
|
|
1229
|
+
"output_relative_path",
|
|
1230
|
+
"output_size_bytes",
|
|
1231
|
+
"error_code",
|
|
1232
|
+
"created_at",
|
|
1233
|
+
"started_at",
|
|
1234
|
+
"completed_at",
|
|
1235
|
+
)
|
|
1236
|
+
if columns != expected:
|
|
1237
|
+
raise sqlite3.DatabaseError("unexpected preview render schema")
|
|
1238
|
+
current = connection.execute("SELECT render_id FROM current_preview_render WHERE slot=1").fetchone()
|
|
1239
|
+
connection.execute("PRAGMA foreign_keys=OFF")
|
|
1240
|
+
try:
|
|
1241
|
+
connection.executescript(
|
|
1242
|
+
"BEGIN IMMEDIATE;\n"
|
|
1243
|
+
"DROP TABLE current_preview_render;\n"
|
|
1244
|
+
"DROP INDEX preview_renders_project_created;\n"
|
|
1245
|
+
"ALTER TABLE preview_renders RENAME TO preview_renders_v14;\n"
|
|
1246
|
+
+ PREVIEW_SCHEMA
|
|
1247
|
+
+ "\nINSERT INTO preview_renders SELECT * FROM preview_renders_v14;\n"
|
|
1248
|
+
"DROP TABLE preview_renders_v14;\n"
|
|
1249
|
+
)
|
|
1250
|
+
if current is not None:
|
|
1251
|
+
connection.execute(
|
|
1252
|
+
"INSERT INTO current_preview_render(slot,render_id) VALUES(1,?)",
|
|
1253
|
+
(current["render_id"],),
|
|
1254
|
+
)
|
|
1255
|
+
connection.execute("PRAGMA user_version=15")
|
|
1256
|
+
connection.commit()
|
|
1257
|
+
except Exception:
|
|
1258
|
+
connection.rollback()
|
|
1259
|
+
raise
|
|
1260
|
+
finally:
|
|
1261
|
+
connection.execute("PRAGMA foreign_keys=ON")
|
|
1262
|
+
|
|
1263
|
+
@staticmethod
|
|
1264
|
+
def _migrate_v2_to_v3(connection: sqlite3.Connection) -> None:
|
|
1265
|
+
try:
|
|
1266
|
+
connection.executescript("BEGIN IMMEDIATE;\n" + _ANALYSIS_SCHEMA + "\nPRAGMA user_version = 4;\nCOMMIT;")
|
|
1267
|
+
except sqlite3.Error:
|
|
1268
|
+
connection.rollback()
|
|
1269
|
+
raise
|
|
1270
|
+
|
|
1271
|
+
@staticmethod
|
|
1272
|
+
def _migrate_v3_to_v4(connection: sqlite3.Connection) -> None:
|
|
1273
|
+
"""Upgrade the unreleased v3 analysis skeleton without losing its rows."""
|
|
1274
|
+
try:
|
|
1275
|
+
connection.executescript(
|
|
1276
|
+
"""
|
|
1277
|
+
BEGIN IMMEDIATE;
|
|
1278
|
+
ALTER TABLE preparation_runs ADD COLUMN project_revision INTEGER;
|
|
1279
|
+
ALTER TABLE preparation_runs ADD COLUMN scope_id TEXT;
|
|
1280
|
+
ALTER TABLE preparation_runs ADD COLUMN operation_id TEXT;
|
|
1281
|
+
ALTER TABLE preparation_runs ADD COLUMN attempt_id TEXT;
|
|
1282
|
+
ALTER TABLE preparation_runs ADD COLUMN attempt_number INTEGER DEFAULT 1;
|
|
1283
|
+
UPDATE preparation_runs SET
|
|
1284
|
+
project_revision = COALESCE(
|
|
1285
|
+
(SELECT project_revision FROM inventory_runs
|
|
1286
|
+
WHERE inventory_runs.run_id = preparation_runs.inventory_run_id),
|
|
1287
|
+
1
|
|
1288
|
+
),
|
|
1289
|
+
scope_id = 'scope_' || substr(run_id, 6, 32),
|
|
1290
|
+
operation_id = 'op_' || substr(run_id, 6, 32),
|
|
1291
|
+
attempt_id = 'att_' || substr(run_id, 6, 32),
|
|
1292
|
+
attempt_number = 1;
|
|
1293
|
+
CREATE UNIQUE INDEX preparation_runs_operation
|
|
1294
|
+
ON preparation_runs(operation_id);
|
|
1295
|
+
CREATE UNIQUE INDEX preparation_runs_attempt
|
|
1296
|
+
ON preparation_runs(attempt_id);
|
|
1297
|
+
|
|
1298
|
+
CREATE TABLE preparation_items_v4 (
|
|
1299
|
+
run_id TEXT NOT NULL REFERENCES preparation_runs(run_id)
|
|
1300
|
+
ON DELETE CASCADE,
|
|
1301
|
+
version_id TEXT NOT NULL REFERENCES asset_versions(version_id),
|
|
1302
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= -1),
|
|
1303
|
+
status TEXT NOT NULL CHECK (
|
|
1304
|
+
status IN ('pending', 'prepared', 'transcribed', 'no_audio',
|
|
1305
|
+
'no_speech', 'failed')
|
|
1306
|
+
),
|
|
1307
|
+
error_code TEXT,
|
|
1308
|
+
checkpoint_json TEXT,
|
|
1309
|
+
audio_artifact_id TEXT REFERENCES artifacts(artifact_id),
|
|
1310
|
+
transcript_revision_id TEXT
|
|
1311
|
+
REFERENCES transcription_revisions(revision_id),
|
|
1312
|
+
PRIMARY KEY(run_id, version_id, stream_index)
|
|
1313
|
+
);
|
|
1314
|
+
INSERT INTO preparation_items_v4
|
|
1315
|
+
(run_id, version_id, stream_index, status, error_code, checkpoint_json)
|
|
1316
|
+
SELECT run_id, version_id, COALESCE(stream_index, -1), status,
|
|
1317
|
+
error_code, checkpoint_json
|
|
1318
|
+
FROM preparation_items;
|
|
1319
|
+
DROP TABLE preparation_items;
|
|
1320
|
+
ALTER TABLE preparation_items_v4 RENAME TO preparation_items;
|
|
1321
|
+
|
|
1322
|
+
CREATE TABLE preparation_chunks (
|
|
1323
|
+
run_id TEXT NOT NULL,
|
|
1324
|
+
version_id TEXT NOT NULL,
|
|
1325
|
+
stream_index INTEGER NOT NULL CHECK (stream_index >= 0),
|
|
1326
|
+
ordinal INTEGER NOT NULL CHECK (ordinal >= 0),
|
|
1327
|
+
start_sample INTEGER NOT NULL CHECK (start_sample >= 0),
|
|
1328
|
+
end_sample INTEGER NOT NULL CHECK (end_sample > start_sample),
|
|
1329
|
+
source_span_json TEXT NOT NULL,
|
|
1330
|
+
status TEXT NOT NULL CHECK (
|
|
1331
|
+
status IN ('pending', 'transcribed', 'no_speech')
|
|
1332
|
+
),
|
|
1333
|
+
transcript_artifact_id TEXT REFERENCES artifacts(artifact_id),
|
|
1334
|
+
result_json TEXT,
|
|
1335
|
+
PRIMARY KEY(run_id, version_id, stream_index, ordinal),
|
|
1336
|
+
FOREIGN KEY(run_id, version_id, stream_index)
|
|
1337
|
+
REFERENCES preparation_items(run_id, version_id, stream_index)
|
|
1338
|
+
ON DELETE CASCADE
|
|
1339
|
+
);
|
|
1340
|
+
CREATE INDEX preparation_items_run_status
|
|
1341
|
+
ON preparation_items(run_id, status, version_id);
|
|
1342
|
+
CREATE INDEX preparation_chunks_run_status
|
|
1343
|
+
ON preparation_chunks(
|
|
1344
|
+
run_id, status, version_id, stream_index, ordinal
|
|
1345
|
+
);
|
|
1346
|
+
PRAGMA user_version = 4;
|
|
1347
|
+
COMMIT;
|
|
1348
|
+
"""
|
|
1349
|
+
)
|
|
1350
|
+
except sqlite3.Error:
|
|
1351
|
+
connection.rollback()
|
|
1352
|
+
raise
|
|
1353
|
+
|
|
1354
|
+
@staticmethod
|
|
1355
|
+
def _migrate_v4_to_v5(connection: sqlite3.Connection) -> None:
|
|
1356
|
+
"""Keep old transcripts while making their unverified quality explicit."""
|
|
1357
|
+
try:
|
|
1358
|
+
columns = {row[1] for row in connection.execute("PRAGMA table_info(preparation_items)").fetchall()}
|
|
1359
|
+
add_review_column = (
|
|
1360
|
+
""
|
|
1361
|
+
if "review_required" in columns
|
|
1362
|
+
else "ALTER TABLE preparation_items ADD COLUMN review_required INTEGER "
|
|
1363
|
+
"NOT NULL DEFAULT 0 CHECK (review_required IN (0, 1));"
|
|
1364
|
+
)
|
|
1365
|
+
connection.executescript(
|
|
1366
|
+
"BEGIN IMMEDIATE;\n"
|
|
1367
|
+
+ add_review_column
|
|
1368
|
+
+ """
|
|
1369
|
+
UPDATE preparation_items
|
|
1370
|
+
SET review_required = 1,
|
|
1371
|
+
error_code = 'transcript_quality_unverified'
|
|
1372
|
+
WHERE status = 'transcribed'
|
|
1373
|
+
AND transcript_revision_id IN (
|
|
1374
|
+
SELECT revision_id FROM transcription_revisions
|
|
1375
|
+
WHERE recipe_id = 'asr.mlx-whisper.v1'
|
|
1376
|
+
);
|
|
1377
|
+
UPDATE transcription_revisions
|
|
1378
|
+
SET status = 'needs_review'
|
|
1379
|
+
WHERE status = 'transcribed'
|
|
1380
|
+
AND recipe_id = 'asr.mlx-whisper.v1';
|
|
1381
|
+
UPDATE preparation_runs
|
|
1382
|
+
SET prepared_count = (
|
|
1383
|
+
SELECT COUNT(*) FROM preparation_items
|
|
1384
|
+
WHERE preparation_items.run_id = preparation_runs.run_id
|
|
1385
|
+
AND status IN ('prepared', 'transcribed', 'no_speech')
|
|
1386
|
+
),
|
|
1387
|
+
transcribed_count = (
|
|
1388
|
+
SELECT COUNT(*) FROM preparation_items
|
|
1389
|
+
WHERE preparation_items.run_id = preparation_runs.run_id
|
|
1390
|
+
AND status = 'transcribed' AND review_required = 0
|
|
1391
|
+
),
|
|
1392
|
+
issue_count = (
|
|
1393
|
+
SELECT COUNT(*) FROM preparation_items
|
|
1394
|
+
WHERE preparation_items.run_id = preparation_runs.run_id
|
|
1395
|
+
AND (status = 'failed' OR review_required = 1)
|
|
1396
|
+
);
|
|
1397
|
+
PRAGMA user_version = 5;
|
|
1398
|
+
COMMIT;
|
|
1399
|
+
"""
|
|
1400
|
+
)
|
|
1401
|
+
except sqlite3.Error:
|
|
1402
|
+
connection.rollback()
|
|
1403
|
+
raise
|
|
1404
|
+
|
|
1405
|
+
@staticmethod
|
|
1406
|
+
def _configure(connection: sqlite3.Connection) -> None:
|
|
1407
|
+
connection.execute("PRAGMA foreign_keys = ON")
|
|
1408
|
+
connection.execute("PRAGMA journal_mode = WAL")
|
|
1409
|
+
connection.execute("PRAGMA synchronous = FULL")
|
|
1410
|
+
connection.execute("PRAGMA busy_timeout = 5000")
|
|
1411
|
+
|
|
1412
|
+
@staticmethod
|
|
1413
|
+
def _read_snapshot(connection: sqlite3.Connection) -> ProjectSnapshot:
|
|
1414
|
+
row = connection.execute(
|
|
1415
|
+
"SELECT project_id, name, brief, stage, revision, created_at, updated_at FROM project LIMIT 1"
|
|
1416
|
+
).fetchone()
|
|
1417
|
+
if row is None:
|
|
1418
|
+
raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
|
|
1419
|
+
directories = connection.execute(
|
|
1420
|
+
"SELECT role, canonical_path, display_path, display_name, device, inode, saved_at "
|
|
1421
|
+
"FROM project_directories ORDER BY role"
|
|
1422
|
+
).fetchall()
|
|
1423
|
+
return ProjectSnapshot(
|
|
1424
|
+
project_id=row["project_id"],
|
|
1425
|
+
name=row["name"],
|
|
1426
|
+
brief=row["brief"],
|
|
1427
|
+
stage=row["stage"],
|
|
1428
|
+
revision=row["revision"],
|
|
1429
|
+
created_at=row["created_at"],
|
|
1430
|
+
updated_at=row["updated_at"],
|
|
1431
|
+
directories=tuple(
|
|
1432
|
+
DirectoryReference(
|
|
1433
|
+
role=DirectoryRole(item["role"]),
|
|
1434
|
+
canonical_path=item["canonical_path"],
|
|
1435
|
+
display_path=item["display_path"],
|
|
1436
|
+
display_name=item["display_name"],
|
|
1437
|
+
device=item["device"],
|
|
1438
|
+
inode=item["inode"],
|
|
1439
|
+
saved_at=item["saved_at"],
|
|
1440
|
+
)
|
|
1441
|
+
for item in directories
|
|
1442
|
+
),
|
|
1443
|
+
)
|
|
1444
|
+
|
|
1445
|
+
def _project_dir(self, project_id: str) -> Path:
|
|
1446
|
+
validate_project_id(project_id)
|
|
1447
|
+
path = self.root / project_id
|
|
1448
|
+
if path.parent != self.root:
|
|
1449
|
+
raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
|
|
1450
|
+
return path
|
|
1451
|
+
|
|
1452
|
+
@staticmethod
|
|
1453
|
+
def _remove_staging(staging: Path) -> None:
|
|
1454
|
+
for name in ("project.sqlite3-wal", "project.sqlite3-shm", "project.sqlite3"):
|
|
1455
|
+
candidate = staging / name
|
|
1456
|
+
if candidate.exists() and not candidate.is_symlink():
|
|
1457
|
+
candidate.unlink()
|
|
1458
|
+
staging.rmdir()
|