@clipen/clipen-cli 1.0.0 → 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.
Files changed (127) hide show
  1. package/README.md +60 -50
  2. package/package.json +7 -4
  3. package/pyproject.toml +18 -2
  4. package/requirements/dev.txt +2 -0
  5. package/src/clipen/__init__.py +1 -1
  6. package/src/clipen/analysis/__init__.py +7 -7
  7. package/src/clipen/analysis/artifacts.py +4 -10
  8. package/src/clipen/analysis/audio.py +10 -8
  9. package/src/clipen/analysis/evidence_service.py +345 -167
  10. package/src/clipen/analysis/image_similarity.py +5 -14
  11. package/src/clipen/analysis/keyframes.py +5 -17
  12. package/src/clipen/analysis/models.py +5 -7
  13. package/src/clipen/analysis/qwen_worker.py +19 -54
  14. package/src/clipen/analysis/resources.py +2 -1
  15. package/src/clipen/analysis/runtime.py +1 -3
  16. package/src/clipen/analysis/service.py +16 -48
  17. package/src/clipen/analysis/setup.py +11 -25
  18. package/src/clipen/analysis/setup_cli.py +5 -15
  19. package/src/clipen/analysis/storage.py +96 -278
  20. package/src/clipen/analysis/transcription.py +40 -82
  21. package/src/clipen/analysis/visual.py +109 -48
  22. package/src/clipen/annotations/__init__.py +5 -2
  23. package/src/clipen/annotations/models.py +1 -1
  24. package/src/clipen/annotations/storage.py +132 -84
  25. package/src/clipen/annotations/suggestions.py +3 -8
  26. package/src/clipen/asr_release.py +4 -11
  27. package/src/clipen/bootstrap.py +65 -54
  28. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  29. package/src/clipen/cli.py +2 -2
  30. package/src/clipen/controller/app.py +401 -214
  31. package/src/clipen/controller/server.py +28 -38
  32. package/src/clipen/domain/__init__.py +1 -1
  33. package/src/clipen/domain/media_time.py +3 -10
  34. package/src/clipen/domain/timeline.py +45 -47
  35. package/src/clipen/domain/validation.py +0 -1
  36. package/src/clipen/editing/__init__.py +1 -1
  37. package/src/clipen/editing/agent_models.py +4 -11
  38. package/src/clipen/editing/agent_repository.py +391 -170
  39. package/src/clipen/editing/agent_tools.py +180 -99
  40. package/src/clipen/editing/alignment.py +92 -52
  41. package/src/clipen/editing/alignment_setup.py +118 -70
  42. package/src/clipen/editing/alignment_worker.py +11 -9
  43. package/src/clipen/editing/change_report.py +95 -38
  44. package/src/clipen/editing/compiler.py +0 -1
  45. package/src/clipen/editing/component_looks.py +58 -34
  46. package/src/clipen/editing/component_review.py +34 -38
  47. package/src/clipen/editing/coordinator.py +213 -90
  48. package/src/clipen/editing/editorial_review.py +217 -95
  49. package/src/clipen/editing/evidence_jobs.py +457 -200
  50. package/src/clipen/editing/history_changes.py +129 -68
  51. package/src/clipen/editing/music_choices.py +8 -5
  52. package/src/clipen/editing/production_catalog.py +573 -136
  53. package/src/clipen/editing/production_limits.py +43 -17
  54. package/src/clipen/editing/production_media.py +376 -167
  55. package/src/clipen/editing/production_preview.py +322 -129
  56. package/src/clipen/editing/production_progress.py +164 -69
  57. package/src/clipen/editing/production_requirements.py +106 -39
  58. package/src/clipen/editing/production_tools.py +1064 -462
  59. package/src/clipen/editing/program_audio.py +211 -81
  60. package/src/clipen/editing/program_direction.py +59 -25
  61. package/src/clipen/editing/program_story.py +83 -45
  62. package/src/clipen/editing/program_subtitles.py +194 -96
  63. package/src/clipen/editing/programme_review.py +98 -50
  64. package/src/clipen/editing/prompt_history.py +64 -27
  65. package/src/clipen/editing/recut.py +65 -25
  66. package/src/clipen/editing/refinement_references.py +176 -86
  67. package/src/clipen/editing/resolve_export.py +449 -218
  68. package/src/clipen/editing/resolve_titles.py +162 -105
  69. package/src/clipen/editing/skill_tools.py +530 -154
  70. package/src/clipen/editing/source_dialogue.py +177 -67
  71. package/src/clipen/editing/speech_coverage.py +42 -22
  72. package/src/clipen/editing/speech_quality.py +6 -1
  73. package/src/clipen/editing/tool_receipts.py +78 -32
  74. package/src/clipen/editing/versions.py +122 -64
  75. package/src/clipen/editing/visual_preview.py +157 -61
  76. package/src/clipen/editing/workbench.py +104 -42
  77. package/src/clipen/finishing/audio.py +69 -30
  78. package/src/clipen/finishing/catalog.py +176 -93
  79. package/src/clipen/finishing/models.py +1 -1
  80. package/src/clipen/finishing/renderer.py +33 -14
  81. package/src/clipen/mcp_editing/__main__.py +3 -1
  82. package/src/clipen/mcp_editing/server.py +77 -34
  83. package/src/clipen/media/__init__.py +3 -3
  84. package/src/clipen/media/discovery.py +7 -20
  85. package/src/clipen/media/models.py +7 -18
  86. package/src/clipen/media/preview.py +14 -24
  87. package/src/clipen/media/probe.py +16 -44
  88. package/src/clipen/media/service.py +6 -19
  89. package/src/clipen/media/storage.py +33 -81
  90. package/src/clipen/music_vocabulary.py +33 -4
  91. package/src/clipen/power.py +8 -3
  92. package/src/clipen/projects/__init__.py +1 -1
  93. package/src/clipen/projects/deletion.py +19 -32
  94. package/src/clipen/projects/finishing_schema.py +3 -1
  95. package/src/clipen/projects/models.py +2 -5
  96. package/src/clipen/projects/picker.py +13 -37
  97. package/src/clipen/projects/service.py +8 -24
  98. package/src/clipen/projects/storage.py +226 -246
  99. package/src/clipen/provider_registry.py +4 -2
  100. package/src/clipen/providers/account.py +86 -35
  101. package/src/clipen/providers/claude.py +59 -25
  102. package/src/clipen/providers/claude_editing.py +14 -7
  103. package/src/clipen/providers/codex.py +73 -118
  104. package/src/clipen/providers/codex_editing.py +2 -2
  105. package/src/clipen/providers/editing_agent.py +19 -17
  106. package/src/clipen/providers/recovery.py +7 -8
  107. package/src/clipen/rendering/cover.py +18 -5
  108. package/src/clipen/rendering/custom_components.py +167 -79
  109. package/src/clipen/rendering/custom_render.py +62 -41
  110. package/src/clipen/rendering/production_effects.py +77 -45
  111. package/src/clipen/rendering/program_components.py +134 -73
  112. package/src/clipen/rendering/program_creator.py +432 -277
  113. package/src/clipen/rendering/program_identities.py +277 -182
  114. package/src/clipen/rendering/program_motion.py +140 -95
  115. package/src/clipen/rendering/program_studio.py +175 -116
  116. package/src/clipen/rendering/program_styles.py +231 -145
  117. package/src/clipen/rendering/program_subtitles.py +71 -34
  118. package/src/clipen/rendering/renderer.py +150 -121
  119. package/src/clipen/rendering/storage.py +9 -22
  120. package/src/clipen/rendering/titles.py +193 -86
  121. package/src/clipen/skills/__init__.py +1 -0
  122. package/src/clipen/skills/catalog.py +151 -55
  123. package/src/clipen/skills/library.py +13 -7
  124. package/src/clipen/skills/package.py +46 -23
  125. package/src/clipen/skills/visual_styles.py +29 -18
  126. package/src/clipen/workspace.py +15 -44
  127. package/src/clipen/planning/__init__.py +0 -9
@@ -2,20 +2,25 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from contextlib import contextmanager
6
- from dataclasses import replace
7
- from datetime import datetime, timezone
8
5
  import hashlib
9
6
  import json
10
7
  import os
11
- from pathlib import Path
12
8
  import re
13
9
  import sqlite3
14
10
  import uuid
15
- from typing import Iterator, Mapping, Any
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
16
 
17
17
  from clipen.filesystem import restrict_permissions
18
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
19
24
  from .models import (
20
25
  DirectoryReference,
21
26
  DirectoryRole,
@@ -27,15 +32,9 @@ from .models import (
27
32
  validate_request_id,
28
33
  validate_revision,
29
34
  )
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
35
  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
-
36
+ from .timeline_schema import TIMELINE_SCHEMA
37
+ from .validation_schema import VALIDATION_WORKFLOW_SCHEMA
39
38
 
40
39
  PROJECT_SCHEMA_VERSION = 19
41
40
  # Tables of the retired confirmed-plan flow, children before parents. Version 19
@@ -301,15 +300,13 @@ class ProjectRepository:
301
300
  normalized_request = validate_request_id(request_id)
302
301
  normalized_name = validate_name(name)
303
302
  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]
303
+ project_id = (
304
+ "prj_" + hashlib.sha256(f"clipen:create-project:v1:{normalized_request}".encode("utf-8")).hexdigest()[:32]
305
+ )
307
306
  project_dir = self._project_dir(project_id)
308
307
 
309
308
  if project_dir.exists():
310
- replay = self.replay_receipt(
311
- project_id, normalized_request, "create_project", command_hash
312
- )
309
+ replay = self.replay_receipt(project_id, normalized_request, "create_project", command_hash)
313
310
  if replay is None:
314
311
  raise ProjectError(
315
312
  "request_conflict",
@@ -332,9 +329,7 @@ class ProjectRepository:
332
329
  staging.rename(project_dir)
333
330
  except FileExistsError:
334
331
  self._remove_staging(staging)
335
- replay = self.replay_receipt(
336
- project_id, normalized_request, "create_project", command_hash
337
- )
332
+ replay = self.replay_receipt(project_id, normalized_request, "create_project", command_hash)
338
333
  if replay is None:
339
334
  raise ProjectError(
340
335
  "request_conflict",
@@ -353,28 +348,24 @@ class ProjectRepository:
353
348
  try:
354
349
  entries = tuple(self.root.iterdir())
355
350
  except OSError as error:
356
- raise ProjectError(
357
- "storage_unavailable", "Clipen 無法讀取作品列表。", status_code=500
358
- ) from error
351
+ raise ProjectError("storage_unavailable", "Clipen 無法讀取作品列表。", status_code=500) from error
359
352
  for entry in entries:
360
353
  if _PROJECT_DIRECTORY.fullmatch(entry.name) is None:
361
354
  continue
362
355
  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)
356
+ raise ProjectError("storage_unsafe", "Clipen 偵測到不安全的作品資料。", status_code=500)
357
+ project = self.get_project(entry.name)
367
358
  # Activity is derived so editing never changes the metadata revision
368
359
  # or invalidates the user's source grants and inventory.
369
360
  with self.connect(entry.name) as db:
370
- activity=db.execute("""SELECT MAX(at) FROM (
361
+ activity = db.execute("""SELECT MAX(at) FROM (
371
362
  SELECT MAX(created_at) AS at FROM edit_agent_events
372
363
  UNION ALL SELECT MAX(created_at) FROM edit_agent_revisions
373
364
  UNION ALL SELECT MAX(created_at) FROM operation_events
374
365
  UNION ALL SELECT MAX(created_at) FROM inventory_runs
375
366
  UNION ALL SELECT MAX(completed_at) FROM preview_renders
376
367
  )""").fetchone()[0]
377
- projects.append(replace(project,last_activity_at=max(project.updated_at,activity or project.updated_at)))
368
+ projects.append(replace(project, last_activity_at=max(project.updated_at, activity or project.updated_at)))
378
369
  projects.sort(key=lambda project: project.last_activity_at or project.updated_at, reverse=True)
379
370
  return tuple(projects)
380
371
 
@@ -383,9 +374,7 @@ class ProjectRepository:
383
374
  with self.connect(project_id) as connection:
384
375
  snapshot = self._read_snapshot(connection)
385
376
  if snapshot.project_id != project_id:
386
- raise ProjectError(
387
- "storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500
388
- )
377
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
389
378
  return snapshot
390
379
 
391
380
  def replay_receipt(
@@ -399,8 +388,7 @@ class ProjectRepository:
399
388
  validate_request_id(request_id)
400
389
  with self.connect(project_id) as connection:
401
390
  row = connection.execute(
402
- "SELECT command_type, request_hash, response_json FROM command_receipts "
403
- "WHERE request_id = ?",
391
+ "SELECT command_type, request_hash, response_json FROM command_receipts WHERE request_id = ?",
404
392
  (request_id,),
405
393
  ).fetchone()
406
394
  if row is None:
@@ -417,9 +405,7 @@ class ProjectRepository:
417
405
  raise ValueError("receipt response must be an object")
418
406
  return ProjectSnapshot.from_storage(payload)
419
407
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
420
- raise ProjectError(
421
- "storage_corrupt", "Clipen 無法讀取作品操作紀錄。", status_code=500
422
- ) from error
408
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品操作紀錄。", status_code=500) from error
423
409
 
424
410
  def update_details(
425
411
  self,
@@ -445,8 +431,7 @@ class ProjectRepository:
445
431
  command_digest(command),
446
432
  revision,
447
433
  lambda connection, now: connection.execute(
448
- "UPDATE project SET name = ?, brief = ?, revision = revision + 1, "
449
- "updated_at = ? WHERE project_id = ?",
434
+ "UPDATE project SET name = ?, brief = ?, revision = revision + 1, updated_at = ? WHERE project_id = ?",
450
435
  (normalized_name, normalized_brief, now, project_id),
451
436
  ),
452
437
  )
@@ -497,14 +482,10 @@ class ProjectRepository:
497
482
  ) -> ProjectSnapshot:
498
483
  normalized_request = validate_request_id(request_id)
499
484
  revision = validate_revision(expected_revision)
500
- command_hash = command_digest(
501
- {"expected_revision": revision, "role": role.value}
502
- )
485
+ command_hash = command_digest({"expected_revision": revision, "role": role.value})
503
486
 
504
487
  def mutation(connection: sqlite3.Connection, _: str) -> None:
505
- connection.execute(
506
- "DELETE FROM project_directories WHERE role = ?", (role.value,)
507
- )
488
+ connection.execute("DELETE FROM project_directories WHERE role = ?", (role.value,))
508
489
  connection.execute("DELETE FROM current_inventory")
509
490
 
510
491
  return self._mutate(
@@ -546,15 +527,11 @@ class ProjectRepository:
546
527
  try:
547
528
  connection.execute("BEGIN IMMEDIATE")
548
529
  receipt = connection.execute(
549
- "SELECT command_type, request_hash, response_json FROM command_receipts "
550
- "WHERE request_id = ?",
530
+ "SELECT command_type, request_hash, response_json FROM command_receipts WHERE request_id = ?",
551
531
  (request_id,),
552
532
  ).fetchone()
553
533
  if receipt is not None:
554
- if (
555
- receipt["command_type"] != command_type
556
- or receipt["request_hash"] != request_hash
557
- ):
534
+ if receipt["command_type"] != command_type or receipt["request_hash"] != request_hash:
558
535
  raise ProjectError(
559
536
  "request_reused",
560
537
  "這次操作的識別資訊已用於不同內容。",
@@ -579,14 +556,11 @@ class ProjectRepository:
579
556
  mutation(connection, now)
580
557
  if command_type != "update_details":
581
558
  connection.execute(
582
- "UPDATE project SET revision = revision + 1, updated_at = ? "
583
- "WHERE project_id = ?",
559
+ "UPDATE project SET revision = revision + 1, updated_at = ? WHERE project_id = ?",
584
560
  (now, project_id),
585
561
  )
586
562
  snapshot = self._read_snapshot(connection)
587
- response_json = json.dumps(
588
- snapshot.to_storage(), ensure_ascii=False, separators=(",", ":")
589
- )
563
+ response_json = json.dumps(snapshot.to_storage(), ensure_ascii=False, separators=(",", ":"))
590
564
  connection.execute(
591
565
  "INSERT INTO command_receipts "
592
566
  "(request_id, command_type, request_hash, response_json, created_at) "
@@ -600,14 +574,10 @@ class ProjectRepository:
600
574
  raise
601
575
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
602
576
  connection.rollback()
603
- raise ProjectError(
604
- "storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500
605
- ) from error
577
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500) from error
606
578
  except sqlite3.Error as error:
607
579
  connection.rollback()
608
- raise ProjectError(
609
- "storage_failed", "Clipen 無法保存作品。", status_code=500
610
- ) from error
580
+ raise ProjectError("storage_failed", "Clipen 無法保存作品。", status_code=500) from error
611
581
 
612
582
  def _initialize_project(
613
583
  self,
@@ -680,9 +650,7 @@ class ProjectRepository:
680
650
  (
681
651
  request_id,
682
652
  command_hash,
683
- json.dumps(
684
- snapshot.to_storage(), ensure_ascii=False, separators=(",", ":")
685
- ),
653
+ json.dumps(snapshot.to_storage(), ensure_ascii=False, separators=(",", ":")),
686
654
  now,
687
655
  ),
688
656
  )
@@ -702,9 +670,7 @@ class ProjectRepository:
702
670
  raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
703
671
  database = project_dir / "project.sqlite3"
704
672
  if database.is_symlink() or not database.is_file():
705
- raise ProjectError(
706
- "storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500
707
- )
673
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
708
674
  try:
709
675
  connection = sqlite3.connect(database, timeout=5, isolation_level=None)
710
676
  connection.row_factory = sqlite3.Row
@@ -723,11 +689,7 @@ class ProjectRepository:
723
689
  self._migrate_v4_to_v5(connection)
724
690
  version = 5
725
691
  if version == 5:
726
- connection.executescript(
727
- "BEGIN IMMEDIATE;\n"
728
- + EVIDENCE_SCHEMA
729
- + "\nPRAGMA user_version = 6;\nCOMMIT;"
730
- )
692
+ connection.executescript("BEGIN IMMEDIATE;\n" + EVIDENCE_SCHEMA + "\nPRAGMA user_version = 6;\nCOMMIT;")
731
693
  version = 6
732
694
  if version == 6:
733
695
  self._migrate_v6_to_v7(connection)
@@ -777,9 +739,7 @@ class ProjectRepository:
777
739
  )
778
740
  yield connection
779
741
  except sqlite3.Error as error:
780
- raise ProjectError(
781
- "storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500
782
- ) from error
742
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500) from error
783
743
  finally:
784
744
  if "connection" in locals():
785
745
  connection.close()
@@ -795,8 +755,7 @@ class ProjectRepository:
795
755
  try:
796
756
  prior_violations = {tuple(row) for row in connection.execute("PRAGMA foreign_key_check")}
797
757
  connection.executescript(
798
- "BEGIN IMMEDIATE;\n" + create
799
- + "INSERT INTO edit_agent_runs_v18 SELECT * FROM edit_agent_runs;\n"
758
+ "BEGIN IMMEDIATE;\n" + create + "INSERT INTO edit_agent_runs_v18 SELECT * FROM edit_agent_runs;\n"
800
759
  "DROP TABLE edit_agent_runs;\n"
801
760
  "ALTER TABLE edit_agent_runs_v18 RENAME TO edit_agent_runs;\n"
802
761
  "CREATE INDEX edit_agent_runs_project_created ON edit_agent_runs(project_id,created_at DESC);\n"
@@ -823,15 +782,12 @@ class ProjectRepository:
823
782
  """
824
783
 
825
784
  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
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
830
789
  ]
831
- archive = {
832
- table: [dict(row) for row in connection.execute(f"SELECT * FROM {table}")]
833
- for table in present
834
- }
790
+ archive = {table: [dict(row) for row in connection.execute(f"SELECT * FROM {table}")] for table in present}
835
791
  if any(archive.values()):
836
792
  target = project_dir / RETIRED_PLANNING_ARCHIVE
837
793
  if target.is_symlink():
@@ -860,11 +816,7 @@ class ProjectRepository:
860
816
  @staticmethod
861
817
  def _migrate_v1_to_v2(connection: sqlite3.Connection) -> None:
862
818
  try:
863
- connection.executescript(
864
- "BEGIN IMMEDIATE;\n"
865
- + _INVENTORY_SCHEMA
866
- + "\nPRAGMA user_version = 2;\nCOMMIT;"
867
- )
819
+ connection.executescript("BEGIN IMMEDIATE;\n" + _INVENTORY_SCHEMA + "\nPRAGMA user_version = 2;\nCOMMIT;")
868
820
  except sqlite3.Error:
869
821
  connection.rollback()
870
822
  raise
@@ -874,26 +826,17 @@ class ProjectRepository:
874
826
  """Finish an interrupted observation migration without deleting data."""
875
827
 
876
828
  existing = connection.execute(
877
- "SELECT sql FROM sqlite_master WHERE type = 'table' "
878
- "AND name = 'evidence_observations'"
829
+ "SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'evidence_observations'"
879
830
  ).fetchone()
880
831
  migration_sql = OBSERVATION_SCHEMA
881
832
  if existing is not None:
882
833
  observed_sql = existing["sql"]
883
834
  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
- )
835
+ observed = " ".join(observed_sql.rstrip(";\n ").split()) if isinstance(observed_sql, str) else ""
889
836
  if observed != expected:
890
837
  raise sqlite3.DatabaseError("unexpected evidence observation schema")
891
838
  migration_sql = ""
892
- connection.executescript(
893
- "BEGIN IMMEDIATE;\n"
894
- + migration_sql
895
- + "\nPRAGMA user_version = 7;\nCOMMIT;"
896
- )
839
+ connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 7;\nCOMMIT;")
897
840
 
898
841
  @staticmethod
899
842
  def _migrate_v7_to_v8(connection: sqlite3.Connection) -> None:
@@ -923,8 +866,7 @@ class ProjectRepository:
923
866
  observed = {
924
867
  row["name"]
925
868
  for row in connection.execute(
926
- "SELECT name FROM sqlite_master WHERE type = 'table' "
927
- "AND name IN (?, ?, ?)",
869
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
928
870
  tuple(expected_columns),
929
871
  )
930
872
  }
@@ -932,28 +874,16 @@ class ProjectRepository:
932
874
  raise sqlite3.DatabaseError("incomplete validation workflow schema")
933
875
  if observed:
934
876
  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
- )
877
+ columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
939
878
  if columns != expected:
940
879
  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
- }
880
+ indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
947
881
  if "timeline_validation_reports_project_created" not in indexes:
948
882
  raise sqlite3.DatabaseError("incomplete validation workflow indexes")
949
883
  migration_sql = ""
950
884
  else:
951
885
  migration_sql = VALIDATION_WORKFLOW_SCHEMA
952
- connection.executescript(
953
- "BEGIN IMMEDIATE;\n"
954
- + migration_sql
955
- + "\nPRAGMA user_version = 8;\nCOMMIT;"
956
- )
886
+ connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 8;\nCOMMIT;")
957
887
 
958
888
  @staticmethod
959
889
  def _migrate_v8_to_v9(connection: sqlite3.Connection) -> None:
@@ -967,21 +897,30 @@ class ProjectRepository:
967
897
 
968
898
  expected_columns = {
969
899
  "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",
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",
973
910
  ),
974
911
  "current_timeline": ("slot", "timeline_id"),
975
912
  "timeline_command_receipts": (
976
- "request_id", "command_type", "request_hash", "timeline_id",
913
+ "request_id",
914
+ "command_type",
915
+ "request_hash",
916
+ "timeline_id",
977
917
  "created_at",
978
918
  ),
979
919
  }
980
920
  observed = {
981
921
  row["name"]
982
922
  for row in connection.execute(
983
- "SELECT name FROM sqlite_master WHERE type = 'table' "
984
- "AND name IN (?, ?, ?)",
923
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
985
924
  tuple(expected_columns),
986
925
  )
987
926
  }
@@ -989,28 +928,16 @@ class ProjectRepository:
989
928
  raise sqlite3.DatabaseError("incomplete timeline schema")
990
929
  if observed:
991
930
  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
- )
931
+ columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
996
932
  if columns != expected:
997
933
  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
- }
934
+ indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
1004
935
  if "edit_timelines_project_created" not in indexes:
1005
936
  raise sqlite3.DatabaseError("incomplete timeline indexes")
1006
937
  migration_sql = ""
1007
938
  else:
1008
939
  migration_sql = TIMELINE_SCHEMA
1009
- connection.executescript(
1010
- "BEGIN IMMEDIATE;\n"
1011
- + migration_sql
1012
- + "\nPRAGMA user_version = 10;\nCOMMIT;"
1013
- )
940
+ connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 10;\nCOMMIT;")
1014
941
 
1015
942
  @staticmethod
1016
943
  def _migrate_v10_to_v11(connection: sqlite3.Connection) -> None:
@@ -1018,23 +945,37 @@ class ProjectRepository:
1018
945
 
1019
946
  expected_columns = {
1020
947
  "material_annotations": (
1021
- "version_id", "revision", "people_json", "location", "trip_day",
1022
- "day_part", "note", "usage", "updated_at",
948
+ "version_id",
949
+ "revision",
950
+ "people_json",
951
+ "location",
952
+ "trip_day",
953
+ "day_part",
954
+ "note",
955
+ "usage",
956
+ "updated_at",
1023
957
  ),
1024
958
  "transcript_annotations": (
1025
- "version_id", "stream_index", "source_revision_id", "revision",
1026
- "confirmed", "corrections_json", "updated_at",
959
+ "version_id",
960
+ "stream_index",
961
+ "source_revision_id",
962
+ "revision",
963
+ "confirmed",
964
+ "corrections_json",
965
+ "updated_at",
1027
966
  ),
1028
967
  "annotation_command_receipts": (
1029
- "request_id", "command_type", "request_hash", "response_json",
968
+ "request_id",
969
+ "command_type",
970
+ "request_hash",
971
+ "response_json",
1030
972
  "created_at",
1031
973
  ),
1032
974
  }
1033
975
  observed = {
1034
976
  row["name"]
1035
977
  for row in connection.execute(
1036
- "SELECT name FROM sqlite_master WHERE type = 'table' "
1037
- "AND name IN (?, ?, ?)",
978
+ "SELECT name FROM sqlite_master WHERE type = 'table' AND name IN (?, ?, ?)",
1038
979
  tuple(expected_columns),
1039
980
  )
1040
981
  }
@@ -1042,58 +983,76 @@ class ProjectRepository:
1042
983
  raise sqlite3.DatabaseError("incomplete annotation schema")
1043
984
  if observed:
1044
985
  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
- )
986
+ columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
1049
987
  allowed = {expected}
1050
988
  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
- ))
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
+ )
1059
1013
  if columns not in allowed:
1060
1014
  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
- }
1015
+ indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type = 'index'")}
1067
1016
  if "material_annotations_updated" not in indexes:
1068
1017
  raise sqlite3.DatabaseError("incomplete annotation indexes")
1069
1018
  migration_sql = ""
1070
1019
  else:
1071
1020
  migration_sql = ANNOTATION_SCHEMA
1072
- connection.executescript(
1073
- "BEGIN IMMEDIATE;\n"
1074
- + migration_sql
1075
- + "\nPRAGMA user_version = 11;\nCOMMIT;"
1076
- )
1021
+ connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 11;\nCOMMIT;")
1077
1022
 
1078
1023
  @staticmethod
1079
1024
  def _migrate_v11_to_v12(connection: sqlite3.Connection) -> None:
1080
1025
  """Add reversible transcript removal without deleting ASR evidence."""
1081
1026
 
1082
- columns = tuple(
1083
- row["name"]
1084
- for row in connection.execute("PRAGMA table_info(transcript_annotations)")
1085
- )
1027
+ columns = tuple(row["name"] for row in connection.execute("PRAGMA table_info(transcript_annotations)"))
1086
1028
  previous = (
1087
- "version_id", "stream_index", "source_revision_id", "revision",
1088
- "confirmed", "corrections_json", "updated_at",
1029
+ "version_id",
1030
+ "stream_index",
1031
+ "source_revision_id",
1032
+ "revision",
1033
+ "confirmed",
1034
+ "corrections_json",
1035
+ "updated_at",
1089
1036
  )
1090
1037
  current = (
1091
- "version_id", "stream_index", "source_revision_id", "revision",
1092
- "confirmed", "discarded", "corrections_json", "updated_at",
1038
+ "version_id",
1039
+ "stream_index",
1040
+ "source_revision_id",
1041
+ "revision",
1042
+ "confirmed",
1043
+ "discarded",
1044
+ "corrections_json",
1045
+ "updated_at",
1093
1046
  )
1094
1047
  migrated = (
1095
- "version_id", "stream_index", "source_revision_id", "revision",
1096
- "confirmed", "corrections_json", "updated_at", "discarded",
1048
+ "version_id",
1049
+ "stream_index",
1050
+ "source_revision_id",
1051
+ "revision",
1052
+ "confirmed",
1053
+ "corrections_json",
1054
+ "updated_at",
1055
+ "discarded",
1097
1056
  )
1098
1057
  if columns == previous:
1099
1058
  migration_sql = (
@@ -1104,11 +1063,7 @@ class ProjectRepository:
1104
1063
  migration_sql = ""
1105
1064
  else:
1106
1065
  raise sqlite3.DatabaseError("unexpected transcript annotation schema")
1107
- connection.executescript(
1108
- "BEGIN IMMEDIATE;\n"
1109
- + migration_sql
1110
- + "\nPRAGMA user_version = 12;\nCOMMIT;"
1111
- )
1066
+ connection.executescript("BEGIN IMMEDIATE;\n" + migration_sql + "\nPRAGMA user_version = 12;\nCOMMIT;")
1112
1067
 
1113
1068
  @staticmethod
1114
1069
  def _migrate_v12_to_v13(connection: sqlite3.Connection) -> None:
@@ -1124,9 +1079,7 @@ class ProjectRepository:
1124
1079
  if observed and observed != {"preview_renders", "current_preview_render"}:
1125
1080
  raise sqlite3.DatabaseError("incomplete preview render schema")
1126
1081
  connection.executescript(
1127
- "BEGIN IMMEDIATE;\n"
1128
- + ("" if observed else PREVIEW_SCHEMA)
1129
- + "\nPRAGMA user_version = 13;\nCOMMIT;"
1082
+ "BEGIN IMMEDIATE;\n" + ("" if observed else PREVIEW_SCHEMA) + "\nPRAGMA user_version = 13;\nCOMMIT;"
1130
1083
  )
1131
1084
 
1132
1085
  @staticmethod
@@ -1135,22 +1088,49 @@ class ProjectRepository:
1135
1088
 
1136
1089
  expected_columns = {
1137
1090
  "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",
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",
1143
1110
  ),
1144
1111
  "edit_agent_revisions": (
1145
- "revision_id", "run_id", "ordinal", "parent_revision_id",
1146
- "payload_digest", "payload_json", "summary", "created_at",
1112
+ "revision_id",
1113
+ "run_id",
1114
+ "ordinal",
1115
+ "parent_revision_id",
1116
+ "payload_digest",
1117
+ "payload_json",
1118
+ "summary",
1119
+ "created_at",
1147
1120
  ),
1148
1121
  "edit_agent_events": (
1149
- "event_id", "run_id", "sequence", "event_type", "payload_json",
1122
+ "event_id",
1123
+ "run_id",
1124
+ "sequence",
1125
+ "event_type",
1126
+ "payload_json",
1150
1127
  "created_at",
1151
1128
  ),
1152
1129
  "edit_agent_command_receipts": (
1153
- "request_id", "command_type", "request_hash", "response_json",
1130
+ "request_id",
1131
+ "command_type",
1132
+ "request_hash",
1133
+ "response_json",
1154
1134
  "created_at",
1155
1135
  ),
1156
1136
  }
@@ -1166,18 +1146,10 @@ class ProjectRepository:
1166
1146
  raise sqlite3.DatabaseError("incomplete edit agent schema")
1167
1147
  if observed:
1168
1148
  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
- )
1149
+ columns = tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})"))
1173
1150
  if columns != expected:
1174
1151
  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
- }
1152
+ indexes = {row["name"] for row in connection.execute("SELECT name FROM sqlite_master WHERE type='index'")}
1181
1153
  if not {
1182
1154
  "edit_agent_runs_project_created",
1183
1155
  "edit_agent_revisions_run_ordinal",
@@ -1185,9 +1157,7 @@ class ProjectRepository:
1185
1157
  }.issubset(indexes):
1186
1158
  raise sqlite3.DatabaseError("incomplete edit agent indexes")
1187
1159
  connection.executescript(
1188
- "BEGIN IMMEDIATE;\n"
1189
- + ("" if observed else EDIT_AGENT_SCHEMA)
1190
- + "\nPRAGMA user_version = 14;\nCOMMIT;"
1160
+ "BEGIN IMMEDIATE;\n" + ("" if observed else EDIT_AGENT_SCHEMA) + "\nPRAGMA user_version = 14;\nCOMMIT;"
1191
1161
  )
1192
1162
 
1193
1163
  @staticmethod
@@ -1207,20 +1177,36 @@ class ProjectRepository:
1207
1177
  def _migrate_v15_to_v16(connection: sqlite3.Connection) -> None:
1208
1178
  expected = {
1209
1179
  "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"),
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
+ ),
1211
1195
  "finishing_draft": ("slot", "revision", "context_json", "payload_json"),
1212
1196
  }
1213
- observed = {row["name"] for row in connection.execute(
1214
- "SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'finishing_%'"
1215
- )}
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
+ }
1216
1203
  if observed and observed != set(expected):
1217
1204
  raise sqlite3.DatabaseError("incomplete finishing schema")
1218
1205
  for table in observed:
1219
1206
  if tuple(row["name"] for row in connection.execute(f"PRAGMA table_info({table})")) != expected[table]:
1220
1207
  raise sqlite3.DatabaseError("unexpected finishing schema")
1221
1208
  connection.executescript(
1222
- "BEGIN IMMEDIATE;\n" + ("" if observed else FINISHING_SCHEMA)
1223
- + "\nPRAGMA user_version = 16;\nCOMMIT;"
1209
+ "BEGIN IMMEDIATE;\n" + ("" if observed else FINISHING_SCHEMA) + "\nPRAGMA user_version = 16;\nCOMMIT;"
1224
1210
  )
1225
1211
 
1226
1212
  @staticmethod
@@ -1232,19 +1218,24 @@ class ProjectRepository:
1232
1218
  before a render can start.
1233
1219
  """
1234
1220
 
1235
- columns = tuple(
1236
- row["name"] for row in connection.execute("PRAGMA table_info(preview_renders)")
1237
- )
1221
+ columns = tuple(row["name"] for row in connection.execute("PRAGMA table_info(preview_renders)"))
1238
1222
  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",
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",
1242
1235
  )
1243
1236
  if columns != expected:
1244
1237
  raise sqlite3.DatabaseError("unexpected preview render schema")
1245
- current = connection.execute(
1246
- "SELECT render_id FROM current_preview_render WHERE slot=1"
1247
- ).fetchone()
1238
+ current = connection.execute("SELECT render_id FROM current_preview_render WHERE slot=1").fetchone()
1248
1239
  connection.execute("PRAGMA foreign_keys=OFF")
1249
1240
  try:
1250
1241
  connection.executescript(
@@ -1272,11 +1263,7 @@ class ProjectRepository:
1272
1263
  @staticmethod
1273
1264
  def _migrate_v2_to_v3(connection: sqlite3.Connection) -> None:
1274
1265
  try:
1275
- connection.executescript(
1276
- "BEGIN IMMEDIATE;\n"
1277
- + _ANALYSIS_SCHEMA
1278
- + "\nPRAGMA user_version = 4;\nCOMMIT;"
1279
- )
1266
+ connection.executescript("BEGIN IMMEDIATE;\n" + _ANALYSIS_SCHEMA + "\nPRAGMA user_version = 4;\nCOMMIT;")
1280
1267
  except sqlite3.Error:
1281
1268
  connection.rollback()
1282
1269
  raise
@@ -1368,15 +1355,11 @@ class ProjectRepository:
1368
1355
  def _migrate_v4_to_v5(connection: sqlite3.Connection) -> None:
1369
1356
  """Keep old transcripts while making their unverified quality explicit."""
1370
1357
  try:
1371
- columns = {
1372
- row[1]
1373
- for row in connection.execute(
1374
- "PRAGMA table_info(preparation_items)"
1375
- ).fetchall()
1376
- }
1358
+ columns = {row[1] for row in connection.execute("PRAGMA table_info(preparation_items)").fetchall()}
1377
1359
  add_review_column = (
1378
- "" if "review_required" in columns else
1379
- "ALTER TABLE preparation_items ADD COLUMN review_required INTEGER "
1360
+ ""
1361
+ if "review_required" in columns
1362
+ else "ALTER TABLE preparation_items ADD COLUMN review_required INTEGER "
1380
1363
  "NOT NULL DEFAULT 0 CHECK (review_required IN (0, 1));"
1381
1364
  )
1382
1365
  connection.executescript(
@@ -1429,13 +1412,10 @@ class ProjectRepository:
1429
1412
  @staticmethod
1430
1413
  def _read_snapshot(connection: sqlite3.Connection) -> ProjectSnapshot:
1431
1414
  row = connection.execute(
1432
- "SELECT project_id, name, brief, stage, revision, created_at, updated_at "
1433
- "FROM project LIMIT 1"
1415
+ "SELECT project_id, name, brief, stage, revision, created_at, updated_at FROM project LIMIT 1"
1434
1416
  ).fetchone()
1435
1417
  if row is None:
1436
- raise ProjectError(
1437
- "storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500
1438
- )
1418
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取作品資料。", status_code=500)
1439
1419
  directories = connection.execute(
1440
1420
  "SELECT role, canonical_path, display_path, display_name, device, inode, saved_at "
1441
1421
  "FROM project_directories ORDER BY role"