Files
pepa-pi-bot/runtime/state-store.js
T
cd14bbf89a feat(runtime): state persistence + proposals + supervisor hot-restart (#6)
Closes the self-improvement loop end-to-end:

  reflex fails 3× → proposal file → operator approves in TUI →
  `npm run propose:apply <file>` spawns Pi on a feature branch →
  Pi commits the patch → supervisor watches runtime/*.js and
  restarts the child on change.

runtime/state-store.js — atomic current-task.json writes, daily diary
  append, proposals/ + proposals/approved/ helpers.

runtime/bot.js:
  - ctx.dispatch writes current-task.json on start and updates it on
    completion / failure / throw.
  - failure tracker: 3 consecutive same-label failures → writeProposal()
    with the snapshot, labels, and a suggested-next-step section.
    30-min cooldown prevents proposal spam.
  - on startup, surfaces resume info (previous task + pending proposal
    count); on death, clears current-task.json + writes diary line.
  - new IPC commands: PROPOSAL_LATEST returns the newest pending
    proposal body; PROPOSAL_APPROVE moves it to proposals/approved/.

tui/tui.tsx — status bar shows `[proposals N, press y]` badge when
  bot.pendingProposals > 0. Hotkey 'y' opens the proposal panel; 'y'
  approves, 'n'/Esc closes.

scripts/propose-apply.js — given an approved proposal filename, creates
  a `feat/proposal-<slug>` branch and spawns `pi -p` with the proposal
  + repo-conventions prompt. Refuses on dirty tree. No auto-push, no
  auto-merge — operator reviews the diff and decides.

runtime/supervisor.js — forks bot.js as a child, watches runtime/*.js,
  restarts on file change or on child exit code 42. Rate-limited at 5
  restarts/minute. SIGINT/SIGTERM forward cleanly. `npm run bot` now
  goes through the supervisor; `npm run bot:bare` skips it.

Smoke-tested: supervisor spawned, bot connected to MC, spawned at
expected coords, diary line written, state cleanup on SIGTERM correct.

Co-authored-by: Yuriy Mayatnikov <mayatnikov@me.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 16:20:09 +03:00

139 lines
3.8 KiB
JavaScript

// Per-server state on disk. Two surfaces:
// - current-task.json — what action is in flight (or last finished).
// Used as the resume anchor across restarts. Atomically rewritten via
// write-rename to avoid torn reads.
// - diary/YYYY-MM-DD.md — append-only daily journal. One line per
// meaningful milestone (death, escalation, first attack on a new mob
// type, sleep success, etc.). The reflex layer decides what counts.
//
// All writes are sync — these files are tiny and per-tick at most.
import fs from "node:fs";
import path from "node:path";
import { stateDir } from "./config.js";
const CURRENT_TASK_PATH = path.join(stateDir, "current-task.json");
const DIARY_DIR = path.join(stateDir, "diary");
const PROPOSALS_DIR = path.join(stateDir, "proposals");
const PROPOSALS_APPROVED_DIR = path.join(PROPOSALS_DIR, "approved");
fs.mkdirSync(DIARY_DIR, { recursive: true });
fs.mkdirSync(PROPOSALS_DIR, { recursive: true });
fs.mkdirSync(PROPOSALS_APPROVED_DIR, { recursive: true });
// ---- current-task ----------------------------------------------------------
export function readCurrentTask() {
try {
const raw = fs.readFileSync(CURRENT_TASK_PATH, "utf8").trim();
if (!raw) return null;
return JSON.parse(raw);
} catch (e) {
if (e.code === "ENOENT") return null;
// corrupt file — treat as no task
return null;
}
}
function writeAtomic(filePath, content) {
const tmp = `${filePath}.tmp`;
fs.writeFileSync(tmp, content);
fs.renameSync(tmp, filePath);
}
export function writeCurrentTask(task) {
if (!task) {
clearCurrentTask();
return;
}
writeAtomic(
CURRENT_TASK_PATH,
JSON.stringify({ ts: new Date().toISOString(), ...task }, null, 2),
);
}
export function clearCurrentTask() {
try {
writeAtomic(CURRENT_TASK_PATH, "{}\n");
} catch (e) {
if (e.code !== "ENOENT") throw e;
}
}
// ---- diary -----------------------------------------------------------------
function diaryPath(date = new Date()) {
const stamp = date.toISOString().slice(0, 10);
return path.join(DIARY_DIR, `${stamp}.md`);
}
export function appendDiary(text) {
const stamp = new Date().toISOString().slice(11, 19);
const line = `${stamp} ${text}\n`;
fs.appendFileSync(diaryPath(), line);
}
// ---- proposals -------------------------------------------------------------
function slugify(s) {
return s
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 60);
}
export function writeProposal({ kind, summary, body }) {
const stamp = new Date().toISOString().replace(/[:.]/g, "-").slice(0, 19);
const filename = `${stamp}-${slugify(kind)}.md`;
const filePath = path.join(PROPOSALS_DIR, filename);
const content = [
"---",
`kind: ${kind}`,
`ts: ${new Date().toISOString()}`,
`summary: ${JSON.stringify(summary)}`,
"approved: false",
"---",
"",
body,
"",
].join("\n");
fs.writeFileSync(filePath, content);
return { filePath, filename };
}
export function listProposals({ approved = false } = {}) {
const dir = approved ? PROPOSALS_APPROVED_DIR : PROPOSALS_DIR;
try {
return fs
.readdirSync(dir)
.filter((f) => f.endsWith(".md"))
.sort();
} catch (e) {
if (e.code === "ENOENT") return [];
throw e;
}
}
export function readProposal(filename, { approved = false } = {}) {
const dir = approved ? PROPOSALS_APPROVED_DIR : PROPOSALS_DIR;
const filePath = path.join(dir, filename);
return fs.readFileSync(filePath, "utf8");
}
export function approveProposal(filename) {
const src = path.join(PROPOSALS_DIR, filename);
const dst = path.join(PROPOSALS_APPROVED_DIR, filename);
const content = fs.readFileSync(src, "utf8").replace(/^approved: false/m, "approved: true");
fs.writeFileSync(dst, content);
fs.unlinkSync(src);
return dst;
}
export const paths = Object.freeze({
currentTask: CURRENT_TASK_PATH,
diary: DIARY_DIR,
proposals: PROPOSALS_DIR,
proposalsApproved: PROPOSALS_APPROVED_DIR,
});