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
//! Post-creation field setters for [`SessionManager`] records (#7087).
//!
//! Why: extracted from `manager.rs` when residency-generation tracking (#7087
//! slice 1b) needed room under that file's 500-SLOC production cap. This
//! follows the precedent `stop.rs` / `create.rs` / `reactivate.rs` /
//! `reconcile.rs` already set for this file: a cohesive group of methods moves
//! to its own sibling module rather than the cap being gamed or raised. The
//! group is cohesive because every method here is the same shape — a plain
//! read-modify-write against one existing record, called AFTER the session
//! already exists (`create`/`stop`/`resume` cover the state-machine
//! transitions; these cover incidental fields set alongside or after them).
//! What: [`SessionManager::mark_errored`], [`SessionManager::set_workspace`],
//! [`SessionManager::set_pending_decision`],
//! [`SessionManager::set_source_id`], [`SessionManager::set_deliverable_id`],
//! and [`SessionManager::clear_pending_decision`]. No behavior change — a pure
//! relocation.
//! Test: covered by handler_spawn_wires_provision_and_spawn (`mark_errored`,
//! `set_workspace`), `front_gate_escalation_sets_pending_decision` and
//! `front_gate_answer_unblocks_spawn` in tests/session_manager_mvp.rs
//! (`set_pending_decision`, `clear_pending_decision`),
//! `set_source_id_succeeds_first_try` /
//! `set_source_id_returns_err_after_retries_for_missing_session` in
//! `tests.rs` (`set_source_id`), `set_deliverable_id_persists` /
//! `set_deliverable_id_missing_session_errors` in
//! `set_deliverable_id_tests.rs` (`set_deliverable_id`).
use chrono::Utc;
use tracing::{error, warn};
use super::manager::{ManagedError, SessionManager};
use super::record::{ManagedSessionId, ManagedSessionState};
impl SessionManager {
/// Mark a session as errored with a message.
///
/// Why: when provisioning or spawning fails the session must not remain in
/// `Provisioning`; marking it errored surfaces the failure to `tm session ls`.
/// What: transitions the record to `ManagedSessionState::Errored` and appends
/// the error message to the task field for observability, then persists.
/// Test: covered by handler_spawn_wires_provision_and_spawn error path;
/// the #7087 residency bump by `generation_increments_across_mark_errored`
/// in `daemon::managed_routes::residency`'s route tests.
pub async fn mark_errored(
&self,
id: &ManagedSessionId,
error_msg: &str,
) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
record.state = ManagedSessionState::Errored;
record.task = format!("{} [error: {}]", record.task, error_msg);
self.store.write().await.upsert(record).await?;
// #7087: `Errored` is not `Active`/`Provisioning`, so a failed spawn,
// a failed resume or a parked auto-resume drops the session out of the
// set `mpm.residency.active` serves.
self.bump_residency_generation();
Ok(())
}
/// Strip the `[error: …]` notes [`SessionManager::mark_errored`] appended.
///
/// Why (#8233 acceptance item 3): `mark_errored` APPENDS its message to
/// `task`, and nothing ever removed it. A session that failed to launch
/// three times and then came up healthy showed three stale failures in
/// `tm ls` forever, which is how `tm-crm` sat `active` behind a live
/// `claude` still advertising "resume relaunch did not take". A verified
/// Running verdict is the moment those notes stop describing the session.
/// What: rewrites `task` with every `[error: …]` suffix removed, and
/// persists ONLY when something changed — a no-op costs no store write. The
/// state is not touched: this clears the note, never the verdict.
/// Test: `clear_error_note_strips_every_appended_error`,
/// `clear_error_note_leaves_a_clean_task_alone`.
pub async fn clear_error_note(&self, id: &ManagedSessionId) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
let cleaned = strip_error_notes(&record.task);
if cleaned == record.task {
return Ok(());
}
record.task = cleaned;
self.store.write().await.upsert(record).await?;
Ok(())
}
/// Update a session's workspace path and transition to a new state.
///
/// Why: after the workspace path is resolved
/// must be persisted so `tm session ls` shows it and `activity` can infer
/// context.
/// What: looks up the record, sets `workspace_path` and `state`, and persists.
///
/// #7087: `new_state` is arbitrary, and this method does NOT bump the
/// residency generation. Every caller today passes `Active` onto a
/// `Provisioning` record, which stays inside the set
/// `mpm.residency.active` serves, so no bump is owed. A caller that passes
/// a state OUTSIDE `Active`/`Provisioning` crosses that boundary and must
/// call [`SessionManager::bump_residency_generation`] itself — or route
/// through the verb that owns that transition (`stop`, `mark_errored`,
/// `decommission`, `delete_record`), which is the better answer.
/// Test: covered by handler_spawn_wires_provision_and_spawn.
pub async fn set_workspace(
&self,
id: &ManagedSessionId,
workspace_path: std::path::PathBuf,
new_state: ManagedSessionState,
) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
record.workspace_path = Some(workspace_path);
record.state = new_state;
self.store.write().await.upsert(record).await?;
Ok(())
}
/// Record a pending decision (an escalation) on a session, awaiting a human.
///
/// Why: the intent-conformance FRONT gate (#1360) escalates *before* the
/// runtime is spawned. It must surface the divergence reason + the conformant
/// default through the SAME channel the harness uses (`pending_decision` /
/// `proposed_default`), so it appears in `GET …/activity`, MCP
/// `session_status`, the supervisor, and the `tm` CLI with zero new UI. The
/// session is left NOT `Active` (the runtime never started) so it reads as
/// awaiting approval until a human resolves it via `POST …/answer`.
/// What: looks up the record, sets `pending_decision`/`proposed_default`,
/// leaves the lifecycle state untouched (it stays `Provisioning` — the
/// runtime was withheld), and persists. No tmux input is sent (unlike
/// `answer_decision`): the pane has no running harness to receive it yet.
/// Test: `front_gate_escalation_sets_pending_decision` in
/// tests/session_manager_mvp.rs.
pub async fn set_pending_decision(
&self,
id: &ManagedSessionId,
decision: &str,
proposed_default: Option<&str>,
) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
record.pending_decision = Some(decision.to_string());
record.proposed_default = proposed_default.map(str::to_string);
record.last_activity_at = Some(Utc::now());
self.store.write().await.upsert(record).await?;
Ok(())
}
/// Record a source project identity on a session, with a bounded retry
/// (#2157 item 5, the #2154 remedy).
///
/// Why: the in-project spawn path (#1706) associates a session with a
/// specific `owner/repo` so callers can later filter sessions by project
/// and reconnect instead of spawning duplicates. Setting it post-creation
/// (rather than via `create_with_id`) keeps the manager's SINGLE generic
/// create path clean of in-project concerns. Previously a single transient
/// `get`/`upsert` failure here was `warn!`-and-continue at the call site —
/// leaving `source_id: None` on the record PERMANENTLY, which makes the
/// session invisible to every `?source_id=` filtered listing (the guided
/// picker, `tm session ls --project`) forever, since nothing else ever
/// retries the write.
/// What: retries the read-modify-write up to `MAX_SET_SOURCE_ID_ATTEMPTS`
/// times with a short linear backoff between attempts, returning `Ok(())`
/// on the first success. If every attempt fails, logs a `tracing::error!`
/// (loud, not `warn!`) carrying `id` and `source_id` so a future
/// reconcile/doctor pass can self-heal a `source_id: None` record from its
/// `repo_url`/`workspace_path`, then returns the last error.
/// Test: `set_source_id_succeeds_first_try`,
/// `set_source_id_returns_err_after_retries_for_missing_session` in
/// `tests.rs`.
pub async fn set_source_id(
&self,
id: &ManagedSessionId,
source_id: &str,
) -> Result<(), ManagedError> {
const MAX_SET_SOURCE_ID_ATTEMPTS: u8 = 3;
let mut last_err: Option<ManagedError> = None;
for attempt in 1..=MAX_SET_SOURCE_ID_ATTEMPTS {
let result: Result<(), ManagedError> = async {
let mut record = self.get(id).await?;
record.source_id = Some(source_id.to_string());
self.store.write().await.upsert(record).await?;
Ok(())
}
.await;
match result {
Ok(()) => return Ok(()),
Err(e) => {
warn!(
id = %id,
attempt,
max_attempts = MAX_SET_SOURCE_ID_ATTEMPTS,
"set_source_id: attempt failed: {e}"
);
last_err = Some(e);
if attempt < MAX_SET_SOURCE_ID_ATTEMPTS {
tokio::time::sleep(std::time::Duration::from_millis(
50 * u64::from(attempt),
))
.await;
}
}
}
}
error!(
id = %id,
source_id = %source_id,
attempts = MAX_SET_SOURCE_ID_ATTEMPTS,
"set_source_id: exhausted all attempts — session will be invisible to \
project-filtered listing (source_id: None) until a reconcile/doctor pass \
repairs it from repo_url/workspace_path"
);
Err(last_err.unwrap_or_else(|| ManagedError::SessionNotFound(id.to_string())))
}
/// Record which Deliverable a session is working on (DOC-35 §10.6, #2379).
///
/// Why: `tm sessions new --deliverable <id>` binds a fresh session to a
/// Deliverable AFTER the session record already exists (mirroring
/// [`Self::set_source_id`]'s post-creation setter shape, which keeps
/// [`Self::create_with_id`]'s already-long parameter list from growing
/// further). The caller (the daemon spawn path,
/// `daemon::managed_routes::lifecycle`) validates the Deliverable exists
/// and belongs to the session's project via `DeliverableManager` BEFORE
/// calling this — this setter trusts that validation and does no lookup of
/// its own. Per §11, this is a PURE POINTER write: it never mutates the
/// Deliverable record itself (no auto-transition of its status).
/// What: a plain read-modify-write — look up the record, set
/// `deliverable_id`, persist. No retry loop (unlike `set_source_id`):
/// losing this link on a rare transient store error is a stale pointer,
/// not a session made invisible to a whole filtered listing, so the
/// simpler shape matches `set_workspace`/`set_pending_decision`.
/// Test: `set_deliverable_id_persists`,
/// `set_deliverable_id_missing_session_errors` in `set_deliverable_id_tests.rs`.
pub async fn set_deliverable_id(
&self,
id: &ManagedSessionId,
deliverable_id: crate::deliverable::DeliverableId,
) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
record.deliverable_id = Some(deliverable_id);
self.store.write().await.upsert(record).await?;
Ok(())
}
/// Clear a pending decision WITHOUT injecting any text into the pane.
///
/// Why: a FRONT-gate (#1360) escalation is resolved *before* a harness exists
/// — the session is still `Provisioning` with no runtime in the pane. Unlike
/// [`answer_decision`](Self::answer_decision) (which sends the answer to a
/// LIVE harness), the FRONT-gate answer path must clear the decision and then
/// LAUNCH the withheld runtime; sending the answer to a bare shell would be
/// meaningless. This method does the clear half only.
/// What: looks up the record, clears `pending_decision`/`proposed_default`,
/// updates `last_activity_at`, and persists. No tmux I/O.
/// Test: `front_gate_answer_unblocks_spawn` in tests/session_manager_mvp.rs.
pub async fn clear_pending_decision(&self, id: &ManagedSessionId) -> Result<(), ManagedError> {
let mut record = self.get(id).await?;
record.pending_decision = None;
record.proposed_default = None;
record.last_activity_at = Some(Utc::now());
self.store.write().await.upsert(record).await?;
Ok(())
}
}
/// Remove every ` [error: …]` note from a task string.
///
/// Why: see [`SessionManager::clear_error_note`]. Pure, so the parsing of the
/// shape `mark_errored` writes can be tested without a store.
/// What: scans for the literal ` [error: ` opener and drops through the note's
/// closing `]`. That close is the LAST `]` before the next opener (or before the
/// end), not the first one after the opener — #8233 round 3, finding 8: a
/// message containing its own `]` (`[error: launch spec [tm-x] unreadable]`)
/// closed the note early and left the tail behind, which is precisely the stale
/// text acceptance item 3 exists to remove. Nesting is impossible — the notes
/// are appended, never wrapped — so a single forward scan is still exact. Text
/// with no note is returned unchanged.
/// Test: `strip_error_notes_removes_one`, `strip_error_notes_removes_several`,
/// `strip_error_notes_leaves_unrelated_brackets_alone`,
/// `strip_error_notes_removes_a_note_whose_message_contains_a_bracket`.
pub(crate) fn strip_error_notes(task: &str) -> String {
const OPEN: &str = " [error: ";
let mut out = String::with_capacity(task.len());
let mut rest = task;
while let Some(at) = rest.find(OPEN) {
let (head, tail) = rest.split_at(at);
out.push_str(head);
let body = &tail[OPEN.len()..];
let limit = body.find(OPEN).unwrap_or(body.len());
match body[..limit].rfind(']') {
Some(end) => rest = &body[end + 1..],
// An unterminated note is the whole remainder; drop it.
None => return out,
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod strip_tests {
use super::strip_error_notes;
#[test]
fn strip_error_notes_removes_one() {
assert_eq!(
strip_error_notes("do the thing [error: boom]"),
"do the thing"
);
}
#[test]
fn strip_error_notes_removes_several() {
assert_eq!(strip_error_notes("task [error: one] [error: two]"), "task");
}
/// #8233 round 3, finding 8: the note's own message can contain `]` — the
/// launch failures this issue produces name specs and panes in brackets.
/// Closing on the FIRST `]` left the rest of the message on the task
/// forever, which is the stale text acceptance item 3 removes.
/// Fails on e1ee6cf52 with `"do the thing unreadable]"`.
#[test]
fn strip_error_notes_removes_a_note_whose_message_contains_a_bracket() {
assert_eq!(
strip_error_notes("do the thing [error: launch spec [tm-x] unreadable]"),
"do the thing"
);
assert_eq!(
strip_error_notes("t [error: a [b] c] [error: d [e] f]"),
"t"
);
}
#[test]
fn strip_error_notes_leaves_unrelated_brackets_alone() {
assert_eq!(strip_error_notes("fix [#8233] now"), "fix [#8233] now");
}
}
/// Tests for the record-level clear, as opposed to the string helper above.
///
/// Why: `strip_tests` proves the substring rule; these prove the method applies
/// it to a persisted record and leaves a clean one untouched, which is the
/// #8233 acceptance-item-3 behaviour the caller depends on.
#[cfg(test)]
mod clear_error_note_tests {
use std::sync::Arc;
use crate::session_manager::{FakeNoopTmuxDriver, SessionManager};
/// A hermetic manager plus one session whose `task` the caller chooses.
async fn manager_with_task(
dir: &tempfile::TempDir,
task: &str,
) -> (Arc<SessionManager>, crate::session_manager::SessionRecord) {
let mgr = Arc::new(
SessionManager::new(dir.path(), Arc::new(FakeNoopTmuxDriver))
.await
.expect("session manager"),
);
let mut record = mgr
.create(
"clear-note".into(),
Some(dir.path().to_path_buf()),
None,
None,
None,
None,
)
.await
.expect("create");
record.task = task.to_owned();
mgr.store
.write()
.await
.upsert(record.clone())
.await
.expect("seed the task");
(mgr, record)
}
#[tokio::test]
async fn clear_error_note_strips_every_appended_error() {
let dir = tempfile::tempdir().expect("tempdir");
let (mgr, record) = manager_with_task(
&dir,
"run the fleet [error: resume relaunch did not take] [error: no runtime came up]",
)
.await;
mgr.clear_error_note(&record.id).await.expect("clear");
let cleaned = mgr.get(&record.id).await.expect("record");
assert_eq!(
cleaned.task, "run the fleet",
"a Running verdict must leave no stale failure in `tm ls`"
);
assert_eq!(
cleaned.state, record.state,
"clearing the note must not touch the verdict"
);
}
#[tokio::test]
async fn clear_error_note_leaves_a_clean_task_alone() {
let dir = tempfile::tempdir().expect("tempdir");
let (mgr, record) = manager_with_task(&dir, "fix [#8233] now").await;
mgr.clear_error_note(&record.id).await.expect("clear");
assert_eq!(
mgr.get(&record.id).await.expect("record").task,
"fix [#8233] now",
"a task carrying no error note must survive byte-for-byte"
);
}
}