@clipen/clipen-cli 0.0.0-stage → 1.0.0

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