@radnine/claude-session-daemon 0.8.3 → 0.9.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -3,8 +3,16 @@
3
3
  const fs = require('node:fs').promises;
4
4
  const path = require('node:path');
5
5
  const matter = require('gray-matter');
6
+ const yaml = require('js-yaml');
6
7
 
7
8
  const PERSONA_SUBDIR = '.claude/personas';
9
+ const CREW_MAP_PATH = '.claude/crew.yml';
10
+ // Bounds on what one crew.yml can put in a heartbeat (and a system prompt).
11
+ const MAX_CREW_MAP_BYTES = 64 * 1024;
12
+ const MAX_CREW_ROLES = 200;
13
+ const MAX_TEXT_LENGTH = 500;
14
+ const MAX_VOICE_LENGTH = 4000;
15
+ const RANK_TITLES = { 1: 'Chief of Staff', 2: 'officer', 3: 'crew' };
8
16
 
9
17
  /**
10
18
  * Scan <workingDir>/.claude/personas/*.md and return parsed persona metadata.
@@ -165,4 +173,262 @@ async function readPersonaBody(workingDir, relativePath) {
165
173
  return body;
166
174
  }
167
175
 
168
- module.exports = { scanPersonas, readPersonaBody, PERSONA_SUBDIR };
176
+ /**
177
+ * Read <workingDir>/.claude/crew.yml, the repo's character map (crew ADR
178
+ * §1.2, CREW-3 #181), in the heartbeat's shape. CREW-2 #180's fixture
179
+ * spec/fixtures/files/crew_map/heartbeat.json is the contract:
180
+ *
181
+ * { path, area, universe, crew: { <slug>: { name, rank, reports_to, avatar_url, voice } }, error: null }
182
+ *
183
+ * Every crew entry carries all five keys; one the YAML leaves out is null.
184
+ * Text values pass through as written, and a rank may be any number or
185
+ * string (a rank of "high" stays "high"), because FlightDeck validates the
186
+ * map and shows the problems on the crew page.
187
+ *
188
+ * Only text is sent. The file is capped at MAX_CREW_MAP_BYTES, and a value
189
+ * that isn't a string (or a number) is dropped to null, so a YAML alias
190
+ * can't expand a small file into a huge heartbeat. A voice may also be a
191
+ * list of strings, sent joined by newlines. Each dropped value adds a line
192
+ * to `warnings`, a key the map carries only when there is one.
193
+ *
194
+ * Never throws:
195
+ * - no file (or no workingDir) => null, and the heartbeat carries no crew_map
196
+ * - a file that won't read or parse, or is too large => { path, error: "<message>" }
197
+ *
198
+ * @param {string} workingDir
199
+ * @param {object} [opts]
200
+ * @param {{warn: function}} [opts.logger]
201
+ * @returns {Promise<object|null>}
202
+ */
203
+ async function scanCrewMap(workingDir, opts = {}) {
204
+ if (!workingDir) return null;
205
+ const logger = opts.logger;
206
+ const filePath = path.join(workingDir, CREW_MAP_PATH);
207
+
208
+ let raw;
209
+ try {
210
+ const stat = await fs.stat(filePath);
211
+ if (stat.size > MAX_CREW_MAP_BYTES) return _crewMapError(_tooLarge(stat.size), logger);
212
+ raw = await fs.readFile(filePath, 'utf8');
213
+ } catch (err) {
214
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return null;
215
+ return _crewMapError(`can't be read: ${err.message}`, logger);
216
+ }
217
+ // The file may have grown between the stat and the read.
218
+ if (Buffer.byteLength(raw) > MAX_CREW_MAP_BYTES) return _crewMapError(_tooLarge(Buffer.byteLength(raw)), logger);
219
+
220
+ let doc;
221
+ try {
222
+ doc = yaml.load(raw, { filename: CREW_MAP_PATH });
223
+ } catch (err) {
224
+ // One line for the crew page; js-yaml's message also quotes the file.
225
+ const where = err.mark ? ` at line ${err.mark.line + 1}, column ${err.mark.column + 1}` : '';
226
+ return _crewMapError(`${err.reason || err.message}${where}`, logger);
227
+ }
228
+ if (!_isPlainObject(doc)) {
229
+ return _crewMapError(doc == null ? 'the file is empty' : 'the top level must be a map with area, universe and crew', logger);
230
+ }
231
+
232
+ const warnings = [];
233
+ const crewMap = {
234
+ path: CREW_MAP_PATH,
235
+ area: _text(doc.area, 'area', MAX_TEXT_LENGTH, warnings),
236
+ universe: _text(doc.universe, 'universe', MAX_TEXT_LENGTH, warnings),
237
+ crew: _crew(doc.crew, warnings),
238
+ error: null,
239
+ };
240
+ if (warnings.length > 0) {
241
+ crewMap.warnings = warnings;
242
+ if (logger) logger.warn(`Crew map ${CREW_MAP_PATH}: ${warnings.join('; ')}`);
243
+ }
244
+ return crewMap;
245
+ }
246
+
247
+ function _crew(crew, warnings) {
248
+ if (crew === undefined || crew === null) return null;
249
+ if (!_isPlainObject(crew)) {
250
+ // Not null, so FlightDeck says the map has no crew: section.
251
+ warnings.push('crew: must be a map of roles, so no role is sent');
252
+ return [];
253
+ }
254
+ const entries = Object.entries(crew);
255
+ if (entries.length > MAX_CREW_ROLES) {
256
+ warnings.push(`crew: has ${entries.length} roles; only the first ${MAX_CREW_ROLES} are sent`);
257
+ }
258
+ return Object.fromEntries(entries.slice(0, MAX_CREW_ROLES).map(([slug, entry]) => [slug, _crewEntry(slug, entry, warnings)]));
259
+ }
260
+
261
+ function _crewEntry(slug, entry, warnings) {
262
+ if (!_isPlainObject(entry)) {
263
+ // null reaches FlightDeck as "its entry isn't a map".
264
+ if (entry !== undefined && entry !== null) warnings.push(`${slug}: its entry must be a map, so it is dropped`);
265
+ return null;
266
+ }
267
+ return {
268
+ name: _text(entry.name, `${slug}.name`, MAX_TEXT_LENGTH, warnings),
269
+ rank: _rank(entry.rank, `${slug}.rank`, warnings),
270
+ reports_to: _text(entry.reports_to, `${slug}.reports_to`, MAX_TEXT_LENGTH, warnings),
271
+ avatar_url: _text(entry.avatar_url, `${slug}.avatar_url`, MAX_TEXT_LENGTH, warnings),
272
+ voice: _voice(entry.voice, `${slug}.voice`, warnings),
273
+ };
274
+ }
275
+
276
+ // A string, or a number sent as its text. Anything else, or text over the
277
+ // cap, is null with a warning.
278
+ function _text(v, label, maxLength, warnings) {
279
+ if (v === undefined || v === null) return null;
280
+ if (typeof v === 'number' && Number.isFinite(v)) v = String(v);
281
+ if (typeof v !== 'string') {
282
+ warnings.push(`${label} must be text, so it is dropped`);
283
+ return null;
284
+ }
285
+ if (v.length > maxLength) {
286
+ warnings.push(`${label} is longer than ${maxLength} characters, so it is dropped`);
287
+ return null;
288
+ }
289
+ return v.length > 0 ? v : null;
290
+ }
291
+
292
+ // Numbers pass as numbers (the fixture sends rank: 1); a string passes for
293
+ // FlightDeck to judge.
294
+ function _rank(v, label, warnings) {
295
+ if (typeof v === 'number' && Number.isFinite(v)) return v;
296
+ return _text(v, label, MAX_TEXT_LENGTH, warnings);
297
+ }
298
+
299
+ function _voice(v, label, warnings) {
300
+ if (Array.isArray(v)) {
301
+ if (!v.every((line) => typeof line === 'string')) {
302
+ warnings.push(`${label} must be text or a list of text, so it is dropped`);
303
+ return null;
304
+ }
305
+ // Each line may be an alias to the same long string: count before joining.
306
+ const length = v.reduce((sum, line) => sum + line.length + 1, 0);
307
+ if (length > MAX_VOICE_LENGTH) {
308
+ warnings.push(`${label} is longer than ${MAX_VOICE_LENGTH} characters, so it is dropped`);
309
+ return null;
310
+ }
311
+ v = v.join('\n');
312
+ }
313
+ return _text(v, label, MAX_VOICE_LENGTH, warnings);
314
+ }
315
+
316
+ function _tooLarge(bytes) {
317
+ return `the file is too large (${bytes} bytes; the limit is ${MAX_CREW_MAP_BYTES})`;
318
+ }
319
+
320
+ function _crewMapError(message, logger) {
321
+ if (logger) logger.warn(`Crew map ${CREW_MAP_PATH} not usable: ${message}`);
322
+ return { path: CREW_MAP_PATH, error: message };
323
+ }
324
+
325
+ function _isPlainObject(v) {
326
+ return v !== null && typeof v === 'object' && !Array.isArray(v) && !(v instanceof Date);
327
+ }
328
+
329
+ /**
330
+ * The persona slug a system_prompt_path names, e.g.
331
+ * `.claude/personas/engagement-manager.md` => `engagement-manager`.
332
+ * Anything else (a path outside .claude/personas, not a .md) => null.
333
+ */
334
+ function personaSlugFromPath(relativePath) {
335
+ if (typeof relativePath !== 'string') return null;
336
+ const normalized = path.posix.normalize(relativePath.split(path.sep).join('/'));
337
+ if (path.posix.dirname(normalized) !== PERSONA_SUBDIR) return null;
338
+ const base = path.posix.basename(normalized);
339
+ return base.endsWith('.md') ? base.slice(0, -3) : null;
340
+ }
341
+
342
+ /**
343
+ * The identity header the daemon puts before a persona's system prompt at
344
+ * spawn (crew ADR §1.3): character name, universe, rank, the superior's
345
+ * character name, and the voice block. Returns null when the map has no
346
+ * usable entry for the slug, so the prompt stays exactly as it is today.
347
+ *
348
+ * The superior: `reports_to`'s character in this map; for a rank-2 role
349
+ * with no reports_to, this map's rank-1 role, or else "your area's Chief
350
+ * of Staff" (who may live in another repo); rank 1 names no superior.
351
+ *
352
+ * @param {object|null} crewMap - scanCrewMap's result
353
+ * @param {string|null} slug
354
+ * @returns {string|null}
355
+ */
356
+ function buildCrewHeader(crewMap, slug) {
357
+ if (!crewMap || crewMap.error || !slug || !_isPlainObject(crewMap.crew)) return null;
358
+ const entry = crewMap.crew[slug];
359
+ if (!_isPlainObject(entry)) return null;
360
+ const name = _textOrNull(entry.name);
361
+ if (!name) return null;
362
+
363
+ const rank = _rankOrDefault(entry.rank);
364
+ const universe = _textOrNull(crewMap.universe);
365
+ const lines = ['# Your crew identity', ''];
366
+ lines.push(`You are ${name}${universe ? ` (${universe})` : ''}. Your role in this repo is ${_oneLine(slug)}.`);
367
+ lines.push(`Rank: ${rank} (${RANK_TITLES[rank]}).`);
368
+
369
+ const superior = _superiorName(crewMap.crew, slug, entry, rank);
370
+ if (superior) lines.push(`You report to ${superior}.`);
371
+
372
+ const voice = _voiceNotes(entry.voice);
373
+ if (voice) lines.push('', VOICE_OPEN, voice, VOICE_CLOSE);
374
+
375
+ return lines.join('\n') + '\n\n';
376
+ }
377
+
378
+ function _superiorName(crew, slug, entry, rank) {
379
+ const reportsTo = _textOrNull(entry.reports_to);
380
+ if (reportsTo) {
381
+ const superior = crew[reportsTo];
382
+ return (_isPlainObject(superior) && _textOrNull(superior.name)) || reportsTo;
383
+ }
384
+ if (rank === 1) return null;
385
+ for (const [otherSlug, other] of Object.entries(crew)) {
386
+ if (otherSlug !== slug && _isPlainObject(other) && _rankOrDefault(other.rank) === 1 && _textOrNull(other.name)) {
387
+ return _textOrNull(other.name);
388
+ }
389
+ }
390
+ return "your area's Chief of Staff";
391
+ }
392
+
393
+ // Mirrors CrewMap::Ingest: a missing or unusable rank is rank 3.
394
+ function _rankOrDefault(raw) {
395
+ const rank = Number(raw);
396
+ return raw !== null && raw !== '' && Number.isInteger(rank) && rank >= 1 && rank <= 3 ? rank : 3;
397
+ }
398
+
399
+ // Header values are single lines: a newline or tab in a name can't start a
400
+ // new line of the system prompt.
401
+ function _textOrNull(v) {
402
+ if (typeof v === 'number') return String(v);
403
+ if (typeof v !== 'string') return null;
404
+ const line = _oneLine(v);
405
+ return line.length > 0 ? line : null;
406
+ }
407
+
408
+ function _oneLine(v) {
409
+ return String(v).replace(/[\s\u0085]+/g, ' ').trim();
410
+ }
411
+
412
+ // The voice block keeps its lines, fenced, with no line that could pass for
413
+ // the closing fence.
414
+ const VOICE_OPEN = 'Voice notes (from .claude/crew.yml; how you sound, nothing more):';
415
+ const VOICE_CLOSE = '(end of voice notes)';
416
+
417
+ function _voiceNotes(v) {
418
+ if (typeof v !== 'string') return '';
419
+ return v.split(/\r\n|[\n\r\u2028\u2029\u0085]/)
420
+ .map((line) => line.replace(/[\t\v\f]/g, ' ').trimEnd())
421
+ .map((line) => (line.trim() === VOICE_CLOSE ? `> ${line}` : ` ${line}`))
422
+ .join('\n')
423
+ .replace(/^(\s*\n)+|(\n\s*)+$/g, '');
424
+ }
425
+
426
+ module.exports = {
427
+ scanPersonas,
428
+ readPersonaBody,
429
+ scanCrewMap,
430
+ buildCrewHeader,
431
+ personaSlugFromPath,
432
+ PERSONA_SUBDIR,
433
+ CREW_MAP_PATH,
434
+ };
@@ -0,0 +1,146 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * #175: which command each stdout line of one Claude CLI process belongs to.
5
+ *
6
+ * The CLI reads stdin messages in order and runs one turn at a time. With
7
+ * --replay-user-messages and stream-json it writes (seen on 2.1.284):
8
+ *
9
+ * - `system/init` when it starts a turn;
10
+ * - a `user` line with `isReplay: true` echoing each message as the turn
11
+ * takes it;
12
+ * - one top-level `result` (no parent_tool_use_id) when the turn ends.
13
+ *
14
+ * A message written while a turn runs is either
15
+ * - QUEUED: the CLI leaves it for its own turn. Its echo comes after the
16
+ * running turn's result, and it gets its own result; or
17
+ * - MERGED: the CLI takes it at a tool boundary and folds it into the running
18
+ * turn. Its echo comes before that turn's result, and the one result ends
19
+ * both.
20
+ * A slash command gets an init and a result but no echo.
21
+ *
22
+ * So a command counts as read at its echo (a slash command, at its result),
23
+ * and a line is tagged with the command read last. A merged turn's result
24
+ * carries the newest command in it, the same id the daemon sent before #175,
25
+ * so Rails still closes both on it. A turn nothing we wrote started (no echo
26
+ * we know) keeps the previous tag. If the CLI never echoed at all, no
27
+ * command would count as read, and every line would fall back to the newest
28
+ * command_execute, as before #175.
29
+ *
30
+ * #224: the CLI takes a message from stdin about 20 ms before a turn's init
31
+ * and echoes it about 1 s later (2.1.284). Killed in between, the message is
32
+ * in the transcript. So readCommandIds() (what the CLI has taken, for Rails'
33
+ * "Not delivered" split) also counts the first written command as read at a
34
+ * turn's init. Tagging is unchanged. A turn the CLI starts on its own counts
35
+ * it too, which errs toward "read": Rails never marks a message the agent
36
+ * has as "Not delivered".
37
+ */
38
+ class TurnTracker {
39
+ constructor() {
40
+ this._written = []; // [{ commandId, text }] written to stdin, not read yet
41
+ this._turn = null; // { commandIds } while a turn runs
42
+ this._current = undefined; // commandId read last; undefined until one is read
43
+ this._newestWritten = null;
44
+ this._takenAtInit = null; // #224: the written entry a turn's init took, until the turn ends
45
+ }
46
+
47
+ /** A message was written to the CLI's stdin. */
48
+ written(commandId, text) {
49
+ this._written.push({ commandId: commandId ?? null, text });
50
+ if (commandId != null) this._newestWritten = commandId;
51
+ }
52
+
53
+ /**
54
+ * Account for one stdout line and say which command it belongs to.
55
+ * @returns {{ commandId: (string|null|undefined), turnCommandIds?: Array }}
56
+ * commandId is undefined until the CLI has read a message on this process.
57
+ * turnCommandIds is set on a turn's result: every command the turn read.
58
+ */
59
+ observe(data) {
60
+ if (!data || typeof data !== 'object') return { commandId: this._current };
61
+
62
+ if (data.type === 'system' && data.subtype === 'init') {
63
+ if (!this._turn) {
64
+ this._turn = { commandIds: [] };
65
+ this._takenAtInit = this._written[0] || null;
66
+ }
67
+ return { commandId: this._current };
68
+ }
69
+
70
+ if (data.type === 'user' && data.isReplay === true) {
71
+ if (!this._turn) this._turn = { commandIds: [] };
72
+ const index = this._written.findIndex((entry) => entry.text === _textOf(data.message));
73
+ // Stdin is read in order, so anything written before it was read too.
74
+ if (index >= 0) this._read(this._written.splice(0, index + 1));
75
+ return { commandId: this._current };
76
+ }
77
+
78
+ if (data.type === 'result' && !data.parent_tool_use_id) {
79
+ const turn = this._turn || { commandIds: [] };
80
+ this._turn = null;
81
+ this._takenAtInit = null;
82
+ // A slash command has no echo; the turn it started reads nothing else.
83
+ const next = this._written[0];
84
+ if (turn.commandIds.length === 0 && next && _isSlashCommand(next.text)) {
85
+ this._turn = turn;
86
+ this._read(this._written.splice(0, 1));
87
+ this._turn = null;
88
+ }
89
+ return { commandId: this._current, turnCommandIds: turn.commandIds.filter((id) => id != null) };
90
+ }
91
+
92
+ return { commandId: this._current };
93
+ }
94
+
95
+ /** The command the CLI read last, or undefined before it has read one. */
96
+ get currentCommandId() {
97
+ return this._current;
98
+ }
99
+
100
+ /** The newest command id written to this process, or null. */
101
+ get newestWrittenCommandId() {
102
+ return this._newestWritten;
103
+ }
104
+
105
+ /** Every command written to this process that no result has ended yet. */
106
+ unfinishedCommandIds() {
107
+ const ids = [
108
+ ...(this._turn ? this._turn.commandIds : []),
109
+ ...this._written.map((entry) => entry.commandId),
110
+ ];
111
+ return ids.filter((id) => id != null);
112
+ }
113
+
114
+ /**
115
+ * #224: every command written to this process that the CLI has taken, in
116
+ * order: the running turn's, plus the one its init took and hasn't echoed
117
+ * yet. A subset of unfinishedCommandIds().
118
+ */
119
+ readCommandIds() {
120
+ const ids = this._turn ? [...this._turn.commandIds] : [];
121
+ if (this._takenAtInit && this._written.includes(this._takenAtInit)) ids.push(this._takenAtInit.commandId);
122
+ return ids.filter((id) => id != null);
123
+ }
124
+
125
+ _read(entries) {
126
+ for (const entry of entries) {
127
+ this._turn.commandIds.push(entry.commandId);
128
+ this._current = entry.commandId;
129
+ }
130
+ }
131
+ }
132
+
133
+ function _isSlashCommand(text) {
134
+ return typeof text === 'string' && text.startsWith('/');
135
+ }
136
+
137
+ function _textOf(message) {
138
+ const content = message && message.content;
139
+ if (typeof content === 'string') return content;
140
+ if (Array.isArray(content)) {
141
+ return content.filter((block) => block && block.type === 'text').map((block) => block.text).join('');
142
+ }
143
+ return null;
144
+ }
145
+
146
+ module.exports = { TurnTracker };
@@ -1,40 +0,0 @@
1
- #!/bin/bash
2
- # permission-gate.sh — PreToolUse hook that gates tool execution on FlightDeck approval.
3
- #
4
- # Reads the hook JSON from stdin, POSTs it to the daemon's local permission server,
5
- # and returns the approval/denial decision to Claude CLI.
6
- #
7
- # Environment:
8
- # CLAUDE_PERMISSION_PORT — port of the daemon's permission server (required)
9
- # CLAUDE_SESSION_ID — session ID (set by daemon when spawning CLI)
10
-
11
- set -e
12
-
13
- INPUT=$(cat)
14
-
15
- PORT="${CLAUDE_PERMISSION_PORT:-}"
16
- if [ -z "$PORT" ]; then
17
- # No permission server configured — allow by default
18
- exit 0
19
- fi
20
-
21
- SESSION_ID="${CLAUDE_SESSION_ID:-unknown}"
22
-
23
- # Add session_id to the hook input
24
- PAYLOAD=$(echo "$INPUT" | jq --arg sid "$SESSION_ID" '. + {session_id: $sid}')
25
-
26
- # POST to daemon permission server and wait for response (blocking)
27
- RESPONSE=$(curl -s --max-time 120 \
28
- -X POST \
29
- -H "Content-Type: application/json" \
30
- -d "$PAYLOAD" \
31
- "http://127.0.0.1:${PORT}/permissions/request" 2>/dev/null)
32
-
33
- if [ $? -ne 0 ] || [ -z "$RESPONSE" ]; then
34
- # If we can't reach the permission server, allow (fail-open for safety)
35
- exit 0
36
- fi
37
-
38
- # Return the hook response to Claude CLI
39
- echo "$RESPONSE"
40
- exit 0