nomad / scripts /session-stop.js
LucioLiu's picture
Initial release - mirrors github.com/LucioLiu/nomad
0110783 verified
Raw
History Blame Contribute Delete
8.79 kB
#!/usr/bin/env node
/**
* session-stop.js — Nomad Stop hook (portable port of production
* `hooks-core/flush-reminder-core.js`, parameterized per team-skeleton.md §3/§5).
*
* Reminds the agent to flush its progress (own memory files + team log) at
* close-out, in a way that is safe against looping — per-session state file
* tracks (transcript byte length, memory dir newest mtime) so it only reminds
* when there's plausible new, unflushed work.
*
* Same four-branch decide() logic as the production original:
* - no state file yet (first Stop this session) → remind
* - memory dir's newest mtime is newer than last recorded → memory was
* already updated since last check → don't remind, advance the baseline
* - otherwise: transcript grew by more than the threshold since the last
* baseline → remind, advance the baseline
* - otherwise → don't remind, leave the baseline untouched (keep accumulating)
*
* On remind=false this script emits nothing on stdout at all (no payload =
* let the session end) — same "silence means proceed" contract as the
* production original and as Cursor's followup_message being optional.
*
* Also releases the cross-session soft lock acquired by session-start.js
* (see lib/session-lock.js) — symmetric acquire/release, best-effort, never
* blocks close-out if it fails.
*
* Usage: node session-stop.js [--platform claude|codex|cursor]
* stdin: hook input JSON (session_id/cwd/transcript_path). No session_id → proceed silently.
*/
'use strict';
const fs = require('fs');
const path = require('path');
const os = require('os');
const emit = require('./lib/emit');
const cfg = require('./lib/config');
const sessionLock = require('./lib/session-lock');
const messages = require('./lib/messages');
const STALE_THRESHOLD_BYTES = 9000;
const STATE_FILE_PREFIX = 'nomad_stop_';
/**
* Recursively find the newest mtimeMs among all files under dirPath. Returns 0
* if the directory is missing/empty. Never throws.
* Rounds down with Math.floor — Node's fs.Stats.mtimeMs often carries a
* sub-millisecond fraction; if stored as-is in the state file and read back
* with parseInt, the fraction gets truncated and "current mtime (with
* fraction) > last-recorded (truncated)" becomes permanently true, falsely
* reading as "memory was just updated" on every check (a real bug the
* production port hit and fixed — millisecond precision is all this needs).
*/
function newestMtimeMs(dirPath) {
let newest = 0;
function walk(dir) {
let entries;
try {
entries = fs.readdirSync(dir, { withFileTypes: true });
} catch (e) {
return;
}
for (const ent of entries) {
const full = path.join(dir, ent.name);
try {
if (ent.isDirectory()) {
walk(full);
} else if (ent.isFile()) {
const mt = Math.floor(fs.statSync(full).mtimeMs);
if (mt > newest) newest = mt;
}
} catch (e) {
/* one bad entry shouldn't sink the rest */
}
}
}
try {
if (fs.existsSync(dirPath)) walk(dirPath);
} catch (e) {
/* ignore */
}
return newest;
}
function fileSizeBytes(filePath) {
try {
if (filePath && fs.existsSync(filePath)) return fs.statSync(filePath).size;
} catch (e) {
/* ignore */
}
return 0;
}
/**
* Core decision logic (pure function — no filesystem access, directly unit-testable).
* @param {{exists:boolean,lastT:number,lastM:number}} prevState
* @param {number} tlen current transcript byte size
* @param {number} memNewest current memory dir newest mtimeMs
* @returns {{remind:boolean,newT:number,newM:number}}
*/
function decide(prevState, tlen, memNewest) {
if (!prevState.exists) {
return { remind: true, newT: tlen, newM: memNewest };
}
const lastT = prevState.lastT || 0;
const lastM = prevState.lastM || 0;
if (memNewest > lastM) {
return { remind: false, newT: tlen, newM: memNewest };
}
if (tlen - lastT > STALE_THRESHOLD_BYTES) {
return { remind: true, newT: tlen, newM: memNewest };
}
return { remind: false, newT: lastT, newM: lastM };
}
function readPrevState(stateFile) {
if (!fs.existsSync(stateFile)) return { exists: false, lastT: 0, lastM: 0 };
try {
const raw = fs.readFileSync(stateFile, 'utf8');
const parts = raw.split('|');
const lastT = parts.length >= 1 ? parseInt(parts[0], 10) : NaN;
const lastM = parts.length >= 2 ? parseInt(parts[1], 10) : NaN;
return { exists: true, lastT: Number.isFinite(lastT) ? lastT : 0, lastM: Number.isFinite(lastM) ? lastM : 0 };
} catch (e) {
return { exists: false, lastT: 0, lastM: 0 };
}
}
function writeState(stateFile, newT, newM) {
fs.writeFileSync(stateFile, String(newT) + '|' + String(newM), 'utf8');
}
/** Build the append-log.js CLI hint shown in the reminder text, resolved against this team's actual team_log path. */
function buildAppendLogHint(teamRoot, config) {
const appendLogScript = path.join(__dirname, 'append-log.js');
const teamLogPath = cfg.resolveSharedPath(teamRoot, config, 'team_log');
const target = teamLogPath || '<team_log path from team-config.json shared_paths.team_log>';
return 'node "' + appendLogScript + '" "- <your entry>" --target "' + target + '"';
}
async function main() {
const platform = emit.getPlatform();
try {
const raw = await emit.readStdin();
let j = {};
try {
j = raw && raw.trim() ? JSON.parse(raw) : {};
} catch (e) {
j = {};
}
const sid = typeof j.session_id === 'string' ? j.session_id : '';
if (!sid) {
process.exit(0);
return;
}
if (emit.isDuplicateInvocation('Stop', sid)) {
process.exit(0);
return;
}
const cwd = emit.resolveCwd(raw, platform);
const tp = typeof j.transcript_path === 'string' ? j.transcript_path : '';
const agentHome = cfg.resolveAgentHome(cwd);
const memDir = agentHome ? cfg.firstExisting(agentHome, ['记忆', 'memory']) : null;
const memNewest = memDir ? newestMtimeMs(memDir) : 0;
const tlen = fileSizeBytes(tp);
const key = sid.replace(/[^A-Za-z0-9]/g, '');
const stateFile = path.join(os.tmpdir(), STATE_FILE_PREFIX + key + '.txt');
const prevState = readPrevState(stateFile);
const result = decide(prevState, tlen, memNewest);
// writeState was the ONE bare filesystem write left in main() — every other
// write call in this file already carries its own try/catch. If it threw
// (tmpdir unwritable, disk full, EPERM under a locked-down profile), control
// jumped straight to the outer catch and the `sessionLock.release()` below
// was skipped — leaving `.session_lock.json` behind, so every subsequent
// start falsely reported "another session is already running". The state
// file is a best-effort reminder heuristic; failing to persist it must never
// cost the lock release, which is the part with cross-session consequences.
try {
writeState(stateFile, result.newT, result.newM);
} catch (e) {
process.stderr.write('[session-stop] could not persist reminder state (non-fatal, ' +
'lock release continues): ' + ((e && e.message) || e) + '\n');
}
if (result.remind) {
const teamRoot = cfg.resolveTeamRoot(cwd || process.cwd());
const config = cfg.loadTeamConfig(teamRoot);
const lang = cfg.resolveLanguage(config);
const msg = messages.get(lang);
const reason = msg.stopReason(buildAppendLogHint(teamRoot, config));
emit.writeJson(emit.buildStopBlockPayload(reason, platform));
}
// remind=false: emit nothing (matches production original — silence = proceed).
if (agentHome) {
try {
sessionLock.release(agentHome);
} catch (e) {
/* best-effort — never block close-out on lock release failure */
}
}
} catch (e) {
// Never block close-out: emit nothing on stdout (silence = proceed). But
// surface an unexpected exception on stderr instead of swallowing it
// silently — stderr does not affect the "silence means let the session end"
// contract, it just gives an operator a trace when something genuinely broke.
process.stderr.write('[session-stop] non-fatal error, no reminder emitted (close-out not blocked): ' + ((e && e.stack) || e) + '\n');
}
process.exit(0);
}
if (require.main === module) {
main();
}
module.exports = {
decide,
newestMtimeMs,
fileSizeBytes,
readPrevState,
writeState,
buildAppendLogHint,
STALE_THRESHOLD_BYTES,
};