@@ -5,6 +5,8 @@ import { $ } from "bun"
55import { Storage } from "../storage/storage"
66import { Log } from "../util/log"
77import { Flag } from "@/flag/flag"
8+ import { Global } from "../global"
9+ import fs from "fs/promises"
810
911export namespace Project {
1012 const log = Log . create ( { service : "project" } )
@@ -77,6 +79,10 @@ export namespace Project {
7779 . text ( )
7880 . then ( ( x ) => path . resolve ( worktree , x . trim ( ) ) )
7981 const projectID = id || "global"
82+ // Migrate sessions from "global" project if this repo just got its first commit
83+ if ( id ) {
84+ await migrateFromGlobal ( id , worktree )
85+ }
8086 const project : Info = {
8187 id : projectID ,
8288 worktree,
@@ -90,6 +96,32 @@ export namespace Project {
9096 return project
9197 }
9298
99+ async function migrateFromGlobal ( newProjectID : string , worktree : string ) {
100+ const globalProject = await Storage . read < Info > ( [ "project" , "global" ] ) . catch ( ( ) => null )
101+ if ( ! globalProject || globalProject . worktree !== worktree ) return
102+
103+ const dir = path . join ( Global . Path . data , "storage" )
104+ const globalSessionsDir = path . join ( dir , "session" , "global" )
105+ if ( ! ( await fs . stat ( globalSessionsDir ) . catch ( ( ) => null ) ) ) return
106+
107+ log . info ( "migrating sessions from global" , { newProjectID, worktree } )
108+ const newSessionsDir = path . join ( dir , "session" , newProjectID )
109+
110+ for await ( const file of new Bun . Glob ( "*.json" ) . scan ( { cwd : globalSessionsDir , absolute : true } ) ) {
111+ const session = await Bun . file ( file ) . json ( )
112+ // Only migrate sessions that belong to this worktree
113+ if ( session . directory && ! session . directory . startsWith ( worktree ) ) continue
114+
115+ session . projectID = newProjectID
116+ const dest = path . join ( newSessionsDir , path . basename ( file ) )
117+ log . info ( "migrating session" , { from : file , to : dest } )
118+ await Bun . write ( dest , JSON . stringify ( session , null , 2 ) )
119+ await Bun . file ( file )
120+ . unlink ( )
121+ . catch ( ( ) => { } )
122+ }
123+ }
124+
93125 export async function setInitialized ( projectID : string ) {
94126 await Storage . update < Info > ( [ "project" , projectID ] , ( draft ) => {
95127 draft . time . initialized = Date . now ( )
0 commit comments