Repository navigation
Expand file tree
/
Copy pathstore.rs
More file actions
3653 lines (3519 loc) · 146 KB
/
Copy pathstore.rs
File metadata and controls
3653 lines (3519 loc) · 146 KB
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
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! In-memory SessionStore: create sessions, record events, and trigger persistence.
//!
//! All durable session-map mutations flow through `SessionStoreInner` helpers.
//! Callers outside this module use `SessionStore` methods only.
use serde_json::Value;
use sha2::{Digest, Sha256};
use std::collections::{BTreeMap, BTreeSet, HashMap, VecDeque};
use std::io;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Instant;
use webcodex_core::runner_job_lifecycle::RunnerJobLifecycle;
use webcodex_core::validation_identity::{
assertion_validation_identity, is_validation_execution_identity,
};
use webcodex_core::workflow_session_contract::{is_safe_job_id, PermissionDecision, SessionMode};
use webcodex_tool_contracts::{
runtime_tool_activity_semantics, runtime_tool_session_evidence_policy, ToolActivityKind,
ToolSessionLifecycleEffect,
};
use super::assignment::{
assignment_fence_fingerprint, assignment_fence_from_state, current_assignment_state,
open_assignment_state, validate_assignment_fence,
};
use super::console::{
build_detail as build_console_detail, build_list_item as build_console_list_item,
normalize_console_activity_limit, normalize_console_session_limit, CachedConsoleList,
ConsoleValidationHooks, WorkflowSessionConsoleDetail, WorkflowSessionConsoleList,
WorkflowSessionConsoleListItem,
};
use super::events::{
actual_failure_kind_for_tool_result, changed_paths_for_tool_call,
changed_paths_for_tool_result, classify_error_message, classify_failure_expectation,
context_result_summary_for_tool_result, diff_review_like_for_tool, extract_job_id,
extract_project, is_valid_session_id, observed_input_paths_for_tool,
observed_paths_for_successful_result, persistent_shell_event_evidence_for_tool_result,
sanitize_tool_execution_state, session_input_summary_for_tool,
validation_output_summary_for_tool_result, SessionToolContract,
};
#[cfg(any(test, feature = "root-test-support"))]
use super::model::SESSION_LEDGER_VERSION;
use super::model::{
CodingSessionError, CodingSessionOutcome, CodingSessionRequest, ColdSessionRecord,
CompleteSessionMessageInput, CompleteSessionMessageOutcome, PersistedSessionRecord,
PersistentShellEventEvidence, PostSessionMessageInput, ReplaceSessionMessageInput,
ReplaceSessionMessageOutcome, SessionCloseError, SessionCloseOutcome, SessionCounts,
SessionCreateOptions, SessionDiscoveryItem, SessionDiscoveryPage, SessionEvent,
SessionExecutionContext, SessionExecutionContextUpdateError,
SessionExecutionContextUpdateOutcome, SessionGuardDenial, SessionGuards, SessionLifecycle,
SessionLifecycleDenial, SessionMessage, SessionMessageClosureKind, SessionMessageDelivery,
SessionMessageDeliveryOutcome, SessionMessageDeliveryReplay, SessionMessageError,
SessionMessagePriority, SessionMessageStatus, SessionRecord, SessionRetentionTombstone,
SessionStoreStatus, SessionSummary, SessionTransport, StoredSession, ToolCallExpectation,
ToolCallRecorderMetadata, ToolCallStart, ToolEffectEventEvidence,
WithdrawSessionMessageOutcome, CALL_ID_PREFIX, DEFAULT_MAX_SESSIONS,
DEFAULT_RECENT_EVENT_LIMIT, DEFAULT_SESSION_CACHE_BYTES, DEFAULT_SUMMARY_LIMIT,
EVENT_ID_PREFIX, MAX_CODING_INSTRUCTION_CHARS, MAX_INPUT_ARRAY_ITEMS,
MAX_MATERIALIZED_VALIDATION_JOB_IDS, MAX_MESSAGE_DELIVERY_KEY_CHARS, MAX_SUMMARY_LIMIT,
MESSAGE_ID_PREFIX, SESSION_ID_PREFIX,
};
#[cfg(test)]
use super::model::{
PersistedRetentionTombstoneRow, PersistedSessionLedger, PersistedSessionSnapshot,
};
use super::persistence::{cold_session_from_persisted, materialize_cold_session};
use super::query::{
build_messages_summary, is_valid_completion_id, validate_message_tags, validate_message_text,
validate_resolution_text,
};
use super::util::{
bound_event_error_summary, bound_summary_string, now_ts, redact_and_bound_instruction,
redact_and_bound_value,
};
#[cfg(test)]
#[path = "identifier_tests.rs"]
mod identifier_tests;
mod recency;
mod records;
mod residency;
use crate::persistence::database::{SessionDatabase, SessionWrite};
use records::SessionRecords;
use recency::SessionRecency;
mod writer;
use writer::LedgerWriterGuard;
#[cfg(test)]
mod borrowed_projection_tests;
#[cfg(test)]
mod event_tests;
#[cfg(test)]
mod scale_tests;
#[derive(Debug, Clone)]
pub struct SessionStore {
/// Shared session map and LRU metadata.
/// `pub(super)` so sibling modules can lock and call `SessionStoreInner`
/// transition helpers without touching the maps directly.
pub(super) inner: Arc<Mutex<SessionStoreInner>>,
persistence_write_mutex: Arc<Mutex<()>>,
/// At most one blocking durability write when the dedicated writer is unavailable.
persistence_fallback: Arc<tokio::sync::Semaphore>,
/// Background writer; absent for memory-only stores or a failed thread spawn.
/// Ordinary mutations retain synchronous fallback; durable requests admit
/// one blocking write before asynchronously waiting for its confirmation.
writer: Option<Arc<LedgerWriterGuard>>,
/// Process-local wake signal only; durable observation truth remains in the
/// persisted per-Session revision bookkeeping.
pub(super) message_observation_notify: tokio::sync::watch::Sender<u64>,
#[cfg(any(test, feature = "root-test-support"))]
fail_next_coding_continuity_precommit: Arc<std::sync::atomic::AtomicBool>,
}
/// Owns admission to a durability barrier, not the business mutation itself.
pub(super) struct SessionDurability<'a> {
store: &'a SessionStore,
fallback_permit: Option<tokio::sync::OwnedSemaphorePermit>,
}
impl SessionDurability<'_> {
pub(super) async fn persist(self) -> Result<(), ()> {
if let Some(writer) = &self.store.writer {
let generation = self
.store
.inner
.lock()
.expect("Session store mutex poisoned")
.sessions
.generation;
writer.flush_through(generation).await
} else if let Some(permit) = self.fallback_permit {
let store = self.store.clone();
// The task owns the permit and write after it is scheduled. Dropping
// the requesting future cannot cancel or replay that write.
tokio::task::spawn_blocking(move || {
let _permit = permit;
writer::persist_batch(&store.inner, &store.persistence_write_mutex)
.1
.map(|_| ())
.map_err(|_| ())
})
.await
.map_err(|_| ())?
} else {
Ok(())
}
}
}
#[derive(Debug)]
pub(super) struct SessionStoreInner {
/// Durable workflow sessions. Mutated only via the helpers below.
sessions: SessionRecords,
lru: SessionRecency,
hot_session_capacity_target: usize,
cache_target_bytes: usize,
/// Imported legacy deletion proofs; no new automatic expiry or pruning.
tombstones: BTreeMap<u64, SessionRetentionTombstone>,
tombstone_ids: HashMap<String, u64>,
recent_event_limit: usize,
persistence: Option<SessionPersistence>,
}
#[derive(Debug, Clone)]
struct SessionPersistence {
path: PathBuf,
database: Arc<SessionDatabase>,
restored_sessions: usize,
last_persist_error: Option<String>,
}
impl Default for SessionStore {
fn default() -> Self {
Self::new_in_memory(DEFAULT_MAX_SESSIONS, DEFAULT_RECENT_EVENT_LIMIT)
}
}
impl SessionStore {
pub fn new(max_sessions: usize, recent_event_limit: usize) -> Self {
Self::new_in_memory(max_sessions, recent_event_limit)
}
/// Memory-only embedder/fixture; its Hot count target never deletes identity.
pub fn new_in_memory(hot_session_capacity_target: usize, recent_event_limit: usize) -> Self {
let (message_observation_notify, _) = tokio::sync::watch::channel(0_u64);
Self {
inner: Arc::new(Mutex::new(SessionStoreInner {
sessions: SessionRecords::default(),
lru: SessionRecency::default(),
hot_session_capacity_target,
cache_target_bytes: DEFAULT_SESSION_CACHE_BYTES,
tombstones: BTreeMap::new(),
tombstone_ids: HashMap::new(),
recent_event_limit,
persistence: None,
})),
persistence_write_mutex: Arc::new(Mutex::new(())),
persistence_fallback: Arc::new(tokio::sync::Semaphore::new(1)),
writer: None,
message_observation_notify,
#[cfg(any(test, feature = "root-test-support"))]
fail_next_coding_continuity_precommit: Arc::new(std::sync::atomic::AtomicBool::new(
false,
)),
}
}
/// Legacy fixture signature retained only to exercise old count thresholds.
#[cfg(any(test, feature = "root-test-support"))]
pub fn new_in_memory_with_limits(
hot: usize,
_retired_history_limit: usize,
recent: usize,
) -> Self {
Self::new_in_memory(hot, recent)
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn with_persistence(
path: impl Into<PathBuf>,
max_sessions: usize,
recent_event_limit: usize,
) -> Self {
Self::with_persistence_limits(path, max_sessions, max_sessions, recent_event_limit)
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn with_persistence_limits(
path: impl Into<PathBuf>,
_hot_session_capacity_target: usize,
_historical_session_retention_limit: usize,
recent_event_limit: usize,
) -> Self {
let legacy = path.into();
let database = legacy.with_extension("sqlite3");
Self::open_database(
database,
Some(&legacy),
DEFAULT_SESSION_CACHE_BYTES,
recent_event_limit,
)
.expect("open Workflow Session database")
}
/// Open the SQLite domain in the configured Server database. Startup fails
/// closed on storage or migration errors; it never substitutes an empty store.
pub fn open_database(
path: impl Into<PathBuf>,
legacy: Option<&std::path::Path>,
cache_target_bytes: usize,
recent_event_limit: usize,
) -> io::Result<Self> {
let path = path.into();
let database = SessionDatabase::open(&path)?;
if let Some(legacy) = legacy {
database.import_legacy(legacy)?;
}
let inventory = database.inventory()?;
let mut lru = SessionRecency::default();
let mut sessions = HashMap::new();
let mut generation = 0;
for record in inventory {
generation = generation.max(record.database_revision);
lru.touch(
&record.session_id,
record.lifecycle == SessionLifecycle::Closed,
);
sessions.insert(record.session_id.clone(), StoredSession::Cold(record));
}
let mut tombstones = BTreeMap::new();
let mut tombstone_ids = HashMap::new();
for (index, mut tombstone) in database.tombstones()?.into_iter().enumerate() {
let ordinal = index as u64 + 1;
tombstone.expiry_ordinal = ordinal;
tombstone_ids.insert(tombstone.session_id.clone(), ordinal);
tombstones.insert(ordinal, tombstone);
}
let restored_sessions = sessions.len();
let inner = Arc::new(Mutex::new(SessionStoreInner {
sessions: SessionRecords {
generation,
..SessionRecords::restored(sessions)
},
lru,
hot_session_capacity_target: DEFAULT_MAX_SESSIONS,
cache_target_bytes,
tombstones,
tombstone_ids,
recent_event_limit: recent_event_limit.max(1),
persistence: Some(SessionPersistence {
path,
database,
restored_sessions,
last_persist_error: None,
}),
}));
let persistence_write_mutex = Arc::new(Mutex::new(()));
let writer =
LedgerWriterGuard::spawn(Arc::clone(&inner), Arc::clone(&persistence_write_mutex));
let (message_observation_notify, _) = tokio::sync::watch::channel(0_u64);
Ok(Self {
inner,
persistence_write_mutex,
persistence_fallback: Arc::new(tokio::sync::Semaphore::new(1)),
writer,
message_observation_notify,
#[cfg(any(test, feature = "root-test-support"))]
fail_next_coding_continuity_precommit: Arc::new(std::sync::atomic::AtomicBool::new(
false,
)),
})
}
/// Synchronous fixture barrier. Production async callers use `flush` and
/// propagate its error; inspecting status does not itself confirm durability.
#[cfg(any(test, feature = "root-test-support"))]
pub fn flush_persistence(&self) {
if let Some(writer) = &self.writer {
writer.flush();
}
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn set_persistence_failure_for_test(&self, fail: bool) {
let database = self
.inner
.lock()
.unwrap()
.persistence
.as_ref()
.unwrap()
.database
.clone();
database.fail_writes(fail);
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn persisted_json_for_test(&self) -> String {
self.flush_persistence();
let database = self
.inner
.lock()
.unwrap()
.persistence
.as_ref()
.unwrap()
.database
.clone();
let rows = database
.inventory()
.unwrap()
.into_iter()
.map(|cold| database.load(&cold, usize::MAX).unwrap())
.collect::<Vec<_>>();
serde_json::to_string(
&serde_json::json!({"version": SESSION_LEDGER_VERSION, "sessions": rows}),
)
.unwrap()
}
pub fn status(&self) -> SessionStoreStatus {
let inner = self.inner.lock().expect("session store mutex poisoned");
let (persistence, restored_sessions, last_persist_error) = match &inner.persistence {
Some(persistence) => (
"enabled".to_string(),
persistence.restored_sessions,
persistence.last_persist_error.clone(),
),
None => ("disabled".to_string(), 0, None),
};
let active_sessions = inner
.sessions
.values()
.filter(|session| session.lifecycle() == SessionLifecycle::Active)
.count();
let closed_sessions = inner.sessions.len().saturating_sub(active_sessions);
let hot_sessions = inner
.sessions
.values()
.filter(|session| matches!(session, StoredSession::Hot(_)))
.count();
let cold_sessions = inner.sessions.len().saturating_sub(hot_sessions);
SessionStoreStatus {
persistence,
restored_sessions,
retained_sessions: inner.sessions.len(),
active_sessions,
closed_sessions,
hot_sessions,
cold_sessions,
active_cold_sessions: inner.sessions.values().filter(|entry| {
matches!(entry, StoredSession::Cold(cold) if cold.lifecycle.allows_mutation())
}).count(),
cold_payload_bytes: inner.sessions.values().filter_map(|entry| {
match entry {
StoredSession::Cold(cold) => Some(cold.raw.get().len()),
StoredSession::Hot(_) => None,
}
}).sum(),
cache_target_bytes: inner.persistence.as_ref().map(|_| inner.cache_target_bytes),
retention_tombstones: inner.tombstones.len(),
recent_event_limit: inner.recent_event_limit,
last_persist_error,
}
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn active_session_count_for_test(&self, project: Option<&str>) -> usize {
let inner = self.inner.lock().expect("session store mutex poisoned");
inner
.sessions
.values()
.filter(|record| {
record.lifecycle() == SessionLifecycle::Active
&& project.is_none_or(|project| record.project() == Some(project))
})
.count()
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn hot_payload_entry_count_for_test(&self, session_id: &str) -> Option<usize> {
self.inner
.lock()
.expect("session store mutex poisoned")
.sessions
.get(session_id)?
.hot()
.map(|record| record.events.len() + record.messages.len())
}
#[cfg(any(test, feature = "root-test-support"))]
pub fn cold_payload_bytes_for_test(&self, session_id: &str) -> Option<usize> {
let inner = self.inner.lock().expect("session store mutex poisoned");
match inner.sessions.get(session_id)? {
StoredSession::Hot(_) => None,
StoredSession::Cold(record) => Some(record.raw.get().len()),
}
}
/// Thin convenience wrapper — creation always goes through
/// [`Self::start_session_with_options`].
#[cfg(any(test, feature = "root-test-support"))]
pub fn start_session(&self, project: Option<String>, title: Option<String>) -> SessionSummary {
self.start_session_with_guards(
project,
title,
SessionMode::Normal,
SessionGuards::default(),
)
}
/// Thin convenience wrapper — creation always goes through
/// [`Self::start_session_with_options`].
#[cfg(any(test, feature = "root-test-support"))]
pub fn start_session_with_guards(
&self,
project: Option<String>,
title: Option<String>,
mode: SessionMode,
guards: SessionGuards,
) -> SessionSummary {
self.start_session_with_options(SessionCreateOptions::new(project, title, mode, guards))
.expect("default Session execution context must be valid")
}
/// Sole create entry point for workflow sessions.
///
/// Stores session-creation inputs (including project instructions) on the
/// `SessionRecord`. Convenience wrappers above all delegate here.
pub fn start_session_with_options(
&self,
mut opts: SessionCreateOptions,
) -> Result<SessionSummary, String> {
opts.execution_context = opts.execution_context.validated()?;
#[cfg(any(test, feature = "root-test-support"))]
if opts.owner_authority_fingerprint.is_none() {
// Direct store fixtures do not have an AuthContext. Give them an
// explicit cfg(test)-only authority so production invariants never
// depend on an optional creation-time fingerprint.
opts.owner_authority_fingerprint =
Some(super::TEST_ONLY_PROJECT_SESSION_AUTHORITY_FINGERPRINT.to_string());
}
if opts.project.is_none() && !opts.execution_context.is_empty() {
return Err(
"execution_context requires a Workflow Session bound to a registered project"
.to_string(),
);
}
let summary = {
let mut inner = self.inner.lock().expect("session store mutex poisoned");
let session_id = inner
.allocate_session_id(webcodex_core::compact::random_suffix::<12>)
.ok_or_else(|| "session_id_allocation_exhausted".to_string())?;
let now = now_ts();
let guards = SessionGuards::effective(opts.mode, opts.guards);
let owner_authority_fingerprint =
opts.owner_authority_fingerprint.ok_or_else(|| {
"Workflow Session creation requires a canonical authority fingerprint"
.to_string()
})?;
let record = SessionRecord {
current_instruction: None,
history_is_durable: false,
event_history_start: 0,
pending_events: Default::default(),
durable: None,
session_id: session_id.clone(),
project: opts.project,
project_identity: opts.project_identity,
owner_authority_fingerprint,
title: opts.title,
mode: opts.mode,
guards,
execution_context: opts.execution_context,
// Create always yields Active; only explicit close transitions later.
lifecycle: SessionLifecycle::Active,
created_at: now,
updated_at: now,
messages: VecDeque::new(),
message_delivery_replays: Default::default(),
events: VecDeque::new(),
events_observed: 0,
git_baseline_tree: None,
repository_edit_observed: false,
materialized_validation_job_ids: VecDeque::new(),
message_observation_revision: 0,
message_observation_floor: 0,
message_observation_revisions: Default::default(),
assignment_history_floors: Default::default(),
assignment_history_tracking_complete: true,
completion_assignment_fence_fingerprints: Default::default(),
completion_assignment_fence_tracking_complete: true,
project_instructions: opts.project_instructions,
};
inner.insert_session(record)
};
self.persist_after_mutation();
Ok(summary)
}
/// Commit the coding context and accepted instruction under the in-memory
/// store lock. Persistent stores then queue the updated JSON ledger to the
/// background writer; success does not imply disk flush.
///
/// Every fallible check happens before the in-memory commit. Once mutation
/// begins, session creation or capability update and the instruction event
/// are applied under the same store lock and enter one persistence generation.
pub fn ensure_coding_session(
&self,
request: CodingSessionRequest,
) -> Result<CodingSessionOutcome, CodingSessionError> {
self.ensure_coding_session_with_git_baseline(request, None)
}
/// Coding bootstrap variant used by `work_on_project` to bind one fresh
/// startup Git tree. Exact continuation ignores the supplied candidate and
/// preserves the durable Session baseline already recorded at creation.
pub fn ensure_coding_session_with_git_baseline(
&self,
request: CodingSessionRequest,
git_baseline_tree: Option<String>,
) -> Result<CodingSessionOutcome, CodingSessionError> {
let explicit_resume_session_id = match request.resume_session_id.as_deref() {
Some(session_id)
if session_id != session_id.trim() || !is_valid_session_id(session_id) =>
{
return Err(CodingSessionError::InvalidResumeSessionId);
}
Some(session_id) => Some(session_id.to_string()),
None => None,
};
let explicit_resume = explicit_resume_session_id.is_some();
let now = now_ts();
let new_event_id = format!("{EVENT_ID_PREFIX}{}", uuid::Uuid::new_v4().simple());
let requested_guards = SessionGuards::effective(request.mode, request.guards);
let requested_execution_context = request
.execution_context
.clone()
.map(SessionExecutionContext::validated)
.transpose()
.map_err(CodingSessionError::InvalidExecutionContext)?;
let instruction = request
.instruction
.as_deref()
.map(str::trim)
.filter(|value| !value.is_empty())
.map(|value| redact_and_bound_instruction(value, MAX_CODING_INSTRUCTION_CHARS));
let outcome = {
let mut inner = self.inner.lock().expect("session store mutex poisoned");
let reusable_session_id = if let Some(session_id) = explicit_resume_session_id {
let Some(stored) = inner.sessions.get(&session_id) else {
if inner
.owned_retention_incarnation(
&session_id,
request.authority_fingerprint.as_str(),
)
.is_some()
{
return Err(CodingSessionError::ResumeRetentionExpired { session_id });
}
return Err(CodingSessionError::UnknownResumeSession { session_id });
};
let lifecycle = stored.lifecycle();
if !lifecycle.allows_mutation() {
return Err(CodingSessionError::ResumeSessionNotActive {
session_id,
lifecycle,
});
}
if stored.project() != Some(request.project.as_str()) {
return Err(CodingSessionError::ResumeProjectMismatch {
session_id,
session_project: stored.project().map(str::to_string),
request_project: request.project.clone(),
});
}
if stored.project_identity() != request.project_identity.as_deref() {
return Err(CodingSessionError::ResumeProjectIdentityChanged { session_id });
}
Some(session_id)
} else {
None
};
if let Some(session_id) = reusable_session_id.as_deref() {
let stored_fingerprint = inner
.sessions
.get(session_id)
.expect("reusable session must exist")
.owner_authority_fingerprint();
#[cfg(any(test, feature = "root-test-support"))]
let synthetic_test_fixture =
stored_fingerprint == super::TEST_ONLY_PROJECT_SESSION_AUTHORITY_FINGERPRINT;
#[cfg(not(any(test, feature = "root-test-support")))]
let synthetic_test_fixture = false;
if !synthetic_test_fixture
&& stored_fingerprint != request.authority_fingerprint.as_str()
{
return Err(CodingSessionError::ResumeAuthorityMismatch {
session_id: session_id.to_string(),
});
}
}
if let Some(session_id) = reusable_session_id {
if !inner.prepare_record_mutation(&session_id) {
return Err(CodingSessionError::CommitFailed);
}
let (previous_mode, previous_guards, previous_execution_context) = {
let record = inner
.sessions
.get(&session_id)
.and_then(StoredSession::hot)
.expect("active reusable session must stay hot");
(record.mode, record.guards, record.execution_context.clone())
};
// Repeating a mode preserves any stricter explicit guard from
// the root task. A real mode transition applies the newly
// requested effective guard profile.
let next_guards = if previous_mode == request.mode {
SessionGuards {
deny_write_tools: previous_guards.deny_write_tools
|| requested_guards.deny_write_tools,
deny_shell_tools: previous_guards.deny_shell_tools
|| requested_guards.deny_shell_tools,
}
} else {
requested_guards
};
let capability_changed =
previous_mode != request.mode || previous_guards != next_guards;
let next_execution_context = requested_execution_context
.clone()
.unwrap_or_else(|| previous_execution_context.clone());
let execution_context_changed =
next_execution_context != previous_execution_context;
if previous_guards.deny_write_tools
&& !next_guards.deny_write_tools
&& !request.write_scope_verified
{
return Err(CodingSessionError::WriteScopeRequired);
}
if self.take_coding_continuity_fault() {
return Err(CodingSessionError::CommitFailed);
}
// Snapshot the previous attempt *before* appending the new
// task_instruction. Continuation feedback projects over this so
// it describes what the previous attempt did, not the empty new
// attempt. Use the per-session evidence cap so a long previous
// attempt's work is retained for the projection.
let pre_instruction_summary = inner
.summary(&session_id, Some(DEFAULT_RECENT_EVENT_LIMIT))
.expect("reusable session must summarize before instruction append");
let event = coding_instruction_event(
&new_event_id,
&session_id,
&request.project,
instruction.clone(),
request.transport,
request.mode,
Some(previous_mode),
requested_guards,
Some(previous_guards),
capability_changed,
request.context_refreshed,
requested_execution_context.clone(),
Some(previous_execution_context.clone()),
execution_context_changed,
true,
explicit_resume,
now,
);
{
let max_events = inner.recent_event_limit;
let record = inner
.sessions
.get_mut(&session_id)
.and_then(StoredSession::hot_mut)
.expect("active reusable session must stay hot before commit");
record.mode = request.mode;
record.guards = next_guards;
record.execution_context = next_execution_context;
record.updated_at = now;
if let Some(project_instructions) = request.project_instructions {
record.project_instructions = Some(
project_instructions
.retain_unavailable_scopes(record.project_instructions.as_ref()),
);
}
append_event(record, event, max_events);
}
inner.touch(&session_id);
let summary = inner
.summary(&session_id, Some(DEFAULT_SUMMARY_LIMIT))
.expect("continued session must summarize");
CodingSessionOutcome {
project_instructions: inner
.sessions
.get(&session_id)
.and_then(StoredSession::hot)
.and_then(|record| record.project_instructions.clone()),
summary,
pre_instruction_summary: Some(pre_instruction_summary),
reused: true,
previous_mode: Some(previous_mode),
previous_guards: Some(previous_guards),
capability_changed,
execution_context_changed,
}
} else {
if self.take_coding_continuity_fault() {
return Err(CodingSessionError::CommitFailed);
}
let new_session_id = inner
.allocate_session_id(webcodex_core::compact::random_suffix::<12>)
.ok_or(CodingSessionError::CommitFailed)?;
let execution_context = requested_execution_context.clone().unwrap_or_default();
let execution_context_changed = !execution_context.is_empty();
let event = coding_instruction_event(
&new_event_id,
&new_session_id,
&request.project,
instruction.clone(),
request.transport,
request.mode,
None,
requested_guards,
None,
false,
request.context_refreshed,
requested_execution_context,
None,
execution_context_changed,
false,
false,
now,
);
let record = SessionRecord {
current_instruction: None,
history_is_durable: false,
event_history_start: 0,
pending_events: Default::default(),
durable: None,
session_id: new_session_id.clone(),
project: Some(request.project.clone()),
project_identity: request.project_identity.clone(),
owner_authority_fingerprint: request.authority_fingerprint.clone(),
// The first accepted instruction remains the root title.
// Follow-up instructions never overwrite it.
title: instruction,
mode: request.mode,
guards: requested_guards,
execution_context,
lifecycle: SessionLifecycle::Active,
created_at: now,
updated_at: now,
messages: VecDeque::new(),
message_delivery_replays: Default::default(),
events: VecDeque::from([Arc::new(event)]),
events_observed: 1,
git_baseline_tree,
repository_edit_observed: false,
materialized_validation_job_ids: VecDeque::new(),
message_observation_revision: 0,
message_observation_floor: 0,
message_observation_revisions: Default::default(),
assignment_history_floors: Default::default(),
assignment_history_tracking_complete: true,
completion_assignment_fence_fingerprints: Default::default(),
completion_assignment_fence_tracking_complete: true,
project_instructions: request.project_instructions,
};
let project_instructions = record.project_instructions.clone();
let summary = inner.insert_session(record);
CodingSessionOutcome {
project_instructions,
summary,
pre_instruction_summary: None,
reused: false,
previous_mode: None,
previous_guards: None,
capability_changed: false,
execution_context_changed,
}
}
};
self.persist_after_mutation();
Ok(outcome)
}
#[cfg(any(test, feature = "root-test-support"))]
/// Inject a failure before any in-memory continuity mutation. This does
/// not model background ledger persistence failure or rollback.
pub fn fail_next_coding_continuity_precommit_for_test(&self) {
self.fail_next_coding_continuity_precommit
.store(true, std::sync::atomic::Ordering::SeqCst);
}
#[cfg(any(test, feature = "root-test-support"))]
fn take_coding_continuity_fault(&self) -> bool {
self.fail_next_coding_continuity_precommit
.swap(false, std::sync::atomic::Ordering::SeqCst)
}
#[cfg(not(any(test, feature = "root-test-support")))]
fn take_coding_continuity_fault(&self) -> bool {
false
}
pub fn summary(&self, session_id: &str, limit: Option<usize>) -> Option<SessionSummary> {
self.with_record_for_query(session_id, |record, cold| {
summarize_record(record, limit, cold)
})
}
/// Exact retained changed-path evidence for recovery attribution. Unlike
/// `summary`, this scans the full bounded durable event ledger instead of the
/// model-facing 200-event tail, so ordinary presentation truncation does not
/// masquerade as history loss. The boolean is true only when the retained
/// ledger and each event's changed-path projection are known complete.
pub fn retained_changed_path_evidence(&self, session_id: &str) -> Option<(Vec<String>, bool)> {
self.with_record_for_query(session_id, |record, _cold| {
let mut paths = BTreeSet::new();
let mut complete = record.events_observed <= record.events.len() as u64;
// Every persisted event sanitizes changed_paths to MAX_INPUT_ARRAY_ITEMS,
// and runtime audit arguments can already be bounded before the Store
// observes them. Equality to that durable bound therefore cannot prove
// the original path set was complete, even while the Session is hot.
for event in super::events::canonical_tool_call_finished_event_refs(
record.events.iter().map(Arc::as_ref),
) {
// Path attribution is consequence evidence, not an attempted-write
// list. A failed/no-op edit can name the same path without proving
// that this Session caused the current dirty state.
if !event_observes_repository_edit(event) {
continue;
}
if event.changed_paths.len() >= MAX_INPUT_ARRAY_ITEMS {
complete = false;
}
paths.extend(event.changed_paths.iter().cloned());
}
(paths.into_iter().collect(), complete)
})
}
/// Latest retained task-instruction identity at an exact Session event-count
/// snapshot. Unlike `summary`, this scans the full bounded durable ledger so
/// the model-facing 200-event tail cannot erase the current attempt identity.
/// `through_events_total` fences the lookup against a later instruction racing
/// the caller's already-observed Session snapshot. Durable eviction remains
/// fail-closed and therefore returns `None`.
pub fn retained_task_instruction_event_id_at(
&self,
session_id: &str,
through_events_total: usize,
) -> Option<String> {
self.with_record_for_query(session_id, |record, _| {
let total = usize::try_from(record.events_observed).ok()?;
if through_events_total > total {
return None;
}
if through_events_total == total {
return record
.current_instruction
.as_ref()
.map(|event| event.event_id.clone());
}
let first = total.saturating_sub(record.events.len());
let tail = record
.events
.iter()
.take(through_events_total.saturating_sub(first))
.rev()
.find(|event| event.kind == "task_instruction")
.map(|event| event.event_id.clone());
tail.or_else(|| {
record
.durable
.as_ref()?
.database
.as_ref()?
.instruction_at(session_id, through_events_total)
.ok()
.flatten()
})
})
.flatten()
}
/// Discover only identities in the already-authorized exact Project and
/// creation-time authority group. Filter before counting/pagination; foreign
/// Sessions cannot affect totals or hide authorized rows behind a page limit.
/// Inventory ordering is presentation only, never an implicit resume rule.
pub fn discover_sessions(
&self,
project: &str,
owner_authority_fingerprint: &str,
lifecycle: Option<SessionLifecycle>,
offset: usize,
limit: usize,
) -> SessionDiscoveryPage {
let limit = limit.clamp(1, 20);
let mut candidates = {
let inner = self.inner.lock().expect("session store mutex poisoned");
inner
.sessions
.values()
.filter(|record| {
record.project() == Some(project)
&& record.owner_authority_fingerprint() == owner_authority_fingerprint
&& lifecycle.is_none_or(|state| record.lifecycle() == state)
})
.map(|record| (record.session_id().to_string(), record.updated_at()))
.collect::<Vec<_>>()
};
candidates.sort_by(|left, right| right.1.cmp(&left.1).then_with(|| right.0.cmp(&left.0)));
let total = candidates.len();
let end = offset.saturating_add(limit).min(total);
let sessions = candidates
.into_iter()
.skip(offset)
.take(limit)
.filter_map(|(session_id, _)| {
self.with_record_for_query(&session_id, |record, _| {
if record.project.as_deref() != Some(project)
|| record.owner_authority_fingerprint != owner_authority_fingerprint
|| lifecycle.is_some_and(|state| record.lifecycle != state)
{
return None;
}
let title = record.title.as_deref().map(|title| {
redact_and_bound_instruction(title, 240)
.chars()
.take(240)
.collect::<String>()
});
let title_truncated = title.as_deref() != record.title.as_deref();
Some(SessionDiscoveryItem {
session_id: record.session_id.clone(),
title,
title_truncated,
lifecycle: record.lifecycle,
created_at: record.created_at,
updated_at: record.updated_at,
})
})
.flatten()
})
.collect();
SessionDiscoveryPage {
total,
offset,