claude-smart 0.2.46 → 0.2.48

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 (170) hide show
  1. package/.claude-plugin/marketplace.json +1 -1
  2. package/README.md +19 -11
  3. package/bin/claude-smart.js +290 -68
  4. package/package.json +1 -1
  5. package/plugin/.claude-plugin/plugin.json +1 -1
  6. package/plugin/.codex-plugin/plugin.json +1 -1
  7. package/plugin/README.md +11 -10
  8. package/plugin/dashboard/app/layout.tsx +20 -0
  9. package/plugin/dashboard/app/sessions/[sessionId]/page.tsx +36 -2
  10. package/plugin/dashboard/package-lock.json +61 -390
  11. package/plugin/dashboard/package.json +2 -2
  12. package/plugin/opencode/dist/server.mjs +76 -2
  13. package/plugin/opencode/server.mts +79 -2
  14. package/plugin/pyproject.toml +6 -2
  15. package/plugin/scripts/smart-install.sh +7 -1
  16. package/plugin/src/claude_smart/cli.py +210 -22
  17. package/plugin/src/claude_smart/context_format.py +9 -9
  18. package/plugin/src/claude_smart/cs_cite.py +66 -19
  19. package/plugin/uv.lock +5 -5
  20. package/plugin/vendor/reflexio/.env.example +7 -0
  21. package/plugin/vendor/reflexio/README.md +3 -3
  22. package/plugin/vendor/reflexio/pyproject.toml +2 -1
  23. package/plugin/vendor/reflexio/reflexio/README.md +11 -6
  24. package/plugin/vendor/reflexio/reflexio/cli/bootstrap_config.py +1 -1
  25. package/plugin/vendor/reflexio/reflexio/cli/commands/setup_cmd.py +2 -2
  26. package/plugin/vendor/reflexio/reflexio/cli/utils.py +44 -1
  27. package/plugin/vendor/reflexio/reflexio/client/client.py +97 -0
  28. package/plugin/vendor/reflexio/reflexio/lib/_agent_playbook.py +8 -0
  29. package/plugin/vendor/reflexio/reflexio/lib/_base.py +15 -0
  30. package/plugin/vendor/reflexio/reflexio/lib/_config.py +23 -18
  31. package/plugin/vendor/reflexio/reflexio/lib/_generation.py +9 -8
  32. package/plugin/vendor/reflexio/reflexio/lib/_interactions.py +16 -1
  33. package/plugin/vendor/reflexio/reflexio/lib/_profiles.py +27 -16
  34. package/plugin/vendor/reflexio/reflexio/lib/_search.py +27 -5
  35. package/plugin/vendor/reflexio/reflexio/lib/_user_playbook.py +9 -0
  36. package/plugin/vendor/reflexio/reflexio/models/api_schema/domain/__init__.py +1 -0
  37. package/plugin/vendor/reflexio/reflexio/models/api_schema/domain/enums.py +1 -0
  38. package/plugin/vendor/reflexio/reflexio/models/api_schema/domain/governance.py +117 -0
  39. package/plugin/vendor/reflexio/reflexio/models/api_schema/retriever_schema.py +45 -3
  40. package/plugin/vendor/reflexio/reflexio/models/config_schema.py +37 -0
  41. package/plugin/vendor/reflexio/reflexio/server/README.md +38 -9
  42. package/plugin/vendor/reflexio/reflexio/server/__init__.py +21 -2
  43. package/plugin/vendor/reflexio/reflexio/server/api.py +274 -3267
  44. package/plugin/vendor/reflexio/reflexio/server/api_endpoints/README.md +4 -3
  45. package/plugin/vendor/reflexio/reflexio/server/api_endpoints/publisher_api.py +16 -1
  46. package/plugin/vendor/reflexio/reflexio/server/api_endpoints/request_context.py +1 -1
  47. package/plugin/vendor/reflexio/reflexio/server/{_auth.py → auth.py} +2 -0
  48. package/plugin/vendor/reflexio/reflexio/server/cache/reflexio_cache.py +62 -36
  49. package/plugin/vendor/reflexio/reflexio/server/deployment_profile.py +69 -0
  50. package/plugin/vendor/reflexio/reflexio/server/extensions.py +213 -0
  51. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_embedding.py +424 -0
  52. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_json_extraction.py +249 -0
  53. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_structured_output.py +195 -0
  54. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_subprocess.py +152 -0
  55. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_text_generation.py +980 -0
  56. package/plugin/vendor/reflexio/reflexio/server/llm/_litellm_types.py +110 -0
  57. package/plugin/vendor/reflexio/reflexio/server/llm/litellm_client.py +73 -1819
  58. package/plugin/vendor/reflexio/reflexio/server/llm/model_defaults.py +4 -4
  59. package/plugin/vendor/reflexio/reflexio/server/llm/providers/claude_code_provider.py +57 -5
  60. package/plugin/vendor/reflexio/reflexio/server/llm/rerank/cross_encoder_reranker.py +12 -1
  61. package/plugin/vendor/reflexio/reflexio/server/middleware.py +244 -0
  62. package/plugin/vendor/reflexio/reflexio/server/operation_limiter.py +9 -1
  63. package/plugin/vendor/reflexio/reflexio/server/prompt/prompt_bank/playbook_extraction_context/v4.4.0.prompt.md +14 -2
  64. package/plugin/vendor/reflexio/reflexio/server/rate_limit.py +79 -0
  65. package/plugin/vendor/reflexio/reflexio/server/routes/__init__.py +6 -0
  66. package/plugin/vendor/reflexio/reflexio/server/routes/_common.py +25 -0
  67. package/plugin/vendor/reflexio/reflexio/server/routes/_metering.py +98 -0
  68. package/plugin/vendor/reflexio/reflexio/server/routes/braintrust.py +129 -0
  69. package/plugin/vendor/reflexio/reflexio/server/routes/config.py +210 -0
  70. package/plugin/vendor/reflexio/reflexio/server/routes/evaluation.py +549 -0
  71. package/plugin/vendor/reflexio/reflexio/server/routes/interactions.py +259 -0
  72. package/plugin/vendor/reflexio/reflexio/server/routes/playbooks.py +578 -0
  73. package/plugin/vendor/reflexio/reflexio/server/routes/profiles.py +423 -0
  74. package/plugin/vendor/reflexio/reflexio/server/routes/provenance.py +345 -0
  75. package/plugin/vendor/reflexio/reflexio/server/routes/search.py +349 -0
  76. package/plugin/vendor/reflexio/reflexio/server/routes/system.py +261 -0
  77. package/plugin/vendor/reflexio/reflexio/server/scheduling.py +132 -0
  78. package/plugin/vendor/reflexio/reflexio/server/services/README.md +5 -2
  79. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/__init__.py +38 -0
  80. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_batch_progress.py +298 -0
  81. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_config_filter.py +152 -0
  82. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_extraction_lifecycle.py +243 -0
  83. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_should_run.py +299 -0
  84. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_status_change.py +273 -0
  85. package/plugin/vendor/reflexio/reflexio/server/services/base_generation/_usage_billing.py +258 -0
  86. package/plugin/vendor/reflexio/reflexio/server/services/base_generation_service.py +17 -1183
  87. package/plugin/vendor/reflexio/reflexio/server/services/deduplication_utils.py +8 -1
  88. package/plugin/vendor/reflexio/reflexio/server/services/extraction/resume_scheduler.py +26 -41
  89. package/plugin/vendor/reflexio/reflexio/server/services/extraction/resume_worker.py +8 -0
  90. package/plugin/vendor/reflexio/reflexio/server/services/generation_service.py +232 -123
  91. package/plugin/vendor/reflexio/reflexio/server/services/governance/config.py +52 -0
  92. package/plugin/vendor/reflexio/reflexio/server/services/governance/service.py +378 -0
  93. package/plugin/vendor/reflexio/reflexio/server/services/governance/subject_refs.py +34 -0
  94. package/plugin/vendor/reflexio/reflexio/server/services/lineage/gc_scheduler.py +385 -78
  95. package/plugin/vendor/reflexio/reflexio/server/services/playbook/README.md +9 -1
  96. package/plugin/vendor/reflexio/reflexio/server/services/playbook/aggregation_prompt_processing.py +100 -0
  97. package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator.py +121 -525
  98. package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_clustering.py +184 -0
  99. package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_postprocessing.py +130 -0
  100. package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/aggregator_prompt_formatting.py +212 -0
  101. package/plugin/vendor/reflexio/reflexio/server/services/playbook/components/consolidator.py +258 -69
  102. package/plugin/vendor/reflexio/reflexio/server/services/playbook/service.py +9 -9
  103. package/plugin/vendor/reflexio/reflexio/server/services/profile/components/extractor.py +3 -2
  104. package/plugin/vendor/reflexio/reflexio/server/services/publish_learning_worker.py +288 -0
  105. package/plugin/vendor/reflexio/reflexio/server/services/retrieval/recency.py +211 -0
  106. package/plugin/vendor/reflexio/reflexio/server/services/retrieval/relevance_floor.py +29 -13
  107. package/plugin/vendor/reflexio/reflexio/server/services/storage/error.py +4 -0
  108. package/plugin/vendor/reflexio/reflexio/server/services/storage/governance_validation.py +681 -0
  109. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/__init__.py +43 -6
  110. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_agent_run.py +10 -1167
  111. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_base.py +58 -351
  112. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_extras.py +49 -19
  113. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_governance.py +452 -0
  114. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_lineage.py +11 -4
  115. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_playbook.py +1 -2133
  116. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_profiles.py +7 -1126
  117. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_requests.py +73 -33
  118. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/_share_links.py +30 -0
  119. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/__init__.py +9 -0
  120. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_agent_run_store.py +506 -0
  121. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_pending_tool_call_store.py +704 -0
  122. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/agent_run/_run_tool_dependency_store.py +123 -0
  123. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/__init__.py +6 -0
  124. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/_deletion.py +263 -0
  125. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/base/_fts_vec.py +132 -0
  126. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/__init__.py +13 -0
  127. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_audit.py +122 -0
  128. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_erase_execution.py +465 -0
  129. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_purge.py +387 -0
  130. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_rebuild_hide.py +332 -0
  131. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/governance/_subject_barrier.py +511 -0
  132. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/__init__.py +13 -0
  133. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_agent.py +955 -0
  134. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_eval_results.py +189 -0
  135. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_optimization.py +247 -0
  136. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_source_linkage.py +145 -0
  137. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/playbook/_user.py +844 -0
  138. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/__init__.py +9 -0
  139. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_interaction_store.py +263 -0
  140. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_profile_store.py +896 -0
  141. package/plugin/vendor/reflexio/reflexio/server/services/storage/sqlite_storage/profiles/_search.py +270 -0
  142. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/__init__.py +50 -9
  143. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_agent_run.py +64 -370
  144. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_extras.py +4 -4
  145. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_playbook.py +0 -909
  146. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_requests.py +2 -0
  147. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/_share_links.py +20 -0
  148. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/__init__.py +9 -0
  149. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_agent_run_store.py +86 -0
  150. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_models.py +195 -0
  151. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_pending_tool_call_store.py +148 -0
  152. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/agent_run/_run_tool_dependency_store.py +38 -0
  153. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/__init__.py +13 -0
  154. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_audit.py +29 -0
  155. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_erase_execution.py +30 -0
  156. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_purge.py +74 -0
  157. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_rebuild_hide.py +32 -0
  158. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/governance/_subject_barrier.py +49 -0
  159. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/__init__.py +13 -0
  160. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/_agent.py +365 -0
  161. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/_eval_results.py +124 -0
  162. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/_optimization.py +85 -0
  163. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/_source_linkage.py +47 -0
  164. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/playbook/_user.py +333 -0
  165. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/__init__.py +9 -0
  166. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/_interaction_store.py +73 -0
  167. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/{_profiles.py → profiles/_profile_store.py} +57 -86
  168. package/plugin/vendor/reflexio/reflexio/server/services/storage/storage_base/profiles/_search.py +32 -0
  169. package/plugin/vendor/reflexio/reflexio/server/services/unified_search_service.py +153 -12
  170. package/plugin/vendor/reflexio/reflexio/server/services/playbook/user_detail_stripping.py +0 -84
@@ -0,0 +1,955 @@
1
+ """Agent playbook CRUD + search methods for SQLite storage."""
2
+
3
+ import json
4
+ import logging
5
+ import sqlite3
6
+ import uuid
7
+ from concurrent.futures import ThreadPoolExecutor
8
+ from typing import Any
9
+
10
+ logger = logging.getLogger(__name__)
11
+
12
+ from reflexio.models.api_schema.common import BlockingIssue
13
+ from reflexio.models.api_schema.retriever_schema import (
14
+ SearchAgentPlaybookRequest,
15
+ )
16
+ from reflexio.models.api_schema.service_schemas import (
17
+ AgentPlaybook,
18
+ PlaybookStatus,
19
+ Status,
20
+ )
21
+ from reflexio.models.config_schema import SearchMode, SearchOptions
22
+ from reflexio.server.services.storage.storage_base._playbook import (
23
+ AGGREGATE_REASON_PREFIX,
24
+ )
25
+
26
+ from .._base import (
27
+ _TOMBSTONE_STATUS_VALUES,
28
+ SQLiteStorageBase,
29
+ _build_status_sql,
30
+ _effective_search_mode,
31
+ _epoch_now,
32
+ _epoch_to_iso,
33
+ _json_dumps,
34
+ _row_to_agent_playbook,
35
+ _sanitize_fts_query,
36
+ _true_rrf_merge,
37
+ _vector_rank_rows,
38
+ )
39
+ from .._lineage import _append_event_stmt
40
+ from .._playbook import _build_tags_sql, _emit_hard_delete_playbook
41
+
42
+ _AGENT_PLAYBOOK_DEFAULT_EXCLUDED_STATUSES = (
43
+ *_TOMBSTONE_STATUS_VALUES,
44
+ Status.ARCHIVE_IN_PROGRESS.value,
45
+ )
46
+
47
+
48
+ def _emit_supersede_playbook(
49
+ conn: sqlite3.Connection,
50
+ *,
51
+ org_id: str,
52
+ entity_id: str,
53
+ old_status: str | None,
54
+ request_id: str,
55
+ ) -> None:
56
+ """Emit a single status_change->superseded lineage event for an agent playbook."""
57
+ _append_event_stmt(
58
+ conn,
59
+ org_id=org_id,
60
+ entity_type="agent_playbook",
61
+ entity_id=entity_id,
62
+ op="status_change",
63
+ prov="wasInvalidatedBy",
64
+ source_ids=[],
65
+ actor="aggregator",
66
+ request_id=request_id,
67
+ reason=f"{old_status or 'None'}->superseded",
68
+ from_status=old_status,
69
+ to_status=Status.SUPERSEDED.value,
70
+ status_namespace="lifecycle_status",
71
+ )
72
+
73
+
74
+ class AgentPlaybookStoreMixin:
75
+ """Mixin providing agent playbook CRUD + search for SQLite storage."""
76
+
77
+ # Type hints for instance attributes/methods provided by SQLiteStorageBase via MRO
78
+ _lock: Any
79
+ conn: sqlite3.Connection
80
+ org_id: str
81
+ _execute: Any
82
+ _fetchone: Any
83
+ _fetchall: Any
84
+ _get_embedding: Any
85
+ _should_expand_documents: Any
86
+ _expand_document: Any
87
+ _fts_upsert: Any
88
+ _vec_upsert: Any
89
+ _delete_playbook_search_rows: Any
90
+
91
+ def _index_agent_playbook_fts_vec(self, ap: AgentPlaybook) -> None:
92
+ """Update the FTS and vector indexes for a single agent playbook row.
93
+
94
+ Must be called AFTER the row's transaction has been committed. The FTS
95
+ and vec helpers self-commit, so they must never be interleaved inside a
96
+ transaction that still has pending mutations.
97
+
98
+ Args:
99
+ ap (AgentPlaybook): The already-saved playbook (``agent_playbook_id``
100
+ must be set).
101
+ """
102
+ fts_parts = [ap.trigger or "", ap.content or ""]
103
+ if ap.expanded_terms:
104
+ fts_parts.append(ap.expanded_terms)
105
+ self._fts_upsert(
106
+ "agent_playbooks_fts",
107
+ ap.agent_playbook_id,
108
+ search_text=" ".join(p for p in fts_parts if p) or "",
109
+ )
110
+ if ap.embedding:
111
+ self._vec_upsert("agent_playbooks_vec", ap.agent_playbook_id, ap.embedding)
112
+
113
+ def _insert_agent_playbook_row(
114
+ self, conn: "sqlite3.Connection", ap: AgentPlaybook, created_at_iso: str
115
+ ) -> "sqlite3.Cursor":
116
+ """Execute the agent_playbooks INSERT and populate ``ap.agent_playbook_id``.
117
+
118
+ Runs the INSERT inside the caller's connection context; does NOT commit.
119
+ The caller is responsible for committing (or rolling back) the transaction.
120
+
121
+ Args:
122
+ conn: The open SQLite connection to execute against.
123
+ ap: The playbook to insert; ``agent_playbook_id`` is set on return.
124
+ created_at_iso: ISO-8601 timestamp string for ``created_at``.
125
+
126
+ Returns:
127
+ sqlite3.Cursor: The cursor from the INSERT (``lastrowid`` is the new PK).
128
+ """
129
+ cur = conn.execute(
130
+ """INSERT INTO agent_playbooks
131
+ (playbook_name, created_at, agent_version, content,
132
+ trigger, rationale, blocking_issue,
133
+ playbook_status, playbook_metadata, embedding,
134
+ expanded_terms, tags, status,
135
+ merged_into, superseded_by)
136
+ VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)""",
137
+ (
138
+ ap.playbook_name,
139
+ created_at_iso,
140
+ ap.agent_version,
141
+ ap.content,
142
+ ap.trigger,
143
+ ap.rationale,
144
+ json.dumps(ap.blocking_issue.model_dump())
145
+ if ap.blocking_issue
146
+ else None,
147
+ ap.playbook_status.value
148
+ if isinstance(ap.playbook_status, PlaybookStatus)
149
+ else ap.playbook_status,
150
+ ap.playbook_metadata,
151
+ _json_dumps(ap.embedding),
152
+ ap.expanded_terms,
153
+ _json_dumps(ap.tags),
154
+ ap.status.value if ap.status else None,
155
+ ap.merged_into,
156
+ ap.superseded_by,
157
+ ),
158
+ )
159
+ ap.agent_playbook_id = cur.lastrowid or 0
160
+ return cur
161
+
162
+ @SQLiteStorageBase.handle_exceptions
163
+ def save_agent_playbooks(
164
+ self, agent_playbooks: list[AgentPlaybook]
165
+ ) -> list[AgentPlaybook]:
166
+ saved: list[AgentPlaybook] = []
167
+ for ap in agent_playbooks:
168
+ embedding_text = ap.trigger or ap.content
169
+ if self._should_expand_documents():
170
+ with ThreadPoolExecutor(max_workers=2) as executor:
171
+ emb_future = executor.submit(self._get_embedding, embedding_text)
172
+ exp_future = executor.submit(self._expand_document, embedding_text)
173
+ ap.embedding = emb_future.result(timeout=15)
174
+ ap.expanded_terms = exp_future.result(timeout=15)
175
+ else:
176
+ ap.embedding = self._get_embedding(embedding_text)
177
+
178
+ created_at_iso = _epoch_to_iso(ap.created_at)
179
+ with self._lock:
180
+ self._insert_agent_playbook_row(self.conn, ap, created_at_iso)
181
+ self.conn.commit()
182
+
183
+ self._index_agent_playbook_fts_vec(ap)
184
+ saved.append(ap)
185
+ return saved
186
+
187
+ @SQLiteStorageBase.handle_exceptions
188
+ def save_agent_playbook_with_aggregate_event(
189
+ self,
190
+ agent_playbook: AgentPlaybook,
191
+ *,
192
+ source_ids: list[str],
193
+ request_id: str,
194
+ run_mode: str,
195
+ ) -> AgentPlaybook:
196
+ """Persist an agent playbook AND its ``op=aggregate`` lineage event atomically.
197
+
198
+ The INSERT and the event are committed in a single transaction — if either
199
+ fails, both roll back. The event is the sole record of the run->playbook
200
+ membership for reconstruction, so atomicity is critical.
201
+
202
+ Args:
203
+ agent_playbook (AgentPlaybook): The playbook to persist.
204
+ source_ids (list[str]): IDs of the source entities that produced this playbook.
205
+ request_id (str): The aggregation run ID.
206
+ run_mode (str): Aggregation run mode (e.g. ``full_archive`` or ``incremental``).
207
+
208
+ Returns:
209
+ AgentPlaybook: The saved playbook with ``agent_playbook_id`` populated.
210
+
211
+ Raises:
212
+ ValueError: If ``request_id`` is empty (would produce an unreconstructable event).
213
+ """
214
+ if not request_id or not request_id.strip():
215
+ raise ValueError(
216
+ "save_agent_playbook_with_aggregate_event requires a non-empty request_id"
217
+ )
218
+ ap = agent_playbook
219
+ embedding_text = ap.trigger or ap.content
220
+ if self._should_expand_documents():
221
+ with ThreadPoolExecutor(max_workers=2) as executor:
222
+ emb_future = executor.submit(self._get_embedding, embedding_text)
223
+ exp_future = executor.submit(self._expand_document, embedding_text)
224
+ ap.embedding = emb_future.result(timeout=15)
225
+ ap.expanded_terms = exp_future.result(timeout=15)
226
+ else:
227
+ ap.embedding = self._get_embedding(embedding_text)
228
+
229
+ created_at_iso = _epoch_to_iso(ap.created_at)
230
+ with self._lock:
231
+ try:
232
+ self._insert_agent_playbook_row(self.conn, ap, created_at_iso)
233
+ _append_event_stmt(
234
+ self.conn,
235
+ org_id=self.org_id,
236
+ entity_type="agent_playbook",
237
+ entity_id=str(ap.agent_playbook_id),
238
+ op="aggregate",
239
+ prov="wasDerivedFrom",
240
+ source_ids=source_ids,
241
+ actor="aggregator",
242
+ request_id=request_id,
243
+ reason=f"{AGGREGATE_REASON_PREFIX}{run_mode}",
244
+ )
245
+ self.conn.commit()
246
+ except Exception:
247
+ self.conn.rollback()
248
+ raise
249
+
250
+ # FTS/vec indexing AFTER commit — these helpers self-commit and must
251
+ # not be interleaved inside the atomic transaction above.
252
+ # Index failure does NOT invalidate the committed row+event; the index
253
+ # is reconstructable from the authoritative row.
254
+ try:
255
+ self._index_agent_playbook_fts_vec(ap)
256
+ except Exception:
257
+ logger.exception(
258
+ "FTS/vec indexing failed for agent_playbook %s (row committed, index skipped)",
259
+ ap.agent_playbook_id,
260
+ )
261
+ return ap
262
+
263
+ @SQLiteStorageBase.handle_exceptions
264
+ def get_agent_playbooks(
265
+ self,
266
+ limit: int = 100,
267
+ playbook_name: str | None = None,
268
+ agent_version: str | None = None,
269
+ status_filter: list[Status | None] | None = None,
270
+ playbook_status_filter: list[PlaybookStatus] | None = None,
271
+ tags: list[str] | None = None,
272
+ agent_playbook_id: int | None = None,
273
+ query: str | None = None,
274
+ start_time: int | None = None,
275
+ end_time: int | None = None,
276
+ ) -> list[AgentPlaybook]:
277
+ sql = "SELECT * FROM agent_playbooks WHERE 1=1"
278
+ params: list[Any] = []
279
+
280
+ if agent_playbook_id is not None:
281
+ sql += " AND agent_playbook_id = ?"
282
+ params.append(agent_playbook_id)
283
+ if query:
284
+ like = f"%{query.lower()}%"
285
+ sql += (
286
+ " AND (LOWER(content) LIKE ? OR LOWER(trigger) LIKE ? "
287
+ "OR LOWER(rationale) LIKE ? OR LOWER(playbook_name) LIKE ? "
288
+ "OR LOWER(playbook_metadata) LIKE ?)"
289
+ )
290
+ params.extend([like, like, like, like, like])
291
+ if playbook_name:
292
+ sql += " AND playbook_name = ?"
293
+ params.append(playbook_name)
294
+
295
+ if agent_version is not None:
296
+ sql += " AND agent_version = ?"
297
+ params.append(agent_version)
298
+ if start_time is not None:
299
+ sql += " AND created_at >= ?"
300
+ params.append(_epoch_to_iso(start_time))
301
+ if end_time is not None:
302
+ sql += " AND created_at <= ?"
303
+ params.append(_epoch_to_iso(end_time))
304
+
305
+ if status_filter is not None:
306
+ frag, sparams = _build_status_sql(status_filter)
307
+ sql += f" AND {frag}"
308
+ params.extend(sparams)
309
+ else:
310
+ sql += " AND status IS NULL"
311
+
312
+ if playbook_status_filter:
313
+ ph = ",".join("?" for _ in playbook_status_filter)
314
+ sql += f" AND playbook_status IN ({ph})"
315
+ params.extend(ps.value for ps in playbook_status_filter)
316
+ tag_frag, tag_params = _build_tags_sql("agent_playbooks", tags)
317
+ if tag_frag:
318
+ sql += f" AND {tag_frag}"
319
+ params.extend(tag_params)
320
+
321
+ sql += " ORDER BY created_at DESC LIMIT ?"
322
+ params.append(limit)
323
+ rows = self._fetchall(sql, params)
324
+ return [_row_to_agent_playbook(r) for r in rows]
325
+
326
+ @SQLiteStorageBase.handle_exceptions
327
+ def get_agent_playbook_by_id(
328
+ self, agent_playbook_id: int, *, include_tombstones: bool = False
329
+ ) -> AgentPlaybook | None:
330
+ sql = "SELECT * FROM agent_playbooks WHERE agent_playbook_id = ?"
331
+ if not include_tombstones:
332
+ _ph = ",".join("?" * len(_AGENT_PLAYBOOK_DEFAULT_EXCLUDED_STATUSES))
333
+ sql += f" AND (status IS NULL OR status NOT IN ({_ph}))"
334
+ row = self._fetchone(
335
+ sql,
336
+ (agent_playbook_id, *_AGENT_PLAYBOOK_DEFAULT_EXCLUDED_STATUSES),
337
+ )
338
+ else:
339
+ row = self._fetchone(sql, (agent_playbook_id,))
340
+ return _row_to_agent_playbook(row) if row else None
341
+
342
+ @SQLiteStorageBase.handle_exceptions
343
+ def delete_all_agent_playbooks(self) -> None:
344
+ batch_request_id = uuid.uuid4().hex
345
+ with self._lock:
346
+ ids = [
347
+ r["agent_playbook_id"]
348
+ for r in self.conn.execute(
349
+ "SELECT agent_playbook_id FROM agent_playbooks"
350
+ ).fetchall()
351
+ ]
352
+ self.conn.execute("DELETE FROM agent_playbooks")
353
+ for apid in ids:
354
+ _emit_hard_delete_playbook(
355
+ self.conn,
356
+ org_id=self.org_id,
357
+ entity_type="agent_playbook",
358
+ entity_id=str(apid),
359
+ request_id=batch_request_id,
360
+ )
361
+ self.conn.commit()
362
+ self._delete_playbook_search_rows("agent", ids)
363
+
364
+ @SQLiteStorageBase.handle_exceptions
365
+ def delete_agent_playbook(self, agent_playbook_id: int) -> None:
366
+ with self._lock:
367
+ cur = self.conn.execute(
368
+ "DELETE FROM agent_playbooks WHERE agent_playbook_id = ?",
369
+ (agent_playbook_id,),
370
+ )
371
+ if cur.rowcount > 0:
372
+ _emit_hard_delete_playbook(
373
+ self.conn,
374
+ org_id=self.org_id,
375
+ entity_type="agent_playbook",
376
+ entity_id=str(agent_playbook_id),
377
+ request_id=uuid.uuid4().hex,
378
+ )
379
+ self._delete_playbook_search_rows(
380
+ "agent", [agent_playbook_id], commit=False
381
+ )
382
+ self.conn.commit()
383
+
384
+ @SQLiteStorageBase.handle_exceptions
385
+ def delete_all_agent_playbooks_by_playbook_name(
386
+ self, playbook_name: str, agent_version: str | None = None
387
+ ) -> None:
388
+ sql = "SELECT agent_playbook_id FROM agent_playbooks WHERE playbook_name = ?"
389
+ params: list[Any] = [playbook_name]
390
+ if agent_version is not None:
391
+ sql += " AND agent_version = ?"
392
+ params.append(agent_version)
393
+ batch_request_id = uuid.uuid4().hex
394
+ with self._lock:
395
+ ids = [
396
+ r["agent_playbook_id"]
397
+ for r in self.conn.execute(sql, params).fetchall()
398
+ ]
399
+ if not ids:
400
+ return
401
+ ph = ",".join("?" for _ in ids)
402
+ self.conn.execute(
403
+ f"DELETE FROM agent_playbooks WHERE agent_playbook_id IN ({ph})", ids
404
+ )
405
+ for apid in ids:
406
+ _emit_hard_delete_playbook(
407
+ self.conn,
408
+ org_id=self.org_id,
409
+ entity_type="agent_playbook",
410
+ entity_id=str(apid),
411
+ request_id=batch_request_id,
412
+ )
413
+ self.conn.commit()
414
+ self._delete_playbook_search_rows("agent", ids)
415
+
416
+ @SQLiteStorageBase.handle_exceptions
417
+ def delete_agent_playbooks_by_ids(
418
+ self, agent_playbook_ids: list[int], *, emit_hard_delete: bool = True
419
+ ) -> None:
420
+ if not agent_playbook_ids:
421
+ return
422
+ ph = ",".join("?" for _ in agent_playbook_ids)
423
+ batch_request_id = uuid.uuid4().hex
424
+ with self._lock:
425
+ existing = [
426
+ r["agent_playbook_id"]
427
+ for r in self.conn.execute(
428
+ f"SELECT agent_playbook_id FROM agent_playbooks WHERE agent_playbook_id IN ({ph})",
429
+ agent_playbook_ids,
430
+ ).fetchall()
431
+ ]
432
+ self.conn.execute(
433
+ f"DELETE FROM agent_playbooks WHERE agent_playbook_id IN ({ph})",
434
+ agent_playbook_ids,
435
+ )
436
+ if emit_hard_delete:
437
+ for apid in existing:
438
+ _emit_hard_delete_playbook(
439
+ self.conn,
440
+ org_id=self.org_id,
441
+ entity_type="agent_playbook",
442
+ entity_id=str(apid),
443
+ request_id=batch_request_id,
444
+ actor="system",
445
+ )
446
+ self.conn.commit()
447
+ self._delete_playbook_search_rows("agent", agent_playbook_ids)
448
+
449
+ @SQLiteStorageBase.handle_exceptions
450
+ def update_agent_playbook_status(
451
+ self, agent_playbook_id: int, playbook_status: PlaybookStatus
452
+ ) -> None:
453
+ """Update an agent playbook's status and emit a status_change lineage event.
454
+
455
+ Each call generates a fresh request_id so every status change is recorded as
456
+ a distinct audit event (not collapsed by the idempotency key).
457
+ """
458
+ with self._lock:
459
+ row = self.conn.execute(
460
+ "SELECT playbook_status FROM agent_playbooks WHERE agent_playbook_id = ?",
461
+ (agent_playbook_id,),
462
+ ).fetchone()
463
+ if not row:
464
+ raise ValueError(
465
+ f"Agent playbook with ID {agent_playbook_id} not found"
466
+ )
467
+ prior_playbook_status = row["playbook_status"]
468
+ old_status = prior_playbook_status or "None"
469
+ cur = self.conn.execute(
470
+ "UPDATE agent_playbooks SET playbook_status = ? WHERE agent_playbook_id = ?",
471
+ (playbook_status.value, agent_playbook_id),
472
+ )
473
+ if cur.rowcount > 0:
474
+ _append_event_stmt(
475
+ self.conn,
476
+ org_id=self.org_id,
477
+ entity_type="agent_playbook",
478
+ entity_id=str(agent_playbook_id),
479
+ op="status_change",
480
+ prov="wasInvalidatedBy",
481
+ source_ids=[],
482
+ actor="api",
483
+ request_id=uuid.uuid4().hex,
484
+ reason=f"{old_status}->{playbook_status.value}",
485
+ from_status=prior_playbook_status,
486
+ to_status=playbook_status.value,
487
+ status_namespace="playbook_status",
488
+ )
489
+ self.conn.commit()
490
+
491
+ @SQLiteStorageBase.handle_exceptions
492
+ def update_agent_playbook(
493
+ self,
494
+ agent_playbook_id: int,
495
+ playbook_name: str | None = None,
496
+ content: str | None = None,
497
+ trigger: str | None = None,
498
+ rationale: str | None = None,
499
+ blocking_issue: BlockingIssue | None = None,
500
+ playbook_status: PlaybookStatus | None = None,
501
+ tags: list[str] | None = None,
502
+ ) -> None:
503
+ updates: list[str] = []
504
+ params: list[Any] = []
505
+ if playbook_name is not None:
506
+ updates.append("playbook_name = ?")
507
+ params.append(playbook_name)
508
+ if content is not None:
509
+ updates.append("content = ?")
510
+ params.append(content)
511
+ if trigger is not None:
512
+ updates.append("trigger = ?")
513
+ params.append(trigger)
514
+ if rationale is not None:
515
+ updates.append("rationale = ?")
516
+ params.append(rationale)
517
+ if blocking_issue is not None:
518
+ updates.append("blocking_issue = ?")
519
+ params.append(json.dumps(blocking_issue.model_dump()))
520
+ if playbook_status is not None:
521
+ updates.append("playbook_status = ?")
522
+ params.append(playbook_status.value)
523
+ if tags is not None:
524
+ updates.append("tags = ?")
525
+ params.append(_json_dumps(tags))
526
+ if updates:
527
+ params.append(agent_playbook_id)
528
+ op = "revise" if content is not None else "status_change"
529
+ prov = "wasRevisionOf" if op == "revise" else "wasInvalidatedBy"
530
+ with self._lock:
531
+ prior_row = self.conn.execute(
532
+ "SELECT playbook_status FROM agent_playbooks WHERE agent_playbook_id = ?",
533
+ (agent_playbook_id,),
534
+ ).fetchone()
535
+ if not prior_row:
536
+ raise ValueError(
537
+ f"Agent playbook with ID {agent_playbook_id} not found"
538
+ )
539
+ prior_playbook_status = prior_row["playbook_status"]
540
+ cur = self.conn.execute(
541
+ f"UPDATE agent_playbooks SET {', '.join(updates)} WHERE agent_playbook_id = ?",
542
+ tuple(params),
543
+ )
544
+ if cur.rowcount > 0:
545
+ # Populate structured status fields only when playbook_status is
546
+ # among the updated fields and the op is status_change (not revise).
547
+ if op == "status_change" and playbook_status is not None:
548
+ from_status = prior_playbook_status
549
+ to_status = playbook_status.value
550
+ status_namespace: str | None = "playbook_status"
551
+ else:
552
+ from_status = None
553
+ to_status = None
554
+ status_namespace = None
555
+ _append_event_stmt(
556
+ self.conn,
557
+ org_id=self.org_id,
558
+ entity_type="agent_playbook",
559
+ entity_id=str(agent_playbook_id),
560
+ op=op,
561
+ prov=prov,
562
+ source_ids=[],
563
+ actor="api",
564
+ request_id=uuid.uuid4().hex,
565
+ reason="in-place update",
566
+ from_status=from_status,
567
+ to_status=to_status,
568
+ status_namespace=status_namespace,
569
+ )
570
+ self.conn.commit()
571
+
572
+ @SQLiteStorageBase.handle_exceptions
573
+ def archive_agent_playbooks_by_playbook_name(
574
+ self, playbook_name: str, agent_version: str | None = None
575
+ ) -> None:
576
+ where = (
577
+ "playbook_name = ? AND playbook_status != ?"
578
+ " AND (status IS NULL OR status != 'archived')"
579
+ )
580
+ params: list[Any] = [playbook_name, PlaybookStatus.APPROVED.value]
581
+ if agent_version is not None:
582
+ where += " AND agent_version = ?"
583
+ params.append(agent_version)
584
+ now_ts = _epoch_now()
585
+ batch_request_id = uuid.uuid4().hex
586
+ with self._lock:
587
+ affected = self.conn.execute(
588
+ f"SELECT agent_playbook_id, status FROM agent_playbooks WHERE {where}",
589
+ params,
590
+ ).fetchall()
591
+ self.conn.execute(
592
+ f"UPDATE agent_playbooks SET status = 'archived', retired_at = ? WHERE {where}",
593
+ [now_ts, *params],
594
+ )
595
+ for row in affected:
596
+ prior = row["status"] or "None"
597
+ _append_event_stmt(
598
+ self.conn,
599
+ org_id=self.org_id,
600
+ entity_type="agent_playbook",
601
+ entity_id=str(row["agent_playbook_id"]),
602
+ op="status_change",
603
+ prov="wasInvalidatedBy",
604
+ source_ids=[],
605
+ actor="api",
606
+ request_id=batch_request_id,
607
+ reason=f"{prior}->archived",
608
+ from_status=row["status"],
609
+ to_status="archived",
610
+ status_namespace="lifecycle_status",
611
+ )
612
+ self.conn.commit()
613
+
614
+ @SQLiteStorageBase.handle_exceptions
615
+ def archive_agent_playbooks_by_ids(self, agent_playbook_ids: list[int]) -> None:
616
+ if not agent_playbook_ids:
617
+ return
618
+ ph = ",".join("?" for _ in agent_playbook_ids)
619
+ now_ts = _epoch_now()
620
+ batch_request_id = uuid.uuid4().hex
621
+ with self._lock:
622
+ affected = self.conn.execute(
623
+ f"SELECT agent_playbook_id, status FROM agent_playbooks"
624
+ f" WHERE agent_playbook_id IN ({ph}) AND playbook_status != ?"
625
+ f" AND (status IS NULL OR status != 'archived')",
626
+ [*agent_playbook_ids, PlaybookStatus.APPROVED.value],
627
+ ).fetchall()
628
+ self.conn.execute(
629
+ f"UPDATE agent_playbooks SET status = 'archived', retired_at = ?"
630
+ f" WHERE agent_playbook_id IN ({ph}) AND playbook_status != ?"
631
+ f" AND (status IS NULL OR status != 'archived')",
632
+ [now_ts, *agent_playbook_ids, PlaybookStatus.APPROVED.value],
633
+ )
634
+ for row in affected:
635
+ prior = row["status"] or "None"
636
+ _append_event_stmt(
637
+ self.conn,
638
+ org_id=self.org_id,
639
+ entity_type="agent_playbook",
640
+ entity_id=str(row["agent_playbook_id"]),
641
+ op="status_change",
642
+ prov="wasInvalidatedBy",
643
+ source_ids=[],
644
+ actor="api",
645
+ request_id=batch_request_id,
646
+ reason=f"{prior}->archived",
647
+ from_status=row["status"],
648
+ to_status="archived",
649
+ status_namespace="lifecycle_status",
650
+ )
651
+ self.conn.commit()
652
+
653
+ @SQLiteStorageBase.handle_exceptions
654
+ def supersede_agent_playbooks_by_ids(
655
+ self, agent_playbook_ids: list[int], request_id: str
656
+ ) -> int:
657
+ """Soft-delete agent playbooks by setting status to SUPERSEDED, emitting set-based lineage.
658
+
659
+ For each eligible id (not APPROVED, not already tombstoned), updates status to
660
+ SUPERSEDED and emits one ``status_change`` event under the shared ``request_id``.
661
+ Atomic: one ``conn.commit()`` at the end, guarded on rowcount per id.
662
+ FTS/vec rows are NOT removed — reads exclude tombstones by status filter.
663
+
664
+ Args:
665
+ agent_playbook_ids (list[int]): Agent playbook ids to supersede.
666
+ request_id (str): Shared request id for all emitted lineage events.
667
+
668
+ Returns:
669
+ int: Number of agent playbooks actually updated.
670
+ """
671
+ if not agent_playbook_ids:
672
+ return 0
673
+ if not request_id:
674
+ raise ValueError("request_id must be non-empty for supersede")
675
+ now_ts = _epoch_now()
676
+ updated = 0
677
+ with self._lock:
678
+ for apid in agent_playbook_ids:
679
+ row = self.conn.execute(
680
+ "SELECT status FROM agent_playbooks WHERE agent_playbook_id = ?",
681
+ (apid,),
682
+ ).fetchone()
683
+ if row is None:
684
+ continue
685
+ old_status = row["status"]
686
+ # NOTE (M3): The model supersede_profiles_by_ids adds an eligible-check
687
+ # `if old_status_val not in eligible: continue` before the UPDATE. For
688
+ # agent_playbooks the ineligible condition spans two columns (status in
689
+ # _TOMBSTONE_STATUS_VALUES OR playbook_status == APPROVED), so aligning
690
+ # would require adding playbook_status to the SELECT. The UPDATE WHERE
691
+ # clause already excludes those rows atomically; the extra continue here
692
+ # would be a no-op and not worth the added complexity.
693
+ _ph = ",".join("?" * len(_TOMBSTONE_STATUS_VALUES))
694
+ cur = self.conn.execute(
695
+ "UPDATE agent_playbooks SET status = ?, retired_at = ?"
696
+ " WHERE agent_playbook_id = ? AND playbook_status != ?"
697
+ f" AND (status IS NULL OR status NOT IN ({_ph}))",
698
+ (
699
+ Status.SUPERSEDED.value,
700
+ now_ts,
701
+ apid,
702
+ PlaybookStatus.APPROVED.value,
703
+ *_TOMBSTONE_STATUS_VALUES,
704
+ ),
705
+ )
706
+ if cur.rowcount > 0:
707
+ _emit_supersede_playbook(
708
+ self.conn,
709
+ org_id=self.org_id,
710
+ entity_id=str(apid),
711
+ old_status=old_status,
712
+ request_id=request_id,
713
+ )
714
+ updated += 1
715
+ self.conn.commit()
716
+ return updated
717
+
718
+ @SQLiteStorageBase.handle_exceptions
719
+ def supersede_agent_playbooks_by_playbook_name(
720
+ self, playbook_name: str, agent_version: str | None, request_id: str
721
+ ) -> int:
722
+ """Soft-delete archived agent playbooks by name/version via SUPERSEDED status.
723
+
724
+ Mirrors ``delete_archived_agent_playbooks_by_playbook_name`` but converts
725
+ the hard-delete to a soft-supersede with status_change lineage events.
726
+ Atomic: one ``conn.commit()`` at the end.
727
+ FTS/vec rows are NOT removed.
728
+
729
+ Args:
730
+ playbook_name (str): Playbook name to supersede.
731
+ agent_version (str | None): Agent version filter. None matches all versions.
732
+ request_id (str): Shared request id for all emitted lineage events.
733
+
734
+ Returns:
735
+ int: Number of agent playbooks actually updated.
736
+ """
737
+ if not request_id:
738
+ raise ValueError("request_id must be non-empty for supersede")
739
+ sql = (
740
+ "SELECT agent_playbook_id, status FROM agent_playbooks"
741
+ " WHERE playbook_name = ? AND status = 'archived'"
742
+ )
743
+ params: list[Any] = [playbook_name]
744
+ if agent_version is not None:
745
+ sql += " AND agent_version = ?"
746
+ params.append(agent_version)
747
+ updated = 0
748
+ with self._lock:
749
+ rows = self.conn.execute(sql, params).fetchall()
750
+ if not rows:
751
+ return 0
752
+ now_ts = _epoch_now()
753
+ for row in rows:
754
+ apid = row["agent_playbook_id"]
755
+ old_status = row["status"]
756
+ cur = self.conn.execute(
757
+ "UPDATE agent_playbooks SET status = ?, retired_at = ?"
758
+ " WHERE agent_playbook_id = ? AND playbook_status != ?"
759
+ " AND status = 'archived'",
760
+ (
761
+ Status.SUPERSEDED.value,
762
+ now_ts,
763
+ apid,
764
+ PlaybookStatus.APPROVED.value,
765
+ ),
766
+ )
767
+ if cur.rowcount > 0:
768
+ _emit_supersede_playbook(
769
+ self.conn,
770
+ org_id=self.org_id,
771
+ entity_id=str(apid),
772
+ old_status=old_status,
773
+ request_id=request_id,
774
+ )
775
+ updated += 1
776
+ self.conn.commit()
777
+ return updated
778
+
779
+ @SQLiteStorageBase.handle_exceptions
780
+ def restore_archived_agent_playbooks_by_playbook_name(
781
+ self, playbook_name: str, agent_version: str | None = None
782
+ ) -> None:
783
+ sql = "UPDATE agent_playbooks SET status = NULL, retired_at = NULL WHERE playbook_name = ? AND status = 'archived'"
784
+ params: list[Any] = [playbook_name]
785
+ if agent_version is not None:
786
+ sql += " AND agent_version = ?"
787
+ params.append(agent_version)
788
+ self._execute(sql, params)
789
+
790
+ @SQLiteStorageBase.handle_exceptions
791
+ def restore_archived_agent_playbooks_by_ids(
792
+ self, agent_playbook_ids: list[int]
793
+ ) -> None:
794
+ if not agent_playbook_ids:
795
+ return
796
+ ph = ",".join("?" for _ in agent_playbook_ids)
797
+ self._execute(
798
+ f"UPDATE agent_playbooks SET status = NULL, retired_at = NULL WHERE agent_playbook_id IN ({ph}) AND status = 'archived'",
799
+ agent_playbook_ids,
800
+ )
801
+
802
+ @SQLiteStorageBase.handle_exceptions
803
+ def delete_archived_agent_playbooks_by_playbook_name(
804
+ self, playbook_name: str, agent_version: str | None = None
805
+ ) -> None:
806
+ sql = "SELECT agent_playbook_id FROM agent_playbooks WHERE playbook_name = ? AND status = 'archived'"
807
+ params: list[Any] = [playbook_name]
808
+ if agent_version is not None:
809
+ sql += " AND agent_version = ?"
810
+ params.append(agent_version)
811
+ batch_request_id = uuid.uuid4().hex
812
+ with self._lock:
813
+ ids = [
814
+ r["agent_playbook_id"]
815
+ for r in self.conn.execute(sql, params).fetchall()
816
+ ]
817
+ if not ids:
818
+ return
819
+ ph = ",".join("?" for _ in ids)
820
+ self.conn.execute(
821
+ f"DELETE FROM agent_playbooks WHERE agent_playbook_id IN ({ph})", ids
822
+ )
823
+ for apid in ids:
824
+ _emit_hard_delete_playbook(
825
+ self.conn,
826
+ org_id=self.org_id,
827
+ entity_type="agent_playbook",
828
+ entity_id=str(apid),
829
+ request_id=batch_request_id,
830
+ )
831
+ self.conn.commit()
832
+ self._delete_playbook_search_rows("agent", ids)
833
+
834
+ @SQLiteStorageBase.handle_exceptions
835
+ def search_agent_playbooks( # noqa: C901
836
+ self,
837
+ request: SearchAgentPlaybookRequest,
838
+ options: SearchOptions | None = None,
839
+ ) -> list[AgentPlaybook]:
840
+ query = request.query
841
+ agent_version = request.agent_version
842
+ playbook_name = request.playbook_name
843
+ start_time = int(request.start_time.timestamp()) if request.start_time else None
844
+ end_time = int(request.end_time.timestamp()) if request.end_time else None
845
+ status_filter = request.status_filter
846
+ playbook_status_filter = request.playbook_status_filter
847
+ match_count = request.top_k or 10
848
+ query_embedding = options.query_embedding if options else None
849
+ mode = _effective_search_mode(
850
+ request.search_mode, query_embedding, request.query
851
+ )
852
+ rrf_k = options.rrf_k if options else 60
853
+ vector_weight = options.vector_weight if options else 1.0
854
+ fts_weight = options.fts_weight if options else 1.0
855
+
856
+ conditions: list[str] = []
857
+ params: list[Any] = []
858
+
859
+ if agent_version:
860
+ conditions.append("ap.agent_version = ?")
861
+ params.append(agent_version)
862
+ if playbook_name:
863
+ conditions.append("ap.playbook_name = ?")
864
+ params.append(playbook_name)
865
+ if start_time:
866
+ conditions.append("ap.created_at >= ?")
867
+ params.append(_epoch_to_iso(start_time))
868
+ if end_time:
869
+ conditions.append("ap.created_at <= ?")
870
+ params.append(_epoch_to_iso(end_time))
871
+ if playbook_status_filter is not None:
872
+ if isinstance(playbook_status_filter, list):
873
+ if not playbook_status_filter:
874
+ conditions.append("1=0")
875
+ else:
876
+ placeholders = ",".join("?" for _ in playbook_status_filter)
877
+ conditions.append(f"ap.playbook_status IN ({placeholders})")
878
+ params.extend(s.value for s in playbook_status_filter)
879
+ else:
880
+ conditions.append("ap.playbook_status = ?")
881
+ params.append(playbook_status_filter.value)
882
+ if status_filter is not None:
883
+ frag, sparams = _build_status_sql(status_filter)
884
+ conditions.append(frag)
885
+ params.extend(sparams)
886
+ else:
887
+ _ph = ",".join("?" * len(_AGENT_PLAYBOOK_DEFAULT_EXCLUDED_STATUSES))
888
+ conditions.append(f"(ap.status IS NULL OR ap.status NOT IN ({_ph}))")
889
+ params.extend(_AGENT_PLAYBOOK_DEFAULT_EXCLUDED_STATUSES)
890
+ tag_frag, tag_params = _build_tags_sql("ap", request.tags)
891
+ if tag_frag:
892
+ conditions.append(tag_frag)
893
+ params.extend(tag_params)
894
+
895
+ where_extra = (" AND " + " AND ".join(conditions)) if conditions else ""
896
+ overfetch = match_count * 5 if mode != SearchMode.FTS else match_count
897
+
898
+ # Pure vector search: fetch all candidates, rank by cosine similarity
899
+ if mode == SearchMode.VECTOR and query_embedding:
900
+ base_where = "WHERE " + " AND ".join(conditions) if conditions else ""
901
+ sql = f"""SELECT * FROM agent_playbooks ap
902
+ {base_where}
903
+ ORDER BY ap.created_at DESC"""
904
+ rows = self._fetchall(sql, params)
905
+ rows = _vector_rank_rows(rows, query_embedding, match_count)
906
+ return [_row_to_agent_playbook(r) for r in rows]
907
+
908
+ if query:
909
+ fts_query = _sanitize_fts_query(query)
910
+ sql = f"""SELECT ap.* FROM agent_playbooks ap
911
+ JOIN agent_playbooks_fts f ON ap.agent_playbook_id = f.rowid
912
+ WHERE agent_playbooks_fts MATCH ?{where_extra}
913
+ ORDER BY bm25(agent_playbooks_fts, 1.0)
914
+ LIMIT ?"""
915
+ fts_rows = self._fetchall(sql, [fts_query, *params, overfetch])
916
+
917
+ if mode == SearchMode.HYBRID and query_embedding:
918
+ base_where = "WHERE " + " AND ".join(conditions) if conditions else ""
919
+ vec_limit = match_count * 10
920
+ vec_sql = f"""SELECT * FROM agent_playbooks ap
921
+ {base_where}
922
+ ORDER BY ap.created_at DESC
923
+ LIMIT ?"""
924
+ vec_candidates = self._fetchall(vec_sql, [*params, vec_limit])
925
+ vec_rows = _vector_rank_rows(vec_candidates, query_embedding, overfetch)
926
+ rows = _true_rrf_merge(
927
+ fts_rows,
928
+ vec_rows,
929
+ "agent_playbook_id",
930
+ match_count,
931
+ rrf_k,
932
+ vector_weight,
933
+ fts_weight,
934
+ )
935
+ return [_row_to_agent_playbook(r) for r in rows]
936
+ return [_row_to_agent_playbook(r) for r in fts_rows[:match_count]]
937
+
938
+ # HYBRID without query text: rank by embedding only
939
+ if query_embedding:
940
+ base_where = "WHERE " + " AND ".join(conditions) if conditions else ""
941
+ sql = f"""SELECT * FROM agent_playbooks ap
942
+ {base_where}
943
+ ORDER BY ap.created_at DESC"""
944
+ rows = self._fetchall(sql, params)
945
+ rows = _vector_rank_rows(rows, query_embedding, match_count)
946
+ return [_row_to_agent_playbook(r) for r in rows]
947
+
948
+ # No query text, no embedding -- recency fallback
949
+ base_where = "WHERE " + " AND ".join(conditions) if conditions else "WHERE 1=1"
950
+ sql = f"""SELECT * FROM agent_playbooks ap
951
+ {base_where}
952
+ ORDER BY ap.created_at DESC LIMIT ?"""
953
+ params.append(match_count)
954
+ rows = self._fetchall(sql, params)
955
+ return [_row_to_agent_playbook(r) for r in rows]