tuitbot-core 0.1.47

Core library for Tuitbot autonomous X growth assistant
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! CRUD operations for content_nodes.

use super::{ContentNode, ContentNodeRow, UpsertResult};
use crate::error::StorageError;
use crate::storage::accounts::DEFAULT_ACCOUNT_ID;
use crate::storage::DbPool;

// ============================================================================
// Account-scoped content node functions
// ============================================================================

/// Upsert a content node for a specific account by (source_id, relative_path).
#[allow(clippy::too_many_arguments)]
pub async fn upsert_content_node_for(
    pool: &DbPool,
    account_id: &str,
    source_id: i64,
    relative_path: &str,
    content_hash: &str,
    title: Option<&str>,
    body_text: &str,
    front_matter_json: Option<&str>,
    tags: Option<&str>,
) -> Result<UpsertResult, StorageError> {
    let existing: Option<(i64, String)> = sqlx::query_as(
        "SELECT id, content_hash FROM content_nodes \
         WHERE source_id = ? AND relative_path = ?",
    )
    .bind(source_id)
    .bind(relative_path)
    .fetch_optional(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    match existing {
        Some((_id, ref existing_hash)) if existing_hash == content_hash => {
            Ok(UpsertResult::Skipped)
        }
        Some((id, _)) => {
            sqlx::query(
                "UPDATE content_nodes \
                 SET content_hash = ?, title = ?, body_text = ?, \
                     front_matter_json = ?, tags = ?, \
                     status = 'pending', updated_at = datetime('now') \
                 WHERE id = ?",
            )
            .bind(content_hash)
            .bind(title)
            .bind(body_text)
            .bind(front_matter_json)
            .bind(tags)
            .bind(id)
            .execute(pool)
            .await
            .map_err(|e| StorageError::Query { source: e })?;

            Ok(UpsertResult::Updated)
        }
        None => {
            sqlx::query(
                "INSERT INTO content_nodes \
                 (account_id, source_id, relative_path, content_hash, \
                  title, body_text, front_matter_json, tags) \
                 VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
            )
            .bind(account_id)
            .bind(source_id)
            .bind(relative_path)
            .bind(content_hash)
            .bind(title)
            .bind(body_text)
            .bind(front_matter_json)
            .bind(tags)
            .execute(pool)
            .await
            .map_err(|e| StorageError::Query { source: e })?;

            Ok(UpsertResult::Inserted)
        }
    }
}

/// Upsert a content node by (source_id, relative_path).
#[allow(clippy::too_many_arguments)]
pub async fn upsert_content_node(
    pool: &DbPool,
    source_id: i64,
    relative_path: &str,
    content_hash: &str,
    title: Option<&str>,
    body_text: &str,
    front_matter_json: Option<&str>,
    tags: Option<&str>,
) -> Result<UpsertResult, StorageError> {
    upsert_content_node_for(
        pool,
        DEFAULT_ACCOUNT_ID,
        source_id,
        relative_path,
        content_hash,
        title,
        body_text,
        front_matter_json,
        tags,
    )
    .await
}

/// Get a content node by ID.
pub async fn get_content_node(pool: &DbPool, id: i64) -> Result<Option<ContentNode>, StorageError> {
    let row: Option<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes WHERE id = ?",
    )
    .bind(id)
    .fetch_optional(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.map(ContentNode::from_row))
}

/// Get all content nodes for a source, optionally filtered by status.
pub async fn get_nodes_for_source(
    pool: &DbPool,
    source_id: i64,
    status_filter: Option<&str>,
) -> Result<Vec<ContentNode>, StorageError> {
    let rows: Vec<ContentNodeRow> = match status_filter {
        Some(status) => {
            sqlx::query_as(
                "SELECT id, account_id, source_id, relative_path, content_hash, \
                            title, body_text, front_matter_json, tags, status, \
                            ingested_at, updated_at \
                     FROM content_nodes WHERE source_id = ? AND status = ? ORDER BY id",
            )
            .bind(source_id)
            .bind(status)
            .fetch_all(pool)
            .await
        }
        None => {
            sqlx::query_as(
                "SELECT id, account_id, source_id, relative_path, content_hash, \
                            title, body_text, front_matter_json, tags, status, \
                            ingested_at, updated_at \
                     FROM content_nodes WHERE source_id = ? ORDER BY id",
            )
            .bind(source_id)
            .fetch_all(pool)
            .await
        }
    }
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(ContentNode::from_row).collect())
}

/// Get content nodes with status='pending' for a specific account.
pub async fn get_pending_content_nodes_for(
    pool: &DbPool,
    account_id: &str,
    limit: u32,
) -> Result<Vec<ContentNode>, StorageError> {
    let rows: Vec<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes \
             WHERE account_id = ? AND status = 'pending' \
             ORDER BY ingested_at ASC \
             LIMIT ?",
    )
    .bind(account_id)
    .bind(limit)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(ContentNode::from_row).collect())
}

/// Get content nodes with status='pending' that need seed generation.
pub async fn get_pending_content_nodes(
    pool: &DbPool,
    limit: u32,
) -> Result<Vec<ContentNode>, StorageError> {
    get_pending_content_nodes_for(pool, DEFAULT_ACCOUNT_ID, limit).await
}

/// Mark a content node as 'processed' for a specific account.
pub async fn mark_node_processed_for(
    pool: &DbPool,
    account_id: &str,
    node_id: i64,
) -> Result<(), StorageError> {
    sqlx::query(
        "UPDATE content_nodes SET status = 'processed', updated_at = datetime('now') \
         WHERE id = ? AND account_id = ?",
    )
    .bind(node_id)
    .bind(account_id)
    .execute(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;
    Ok(())
}

/// Mark a content node as 'processed' after seed generation.
pub async fn mark_node_processed(pool: &DbPool, node_id: i64) -> Result<(), StorageError> {
    sqlx::query(
        "UPDATE content_nodes SET status = 'processed', updated_at = datetime('now') WHERE id = ?",
    )
    .bind(node_id)
    .execute(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;
    Ok(())
}

/// Search content nodes by title or path for a specific account.
///
/// Returns nodes matching the query (LIKE-based), without loading body_text
/// into the API response layer. The caller should omit body_text when serializing.
pub async fn search_nodes_for(
    pool: &DbPool,
    account_id: &str,
    query: &str,
    limit: u32,
) -> Result<Vec<ContentNode>, StorageError> {
    let rows: Vec<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes \
             WHERE account_id = ? AND (title LIKE '%' || ? || '%' OR relative_path LIKE '%' || ? || '%') \
             ORDER BY updated_at DESC \
             LIMIT ?",
    )
    .bind(account_id)
    .bind(query)
    .bind(query)
    .bind(limit)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(ContentNode::from_row).collect())
}

/// Get all content nodes for a specific account and source.
pub async fn get_nodes_for_source_for(
    pool: &DbPool,
    account_id: &str,
    source_id: i64,
    limit: u32,
) -> Result<Vec<ContentNode>, StorageError> {
    let rows: Vec<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes \
             WHERE account_id = ? AND source_id = ? \
             ORDER BY updated_at DESC \
             LIMIT ?",
    )
    .bind(account_id)
    .bind(source_id)
    .bind(limit)
    .fetch_all(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(ContentNode::from_row).collect())
}

/// Get a content node by ID, scoped to account.
pub async fn get_content_node_for(
    pool: &DbPool,
    account_id: &str,
    node_id: i64,
) -> Result<Option<ContentNode>, StorageError> {
    let row: Option<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes WHERE id = ? AND account_id = ?",
    )
    .bind(node_id)
    .bind(account_id)
    .fetch_optional(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.map(ContentNode::from_row))
}

/// Count active chunks for a node, scoped to account.
pub async fn count_chunks_for_node(
    pool: &DbPool,
    account_id: &str,
    node_id: i64,
) -> Result<i64, StorageError> {
    let row: (i64,) = sqlx::query_as(
        "SELECT COUNT(*) FROM content_chunks \
         WHERE account_id = ? AND node_id = ? AND status = 'active'",
    )
    .bind(account_id)
    .bind(node_id)
    .fetch_one(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.0)
}

/// Count content nodes for a source, scoped to account.
pub async fn count_nodes_for_source(
    pool: &DbPool,
    account_id: &str,
    source_id: i64,
) -> Result<i64, StorageError> {
    let row: (i64,) =
        sqlx::query_as("SELECT COUNT(*) FROM content_nodes WHERE account_id = ? AND source_id = ?")
            .bind(account_id)
            .bind(source_id)
            .fetch_one(pool)
            .await
            .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.0)
}

/// Find a content node by `relative_path` for a given account (across all sources).
///
/// Returns the most recently updated match if multiple sources contain the same path.
pub async fn find_node_by_path_for(
    pool: &DbPool,
    account_id: &str,
    relative_path: &str,
) -> Result<Option<ContentNode>, StorageError> {
    let row: Option<ContentNodeRow> = sqlx::query_as(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                    title, body_text, front_matter_json, tags, status, \
                    ingested_at, updated_at \
             FROM content_nodes \
             WHERE account_id = ? AND relative_path = ? \
             ORDER BY updated_at DESC \
             LIMIT 1",
    )
    .bind(account_id)
    .bind(relative_path)
    .fetch_optional(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;

    Ok(row.map(ContentNode::from_row))
}

/// Batch lookup content nodes by IDs, scoped to account.
///
/// Uses parameterized `WHERE IN` clause. Only returns nodes owned by the account.
pub async fn get_nodes_by_ids(
    pool: &DbPool,
    account_id: &str,
    node_ids: &[i64],
) -> Result<Vec<ContentNode>, StorageError> {
    if node_ids.is_empty() {
        return Ok(Vec::new());
    }

    let placeholders: Vec<&str> = node_ids.iter().map(|_| "?").collect();
    let in_clause = placeholders.join(", ");
    let sql = format!(
        "SELECT id, account_id, source_id, relative_path, content_hash, \
                title, body_text, front_matter_json, tags, status, \
                ingested_at, updated_at \
         FROM content_nodes \
         WHERE account_id = ? AND id IN ({in_clause}) \
         ORDER BY id"
    );

    let mut q = sqlx::query_as::<_, ContentNodeRow>(&sql);
    q = q.bind(account_id);
    for id in node_ids {
        q = q.bind(id);
    }

    let rows = q
        .fetch_all(pool)
        .await
        .map_err(|e| StorageError::Query { source: e })?;

    Ok(rows.into_iter().map(ContentNode::from_row).collect())
}

/// Mark a content node as 'chunked' for a specific account.
pub async fn mark_node_chunked(
    pool: &DbPool,
    account_id: &str,
    node_id: i64,
) -> Result<(), StorageError> {
    sqlx::query(
        "UPDATE content_nodes SET status = 'chunked', updated_at = datetime('now') \
         WHERE id = ? AND account_id = ?",
    )
    .bind(node_id)
    .bind(account_id)
    .execute(pool)
    .await
    .map_err(|e| StorageError::Query { source: e })?;
    Ok(())
}