diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 7028a9c..017a923 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "name": "pastdotdev", "source": "./plugins/past", "description": "Your Claude Code sessions become memory, and every session starts briefed.", - "version": "0.4.0", + "version": "0.4.1", "author": { "name": "past.dev", "url": "https://past.dev" diff --git a/CLAUDE.md b/CLAUDE.md index 616ad0f..9340d60 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -203,6 +203,20 @@ Use `updateState` for every change. Keep transcript hashes and pending sessions set by measurement: change them with a measurement. The block before a prompt names the tool in one line, which is how the model learns to call it; the line rides inside a block the script already drops from what it sends (rule 13), so it changes nothing that travels. +16. **A sitting is sent with the connection it was typed under.** `state.json` keeps, per session, + the connections its prompts were typed under (`connections`: a fingerprint of the key and the + address, empty while the machine has no key, each with the time it began; the first covers the + session from its start). Every hook of a session records a change (`noteConnection`), and + `connect` does for the sessions still open. A prompt typed under another connection than its + sitting's starts a new sitting, and a sitting is sent only while its connection is the one in + force, whichever way the send starts (a hook, the waiter, `ingest`, `backfill`); `cut` does not + print the others. So what a person typed before connecting, or under another project's key, + stays on the machine. A session the hooks kept no record of, one from before the plugin was + installed or before 0.4.1, names no connection: it is cut and sent as it was, so nothing + already in past.dev moves, and `backfill` still sends the history. A sitting kept back holds its + last hash in `sittings`, or `null`, and the session's whole hash is written only once every + sitting is in past.dev. The folder's path is never sent: `metadata.project` is the folder's + name. `WAITER_VERSION` went to 7 with it. ## Beside other past.dev plugins @@ -227,8 +241,8 @@ cannot read the conversation and can only be recalled from. - `POST /api/v1/ingest/batch` — one item per sitting. `id` gives replacement, `timestamp` dates every memory drawn from the item, `label` names the session, `metadata` carries - `conversationId`, `sessionId`, `project`, `gitBranch`, `sitting`. A batch takes up to 1,000 - items and 16 MB of content. + `conversationId`, `sessionId`, `project`, `gitBranch`, `sitting`, and `model` and `effort` where + the transcript names them. A batch takes up to 1,000 items and 16 MB of content. - `POST /api/v1/recall` — **`identity` is required**. Recall stays off until `/pastdotdev:connect` sets one. The response is one result per document in rank order; the hooks read each result's `content` and `occurredAt`, and the tool also its sources' `excerpts` and `metadata.localTime` @@ -238,6 +252,10 @@ cannot read the conversation and can only be recalled from. with `GET /api/v1/audiences/{slug}` (404 when unknown); a later `audience-unknown` refusal is kept in `state.lastError` for `/pastdotdev:status`, like every failed send. - `UserPromptSubmit` gives the prompt as `prompt` on stdin. +- Claude Code writes, on each of the agent's entries in a transcript, the model that wrote it + (`message.model`) and the effort it ran at (`effort`). It documents neither field, so the script + takes a string where it finds one and otherwise sends nothing. A sitting carries what its last + turn ran on; neither is rendered, so neither changes a hash (rule 10). - Claude Code gives a hook `session_id`, `transcript_path`, `cwd` and `hook_event_name`, and takes `hookSpecificOutput.additionalContext` at session start and on a prompt. - A project API key (`past_sk_…`) names its own project. The plugin never sends a project id. @@ -277,3 +295,7 @@ throwaway `CLAUDE_CONFIG_DIR` and see `claude mcp list` report `plugin:pastdotde **A change to the script is checked against what it sent before.** Run the old script and the new one over the same transcripts, each in a throwaway home with its own stand-in, and compare what each mode prints, what each request carries and what `state.json` keeps, byte for byte (rule 10). + +For rule 16, run the hooks in a throwaway home with no key, then `connect`, then add a prompt to the +transcript and run the prompt hook and `flush`: one sitting goes, the one after connecting. Do the +same with a second key in place of no key, and check the key each request carries. diff --git a/README.md b/README.md index a1b0bed..e914492 100644 --- a/README.md +++ b/README.md @@ -53,8 +53,9 @@ You need Claude Code and Node 16 or later. 4. **Check it.** `/pastdotdev:status` shows the project it talks to and what it has sent. -New sessions are read from then on. `/pastdotdev:backfill` lists the sessions already on this machine, -estimates what sending them costs, and sends them when you confirm. +Sessions are read from your next prompt on: what you typed before connecting stays on your machine. +`/pastdotdev:backfill` lists the sessions from before the plugin was installed, estimates what +sending them costs, and sends them when you confirm. To keep the key out of the conversation, use `/plugin configure pastdotdev@pastdotdev` in the terminal CLI instead of step 3: a form that masks the key and keeps it in your system's credential store. @@ -87,7 +88,16 @@ past.dev on demand: ask what was decided about something, or whether it was trie ## What leaves your machine -Your prompts, Claude's replies, and the project and branch names. Nothing else. +Your prompts and Claude's replies, with the names of the project's folder and its branch, the +session's id, the model Claude ran on with its effort level, and the identity you connected with. +The folder's path stays on your machine. Recall +sends queries: one when a session starts, the first 1,000 characters of each prompt, and the +questions Claude asks `past_recall`. Nothing else. + +What you type is sent with the key it was typed under, and with no other. Nothing typed before you +connect is sent, and what was typed under one project's key never goes to another project: a +session goes on, in a new sitting, from the prompt after you connect or change keys. Sessions from +before the plugin was installed are your history, sent only when you run `/pastdotdev:backfill`. Never sent: tool calls and their results, file contents, diffs, command output, subagent threads, and anything injected into the conversation rather than typed by a person. Strings that look like diff --git a/plugins/past/.claude-plugin/plugin.json b/plugins/past/.claude-plugin/plugin.json index 85665a7..5707d31 100644 --- a/plugins/past/.claude-plugin/plugin.json +++ b/plugins/past/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "pastdotdev", "displayName": "past.dev", - "version": "0.4.0", + "version": "0.4.1", "description": "Your Claude Code sessions become memory, and every session starts briefed.", "author": { "name": "past.dev", "url": "https://past.dev" }, "homepage": "https://github.com/pastdotdev/claude-code-plugin", diff --git a/plugins/past/bin/past-hook.mjs b/plugins/past/bin/past-hook.mjs index 3cf341f..a1ad14b 100755 --- a/plugins/past/bin/past-hook.mjs +++ b/plugins/past/bin/past-hook.mjs @@ -38,7 +38,7 @@ const MIN_SITTING_KILOBYTES = 10; const COMPACTION_RESEND_MS = 60 * 60000; const DEFAULT_API_URL = 'https://api.past.dev'; const MARKER = '=== past · recalled from memory ==='; -const VERSION = '0.4.0'; +const VERSION = '0.4.1'; // ---------------------------------------------------------------------------------- Claude Code @@ -175,8 +175,8 @@ function saveConfig(next) { function loadState() { return readJson(STATE_PATH, { sessions: {}, pending: {} }); } /** - * This plugin's sessions in the state: `sessions` that were sent, `pending` ones still open, at the - * top of the file. The file can also hold another past.dev plugin's sessions, under `hosts`; they are + * This plugin's sessions in the state: `sessions` that were sent, `pending` ones still open and the + * `connections` each was typed under, at the top of the file. The file can also hold another past.dev plugin's sessions, under `hosts`; they are * never read here, and every write puts them back as they were. */ function book(state) { @@ -184,6 +184,7 @@ function book(state) { // every hook, loudly. if (!state.sessions) state.sessions = {}; if (!state.pending) state.pending = {}; + if (!state.connections) state.connections = {}; return state; } @@ -314,6 +315,8 @@ function readTranscript(path) { let firstAt = null; let branch = ''; let project = ''; + let model = ''; + let effort = ''; let raw = ''; try { raw = readFileSync(path, 'utf8'); } catch { return null; } const silence = silenceMeter(); @@ -330,6 +333,15 @@ function readTranscript(path) { // user turn. Neither is the conversation. if (entry.isSidechain || entry.isMeta || entry.toolUseResult) continue; + // Claude Code writes, on each of the agent's entries, the model that wrote it and the effort it + // ran at. Each turn keeps the latest, for the sitting's metadata; a message Claude Code made up + // itself names no model (``). + if (entry.type === 'assistant') { + const wrote = entry.message && entry.message.model; + if (typeof wrote === 'string' && wrote && !wrote.startsWith('<')) model = wrote.slice(0, 100); + if (typeof entry.effort === 'string' && entry.effort) effort = entry.effort.slice(0, 40); + } + const text = textOf(entry.message && entry.message.content); if (!text || text.trim().length < 2 || isSynthetic(text)) continue; @@ -338,7 +350,7 @@ function readTranscript(path) { if (entry.cwd) project = basename(entry.cwd); // Each turn keeps the branch current at it: a sitting is rendered with its first turn's, while // the session as a whole keeps the last, so a session that never switched renders as it did. - turns.push({ role: entry.type, at: entry.timestamp || '', text: text.trim(), quiet: silence.take(), branch }); + turns.push({ role: entry.type, at: entry.timestamp || '', text: text.trim(), quiet: silence.take(), branch, model, effort }); } if (!turns.length) return null; @@ -393,8 +405,9 @@ function silenceMeter() { // where the transcript records one per turn, and the whole session keeps its last: a switch later // in the session then changes no sitting already closed. A session only grows at its end, so a // sitting never changes once the next one has begun, and a session that resumes sends its last -// sitting again, not the whole. -function sittingsOf(parsed, minutes, kilobytes) { +// sitting again, not the whole. A prompt typed under another connection than the sitting's starts a +// new one too (`spans`, the session's record in state.json): a sitting belongs to one connection. +function sittingsOf(parsed, minutes, kilobytes, spans) { const sittings = []; let held = 0; let previous = null; @@ -402,12 +415,17 @@ function sittingsOf(parsed, minutes, kilobytes) { const quiet = turn.quiet >= minutes * 60000; // Measured on the turns' own text, so the cut moves with neither the heading nor the redaction. const full = kilobytes > 0 && held >= kilobytes * 1024 && previous !== null && previous.role !== 'user'; - if (!sittings.length || (turn.at && (quiet || full))) { + const open = sittings[sittings.length - 1]; + // The agent's turns stay with the prompt they answer, whatever was connected meanwhile. + const connection = open && turn.role !== 'user' ? open.connection : connectionAt(spans, turn.at, open && open.connection); + const moved = Boolean(open) && connection !== open.connection; + if (!open || (turn.at && (quiet || full || moved))) { sittings.push({ ...parsed, turns: [], firstAt: sittings.length ? turn.at : parsed.firstAt, branch: turn.branch || parsed.branch, + connection, }); held = 0; } @@ -418,6 +436,17 @@ function sittingsOf(parsed, minutes, kilobytes) { return sittings; } +// The model a sitting ran on and its reasoning effort, as its last turn has them: what Claude Code was +// set to when the sitting was last sent. Neither is part of the rendered content, so they change no +// hash, and a transcript that names none adds nothing to the request. +function ranOn(sitting) { + const last = sitting.turns[sitting.turns.length - 1] || {}; + const ran = {}; + if (last.model) ran.model = last.model; + if (last.effort) ran.effort = last.effort; + return ran; +} + /** The first sitting keeps the id a whole session had, so a session first sent whole is replaced, not doubled. */ function sittingId(sessionId, index) { return `${SOURCE}:${sessionId}` + (index ? `:${index + 1}` : ''); @@ -425,6 +454,43 @@ function sittingId(sessionId, index) { const hashOf = (text) => createHash('sha256').update(text).digest('hex'); +// A fingerprint of the key and address this machine is connected with, empty while it has none. +// state.json keeps, per session, the connections its prompts were typed under (`connections`), and +// a sitting is sent with the connection it was typed under and with no other: what a person typed +// before connecting, or under another project's key, stays on this machine. +const connectionOf = (config) => (config.apiKey ? hashOf(`${config.apiUrl}\n${config.apiKey}`).slice(0, 16) : ''); + +/** + * Records the connection a session's next prompts are typed under, when it is not the one recorded + * last. The first record covers the session from its start. Every hook of a session calls this, and + * `connect` does for the sessions still open, so a new connection holds from the prompt after it. + */ +function noteConnection(config, sessionId, state) { + if (!sessionId) return; + const connection = connectionOf(config); + const last = (spans) => (Array.isArray(spans) && spans.length ? spans[spans.length - 1].connection : undefined); + if (last(book(state || loadState()).connections[sessionId]) === connection) return; + const at = Date.now(); + updateState((fresh) => { + const all = book(fresh).connections; + const spans = Array.isArray(all[sessionId]) ? all[sessionId] : []; + if (last(spans) !== connection) all[sessionId] = spans.concat({ at: spans.length ? at : 0, connection }); + }, state); +} + +/** + * The connection a turn was typed under: the last one recorded before it. A session the hooks kept + * no record of (one from before the plugin was installed) has none, and is sent as backfill sends it. + */ +function connectionAt(spans, at, fallback) { + if (!Array.isArray(spans) || !spans.length) return undefined; + const time = Date.parse(at); + if (Number.isNaN(time)) return fallback !== undefined ? fallback : spans[0].connection; + let found = spans[0].connection; + for (const span of spans) if (span.at <= time) found = span.connection; + return found; +} + /** * What sending a session carries now: each sitting rendered, and the ones past.dev does not hold yet. * state.json knows a sent session by the hash of its whole rendering (`hash`), which is what still @@ -433,28 +499,37 @@ const hashOf = (text) => createHash('sha256').update(text).digest('hex'); * keeps the sitting length and size it was first sent with (`sittingMinutes`, `sittingKilobytes`): * a new value in the config applies to the sessions sent after it, and the boundaries of one * already in past.dev never move. One sent in sittings before the size existed keeps no size at all. + * `changed` holds the sittings to send; `kept` the ones that differ too but were typed under another + * connection, or under none, and stay on this machine (`spans`, the session's record of them). */ -function planSend(parsed, context, sent, config) { +function planSend(parsed, context, sent, config, spans) { const pinned = Boolean(sent && sent.sittingMinutes); const minutes = pinned ? sent.sittingMinutes : config.sittingMinutes; const kilobytes = pinned ? (Number(sent.sittingKilobytes) || 0) : config.sittingKilobytes; - const sittings = sittingsOf(parsed, minutes, kilobytes).map((sitting, index) => { + const sittings = sittingsOf(parsed, minutes, kilobytes, spans).map((sitting, index) => { const content = renderTranscript(sitting, context); return { index, sitting, content, hash: hashOf(content), bytes: Buffer.byteLength(content) }; }); const whole = hashOf(renderTranscript(parsed, context)); const known = sent && Array.isArray(sent.sittings) ? sent.sittings : []; - if (sent && sent.hash === whole) return { whole, minutes, kilobytes, sittings, known, changed: [] }; - return { whole, minutes, kilobytes, sittings, known, changed: sittings.filter((part) => known[part.index] !== part.hash) }; + if (sent && sent.hash === whole) return { whole, minutes, kilobytes, sittings, known, changed: [], kept: [] }; + const connection = connectionOf(config); + const mine = (part) => part.sitting.connection === undefined || (connection !== '' && part.sitting.connection === connection); + const differing = sittings.filter((part) => known[part.index] !== part.hash); + return { + whole, minutes, kilobytes, sittings, known, + changed: differing.filter(mine), + kept: differing.filter((part) => !mine(part)), + }; } -// Which project, branch and directory a session belongs to: where the hook or the command ran, -// which the caller knows, and what the transcript says where it does not. +// Which project and branch a session belongs to: where the hook or the command ran, which the +// caller knows, and what the transcript says where it does not. The folder's name is the project; +// its path never leaves this machine. function placeOf(parsed, context) { return { project: context.project || parsed.project, branch: context.branch || parsed.branch, - cwd: context.cwd || '', }; } @@ -758,7 +833,7 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, } const before = sessions[sessionId]; - const plan = planSend(parsed, context, before, config); + const plan = planSend(parsed, context, before, config, book(state).connections[sessionId]); // A compaction sends the sittings that closed since the last send, once each, and holds the one // still open unless the session's last send is an hour old: that sitting grows at every turn, // and sent at every compaction it was a new paid revision of itself every few minutes. Its turns @@ -773,7 +848,7 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, // Unchanged still closes the session out. Without this it stays pending, and every later // SessionStart re-reads and re-hashes a transcript that is already in past.dev. if (!stillRunning && pending[sessionId]) updateState((fresh) => { delete book(fresh).pending[sessionId]; }, state); - return { skipped: held ? 'held' : 'unchanged' }; + return { skipped: held ? 'held' : plan.kept.length ? 'kept' : 'unchanged', kept: plan.kept.length }; } const place = placeOf(parsed, context); @@ -795,10 +870,10 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, conversationId: sessionId, sessionId, project: place.project, - cwd: place.cwd, gitBranch: branch || '', sitting: part.index + 1, turns: part.sitting.turns.length, + ...ranOn(part.sitting), }, }; }), @@ -813,11 +888,13 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, return { error: result ? result.error : 'unreachable', code }; } // A held sitting keeps the hash it was last sent with, or none, so it goes at the next send, and - // the whole hash is written only once the whole session is in past.dev. + // the whole hash is written only once the whole session is in past.dev. A sitting kept on this + // machine keeps its last hash, or none, the same way: it is never in past.dev as it is now. const hashes = plan.sittings.map((part) => part.hash); + for (const part of plan.kept) hashes[part.index] = plan.known[part.index] || null; if (held) { if (plan.known[held.index]) hashes[held.index] = plan.known[held.index]; else hashes.pop(); } const sent = { - hash: held ? before.hash : plan.whole, + hash: held || plan.kept.length ? (before ? before.hash : undefined) : plan.whole, sittings: hashes, sittingMinutes: plan.minutes, sittingKilobytes: plan.kilobytes, @@ -837,6 +914,7 @@ async function ingestSession(config, state, sessionId, transcriptPath, context, sittings: plan.sittings.length, sent: parts.length, held: held ? 1 : 0, + kept: plan.kept.length, bytes: parts.reduce((sum, part) => sum + part.bytes, 0), credits: creditsOf(parts), }; @@ -895,7 +973,7 @@ function tidyPending(state, config, currentId) { const parsed = transcript && existsSync(transcript) ? readTranscript(transcript) : null; let done = !parsed; if (parsed && idleFor(transcript, config)) { - const content = renderTranscript(parsed, { project: pending.project, cwd: pending.cwd, branch: '' }); + const content = renderTranscript(parsed, { project: pending.project, branch: '' }); const hash = createHash('sha256').update(content).digest('hex'); done = Boolean(sessions[id] && sessions[id].hash === hash); } @@ -916,6 +994,7 @@ async function modeBrief(config) { const entry = { transcript, cwd, project: basename(cwd) }; updateState((fresh) => { book(fresh).pending[input.session_id] = entry; }, state); } + noteConnection(config, input.session_id, state); // SessionEnd does not fire when a session is killed or the machine sleeps, so the start of the // next one is where an unsent session gets picked up. Only an idle one: a session still being @@ -926,7 +1005,7 @@ async function modeBrief(config) { for (const [id, pending] of Object.entries(book(state).pending)) { if (id === input.session_id || !idleFor(pending.transcript, config)) continue; await ingestSession(config, state, id, pending.transcript, { - project: pending.project, cwd: pending.cwd, branch: '', + project: pending.project, branch: '', }); } @@ -970,12 +1049,13 @@ async function modePreCompact(config) { const transcript = input.transcript_path; if (!input.session_id || !transcript) return; const state = loadState(); + noteConnection(config, input.session_id, state); await ingestSession( config, state, input.session_id, transcript, - {project: basename(cwd), cwd, branch: ''}, + {project: basename(cwd), branch: ''}, {stillRunning: true, compacting: true}, ); } @@ -984,6 +1064,7 @@ async function modePrompt(config) { const input = await readStdin(); if (!ownEvent(input, 'UserPromptSubmit')) return; if (denied(config, input.cwd || '')) return; + noteConnection(config, input.session_id); const prompt = input.prompt || ''; // A short prompt ("yes", "go on") carries no query. Spending a recall on it wastes the budget // and returns noise. @@ -1017,8 +1098,9 @@ function clearActivity(sessionId) { try { unlinkSync(activityPath(sessionId)); } // sent in sittings, and a waiter of 3 would send an open session whole. 5: sittings are cut where // the transcript went quiet, for as long as the config says. 6: sittings are also cut by size, and // a waiter of 5 would cut a session the hooks already sent by size along other lines, and send its -// sittings again under shifted ids. -const WAITER_VERSION = 6; +// sittings again under shifted ids. 7: a sitting is sent with the connection it was typed under, and +// a waiter of 6 would send what was typed before connecting, or under another key. +const WAITER_VERSION = 7; // The waiter never sleeps longer than this in one go. A timer does not count the time the machine // is asleep, so one long timer set for "in twelve hours" fires hours late after a night with the // lid closed. Short slices checked against the wall clock send within a minute of waking instead. @@ -1064,7 +1146,9 @@ async function modeStop(config) { const input = await readStdin(); if (!ownEvent(input, 'Stop')) return; const cwd = input.cwd || ''; - if (denied(config, cwd) || !config.ingest || !config.apiKey) return; + if (denied(config, cwd)) return; + noteConnection(config, input.session_id); + if (!config.ingest || !config.apiKey) return; const transcript = input.transcript_path; if (!input.session_id || !transcript) return; const previous = readActivity(input.session_id) || {}; @@ -1120,7 +1204,7 @@ async function modeIdle(config, argv) { continue; } await ingestSession(loadConfig(), loadState(), sessionId, activity.transcript, { - project: basename(activity.cwd), cwd: activity.cwd, branch: '', + project: basename(activity.cwd), branch: '', }, { stillRunning: !ended }); // A turn that landed while this was sending keeps the file, and the next Stop starts a waiter. const after = readActivity(sessionId); @@ -1144,7 +1228,7 @@ async function modeFlush(config, argv) { const [sessionId, transcriptPath, cwd = ''] = argv; if (!sessionId || !transcriptPath) return; await ingestSession(config, loadState(), sessionId, transcriptPath, { - project: basename(cwd), cwd, branch: '', + project: basename(cwd), branch: '', }); } @@ -1216,6 +1300,9 @@ const credits = (bytes) => Math.ceil(bytes / 350); // Every data point is priced on its own and rounds up on its own, so sittings are summed one by one. const creditsOf = (parts) => parts.reduce((sum, part) => sum + credits(part.bytes), 0); +// Why a sitting is not sent: it belongs to the connection it was typed under. +const KEPT_WHY = 'they were typed before this machine was connected, or under another key'; + // Sending the history already on disk: every unsent session of this project, or of every project // with --all. One session is /pastdotdev:ingest. The session this command runs in is never part of it: // the hooks send it when it goes idle or ends, and sending it now as well would pay for it twice. @@ -1241,17 +1328,21 @@ async function modeBackfill(config, argv) { // size. The two differ by about three hundred times and only one of them is billed. const rows = []; let already = 0; - const { sessions } = book(state); + let kept = 0; + const { sessions, connections } = book(state); for (const item of found) { const parsed = readTranscript(item.path); if (!parsed) continue; - const plan = planSend(parsed, { project: basename(cwd), branch: '' }, sessions[item.sessionId], config); - if (!plan.changed.length) { already++; continue; } + const plan = planSend(parsed, { project: basename(cwd), branch: '' }, sessions[item.sessionId], config, connections[item.sessionId]); + kept += plan.kept.length; + if (!plan.changed.length) { if (!plan.kept.length) already++; continue; } rows.push({ item, at: parsed.firstAt, prompt: firstPrompt(parsed), parts: plan.changed }); } + const keptNote = `${kept} sitting(s) stay on this machine: ${KEPT_WHY}.`; if (!rows.length) { console.log(`Nothing new to send. ${already} session(s) are already in past.dev.`); + if (kept) console.log(keptNote); return; } @@ -1271,6 +1362,7 @@ async function modeBackfill(config, argv) { `${(bytesOf(parts) / 1024).toFixed(1)} KB of prose in ${parts.length} sitting(s), about ${creditsOf(parts).toLocaleString()} credits.`); console.log('Each sitting is one data point, dated at its own first turn: one ingestion toward the project\'s monthly cap.'); if (current) console.log('The session you are in is left out: it is sent when it goes idle or ends.'); + if (kept) console.log(keptNote); console.log('Nothing has been sent. Run the same command with --confirm to send them all, ' + `or ${commandOf('ingest')} to send only one.`); return; @@ -1280,7 +1372,7 @@ async function modeBackfill(config, argv) { let sittings = 0; for (const row of rows) { const result = await ingestSession(config, state, row.item.sessionId, row.item.path, { - project: basename(cwd), cwd, branch: '', + project: basename(cwd), branch: '', }); if (result.ok) { sent++; sittings += result.sent; } } @@ -1313,19 +1405,22 @@ async function modeIngest(config, argv) { const state = loadState(); const open = target.sessionId === current || Boolean(book(state).pending[target.sessionId]); const result = await ingestSession(config, state, target.sessionId, target.path, { - project: basename(cwd), cwd, branch: '', + project: basename(cwd), branch: '', }, { stillRunning: open }); const id = short(target.sessionId); if (result.skipped === 'unchanged') console.log(`Session ${id} is already in past.dev, unchanged. Nothing was sent.`); + else if (result.skipped === 'kept') console.log(`Nothing to send from session ${id}. ${result.kept} sitting(s) stay on this machine: ${KEPT_WHY}.`); else if (result.skipped) console.log(`Session ${id}: ${result.skipped}.`); else if (result.error) { console.log(`Session ${id} was not sent: ${result.error}${result.code ? ` ${result.code}` : ''}.`); } else { + const others = result.sittings - result.sent - result.kept; const what = result.sent === result.sittings ? `${result.turns} turns in ${result.sittings} sitting(s)` - : `${result.sent} of its ${result.sittings} sittings (the others are already in past.dev)`; + : `${result.sent} of its ${result.sittings} sittings` + (!others ? '' : result.kept ? ` (${others} already in past.dev)` : ' (the others are already in past.dev)'); console.log(`Sent session ${id}: ${what}, ${(result.bytes / 1024).toFixed(1)} KB, ` + `about ${result.credits} credits. It appears in Memories once the pipeline finishes.`); + if (result.kept) console.log(`${result.kept} sitting(s) stay on this machine: ${KEPT_WHY}.`); if (open) console.log('It is still open: if it grows, it is sent again when it goes idle or ends.'); } } @@ -1341,18 +1436,23 @@ function modeCut(config, argv) { if (error) { console.log(error); return; } const parsed = readTranscript(target.path); if (!parsed) { console.log('Nothing to send from that transcript.'); return; } - const { sessions, pending } = book(loadState()); - const plan = planSend(parsed, { project: basename(cwd), branch: '' }, sessions[target.sessionId], config); + const { sessions, pending, connections } = book(loadState()); + const plan = planSend(parsed, { project: basename(cwd), branch: '' }, sessions[target.sessionId], config, connections[target.sessionId]); + // A sitting that stays on this machine is not part of what would be sent, so it is not printed. + const shown = plan.sittings.filter((part) => !plan.kept.includes(part)); + const keptNote = `${plan.kept.length} sitting(s) stay on this machine and are not shown: ${KEPT_WHY}.`; + if (!shown.length) { console.log(`Nothing to send from that session. ${keptNote}`); return; } const kb = (parts) => (parts.reduce((sum, part) => sum + part.bytes, 0) / 1024).toFixed(1); - const held = plan.sittings.length - plan.changed.length; + const held = shown.length - plan.changed.length; const cost = !plan.changed.length || !held - ? `${kb(plan.sittings)} KB sent · about ${creditsOf(plan.sittings)} credits` - : `${kb(plan.sittings)} KB, ${held} sitting(s) already in past.dev · ${kb(plan.changed)} KB still to send · about ${creditsOf(plan.changed)} credits`; + ? `${kb(shown)} KB sent · about ${creditsOf(shown)} credits` + : `${kb(shown)} KB, ${held} sitting(s) already in past.dev · ${kb(plan.changed)} KB still to send · about ${creditsOf(plan.changed)} credits`; let raw = 0; try { raw = statSync(target.path).size; } catch { /* size is informational */ } - console.error(`# session ${short(target.sessionId)} · ${parsed.turns.length} turns in ${plan.sittings.length} sitting(s) · ` + + const turns = shown.reduce((sum, part) => sum + part.sitting.turns.length, 0); + console.error(`# session ${short(target.sessionId)} · ${turns} turns in ${shown.length} sitting(s) · ` + `${(raw / 1024).toFixed(0)} KB on disk · ${cost}\n`); - console.log(plan.sittings.map((part) => part.content).join('\n')); + console.log(shown.map((part) => part.content).join('\n')); const id = short(target.sessionId); const ingest = commandOf('ingest'); @@ -1362,6 +1462,7 @@ function modeCut(config, argv) { else if (pending[target.sessionId]) next = `This session is still open. past.dev receives it when it goes idle or ends. To send it now: ${ingest} ${id}`; else next = `To send it: ${ingest} ${id}`; console.error(`\n# ${next}`); + if (plan.kept.length) console.error(`# ${keptNote}`); } // On-demand recall, for the skill and for a person at a terminal. The hooks cover the automatic @@ -1515,9 +1616,15 @@ async function modeConnect(argv) { console.log(`Warning: ${next.apiUrl} is plain http, so the key travels unencrypted. Use https unless this network is yours.`); } if (key) { + // The sessions still open go on under this connection: what they hold so far stays here. + try { + const connected = loadConfig(); + for (const id of Object.keys(book(loadState()).pending)) noteConnection(connected, id); + } catch { /* the next prompt's hook records it */ } console.log(`Connected as ${identity}. The key is in ${CONFIG_PATH}, readable only by you.`); console.log(`What is sent is visible to ${who}.`); - console.log(`New sessions are read from now on. Run ${commandOf('backfill')} to send the history already on this machine.`); + console.log('Sessions are read from your next prompt on: what you typed before connecting stays on this machine.'); + console.log(`Run ${commandOf('backfill')} to send the sessions from before the plugin was installed.`); } else { console.log(`From now on, what is sent is visible to ${who}. Sessions already in past.dev keep their audience until they are sent again.`); } diff --git a/plugins/past/commands/connect.md b/plugins/past/commands/connect.md index fed5279..7df336e 100644 --- a/plugins/past/commands/connect.md +++ b/plugins/past/commands/connect.md @@ -43,5 +43,6 @@ organization's management key (`past_mk_…`). The identity is the email or id every memory is attributed to; recall stays off without one. The API URL is only for a self-hosted or staging deployment. -After it succeeds, tell them two things: new sessions are read from now on, and `/pastdotdev:backfill` -sends the history already on this machine. +After it succeeds, tell them two things: sessions are read from their next prompt on, so what they +typed before connecting stays on this machine, and `/pastdotdev:backfill` sends the sessions from +before the plugin was installed.