artifactize-core 0.25.1

The library behind artifactize: Artifacts, evals, reviews, the monitor and review models, and the shared operations every interface calls.
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
//! The Chat catalog and one running writer per session.
use std::path::{Path, PathBuf};

use rusqlite::{Connection, OptionalExtension, TransactionBehavior, params};
use serde::{Deserialize, Serialize};

use super::{Receipts, receipts::Error};
use crate::{
    chat::{Model, Session, SessionView},
    monitor::live::Place,
    process::{self, ChildIdentity},
    repository,
    types::SessionId,
};

#[derive(Debug, Clone, Serialize, Deserialize)]
pub(crate) struct Owner {
    birth: ChildIdentity,
    token: String,
    #[serde(default)]
    stop_requested: bool,
}

impl Owner {
    pub(crate) fn current() -> Result<Self, String> {
        Ok(Self {
            birth: process::child_identity(std::process::id())
                .map_err(|error| error.to_string())?,
            token: crate::agent::uuid()?,
            stop_requested: false,
        })
    }

    pub(crate) fn in_current_process(&self) -> bool {
        self.birth.pid.get() == std::process::id()
    }

    pub(crate) fn live(&self) -> Result<bool, String> {
        process::is_alive(Some(self.birth)).map_err(|error| error.to_string())
    }
}

async fn read<T: Send + 'static>(
    state: &Path,
    read: impl FnOnce(&Connection) -> Result<T, Error> + Send + 'static,
) -> Result<Option<T>, String> {
    let Some(connection) = super::requests::open_read(state).await? else {
        return Ok(None);
    };
    let result = connection
        .call(move |db| {
            super::wait_when_busy(db)?;
            let transaction = db.transaction()?;
            if !super::receipts::schema_initialized(&transaction)? {
                return Ok(None);
            }
            let rows = read(&transaction)?;
            transaction.commit()?;
            Ok::<_, Error>(Some(rows))
        })
        .await
        .map_err(|error| error.to_string());
    super::connection::finish(connection, result).await
}

pub(crate) async fn list(state: &Path, worktree: Option<&Path>) -> Result<Vec<Session>, String> {
    let worktree = worktree
        .map(crate::workspace::canonical_target)
        .transpose()
        .map_err(|error| error.to_string())?
        .as_deref()
        .map(crate::platform::path_text);
    let state_path = state.to_owned();
    Ok(read(state, move |db| {
        let mut statement = db.prepare(
            "SELECT s.data, a.data FROM chat_sessions s LEFT JOIN chat_active_turns a ON a.session_id=s.id \
             WHERE ?1 IS NULL OR s.worktree=?1 ORDER BY s.updated_at DESC,s.id DESC",
        )?;
        let rows = statement.query_map([worktree], session_row)?
            .map(|row| session(row?, &state_path)).collect::<Result<Vec<_>, Error>>()?;
        Ok(rows)
    }).await?.unwrap_or_default())
}

pub(crate) async fn for_branch(state: &Path, branch: &Place) -> Result<Vec<Session>, String> {
    let branch = branch.clone();
    let state_path = state.to_owned();
    Ok(read(state, move |db| {
        let mut statement = db.prepare(
            "SELECT s.data, a.data FROM chat_sessions s LEFT JOIN chat_active_turns a ON a.session_id=s.id \
             ORDER BY s.updated_at DESC,s.id DESC",
        )?;
        let mut sessions = Vec::new();
        for row in statement.query_map([], session_row)? {
            let (data, owner) = row?;
            let saved: Session = serde_json::from_str(&data)?;
            if saved.branch() == branch {
                sessions.push(with_activity(saved, owner, &state_path)?);
            }
        }
        Ok(sessions)
    }).await?.unwrap_or_default())
}

/// Read only active owners, even if they are no longer alive.
pub(crate) async fn active_turns(
    state: &Path,
    live: bool,
) -> Result<Vec<(Session, Owner)>, String> {
    let state_path = state.to_owned();
    Ok(read(state, move |db| {
        let mut query = db.prepare("SELECT s.data, a.data FROM chat_active_turns a JOIN chat_sessions s ON s.id=a.session_id")?;
        let rows = query.query_map([], |row| Ok((row.get::<_, String>(0)?, row.get::<_, String>(1)?)))?;
        let mut active = Vec::new();
        for row in rows {
            let (data, owner) = row?;
            let owner: Owner = serde_json::from_str(&owner)?;
            if owner.live().map_err(Error::Invalid)? == live {
                let mut session: Session = serde_json::from_str(&data)?;
                if !live {
                    refresh_activity(&mut session, &state_path);
                }
                active.push((session, owner));
            }
        }
        Ok(active)
    }).await?.unwrap_or_default())
}

pub(crate) async fn turn_owner(state: &Path, id: &SessionId) -> Result<Option<Owner>, String> {
    let id = id.clone();
    Ok(read(state, move |db| owner(db, &id)).await?.flatten())
}

pub(crate) async fn load(state: &Path, id: &SessionId) -> Result<Session, String> {
    let id = id.clone();
    let state_path = state.to_owned();
    read(state, move |db| load_session(db, &state_path, &id))
        .await?
        .ok_or("No Chat sessions have been saved.".into())
}

fn session_row(row: &rusqlite::Row<'_>) -> rusqlite::Result<(String, Option<String>)> {
    Ok((row.get(0)?, row.get(1)?))
}

fn load_session(db: &Connection, state: &Path, id: &SessionId) -> Result<Session, Error> {
    let row = db.query_row(
        "SELECT s.data, a.data FROM chat_sessions s LEFT JOIN chat_active_turns a ON a.session_id=s.id WHERE s.id=?1",
        [id], session_row,
    ).optional()?.ok_or_else(|| Error::Invalid(format!("No Chat session {id}.")))?;
    session(row, state)
}

fn session((data, owner): (String, Option<String>), state: &Path) -> Result<Session, Error> {
    with_activity(serde_json::from_str(&data)?, owner, state)
}

fn with_activity(
    mut session: Session,
    owner: Option<String>,
    state: &Path,
) -> Result<Session, Error> {
    if let Some(owner) = owner {
        session.running = serde_json::from_str::<Owner>(&owner)?
            .live()
            .map_err(Error::Invalid)?;
    }
    refresh_activity(&mut session, state);
    Ok(session)
}

fn refresh_activity(session: &mut Session, state: &Path) {
    if session.needs_activity() {
        session.refresh_activity(crate::chat::recorded_outcome(state, &session.id));
    }
}

fn owner(db: &Connection, id: &SessionId) -> Result<Option<Owner>, Error> {
    let data: Option<String> = db
        .query_row(
            "SELECT data FROM chat_active_turns WHERE session_id=?",
            [id],
            |row| row.get(0),
        )
        .optional()?;
    data.map(|data| serde_json::from_str(&data).map_err(Error::from))
        .transpose()
}

impl Receipts {
    pub(crate) async fn create_chat(&self, session: &Session) -> Result<(), String> {
        let session = session.clone();
        self.connection
            .call(move |db| {
                db.execute(
                    "INSERT INTO chat_sessions(id,worktree,updated_at,data) VALUES (?,?,?,?)",
                    params![
                        session.id,
                        crate::platform::path_text(&session.worktree),
                        session.updated_at,
                        serde_json::to_string(&session)?
                    ],
                )?;
                Ok::<_, Error>(())
            })
            .await
            .map_err(|error| error.to_string())
    }

    /// Accept the turn with an explicit choice, or take the latest saved choice atomically.
    pub(crate) async fn accept_chat(
        &self,
        session: &Session,
        selection: Option<Model>,
    ) -> Result<Model, String> {
        let mut session = session.clone();
        self.connection
            .call(move |db| {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let current = saved_chat(&transaction, &session.id)?;
                let model = selection.or(current.model).ok_or_else(|| {
                    Error::Invalid(
                        "The saved Chat model was removed before the turn started.".into(),
                    )
                })?;
                session.model = Some(model.clone());
                session.view = current.view;
                session.moved_from = None;
                save(&transaction, &session)?;
                transaction.commit()?;
                Ok::<_, Error>(model)
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn set_chat_model(
        &self,
        state: &Path,
        id: &SessionId,
        selection: Model,
    ) -> Result<Session, String> {
        let state = state.to_owned();
        let id = id.clone();
        self.connection
            .call(move |db| {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut session = load_session(&transaction, &state, &id)?;
                if session.model.as_ref() != Some(&selection) {
                    session.model = Some(selection);
                    session.updated_at = crate::broker::now();
                    save(&transaction, &session)?;
                }
                transaction.commit()?;
                Ok::<_, Error>(session)
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn set_chat_view(
        &self,
        state: &Path,
        id: &SessionId,
        view: SessionView,
    ) -> Result<(Session, bool), String> {
        let state = state.to_owned();
        let id = id.clone();
        self.connection
            .call(move |db| {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut session = load_session(&transaction, &state, &id)?;
                let changed = session.view != view;
                if changed {
                    session.view = view;
                    save(&transaction, &session)?;
                }
                transaction.commit()?;
                Ok::<_, Error>((session, changed))
            })
            .await
            .map_err(|error| error.to_string())
    }

    /// Share the same writer reservation as turn admission. A dead owner does not bar a move.
    pub(crate) async fn set_chat_worktree(
        &self,
        state: &Path,
        id: &SessionId,
        worktree: PathBuf,
        repository: repository::Identity,
    ) -> Result<Option<(Session, bool)>, String> {
        let state = state.to_owned();
        let id = id.clone();
        self.connection
            .call(move |db| {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut session = load_session(&transaction, &state, &id)?;
                if session.running {
                    return Ok::<_, Error>(None);
                }
                let changed = session.worktree != worktree;
                if changed {
                    session.moved_from = Some(std::mem::replace(&mut session.worktree, worktree));
                    session.repository = Some(repository);
                    session.updated_at = crate::broker::now().max(session.updated_at);
                    save(&transaction, &session)?;
                }
                transaction.commit()?;
                Ok(Some((session, changed)))
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn mark_chat_seen(
        &self,
        state: &Path,
        id: &SessionId,
    ) -> Result<bool, String> {
        let state = state.to_owned();
        let id = id.clone();
        self.connection
            .call(move |db| {
                let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
                let mut session = load_session(&transaction, &state, &id)?;
                let changed = session.mark_seen();
                if changed {
                    save(&transaction, &session)?;
                }
                transaction.commit()?;
                Ok::<_, Error>(changed)
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn claim_chat(
        &self,
        state: &Path,
        id: &SessionId,
        claimant: &Owner,
    ) -> Result<Session, String> {
        let state = state.to_owned();
        let id = id.clone();
        let claimant = claimant.clone();
        self.connection.call(move |db| {
            let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
            if let Some(current) = owner(&transaction, &id)?
                && current.live().map_err(Error::Invalid)?
            {
                return Err(Error::Invalid("This Chat session already has an active turn.".into()));
            }
            let session = load_session(&transaction, &state, &id)?;
            let pid = claimant.birth.pid.get();
            let start = i64::try_from(claimant.birth.start_time).map_err(|error| Error::Invalid(error.to_string()))?;
            transaction.execute(
                "INSERT INTO chat_active_turns(session_id,owner_pid,owner_start_time,data) VALUES (?,?,?,?) ON CONFLICT(session_id) DO UPDATE SET owner_pid=excluded.owner_pid,owner_start_time=excluded.owner_start_time,data=excluded.data",
                params![id, pid, start, serde_json::to_string(&claimant)?],
            )?;
            transaction.commit()?;
            Ok(session)
        }).await.map_err(|error| error.to_string())
    }

    /// Request only this exact observed turn, not a replacement accepted after the read.
    pub(crate) async fn stop_chat(&self, id: &SessionId, expected: Owner) -> Result<bool, String> {
        let id = id.clone();
        self.connection
            .call(move |db| {
                if !expected.live().map_err(Error::Invalid)? {
                    return Ok(false);
                }
                let updated = db.execute(
                    "UPDATE chat_active_turns SET data=json_set(data,'$.stop_requested',json('true')) \
                     WHERE session_id=? AND json_extract(data,'$.token')=?",
                    params![id, expected.token],
                )?;
                Ok::<_, Error>(updated != 0)
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn chat_stop_requested(
        &self,
        id: &SessionId,
        expected: &Owner,
    ) -> Result<bool, String> {
        let id = id.clone();
        let token = expected.token.clone();
        self.connection
            .call(move |db| {
                Ok::<_, Error>(
                    owner(db, &id)?
                        .is_some_and(|current| current.token == token && current.stop_requested),
                )
            })
            .await
            .map_err(|error| error.to_string())
    }

    pub(crate) async fn finish_chat(
        &self,
        id: &SessionId,
        owner: &Owner,
        settled: Option<&Session>,
    ) -> Result<bool, String> {
        let id = id.clone();
        let token = owner.token.clone();
        let settled = settled.cloned();
        self.connection.call(move |db| {
            let transaction = db.transaction_with_behavior(TransactionBehavior::Immediate)?;
            let released = transaction.execute("DELETE FROM chat_active_turns WHERE session_id=? AND json_extract(data,'$.token')=?", params![id, token])?;
            if released != 0 && let Some(session) = settled {
                // Keep selector and checkout changes; recovery of a dead owner may race a move.
                let mut current = saved_chat(&transaction, &id)?;
                current.settle_from(&session);
                save(&transaction, &current)?;
            }
            transaction.commit()?;
            Ok::<_, Error>(released != 0)
        }).await.map_err(|error| error.to_string())
    }
}

fn saved_chat(db: &Connection, id: &SessionId) -> Result<Session, Error> {
    let data: String = db.query_row("SELECT data FROM chat_sessions WHERE id=?", [id], |row| {
        row.get(0)
    })?;
    Ok(serde_json::from_str(&data)?)
}

fn save(db: &Connection, session: &Session) -> Result<(), Error> {
    db.execute(
        "UPDATE chat_sessions SET worktree=?, updated_at=?, data=? WHERE id=?",
        params![
            crate::platform::path_text(&session.worktree),
            session.updated_at,
            serde_json::to_string(session)?,
            session.id
        ],
    )?;
    Ok(())
}