plugin.json
{
"$schema": "https://antigravity.google/schemas/v1/plugin.json",
"name": "time-machine",
"displayName": "Time Machine",
"version": "0.1.3",
"description": "Automatic git working-tree snapshots per turn. Use /timeline to inspect history, diff states, and undo or redo changes safely.",
"suggestedPrompts": [
"/timeline",
"/timeline undo"
],
"author": {
"name": "MateLogic (adapted from DiegoMarty & midudev/better-claude)",
"url": "https://mate-logic.tech/"
},
"homepage": "https://github.com/Mate-Logic/better-agy/tree/main/plugins/time-machine",
"repository": "https://github.com/Mate-Logic/better-agy",
"license": "MIT",
"keywords": [
"git",
"timeline",
"undo",
"snapshot",
"time-machine"
]
}
README.md
# Time Machine
Every turn that modifies files in a git repository is automatically snapshotted into an isolated git ref (`refs/time-machine/...`) without touching your staging area, `HEAD`, branches, or `.gitignore`d files. Jumps are always undoable.
## Commands
- `/timeline` or `/timeline list` — List turn snapshots
- `/timeline diff <n>` — Preview changes before jumping
- `/timeline <n>` — Jump working tree to state `#n`
- `/timeline undo` / `/timeline redo` — Step backward or forward
- `/timeline prune [days]` — Clean up old snapshots
## Quick install
**Linux / macOS:**
```bash
curl -fsSL https://raw.githubusercontent.com/Mate-Logic/better-agy/main/install.sh | bash -s -- time-machine
```
**Windows (PowerShell):**
```powershell
$env:PLUGINS="time-machine"; irm https://raw.githubusercontent.com/Mate-Logic/better-agy/main/install.ps1 | iex
```
README.es.md
# Time Machine
Cada turno que modifica archivos en un repo git genera un snapshot automático en una ref aislada (`refs/time-machine/...`) sin tocar tu staging area, `HEAD`, ramas ni archivos ignorados. Cada salto se puede deshacer.
## Comandos
- `/timeline` o `/timeline list` — Lista los snapshots por turno
- `/timeline diff <n>` — Muestra qué cambiaría antes de saltar
- `/timeline <n>` — Vuelve el working tree al estado `#n`
- `/timeline undo` / `/timeline redo` — Deshace o rehace saltos
- `/timeline prune [días]` — Limpia snapshots viejos
## Instalación rápida
**Linux / macOS:**
```bash
curl -fsSL https://raw.githubusercontent.com/Mate-Logic/better-agy/main/install.sh | bash -s -- time-machine
```
**Windows (PowerShell):**
```powershell
$env:PLUGINS="time-machine"; irm https://raw.githubusercontent.com/Mate-Logic/better-agy/main/install.ps1 | iex
```
hooks.json
{
"time-machine": {
"PreInvocation": [
{
"type": "command",
"command": "node ./scripts/hook.mjs",
"timeout": 20
}
],
"Stop": [
{
"type": "command",
"command": "node ./scripts/hook.mjs",
"timeout": 20
}
]
}
}
package.json
{
"name": "time-machine",
"private": true,
"type": "module"
}
scripts/hook.mjs
#!/usr/bin/env node
import { run } from '../src/runner.js'
import { locate, treeOf, keep, changes, prune, REF_ROOT } from '../src/git.js'
import { nextId } from '../src/states.js'
import { shorten, digestText } from '../src/format.js'
import { loadSession, saveSession, MAX_AGE_DAYS } from '../src/store.js'
let raw = ''
for await (const chunk of process.stdin) raw += chunk
let input = {}
try {
input = raw.trim() ? JSON.parse(raw) : {}
} catch {
process.stdout.write('{}')
process.exit(0)
}
const event = input.hookEventName
const sessionId = input.conversationId || 'default'
const cwd = input.cwd || (Array.isArray(input.workspacePaths) ? input.workspacePaths[0] : process.cwd())
async function main () {
if (!cwd) return {}
const repo = await locate(run, cwd, sessionId.replace(/[^a-zA-Z0-9._-]/g, '_'))
if (!repo) return {}
const session = loadSession(sessionId)
session.repoTop = repo.top
if (event === 'PreInvocation') {
// Only snapshot at the start of a new user turn (invocationNum === 1) or if not yet captured
if (input.invocationNum && input.invocationNum > 1 && session.turnBefore) {
return {}
}
// Prune snapshots older than MAX_AGE_DAYS once per day
const now = Date.now()
if (now - (session.prunedAt || 0) > 24 * 60 * 60 * 1000) {
await prune(run, repo, now, MAX_AGE_DAYS * 24 * 60 * 60 * 1000).catch(() => {})
session.prunedAt = now
}
const before = await treeOf(run, repo)
session.turnBefore = {
tree: before.tree,
head: before.head,
prompt: input.lastUserInput || '',
at: now
}
let injectSteps
if (session.jumpedSinceLastTurn && session.lastAgentTree && session.lastAgentTree !== before.tree) {
const diff = await changes(run, repo, session.lastAgentTree, before.tree).catch(() => [])
session.jumpedSinceLastTurn = false
if (diff.length > 0) {
injectSteps = [
{
systemMessage: {
systemMessage: `[Time Machine] Files changed since your last turn (via /timeline jump): ${digestText(diff)}`
}
}
]
}
} else if (session.jumpedSinceLastTurn) {
session.jumpedSinceLastTurn = false
}
saveSession(sessionId, session)
return injectSteps ? { injectSteps } : {}
}
if (event === 'Stop') {
if (!session.turnBefore) return {}
const before = session.turnBefore
session.turnBefore = null
const after = await treeOf(run, repo)
if (after.tree === before.tree) {
saveSession(sessionId, session)
return {}
}
const now = Date.now()
const safeSession = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_')
// Ensure the "before" tree is saved as a state if no existing state holds it
let parentState = session.states.find(s => s.tree === before.tree)
if (!parentState) {
const id = nextId(session.states)
const label = session.states.length === 0 ? 'start of the session' : 'changes outside agent'
const ref = `${REF_ROOT}/${safeSession}/${id}`
const commit = await keep(run, repo, { tree: before.tree, head: before.head }, ref, label)
parentState = {
id,
parent: session.cursor,
tree: before.tree,
head: before.head,
commit,
ref,
label,
prompt: label,
files: [],
at: before.at || now
}
session.states.push(parentState)
}
// Save the "after" tree as the new turn state
const id = nextId(session.states)
const prompt = before.prompt || input.lastUserInput || 'turn changes'
const label = shorten(prompt)
const ref = `${REF_ROOT}/${safeSession}/${id}`
const commit = await keep(run, repo, after, ref, label)
const files = await changes(run, repo, before.tree, after.tree)
const newState = {
id,
parent: parentState.id,
tree: after.tree,
head: after.head,
commit,
ref,
label,
prompt,
files,
at: now
}
session.states.push(newState)
session.cursor = newState.id
session.lastAgentTree = after.tree
saveSession(sessionId, session)
return {}
}
return {}
}
main()
.then(out => process.stdout.write(JSON.stringify(out || {})))
.catch(() => process.stdout.write('{}'))
scripts/timeline.mjs
#!/usr/bin/env node
import { run } from '../src/runner.js'
import { locate, treeOf, keep, changes, move, prune, MoveBlocked, REF_ROOT } from '../src/git.js'
import { lineOf, nextId } from '../src/states.js'
import { ago, digestText, ICON, summary } from '../src/format.js'
import { loadSession, saveSession, listSessionsForRepo, MAX_AGE_DAYS } from '../src/store.js'
const argv = process.argv.slice(2)
let sessionId = process.env.AGY_CONVERSATION_ID || ''
let cwd = process.cwd()
const args = []
for (let i = 0; i < argv.length; i++) {
if (argv[i] === '--session' && argv[i + 1]) {
sessionId = argv[++i]
} else if (argv[i] === '--cwd' && argv[i + 1]) {
cwd = argv[++i]
} else {
args.push(argv[i])
}
}
const cmd = args[0] || 'list'
async function resolveContext () {
const probe = await locate(run, cwd, 'probe')
if (!probe) {
console.error('Time Machine requires a git repository.')
process.exit(1)
}
if (!sessionId) {
const sessions = listSessionsForRepo(probe.top)
sessionId = sessions[0]?.sessionId || 'default'
}
const safeSession = sessionId.replace(/[^a-zA-Z0-9._-]/g, '_')
const repo = await locate(run, cwd, safeSession)
const session = loadSession(sessionId)
session.repoTop = repo.top
return { repo, session, safeSession }
}
async function jumpTo (repo, session, safeSession, targetId) {
const target = session.states.find(s => s.id === targetId)
if (!target) {
console.error(`State #${targetId} not found.`)
process.exit(1)
}
const nowTree = await treeOf(run, repo)
// Save current unsaved working tree if no state holds it yet
let currentState = session.states.find(s => s.tree === nowTree.tree)
if (!currentState) {
const id = nextId(session.states)
const label = 'your changes, kept before a jump'
const ref = `${REF_ROOT}/${safeSession}/${id}`
const commit = await keep(run, repo, nowTree, ref, label)
currentState = {
id,
parent: session.cursor,
tree: nowTree.tree,
head: nowTree.head,
commit,
ref,
label,
prompt: label,
files: [],
at: Date.now()
}
session.states.push(currentState)
}
if (nowTree.tree === target.tree) {
session.cursor = target.id
saveSession(sessionId, session)
console.log(`Already at state #${target.id}: ${target.label}`)
return
}
try {
const moved = await move(run, repo, nowTree.tree, target.tree)
session.jumpedFrom = currentState.id
session.cursor = target.id
session.jumpedSinceLastTurn = true
saveSession(sessionId, session)
console.log(`Jumped to #${target.id} (${target.label})`)
console.log(`Changed: ${digestText(moved)} (${summary(moved)})`)
if (target.head && nowTree.head && target.head !== nowTree.head) {
console.log('Note: HEAD moved since this snapshot. Files were restored on top of your current HEAD/branch.')
}
} catch (err) {
if (err instanceof MoveBlocked) {
console.error(`Jump blocked: ${err.message}`)
process.exit(1)
}
throw err
}
}
async function main () {
const { repo, session, safeSession } = await resolveContext()
if (cmd === 'list' || cmd === 'status') {
if (session.states.length === 0) {
console.log('No Time Machine snapshots yet in this session.')
return
}
const now = Date.now()
const onLine = lineOf(session.states, session.cursor)
console.log(`Time Machine (${session.states.length} states, session ${sessionId.slice(0, 8)}):`)
for (const s of [...session.states].reverse()) {
const marker = s.id === session.cursor ? '◉' : onLine.has(s.id) ? '●' : '○'
const age = ago(now - s.at)
const files = s.files?.length ? digestText(s.files) : 'no files'
console.log(`${marker} #${s.id} ${s.label} (${age})`)
console.log(` ${files}`)
}
return
}
if (cmd === 'undo') {
const current = session.states.find(s => s.id === session.cursor)
if (!current || current.parent === null) {
console.log('Nothing to undo.')
return
}
await jumpTo(repo, session, safeSession, current.parent)
return
}
if (cmd === 'redo') {
const children = session.states.filter(s => s.parent === session.cursor)
if (children.length === 0) {
console.log('Nothing to redo.')
return
}
const newest = children.sort((a, b) => b.at - a.at)[0]
await jumpTo(repo, session, safeSession, newest.id)
return
}
if (cmd === 'diff') {
const targetId = Number(String(args[1] || '').replace(/^#/, ''))
const target = session.states.find(s => s.id === targetId)
if (!target) {
console.error(`State #${args[1]} not found.`)
process.exit(1)
}
const nowTree = await treeOf(run, repo)
const diff = await changes(run, repo, nowTree.tree, target.tree)
if (diff.length === 0) {
console.log(`Working tree already matches #${target.id}.`)
} else {
console.log(`Jumping to #${target.id} (${target.label}) would change ${summary(diff)}:`)
for (const f of diff) {
const stats = f.added === null ? 'binary' : `+${f.added} -${f.removed}`
console.log(` ${ICON[f.status] ?? '~'} ${f.path} (${stats})`)
}
}
return
}
if (cmd === 'prune') {
const days = Number(args[1]) || MAX_AGE_DAYS
const dropped = await prune(run, repo, Date.now(), days * 24 * 60 * 60 * 1000)
console.log(`Pruned ${dropped} snapshot(s) older than ${days} day(s).`)
return
}
if (cmd === 'go' || /^#?\d+$/.test(cmd)) {
const rawId = cmd === 'go' ? args[1] : cmd
const targetId = Number(String(rawId || '').replace(/^#/, ''))
if (!Number.isInteger(targetId)) {
console.error('Usage: timeline.mjs [list | <n> | go <n> | undo | redo | diff <n> | prune [days]]')
process.exit(1)
}
await jumpTo(repo, session, safeSession, targetId)
return
}
console.error(`Unknown command: ${cmd}`)
process.exit(1)
}
main().catch((err) => {
console.error(err.message)
process.exit(1)
})
skills/timeline/SKILL.md
---
name: timeline
description: >-
Time Machine git snapshot history adapted from betterclaude.dev (/timeline).
Use when the user runs /timeline, wants to view turn snapshots, undo/redo
working tree changes, or roll back files to an earlier turn (including shell changes).
---
# Time Machine (`/timeline`)
Every turn that modifies files in a git repository is automatically snapshotted into an isolated git index (`refs/time-machine/...`) without touching your staging area, HEAD, branches, or `.gitignore`d files.
Always pass `--session <conversation-id>` and `--cwd <workspace-path>` when invoking `timeline.mjs`. On Windows PowerShell use `$HOME/.gemini/config/plugins/time-machine/scripts/timeline.mjs`.
## Commands
- **List snapshots** (`/timeline` or `/timeline list`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs list --session "<conversation-id>" --cwd "<workspace>"
```
- **Preview changes before jumping** (`/timeline diff <n>`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs diff <n> --session "<conversation-id>" --cwd "<workspace>"
```
- **Jump to state `#n`** (`/timeline <n>`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs go <n> --session "<conversation-id>" --cwd "<workspace>"
```
- **Undo** (`/timeline undo`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs undo --session "<conversation-id>" --cwd "<workspace>"
```
- **Redo** (`/timeline redo`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs redo --session "<conversation-id>" --cwd "<workspace>"
```
- **Prune old snapshots** (`/timeline prune [days]`):
```bash
node ~/.gemini/config/plugins/time-machine/scripts/timeline.mjs prune 7 --session "<conversation-id>" --cwd "<workspace>"
```
Note: Any unsaved changes in the working tree are automatically saved as a snapshot (`your changes, kept before a jump`) before jumping, so jumps are always undoable.
src/format.js
const LABEL_MAX = 60
const FEW = 2
const GROUPS = 2
export const ICON = { A: '+', D: '−', M: '~' }
export function shorten (text, max = LABEL_MAX) {
const line = text.replace(/\s+/g, ' ').trim()
return line.length > max ? `${line.slice(0, max - 1)}…` : line
}
export function summary (files) {
const added = files.reduce((sum, file) => sum + (file.added ?? 0), 0)
const removed = files.reduce((sum, file) => sum + (file.removed ?? 0), 0)
return files.length === 0 ? 'no files' : `${files.length} file${files.length === 1 ? '' : 's'} +${added} −${removed}`
}
const shortPath = path => path.split('/').slice(-2).join('/')
export function digest (files) {
if (files.length <= FEW) return { kind: 'few', files: files.map(file => ({ ...file, name: shortPath(file.path) })) }
const split = files.map(file => file.path.split('/'))
let shared = 0
while (split.every(parts => parts.length > shared + 1 && parts[shared] === split[0][shared])) shared++
const counts = new Map()
for (const parts of split) {
const rest = parts.slice(shared)
const group = rest.length > 1 ? `${rest[0]}/` : rest[0]
counts.set(group, (counts.get(group) ?? 0) + 1)
}
const ranked = [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
return {
kind: 'many',
count: files.length,
added: files.reduce((sum, file) => sum + (file.added ?? 0), 0),
removed: files.reduce((sum, file) => sum + (file.removed ?? 0), 0),
groups: ranked.slice(0, GROUPS).map(([name, n]) => n > 1 ? `${name} ×${n}` : name),
more: Math.max(0, ranked.length - GROUPS)
}
}
export function digestText (files) {
const d = digest(files)
if (d.kind === 'few') return d.files.map(file => `${ICON[file.status] ?? '~'} ${file.name}`).join(' ')
return `${d.count} files +${d.added} −${d.removed} · ${d.groups.join(' · ')}${d.more ? ` · +${d.more}` : ''}`
}
export function ago (ms) {
const minutes = Math.round(ms / 60000)
if (minutes < 1) return 'now'
if (minutes < 60) return `${minutes}m`
const hours = Math.floor(minutes / 60)
return hours < 24 ? `${hours}h` : `${Math.floor(hours / 24)}d`
}
src/git.js
// The git side of Time Machine: snapshots of the working tree as commits no branch points
// at, and a move of the working tree from one of them to another.
export const REF_ROOT = 'refs/time-machine'
const IDENTITY = {
GIT_AUTHOR_NAME: 'time-machine',
GIT_AUTHOR_EMAIL: 'time-machine@localhost',
GIT_COMMITTER_NAME: 'time-machine',
GIT_COMMITTER_EMAIL: 'time-machine@localhost'
}
const TIMEOUT_MS = 120_000
const PATHS_PER_CALL = 500
const seededFrom = new Map()
export class MoveBlocked extends Error {
constructor (paths, why) {
super(why ?? `it would write over ignored files no snapshot holds (${paths.join(', ')})`)
this.name = 'MoveBlocked'
this.paths = paths
}
}
async function git (run, argv, init = {}) {
const result = await run(['git', ...argv], { timeoutMs: TIMEOUT_MS, ...init })
if (result.exitCode !== 0) {
const said = (result.stderr || result.stdout || '').trim().split('\n')[0]
throw new Error(`git ${argv[0]}: ${said || `exit ${result.exitCode}`}`)
}
return result.stdout.trim()
}
export async function locate (run, cwd, session) {
try {
const [top, gitDir] = await Promise.all([
git(run, ['rev-parse', '--show-toplevel'], { cwd }),
git(run, ['rev-parse', '--absolute-git-dir'], { cwd })
])
return { top, gitDir, index: `${gitDir}/time-machine-${session}.index` }
} catch {
return null
}
}
function indexEnv (repo) {
if (!repo.index) throw new Error('time-machine: no index of its own')
return { ...IDENTITY, GIT_INDEX_FILE: repo.index }
}
export function forget (index) {
seededFrom.delete(index)
}
export function isSeeded (index) {
return seededFrom.has(index)
}
export async function treeOf (run, repo) {
const init = { cwd: repo.top, env: indexEnv(repo) }
const { index } = repo
const head = await headOf(run, repo)
if (head !== null && seededFrom.get(index) !== head) {
if (!seededFrom.has(index)) await run(['cp', '-n', `${repo.gitDir}/index`, index], { cwd: repo.top }).catch(() => undefined)
await git(run, ['read-tree', '-m', 'HEAD'], init).catch(() => git(run, ['read-tree', 'HEAD'], init))
seededFrom.set(index, head)
}
await git(run, ['add', '-A', '--', '.'], init)
await untrackIgnored(run, repo, head, init)
return { tree: await git(run, ['write-tree'], init), head }
}
async function untrackIgnored (run, repo, head, init) {
const ignored = (await git(run, ['ls-files', '-z', '--cached', '--ignored', '--exclude-standard'], init)).split('\0').filter(Boolean)
if (ignored.length === 0) return
let leave = ignored
if (head !== null) {
const found = await git(run, ['cat-file', '--batch-check'], { cwd: repo.top, stdin: ignored.map(path => `${head}:${path}\n`).join('') })
const lines = found.split('\n')
leave = ignored.filter((_, i) => lines[i]?.endsWith(' missing'))
}
if (leave.length === 0) return
await git(run, ['rm', '-q', '--cached', '--pathspec-from-file=-', '--pathspec-file-nul'], { ...init, stdin: leave.map(path => `:(literal)${path}`).join('\0') })
}
async function headOf (run, repo) {
const result = await run(['git', 'rev-parse', '-q', '--verify', 'HEAD'], { cwd: repo.top })
return result.exitCode === 0 ? result.stdout.trim() : null
}
export async function keep (run, repo, { tree, head }, ref, message) {
const parent = head ? ['-p', head] : []
const commit = await git(run, ['commit-tree', tree, ...parent, '-m', message], { cwd: repo.top, env: IDENTITY })
await git(run, ['update-ref', ref, commit], { cwd: repo.top })
return commit
}
export async function snapshot (run, repo, ref, message) {
const now = await treeOf(run, repo)
return { tree: now.tree, commit: await keep(run, repo, now, ref, message) }
}
async function whole (run, repo, argv) {
const result = await run(['git', ...argv], { cwd: repo.top, timeoutMs: TIMEOUT_MS })
if (result.exitCode !== 0) throw new Error(`git ${argv[0]}: ${(result.stderr || '').trim().split('\n')[0] || `exit ${result.exitCode}`}`)
if (!result.isStdoutTruncated) return result.stdout
return result.stdout.slice(0, result.stdout.lastIndexOf('\0') + 1)
}
async function every (run, repo, argv, { stdin, okCodes = [0] } = {}) {
const result = await run(['git', ...argv], { cwd: repo.top, timeoutMs: TIMEOUT_MS, ...(stdin === undefined ? {} : { stdin }) })
if (!okCodes.includes(result.exitCode)) throw new Error(`git ${argv[0]}: ${(result.stderr || '').trim().split('\n')[0] || `exit ${result.exitCode}`}`)
if (result.isStdoutTruncated) throw new MoveBlocked([], 'it changes more files than can all be checked for ignored ones')
return result.stdout.split('\0').filter(Boolean)
}
export async function changes (run, repo, a, b) {
if (a === b) return []
const [numstat, status] = await Promise.all([
whole(run, repo, ['diff', '--numstat', '--no-renames', '-z', a, b]),
whole(run, repo, ['diff', '--name-status', '--no-renames', '-z', a, b])
])
const statusOf = new Map()
const parts = status.split('\0').filter(Boolean)
for (let i = 0; i + 1 < parts.length; i += 2) statusOf.set(parts[i + 1], parts[i])
return numstat.split('\0').filter(Boolean).map(line => {
const first = line.indexOf('\t')
const second = line.indexOf('\t', first + 1)
const added = line.slice(0, first)
const removed = line.slice(first + 1, second)
const path = line.slice(second + 1)
return {
path,
status: statusOf.get(path) ?? 'M',
added: added === '-' ? null : Number(added),
removed: removed === '-' ? null : Number(removed)
}
})
}
export async function move (run, repo, from, to) {
if (from === to) return []
const added = await every(run, repo, ['diff', '--name-only', '--diff-filter=A', '--no-renames', '-z', from, to])
if (added.length > 0) {
const ignored = await every(run, repo, ['check-ignore', '-z', '--stdin'], { stdin: added.join('\0') + '\0', okCodes: [0, 1] })
const blocked = []
for (let i = 0; i < ignored.length; i += PATHS_PER_CALL) {
blocked.push(...await every(run, repo, ['ls-files', '-z', '--others', '--ignored', '--exclude-standard', '--', ...ignored.slice(i, i + PATHS_PER_CALL).map(path => `:(literal)${path}`)]))
}
if (blocked.length > 0) throw new MoveBlocked(blocked)
}
const moved = await changes(run, repo, from, to)
await git(run, ['read-tree', '-m', '-u', from, to], { cwd: repo.top, env: indexEnv(repo) })
return moved
}
export async function pin (run, repo, ref, commit) {
await git(run, ['update-ref', ref, commit], { cwd: repo.top })
}
export async function drop (run, repo, ref) {
await run(['git', 'update-ref', '-d', ref], { cwd: repo.top })
}
export async function prune (run, repo, now, maxAgeMs) {
const list = await git(run, ['for-each-ref', '--format=%(refname) %(committerdate:unix)', REF_ROOT], { cwd: repo.top })
const old = list.split('\n').filter(Boolean).map(line => line.split(' ')).filter(([, seconds]) => now - Number(seconds) * 1000 > maxAgeMs)
if (old.length > 0) await git(run, ['update-ref', '--stdin'], { cwd: repo.top, stdin: old.map(([ref]) => `delete ${ref}\n`).join('') })
return old.length
}
src/runner.js
import { spawn } from 'node:child_process'
const MAX_STDOUT = 4 * 1024 * 1024
/**
* Matches the `run(argv, init)` contract expected by better-claude's `src/git.js`.
*/
export function run (argv, init = {}) {
return new Promise((resolve) => {
const [cmd, ...args] = argv
const child = spawn(cmd, args, {
cwd: init.cwd,
env: init.env ? { ...process.env, ...init.env } : process.env,
stdio: ['pipe', 'pipe', 'pipe']
})
const outChunks = []
let outLen = 0
let isStdoutTruncated = false
const errChunks = []
child.stdout.on('data', (chunk) => {
if (outLen < MAX_STDOUT) {
const remaining = MAX_STDOUT - outLen
if (chunk.length <= remaining) {
outChunks.push(chunk)
outLen += chunk.length
} else {
outChunks.push(chunk.subarray(0, remaining))
outLen = MAX_STDOUT
isStdoutTruncated = true
}
} else {
isStdoutTruncated = true
}
})
child.stderr.on('data', (chunk) => {
if (errChunks.length < 64) errChunks.push(chunk)
})
let timer = null
if (init.timeoutMs) {
timer = setTimeout(() => {
try { child.kill('SIGKILL') } catch {}
}, init.timeoutMs)
}
child.on('error', (err) => {
if (timer) clearTimeout(timer)
resolve({ exitCode: 127, stdout: '', stderr: err.message, isStdoutTruncated: false })
})
child.on('close', (code) => {
if (timer) clearTimeout(timer)
resolve({
exitCode: code ?? 1,
stdout: Buffer.concat(outChunks).toString('utf8'),
stderr: Buffer.concat(errChunks).toString('utf8'),
isStdoutTruncated
})
})
if (init.stdin !== undefined) {
child.stdin.end(init.stdin)
} else {
child.stdin.end()
}
})
}
src/states.js
export function lineOf (states, cursor) {
const line = new Set()
if (cursor === null) return line
const parentOf = new Map()
for (const state of states) parentOf.set(state.id, state.parent)
let id = cursor
while (id !== null && !line.has(id)) {
line.add(id)
id = parentOf.get(id) ?? null
}
return line
}
export const nextId = states => states.reduce((max, state) => Math.max(max, state.id), 0) + 1
export function merge (saved, live) {
const byCommit = new Map()
for (const state of [...saved, ...live]) byCommit.set(state.commit, state)
const merged = [...byCommit.values()].sort((a, b) => a.at - b.at || a.id - b.id)
let max = nextId(merged) - 1
const firstById = new Map()
const repaired = []
const states = merged.map(state => {
const first = firstById.get(state.id)
if (!first) {
firstById.set(state.id, state)
return state
}
const moved = { ...state, id: ++max }
repaired.push(moved, first)
return moved
})
return { states, repaired }
}
src/store.js
import fs from 'node:fs'
import path from 'node:path'
import os from 'node:os'
export const DATA_DIR = process.env.PLUGIN_DATA || path.join(os.homedir(), '.gemini', 'antigravity-cli', 'plugin_data', 'time-machine')
export const MAX_AGE_DAYS = 7
function safeId (id) {
return (id || 'default').replace(/[^a-zA-Z0-9._-]/g, '_')
}
export function stateFile (sessionId) {
return path.join(DATA_DIR, `session-${safeId(sessionId)}.json`)
}
export function loadSession (sessionId) {
try {
return JSON.parse(fs.readFileSync(stateFile(sessionId), 'utf8'))
} catch {
return {
sessionId,
repoTop: null,
states: [],
cursor: null,
jumpedFrom: null,
turnBefore: null,
lastAgentTree: null,
jumpedSinceLastTurn: false,
prunedAt: 0
}
}
}
export function saveSession (sessionId, data) {
fs.mkdirSync(DATA_DIR, { recursive: true })
fs.writeFileSync(stateFile(sessionId), JSON.stringify(data, null, 2))
}
export function listSessionsForRepo (repoTop) {
try {
const files = fs.readdirSync(DATA_DIR).filter(f => f.startsWith('session-') && f.endsWith('.json'))
const sessions = []
for (const f of files) {
try {
const s = JSON.parse(fs.readFileSync(path.join(DATA_DIR, f), 'utf8'))
if (!repoTop || s.repoTop === repoTop) sessions.push(s)
} catch {}
}
return sessions.sort((a, b) => {
const aLast = a.states?.at(-1)?.at ?? 0
const bLast = b.states?.at(-1)?.at ?? 0
return bLast - aLast
})
} catch {
return []
}
}