Repository navigation
Expand file tree
/
Copy pathchatv3_layout.go
More file actions
952 lines (897 loc) · 39.5 KB
/
Copy pathchatv3_layout.go
File metadata and controls
952 lines (897 loc) · 39.5 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
package main
// chatv3_layout.go is where a v3 conversation lives, and which one a launch
// opens.
//
// A session is a FOLDER: ~/.codeaf/v3/projects/<encoded-workspace>/<id>/, with
// the transcript, the sidecars, the node journals and — for an owned session —
// the workspace itself inside it. internal/session's place.go is the arithmetic
// on that folder; this file is the three decisions a launch makes before the
// arithmetic can start:
//
// - WHICH PROJECT. The workspace is the git root of the directory the person
// stood in, so `codeaf` typed in repo/cmd and in repo/ is the same project.
// The encoded directory name is a bucket and not an identity — meta.json
// carries the real path — which is what lets the encoding stay simple.
// - BORROWED OR OWNED. A conversation opened inside a project borrows it and
// litters nothing; one opened nowhere at all owns a workspace of its own.
// - WHICH CONVERSATION. The newest one the PERSON spoke in, or a fresh
// identity — unassigned empty folders are reaped on the way past.
//
// EVERY PATH GOES THROUGH internal/home, so CODEAF_HOME moves all of it.
import (
"context"
"fmt"
"os"
"os/exec"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/Agent-Field/codeaf/internal/cell"
"github.com/Agent-Field/codeaf/internal/cellindex"
"github.com/Agent-Field/codeaf/internal/cellstore"
"github.com/Agent-Field/codeaf/internal/config"
"github.com/Agent-Field/codeaf/internal/executor"
"github.com/Agent-Field/codeaf/internal/gitidentity"
"github.com/Agent-Field/codeaf/internal/home"
"github.com/Agent-Field/codeaf/internal/preflight"
"github.com/Agent-Field/codeaf/internal/session"
"github.com/Agent-Field/codeaf/internal/syncsetup"
"github.com/Agent-Field/codeaf/internal/teams"
"github.com/Agent-Field/codeaf/internal/tui3"
)
// v3Dir is ~/.codeaf/v3: the directory this surface keeps its own files in —
// the model cache, the history list, the drafts, the memory file. The
// conversations live under it in projects/ (see [v3ProjectDir]).
func v3Dir() (string, error) {
dir := home.Join("v3")
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", fmt.Errorf("create session directory: %w", err)
}
return dir, nil
}
// v3ProjectDir is one project's BUCKET: the directory holding every session
// folder this workspace has ever had, plus the project's task index. The name
// is the workspace with its separators turned to dashes — one flat level, and
// readable, because the point of keeping a person's sessions in files is that
// they can find them.
func v3ProjectDir(workspace string) (string, error) {
dir := home.Join("v3", "projects", encodeWorkspace(workspace))
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", fmt.Errorf("create session directory: %w", err)
}
return dir, nil
}
func encodeWorkspace(workspace string) string {
encoded := strings.ReplaceAll(filepath.Clean(workspace), string(filepath.Separator), "-")
encoded = strings.ReplaceAll(encoded, ":", "-")
if !strings.HasPrefix(encoded, "-") {
encoded = "-" + encoded
}
return encoded
}
// ── which project, and does the conversation have one ───────────────────────
// v3Workspace answers the two questions a launch asks about the directory it
// was typed in: which PROJECT this is, and whether the conversation has one at
// all.
//
// The answer's first half is the bucket key and the borrowed session's tools
// root: the git root of the directory, so every subdirectory of a repository is
// the same project, and the directory itself when there is no repository. An
// explicit workspace — the engine's --workspace, a door that has already
// resolved one — is taken as given and is always borrowed: it is a place
// somebody named, and naming a place is asking to work in it.
func v3Workspace(cwd, explicit string) (string, bool) {
if named := strings.TrimSpace(explicit); named != "" {
return named, false
}
if root, found := v3GitRoot(cwd); found {
return root, false
}
return cwd, v3NoProjectPlace(cwd)
}
// v3NoProjectPlace reports whether a directory is somewhere the person stood by
// accident rather than on purpose — the two places a conversation has no
// project to be about.
//
// A PLAIN DIRECTORY IS STILL BORROWED. Somebody who runs codeaf in ~/notes
// means ~/notes: it is not a repository, but it is where their work is, and a
// session that quietly worked in a hidden folder of its own instead would be
// answering questions about the wrong directory. What is left is the home
// directory ITSELF — where a terminal opens, which nobody chose — and the
// temporary directories, which are where a launcher, a script or an editor
// starts a process that was never about a place at all. Those own a workspace,
// and a session whose workspace was temporary is litter the sweep may reap.
func v3NoProjectPlace(dir string) bool {
dir = filepath.Clean(dir)
if home, err := os.UserHomeDir(); err == nil && filepath.Clean(home) == dir {
return true
}
for _, temporary := range []string{os.TempDir(), "/tmp"} {
temporary = filepath.Clean(temporary)
if dir == temporary || strings.HasPrefix(dir, temporary+string(filepath.Separator)) {
return true
}
}
return false
}
// v3GitRootTimeout bounds the one subprocess this answer costs.
//
// IT IS A BACKSTOP AND NOT A BUDGET. `git rev-parse --show-toplevel` walks the
// directory chain and refreshes nothing — no index, no lock — so a tree that
// answers at all answers in milliseconds. What the ceiling is for is the tree
// that does NOT: a dead network mount, a filesystem stalled on somebody else's
// lock, a git that never returns. Unbounded, that is a launch held open forever
// on a question whose "no" was already a legal answer.
//
// It is stated far more generously than internal/tui3's own git budget, which
// is a quarter of a second for a branch name in a border. That answer is
// furniture; THIS one decides which project the conversation is about, and a
// repository whose root was given up on because a disk was briefly slow would
// open the session in the wrong directory. Two seconds is internal/plan's
// terrain budget for the same reason and to the same end — long enough that
// only a wedged git ever reaches it.
const v3GitRootTimeout = 2 * time.Second
// v3GitRoots is every root this process has already watched git name, and it is
// the whole of why one launch shells out once rather than twice.
//
// A LAUNCH ASKS THIS QUESTION TWICE ABOUT ONE REPOSITORY: once for the directory
// the person is standing in ([v3Workspace], deciding which project this is), and
// again for the workspace that came out of it ([v3Subharnesses], looking for the
// project's bundle store). The second call spent a second subprocess on an
// answer the first was already holding.
//
// The dedup is sound because A GIT ROOT IS A FIXED POINT: asked inside the
// toplevel of a worktree, `rev-parse --show-toplevel` prints that same toplevel,
// so a directory git has already named as a root answers itself. The string
// handed back is git's own, recorded exactly as git printed it.
//
// ONLY ROOTS ARE REMEMBERED, NEVER THE ABSENCE OF ONE. A directory that is not
// in a repository is asked again every time, because a repository can appear
// under a running process — [initOwnedRepository] does precisely that to an
// owned session's work directory, before [v3Subharnesses] goes looking for a
// project store in it — and a cached "there is nothing here" would outlive the
// truth by the whole life of the process.
var v3GitRoots struct {
sync.Mutex
known map[string]bool
}
// v3GitRoot is `git rev-parse --show-toplevel` in one directory. A machine with
// no git, a directory that is not in a repository, and a repository this build
// cannot read all answer the same thing — no root — because all three mean the
// same to the caller: there is nothing here to call a project. A git that hangs
// past [v3GitRootTimeout] joins them, and the silence is deliberate: this
// function has one way of saying it could not tell, and every caller already
// handles it.
func v3GitRoot(dir string) (string, bool) {
if root, known := v3KnownGitRoot(dir); known {
return root, true
}
ctx, cancel := context.WithTimeout(context.Background(), v3GitRootTimeout)
defer cancel()
command := exec.CommandContext(ctx, "git", "--no-optional-locks", "rev-parse", "--show-toplevel")
command.Dir = dir
out, err := command.Output()
if err != nil {
return "", false
}
root := strings.TrimSpace(string(out))
if root == "" {
return "", false
}
v3RememberGitRoot(root)
return root, true
}
// v3KnownGitRoot answers from [v3GitRoots] when this directory is one git has
// already named a root of, and nothing at all otherwise.
func v3KnownGitRoot(dir string) (string, bool) {
dir = strings.TrimSpace(dir)
if dir == "" || !filepath.IsAbs(dir) {
// A relative directory is resolved against the subprocess's own working
// directory rather than against anything this table holds, so it is not a
// key here and never becomes one.
return "", false
}
dir = filepath.Clean(dir)
v3GitRoots.Lock()
defer v3GitRoots.Unlock()
if v3GitRoots.known[dir] {
return dir, true
}
return "", false
}
// v3RememberGitRoot records a root git has just printed.
func v3RememberGitRoot(root string) {
v3GitRoots.Lock()
defer v3GitRoots.Unlock()
if v3GitRoots.known == nil {
v3GitRoots.known = map[string]bool{}
}
v3GitRoots.known[filepath.Clean(root)] = true
}
// ── which conversation ──────────────────────────────────────────────────────
// v3Session is one launch's answer: the folder, the journal inside it, and
// whether the conversation was found rather than made.
type v3Session struct {
Place session.Place
Transcript string
Resumed bool
// Bucket is the project directory the folder sits in, which the surface
// needs after the launch for its list of recent conversations.
Bucket string
}
// v3ResolveSession decides which conversation this launch opens.
//
// THE ORDER IS THE LAW, and every step of it is Decision 26's:
//
// 1. An explicit --session is taken as given. A path a person named is a path
// they mean, existing or not, and an old flat transcript still opens as
// itself — with no Place, which is what the legacy layout is spelled as.
// 2. Otherwise the newest conversation the PERSON last spoke in, read from
// meta.json rather than from file mtime: a background write touching a file
// is not somebody returning to a conversation.
// 3. Otherwise a new identity is minted, protecting empty conversations that
// might acquire team membership after discovery.
//
// And the other empties are reaped on the way past.
func v3ResolveSession(explicit, workspace, launchDir string, owned bool) (v3Session, error) {
if explicit != "" {
return v3NamedSession(explicit, workspace, owned)
}
bucket, err := v3ProjectDir(workspace)
if err != nil {
return v3Session{}, err
}
spoken, empty := v3ScanBucket(bucket)
if folder, resumed, found := v3PickFolder(spoken, empty, true); found {
// C29.2: the first paint never waits for an older folder's capture.
// Home can open its independent copy asynchronously through v3Reopen;
// this launch holds a fresh shell while the background worker copies.
if resumed && cell.Available() && syncsetup.MayTalk(home.Dir()) {
if _, err := cell.OpenAt(folder.dir, filepath.Base(folder.dir)); err != nil {
place, err := v3MintSession(bucket, workspace, launchDir, owned)
return v3Session{Place: place, Transcript: place.Transcript(), Bucket: bucket}, err
}
}
// A folder somebody has spoken in carries its OWN posture — a
// conversation that owns its workspace goes on owning it whatever
// terminal reopens it — while an empty one has nothing to remember and
// takes this launch's.
keeps := owned
keep := ""
if resumed {
keeps = owned || folder.meta.Owned
} else {
// The folder this launch is about to open is the one empty it may
// not reap.
keep = folder.dir
}
place := v3PlaceFor(folder.dir, workspace, keeps)
v3ReapEmpty(empty, keep)
// Resumed only for a folder somebody has SPOKEN in: there is nothing to
// come back to in an empty one, and a surface that said "resumed" about
// a folder with no words in it would be naming a conversation that never
// happened.
return v3Session{Place: place, Transcript: place.Transcript(), Resumed: resumed, Bucket: bucket}, nil
}
place, err := v3MintSession(bucket, workspace, launchDir, owned)
if err != nil {
return v3Session{}, err
}
v3ReapEmpty(empty, place.Dir)
return v3Session{Place: place, Transcript: place.Transcript(), Bucket: bucket}, nil
}
// v3PickFolder resumes the newest conversation somebody has spoken in. A
// writer mints a fresh identity when there are only unused conversations: an
// old empty identity could be assigned to a team between discovery and opening.
// Read-only host discovery can still find an existing empty conversation to join.
func v3PickFolder(spoken, empty []v3Folder, free bool) (v3Folder, bool, bool) {
if len(spoken) > 0 {
return spoken[0], true, true
}
if !free {
if len(empty) > 0 {
return empty[0], false, true
}
return v3Folder{}, false, false
}
return v3Folder{}, false, false
}
// v3LatestTranscript is the transcript a launch that named NO session is asking
// for in this workspace, and "" when the workspace has no conversation yet.
//
// IT CHANGES NOTHING ON DISK, which is the one thing that separates it from
// [v3ResolveSession] and the reason it exists at all. The engine host asks it on
// every hello, to answer "which conversation is this" BEFORE it opens anything
// (engine.go's [engineHelloKey]); a reading that reaped empty folders or minted
// a new one would make the question itself change the answer, and would mint a
// conversation for a hello that was about to join one.
//
// Spoken conversations use the boot's resume order. Empty conversations remain
// discoverable so a host can join an agent it already holds. If none is held,
// boot mints a fresh identity and the host files the agent under its actual
// transcript, rather than taking over an abandoned empty conversation.
func v3LatestTranscript(workspace string) string {
if strings.TrimSpace(workspace) == "" {
return ""
}
bucket, err := v3ProjectDir(workspace)
if err != nil {
return ""
}
spoken, empty := v3ScanBucket(bucket)
folder, _, found := v3PickFolder(spoken, empty, false)
if !found {
return ""
}
return session.Place{Dir: folder.dir}.Transcript()
}
// v3NamedSession opens the path a person put on the command line.
//
// A folder's transcript is opened AS a folder — the sidecars, the node journals
// and the droppings all belong to it, and a session opened by its own path is
// still that session. Anything else is the flat layout, which keeps working
// exactly as it did: a zero Place, and every sidecar derived from the file's
// stem.
func v3NamedSession(explicit, workspace string, owned bool) (v3Session, error) {
path, err := expandHome(explicit)
if err != nil {
return v3Session{}, err
}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return v3Session{}, fmt.Errorf("create session directory: %w", err)
}
_, statErr := os.Stat(path)
found := v3Session{Transcript: path, Resumed: statErr == nil, Bucket: session.BucketOf(path)}
if _, isFolder := session.FolderOf(path); !isFolder {
bucket, err := v3ProjectDir(workspace)
if err != nil {
return v3Session{}, err
}
found.Bucket = bucket
return found, nil
}
// The folder's own account of itself wins over the launch's: a session
// carried in from another directory is the session it was, borrowed or
// owned, whatever the terminal it is being opened from looks like. A folder
// with no meta.json yet takes the launch's posture.
found.Place = v3PlaceOf(path, workspace)
if found.Place, err = movablePlace(context.Background(), found.Place); err != nil {
return v3Session{}, err
}
found.Transcript = found.Place.Transcript()
dir := found.Place.Dir
if meta, _ := session.LoadMeta(dir); strings.TrimSpace(meta.ID) == "" && owned {
found.Place = v3PlaceFor(dir, workspace, true)
}
return found, nil
}
// v3PlaceOf reads which session folder a transcript belongs to: the folder when
// the path is one's transcript.jsonl, and the legacy zero Place for a flat file
// — which is how a caller says "derive the sidecars the old way" (place.go).
//
// The folder's own meta.json answers whether it owns its workspace, because
// that is a fact about the conversation and not about the window opening it.
func v3PlaceOf(transcript, workspace string) session.Place {
transcript = strings.TrimSpace(transcript)
dir, ok := session.FolderOf(transcript)
if transcript == "" || !ok {
return session.Place{}
}
meta, _ := session.LoadMetaIn(dir, workspace)
return v3PlaceFor(dir, strings.TrimSpace(meta.Workspace), meta.Owned)
}
// v3PointAt aims one launch's config at a session folder: the journal inside
// it, the folder itself, and — for an owned session — the tools root that comes
// with it. It is the ONE place a config changes conversations, so /new, a
// contended resume and the picker cannot drift apart.
func v3PointAt(cfg session.Config, place session.Place) (session.Config, error) {
var err error
if place, err = movablePlace(context.Background(), place); err != nil {
return cfg, err
}
cfg.Place = place
cfg.SessionFile = place.Transcript()
if !place.Owned {
// A resumed conversation may have acquired its project after it was
// minted in the no-project bucket. The Place is the persisted authority;
// keeping the launch directory here would reopen the right transcript with
// the wrong tools root and lose the anchor precisely on resume.
if workspace := strings.TrimSpace(place.Workspace); workspace != "" {
cfg.Workspace = workspace
}
cfg.MemoryProjectKey = v3ProjectKey(cfg.Workspace)
cfg.MemoryProjectName = gitidentity.ProjectName(cfg.Workspace)
return cfg, nil
}
if err := prepareOwnedWorkspace(place); err != nil {
return cfg, err
}
cfg.Workspace = place.Work()
// AND THE PROJECT KEY FOLLOWS THE WORKSPACE, because the key IS the
// workspace's provable identity: a conversation moved to another session
// folder — /new, a resume, a picker — is a conversation that may be in a
// different project, and a memory scoped to the wrong key is a memory in
// the wrong place. Recomputed here, where the workspace is settled, so
// every door through this function agrees about whose project this is —
// and the name moves with it, so a line kept here says where it holds.
cfg.MemoryProjectKey = v3ProjectKey(cfg.Workspace)
cfg.MemoryProjectName = gitidentity.ProjectName(cfg.Workspace)
return cfg, nil
}
// v3Reopen aims a config at a transcript a person picked. It is [v3PointAt] for
// a path rather than a folder: a session folder's journal reopens as its
// folder, and a flat one reopens as the legacy layout it was written in.
func v3Reopen(cfg session.Config, transcript, workspace string) (session.Config, error) {
place := v3PlaceOf(transcript, workspace)
if place.Dir == "" {
cfg.Place = session.Place{}
cfg.SessionFile = transcript
return cfg, nil
}
return v3PointAt(cfg, place)
}
// v3PlaceFor builds the Place for one session folder. The workspace follows
// from the posture and never from a caller's opinion: an owned session's tools
// root is its own work/, and a borrowed one's is the project it borrowed.
func v3PlaceFor(dir, workspace string, owned bool) session.Place {
place := session.Place{Dir: dir, Owned: owned}
if owned {
place.Workspace = place.Work()
return place
}
place.Workspace = workspace
return place
}
// v3MintSession makes one session folder: a fresh id, the directory named by
// it, and meta.json written BEFORE the first line of the journal — so a picker
// in another window sees the conversation from the moment it exists rather than
// from the moment somebody speaks in it.
func v3MintSession(bucket, workspace, launchDir string, owned bool) (session.Place, error) {
return v3MintSessionAs(cell.HostBound, bucket, workspace, launchDir, owned)
}
// v3MintSessionAs is [v3MintSession] for a session whose cell declares class:
// chats and runs keep the host access their commands have always had (C23).
func v3MintSessionAs(class cell.Class, bucket, workspace, launchDir string, owned bool) (session.Place, error) {
id, dir, err := v3NewFolder(bucket, class)
if err != nil {
return session.Place{}, err
}
place := v3PlaceFor(dir, workspace, owned)
var policy *session.WorkspacePolicy
if session.WorkspaceOwnershipPrototypeEnabled() {
policy = session.DefaultWorkspacePolicy()
}
// Placement policy is durable conversation truth, so a failed creation
// write must not silently open the conversation with legacy task placement.
if err := session.SaveMeta(dir, session.Meta{
ID: id,
Workspace: place.Workspace,
LaunchDir: launchDir,
Owned: owned,
Created: time.Now(),
WorkspacePolicy: policy,
}); err != nil {
return session.Place{}, fmt.Errorf("save new conversation policy: %w", err)
}
return place, nil
}
// v3NewFolder makes the empty folder a new session lives in and answers its id
// and path: a cell when a compatible engine is available and a capable platform and engine (the session package finds its
// transcript in .cell/ by the folder's shape), a plain folder otherwise.
func v3NewFolder(bucket string, class cell.Class) (id, dir string, err error) {
if cell.Available() {
c, err := cell.CreateIn(bucket, cell.Options{Class: class})
if err != nil {
return "", "", fmt.Errorf("create session directory: %w", err)
}
return c.ID, c.Root, nil
}
id = session.NewSessionID()
dir = filepath.Join(bucket, id)
if err := os.MkdirAll(dir, 0o700); err != nil {
return "", "", fmt.Errorf("create session directory: %w", err)
}
return id, dir, nil
}
// v3NextSession mints a sibling of the session a launch is already on: the same
// bucket, the same borrowed-or-owned posture, a new id. It is what /new and a
// contended resume both need — a second conversation about the same project —
// and it falls back to the workspace's own bucket for a launch that has no
// folder at all (an explicit flat --session).
func v3NextSession(current session.Place, workspace string) (session.Place, error) {
return v3NextSessionFrom(current, workspace, v3LaunchDir())
}
// v3NextSessionFrom is [v3NextSession] with the launch directory named by the
// door rather than read off the process.
func v3NextSessionFrom(current session.Place, workspace, launchDir string) (session.Place, error) {
if dir := strings.TrimSpace(current.Dir); dir != "" {
root := strings.TrimSpace(current.Workspace)
if current.Owned {
// An owned session's workspace is its OWN work/, so the sibling's
// cannot be inherited: it is minted with the folder, below.
root = workspace
}
return v3MintSession(session.BucketOf(current.Transcript()), root,
v3StampLaunchDir(launchDir, root), current.Owned)
}
bucket, err := v3ProjectDir(workspace)
if err != nil {
return session.Place{}, err
}
return v3MintSession(bucket, workspace,
v3StampLaunchDir(launchDir, workspace), false)
}
// v3LaunchDir is where the person is standing, and "" when even that cannot be
// read — which is a field of meta.json left empty rather than a launch that
// fails.
//
// IT IS CAPTURED ONCE, on the first call, and every later call reads the same
// answer back. The reason is that a process can now open several conversations
// and one of them may be about another project entirely: the launch directory is
// a fact about the WINDOW — where the person was standing when they typed
// `codeaf` — and re-reading it per conversation would only be a way for it to
// come back different. Nothing in this process changes directory; `codeaf
// engine` is the one door that does and it does so before it opens anything
// (engine.go), so its first call captures the workspace it moved into, exactly
// as the per-call read did.
var v3LaunchWhere struct {
once sync.Once
dir string
}
func v3LaunchDir() string {
v3LaunchWhere.once.Do(func() {
if dir, err := os.Getwd(); err == nil {
v3LaunchWhere.dir = dir
}
})
return v3LaunchWhere.dir
}
// v3StampLaunchDir is what a new session folder RECORDS as the launch directory,
// and the one case where the honest answer is nothing.
//
// [session.Meta.LaunchDir] is "where the person actually stood when the session
// opened", and it is read by two things: [projectPath] names the project of an
// owned session from it, and the idle sweep marks a session disposable if EITHER
// its workspace or its launch directory is under a temp directory
// (internal/session's sweep.go). The second is the trap. A process started in
// /tmp — by a script, by an editor, by a test harness — that then opens a
// conversation in ~/work/repo would stamp that conversation as litter and have
// it reaped once it went idle, in a project the person very much meant.
//
// SO THE LAUNCH DIRECTORY TRAVELS ONLY WHILE IT AGREES WITH THE WORKSPACE ABOUT
// BEING TEMPORARY. When it does not, the field is left empty, which the sweep
// reads as not-temporary and meta.json omits. A conversation opened in /tmp is
// still litter, because its workspace says so on its own.
func v3StampLaunchDir(launchDir, workspace string) string {
if strings.TrimSpace(launchDir) == "" {
return ""
}
if v3TempPath(launchDir) && !v3TempPath(workspace) {
return ""
}
return launchDir
}
// v3TempPath reports whether a path sits inside a directory the machine itself
// considers disposable.
//
// IT IS THE SAME RULE internal/session's sweep applies to the two fields of
// meta.json, spelled here because that one is unexported and because this side
// has to answer the question BEFORE the file is written rather than after. Both
// the configured temp directory and /tmp are asked, because TMPDIR moves the
// first without making the second any less of a temp directory to the person who
// typed it. The pair is pinned by a test; if the sweep's rule ever widens, this
// one widens with it or a conversation gets reaped under somebody.
func v3TempPath(path string) bool {
path = strings.TrimSpace(path)
if path == "" {
return false
}
path = filepath.Clean(path)
for _, temporary := range []string{os.TempDir(), "/tmp"} {
temporary = filepath.Clean(strings.TrimSpace(temporary))
if temporary == "" || temporary == string(filepath.Separator) {
continue
}
if path == temporary || strings.HasPrefix(path, temporary+string(filepath.Separator)) {
return true
}
}
return false
}
// ── the bucket, read and groomed ────────────────────────────────────────────
// v3Folder is one session folder as the resume law weighs it.
type v3Folder struct {
dir string
meta session.Meta
// at is what the folder is ordered by: when the person last spoke in it,
// and the folder's own modification time for one whose meta.json is missing
// or was written before this field existed.
at time.Time
}
// v3ScanBucket sorts a project's session folders into the two piles the resume
// law needs, each newest first: the ones somebody has SPOKEN in, and the empty
// ones.
//
// Emptiness is read from the transcript rather than from meta.json, because the
// transcript is the record and meta.json is a citation: [session.Peek] answers
// false for a file nobody ever said anything in, which is exactly the folder
// this groom may remove. A folder holding work, worktrees or
// deliverables is never empty whatever its journal says — those are somebody's
// content, and no groom of a bookkeeping file may take them.
func v3ScanBucket(bucket string) (spoken, empty []v3Folder) {
sessionDirs := session.BucketSessionDirs(bucket)
if len(sessionDirs) == 0 {
return nil, nil
}
for _, dir := range sessionDirs {
place := session.Place{Dir: dir}
if _, err := os.Stat(place.Transcript()); err != nil {
continue
}
folder := v3Folder{dir: dir}
folder.meta, _ = session.LoadMeta(dir)
folder.at = folder.meta.LastUserAt
if folder.at.IsZero() {
if info, err := os.Stat(dir); err == nil {
folder.at = info.ModTime()
}
}
if v3EmptyUnassignedSession(dir) {
// A team or collection reference keeps a blank out of both piles.
// So does a store that cannot say whether it is referenced.
if referenced, err := teams.ConversationReferenced(config.ProfileDir(), place.Transcript()); err == nil && !referenced && !collectionKeepsConversation(dir) {
empty = append(empty, folder)
}
continue
}
spoken = append(spoken, folder)
}
sort.SliceStable(spoken, func(i, j int) bool { return spoken[i].at.After(spoken[j].at) })
sort.SliceStable(empty, func(i, j int) bool { return empty[i].at.After(empty[j].at) })
return spoken, empty
}
// v3EmptySession reports whether a session folder is one nobody ever said
// anything in and nothing was made in.
//
// A TRANSCRIPT WE COULD NOT READ IS NOT AN EMPTY ONE. This is the law
// [session.sweepSession] rule 3 states about meta.json — a session that cannot
// say what it is, stays, because the rule reaps what is PROVABLY litter and
// leaves everything else alone forever — applied here to a much bigger file. A
// journal torn by a lid closing mid-write, one line past the scanner's buffer,
// or a schema this build has never seen all look like silence to a reader, and
// none of them is silence. Hiding somebody's conversation on the strength of a
// failed parse is the more expensive mistake by far, and [v3ReapEmpty] is the
// only rm -rf on the launch path.
//
// That is why the question is put to [session.SpokeIn] and not to
// [session.Peek]: Peek folds "read it all, nobody spoke" and "could not read
// it" into one false, which is right for a picker row and fatal for a delete.
// Only the first of the two is emptiness.
// A team reference makes an empty conversation intentional, not reusable
// litter. Only the teams that name this conversation are read (the store's
// index), and a store that cannot say keeps the folder.
// A collection reference keeps it too, including when its store cannot be read.
func v3EmptySession(dir string) bool {
referenced, err := teams.ConversationReferenced(config.ProfileDir(), session.Place{Dir: dir}.Transcript())
if err != nil || referenced {
return false
}
return v3EmptyUnassignedSession(dir) && !collectionKeepsConversation(dir)
}
// v3EmptyUnassignedSession reads only content. References decide whether a blank
// is kept, never whether it is a conversation somebody has spoken in.
func v3EmptyUnassignedSession(dir string) bool {
place := session.Place{Dir: dir, Owned: true}
spoken, sure := session.SpokeIn(place.Transcript())
if spoken || !sure || session.HasSavedTasks(dir) {
return false
}
// A sealed chain is something made in it: a run that worked in the cell said
// nothing, and its turns are the record of what it did.
for _, kept := range []string{place.Work(), place.Trees(), place.Artifacts(), filepath.Join(dir, cellstore.TurnsPath)} {
if _, err := os.Stat(kept); err == nil {
return false
}
}
return true
}
// v3ReapEmpty removes the empty session folders a launch left behind, except
// the one it is about to open.
//
// It is `rm -rf` and it is safe to be only because [v3EmptySession] reaps what
// is PROVABLY litter and leaves everything else alone forever: an empty folder
// has no words in its journal, no worktrees to unregister and no work directory
// to lose. A folder another window is holding open is skipped — a live empty
// session is somebody sitting at a prompt.
func v3ReapEmpty(empty []v3Folder, keep string) {
// Recheck the record and emptiness under the team writer's lock. Unknown
// membership is a reason to keep a folder, never a reason to remove it.
for _, folder := range empty {
if folder.dir == keep {
continue
}
transcript := session.Place{Dir: folder.dir}.Transcript()
_ = teams.InspectConversation(config.ProfileDir(), transcript, func(referenced bool) error {
if !referenced && !session.InUse(transcript) && v3EmptyUnassignedSession(folder.dir) && !collectionKeepsConversation(folder.dir) {
_ = os.RemoveAll(folder.dir)
}
return nil
})
}
}
// v3Migrated readies an existing cell without changing a legacy chat's layout.
// C24 keeps older chats readable by every build that shares this home.
func v3Migrated(cfg session.Config) session.Config {
if !cell.Available() || cfg.Place.Dir == "" {
return cfg
}
if _, err := cell.OpenAt(cfg.Place.Dir, filepath.Base(cfg.Place.Dir)); err != nil {
return cfg
}
session.AdoptArtifacts(cfg.Place, artifactsIndexPath())
budgetOnOpen(cfg.Place.Dir)
if cfg.Memory != nil {
_ = session.SealMemories(cfg.Place.Dir, cfg.Memory)
}
_, _ = cellindex.RebuildAt(cfg.Place.Dir, cfg.Place.Workspace)
cfg.SessionFile = cfg.Place.Transcript()
return cfg
}
// v3Seated is for a caller that already holds the journal. It gives the session
// the executor it owns, built from the cell class and its tools' workspace.
//
// A folder that is not a readable cell gets no seat and its calls run on the
// host as they always did, and so does every folder without a compatible engine. The
// seat is set on every call, so a config reused for the next conversation never
// carries the last one's executor.
func v3Seated(cfg session.Config) session.Config {
cfg, claim := v3SeatedPending(cfg)
claim(true)
return cfg
}
// v3SeatedPending builds the seat before committing its drive to journal ownership.
func v3SeatedPending(cfg session.Config) (session.Config, func(bool)) {
cfg.Seat, cfg.Machine, cfg.Seals, cfg.Interrupted = nil, nil, nil, nil
seat, machine, seals, claim := v3SeatPending(cfg.Place, nil, syncDrives)
cfg.Seat, cfg.Interrupted = seat, executor.InterruptedOn(seat)
cfg.Renewals = syncDrives.renewalsOf(cfg.Place.ID())
cfg.FinishSaving, cfg.SavingNotices = nil, nil
if drive := syncDrives.renewalsOf(cfg.Place.ID()); drive != nil {
book, id := syncDrives, cfg.Place.ID()
cfg.FinishSaving = func() error { return book.closeCell(id) }
cfg.SavingNotices = drive.TakeSavingNotices
}
if machine != nil {
cfg.Machine = machine
}
if seals != nil {
cfg.Seals = seals
}
return cfg, claim
}
// v3SeatOf is the seat of the cell a place names, the machine view it was
// built with, and the watch of its seals — one per seat, so one per cell. A
// nil say queues the watch's sentences for the surface showing the session;
// a door with no surface passes where they go: the one construction every door that seals its calls goes
// through. A place that is not a readable cell answers no seat.
func v3SeatOf(place session.Place, say func(string)) (executor.Seat, *preflight.Machine, *cellstore.SealWatch) {
return v3SeatWith(place, say, nil)
}
// v3SeatWith is v3SeatOf for a door that syncs: with a drive side for the cell
// every seal is also noted for the relay, and once another machine has taken
// the chat its tool calls are refused. A nil book, or sync off, is the seat
// exactly as it was.
func v3SeatWith(place session.Place, say func(string), drives *driveBook) (executor.Seat, *preflight.Machine, *cellstore.SealWatch) {
seat, machine, watch, claim := v3SeatPending(place, say, drives)
claim(true)
return seat, machine, watch
}
func v3SeatPending(place session.Place, say func(string), drives *driveBook) (executor.Seat, *preflight.Machine, *cellstore.SealWatch, func(bool)) {
noop := func(bool) {}
if !cell.Available() || place.Dir == "" || place.Workspace == "" {
return nil, nil, nil, noop
}
c, err := cell.OpenAt(place.Dir, filepath.Base(place.Dir))
if err != nil {
return nil, nil, nil, noop
}
class, ok := executor.ParseClass(string(c.Meta().Class))
if !ok {
class = executor.HostBound
}
machine, err := preflight.OpenMachine(c.Root, place.Workspace)
watch := &cellstore.SealWatch{Say: say, SyncAddress: chatSyncService()}
failed(watch, err)
drive, claim := drives.pendingDriveOf(c, cellstore.EngineFor(place.Workspace), watch.SyncReport, watch)
if drive != nil {
drive.setIdleCheck(watch.IdleReady)
watch.OnMetadataWrite = drive.SavedMetadata
// The turn can finish locally while its final capture is still running.
watch.OnTurnEnd = func() { drive.TurnEnded(c, watch.Report) }
watch.OnTurnStart = func() { drive.Working(true) }
}
seat, err := cellstore.SeatOver(class, c, place.Workspace, observerOf(machine), watch.Report, driveStore(drive), cellstore.WithNotices(watch.Note), cellstore.WithPipeline(), cellstore.WithWarmCapture())
failed(watch, err)
if err != nil {
watch.Retire()
}
watch.OnTail = func() { sealTail(seat, drive) }
// A fresh seat has no foreground turn in flight. Background tasks may be
// the first input; their journal writes need a tail seal even before chat.
// Window attachment reuses the engine's seat rather than constructing one.
watch.Waiting()
return executor.Gated(seat, driveGate(drive), driveWorkGate(drive), drivePreparedGate(drive), driveSettingsGate(drive)), machine, watch, claim
}
// sealTail seals what the chat wrote after the turn-end seal (titles, summaries,
// memories) and sends it. It is the turn's own ending again, so the record has
// one way to become durable; the sync side's single flight folds it into the
// upload already running. The watch calls it from its own timer, once.
func sealTail(seat executor.Seat, drive *liveDrive) {
executor.Settle(context.Background(), seat)
if drive != nil {
drive.Idle()
}
}
// observerOf is the machine's observer, and no observer where the inventory
// could not be opened: a call is never failed for want of a record.
func observerOf(m *preflight.Machine) executor.Observer {
if m == nil {
return nil
}
return m.Observer()
}
// sealSeamOf is what a session's seals tell the chat surface: nothing for a
// session with no seat of its own.
//
// WHETHER THE LAST SEAL FAILED IS ASKED OF THE AGENT, not of the watch: the
// ordinary launch shows an agent running in a separate engine process, where
// the watch is not in this one and the engine states the fact over the wire
// ([session.Facts.Unsealed]). The agent's own predicate is the one source both
// readings come from. The sentences are drained from the local watch only; an
// engine tells its own on the turn's stream.
func sealSeamOf(agent any, seals session.SealState) tui3.SealSeam {
var seam tui3.SealSeam
if seals != nil {
seam = tui3.SealSeam{Failing: seals.Failing, Notice: seals.Take}
}
if watch, ok := seals.(interface{ Listen(func()) func() }); ok {
seam.Listen = watch.Listen
}
if door, ok := agent.(interface{ SealFailing() bool }); ok {
seam.Failing = door.SealFailing
}
return seam
}
// stderrSay is where a run with no surface says its sentences.
func stderrSay(sentence string) { fmt.Fprintln(os.Stderr, "codeaf: "+sentence) }
// failed tells the watch about a seat that could not be built, and is silent
// about one that could: a nil error there is no seal having held.
func failed(watch *cellstore.SealWatch, err error) {
if err != nil {
watch.Report(err)
}
}
// hostSeated is the root of a command that runs work outside any conversation
// (do, exec, run, a carried program): its tool calls run on the host seat, and
// say so here once instead of at every site.
func hostSeated(ctx context.Context) context.Context {
return executor.With(ctx, executor.Host)
}
// v3Interrupted is the entry notice with what a person reads about a last run
// that was cut off mid-call added under it: one line for each call, and nothing
// added when none was.
func v3Interrupted(cfg session.Config, notice string) string {
if cfg.Interrupted == nil {
return notice
}
lines := append([]string{notice}, v3InterruptedLines(cfg)...)
return strings.TrimSpace(strings.Join(lines, "\n"))
}
func v3InterruptedLines(cfg session.Config) []string {
if cfg.Interrupted == nil {
return nil
}
return cfg.Interrupted.Lines()
}