File size: 8,787 Bytes
0110783
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
#!/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,
};