@clipen/clipen-cli 1.0.0 → 1.0.2

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 (132) hide show
  1. package/README.md +56 -48
  2. package/apps/web/dist/assets/{index-D5D2HiB1.js → index-DPHwA954.js} +1 -1
  3. package/apps/web/dist/index.html +1 -1
  4. package/bin/clipen.js +1 -1
  5. package/package.json +7 -6
  6. package/pyproject.toml +18 -2
  7. package/requirements/dev.txt +2 -0
  8. package/src/clipen/__init__.py +1 -1
  9. package/src/clipen/analysis/__init__.py +7 -7
  10. package/src/clipen/analysis/artifacts.py +4 -10
  11. package/src/clipen/analysis/audio.py +10 -8
  12. package/src/clipen/analysis/evidence_service.py +345 -167
  13. package/src/clipen/analysis/image_similarity.py +5 -14
  14. package/src/clipen/analysis/keyframes.py +5 -17
  15. package/src/clipen/analysis/models.py +5 -7
  16. package/src/clipen/analysis/qwen_worker.py +19 -54
  17. package/src/clipen/analysis/resources.py +2 -1
  18. package/src/clipen/analysis/runtime.py +1 -3
  19. package/src/clipen/analysis/service.py +16 -48
  20. package/src/clipen/analysis/setup.py +11 -25
  21. package/src/clipen/analysis/setup_cli.py +5 -15
  22. package/src/clipen/analysis/storage.py +96 -278
  23. package/src/clipen/analysis/transcription.py +40 -82
  24. package/src/clipen/analysis/visual.py +109 -48
  25. package/src/clipen/annotations/__init__.py +5 -2
  26. package/src/clipen/annotations/models.py +1 -1
  27. package/src/clipen/annotations/storage.py +132 -84
  28. package/src/clipen/annotations/suggestions.py +3 -8
  29. package/src/clipen/asr_release.py +4 -11
  30. package/src/clipen/bootstrap.py +71 -61
  31. package/src/clipen/{planning/models.py → candidates.py} +29 -47
  32. package/src/clipen/cli.py +4 -9
  33. package/src/clipen/controller/app.py +401 -214
  34. package/src/clipen/controller/server.py +28 -38
  35. package/src/clipen/domain/__init__.py +1 -1
  36. package/src/clipen/domain/media_time.py +3 -10
  37. package/src/clipen/domain/timeline.py +45 -47
  38. package/src/clipen/domain/validation.py +0 -1
  39. package/src/clipen/editing/__init__.py +1 -1
  40. package/src/clipen/editing/agent_models.py +4 -11
  41. package/src/clipen/editing/agent_repository.py +393 -172
  42. package/src/clipen/editing/agent_tools.py +180 -99
  43. package/src/clipen/editing/alignment.py +92 -52
  44. package/src/clipen/editing/alignment_setup.py +118 -70
  45. package/src/clipen/editing/alignment_worker.py +11 -9
  46. package/src/clipen/editing/change_report.py +95 -38
  47. package/src/clipen/editing/compiler.py +0 -1
  48. package/src/clipen/editing/component_looks.py +58 -34
  49. package/src/clipen/editing/component_review.py +34 -38
  50. package/src/clipen/editing/coordinator.py +213 -92
  51. package/src/clipen/editing/editorial_review.py +217 -95
  52. package/src/clipen/editing/evidence_jobs.py +457 -200
  53. package/src/clipen/editing/history_changes.py +129 -68
  54. package/src/clipen/editing/music_choices.py +8 -5
  55. package/src/clipen/editing/production_catalog.py +573 -136
  56. package/src/clipen/editing/production_limits.py +43 -17
  57. package/src/clipen/editing/production_media.py +376 -167
  58. package/src/clipen/editing/production_preview.py +322 -129
  59. package/src/clipen/editing/production_progress.py +164 -69
  60. package/src/clipen/editing/production_requirements.py +106 -39
  61. package/src/clipen/editing/production_tools.py +1064 -462
  62. package/src/clipen/editing/program_audio.py +211 -81
  63. package/src/clipen/editing/program_direction.py +59 -25
  64. package/src/clipen/editing/program_story.py +83 -45
  65. package/src/clipen/editing/program_subtitles.py +194 -96
  66. package/src/clipen/editing/programme_review.py +98 -50
  67. package/src/clipen/editing/prompt_history.py +64 -27
  68. package/src/clipen/editing/recut.py +65 -25
  69. package/src/clipen/editing/refinement_references.py +176 -86
  70. package/src/clipen/editing/resolve_export.py +449 -218
  71. package/src/clipen/editing/resolve_titles.py +162 -105
  72. package/src/clipen/editing/skill_tools.py +530 -154
  73. package/src/clipen/editing/source_dialogue.py +177 -67
  74. package/src/clipen/editing/speech_coverage.py +42 -22
  75. package/src/clipen/editing/speech_quality.py +6 -1
  76. package/src/clipen/editing/tool_receipts.py +78 -32
  77. package/src/clipen/editing/versions.py +122 -64
  78. package/src/clipen/editing/visual_preview.py +157 -61
  79. package/src/clipen/editing/workbench.py +104 -42
  80. package/src/clipen/finishing/audio.py +69 -30
  81. package/src/clipen/finishing/catalog.py +176 -93
  82. package/src/clipen/finishing/models.py +1 -1
  83. package/src/clipen/finishing/renderer.py +33 -14
  84. package/src/clipen/mcp_editing/__main__.py +3 -1
  85. package/src/clipen/mcp_editing/server.py +77 -34
  86. package/src/clipen/media/__init__.py +3 -3
  87. package/src/clipen/media/discovery.py +7 -20
  88. package/src/clipen/media/models.py +7 -18
  89. package/src/clipen/media/preview.py +14 -24
  90. package/src/clipen/media/probe.py +16 -44
  91. package/src/clipen/media/service.py +6 -19
  92. package/src/clipen/media/storage.py +33 -81
  93. package/src/clipen/music_vocabulary.py +33 -4
  94. package/src/clipen/power.py +8 -3
  95. package/src/clipen/projects/__init__.py +1 -1
  96. package/src/clipen/projects/deletion.py +19 -32
  97. package/src/clipen/projects/finishing_schema.py +3 -1
  98. package/src/clipen/projects/models.py +2 -5
  99. package/src/clipen/projects/picker.py +13 -37
  100. package/src/clipen/projects/service.py +8 -24
  101. package/src/clipen/projects/storage.py +226 -246
  102. package/src/clipen/provider_registry.py +9 -20
  103. package/src/clipen/providers/account.py +86 -35
  104. package/src/clipen/providers/claude.py +59 -25
  105. package/src/clipen/providers/claude_editing.py +14 -7
  106. package/src/clipen/providers/codex.py +73 -118
  107. package/src/clipen/providers/codex_editing.py +2 -2
  108. package/src/clipen/providers/editing_agent.py +19 -17
  109. package/src/clipen/providers/recovery.py +7 -8
  110. package/src/clipen/rendering/cover.py +18 -5
  111. package/src/clipen/rendering/custom_components.py +167 -79
  112. package/src/clipen/rendering/custom_render.py +62 -41
  113. package/src/clipen/rendering/production_effects.py +77 -45
  114. package/src/clipen/rendering/program_components.py +134 -73
  115. package/src/clipen/rendering/program_creator.py +432 -277
  116. package/src/clipen/rendering/program_identities.py +277 -182
  117. package/src/clipen/rendering/program_motion.py +140 -95
  118. package/src/clipen/rendering/program_studio.py +175 -116
  119. package/src/clipen/rendering/program_styles.py +231 -145
  120. package/src/clipen/rendering/program_subtitles.py +71 -34
  121. package/src/clipen/rendering/renderer.py +150 -121
  122. package/src/clipen/rendering/storage.py +9 -22
  123. package/src/clipen/rendering/titles.py +193 -86
  124. package/src/clipen/skills/__init__.py +1 -0
  125. package/src/clipen/skills/catalog.py +151 -55
  126. package/src/clipen/skills/library.py +13 -7
  127. package/src/clipen/skills/package.py +46 -23
  128. package/src/clipen/skills/visual_styles.py +29 -18
  129. package/src/clipen/workspace.py +15 -44
  130. package/install +0 -25
  131. package/src/clipen/planning/__init__.py +0 -9
  132. package/uninstall +0 -25
@@ -31,7 +31,6 @@ from .models import (
31
31
  validate_run_id,
32
32
  )
33
33
 
34
-
35
34
  _TERMINAL_STATES = frozenset(
36
35
  {
37
36
  InventoryState.SUCCEEDED,
@@ -94,15 +93,11 @@ class InventoryRepository:
94
93
  try:
95
94
  connection.execute("BEGIN IMMEDIATE")
96
95
  receipt = connection.execute(
97
- "SELECT command_type, request_hash, run_id "
98
- "FROM inventory_command_receipts WHERE request_id = ?",
96
+ "SELECT command_type, request_hash, run_id FROM inventory_command_receipts WHERE request_id = ?",
99
97
  (normalized_request,),
100
98
  ).fetchone()
101
99
  if receipt is not None:
102
- if (
103
- receipt["command_type"] != "start_inventory"
104
- or receipt["request_hash"] != request_hash
105
- ):
100
+ if receipt["command_type"] != "start_inventory" or receipt["request_hash"] != request_hash:
106
101
  raise ProjectError(
107
102
  "request_reused",
108
103
  "這次操作的識別資訊已用於不同內容。",
@@ -124,8 +119,7 @@ class InventoryRepository:
124
119
  status_code=409,
125
120
  )
126
121
  rows = connection.execute(
127
- "SELECT role, canonical_path, device, inode, saved_at "
128
- "FROM project_directories ORDER BY role"
122
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
129
123
  ).fetchall()
130
124
  roots = tuple(
131
125
  InventoryRoot(
@@ -144,8 +138,7 @@ class InventoryRepository:
144
138
  status_code=409,
145
139
  )
146
140
  incomplete = connection.execute(
147
- "SELECT run_id FROM inventory_runs "
148
- "WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
141
+ "SELECT run_id FROM inventory_runs WHERE state IN ('queued', 'running', 'cancelling') LIMIT 1"
149
142
  ).fetchone()
150
143
  if incomplete is not None:
151
144
  raise ProjectError(
@@ -200,14 +193,10 @@ class InventoryRepository:
200
193
  raise
201
194
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
202
195
  connection.rollback()
203
- raise ProjectError(
204
- "storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500
205
- ) from error
196
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500) from error
206
197
  except sqlite3.Error as error:
207
198
  connection.rollback()
208
- raise ProjectError(
209
- "storage_failed", "Clipen 無法建立素材檢查。", status_code=500
210
- ) from error
199
+ raise ProjectError("storage_failed", "Clipen 無法建立素材檢查。", status_code=500) from error
211
200
 
212
201
  def get_run(self, project_id: str, run_id: object) -> InventoryRun:
213
202
  validate_project_id(project_id)
@@ -221,17 +210,13 @@ class InventoryRepository:
221
210
  def current_run(self, project_id: str) -> InventoryRun | None:
222
211
  validate_project_id(project_id)
223
212
  with self.projects.connect(project_id) as connection:
224
- row = connection.execute(
225
- "SELECT run_id FROM current_inventory WHERE slot = 1"
226
- ).fetchone()
213
+ row = connection.execute("SELECT run_id FROM current_inventory WHERE slot = 1").fetchone()
227
214
  return None if row is None else self._read_run(connection, row["run_id"])
228
215
 
229
216
  def latest_run(self, project_id: str) -> InventoryRun | None:
230
217
  validate_project_id(project_id)
231
218
  with self.projects.connect(project_id) as connection:
232
- row = connection.execute(
233
- "SELECT run_id FROM inventory_runs ORDER BY created_at DESC LIMIT 1"
234
- ).fetchone()
219
+ row = connection.execute("SELECT run_id FROM inventory_runs ORDER BY created_at DESC LIMIT 1").fetchone()
235
220
  return None if row is None else self._read_run(connection, row["run_id"])
236
221
 
237
222
  def list_items(
@@ -252,15 +237,11 @@ class InventoryRepository:
252
237
  or not isinstance(limit, int)
253
238
  or not 1 <= limit <= 200
254
239
  ):
255
- raise ProjectError(
256
- "pagination_invalid", "素材清單頁碼無效。", status_code=422
257
- )
240
+ raise ProjectError("pagination_invalid", "素材清單頁碼無效。", status_code=422)
258
241
  with self.projects.connect(project_id) as connection:
259
242
  run = self._read_run(connection, normalized_run)
260
243
  if run.project_id != project_id:
261
- raise ProjectError(
262
- "inventory_not_found", "找不到這次素材檢查。", status_code=404
263
- )
244
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
264
245
  total = connection.execute(
265
246
  "SELECT COUNT(*) FROM inventory_items WHERE run_id = ?",
266
247
  (normalized_run,),
@@ -302,9 +283,7 @@ class InventoryRepository:
302
283
  "Clipen 無法讀取素材清單。",
303
284
  status_code=500,
304
285
  ) from error
305
- streams_by_version.setdefault(stream_row["version_id"], []).append(
306
- stream
307
- )
286
+ streams_by_version.setdefault(stream_row["version_id"], []).append(stream)
308
287
  try:
309
288
  items = tuple(
310
289
  InventoryItem(
@@ -316,21 +295,15 @@ class InventoryRepository:
316
295
  ItemStatus(row["status"]),
317
296
  row["issue_code"],
318
297
  row["size_bytes"],
319
- None
320
- if row["probe_status"] is None
321
- else ProbeStatus(row["probe_status"]),
322
- None
323
- if row["probe_json"] is None
324
- else json.loads(row["probe_json"]),
298
+ None if row["probe_status"] is None else ProbeStatus(row["probe_status"]),
299
+ None if row["probe_json"] is None else json.loads(row["probe_json"]),
325
300
  tuple(streams_by_version.get(row["version_id"], ())),
326
301
  )
327
302
  for row in rows
328
303
  )
329
304
  return InventoryPage(items, total, offset, limit)
330
305
  except (json.JSONDecodeError, TypeError, ValueError) as error:
331
- raise ProjectError(
332
- "storage_corrupt", "Clipen 無法讀取素材清單。", status_code=500
333
- ) from error
306
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材清單。", status_code=500) from error
334
307
 
335
308
  def request_cancel(self, project_id: str, run_id: object) -> InventoryRun:
336
309
  """Idempotently request cancellation without reviving terminal work."""
@@ -341,9 +314,7 @@ class InventoryRepository:
341
314
  connection.execute("BEGIN IMMEDIATE")
342
315
  current = self._read_run(connection, normalized_run)
343
316
  if current.project_id != project_id:
344
- raise ProjectError(
345
- "inventory_not_found", "找不到這次素材檢查。", status_code=404
346
- )
317
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
347
318
  if current.state in _TERMINAL_STATES or current.state is InventoryState.CANCELLING:
348
319
  connection.rollback()
349
320
  return current
@@ -356,8 +327,7 @@ class InventoryRepository:
356
327
  )
357
328
  else:
358
329
  connection.execute(
359
- "UPDATE inventory_runs SET state = 'cancelling', "
360
- "phase = 'cancelling' WHERE run_id = ?",
330
+ "UPDATE inventory_runs SET state = 'cancelling', phase = 'cancelling' WHERE run_id = ?",
361
331
  (normalized_run,),
362
332
  )
363
333
  updated = self._read_run(connection, normalized_run)
@@ -368,9 +338,7 @@ class InventoryRepository:
368
338
  raise
369
339
  except sqlite3.Error as error:
370
340
  connection.rollback()
371
- raise ProjectError(
372
- "storage_failed", "Clipen 無法取消素材檢查。", status_code=500
373
- ) from error
341
+ raise ProjectError("storage_failed", "Clipen 無法取消素材檢查。", status_code=500) from error
374
342
 
375
343
  def transition(
376
344
  self,
@@ -392,9 +360,7 @@ class InventoryRepository:
392
360
  connection.execute("BEGIN IMMEDIATE")
393
361
  current = self._read_run(connection, normalized_run)
394
362
  if current.project_id != project_id:
395
- raise ProjectError(
396
- "inventory_not_found", "找不到這次素材檢查。", status_code=404
397
- )
363
+ raise ProjectError("inventory_not_found", "找不到這次素材檢查。", status_code=404)
398
364
  if target not in _TRANSITIONS.get(current.state, set()):
399
365
  raise ProjectError(
400
366
  "inventory_state_conflict",
@@ -417,9 +383,7 @@ class InventoryRepository:
417
383
  raise
418
384
  except sqlite3.Error as error:
419
385
  connection.rollback()
420
- raise ProjectError(
421
- "storage_failed", "Clipen 無法更新素材檢查。", status_code=500
422
- ) from error
386
+ raise ProjectError("storage_failed", "Clipen 無法更新素材檢查。", status_code=500) from error
423
387
 
424
388
  def publish(self, project_id: str, run_id: object) -> InventoryRun:
425
389
  validate_project_id(project_id)
@@ -435,8 +399,7 @@ class InventoryRepository:
435
399
  status_code=409,
436
400
  )
437
401
  root_rows = connection.execute(
438
- "SELECT role, canonical_path, device, inode, saved_at "
439
- "FROM project_directories ORDER BY role"
402
+ "SELECT role, canonical_path, device, inode, saved_at FROM project_directories ORDER BY role"
440
403
  ).fetchall()
441
404
  current_roots = tuple(
442
405
  InventoryRoot(
@@ -497,17 +460,7 @@ class InventoryRepository:
497
460
  raise
498
461
  except sqlite3.Error as error:
499
462
  connection.rollback()
500
- raise ProjectError(
501
- "storage_failed", "Clipen 無法發布素材檢查結果。", status_code=500
502
- ) from error
503
-
504
- def stage_item(
505
- self,
506
- project_id: str,
507
- run_id: object,
508
- candidate: AssetCandidate,
509
- ) -> InventoryRun:
510
- return self.stage_items(project_id, run_id, (candidate,))
463
+ raise ProjectError("storage_failed", "Clipen 無法發布素材檢查結果。", status_code=500) from error
511
464
 
512
465
  def stage_items(
513
466
  self,
@@ -543,8 +496,7 @@ class InventoryRepository:
543
496
  now,
544
497
  )
545
498
  probed_increment += int(
546
- candidate.probe_status is not None
547
- and candidate.probe_status.value != "pending"
499
+ candidate.probe_status is not None and candidate.probe_status.value != "pending"
548
500
  )
549
501
  usable_increment += int(candidate.status is ItemStatus.USABLE)
550
502
  issue_increment += int(candidate.status is ItemStatus.NEEDS_ATTENTION)
@@ -576,9 +528,7 @@ class InventoryRepository:
576
528
  ) from error
577
529
  except sqlite3.Error as error:
578
530
  connection.rollback()
579
- raise ProjectError(
580
- "storage_failed", "Clipen 無法保存素材檢查結果。", status_code=500
581
- ) from error
531
+ raise ProjectError("storage_failed", "Clipen 無法保存素材檢查結果。", status_code=500) from error
582
532
 
583
533
  @staticmethod
584
534
  def _insert_candidate(
@@ -652,7 +602,9 @@ class InventoryRepository:
652
602
  )
653
603
  # Enrich legacy probe rows with newly understood disposition flags.
654
604
  # Do not replace the immutable source version or its time mapping.
655
- flags = {key: stream.details[key] for key in ("attached_pic", "timed_thumbnails") if key in stream.details}
605
+ flags = {
606
+ key: stream.details[key] for key in ("attached_pic", "timed_thumbnails") if key in stream.details
607
+ }
656
608
  if flags:
657
609
  existing_details = connection.execute(
658
610
  "SELECT details_json FROM media_streams WHERE version_id=? AND stream_index=?",
@@ -663,7 +615,11 @@ class InventoryRepository:
663
615
  details.update(flags)
664
616
  connection.execute(
665
617
  "UPDATE media_streams SET details_json=? WHERE version_id=? AND stream_index=?",
666
- (json.dumps(details, sort_keys=True, separators=(",", ":")), version_id, stream.stream_index),
618
+ (
619
+ json.dumps(details, sort_keys=True, separators=(",", ":")),
620
+ version_id,
621
+ stream.stream_index,
622
+ ),
667
623
  )
668
624
  connection.execute(
669
625
  "INSERT INTO inventory_items "
@@ -697,9 +653,7 @@ class InventoryRepository:
697
653
  return cursor.rowcount
698
654
  except sqlite3.Error as error:
699
655
  connection.rollback()
700
- raise ProjectError(
701
- "storage_failed", "Clipen 無法恢復素材檢查。", status_code=500
702
- ) from error
656
+ raise ProjectError("storage_failed", "Clipen 無法恢復素材檢查。", status_code=500) from error
703
657
 
704
658
  @staticmethod
705
659
  def _read_run(connection: sqlite3.Connection, run_id: str) -> InventoryRun:
@@ -737,6 +691,4 @@ class InventoryRepository:
737
691
  completed_at=row["completed_at"],
738
692
  )
739
693
  except (json.JSONDecodeError, KeyError, TypeError, ValueError) as error:
740
- raise ProjectError(
741
- "storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500
742
- ) from error
694
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取素材檢查紀錄。", status_code=500) from error
@@ -1,5 +1,34 @@
1
1
  """Public musical vocabulary shared by planning and search tool contracts."""
2
- MUSIC_TAGS = ['travel', 'cinematic', 'ambient', 'acoustic', 'electronic', 'folk', 'jazz', 'classical',
3
- 'happy', 'calm', 'peaceful', 'energetic', 'dramatic', 'nostalgic', 'uplifting',
4
- 'piano', 'guitar', 'strings', 'percussion', 'chill', 'adventure', 'nature',
5
- 'japanese', 'citypop', 'bossa nova', 'lofi', 'kawaii', 'upbeat', 'funk', 'soul']
2
+
3
+ MUSIC_TAGS = [
4
+ "travel",
5
+ "cinematic",
6
+ "ambient",
7
+ "acoustic",
8
+ "electronic",
9
+ "folk",
10
+ "jazz",
11
+ "classical",
12
+ "happy",
13
+ "calm",
14
+ "peaceful",
15
+ "energetic",
16
+ "dramatic",
17
+ "nostalgic",
18
+ "uplifting",
19
+ "piano",
20
+ "guitar",
21
+ "strings",
22
+ "percussion",
23
+ "chill",
24
+ "adventure",
25
+ "nature",
26
+ "japanese",
27
+ "citypop",
28
+ "bossa nova",
29
+ "lofi",
30
+ "kawaii",
31
+ "upbeat",
32
+ "funk",
33
+ "soul",
34
+ ]
@@ -1,4 +1,5 @@
1
1
  """Whether the Mac runs on battery: on battery, closing the lid sleeps it even while the AI works."""
2
+
2
3
  from __future__ import annotations
3
4
 
4
5
  import re
@@ -14,10 +15,14 @@ def power_status() -> dict:
14
15
  if sys.platform != "darwin":
15
16
  return {"on_battery": None, "percent": None}
16
17
  try:
17
- output = subprocess.run(["/usr/bin/pmset", "-g", "batt"], capture_output=True, text=True, timeout=3, check=False).stdout
18
+ output = subprocess.run(
19
+ ["/usr/bin/pmset", "-g", "batt"], capture_output=True, text=True, timeout=3, check=False
20
+ ).stdout
18
21
  except (OSError, subprocess.TimeoutExpired):
19
22
  return {"on_battery": None, "percent": None}
20
23
  source = _SOURCE.search(output)
21
24
  percent = _PERCENT.search(output)
22
- return {"on_battery": None if source is None else source.group(1) == "Battery Power",
23
- "percent": int(percent.group(1)) if percent else None}
25
+ return {
26
+ "on_battery": None if source is None else source.group(1) == "Battery Power",
27
+ "percent": int(percent.group(1)) if percent else None,
28
+ }
@@ -7,9 +7,9 @@ from .models import (
7
7
  ProjectError,
8
8
  ProjectSnapshot,
9
9
  )
10
- from .storage import ProjectRepository, command_digest
11
10
  from .picker import MacOSDirectoryPicker, NativeDirectoryPicker, SelectionAuthority
12
11
  from .service import ProjectWorkspace
12
+ from .storage import ProjectRepository, command_digest
13
13
 
14
14
  __all__ = [
15
15
  "DirectoryAvailability",
@@ -2,18 +2,18 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from contextlib import AbstractContextManager
6
5
  import hashlib
7
6
  import json
8
7
  import os
9
- from pathlib import Path
10
8
  import re
11
9
  import shutil
12
10
  import sqlite3
13
11
  import stat
14
12
  import threading
15
- from typing import Mapping, Protocol
16
13
  import uuid
14
+ from contextlib import AbstractContextManager
15
+ from pathlib import Path
16
+ from typing import Mapping, Protocol
17
17
 
18
18
  from clipen.filesystem import restrict_permissions
19
19
 
@@ -32,9 +32,7 @@ class ProjectStorage(Protocol):
32
32
 
33
33
  def get_project(self, project_id: str) -> ProjectSnapshot: ...
34
34
 
35
- def connect(
36
- self, project_id: str
37
- ) -> AbstractContextManager[sqlite3.Connection]: ...
35
+ def connect(self, project_id: str) -> AbstractContextManager[sqlite3.Connection]: ...
38
36
 
39
37
 
40
38
  class ProjectDeletion:
@@ -92,11 +90,7 @@ class ProjectDeletion:
92
90
 
93
91
  def _validate_managed_tree(self, project_id: str) -> None:
94
92
  project = self.storage.root / project_id
95
- if (
96
- project.parent != self.storage.root
97
- or project.is_symlink()
98
- or not project.is_dir()
99
- ):
93
+ if project.parent != self.storage.root or project.is_symlink() or not project.is_dir():
100
94
  raise ProjectError("project_not_found", "找不到這個作品。", status_code=404)
101
95
  expected_owner = os.getuid() if hasattr(os, "getuid") else None
102
96
  for parent, directory_names, file_names in os.walk(project, followlinks=False):
@@ -185,16 +179,17 @@ class ProjectDeletion:
185
179
  "SELECT 1 FROM preparation_runs WHERE state IN (?, ?, ?) LIMIT 1",
186
180
  )
187
181
  with self.storage.connect(project_id) as connection:
188
- active = any(
189
- connection.execute(query, active_states).fetchone() is not None
190
- for query in queries
182
+ active = any(connection.execute(query, active_states).fetchone() is not None for query in queries)
183
+ active = (
184
+ active
185
+ or connection.execute("SELECT 1 FROM evidence_runs WHERE state = 'running' LIMIT 1").fetchone()
186
+ is not None
187
+ )
188
+ active = (
189
+ active
190
+ or connection.execute("SELECT 1 FROM evidence_observations WHERE state = 'running' LIMIT 1").fetchone()
191
+ is not None
191
192
  )
192
- active = active or connection.execute(
193
- "SELECT 1 FROM evidence_runs WHERE state = 'running' LIMIT 1"
194
- ).fetchone() is not None
195
- active = active or connection.execute(
196
- "SELECT 1 FROM evidence_observations WHERE state = 'running' LIMIT 1"
197
- ).fetchone() is not None
198
193
  if active:
199
194
  raise ProjectError(
200
195
  "project_busy",
@@ -206,9 +201,7 @@ class ProjectDeletion:
206
201
  receipts = self.storage.root / ".delete-receipts"
207
202
  receipts.mkdir(mode=0o700, exist_ok=True)
208
203
  if receipts.is_symlink() or not receipts.is_dir():
209
- raise ProjectError(
210
- "storage_unsafe", "Clipen 刪除紀錄位置不安全。", status_code=500
211
- )
204
+ raise ProjectError("storage_unsafe", "Clipen 刪除紀錄位置不安全。", status_code=500)
212
205
  restrict_permissions(receipts, 0o700)
213
206
  return receipts
214
207
 
@@ -221,19 +214,13 @@ class ProjectDeletion:
221
214
  if not path.exists():
222
215
  return None
223
216
  if path.is_symlink() or not path.is_file():
224
- raise ProjectError(
225
- "storage_unsafe", "Clipen 刪除紀錄不安全。", status_code=500
226
- )
217
+ raise ProjectError("storage_unsafe", "Clipen 刪除紀錄不安全。", status_code=500)
227
218
  try:
228
219
  value = json.loads(path.read_text(encoding="utf-8"))
229
220
  except (OSError, UnicodeError, json.JSONDecodeError) as error:
230
- raise ProjectError(
231
- "storage_corrupt", "Clipen 無法讀取刪除紀錄。", status_code=500
232
- ) from error
221
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取刪除紀錄。", status_code=500) from error
233
222
  if not isinstance(value, dict) or value.get("project_id") is None:
234
- raise ProjectError(
235
- "storage_corrupt", "Clipen 無法讀取刪除紀錄。", status_code=500
236
- )
223
+ raise ProjectError("storage_corrupt", "Clipen 無法讀取刪除紀錄。", status_code=500)
237
224
  return value
238
225
 
239
226
  def _write_receipt(self, request_id: str, value: Mapping[str, object]) -> None:
@@ -31,4 +31,6 @@ CREATE TABLE finishing_draft (
31
31
  CREATE INDEX finishing_runs_created ON finishing_runs(created_at DESC);
32
32
  """
33
33
 
34
- FINISHING_RUNS_SCHEMA = FINISHING_SCHEMA[FINISHING_SCHEMA.index("CREATE TABLE finishing_runs"):FINISHING_SCHEMA.index("CREATE TABLE finishing_draft")]
34
+ FINISHING_RUNS_SCHEMA = FINISHING_SCHEMA[
35
+ FINISHING_SCHEMA.index("CREATE TABLE finishing_runs") : FINISHING_SCHEMA.index("CREATE TABLE finishing_draft")
36
+ ]
@@ -2,12 +2,11 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
+ import re
5
6
  from dataclasses import dataclass, field
6
7
  from enum import Enum
7
- import re
8
8
  from typing import Any, Mapping
9
9
 
10
-
11
10
  _PROJECT_ID = re.compile(r"prj_[0-9a-f]{32}\Z")
12
11
  _REQUEST_ID = re.compile(r"[A-Za-z0-9][A-Za-z0-9._:-]{7,127}\Z")
13
12
 
@@ -186,7 +185,5 @@ class ProjectSnapshot:
186
185
  revision=int(value["revision"]),
187
186
  created_at=str(value["created_at"]),
188
187
  updated_at=str(value["updated_at"]),
189
- directories=tuple(
190
- DirectoryReference.from_storage(item) for item in raw_directories
191
- ),
188
+ directories=tuple(DirectoryReference.from_storage(item) for item in raw_directories),
192
189
  )
@@ -2,15 +2,15 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import dataclass, replace
6
5
  import os
7
- from pathlib import Path
8
6
  import secrets
9
7
  import stat
10
8
  import subprocess
11
9
  import sys
12
10
  import threading
13
11
  import time
12
+ from dataclasses import dataclass, replace
13
+ from pathlib import Path
14
14
  from typing import Callable
15
15
 
16
16
  from .models import (
@@ -21,7 +21,6 @@ from .models import (
21
21
  )
22
22
  from .storage import utc_now
23
23
 
24
-
25
24
  _SELECTION_LIFETIME_SECONDS = 10 * 60
26
25
  _MAX_PICKER_OUTPUT_BYTES = 8192
27
26
  _PICKER_TIMEOUT_SECONDS = 5 * 60
@@ -73,33 +72,21 @@ class MacOSDirectoryPicker(NativeDirectoryPicker):
73
72
  timeout=_PICKER_TIMEOUT_SECONDS,
74
73
  )
75
74
  except subprocess.TimeoutExpired as error:
76
- raise ProjectError(
77
- "picker_timeout", "資料夾選擇已逾時,請再試一次。", status_code=408
78
- ) from error
75
+ raise ProjectError("picker_timeout", "資料夾選擇已逾時,請再試一次。", status_code=408) from error
79
76
  except OSError as error:
80
- raise ProjectError(
81
- "picker_unavailable", "無法開啟 macOS 資料夾選擇器。", status_code=500
82
- ) from error
77
+ raise ProjectError("picker_unavailable", "無法開啟 macOS 資料夾選擇器。", status_code=500) from error
83
78
  if completed.returncode != 0:
84
- raise ProjectError(
85
- "picker_failed", "無法完成資料夾選擇。", status_code=500
86
- )
79
+ raise ProjectError("picker_failed", "無法完成資料夾選擇。", status_code=500)
87
80
  if len(completed.stdout) > _MAX_PICKER_OUTPUT_BYTES:
88
- raise ProjectError(
89
- "picker_failed", "資料夾選擇器回傳的路徑過長。", status_code=500
90
- )
81
+ raise ProjectError("picker_failed", "資料夾選擇器回傳的路徑過長。", status_code=500)
91
82
  try:
92
83
  output = completed.stdout.decode("utf-8").strip()
93
84
  except UnicodeDecodeError as error:
94
- raise ProjectError(
95
- "picker_failed", "資料夾選擇器回傳無法辨識的路徑。", status_code=500
96
- ) from error
85
+ raise ProjectError("picker_failed", "資料夾選擇器回傳無法辨識的路徑。", status_code=500) from error
97
86
  if not output:
98
87
  return None
99
88
  if "\x00" in output or not output.startswith("/"):
100
- raise ProjectError(
101
- "picker_failed", "資料夾選擇器回傳無效的路徑。", status_code=500
102
- )
89
+ raise ProjectError("picker_failed", "資料夾選擇器回傳無效的路徑。", status_code=500)
103
90
  return Path(output)
104
91
 
105
92
 
@@ -137,9 +124,7 @@ def inspect_directory(
137
124
  canonical = selected_path.resolve(strict=True)
138
125
  info = canonical.stat()
139
126
  except FileNotFoundError as error:
140
- raise ProjectError(
141
- "directory_offline", "找不到選取的資料夾或外接磁碟。", status_code=422
142
- ) from error
127
+ raise ProjectError("directory_offline", "找不到選取的資料夾或外接磁碟。", status_code=422) from error
143
128
  except PermissionError as error:
144
129
  raise ProjectError(
145
130
  "directory_permission",
@@ -232,25 +217,16 @@ class SelectionAuthority:
232
217
 
233
218
  def resolve(self, token: object, role: DirectoryRole) -> DirectoryReference:
234
219
  if not isinstance(token, str) or len(token) < 32 or len(token) > 256:
235
- raise ProjectError(
236
- "selection_invalid", "資料夾選擇已失效,請重新選擇。", status_code=422
237
- )
220
+ raise ProjectError("selection_invalid", "資料夾選擇已失效,請重新選擇。", status_code=422)
238
221
  with self._lock:
239
222
  self._prune()
240
223
  selection = self._selections.get(token)
241
224
  if selection is None or selection.reference.role is not role:
242
- raise ProjectError(
243
- "selection_invalid", "資料夾選擇已失效,請重新選擇。", status_code=422
244
- )
245
- return inspect_directory(
246
- Path(selection.reference.canonical_path), role, self._managed_root
247
- )
225
+ raise ProjectError("selection_invalid", "資料夾選擇已失效,請重新選擇。", status_code=422)
226
+ return inspect_directory(Path(selection.reference.canonical_path), role, self._managed_root)
248
227
 
249
228
  def _prune(self) -> None:
250
229
  current = self._now()
251
- expired = [
252
- token for token, selection in self._selections.items()
253
- if selection.expires_at < current
254
- ]
230
+ expired = [token for token, selection in self._selections.items() if selection.expires_at < current]
255
231
  for token in expired:
256
232
  self._selections.pop(token, None)
@@ -2,10 +2,10 @@
2
2
 
3
3
  from __future__ import annotations
4
4
 
5
- from dataclasses import replace
6
- from pathlib import Path
7
5
  import threading
8
6
  import time
7
+ from dataclasses import replace
8
+ from pathlib import Path
9
9
 
10
10
  from .models import (
11
11
  DirectoryReference,
@@ -55,15 +55,9 @@ class ProjectWorkspace:
55
55
  name: object,
56
56
  brief: object,
57
57
  ) -> ProjectSnapshot:
58
- return self._refresh(
59
- self.repository.update_details(
60
- project_id, request_id, expected_revision, name, brief
61
- )
62
- )
58
+ return self._refresh(self.repository.update_details(project_id, request_id, expected_revision, name, brief))
63
59
 
64
- def select_directory(
65
- self, request_id: object, role: DirectoryRole
66
- ) -> dict[str, object] | None:
60
+ def select_directory(self, request_id: object, role: DirectoryRole) -> dict[str, object] | None:
67
61
  normalized_request = validate_request_id(request_id)
68
62
  with self._picker_lock:
69
63
  cached = self._picker_receipts.get(normalized_request)
@@ -102,16 +96,12 @@ class ProjectWorkspace:
102
96
  "selection_token": selection_token,
103
97
  }
104
98
  )
105
- replay = self.repository.replay_receipt(
106
- project_id, normalized_request, "set_directory", command_hash
107
- )
99
+ replay = self.repository.replay_receipt(project_id, normalized_request, "set_directory", command_hash)
108
100
  if replay is not None:
109
101
  return self._refresh(replay)
110
102
  reference = self.selections.resolve(selection_token, role)
111
103
  current = self.repository.get_project(project_id)
112
- other = next(
113
- (item for item in current.directories if item.role is not role), None
114
- )
104
+ other = next((item for item in current.directories if item.role is not role), None)
115
105
  if other is not None and self._overlaps(reference, other):
116
106
  raise ProjectError(
117
107
  "directory_overlap",
@@ -135,11 +125,7 @@ class ProjectWorkspace:
135
125
  expected_revision: object,
136
126
  role: DirectoryRole,
137
127
  ) -> ProjectSnapshot:
138
- return self._refresh(
139
- self.repository.remove_directory(
140
- project_id, request_id, expected_revision, role
141
- )
142
- )
128
+ return self._refresh(self.repository.remove_directory(project_id, request_id, expected_revision, role))
143
129
 
144
130
  def delete_project(
145
131
  self,
@@ -169,7 +155,5 @@ class ProjectWorkspace:
169
155
  def _refresh(project: ProjectSnapshot) -> ProjectSnapshot:
170
156
  return replace(
171
157
  project,
172
- directories=tuple(
173
- refresh_availability(reference) for reference in project.directories
174
- ),
158
+ directories=tuple(refresh_availability(reference) for reference in project.directories),
175
159
  )