Private/Onboarding.ps1

# The onboarding: one page that tells a new session where everything is and how to read it.
# Nothing is put back into a tool's own folders; the newcomer reads what it needs from here.

function Get-PCContinuitySaved {
    param([string]$ContextPath)
    $dir = Join-Path $ContextPath 'machines'
    @(if (Test-Path -LiteralPath $dir) {
            Get-ChildItem -LiteralPath $dir -Directory | Sort-Object Name | ForEach-Object { Read-PCContinuityJson (Join-Path $_.FullName 'manifest.json') } | Where-Object { $_ }
        })
}

function Write-PCContinuityOnboarding {
    param([string]$ContextPath)
    $manifests = Get-PCContinuitySaved $ContextPath
    if (-not $manifests.Count) { throw "Nothing has been saved in '$ContextPath' yet. Run Save-PCContinuity first." }
    $state = Read-PCContinuityJson (Join-Path $ContextPath 'continuity.json')
    $latest = $manifests | Sort-Object { "$($_['saved'])" } | Select-Object -Last 1
    $ws = $latest['workspace']
    $name = if ($state -and $state['workspace']) { $state['workspace'] } else { $ws['name'] }
    $kept = { param($s) @(@($s['entries']) | Where-Object { $_ -and $_['mode'] -ne 'skipped' }) }
    $L = [Collections.Generic.List[string]]::new()

    $L.Add("# Joining the work on $name"); $L.Add('')
    $L.Add('You are picking up work that is already under way. This repository is its saved context: the sessions, the memory and the history that came before you, from every machine the work has been done on. Nothing here is loaded for you. Read what you need, when you need it, and say what you read.'); $L.Add('')

    $L.Add('## Start here'); $L.Add('')
    $where = if ($ws['remote']) { "The working folder is kept at ``$($ws['remote'])``." } else { 'The working folder is not kept in a repository; it travels by other means.' }
    $first = @($ws['read_first']) | Where-Object { $_ }
    $L.Add("1. **The working folder.** $where " + $(if ($first) { 'Read these first, in this order: ' + (($first | ForEach-Object { "``$_``" }) -join ', ') + '.' } else { 'Read its README first, where it has one.' }))
    $L.Add('2. **The memory**, below: what earlier sessions chose to keep as standing facts and preferences. It is short. Read all of it.')
    $L.Add('3. **The most recent session**, below, and only as far as you need it. Search it; do not read it through.')
    $companions = @($ws['companions']) | Where-Object { $_ -and $_['repository'] }
    if ($companions) {
        $L.Add('4. **What travels beside the working folder**, each a repository of its own:')
        foreach ($c in $companions) { $L.Add(" - $($c['kind']): ``$($c['repository'])``" + $(if ($c['folder']) { ", cloned as ``$($c['folder'])``" }) + $(if ($c['link']) { " and linked as ``$($c['link'])``" }) + $(if ($c['what']) { ". $($c['what'])" })) }
    }
    $L.Add('')

    $L.Add('## Memory'); $L.Add('')
    $memory = foreach ($m in $manifests) { foreach ($s in @($m['sources'])) { foreach ($e in (& $kept $s)) { if ($e['path'] -match '^memory/') { [pscustomobject]@{ Machine = $m['machine']; Path = "machines/$($m['machine'])/$($s['target'])/$($e['path'])"; Index = ($e['path'] -match '/MEMORY\.md$') } } } } }
    if ($memory) {
        $L.Add('Where there is a `MEMORY.md` it is the index: one line per memory. Read it, then the files it names.'); $L.Add('')
        $L.Add('| Machine | File |'); $L.Add('| --- | --- |')
        foreach ($x in ($memory | Sort-Object Machine, @{ Expression = 'Index'; Descending = $true }, Path)) { $L.Add("| $($x.Machine) | ``$($x.Path)`` |") }
        $L.Add('')
        $L.Add('To carry the memory into Claude on this machine, copy those files into the memory folder Claude keeps for the working folder: `~/.claude/projects/<the working folder''s full path, every character that is not a letter or a digit replaced by a hyphen>/memory/`. Where the machines disagree, the newer file is the one to trust.')
    }
    else { $L.Add('No memory files were found on any machine.') }
    $L.Add('')

    $L.Add('## Sessions'); $L.Add('')
    $L.Add('| Machine | Tool | Sessions | Last activity | Size | Where |'); $L.Add('| --- | --- | --- | --- | --- | --- |')
    $newest = $null
    foreach ($m in $manifests) {
        foreach ($s in @($m['sources'])) {
            $entries = & $kept $s
            $pattern = switch ($s['tool']) { 'claude' { '^[^/]+\.jsonl$' } 'copilot' { '^chatSessions/[^/]+$' } default { '^history/' } }
            $sessions = @($entries | Where-Object { $_['path'] -match $pattern })
            $L.Add("| $($m['machine']) | $($s['tool']) | $($sessions.Count) | $($s['last_activity']) | $(Format-PCContinuitySize ([long]$s['bytes'])) | ``machines/$($m['machine'])/$($s['target'])/`` |")
            foreach ($e in $sessions) {
                if ($s['tool'] -eq 'claude' -and (-not $newest -or [long]$e['modified_ms'] -gt [long]$newest.Entry['modified_ms'])) { $newest = @{ Entry = $e; Machine = $m['machine']; Source = $s } }
            }
        }
    }
    $L.Add('')
    if ($newest) {
        $p = "machines/$($newest.Machine)/$($newest.Source['target'])/$($newest.Entry['path'])"
        if ($newest.Entry['mode'] -eq 'segmented') { $L.Add("The most recent Claude session is ``$p.segments/``, in $(@($newest.Entry['segments']).Count) numbered segments. The last segment holds the newest turns.") }
        else { $L.Add("The most recent Claude session is ``$p``.") }
        $L.Add('')
    }
    $L.Add('### How to read a session'); $L.Add('')
    $L.Add('- **Claude.** A session is a `.jsonl` file: one event to a line, each a JSON object with a `type` (`user`, `assistant` and others) and a `timestamp`. A session too large for one file is a folder named for it and ending in `.segments`; its numbered files, joined in order, are the session. A long session writes a recap of itself each time it runs out of room: search for `"isCompactSummary":true`, and read the last one first. Beside a session, a folder of the same name holds what its tools returned.')
    $L.Add('- **Copilot.** `chatSessions/` holds one JSON file per conversation. `state.vscdb` is the editor''s own store for the working folder, a SQLite file.')
    $L.Add('- **SpecStory.** `history/` holds each chat as a markdown file, named for when it began.')
    $L.Add('')

    $L.Add('## Where the work has lived'); $L.Add('')
    $L.Add('| Machine | System | Folder | First saved | Last saved |'); $L.Add('| --- | --- | --- | --- | --- |')
    foreach ($h in (@($state['homes']) | Where-Object { $_ } | Sort-Object { $_['machine'] }, { $_['path'] })) { $L.Add("| $($h['machine']) | $($h['os']) | ``$($h['path'])`` | $($h['first_saved']) | $($h['last_saved']) |") }
    $L.Add('')

    $L.Add('## What was changed on the way in'); $L.Add('')
    $masks = Merge-PCContinuityMask @(foreach ($m in $manifests) { foreach ($s in @($m['sources'])) { $s['masks'] } })
    if ($masks.Count) {
        $L.Add('Anything that looked like a key, a token or a password was replaced in the copy by `[masked:<kind>]`. The values are not in this repository; they remain on the machine they came from.'); $L.Add('')
        $L.Add('| Kind | Replaced |'); $L.Add('| --- | --- |')
        foreach ($k in $masks.Keys) { $L.Add("| $k | $($masks[$k]) |") }
    }
    else { $L.Add('Every text file was searched for anything that looked like a key, a token or a password. Nothing was found, so nothing was changed.') }
    $skipped = @(foreach ($m in $manifests) { foreach ($s in @($m['sources'])) { foreach ($e in @($s['entries'])) { if ($e -and $e['mode'] -eq 'skipped') { "machines/$($m['machine'])/$($s['target'])/$($e['path'])" } } } })
    if ($skipped) { $L.Add(''); $L.Add('Not kept, because each is larger than a single file may be on GitHub: ' + (($skipped | ForEach-Object { "``$_``" }) -join ', ') + '.') }
    $L.Add('')

    $L.Add('## Notes from the team'); $L.Add('')
    $notes = Join-Path $ContextPath 'ONBOARDING.notes.md'
    if (Test-Path -LiteralPath $notes) { $L.Add(((Get-Content -LiteralPath $notes -Raw -Encoding utf8) -replace "`r`n", "`n").Trim()) }
    else { $L.Add('None yet. Write `ONBOARDING.notes.md` beside this file, by hand, and it appears here: how the team likes to work, what to do first, what never to do.') }
    $L.Add('')
    $L.Add("Generated by PowerCraft.Continuity $($script:PCContinuityVersion). Do not edit: it is written again on every save.")

    $path = Join-Path $ContextPath 'ONBOARDING.md'
    Write-PCContinuityText -Path $path -Line $L
    $path
}

function Initialize-PCContinuityRepository {
    # The two files a context repository needs besides what is saved into it.
    param([string]$ContextPath, [string]$Name)
    $attributes = Join-Path $ContextPath '.gitattributes'
    if (-not (Test-Path -LiteralPath $attributes)) { Write-PCContinuityText -Path $attributes -Line '# Context travels byte for byte: no line-ending conversion on any system', '* -text' }
    $readme = Join-Path $ContextPath 'README.md'
    if (-not (Test-Path -LiteralPath $readme)) {
        Write-PCContinuityText -Path $readme -Line @(
            "# The saved context of $Name", ''
            'The sessions, the memory and the chat history of the work, from every machine it has been done on, saved by PowerCraft.Continuity. Keep this repository private: a session holds everything that was said and seen in it.', ''
            'A new session starts at `ONBOARDING.md`.', ''
            '| Path | What |', '| --- | --- |'
            '| `ONBOARDING.md` | Where everything is and how to read it. Written again on every save |'
            '| `ONBOARDING.notes.md` | The team''s own notes for a newcomer, written by hand; optional |'
            '| `continuity.json` | Every machine and folder the work has lived at |'
            '| `machines/<machine>/` | What that machine saved, by tool, with a `manifest.json` of every file |', ''
            'On Windows, clone with long paths allowed: `git clone -c core.longpaths=true <url>`.'
        )
    }
}