@shumkov/orchestra 0.8.0 → 0.9.0

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.
@@ -192,15 +192,22 @@ direct-binary run; it does not clear the broader hosted-tool enforcement gate.
192
192
 
193
193
  ## Profile provenance
194
194
 
195
- Live pinned-runtime characterization found the exact profile at top-level
195
+ Two live pinned-runtime rollout runs found the exact profile at top-level
196
196
  `activePermissionProfile` in both `thread/start` and `thread/resume`
197
197
  responses. The value is fixture-pinned as `{id: "polygram-session",
198
198
  extends: null}`. Both attachment responses also return exactly one concrete
199
199
  `runtimeWorkspaceRoots` entry equal to the owned cwd. Orchestra exposes that
200
200
  entry only as `{count: 1, sha256: [sha256(ownedCwd)]}`.
201
201
 
202
- Fresh, resume, and `thread/settings/updated` all return the same legacy
203
- compatibility envelope:
202
+ Neither rollout run emitted `thread/settings/updated` during fresh or resume
203
+ attachment within the bounded wait. An exact attachment response is therefore
204
+ sufficient profile provenance. If an attachment-time notification does appear,
205
+ the checker still requires its complete static settings view to be exact.
206
+ Notifications caused by explicit experimental `thread/settings/update` calls
207
+ are characterized separately and do not establish attachment-time emission.
208
+
209
+ Fresh and resume responses, and any observed `thread/settings/updated`, use the
210
+ same legacy compatibility envelope:
204
211
 
205
212
  ```json
206
213
  {
@@ -31,10 +31,17 @@ const { createTmuxRunner } = require('./tmux-runner');
31
31
  * @param {object} opts
32
32
  * @param {string} opts.botName — only sweep sessions for THIS bot
33
33
  * @param {object} [opts.runner] — injected TmuxRunner (for tests)
34
+ * @param {string} [opts.socketName] — dedicated tmux server to enumerate, when
35
+ * no runner is injected. Must match the caller's own runner.
34
36
  * @param {object} [opts.logger=console]
35
- * @returns {Promise<{ swept: string[], errors: Array<{name:string, error:string}> }>}
37
+ * @returns {Promise<{ swept: string[], errors: Array<{name:string, error:string}>,
38
+ * listFailed: boolean, listError?: string }>} `listFailed` is true when the
39
+ * host could not be enumerated at all — distinct from an empty `swept`, which
40
+ * means the host was reachable and genuinely had no orphans.
36
41
  */
37
- async function sweepTmuxOrphans({ botName, runner, logger = console } = {}) {
42
+ async function sweepTmuxOrphans({
43
+ botName, runner, logger = console, socketName = null,
44
+ } = {}) {
38
45
  if (!botName) throw new TypeError('sweepTmuxOrphans: botName required');
39
46
  // SECURITY (audit M2): dashes in bot names risk prefix-match
40
47
  // collision when two bots share a prefix (e.g. `shumabit` matches
@@ -49,32 +56,43 @@ async function sweepTmuxOrphans({ botName, runner, logger = console } = {}) {
49
56
  + `prefix. Consider renaming (e.g. use _ instead).`,
50
57
  );
51
58
  }
52
- const r = runner || createTmuxRunner({ logger });
59
+ // The fallback runner must target the SAME tmux server the caller uses.
60
+ // Without forwarding socketName it would enumerate the default socket while
61
+ // the app's sessions live on a dedicated one — finding nothing and reporting a
62
+ // clean host, which is the very fail-open this function was hardened against.
63
+ const r = runner || createTmuxRunner({ logger, socketName });
53
64
  let names;
54
65
  try {
55
- names = await r.listPolygramSessions(botName);
66
+ names = await r.listPolygramSessions(botName, { strict: true });
56
67
  } catch (err) {
57
- // Most common: tmux not running. Best-effort = no-op.
58
- logger.log?.(`[orphan-sweep] list-sessions failed (${err.message}); assuming no orphans`);
59
- return { swept: [], errors: [] };
68
+ // "Could not ask" is NOT "nothing to sweep". Enumerating strictly and
69
+ // reporting the failure lets the caller decide: with a dedicated socket and
70
+ // `-N`, an unreachable server means the tmux unit never came up, and booting
71
+ // on would leave the daemon blind to sessions it is supposed to own.
72
+ logger.warn?.(`[orphan-sweep] list-sessions failed (${err.message}); cannot determine whether orphans exist`);
73
+ return { swept: [], errors: [], listFailed: true, listError: err.message };
60
74
  }
61
75
  if (names.length === 0) {
62
76
  logger.log?.(`[orphan-sweep] no orphan tmux sessions for ${botName}`);
63
- return { swept: [], errors: [] };
77
+ return { swept: [], errors: [], listFailed: false };
64
78
  }
65
79
  logger.log?.(`[orphan-sweep] killing ${names.length} orphan tmux session(s): ${names.join(', ')}`);
66
80
  const errors = [];
67
81
  const swept = [];
68
82
  for (const name of names) {
69
83
  try {
70
- await r.killSession(name);
84
+ // strict: this loop REPORTS what it reaped. Non-strict killSession
85
+ // resolves even when tmux refused, so every session would be logged as
86
+ // swept and the `errors` array below could never be populated — a stale
87
+ // session then survives and collides with the next spawn of that name.
88
+ await r.killSession(name, { strict: true });
71
89
  swept.push(name);
72
90
  } catch (err) {
73
91
  errors.push({ name, error: err.message });
74
92
  logger.warn?.(`[orphan-sweep] kill ${name} failed: ${err.message}`);
75
93
  }
76
94
  }
77
- return { swept, errors };
95
+ return { swept, errors, listFailed: false };
78
96
  }
79
97
 
80
98
  module.exports = { sweepTmuxOrphans };
@@ -84,6 +84,12 @@ const CONTROL_CHAR_RE = /[\x00-\x08\x0b-\x1f\x7f]/g;
84
84
  // SIGTERM. 10s is generous headroom over the sub-second norm.
85
85
  const TMUX_RUN_TIMEOUT_MS = 10_000;
86
86
 
87
+ // A tmux socket name becomes a bare CLI argument. execFile means this is not a
88
+ // shell-injection vector, but a value starting with '-' would be parsed by tmux
89
+ // as another server flag, and a path separator would silently select a
90
+ // different socket directory. Same reasoning as the paneWidth guard in spawn().
91
+ const SOCKET_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,63}$/;
92
+
87
93
  /**
88
94
  * Promise-wrapped childProcess.execFile. Returns { stdout, stderr }.
89
95
  * Rejects on non-zero exit (or timeout) with err.stdout + err.stderr
@@ -183,15 +189,37 @@ function ensureLogDir(logPath) {
183
189
  * @param {object} [opts.logger=console]
184
190
  * @param {Function} [opts.runFn] — override the underlying execFile
185
191
  * wrapper (for tests). Same signature: (cmd, args, opts?) → Promise.
192
+ * @param {string} [opts.socketName] — run against a dedicated tmux server
193
+ * (`tmux -L <name>`) instead of the shared default socket.
186
194
  */
187
195
  function createTmuxRunner({
188
196
  sessionPrefix = 'orchestra',
189
197
  logger = console,
190
198
  runFn = run,
191
199
  requireExistingServer = false,
200
+ socketName = null,
192
201
  } = {}) {
202
+ if (socketName != null && !SOCKET_NAME_RE.test(socketName)) {
203
+ throw new TypeError(
204
+ `socketName must match ${SOCKET_NAME_RE} (got ${JSON.stringify(socketName)})`,
205
+ );
206
+ }
193
207
  const runnerPrefix = sessionPrefix;
194
- const runTmux = (args, opts) => runFn('tmux', requireExistingServer ? ['-N', ...args] : args, opts);
208
+ // Server-scope flags, in tmux's required position: before the command word.
209
+ //
210
+ // `-L <name>` gives this app its own tmux server. Without it orchestra shares
211
+ // the DEFAULT socket with the operator's interactive sessions, so one
212
+ // `tmux kill-server` — from a unit's ExecStop or from a human at a prompt —
213
+ // reaches every bot, water and the admin session at once.
214
+ //
215
+ // Blast-radius control, not a privilege boundary: every server here runs under
216
+ // the same uid, so any process that knows the name can still run
217
+ // `tmux -L <name>` against it.
218
+ const serverArgs = [
219
+ ...(socketName ? ['-L', socketName] : []),
220
+ ...(requireExistingServer ? ['-N'] : []),
221
+ ];
222
+ const runTmux = (args, opts) => runFn('tmux', serverArgs.length ? [...serverArgs, ...args] : args, opts);
195
223
  async function spawn({
196
224
  name,
197
225
  cwd,
@@ -387,21 +415,48 @@ function createTmuxRunner({
387
415
  }
388
416
  }
389
417
 
390
- async function killSession(name) {
391
- await runTmux(['kill-session', '-t', name]).catch(() => {});
418
+ /**
419
+ * Kill a tmux session. Best-effort by default (teardown paths race normal
420
+ * exits and must not throw). Pass `{ strict: true }` when the caller reports
421
+ * success or failure to someone: silently swallowing here makes a stale
422
+ * session look reaped, and the next spawn then collides with the name.
423
+ */
424
+ async function killSession(name, { strict = false } = {}) {
425
+ try {
426
+ await runTmux(['kill-session', '-t', name]);
427
+ } catch (err) {
428
+ if (strict) {
429
+ throw Object.assign(new Error(`tmux kill-session failed: ${err.message}`), {
430
+ code: 'TMUX_KILL_FAILED',
431
+ cause: err,
432
+ });
433
+ }
434
+ }
392
435
  }
393
436
 
394
437
  /**
395
438
  * List polygram-managed tmux sessions on the host. Optional `botName`
396
439
  * narrows the prefix; without it returns all `water-*` sessions.
440
+ *
441
+ * Default is best-effort: an unreachable tmux server reads as an empty host.
442
+ * Pass `{ strict: true }` when the caller must distinguish "no sessions" from
443
+ * "could not ask" — with a dedicated socket and `-N` (never auto-start), an
444
+ * unreachable server means the tmux unit failed to come up, and treating that
445
+ * as "nothing here" hides it.
397
446
  */
398
- async function listPolygramSessions(botName = null) {
447
+ async function listPolygramSessions(botName = null, { strict = false } = {}) {
399
448
  try {
400
449
  const { stdout } = await runTmux(['list-sessions', '-F', '#{session_name}']);
401
450
  const all = stdout.trim().split('\n').filter(Boolean);
402
451
  const prefix = botName ? `${runnerPrefix}-${String(botName).replace(/[^\w-]/g, '_')}-` : `${runnerPrefix}-`;
403
452
  return all.filter((n) => n.startsWith(prefix));
404
- } catch {
453
+ } catch (err) {
454
+ if (strict) {
455
+ throw Object.assign(new Error(`tmux list-sessions failed: ${err.message}`), {
456
+ code: 'TMUX_LIST_FAILED',
457
+ cause: err,
458
+ });
459
+ }
405
460
  return [];
406
461
  }
407
462
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.8.0",
3
+ "version": "0.9.0",
4
4
  "description": "Transport-agnostic session engine for Claude Code and the native Codex app-server: spawn, steer, supervise, observe turns, and recover.",
5
5
  "type": "commonjs",
6
6
  "main": "index.js",