@radnine/claude-session-daemon 0.7.1 → 0.7.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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@radnine/claude-session-daemon",
3
- "version": "0.7.1",
3
+ "version": "0.7.3",
4
4
  "description": "Node.js daemon for managing Claude CLI sessions",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {
@@ -31,8 +31,8 @@
31
31
  "node": ">=18.0.0"
32
32
  },
33
33
  "dependencies": {
34
+ "gray-matter": "^4.0.3",
34
35
  "js-yaml": "^4.1.0",
35
36
  "ws": "^8.16.0"
36
- },
37
- "devDependencies": {}
37
+ }
38
38
  }
package/src/config.js CHANGED
@@ -23,7 +23,7 @@ function loadConfig() {
23
23
  workingDir: env.CLAUDE_WORKING_DIR || process.cwd(),
24
24
 
25
25
  // Maximum concurrent sessions
26
- maxSessions: intEnv(env.CLAUDE_MAX_SESSIONS, 10),
26
+ maxSessions: intEnv(env.CLAUDE_MAX_SESSIONS, 15),
27
27
 
28
28
  // Anthropic API key passed through to Claude CLI
29
29
  anthropicApiKey: env.ANTHROPIC_API_KEY || null,
@@ -8,6 +8,7 @@ const WebSocket = require('ws');
8
8
  const { BaseConnection } = require('./base-connection');
9
9
  const { getGitContext } = require('../git-context');
10
10
  const { getClaudeAccount } = require('../claude-account');
11
+ const { scanPersonas, readPersonaBody } = require('../persona-scanner');
11
12
  const daemonPkg = require('../../package.json');
12
13
 
13
14
  /**
@@ -629,6 +630,20 @@ class ActionCableClient extends BaseConnection {
629
630
 
630
631
  /**
631
632
  * Handle session_activate — spawn or reuse a Claude process for the session.
633
+ *
634
+ * Two ways to seed the Claude system prompt:
635
+ * - `system_prompt` — inline body (DB-backed Prompt path)
636
+ * - `system_prompt_path` — relative path under workingDir to a
637
+ * file-backed Persona (.claude/personas/<slug>.md). Read fresh
638
+ * every activation; frontmatter stripped; path traversal rejected.
639
+ *
640
+ * When both are present, system_prompt_path wins. The file is the
641
+ * canonical source for file-backed personas, and Rails should not
642
+ * have a stale snapshot to fall back to.
643
+ *
644
+ * Errors from path validation or file reads are reported back as a
645
+ * structured SESSION_ACTIVATION_FAILED — never a silent hang.
646
+ *
632
647
  * @param {object} message
633
648
  */
634
649
  async _handleSessionActivation(message) {
@@ -636,9 +651,30 @@ class ActionCableClient extends BaseConnection {
636
651
  const userId = message.user_id;
637
652
  const claudeSessionId = message.claude_session_id || undefined;
638
653
  const resetGit = !!message.reset_git_state;
639
- const systemPrompt = message.system_prompt || undefined;
654
+ const systemPromptPath = message.system_prompt_path || undefined;
655
+ let systemPrompt = message.system_prompt || undefined;
656
+
657
+ if (systemPromptPath) {
658
+ try {
659
+ // Re-read every activation — authors edit persona files mid-session
660
+ // and we want the next session to pick that up without a daemon restart.
661
+ systemPrompt = await readPersonaBody(this._config.workingDir, systemPromptPath);
662
+ } catch (err) {
663
+ this._logger.error('Persona resolution failed', { sessionId, systemPromptPath, code: err.code, error: err.message });
664
+ this._sendError('SESSION_ACTIVATION_FAILED', err.message, {
665
+ session_id: sessionId,
666
+ system_prompt_path: systemPromptPath,
667
+ reason: err.code || 'PERSONA_RESOLUTION_FAILED',
668
+ });
669
+ return;
670
+ }
671
+ }
640
672
 
641
- this._logger.info('Received session_activate', { sessionId, userId, claudeSessionId, resetGit, hasSystemPrompt: !!systemPrompt });
673
+ this._logger.info('Received session_activate', {
674
+ sessionId, userId, claudeSessionId, resetGit,
675
+ hasSystemPrompt: !!systemPrompt,
676
+ fileBacked: !!systemPromptPath,
677
+ });
642
678
 
643
679
  try {
644
680
  const proc = await this._daemon.activateSession(sessionId, {
@@ -858,7 +894,9 @@ class ActionCableClient extends BaseConnection {
858
894
 
859
895
  try {
860
896
  await this._daemon.terminateSession(sessionId);
861
- this._sendSessionStateUpdate(sessionId, { status: 'deactivated' });
897
+ // Rails Session#status only allows active/paused/terminated — sending
898
+ // 'deactivated' here raises RecordInvalid on the server.
899
+ this._sendSessionStateUpdate(sessionId, { status: 'terminated' });
862
900
  } catch (err) {
863
901
  this._logger.error('Failed to deactivate session', { sessionId, error: err.message });
864
902
  }
@@ -1107,9 +1145,10 @@ class ActionCableClient extends BaseConnection {
1107
1145
  * Send a heartbeat message to the server.
1108
1146
  */
1109
1147
  async _sendHeartbeat() {
1110
- const [gitContext, claudeAccount] = await Promise.all([
1148
+ const [gitContext, claudeAccount, personas] = await Promise.all([
1111
1149
  this._getGitContext(),
1112
1150
  this._getClaudeAccount(),
1151
+ this._getPersonas(),
1113
1152
  ]);
1114
1153
 
1115
1154
  this.sendDaemonMessage({
@@ -1121,10 +1160,31 @@ class ActionCableClient extends BaseConnection {
1121
1160
  resource_usage: this._getResourceUsage(),
1122
1161
  git_context: gitContext,
1123
1162
  claude_account: claudeAccount,
1163
+ personas,
1124
1164
  timestamp: new Date().toISOString(),
1125
1165
  });
1126
1166
  }
1127
1167
 
1168
+ /**
1169
+ * Scan the pilot's working directory for file-backed personas.
1170
+ * Body content is intentionally not included — heartbeat carries metadata only.
1171
+ * Failures degrade to an empty list; the heartbeat must never block on this.
1172
+ */
1173
+ async _getPersonas() {
1174
+ try {
1175
+ const personas = await scanPersonas(this._workingDir, { logger: this._logger });
1176
+ if (personas.length > 0) {
1177
+ this._logger.debug(`Reporting ${personas.length} file-backed persona(s) in heartbeat`, {
1178
+ slugs: personas.map((p) => p.slug),
1179
+ });
1180
+ }
1181
+ return personas;
1182
+ } catch (err) {
1183
+ this._logger.warn('Persona scan failed; reporting empty list', { error: err.message });
1184
+ return [];
1185
+ }
1186
+ }
1187
+
1128
1188
  /**
1129
1189
  * Get git context (branch, PR, remote) for the working directory.
1130
1190
  * Returns cached results (30s TTL via git-context module).
@@ -0,0 +1,162 @@
1
+ 'use strict';
2
+
3
+ const fs = require('node:fs').promises;
4
+ const path = require('node:path');
5
+ const matter = require('gray-matter');
6
+
7
+ const PERSONA_SUBDIR = '.claude/personas';
8
+
9
+ /**
10
+ * Scan <workingDir>/.claude/personas/*.md and return parsed persona metadata.
11
+ *
12
+ * For each .md file:
13
+ * - slug is derived from the filename (minus the .md suffix)
14
+ * - YAML frontmatter is parsed for optional `name`, `description`, `role`, `tokens`
15
+ * (the heartbeat wire format calls this field `decision_tokens` — see below)
16
+ * - body is parsed but NOT included in the returned metadata (heartbeat carries
17
+ * metadata only; body is re-read at activation time in Phase 3)
18
+ * - path is returned relative to workingDir for stable cross-pilot keys
19
+ *
20
+ * The frontmatter key is `tokens` (short and idiomatic for persona authors),
21
+ * but the heartbeat emits it as `decision_tokens` so the Rails default
22
+ * filter_parameters rule (which redacts anything matching /token/) doesn't
23
+ * blank the array in dev logs. Same data, name chosen for log-friendliness.
24
+ *
25
+ * Failure modes are non-fatal:
26
+ * - missing personas directory => empty array
27
+ * - unreadable file => skipped with logger.warn
28
+ * - invalid YAML frontmatter => persona is still returned with slug only
29
+ * (the whole file is treated as body, per spec)
30
+ *
31
+ * @param {string} workingDir - The pilot's working directory.
32
+ * @param {object} [opts]
33
+ * @param {{warn: function}} [opts.logger] - Optional logger; warnings only.
34
+ * @returns {Promise<Array<{slug: string, name: string|null, description: string|null, path: string, role: string|null, decision_tokens: Array|null}>>}
35
+ */
36
+ async function scanPersonas(workingDir, opts = {}) {
37
+ if (!workingDir) return [];
38
+ const logger = opts.logger;
39
+ const personaDir = path.join(workingDir, PERSONA_SUBDIR);
40
+
41
+ let entries;
42
+ try {
43
+ entries = await fs.readdir(personaDir, { withFileTypes: true });
44
+ } catch (err) {
45
+ if (err.code === 'ENOENT' || err.code === 'ENOTDIR') return [];
46
+ if (logger) logger.warn(`Failed to read personas directory ${personaDir}: ${err.message}`);
47
+ return [];
48
+ }
49
+
50
+ const personas = [];
51
+ for (const entry of entries) {
52
+ if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
53
+ const filePath = path.join(personaDir, entry.name);
54
+ const persona = await _parsePersonaFile(filePath, entry.name, workingDir, logger);
55
+ if (persona) personas.push(persona);
56
+ }
57
+ personas.sort((a, b) => a.slug.localeCompare(b.slug));
58
+ return personas;
59
+ }
60
+
61
+ async function _parsePersonaFile(filePath, fileName, workingDir, logger) {
62
+ const slug = fileName.replace(/\.md$/, '');
63
+
64
+ let raw;
65
+ try {
66
+ raw = await fs.readFile(filePath, 'utf8');
67
+ } catch (err) {
68
+ if (logger) logger.warn(`Failed to read persona file ${filePath}: ${err.message}`);
69
+ return null;
70
+ }
71
+
72
+ let frontmatter = {};
73
+ try {
74
+ const parsed = matter(raw);
75
+ frontmatter = parsed.data || {};
76
+ } catch (err) {
77
+ if (logger) {
78
+ logger.warn(`Invalid YAML frontmatter in ${filePath}, treating whole file as body: ${err.message}`);
79
+ }
80
+ }
81
+
82
+ return {
83
+ slug,
84
+ name: _stringOrNull(frontmatter.name),
85
+ description: _stringOrNull(frontmatter.description),
86
+ path: path.relative(workingDir, filePath),
87
+ role: _stringOrNull(frontmatter.role),
88
+ decision_tokens: Array.isArray(frontmatter.tokens) ? frontmatter.tokens.slice() : null,
89
+ };
90
+ }
91
+
92
+ function _stringOrNull(v) {
93
+ return typeof v === 'string' && v.length > 0 ? v : null;
94
+ }
95
+
96
+ /**
97
+ * Read a persona file fresh from disk, validate it stays inside the
98
+ * pilot's working tree, strip frontmatter, and return the body.
99
+ *
100
+ * Used at session activation time when Rails sends `system_prompt_path`
101
+ * (a relative path under the pilot's working dir) instead of an inline
102
+ * `system_prompt`. The body is never cached — every activation re-reads
103
+ * the file so authors can edit a persona and see changes on the next
104
+ * session without restarting the daemon.
105
+ *
106
+ * Path-traversal hardening:
107
+ * - `relativePath` is resolved against `workingDir`
108
+ * - the resolved path MUST live under `workingDir + path.sep`
109
+ * - absolute paths, `..` escapes, and bind-mount tricks are rejected
110
+ *
111
+ * @param {string} workingDir - The pilot's working directory (absolute).
112
+ * @param {string} relativePath - Persona file path, expected relative
113
+ * to workingDir (e.g. `.claude/personas/commander.md`).
114
+ * @returns {Promise<string>} The persona body (frontmatter stripped).
115
+ * @throws {Error} with `.code` set to one of:
116
+ * - `PERSONA_WORKING_DIR_MISSING` — no workingDir configured
117
+ * - `PERSONA_PATH_INVALID` — relativePath empty/non-string
118
+ * - `PERSONA_PATH_ESCAPES_WORKING_DIR` — traversal attempt
119
+ * - `PERSONA_FILE_UNREADABLE` — missing or read error
120
+ */
121
+ async function readPersonaBody(workingDir, relativePath) {
122
+ if (!workingDir) {
123
+ const err = new Error('No workingDir configured for persona resolution');
124
+ err.code = 'PERSONA_WORKING_DIR_MISSING';
125
+ throw err;
126
+ }
127
+ if (typeof relativePath !== 'string' || relativePath.length === 0) {
128
+ const err = new Error('system_prompt_path must be a non-empty string');
129
+ err.code = 'PERSONA_PATH_INVALID';
130
+ throw err;
131
+ }
132
+
133
+ const resolved = path.resolve(workingDir, relativePath);
134
+ // Add path.sep so workingDir="/var/foo" does not accept "/var/foobar".
135
+ if (!resolved.startsWith(workingDir + path.sep) && resolved !== workingDir) {
136
+ const err = new Error(`Persona path escapes working dir: ${relativePath}`);
137
+ err.code = 'PERSONA_PATH_ESCAPES_WORKING_DIR';
138
+ throw err;
139
+ }
140
+
141
+ let raw;
142
+ try {
143
+ raw = await fs.readFile(resolved, 'utf8');
144
+ } catch (readErr) {
145
+ const err = new Error(`Cannot read persona file ${relativePath}: ${readErr.message}`);
146
+ err.code = 'PERSONA_FILE_UNREADABLE';
147
+ err.cause = readErr;
148
+ throw err;
149
+ }
150
+
151
+ let body = raw;
152
+ try {
153
+ const parsed = matter(raw);
154
+ body = parsed.content;
155
+ } catch (_parseErr) {
156
+ // Mirror scanPersonas: malformed YAML => treat whole file as body.
157
+ body = raw;
158
+ }
159
+ return body;
160
+ }
161
+
162
+ module.exports = { scanPersonas, readPersonaBody, PERSONA_SUBDIR };