fusion-artifacts-engine 0.7.18__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (114) hide show
  1. fusion_artifacts_engine/__init__.py +0 -0
  2. fusion_artifacts_engine/__main__.py +263 -0
  3. fusion_artifacts_engine/ai_client.py +54 -0
  4. fusion_artifacts_engine/auto_identifier.py +148 -0
  5. fusion_artifacts_engine/compactor.py +164 -0
  6. fusion_artifacts_engine/config.py +462 -0
  7. fusion_artifacts_engine/default_config.yaml +144 -0
  8. fusion_artifacts_engine/dsl_parser.py +231 -0
  9. fusion_artifacts_engine/engine.py +1372 -0
  10. fusion_artifacts_engine/gateway_client.py +396 -0
  11. fusion_artifacts_engine/ipc_consumer.py +321 -0
  12. fusion_artifacts_engine/long_context.py +392 -0
  13. fusion_artifacts_engine/metrics.py +144 -0
  14. fusion_artifacts_engine/models.py +168 -0
  15. fusion_artifacts_engine/office_ingest.py +365 -0
  16. fusion_artifacts_engine/rate_limiter.py +82 -0
  17. fusion_artifacts_engine/ref_parser.py +77 -0
  18. fusion_artifacts_engine/render.py +184 -0
  19. fusion_artifacts_engine/rpc/__init__.py +0 -0
  20. fusion_artifacts_engine/rpc/errors.py +61 -0
  21. fusion_artifacts_engine/rpc/event_bus.py +95 -0
  22. fusion_artifacts_engine/rpc/methods.py +1365 -0
  23. fusion_artifacts_engine/rpc/server.py +1279 -0
  24. fusion_artifacts_engine/section_index.py +189 -0
  25. fusion_artifacts_engine/share.py +326 -0
  26. fusion_artifacts_engine/storage/__init__.py +0 -0
  27. fusion_artifacts_engine/storage/base.py +270 -0
  28. fusion_artifacts_engine/storage/sqlite_storage.py +2813 -0
  29. fusion_artifacts_engine/token_budget.py +119 -0
  30. fusion_artifacts_engine/token_counter.py +80 -0
  31. fusion_artifacts_engine/tracing.py +132 -0
  32. fusion_artifacts_engine/utils.py +170 -0
  33. fusion_artifacts_engine/visual_dispatcher.py +135 -0
  34. fusion_artifacts_engine/visual_error_boundary.py +52 -0
  35. fusion_artifacts_engine/visual_primitives/__init__.py +34 -0
  36. fusion_artifacts_engine/visual_primitives/array_grid.py +66 -0
  37. fusion_artifacts_engine/visual_primitives/base.py +79 -0
  38. fusion_artifacts_engine/visual_primitives/bucket_divider.py +66 -0
  39. fusion_artifacts_engine/visual_primitives/data_chart.py +65 -0
  40. fusion_artifacts_engine/visual_primitives/flow_card.py +101 -0
  41. fusion_artifacts_engine/visual_primitives/geometry_2d.py +80 -0
  42. fusion_artifacts_engine/visual_primitives/isometric_3d.py +82 -0
  43. fusion_artifacts_engine/visual_primitives/tape_diagram.py +58 -0
  44. fusion_artifacts_engine/visual_primitives/track_timeline.py +58 -0
  45. fusion_artifacts_engine/webui_dist/assets/abnfDiagram-WEYOIA3C-2ebtMp5N.js +1 -0
  46. fusion_artifacts_engine/webui_dist/assets/architectureDiagram-ZHVYKT53-COvSzFYy.js +36 -0
  47. fusion_artifacts_engine/webui_dist/assets/blockDiagram-RJAE7QA3-CsO2Iy8b.js +140 -0
  48. fusion_artifacts_engine/webui_dist/assets/c4Diagram-XDPPPE54-dFggQosH.js +38 -0
  49. fusion_artifacts_engine/webui_dist/assets/channel-BXYZthxM.js +1 -0
  50. fusion_artifacts_engine/webui_dist/assets/chunk-2E7WHVMD-B93QdjG6.js +88 -0
  51. fusion_artifacts_engine/webui_dist/assets/chunk-2Q5K7J3B-DHEJLJup.js +1 -0
  52. fusion_artifacts_engine/webui_dist/assets/chunk-4EMNKR2T-OGUUH-PY.js +1 -0
  53. fusion_artifacts_engine/webui_dist/assets/chunk-55XCU76K-CKbux1-g.js +1 -0
  54. fusion_artifacts_engine/webui_dist/assets/chunk-5VM5RSS4-CPHhHyIF.js +15 -0
  55. fusion_artifacts_engine/webui_dist/assets/chunk-JWPE2WC7-CJSxuarC.js +1 -0
  56. fusion_artifacts_engine/webui_dist/assets/chunk-VQ5W62QI-LHItmtfv.js +1 -0
  57. fusion_artifacts_engine/webui_dist/assets/chunk-XXDRQBXY-BRYBW56M.js +1 -0
  58. fusion_artifacts_engine/webui_dist/assets/chunk-ZCHMQSOR-cGbkforM.js +2 -0
  59. fusion_artifacts_engine/webui_dist/assets/classDiagram-v2-4MYWR3UA-RVdXT7ne.js +217 -0
  60. fusion_artifacts_engine/webui_dist/assets/cose-bilkent-JH36ORCC-C1hy4K0b.js +1 -0
  61. fusion_artifacts_engine/webui_dist/assets/cynefin-EF2NZ3EQ-D8ytFvIy.js +141 -0
  62. fusion_artifacts_engine/webui_dist/assets/cynefinDiagram-WF24UDRP-9iOV04Va.js +62 -0
  63. fusion_artifacts_engine/webui_dist/assets/cytoscape.esm-BLAcgzS2.js +331 -0
  64. fusion_artifacts_engine/webui_dist/assets/dagre-NK4GIZVX-zE4dzUJh.js +4 -0
  65. fusion_artifacts_engine/webui_dist/assets/defaultLocale-5voVPcsN.js +1 -0
  66. fusion_artifacts_engine/webui_dist/assets/diagram-CBK3MWTC-BrXmQtKM.js +24 -0
  67. fusion_artifacts_engine/webui_dist/assets/diagram-I5XIIV2D-Bctxj8zx.js +24 -0
  68. fusion_artifacts_engine/webui_dist/assets/diagram-ODIL2UCW-DfDzzeod.js +30 -0
  69. fusion_artifacts_engine/webui_dist/assets/diagram-PFBEJUXE-BGZKfFXu.js +3 -0
  70. fusion_artifacts_engine/webui_dist/assets/diagram-RJA3I4VV-CXB6A2jx.js +41 -0
  71. fusion_artifacts_engine/webui_dist/assets/diagram-TYUNFSNR-gfqyjmIj.js +200 -0
  72. fusion_artifacts_engine/webui_dist/assets/ebnfDiagram-V4P3TTPT-CZ1BZkcl.js +1 -0
  73. fusion_artifacts_engine/webui_dist/assets/elk-QONTBCTQ-C5YzS41r.js +27 -0
  74. fusion_artifacts_engine/webui_dist/assets/erDiagram-KYQIGQAA-B-DYTd4O.js +99 -0
  75. fusion_artifacts_engine/webui_dist/assets/flowDiagram-IUGLLWBU-IRAKfxcJ.js +213 -0
  76. fusion_artifacts_engine/webui_dist/assets/ganttDiagram-R7GPNTJY-DRdmsg6i.js +292 -0
  77. fusion_artifacts_engine/webui_dist/assets/gitGraphDiagram-PDYL7XHY-B0QL_KrV.js +106 -0
  78. fusion_artifacts_engine/webui_dist/assets/graph-Bn3Yngep.js +1 -0
  79. fusion_artifacts_engine/webui_dist/assets/index-CCsQ6nhB.js +374 -0
  80. fusion_artifacts_engine/webui_dist/assets/index-Cw23dyL1.css +1 -0
  81. fusion_artifacts_engine/webui_dist/assets/infoDiagram-MVDRKAX5-DMlVkZRb.js +2 -0
  82. fusion_artifacts_engine/webui_dist/assets/init-DDsq4BXF.js +1 -0
  83. fusion_artifacts_engine/webui_dist/assets/ishikawaDiagram-HPEHV2GE-yZW7Bvw7.js +70 -0
  84. fusion_artifacts_engine/webui_dist/assets/journeyDiagram-BOSHW7O7-C0UaOGz2.js +139 -0
  85. fusion_artifacts_engine/webui_dist/assets/kanban-definition-FNSA4HC5-D2VjWSCv.js +89 -0
  86. fusion_artifacts_engine/webui_dist/assets/katex-Be3d8Y4U.js +257 -0
  87. fusion_artifacts_engine/webui_dist/assets/linear-B0L4ZWGd.js +1 -0
  88. fusion_artifacts_engine/webui_dist/assets/mermaid.core-C0Fw4Tzk.js +314 -0
  89. fusion_artifacts_engine/webui_dist/assets/mindmap-definition-6OY57UG3-Dy3WTB5p.js +98 -0
  90. fusion_artifacts_engine/webui_dist/assets/ordinal-_ShbN0yz.js +1 -0
  91. fusion_artifacts_engine/webui_dist/assets/pegDiagram-ECIUJNBX-Cdm0XnAV.js +1 -0
  92. fusion_artifacts_engine/webui_dist/assets/pieDiagram-GNMPY74T-TrdpBRYl.js +39 -0
  93. fusion_artifacts_engine/webui_dist/assets/quadrantDiagram-D57K4MC3-N1OmHTjQ.js +7 -0
  94. fusion_artifacts_engine/webui_dist/assets/railroadDiagram-Y72NRBL7-DhZcDSX6.js +1 -0
  95. fusion_artifacts_engine/webui_dist/assets/requirementDiagram-EQYSW5RA-CGmfo0LK.js +84 -0
  96. fusion_artifacts_engine/webui_dist/assets/sankeyDiagram-SY24JHO5-CnAXR6RI.js +40 -0
  97. fusion_artifacts_engine/webui_dist/assets/sequenceDiagram-BLEHNHQU-Divp82Qv.js +169 -0
  98. fusion_artifacts_engine/webui_dist/assets/sizeCapture-INFHLROL-BxUSO2gs.js +1 -0
  99. fusion_artifacts_engine/webui_dist/assets/stateDiagram-v2-A6IESKWZ-Ch2o3gee.js +291 -0
  100. fusion_artifacts_engine/webui_dist/assets/swimlanes-B3ENRKFQ-CBnYOtut.js +1 -0
  101. fusion_artifacts_engine/webui_dist/assets/swimlanesDiagram-AYQRV4AK-Bdp49byx.js +8 -0
  102. fusion_artifacts_engine/webui_dist/assets/timeline-definition-JXYKGLGB-Cp8DPlck.js +120 -0
  103. fusion_artifacts_engine/webui_dist/assets/usecaseDiagram-WPOLBNNX-CcF_Y4cE.js +370 -0
  104. fusion_artifacts_engine/webui_dist/assets/vennDiagram-Q3Y3IDCW-Dplzp3gZ.js +34 -0
  105. fusion_artifacts_engine/webui_dist/assets/wardleyDiagram-IVAIDKWA-fKoKxoZw.js +78 -0
  106. fusion_artifacts_engine/webui_dist/assets/xychartDiagram-4URNHDU4-DRVZF7Gc.js +7 -0
  107. fusion_artifacts_engine/webui_dist/favicon.svg +1 -0
  108. fusion_artifacts_engine/webui_dist/index.html +14 -0
  109. fusion_artifacts_engine-0.7.18.dist-info/METADATA +1115 -0
  110. fusion_artifacts_engine-0.7.18.dist-info/RECORD +114 -0
  111. fusion_artifacts_engine-0.7.18.dist-info/WHEEL +5 -0
  112. fusion_artifacts_engine-0.7.18.dist-info/entry_points.txt +2 -0
  113. fusion_artifacts_engine-0.7.18.dist-info/licenses/LICENSE +201 -0
  114. fusion_artifacts_engine-0.7.18.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1372 @@
1
+ import asyncio
2
+ import difflib
3
+ import hashlib
4
+ import json
5
+ import logging
6
+ import threading
7
+ import time
8
+ from pathlib import Path
9
+ from typing import ClassVar
10
+
11
+ from fusion_artifacts_engine.auto_identifier import should_create_artifact
12
+ from fusion_artifacts_engine.config import ArtifactEngineConfig
13
+ from fusion_artifacts_engine.models import (
14
+ Artifact,
15
+ ArtifactEvent,
16
+ ArtifactFolder,
17
+ ArtifactShare,
18
+ ArtifactTag,
19
+ ArtifactVersion,
20
+ infer_kind,
21
+ )
22
+ from fusion_artifacts_engine.ref_parser import generate_ref_text
23
+ from fusion_artifacts_engine.rpc.errors import ConflictError, NotFoundError, ResourceLimitError
24
+ from fusion_artifacts_engine.rpc.event_bus import EventBus
25
+ from fusion_artifacts_engine.section_index import build_sections_with_tokens as _build_secs
26
+ from fusion_artifacts_engine.section_index import delete_section as _delete_sec
27
+ from fusion_artifacts_engine.section_index import (
28
+ extract_sections,
29
+ normalize_anchor,
30
+ )
31
+ from fusion_artifacts_engine.section_index import find_section_bounds as _find_bounds
32
+ from fusion_artifacts_engine.section_index import replace_section as _replace_sec
33
+ from fusion_artifacts_engine.share import ShareManager
34
+ from fusion_artifacts_engine.storage.sqlite_storage import SQLiteStorage
35
+ from fusion_artifacts_engine.token_budget import (
36
+ check_safety as _check_safety_fn,
37
+ )
38
+ from fusion_artifacts_engine.token_budget import (
39
+ context_budget as _context_budget_fn,
40
+ )
41
+ from fusion_artifacts_engine.token_budget import (
42
+ inject as _inject_fn,
43
+ )
44
+ from fusion_artifacts_engine.token_counter import count_tokens
45
+ from fusion_artifacts_engine.utils import generate_artifact_id
46
+
47
+ logger = logging.getLogger(__name__)
48
+
49
+ _SUMMARY_MAX_LEN = 200
50
+
51
+
52
+ def _truncate_summary(content: str) -> str:
53
+ # JSON structured content truncation is a text wall, not a human summary - return empty (GUI falls back to the type icon)
54
+ if content.lstrip()[:1] in ("{", "["):
55
+ return ""
56
+ return content[:_SUMMARY_MAX_LEN].replace("\n", " ").strip()
57
+
58
+
59
+ def _auto_changelog(old_content: str, new_content: str) -> str:
60
+ # Count additions/deletions from the real line-level diff, not mere line-count arithmetic (P2-11).
61
+ old_lines = old_content.splitlines()
62
+ new_lines = new_content.splitlines()
63
+ diff_lines = list(difflib.unified_diff(old_lines, new_lines, lineterm=""))
64
+ added = sum(1 for line in diff_lines if line.startswith("+") and not line.startswith("+++"))
65
+ removed = sum(1 for line in diff_lines if line.startswith("-") and not line.startswith("---"))
66
+ parts = []
67
+ if added:
68
+ parts.append(f"+{added} lines")
69
+ if removed:
70
+ parts.append(f"-{removed} lines")
71
+ if not parts:
72
+ if old_content != new_content:
73
+ parts.append("content modified")
74
+ else:
75
+ parts.append("no change")
76
+ elif added == removed and old_content != new_content:
77
+ # Same-line-count content replacement: diff reports +n/-n; add 'content modified' to mark the replacement semantics (P2-11).
78
+ parts.append("content modified")
79
+ return ", ".join(parts)
80
+
81
+
82
+ def _size_bytes(content: str) -> int:
83
+ return len(content.encode("utf-8"))
84
+
85
+
86
+ # H3/H7: _sanitize_html / _render_share_html / _SHARE_DOC_CSP / _html_escape moved to render.py.
87
+ # _sanitize_html now uses lxml Cleaner (real HTML parse tree); regex only as a fallback when lxml is missing.
88
+
89
+
90
+ class ArtifactEngine:
91
+ def __init__(self, config: ArtifactEngineConfig | None = None):
92
+ self.config = config or ArtifactEngineConfig()
93
+ self.storage = SQLiteStorage(
94
+ db_path=self.config.db_path,
95
+ content_dir=self.config.content_dir,
96
+ small_content_limit=self.config.small_content_limit,
97
+ max_versions_per_artifact=self.config.max_versions_per_artifact,
98
+ disk_space_warning_pct=self.config.disk_space_warning_pct,
99
+ max_content_bytes=self.config.max_content_bytes,
100
+ max_metadata_bytes=self.config.max_metadata_bytes,
101
+ wal_checkpoint_interval=self.config.wal_checkpoint_interval, metadata_indexed_keys=self.config.metadata_indexed_keys,
102
+ )
103
+ # A-1/R6: _watchers is an audit-only registry, no active delivery path.
104
+ # Change notifications actually flow via EventBus -> SSE (engine.event_bus.publish). _watchers does not push,
105
+ # it only keeps a record of 'who registered' for the watch RPC. Future push features should extend EventBus,
106
+ # do NOT add delivery logic on _watchers (it would duplicate SSE pushes).
107
+ # ThreadingMixIn multi-thread rework: lock to prevent 'dict changed size during iteration' races.
108
+ self._watchers: dict[str, list[str]] = {}
109
+ self._watchers_lock = threading.Lock()
110
+ # A-2: EventBus is injected per engine instance, avoiding module-level singleton cross-engine streaming
111
+ self.event_bus = EventBus()
112
+ # H7: share access control + R2 in-memory buffering extracted to ShareManager
113
+ self.share_mgr = ShareManager(self)
114
+ # #58/#59/#60: visual engine dispatcher (DSL parsing + 8 primitives + 3-level fallback)
115
+ from fusion_artifacts_engine.visual_dispatcher import VisualEngineDispatcher
116
+ self.visual_dispatcher = VisualEngineDispatcher()
117
+ logger.info(
118
+ "ArtifactEngine initialized: storage_root=%s", self.config.storage_root
119
+ )
120
+
121
+ def _publish_disk_alarm(self, message: str) -> None:
122
+ # Ops-4: disk watermark warning event, delivered via EventBus to SSE subscribers (ops-side listening)
123
+ try:
124
+ self.event_bus.publish(
125
+ "disk_full_alarm",
126
+ {"kind": "system.alarm", "message": message, "severity": "critical"},
127
+ )
128
+ except Exception: # noqa: BLE001
129
+ logger.exception("Failed to publish disk alarm event")
130
+ logger.critical("DISK ALARM: %s", message)
131
+
132
+ def shutdown_share_buffer(self) -> None:
133
+ # H7: delegate to ShareManager.shutdown (R2 final flush prevents count loss)
134
+ self.share_mgr.shutdown()
135
+
136
+
137
+ async def create_artifact(
138
+ self,
139
+ session_id: str,
140
+ name: str,
141
+ artifact_type: str,
142
+ content: str,
143
+ summary: str = "",
144
+ change_log: str = "Initial version",
145
+ kind: str | None = None,
146
+ project_id: str | None = None,
147
+ metadata: dict | None = None,
148
+ owner_user_id: str | None = None, ownership_type: str | None = None,
149
+ ) -> tuple[Artifact, ArtifactVersion, str]:
150
+ artifact_id = generate_artifact_id(self.config.artifact_id_prefix)
151
+ now = time.time()
152
+ if not summary:
153
+ summary = _truncate_summary(content)
154
+ if kind is None:
155
+ kind = infer_kind(artifact_type)
156
+ artifact = Artifact(
157
+ id=artifact_id,
158
+ session_id=session_id,
159
+ name=name,
160
+ type=artifact_type,
161
+ kind=kind,
162
+ project_id=project_id,
163
+ metadata=metadata, current_version=1,
164
+ summary=summary,
165
+ created_at=now, updated_at=now,
166
+ owner_user_id=owner_user_id, ownership_type=ownership_type if ownership_type is not None else "free",
167
+ )
168
+ size = _size_bytes(content)
169
+ sections = extract_sections(content, artifact_type)
170
+ version = ArtifactVersion(
171
+ artifact_id=artifact_id,
172
+ version_num=1,
173
+ content=content,
174
+ size_bytes=size,
175
+ token_count=count_tokens(content),
176
+ section_index=json.dumps(sections) if sections else None,
177
+ change_log=change_log,
178
+ created_at=now,
179
+ )
180
+ # H5: offload blocking storage write to the thread pool, do not hog the event loop
181
+ # Ops-4: pre-write disk check may raise ResourceLimitError; emit the warning event then re-raise
182
+ try:
183
+ await asyncio.to_thread(self.storage.save_artifact_and_version, artifact, version)
184
+ except ResourceLimitError as e:
185
+ self._publish_disk_alarm(str(e))
186
+ raise
187
+ ref_text = generate_ref_text(artifact_id, name, artifact_type, 1, size, summary)
188
+ logger.info(
189
+ "Created artifact: %s name=%s size=%d tokens=%d sections=%d",
190
+ artifact_id,
191
+ name,
192
+ size,
193
+ version.token_count,
194
+ len(sections),
195
+ )
196
+ return artifact, version, ref_text
197
+
198
+ async def create_external_artifact(
199
+ self,
200
+ source_module: str,
201
+ workspace_id: str,
202
+ name: str,
203
+ artifact_type: str,
204
+ content: str,
205
+ workflow_run_id: str | None = None,
206
+ summary: str = "",
207
+ kind: str | None = None,
208
+ project_id: str | None = None,
209
+ metadata: dict | None = None,
210
+ ) -> tuple[Artifact, ArtifactVersion, str]:
211
+ session_id = f"ext_{source_module}_{workspace_id}"
212
+ artifact_id = generate_artifact_id(self.config.artifact_id_prefix)
213
+ now = time.time()
214
+ if not summary:
215
+ summary = _truncate_summary(content)
216
+ if kind is None:
217
+ kind = infer_kind(artifact_type)
218
+ artifact = Artifact(
219
+ id=artifact_id,
220
+ session_id=session_id,
221
+ name=name,
222
+ type=artifact_type,
223
+ kind=kind,
224
+ project_id=project_id,
225
+ metadata=metadata,
226
+ current_version=1,
227
+ summary=summary,
228
+ created_at=now,
229
+ updated_at=now,
230
+ source_module=source_module,
231
+ workspace_id=workspace_id,
232
+ workflow_run_id=workflow_run_id,
233
+ )
234
+ size = _size_bytes(content)
235
+ sections = extract_sections(content, artifact_type)
236
+ version = ArtifactVersion(
237
+ artifact_id=artifact_id,
238
+ version_num=1,
239
+ content=content,
240
+ size_bytes=size,
241
+ token_count=count_tokens(content),
242
+ section_index=json.dumps(sections) if sections else None,
243
+ change_log="Created by external module",
244
+ created_at=now,
245
+ )
246
+ # H5: offload blocking storage write to the thread pool
247
+ # Ops-4: pre-write disk check may raise ResourceLimitError; emit the warning event then re-raise
248
+ try:
249
+ await asyncio.to_thread(self.storage.save_artifact_and_version, artifact, version)
250
+ except ResourceLimitError as e:
251
+ self._publish_disk_alarm(str(e))
252
+ raise
253
+ if project_id:
254
+ await asyncio.to_thread(self.storage.move_to_project_kb, artifact_id, project_id)
255
+ artifact = self.storage.get_artifact(artifact_id)
256
+ logger.info(
257
+ "Auto-archived external artifact %s to project %s",
258
+ artifact_id,
259
+ project_id,
260
+ )
261
+ ref_text = generate_ref_text(artifact_id, name, artifact_type, 1, size, summary)
262
+ logger.info(
263
+ "Created external artifact: %s source=%s ws=%s size=%d",
264
+ artifact_id,
265
+ source_module,
266
+ workspace_id,
267
+ size,
268
+ )
269
+ return artifact, version, ref_text
270
+
271
+ def list_by_source(
272
+ self,
273
+ source_module: str,
274
+ workspace_id: str | None = None,
275
+ workflow_run_id: str | None = None,
276
+ page: int = 1,
277
+ page_size: int = 200,
278
+ ) -> list[Artifact]:
279
+ return self.storage.list_by_source(
280
+ source_module, workspace_id, workflow_run_id, page=page, page_size=page_size
281
+ )
282
+
283
+ def get_artifact(
284
+ self, artifact_id: str, project_id: str | None = None
285
+ ) -> Artifact | None:
286
+ return self.storage.get_artifact(artifact_id, project_id)
287
+
288
+ def list_artifacts(
289
+ self,
290
+ session_id: str,
291
+ include_deleted: bool = False,
292
+ project_id: str | None = None,
293
+ metadata_filter: dict | None = None,
294
+ ) -> list[Artifact]:
295
+ return self.storage.list_artifacts(
296
+ session_id, include_deleted, project_id, metadata_filter
297
+ )
298
+
299
+ def delete_artifact(
300
+ self,
301
+ artifact_id: str,
302
+ soft_delete: bool = True,
303
+ project_id: str | None = None,
304
+ ) -> bool:
305
+ return self.storage.delete_artifact(artifact_id, soft_delete, project_id)
306
+
307
+ def get_version_content(
308
+ self, artifact_id: str, version: int | None = None
309
+ ) -> ArtifactVersion | None:
310
+ artifact = self.storage.get_artifact(artifact_id)
311
+ if artifact is None:
312
+ return None
313
+ ver = version if version is not None else artifact.current_version
314
+ try:
315
+ result = self.storage.get_version(artifact_id, ver)
316
+ except FileNotFoundError as e:
317
+ logger.error("Content file missing for %s v%s: %s", artifact_id, ver, e)
318
+ return None
319
+ # section_index keeps the original JSON string (consistent with list_versions); the type is not changed in place,
320
+ # avoiding str/dict drift; callers json.loads themselves when they need a dict (P2-8).
321
+ return result
322
+
323
+ def list_versions(
324
+ self,
325
+ artifact_id: str,
326
+ page: int = 1,
327
+ page_size: int = 200,
328
+ include_content: bool = True,
329
+ ) -> list[ArtifactVersion]:
330
+ return self.storage.list_versions(
331
+ artifact_id, page=page, page_size=page_size, include_content=include_content
332
+ )
333
+
334
+ async def rollback_version(
335
+ self,
336
+ artifact_id: str,
337
+ target_version: int,
338
+ ) -> tuple[ArtifactVersion, str]:
339
+ # H5: offload blocking storage read to the thread pool
340
+ try:
341
+ target = await asyncio.to_thread(
342
+ self.storage.get_version, artifact_id, target_version
343
+ )
344
+ except FileNotFoundError as e:
345
+ logger.error(
346
+ "Content file missing for %s v%s: %s", artifact_id, target_version, e
347
+ )
348
+ raise ValueError(
349
+ f"Version content not found: {artifact_id} v{target_version}"
350
+ ) from e
351
+ if target is None:
352
+ raise ValueError(f"Version not found: {artifact_id} v{target_version}")
353
+ version, ref_text = await self.create_version(
354
+ artifact_id,
355
+ target.content,
356
+ f"Rollback to v{target_version}",
357
+ snapshot_type="rollback",
358
+ parent_version=target_version,
359
+ )
360
+ logger.info(
361
+ "Rolled back %s to v%s, new v%s (rollback-tagged, parent=%s)",
362
+ artifact_id,
363
+ target_version,
364
+ version.version_num,
365
+ target_version,
366
+ )
367
+ return version, ref_text
368
+
369
+ def should_create_artifact(self, content: str, content_type: str = "text") -> bool:
370
+ return should_create_artifact(
371
+ content,
372
+ content_type,
373
+ self.config.auto_create_threshold_lines,
374
+ self.config.auto_create_threshold_chars,
375
+ )
376
+
377
+ _LANG_EXT: ClassVar[dict[str, str]] = {
378
+ "python": "py",
379
+ "javascript": "js",
380
+ "typescript": "ts",
381
+ "html": "html",
382
+ "css": "css",
383
+ "markdown": "md",
384
+ "json": "json",
385
+ "yaml": "yaml",
386
+ "rust": "rs",
387
+ "go": "go",
388
+ "java": "java",
389
+ "c": "c",
390
+ "cpp": "cpp",
391
+ }
392
+
393
+ _EXT_LANG: ClassVar[dict[str, str]] = {v: k for k, v in _LANG_EXT.items()}
394
+
395
+ def export_code(self, artifact_id: str, language: str = "") -> dict:
396
+ artifact = self.storage.get_artifact(artifact_id)
397
+ if artifact is None:
398
+ raise ValueError(f"Artifact not found: {artifact_id}")
399
+ version = self.get_version_content(artifact_id)
400
+ if version is None:
401
+ raise ValueError(f"No content for artifact: {artifact_id}")
402
+ ext = self._LANG_EXT.get(language, "")
403
+ if not ext:
404
+ name = artifact.name.lower()
405
+ if "." in name:
406
+ ext = name.rsplit(".", 1)[-1]
407
+ language = self._EXT_LANG.get(ext, language)
408
+ else:
409
+ ext = self._LANG_EXT.get(artifact.type, "txt")
410
+ code = version.content
411
+ return {
412
+ "code": code,
413
+ "language": language,
414
+ "ext": ext,
415
+ "artifact_id": artifact_id,
416
+ "version": version.version_num,
417
+ "name": artifact.name,
418
+ }
419
+
420
+ async def import_code(
421
+ self,
422
+ session_id: str,
423
+ code: str,
424
+ language: str = "",
425
+ name: str = "",
426
+ metadata: dict | None = None,
427
+ ) -> tuple[Artifact, ArtifactVersion, str]:
428
+ meta = metadata or {}
429
+ artifact_type = "code"
430
+ ext = self._LANG_EXT.get(language, "")
431
+ if language in ("html",) or ext == "html":
432
+ artifact_type = "html"
433
+ elif language in ("javascript", "typescript") and ext in ("jsx", "tsx"):
434
+ artifact_type = "react"
435
+ if not name:
436
+ name = meta.get("filename", f"imported.{ext}" if ext else "imported.txt")
437
+ summary = meta.get("summary", _truncate_summary(code))
438
+ return await self.create_artifact(
439
+ session_id=session_id,
440
+ name=name,
441
+ artifact_type=artifact_type,
442
+ content=code,
443
+ summary=summary,
444
+ )
445
+
446
+ def register_watcher(self, artifact_id: str, watcher_id: str) -> None:
447
+ with self._watchers_lock:
448
+ if artifact_id not in self._watchers:
449
+ self._watchers[artifact_id] = []
450
+ if watcher_id not in self._watchers[artifact_id]:
451
+ self._watchers[artifact_id].append(watcher_id)
452
+ logger.info(
453
+ "Watcher registered: %s for artifact %s", watcher_id, artifact_id
454
+ )
455
+
456
+ def unregister_watcher(self, artifact_id: str, watcher_id: str) -> None:
457
+ with self._watchers_lock:
458
+ if artifact_id in self._watchers:
459
+ self._watchers[artifact_id] = [
460
+ w for w in self._watchers[artifact_id] if w != watcher_id
461
+ ]
462
+ if not self._watchers[artifact_id]:
463
+ del self._watchers[artifact_id]
464
+ logger.info(
465
+ "Watcher unregistered: %s for artifact %s", watcher_id, artifact_id
466
+ )
467
+
468
+ def get_watch_events(self, artifact_id: str, since_version: int = 0) -> list[dict]:
469
+ versions = self.storage.list_versions(artifact_id)
470
+ events = []
471
+ for v in versions:
472
+ if v.version_num > since_version:
473
+ events.append(
474
+ {
475
+ "artifact_id": artifact_id,
476
+ "version": v.version_num,
477
+ "change_log": v.change_log,
478
+ "created_at": v.created_at,
479
+ }
480
+ )
481
+ logger.debug(
482
+ "Watch events for %s since v%d: %d events",
483
+ artifact_id,
484
+ since_version,
485
+ len(events),
486
+ )
487
+ return events
488
+
489
+ def get_artifact_raw_content(self, artifact_id: str) -> dict | None:
490
+ artifact = self.storage.get_artifact(artifact_id)
491
+ if artifact is None:
492
+ return None
493
+ version = self.get_version_content(artifact_id)
494
+ if version is None:
495
+ return None
496
+ content_type_map = {
497
+ "html": "text/html",
498
+ "react": "text/html",
499
+ "markdown": "text/markdown",
500
+ "code": "text/plain",
501
+ "data": "application/json",
502
+ }
503
+ ct = content_type_map.get(artifact.type, "text/plain")
504
+ return {
505
+ "content": version.content,
506
+ "content_type": ct,
507
+ "artifact_id": artifact_id,
508
+ "version": version.version_num,
509
+ }
510
+
511
+ # ── P1: lifecycle + global repo ────────────────────────────
512
+
513
+ def rename_artifact(self, artifact_id: str, new_name: str) -> bool:
514
+ artifact = self.storage.get_artifact(artifact_id)
515
+ if artifact is None:
516
+ raise ValueError(f"Artifact not found: {artifact_id}")
517
+ ok = self.storage.rename_artifact(artifact_id, new_name)
518
+ logger.info("Renamed artifact %s -> %s ok=%s", artifact_id, new_name, ok)
519
+ return ok
520
+
521
+ def star_artifact(self, artifact_id: str, starred: bool = True) -> bool:
522
+ artifact = self.storage.get_artifact(artifact_id)
523
+ if artifact is None:
524
+ raise ValueError(f"Artifact not found: {artifact_id}")
525
+ ok = self.storage.star_artifact(artifact_id, starred)
526
+ logger.info("Star artifact %s starred=%s ok=%s", artifact_id, starred, ok)
527
+ return ok
528
+
529
+ def pin_artifact(
530
+ self, artifact_id: str, chat_id: str | None = None, pinned: bool = True
531
+ ) -> bool:
532
+ artifact = self.storage.get_artifact(artifact_id)
533
+ if artifact is None:
534
+ raise ValueError(f"Artifact not found: {artifact_id}")
535
+ ok = self.storage.pin_artifact(artifact_id, chat_id, pinned)
536
+ logger.info(
537
+ "Pin artifact %s pinned=%s chat=%s ok=%s", artifact_id, pinned, chat_id, ok
538
+ )
539
+ return ok
540
+
541
+ def duplicate_artifact(
542
+ self, artifact_id: str, new_name: str | None = None
543
+ ) -> Artifact | None:
544
+ artifact = self.storage.get_artifact(artifact_id)
545
+ if artifact is None:
546
+ raise ValueError(f"Artifact not found: {artifact_id}")
547
+ new_id = generate_artifact_id(self.config.artifact_id_prefix)
548
+ dup = self.storage.duplicate_artifact(artifact_id, new_id, new_name)
549
+ logger.info("Duplicated artifact %s -> %s", artifact_id, new_id)
550
+ return dup
551
+
552
+ def list_all_artifacts(
553
+ self,
554
+ filters: dict | None = None,
555
+ sort: str = "updated_at",
556
+ page: int = 1,
557
+ page_size: int = 20, cursor: str | None = None,
558
+ ) -> tuple[list[Artifact], int]:
559
+ artifacts, total = self.storage.list_all_artifacts(
560
+ filters, sort, page, page_size, cursor
561
+ )
562
+ logger.info("list_all_artifacts: %d/%d page=%s", len(artifacts), total, page)
563
+ return artifacts, total
564
+
565
+ # ── P1: recycle bin ────────────────────────────────────────
566
+
567
+ def list_recycle(
568
+ self, page: int = 1, page_size: int = 20
569
+ ) -> tuple[list[Artifact], int]:
570
+ artifacts, total = self.storage.list_recycle(page, page_size)
571
+ logger.info("list_recycle: %d/%d page=%s", len(artifacts), total, page)
572
+ return artifacts, total
573
+
574
+ def restore_artifact(self, artifact_id: str) -> bool:
575
+ ok = self.storage.restore_artifact(artifact_id)
576
+ logger.info("Restored artifact %s ok=%s", artifact_id, ok)
577
+ return ok
578
+
579
+ def purge_expired(self) -> int:
580
+ retention_days = getattr(self.config, "recycle_retention_days", 7)
581
+ count = self.storage.purge_expired(retention_days)
582
+ logger.info(
583
+ "Purged %d expired artifacts (retention=%d days)", count, retention_days
584
+ )
585
+ return count
586
+
587
+ # ── P1: optimistic lock ────────────────────────────────────
588
+
589
+ async def create_version(
590
+ self,
591
+ artifact_id: str,
592
+ content: str,
593
+ change_log: str = "",
594
+ source: str = "manual",
595
+ expected_content_hash: str | None = None,
596
+ snapshot_type: str = "auto",
597
+ parent_version: int | None = None,
598
+ ) -> tuple[ArtifactVersion, str]:
599
+ # H5: offload blocking storage read to the thread pool
600
+ artifact = await asyncio.to_thread(self.storage.get_artifact, artifact_id)
601
+ if artifact is None:
602
+ raise ValueError(f"Artifact not found: {artifact_id}")
603
+ if not change_log:
604
+ old = await asyncio.to_thread(
605
+ self.storage.get_version, artifact_id, artifact.current_version
606
+ )
607
+ change_log = _auto_changelog(old.content if old else "", content)
608
+ now = time.time()
609
+ size = _size_bytes(content)
610
+ sections = extract_sections(content, artifact.type)
611
+ # C-8: version_num is allocated inside the transaction by the atomic storage method; 0 is a placeholder here
612
+ version = ArtifactVersion(
613
+ artifact_id=artifact_id,
614
+ version_num=0,
615
+ content=content,
616
+ size_bytes=size,
617
+ token_count=count_tokens(content),
618
+ section_index=json.dumps(sections) if sections else None,
619
+ change_log=change_log,
620
+ source=source,
621
+ created_at=now,
622
+ snapshot_type=snapshot_type,
623
+ parent_version=parent_version,
624
+ )
625
+ # L-8: the rollback content_hash collides when identical to the historical version content - optimistic-lock callers
626
+ # cannot distinguish 'rolled back to vN' from 'still on vN'. Add a marker prefix before hashing the rollback version
627
+ # so its hash differs from the original version hash, removing the lock ambiguity.
628
+ hash_input = content
629
+ if snapshot_type == "rollback":
630
+ hash_input = f"rollback:{parent_version}:{content}"
631
+ content_hash = hashlib.sha256(hash_input.encode("utf-8")).hexdigest()[:16]
632
+ summary = _truncate_summary(content) if not artifact.summary else None
633
+ # C-8: validate + allocate + write atomically; BEGIN IMMEDIATE serializes concurrent writes
634
+ # H5: offload the atomic write to the thread pool
635
+ # Ops-4: pre-write disk check may raise ResourceLimitError; emit the warning event then re-raise
636
+ try:
637
+ new_version = await asyncio.to_thread(
638
+ self.storage.create_version_atomic,
639
+ artifact,
640
+ version,
641
+ content_hash,
642
+ summary,
643
+ expected_content_hash=expected_content_hash,
644
+ )
645
+ except ResourceLimitError as e:
646
+ self._publish_disk_alarm(str(e))
647
+ raise
648
+ ref_text = generate_ref_text(
649
+ artifact_id,
650
+ artifact.name,
651
+ artifact.type,
652
+ new_version,
653
+ size,
654
+ artifact.summary,
655
+ )
656
+ logger.info(
657
+ "Created version: %s v%s size=%d tokens=%d sections=%d hash=%s",
658
+ artifact_id,
659
+ new_version,
660
+ size,
661
+ version.token_count,
662
+ len(sections),
663
+ content_hash,
664
+ )
665
+ return version, ref_text
666
+
667
+ # ── P1: share ──────────────────────────────────────────────
668
+
669
+ def create_share(
670
+ self, artifact_id: str, created_by: str | None = None,
671
+ expires_at: str | None = None, max_accesses: int | None = None,
672
+ permission: str = "view",
673
+ ) -> ArtifactShare:
674
+ # H7: delegate to ShareManager
675
+ return self.share_mgr.create_share(
676
+ artifact_id, created_by, expires_at, max_accesses, permission
677
+ )
678
+
679
+ def remix_artifact(
680
+ self, artifact_id: str, new_name: str | None = None
681
+ ) -> Artifact | None:
682
+ # #77: remix derived copy - duplicate the current version as an independent artifact; parent_artifact_id records lineage
683
+ art = self.storage.get_artifact(artifact_id)
684
+ if art is None:
685
+ raise ValueError(f"Artifact not found: {artifact_id}")
686
+ logger.info("Remixing artifact %s", artifact_id)
687
+ return self.storage.duplicate_artifact(
688
+ artifact_id,
689
+ generate_artifact_id(self.config.artifact_id_prefix),
690
+ new_name or f"{art.name} (remix)",
691
+ parent_artifact_id=artifact_id,
692
+ )
693
+
694
+ def get_shared_artifact(self, share_id: str) -> dict | None:
695
+ # H7: delegate to ShareManager
696
+ return self.share_mgr.get_shared_artifact(share_id)
697
+
698
+ def revoke_share(self, share_id: str) -> bool:
699
+ # H7: delegate to ShareManager
700
+ return self.share_mgr.revoke_share(share_id)
701
+
702
+ def get_public_share(self, share_id: str) -> dict:
703
+ # H7: delegate to ShareManager
704
+ return self.share_mgr.get_public_share(share_id)
705
+
706
+ # ── P2: snapshots ──────────────────────────────────────────
707
+
708
+ async def create_snapshot(
709
+ self,
710
+ artifact_id: str,
711
+ label: str | None = None,
712
+ author: str | None = None,
713
+ ) -> ArtifactVersion:
714
+ # H5: offload blocking storage read/write to the thread pool
715
+ artifact = await asyncio.to_thread(self.storage.get_artifact, artifact_id)
716
+ if artifact is None:
717
+ raise ValueError(f"Artifact not found: {artifact_id}")
718
+ current = await asyncio.to_thread(
719
+ self.storage.get_version, artifact_id, artifact.current_version
720
+ )
721
+ if current is None:
722
+ raise ValueError(f"No current version for artifact: {artifact_id}")
723
+ new_ver_num = self.storage.next_version_num(artifact_id)
724
+ now = time.time()
725
+ snapshot_content = current.content
726
+ snapshot_size = _size_bytes(snapshot_content)
727
+ snapshot_sections = extract_sections(snapshot_content, artifact.type)
728
+ snapshot = ArtifactVersion(
729
+ artifact_id=artifact_id,
730
+ version_num=new_ver_num,
731
+ content=snapshot_content,
732
+ size_bytes=snapshot_size,
733
+ token_count=count_tokens(snapshot_content),
734
+ section_index=json.dumps(snapshot_sections) if snapshot_sections else None,
735
+ change_log=f"Snapshot: {label}" if label else "Snapshot",
736
+ source="manual",
737
+ created_at=now,
738
+ snapshot_type="named",
739
+ snapshot_label=label,
740
+ author=author,
741
+ parent_version=artifact.current_version,
742
+ )
743
+ await asyncio.to_thread(self.storage.save_version, snapshot)
744
+ artifact.current_version = new_ver_num
745
+ artifact.updated_at = now
746
+ await asyncio.to_thread(self.storage.save_artifact, artifact)
747
+ logger.info(
748
+ "Created snapshot: %s v%d label=%s", artifact_id, new_ver_num, label
749
+ )
750
+ return snapshot
751
+
752
+ def list_snapshots(
753
+ self,
754
+ artifact_id: str,
755
+ page: int = 1,
756
+ page_size: int = 200,
757
+ include_content: bool = True,
758
+ ) -> list[ArtifactVersion]:
759
+ return self.storage.list_snapshots(
760
+ artifact_id, page=page, page_size=page_size, include_content=include_content
761
+ )
762
+
763
+ # ── P2: folders ────────────────────────────────────────────
764
+
765
+ def create_folder(
766
+ self,
767
+ name: str,
768
+ parent_id: str | None = None,
769
+ project_id: str | None = None,
770
+ ) -> ArtifactFolder:
771
+ import uuid
772
+
773
+ folder_id = f"fld_{uuid.uuid4().hex[:12]}"
774
+ # E1: created_at uses float epoch, consistent with Artifact/Version
775
+ folder = ArtifactFolder(
776
+ folder_id=folder_id,
777
+ name=name,
778
+ parent_id=parent_id,
779
+ project_id=project_id,
780
+ created_at=time.time(),
781
+ )
782
+ self.storage.save_folder(folder)
783
+ logger.info("Created folder: %s name=%s", folder_id, name)
784
+ return folder
785
+
786
+ def list_folders(self, project_id: str | None = None) -> list[ArtifactFolder]:
787
+ return self.storage.list_folders(project_id)
788
+
789
+ def rename_folder(self, folder_id: str, new_name: str) -> bool:
790
+ ok = self.storage.rename_folder(folder_id, new_name)
791
+ logger.info("Renamed folder %s -> %s ok=%s", folder_id, new_name, ok)
792
+ return ok
793
+
794
+ def delete_folder(self, folder_id: str) -> bool:
795
+ ok = self.storage.delete_folder(folder_id)
796
+ logger.info("Deleted folder %s ok=%s", folder_id, ok)
797
+ return ok
798
+
799
+ def move_to_folder(self, artifact_id: str, folder_id: str | None = None) -> bool:
800
+ ok = self.storage.move_to_folder(artifact_id, folder_id)
801
+ logger.info("Moved artifact %s to folder %s ok=%s", artifact_id, folder_id, ok)
802
+ return ok
803
+
804
+ # ── P4: tags ───────────────────────────────────────────────
805
+
806
+ @staticmethod
807
+ def _tag_scope(artifact: "Artifact") -> str | None:
808
+ # L-7: tag scope prefers session_id, then project_id; None (global) when neither is present
809
+ if artifact.session_id:
810
+ return artifact.session_id
811
+ if artifact.project_id:
812
+ return artifact.project_id
813
+ return None
814
+
815
+ def add_tag(
816
+ self, artifact_id: str, tag_name: str, color: str | None = None
817
+ ) -> ArtifactTag:
818
+ import uuid
819
+
820
+ artifact = self.storage.get_artifact(artifact_id)
821
+ if artifact is None:
822
+ raise ValueError(f"Artifact not found: {artifact_id}")
823
+ scope = self._tag_scope(artifact)
824
+ existing = self.storage.get_tag_by_name(tag_name, scope)
825
+ if existing:
826
+ tag = existing
827
+ else:
828
+ tag_id = f"tag_{uuid.uuid4().hex[:12]}"
829
+ tag = ArtifactTag(tag_id=tag_id, name=tag_name, color=color, scope=scope)
830
+ self.storage.save_tag(tag)
831
+ logger.info("Created tag: %s name=%s scope=%s", tag_id, tag_name, scope)
832
+ self.storage.add_artifact_tag(artifact_id, tag.tag_id)
833
+ logger.info("Added tag %s to artifact %s", tag.tag_id, artifact_id)
834
+ return tag
835
+
836
+ def remove_tag(self, artifact_id: str, tag_name: str) -> bool:
837
+ artifact = self.storage.get_artifact(artifact_id)
838
+ scope = self._tag_scope(artifact) if artifact else None
839
+ tag = self.storage.get_tag_by_name(tag_name, scope)
840
+ if tag is None:
841
+ logger.warning("Tag not found: %s scope=%s", tag_name, scope)
842
+ return False
843
+ ok = self.storage.remove_artifact_tag(artifact_id, tag.tag_id)
844
+ logger.info("Removed tag %s from artifact %s ok=%s", tag_name, artifact_id, ok)
845
+ return ok
846
+
847
+ def list_tags(self, scope: str | None = None) -> list[ArtifactTag]:
848
+ return self.storage.list_tags(scope)
849
+
850
+ def list_artifact_tags(self, artifact_id: str) -> list[ArtifactTag]:
851
+ return self.storage.list_artifact_tags(artifact_id)
852
+
853
+ # ── P4: events ─────────────────────────────────────────────
854
+
855
+ def emit_event(
856
+ self,
857
+ event_type: str,
858
+ artifact_id: str | None = None,
859
+ session_id: str | None = None,
860
+ payload: dict | None = None,
861
+ ) -> ArtifactEvent:
862
+ import time as _time
863
+ import uuid
864
+
865
+ event_id = f"evt_{uuid.uuid4().hex[:12]}"
866
+ now_ts = _time.time()
867
+ # P0-5/H6: enforce the emit_event payload byte limit; reject oversized writes to prevent event-bus amplification
868
+ if payload is not None:
869
+ import json as _json
870
+
871
+ payload_size = len(_json.dumps(payload, ensure_ascii=False).encode("utf-8"))
872
+ limit = self.config.max_event_payload_bytes
873
+ if limit > 0 and payload_size > limit:
874
+ logger.warning(
875
+ "Event payload rejected: %d bytes > max_event_payload_bytes %d (type=%s)",
876
+ payload_size, limit, event_type,
877
+ )
878
+ raise ResourceLimitError(
879
+ f"Event payload too large: {payload_size} bytes exceeds "
880
+ f"max_event_payload_bytes {limit}"
881
+ )
882
+ event = ArtifactEvent(
883
+ event_id=event_id,
884
+ artifact_id=artifact_id,
885
+ session_id=session_id,
886
+ event_type=event_type,
887
+ payload=payload,
888
+ created_at=now_ts,
889
+ )
890
+ self.storage.save_event(event)
891
+ logger.info(
892
+ "Emitted event: %s type=%s artifact=%s", event_id, event_type, artifact_id
893
+ )
894
+ return event
895
+
896
+ def list_events(
897
+ self,
898
+ artifact_id: str | None = None,
899
+ session_id: str | None = None,
900
+ since_ts: str | None = None,
901
+ page: int = 1,
902
+ page_size: int = 50,
903
+ ) -> tuple[list[ArtifactEvent], int]:
904
+ events, total = self.storage.list_events(
905
+ artifact_id, session_id, since_ts, page, page_size
906
+ )
907
+ logger.info("list_events: %d/%d page=%s", len(events), total, page)
908
+ return events, total
909
+
910
+ # ── P3: project KB ─────────────────────────────────────────
911
+
912
+ def move_to_project_kb(self, artifact_id: str, project_id: str) -> bool:
913
+ artifact = self.storage.get_artifact(artifact_id)
914
+ if artifact is None:
915
+ raise ValueError(f"Artifact not found: {artifact_id}")
916
+ ok = self.storage.move_to_project_kb(artifact_id, project_id)
917
+ logger.info(
918
+ "Moved artifact %s to project_kb project=%s ok=%s",
919
+ artifact_id,
920
+ project_id,
921
+ ok,
922
+ )
923
+ return ok
924
+
925
+ # ── AE-1: patch_artifact ───────────────────────────────────
926
+
927
+ async def patch_artifact(
928
+ self,
929
+ artifact_id: str,
930
+ operation: str,
931
+ anchor: str = "",
932
+ content: str = "",
933
+ expected_version: int | None = None,
934
+ ) -> tuple[ArtifactVersion, dict]:
935
+ # H5: offload blocking storage read to the thread pool
936
+ artifact = await asyncio.to_thread(self.storage.get_artifact, artifact_id)
937
+ if artifact is None:
938
+ raise NotFoundError(f"Artifact not found: {artifact_id}")
939
+ if (
940
+ expected_version is not None
941
+ and artifact.current_version != expected_version
942
+ ):
943
+ # P0-2: optimistic-lock conflict maps to ConflictError(-32002, retryable).
944
+ raise ConflictError(
945
+ f"Optimistic lock failed: expected version {expected_version}, "
946
+ f"got {artifact.current_version}"
947
+ )
948
+ current = await asyncio.to_thread(
949
+ self.storage.get_version, artifact_id, artifact.current_version
950
+ )
951
+ if current is None:
952
+ raise NotFoundError(f"No current version for artifact: {artifact_id}")
953
+ old_content = current.content
954
+ old_tokens = current.token_count
955
+
956
+ if operation == "replace_section":
957
+ if not anchor:
958
+ raise ValueError("anchor is required for replace_section")
959
+ # H7: section patch extracted to the section_index module
960
+ new_content, replaced_content = _replace_sec(
961
+ old_content, anchor, content, artifact.type
962
+ )
963
+ elif operation == "append":
964
+ new_content = old_content + content
965
+ replaced_content = ""
966
+ elif operation == "prepend":
967
+ new_content = content + old_content
968
+ replaced_content = ""
969
+ elif operation == "delete_section":
970
+ if not anchor:
971
+ raise ValueError("anchor is required for delete_section")
972
+ # H7: section patch extracted to the section_index module
973
+ new_content, replaced_content = _delete_sec(
974
+ old_content, anchor, artifact.type
975
+ )
976
+ else:
977
+ raise ValueError(f"Unknown operation: {operation}")
978
+
979
+ version, _ref_text = await self.create_version(
980
+ artifact_id, new_content, f"patch:{operation} anchor={anchor}"
981
+ )
982
+ # F3: reuse version.token_count (already counted in create_version); avoid re-encoding new_content
983
+ new_tokens = version.token_count
984
+ replaced_tokens = count_tokens(replaced_content)
985
+ tokens_added = new_tokens - old_tokens + replaced_tokens
986
+ tokens_removed = replaced_tokens
987
+ tokens_net = tokens_added - tokens_removed
988
+ patch_info = {
989
+ "artifact_id": artifact_id,
990
+ "new_version": version.version_num,
991
+ "tokens_added": tokens_added,
992
+ "tokens_removed": tokens_removed,
993
+ "tokens_net": tokens_net,
994
+ }
995
+ logger.info(
996
+ "Patched artifact %s op=%s anchor=%s new_v=%d net_tokens=%d",
997
+ artifact_id,
998
+ operation,
999
+ anchor,
1000
+ version.version_num,
1001
+ tokens_net,
1002
+ )
1003
+ return version, patch_info
1004
+
1005
+ # ── AE-2: load_artifact ────────────────────────────────────
1006
+
1007
+ def load_artifact(
1008
+ self,
1009
+ artifact_id: str,
1010
+ preview_only: bool = True,
1011
+ section: str | None = None,
1012
+ ) -> dict:
1013
+ artifact = self.storage.get_artifact(artifact_id)
1014
+ if artifact is None:
1015
+ raise ValueError(f"Artifact not found: {artifact_id}")
1016
+ version = self.get_version_content(artifact_id)
1017
+ if version is None:
1018
+ raise ValueError(f"No version found for artifact: {artifact_id}")
1019
+
1020
+ # H7: section build/lookup extracted to the section_index module
1021
+ sections = _build_secs(version.content, artifact.type)
1022
+
1023
+ result: dict = {
1024
+ "artifact_id": artifact_id,
1025
+ "title": artifact.name,
1026
+ "type": artifact.type,
1027
+ "version": version.version_num,
1028
+ "total_tokens": version.token_count,
1029
+ "sections": sections,
1030
+ "summary": artifact.summary or "",
1031
+ }
1032
+
1033
+ if section:
1034
+ section = normalize_anchor(section)
1035
+ matches = _find_bounds(version.content, section, artifact.type)
1036
+ if not matches:
1037
+ raise ValueError(f"Section '{section}' not found in content")
1038
+ if len(matches) > 1:
1039
+ raise ValueError(
1040
+ f"Multiple matches for section '{section}': "
1041
+ f"found at lines {[m[0] + 1 for m in matches]}"
1042
+ )
1043
+ lines = version.content.split("\n")
1044
+ start, end, _ = matches[0]
1045
+ sec_content = "\n".join(lines[start:end])
1046
+ sec_tokens = count_tokens(sec_content)
1047
+ matched_anchor = section
1048
+ for s in sections:
1049
+ if s["anchor"].strip() == section:
1050
+ matched_anchor = s["anchor"]
1051
+ break
1052
+ result["section"] = {"anchor": matched_anchor, "tokens": sec_tokens}
1053
+ result["content"] = sec_content
1054
+ elif preview_only:
1055
+ result["content"] = None
1056
+ else:
1057
+ result["content"] = version.content
1058
+
1059
+ logger.info(
1060
+ "Loaded artifact %s preview=%s section=%s sections=%d",
1061
+ artifact_id,
1062
+ preview_only,
1063
+ section,
1064
+ len(sections),
1065
+ )
1066
+ return result
1067
+
1068
+ # ── AE-6: context_budget ───────────────────────────────────
1069
+
1070
+ def context_budget(
1071
+ self,
1072
+ session_id: str | None = None,
1073
+ context_window: int | None = None,
1074
+ ) -> dict:
1075
+ # H7: token budget logic extracted to the token_budget module
1076
+ return _context_budget_fn(self.config, self.storage, session_id, context_window)
1077
+
1078
+ # ── AE-7: auto_compact ─────────────────────────────────────
1079
+
1080
+ async def auto_compact(self, artifact_id: str, token_budget: int) -> dict:
1081
+ from fusion_artifacts_engine.compactor import compact_and_count
1082
+
1083
+ # H5: offload blocking storage read to the thread pool
1084
+ artifact = await asyncio.to_thread(self.storage.get_artifact, artifact_id)
1085
+ if artifact is None:
1086
+ raise ValueError(f"Artifact not found: {artifact_id}")
1087
+ version = self.get_version_content(artifact_id)
1088
+ if version is None:
1089
+ raise ValueError(f"No version found for artifact: {artifact_id}")
1090
+
1091
+ original_tokens = version.token_count
1092
+ if original_tokens <= token_budget:
1093
+ logger.info(
1094
+ "Artifact %s already within budget: %d <= %d",
1095
+ artifact_id,
1096
+ original_tokens,
1097
+ token_budget,
1098
+ )
1099
+ return {
1100
+ "version": version.model_dump(),
1101
+ "original_tokens": original_tokens,
1102
+ "compacted_tokens": original_tokens,
1103
+ "savings_pct": 0.0,
1104
+ "compacted": False,
1105
+ "reason": "already_within_budget",
1106
+ }
1107
+
1108
+ # F3: offload large-content compress+count to the thread pool, avoid blocking the event loop
1109
+ compacted_content, compacted_tokens = await asyncio.to_thread(compact_and_count, version.content, artifact.type, token_budget)
1110
+
1111
+ if compacted_tokens < original_tokens:
1112
+ version, _ = await self.create_version(
1113
+ artifact_id,
1114
+ compacted_content,
1115
+ change_log=f"auto_compact: {original_tokens} -> {compacted_tokens} tokens (budget={token_budget})",
1116
+ source="ai_generation",
1117
+ )
1118
+ savings = round(
1119
+ (original_tokens - compacted_tokens) / original_tokens * 100, 1
1120
+ )
1121
+ logger.info(
1122
+ "Auto-compacted %s: %d -> %d tokens (%.1f%% savings)",
1123
+ artifact_id,
1124
+ original_tokens,
1125
+ compacted_tokens,
1126
+ savings,
1127
+ )
1128
+ return {
1129
+ "version": version.model_dump(),
1130
+ "original_tokens": original_tokens,
1131
+ "compacted_tokens": compacted_tokens,
1132
+ "savings_pct": savings,
1133
+ "compacted": True,
1134
+ }
1135
+
1136
+ logger.warning(
1137
+ "Auto-compact could not reduce %s below budget %d",
1138
+ artifact_id,
1139
+ token_budget,
1140
+ )
1141
+ return {
1142
+ "version": version.model_dump(),
1143
+ "original_tokens": original_tokens,
1144
+ "compacted_tokens": compacted_tokens,
1145
+ "savings_pct": 0.0,
1146
+ "compacted": False,
1147
+ "reason": "could_not_reduce",
1148
+ }
1149
+
1150
+ # ── #36: version_diff ───────────────────────────────────────
1151
+
1152
+ def version_diff(
1153
+ self, artifact_id: str, from_version: int, to_version: int
1154
+ ) -> dict:
1155
+ artifact = self.storage.get_artifact(artifact_id)
1156
+ if artifact is None:
1157
+ raise ValueError(f"Artifact not found: {artifact_id}")
1158
+ from_ver = self.storage.get_version(artifact_id, from_version)
1159
+ if from_ver is None:
1160
+ raise ValueError(
1161
+ f"Version {from_version} not found for artifact: {artifact_id}"
1162
+ )
1163
+ to_ver = self.storage.get_version(artifact_id, to_version)
1164
+ if to_ver is None:
1165
+ raise ValueError(
1166
+ f"Version {to_version} not found for artifact: {artifact_id}"
1167
+ )
1168
+ from_lines = from_ver.content.splitlines(keepends=True)
1169
+ to_lines = to_ver.content.splitlines(keepends=True)
1170
+ diff_lines = list(
1171
+ difflib.unified_diff(
1172
+ from_lines,
1173
+ to_lines,
1174
+ fromfile=f"v{from_version}",
1175
+ tofile=f"v{to_version}",
1176
+ )
1177
+ )
1178
+ diff_text = "".join(diff_lines)
1179
+ lines_added = sum(1 for dl in diff_lines if dl.startswith("+") and not dl.startswith("+++"))
1180
+ lines_removed = sum(1 for dl in diff_lines if dl.startswith("-") and not dl.startswith("---"))
1181
+ logger.info(
1182
+ "Version diff %s v%d->v%d: +%d -%d lines",
1183
+ artifact_id,
1184
+ from_version,
1185
+ to_version,
1186
+ lines_added,
1187
+ lines_removed,
1188
+ )
1189
+ return {
1190
+ "diff": diff_text,
1191
+ "lines_added": lines_added,
1192
+ "lines_removed": lines_removed,
1193
+ }
1194
+
1195
+ # ── #37: render / check_safety / inject / interact / sync ───
1196
+
1197
+ async def render_artifact(
1198
+ self,
1199
+ content: str,
1200
+ session_id: str,
1201
+ lang_hint: str = "",
1202
+ project_id: str | None = None,
1203
+ ) -> dict:
1204
+ # Boundary note: this method performs no browser rendering; it only does (1) threshold check (2) type detection
1205
+ # (3) stores as artifact (4) returns the render_type hint + raw content.
1206
+ # Browser rendering is the responsibility of the caller (fusion-studio); for server-side rendering see
1207
+ # _render_share_html (public share read-only preview, implemented in render.py).
1208
+ from fusion_artifacts_engine.auto_identifier import (
1209
+ detect_artifact_type,
1210
+ detect_renderable_type,
1211
+ extract_name_hint,
1212
+ should_create_artifact,
1213
+ )
1214
+
1215
+ if not content:
1216
+ logger.info("render_artifact: empty content, skipping")
1217
+ return {"created": False, "reason": "empty_content"}
1218
+ if not should_create_artifact(content, content_type="text"):
1219
+ logger.info("render_artifact: content below threshold, skipping")
1220
+ return {"created": False, "reason": "below_threshold"}
1221
+ try:
1222
+ name = extract_name_hint(content, lang_hint)
1223
+ artifact_type = detect_artifact_type(name, content)
1224
+ render_type = detect_renderable_type(content, name) or artifact_type
1225
+ renderable_types = {"html", "react", "markdown", "svg", "mermaid"}
1226
+ is_renderable = render_type in renderable_types
1227
+ artifact, _version, ref_text = await self.create_artifact(
1228
+ session_id=session_id,
1229
+ name=name,
1230
+ artifact_type=artifact_type,
1231
+ content=content,
1232
+ summary=_truncate_summary(content),
1233
+ change_log="Created via artifact.render",
1234
+ project_id=project_id,
1235
+ )
1236
+ logger.info(
1237
+ "render_artifact: created %s type=%s render_type=%s renderable=%s",
1238
+ artifact.id,
1239
+ artifact_type,
1240
+ render_type,
1241
+ is_renderable,
1242
+ )
1243
+ return {
1244
+ "created": True,
1245
+ "artifact": artifact.model_dump(),
1246
+ "render_type": render_type if is_renderable else None,
1247
+ "content": content,
1248
+ "ref_text": ref_text,
1249
+ }
1250
+ except Exception as e:
1251
+ logger.exception("render_artifact failed")
1252
+ return {"created": False, "reason": str(e)}
1253
+
1254
+ def render_visual(self, raw_text: str | None = None, dsl: dict | None = None, progress: float = 1.0) -> dict:
1255
+ # #58/#59/#60: delegate to VisualEngineDispatcher.render (H7: engine stays a thin wrapper, logic lives in visual_dispatcher.py).
1256
+ return self.visual_dispatcher.render(raw_text=raw_text, dsl=dsl, progress=progress)
1257
+
1258
+ def check_safety(
1259
+ self, messages: list[dict], output_budget: int | None = None
1260
+ ) -> dict:
1261
+ # H7: delegate to the token_budget module
1262
+ return _check_safety_fn(self.config, messages, output_budget)
1263
+
1264
+ def inject(
1265
+ self, messages: list[dict], output_budget: int | None = None
1266
+ ) -> dict:
1267
+ # H7: delegate to the token_budget module (R7/STUB semantics unchanged)
1268
+ return _inject_fn(self.config, messages, output_budget)
1269
+
1270
+ def interact_artifact(
1271
+ self,
1272
+ artifact_id: str,
1273
+ action: str,
1274
+ payload: dict | None = None,
1275
+ session_id: str | None = None,
1276
+ ) -> dict:
1277
+ artifact = self.storage.get_artifact(artifact_id)
1278
+ if artifact is None:
1279
+ raise ValueError(f"Artifact not found: {artifact_id}")
1280
+ event = self.emit_event(
1281
+ "artifact.interaction",
1282
+ artifact_id=artifact_id,
1283
+ session_id=session_id,
1284
+ payload={"action": action, "payload": payload or {}},
1285
+ )
1286
+ logger.info(
1287
+ "interact_artifact: %s action=%s event=%s", artifact_id, action, event.event_id
1288
+ )
1289
+ return {
1290
+ "ok": True,
1291
+ "artifact_id": artifact_id,
1292
+ "action": action,
1293
+ "event_id": event.event_id,
1294
+ "dispatched": False,
1295
+ "stub": True,
1296
+ "note": "STUB: records interaction event only, no action dispatch implemented",
1297
+ }
1298
+
1299
+ async def sync_artifact_file(
1300
+ self, artifact_id: str, file_path: str, direction: str
1301
+ ) -> dict:
1302
+ if direction not in ("artifact_to_code", "code_to_artifact"):
1303
+ raise ValueError(
1304
+ "direction must be 'artifact_to_code' or 'code_to_artifact'"
1305
+ )
1306
+ # H5: offload blocking storage read to the thread pool
1307
+ artifact = await asyncio.to_thread(self.storage.get_artifact, artifact_id)
1308
+ if artifact is None:
1309
+ raise ValueError(f"Artifact not found: {artifact_id}")
1310
+ path = Path(file_path).expanduser()
1311
+ # C-1: the path must resolve inside the configured sync_root; blocks arbitrary file write/read (LFI)
1312
+ sync_root = self.config.sync_root
1313
+ if sync_root is None:
1314
+ raise PermissionError(
1315
+ "sync_root not configured; refuse sync_artifact_file"
1316
+ )
1317
+ root_resolved = sync_root.resolve()
1318
+ try:
1319
+ target_resolved = path.resolve()
1320
+ target_resolved.relative_to(root_resolved)
1321
+ except ValueError as e:
1322
+ logger.warning(
1323
+ "sync path %s escapes sync_root %s", file_path, sync_root
1324
+ )
1325
+ raise PermissionError(
1326
+ f"file_path must be within sync_root: {file_path}"
1327
+ ) from e
1328
+ if direction == "artifact_to_code":
1329
+ version = self.get_version_content(artifact_id)
1330
+ if version is None:
1331
+ raise ValueError(f"No version found for artifact: {artifact_id}")
1332
+ path.parent.mkdir(parents=True, exist_ok=True)
1333
+ path.write_text(version.content, encoding="utf-8")
1334
+ logger.info(
1335
+ "sync_artifact_file: artifact %s -> %s (%d bytes)",
1336
+ artifact_id,
1337
+ file_path,
1338
+ len(version.content),
1339
+ )
1340
+ else:
1341
+ if not path.exists():
1342
+ raise ValueError(f"File not found: {file_path}")
1343
+ new_content = path.read_text(encoding="utf-8")
1344
+ await self.create_version(
1345
+ artifact_id, new_content, f"sync from {file_path}"
1346
+ )
1347
+ logger.info(
1348
+ "sync_artifact_file: %s -> artifact %s (%d bytes)",
1349
+ file_path,
1350
+ artifact_id,
1351
+ len(new_content),
1352
+ )
1353
+ return {
1354
+ "ok": True,
1355
+ "direction": direction,
1356
+ "artifact_id": artifact_id,
1357
+ "file_path": file_path,
1358
+ }
1359
+
1360
+ def close(self) -> None:
1361
+ # A-4: graceful shutdown - first flush the share access buffer to prevent count loss, then notify EventBus to close streams
1362
+ # so SSE handlers exit, and finally close storage, avoiding threads stuck on a closed storage handle
1363
+ try:
1364
+ self.shutdown_share_buffer()
1365
+ except Exception:
1366
+ logger.exception("share buffer flush error during close")
1367
+ try:
1368
+ self.event_bus.shutdown()
1369
+ except Exception:
1370
+ logger.exception("EventBus shutdown error during close")
1371
+ self.storage.close()
1372
+ logger.info("ArtifactEngine closed")