File size: 9,034 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
229
'use strict';
/**

 * emit.js — hook I/O wrapper shared by session-start.js / session-stop.js / precompact.js.

 *

 * Ported from a production hooks-core module, deployed at `91-team-tools/hooks-core/emit.js`, desensitized.

 * One deliberate simplification versus the production version: this port covers

 * `claude` and `codex` (byte-for-byte identical stdin/stdout schema for the three

 * hook events used here) plus a best-effort `cursor` branch, since those are the

 * two harnesses named in this batch's brief. The switch-per-event structure is

 * kept exactly as the production version so adding another harness later means

 * touching only this one file, never the three hook scripts.

 *

 * Output discipline: UTF-8, no BOM, one JSON object per line, trailing newline —

 * matches what a hook host reading stdout line-by-line expects.

 */

const SUPPORTED_PLATFORMS = ['claude', 'codex', 'cursor'];

function normalizePlatform(p) {
  p = String(p || '').trim().toLowerCase();
  return SUPPORTED_PLATFORMS.includes(p) ? p : 'claude';
}

/** Read `--platform <name>` or `--platform=<name>` from argv; default 'claude'. */
function getPlatform(argv) {
  argv = argv || process.argv.slice(2);
  const idx = argv.indexOf('--platform');
  if (idx >= 0 && argv[idx + 1]) return normalizePlatform(argv[idx + 1]);
  const eq = argv.find((a) => a.startsWith('--platform='));
  if (eq) return normalizePlatform(eq.split('=').slice(1).join('='));
  return 'claude';
}

/** SessionStart event: inject additional context. */
function buildSessionStartPayload(additionalContext, platform) {
  switch (normalizePlatform(platform)) {
    case 'cursor':
      // Cursor's `sessionStart` hook takes a top-level snake_case `additional_context`
      // field, no hookSpecificOutput wrapper. Best-effort — not independently
      // verified against a real Cursor install by this batch; see README.md.
      return { additional_context: additionalContext };
    case 'codex':
    case 'claude':
    default:
      return { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: additionalContext } };
  }
}

/** Stop event: emitting nothing at all means "let the session end" — callers should not print when remind=false. */
function buildStopBlockPayload(reason, platform) {
  switch (normalizePlatform(platform)) {
    case 'cursor':
      // Cursor's `stop` hook has no decision:block mechanism, only an optional
      // `followup_message` (re-injected as a follow-up turn). Close enough in
      // effect to "the reminder text reaches the session" — not identical semantics.
      return { followup_message: reason };
    case 'codex':
    case 'claude':
    default:
      return { decision: 'block', reason: reason };
  }
}

/** PreCompact event: only the top-level systemMessage field is honored by claude/codex — no hookSpecificOutput here. */
function buildPreCompactPayload(systemMessage, platform) {
  switch (normalizePlatform(platform)) {
    case 'cursor':
      return { user_message: systemMessage };
    case 'codex':
    case 'claude':
    default:
      return { systemMessage: systemMessage };
  }
}

/** Serialize payload as single-line JSON to stdout, UTF-8 no BOM, trailing newline. */
function writeJson(payload) {
  process.stdout.write(JSON.stringify(payload) + '\n');
}

/**

 * Read all of stdin as a UTF-8 string (Promise). No timeout — a real hook host

 * closes stdin (EOF) after sending its payload; running this file directly in

 * an interactive terminal with no redirection will hang waiting for input,

 * which is expected (pipe in `echo ... |` or `printf '' |` for manual testing).

 */
function readStdin() {
  return new Promise((resolve) => {
    let data = '';
    try {
      process.stdin.setEncoding('utf8');
    } catch (e) {
      /* ignore */
    }
    process.stdin.on('data', (chunk) => {
      data += chunk;
    });
    process.stdin.on('end', () => resolve(data));
    process.stdin.on('error', () => resolve(data));
  });
}

/** Rough mojibake detector — looks for the Unicode replacement character U+FFFD. */
function looksMojibake(s) {
  return typeof s === 'string' && s.indexOf('�') !== -1;
}

/**

 * Unified cwd resolution, shared by session-start.js / session-stop.js.

 * Priority: ① stdin JSON's `cwd` field (not mojibake-damaged) → ② `process.cwd()`

 * (the hook subprocess's own working directory, set by the OS directly, not routed

 * through any text transcoding — usually equivalent to ① anyway) → ③ cursor-only

 * fallback to stdin's `workspace_roots[0]` (must be pure ASCII and undamaged —

 * non-ASCII workspace_roots are not trusted on Cursor, see production hooks-core's

 * documented finding of a UTF-8-decoded-as-GBK corruption case) → '' if nothing works.

 * @param {string} raw stdin raw text

 * @param {string} platform claude|codex|cursor

 * @param {Function} [pcwdFn] injectable process.cwd stand-in for tests

 */
function resolveCwd(raw, platform, pcwdFn) {
  pcwdFn = pcwdFn || process.cwd;
  let j = null;
  try {
    j = raw && raw.trim() ? JSON.parse(raw) : null;
  } catch (e) {
    j = null;
  }

  const stdinCwd = j && typeof j.cwd === 'string' ? j.cwd : '';
  if (stdinCwd && !looksMojibake(stdinCwd)) return stdinCwd;

  let pcwd = '';
  try {
    pcwd = pcwdFn() || '';
  } catch (e) {
    pcwd = '';
  }
  if (pcwd && !looksMojibake(pcwd)) return pcwd;

  if (normalizePlatform(platform) === 'cursor') {
    try {
      const root = j && Array.isArray(j.workspace_roots) ? j.workspace_roots[0] : '';
      if (root && /^[\x00-\x7F]+$/.test(root) && !looksMojibake(root)) {
        // Only rewrite a POSIX-style Windows drive path (/D:/foo -> D:\foo).
        // A genuine POSIX path (/home/user/...) has no drive-letter prefix and
        // must be returned untouched — unconditionally turning every '/' into
        // '\' (the previous behavior) would corrupt a real Mac/Linux path in
        // the low-probability case where a Cursor session on a POSIX host falls
        // through both earlier fallbacks to here. Gate the slash-flip on an
        // actual drive-letter match rather than doing it always.
        const winDrive = /^\/([A-Za-z]):/;
        if (winDrive.test(root)) return root.replace(winDrive, '$1:').replace(/\//g, '\\');
        return root;
      }
    } catch (e) {
      /* ignore */
    }
  }
  return '';
}

/** Safely extract session_id from raw stdin text. Never throws. */
function extractSessionId(raw) {
  try {
    if (!raw || !raw.trim()) return '';
    const j = JSON.parse(raw);
    return typeof j.session_id === 'string' ? j.session_id : '';
  } catch (e) {
    return '';
  }
}

/**

 * Double-fire dedup guard. Some harnesses (documented case: Claude Code's

 * project-level config lookup climbing to a repository root that also has its

 * own hooks config) can end up firing the same hook event twice for one

 * session. This gives callers a short-window idempotency check: same event +

 * same session_id within `windowMs` (default 5s) is treated as a duplicate.

 * No session_id means no dedup (would rather occasionally double-fire than

 * risk false-positively swallowing a legitimate single call).

 * @param {string} eventName e.g. 'SessionStart' | 'Stop' | 'PreCompact'

 * @param {string} sessionId

 * @param {{windowMs?: number}} [opts]

 * @returns {boolean} true = duplicate, caller should skip

 */
function isDuplicateInvocation(eventName, sessionId, opts) {
  if (!sessionId) return false;
  opts = opts || {};
  const windowMs = typeof opts.windowMs === 'number' ? opts.windowMs : 5000;
  const fs = require('fs');
  const os = require('os');
  const path = require('path');
  const key = String(eventName) + '_' + String(sessionId).replace(/[^A-Za-z0-9]/g, '');
  const markerFile = path.join(os.tmpdir(), 'nomad_dedupe_' + key + '.marker');
  const now = Date.now();
  try {
    fs.writeFileSync(markerFile, String(now), { flag: 'wx' });
    return false; // exclusive create succeeded — first arrival of this batch
  } catch (e) {
    if (e && e.code === 'EEXIST') {
      try {
        const raw = fs.readFileSync(markerFile, 'utf8');
        const ts = parseInt(raw, 10);
        if (Number.isFinite(ts) && now - ts < windowMs) return true; // within window = duplicate
        fs.writeFileSync(markerFile, String(now), 'utf8'); // stale marker — treat as new batch
        return false;
      } catch (e2) {
        return false; // read/overwrite failure — fail open
      }
    }
    return false; // any other write failure — fail open
  }
}

module.exports = {
  SUPPORTED_PLATFORMS,
  getPlatform,
  normalizePlatform,
  buildSessionStartPayload,
  buildStopBlockPayload,
  buildPreCompactPayload,
  writeJson,
  readStdin,
  looksMojibake,
  resolveCwd,
  extractSessionId,
  isDuplicateInvocation,
};