Something went wrong. Try again.
Something went wrong. Try again.
coding_club watch.mjs
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227#!/usr/bin/env node// Watch a pi session (JSONL in the repo) and git-commit each turn.//// A turn is a work unit: the user/assistant exchanges since the last commit are// buffered, and when the working tree changes (the agent edited files) the turn// closes — the whole tree, including the growing session JSONL, is committed.// The JSONL file IS the conversation record; git history is the record of the// work. Chat with no file changes closes on idle timeout so it is not lost.//// Sessions live in <repo>/data/pi/sessions/ (the pi backend writes there via// --session-dir). Each file is named <timestamp>_<sessionId>.jsonl. The watch// follows the newest file for the repo's session id and reads appended lines.//// State (last processed line + the open exchange buffer) lives in// .club-state.json, gitignored, so a restart neither re-records nor loses// in-progress exchanges.//// Usage:// node watch.mjs # watch the repo in cwd (pi JSONL source)// node watch.mjs --dry-run # show what it would do, change nothing// node watch.mjs --session-dir DIR # where pi writes session JSONL// node watch.mjs --author-did did:plc:xyz # explicit turn author (DID)import { execFileSync } from "node:child_process";import { existsSync, readFileSync, readdirSync, statSync, writeFileSync } from "node:fs";import { join } from "node:path";
const STATE_FILE = ".club-state.json";
function parseArgs(argv) { const args = { repo: process.cwd(), sessionDir: null, sessionId: null, interval: 3.0, idleTimeout: 45.0, dryRun: false, authorDid: null, help: false, }; for (let i = 0; i < argv.length; i++) { const a = argv[i]; const next = () => argv[++i]; if (a === "--repo") args.repo = next(); else if (a === "--session-dir") args.sessionDir = next(); else if (a === "--session-id") args.sessionId = next(); else if (a === "--interval") args.interval = parseFloat(next()); else if (a === "--idle-timeout") args.idleTimeout = parseFloat(next()); else if (a === "--author-did") args.authorDid = next(); else if (a === "--dry-run") args.dryRun = true; else if (a === "--help") args.help = true; } args.sessionDir = args.sessionDir ?? join(args.repo, "data", "pi", "sessions"); args.sessionId = args.sessionId ?? process.env.PI_SESSION_ID ?? "pi-collab"; return args;}
// ---- git -------------------------------------------------------------------
function git(repo, ...cmd) { try { return { ok: true, out: execFileSync("git", ["-C", repo, ...cmd], { encoding: "utf8" }) }; } catch (err) { return { ok: false, out: err.stdout ?? "" }; }}
function gitDirty(repo) { return Boolean(git(repo, "status", "--porcelain").out.trim());}
function gitCommit(repo, message) { git(repo, "add", "-A"); const res = git(repo, "commit", "-q", "-m", message); return res.ok;}
// ---- pi session JSONL -------------------------------------------------------
function sessionFiles(sessionDir) { try { return readdirSync(sessionDir) .filter((n) => n.endsWith(".jsonl")) .sort((a, b) => statSync(join(sessionDir, a)).mtimeMs - statSync(join(sessionDir, b)).mtimeMs); } catch { return []; }}
function activeSessionFile(sessionDir, sessionId) { const files = sessionFiles(sessionDir); const matching = files.filter((n) => n.endsWith(`_${sessionId}.jsonl`)); const pool = matching.length ? matching : files; if (!pool.length) return null; return join(sessionDir, pool[pool.length - 1]);}
function readMessagesFrom(sessionFile, fromLine) { // Returns { messages, lastLine } — new message entries at or after fromLine. try { const lines = readFileSync(sessionFile, "utf8").split("\n"); const out = []; let last = fromLine; for (let i = fromLine; i < lines.length; i++) { const line = lines[i].trim(); if (!line) continue; last = i + 1; try { const entry = JSON.parse(line); if (entry.type === "message") out.push(entry); } catch { /* partial tail line, skip */ } } return { messages: out, lastLine: last }; } catch { return { messages: [], lastLine: fromLine }; }}
function textOf(content) { return (content ?? []) .filter((c) => c.type === "text") .map((c) => c.text ?? "") .join("\n");}
function buildExchange(messages) { // Pair each user message with the assistant reply that follows it. const out = []; let curUser = null; let curAsst = ""; for (const m of messages) { const role = m.message?.role; const text = textOf(m.message?.content); if (role === "user") { if (curUser !== null || curAsst) out.push({ user: curUser ?? "", assistant: curAsst }); curUser = text; curAsst = ""; } else if (role === "assistant") { curAsst += text; } } if (curUser !== null || curAsst) out.push({ user: curUser ?? "", assistant: curAsst }); return out;}
// ---- main loop -------------------------------------------------------------
function main() { const args = parseArgs(process.argv.slice(2)); if (args.help) { console.log(`Usage: node watch.mjs [options] --repo PATH repo to watch (default: cwd) --session-dir DIR where pi writes session JSONL (default: <repo>/data/pi/sessions) --session-id ID session id to follow (default: pi-collab) --interval SEC poll interval (default 3.0) --idle-timeout SEC close a chat-only turn after this many seconds (default 45; 0 disables) --author-did DID explicit DID for turn attribution (CLUB_AUTHOR_DID env fallback) --dry-run show what it would do, change nothing`); return; }
const repo = args.repo; const statePath = join(repo, STATE_FILE); const state = existsSync(statePath) ? JSON.parse(readFileSync(statePath, "utf8")) : {};
console.log(`watching pi session in ${repo} (${args.sessionDir}, session ${args.sessionId})`); if (args.dryRun) console.log("dry-run: no commits");
const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); const loop = async () => { for (;;) { try { const sessionFile = activeSessionFile(args.sessionDir, args.sessionId); if (!sessionFile) { console.log("no pi session jsonl yet"); } else { const info = state[sessionFile] ?? (state[sessionFile] = { lastLine: 0, buffer: [], lastActivity: 0 }); const { messages, lastLine } = readMessagesFrom(sessionFile, info.lastLine); info.lastLine = lastLine; if (messages.length) { const fresh = buildExchange(messages); info.buffer.push(...fresh); info.lastActivity = Date.now(); console.log(` buffered ${fresh.length} exchange(s) (${info.buffer.length} in turn)`); }
const dirty = gitDirty(repo); const idleSecs = info.buffer.length && info.lastActivity ? (Date.now() - info.lastActivity) / 1000 : 0; const closeForFile = info.buffer.length && dirty; const closeForIdle = args.idleTimeout > 0 && info.buffer.length && idleSecs >= args.idleTimeout;
if (closeForFile || closeForIdle) { const reason = closeForFile ? "file change" : `idle ${idleSecs.toFixed(0)}s`; const author = args.authorDid || process.env.CLUB_AUTHOR_DID || ""; console.log(`\n[turn] ${reason} — closing the record (${info.buffer.length} exchange(s))`); for (const e of info.buffer) { console.log(` user: ${e.user.slice(0, 80)}`); console.log(` assistant: ${e.assistant.slice(0, 80)}`); } if (args.dryRun) { console.log(" [dry-run] would commit the working tree"); } else { const ts = new Date().toISOString(); const authorTag = author ? ` [${author}]` : ""; const sid = sessionFile.split("/").pop()?.replace(/\.jsonl$/, ""); const message = `turn ${sid}${authorTag} (${info.buffer.length} exchange(s)) ${ts}`; const committed = gitCommit(repo, message); console.log(` commit: ${committed ? "ok" : "clean or failed"} ${message}`); } info.buffer = []; info.lastActivity = 0; } writeFileSync(statePath, JSON.stringify(state, null, 2)); } } catch (e) { console.log(`watch error: ${e.message}`); } await sleep(args.interval * 1000); } }; loop();}
main();