@shumkov/orchestra 0.10.4 → 0.10.6

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.
@@ -505,7 +505,16 @@ class CliProcess extends Process {
505
505
  // While non-empty, the keep-alive interval resets the turn's idle ceiling (an
506
506
  // idle `ask` fires no tool hooks, so _extendQuietOnToolActivity wouldn't run).
507
507
  this._openQuestions = new Set();
508
+ this._openApprovals = new Set();
508
509
  this._questionKeepAliveTimer = null;
510
+ this._cleanRestartOutputFenced = false;
511
+ this._cleanRestartEvidenceLost = false;
512
+ this._resumeAttestation = null;
513
+ Object.defineProperty(this, 'resumeAttestation', {
514
+ enumerable: true,
515
+ configurable: false,
516
+ get: () => this._resumeAttestation,
517
+ });
509
518
 
510
519
  // File-send outbound cap (bot → user). Safe cloud default; overwritten in
511
520
  // _spawnTmuxClaude with the backend/chat-resolved value before any turn.
@@ -552,6 +561,11 @@ class CliProcess extends Process {
552
561
  async start(opts = {}) {
553
562
  if (this.closed) throw new Error('CliProcess: cannot start a closed instance');
554
563
 
564
+ this._resumeAttestation = null;
565
+ this._pendingResumeAttestation = null;
566
+ this._strictExpectedSessionId = opts.resumePolicy === 'require-existing-session'
567
+ ? opts.expectedSessionId
568
+ : null;
555
569
  this.claudeSessionId = opts.existingSessionId || crypto.randomUUID();
556
570
  // Save cwd so the tool dispatcher's file-attachment allowlist (P0 #2) can
557
571
  // permit files under the agent's workspace.
@@ -593,6 +607,15 @@ class CliProcess extends Process {
593
607
  await this._createSocketServer();
594
608
  await this._spawnTmuxClaude({ tmuxName, opts });
595
609
  await this._waitForBridgeHandshake();
610
+ if (this._strictExpectedSessionId != null) {
611
+ if (this.claudeSessionId !== this._strictExpectedSessionId) {
612
+ throw Object.assign(
613
+ new Error('strict resume reported a different session identity'),
614
+ { code: 'REQUIRED_SESSION_MISMATCH' },
615
+ );
616
+ }
617
+ this._resumeAttestation = this._pendingResumeAttestation;
618
+ }
596
619
  this._stopStartupPingLoop();
597
620
  // Phase 1.3: arm hook tail AFTER spawn so this._hookNdjsonPath is
598
621
  // populated (set inside _spawnTmuxClaude when writeHookFiles runs).
@@ -670,6 +693,7 @@ class CliProcess extends Process {
670
693
  });
671
694
 
672
695
  this.bridgeServer.on('session-init', msg => {
696
+ if (!this._acceptBridgeSessionId(msg.claude_session_id)) return;
673
697
  // Adopt the canonical claude session_id the bridge reports (claude may
674
698
  // have ignored our --session-id; the bridge tells us what claude is
675
699
  // actually running).
@@ -705,6 +729,22 @@ class CliProcess extends Process {
705
729
  await this.bridgeServer.listen();
706
730
  }
707
731
 
732
+ _acceptBridgeSessionId(sessionId) {
733
+ if (
734
+ this._strictExpectedSessionId != null
735
+ && sessionId !== this._strictExpectedSessionId
736
+ ) {
737
+ this._resumeAttestation = null;
738
+ this._pendingResumeAttestation = null;
739
+ this._cancelPendingBridgeHandshake(
740
+ 'REQUIRED_SESSION_MISMATCH',
741
+ 'strict resume reported a different session identity',
742
+ );
743
+ return false;
744
+ }
745
+ return true;
746
+ }
747
+
708
748
  /**
709
749
  * Env for the spawned channels-bridge MCP subprocess. ORCHESTRA_QUESTION_TIMEOUT_MS
710
750
  * tells the bridge our question wait so its last-resort `ask` backstop sits ABOVE
@@ -831,17 +871,47 @@ class CliProcess extends Process {
831
871
  // - ghost ids from failed-before-first-turn attempts
832
872
  let canResume = false;
833
873
  let resumePath = null;
874
+ const strictResume = opts.resumePolicy === 'require-existing-session';
875
+ if (
876
+ strictResume
877
+ && (
878
+ typeof opts.expectedSessionId !== 'string'
879
+ || !opts.expectedSessionId
880
+ || opts.expectedSessionId !== opts.existingSessionId
881
+ )
882
+ ) {
883
+ throw Object.assign(
884
+ new Error('strict resume requires expectedSessionId to match existingSessionId'),
885
+ { code: 'REQUIRED_SESSION_MISMATCH' },
886
+ );
887
+ }
834
888
  if (opts.existingSessionId && resolvedCwd) {
835
- // claude's projects dir naming: cwd with '/' → '-'.
889
+ // Claude replaces path separators and dots in project directory names.
836
890
  // Verified live at ~/.claude/projects/-Users-ivanshumkov-Music-rekordbox/
837
- const cwdMangled = resolvedCwd.replace(/\//g, '-');
891
+ const cwdMangled = resolvedCwd.replace(/[/.]/g, '-');
838
892
  resumePath = path.join(os.homedir(), '.claude', 'projects', cwdMangled, `${opts.existingSessionId}.jsonl`);
839
893
  try { canResume = fs.statSync(resumePath).isFile(); } catch { canResume = false; }
840
894
  }
895
+ if (strictResume && !canResume) {
896
+ throw Object.assign(
897
+ new Error(
898
+ `required session ${opts.expectedSessionId} is unavailable at ${resumePath || '<unknown cwd>'}`,
899
+ ),
900
+ { code: 'REQUIRED_SESSION_NOT_FOUND' },
901
+ );
902
+ }
841
903
  if (canResume) {
842
904
  claudeArgs.push('--resume', opts.existingSessionId);
905
+ this._pendingResumeAttestation = Object.freeze({
906
+ namespace: 'claude:channels',
907
+ sessionId: opts.existingSessionId,
908
+ resumed: true,
909
+ freshFallback: false,
910
+ });
843
911
  } else {
844
912
  claudeArgs.push('--session-id', this.claudeSessionId);
913
+ this._resumeAttestation = null;
914
+ this._pendingResumeAttestation = null;
845
915
  if (opts.existingSessionId) {
846
916
  this.logger.warn?.(
847
917
  `[${this.label}] channels: dropping DB session ${opts.existingSessionId} — ` +
@@ -965,6 +1035,11 @@ class CliProcess extends Process {
965
1035
  ' watches ONE message fill in, live.',
966
1036
  '4. Always re-send the WHOLE list — an edit REPLACES the body, so a partial',
967
1037
  ' re-send loses everything you left out.',
1038
+ '5. Mark the item you are working on RIGHT NOW with a trailing hourglass:',
1039
+ ' `- [ ] Проверяю конфиги… ⏳` — at the END of that line, never the start',
1040
+ ' (the checkbox column stays aligned). Exactly one item carries it at a',
1041
+ ' time; when the item completes it becomes `- [x]` and the ⏳ moves to',
1042
+ ' the next one. The user sees at a glance what is happening right now.',
968
1043
  '',
969
1044
  'An edit re-renders the bubble exactly as the original `reply` did — a chat',
970
1045
  'that renders rich re-renders an edited checklist, table or heading rich, not',
@@ -1348,6 +1423,7 @@ class CliProcess extends Process {
1348
1423
  break;
1349
1424
 
1350
1425
  case 'perm_req':
1426
+ this._openApprovals.add(msg.request_id);
1351
1427
  // Canonical 'approval-required' shape — matches TmuxProcess emit signature
1352
1428
  // (lib/process/tmux-process.js:2877). polygram.js's existing onApprovalRequired
1353
1429
  // handler (lib/sdk/callbacks.js wired in polygram.js:2217) consumes this
@@ -1764,6 +1840,34 @@ class CliProcess extends Process {
1764
1840
 
1765
1841
  async _dispatchToolCall(msg) {
1766
1842
  const args = msg.args || {};
1843
+ const correlatedPending = args.turn_id
1844
+ ? this.pendingTurns.get(args.turn_id)
1845
+ : (this.pendingTurns.size === 1
1846
+ ? this.pendingTurns.values().next().value
1847
+ : null);
1848
+ if (msg.name === 'reply' || msg.name === 'stream' || msg.name === 'edit_message') {
1849
+ if (correlatedPending) correlatedPending.outputAttempted = true;
1850
+ else this._cleanRestartEvidenceLost = true;
1851
+ }
1852
+ if (this._cleanRestartOutputFenced) {
1853
+ this._cleanRestartEvidenceLost = true;
1854
+ if (msg.name === 'ask') {
1855
+ this._writeToBridge({
1856
+ kind: 'question_answer',
1857
+ tool_call_id: msg.tool_call_id,
1858
+ result: { cancelled: true, error: 'process retiring' },
1859
+ });
1860
+ } else {
1861
+ this._writeToBridge({
1862
+ kind: 'tool_ack',
1863
+ tool_call_id: msg.tool_call_id,
1864
+ ok: false,
1865
+ error: 'process retiring',
1866
+ attempt_id: msg.tool_call_id,
1867
+ });
1868
+ }
1869
+ return;
1870
+ }
1767
1871
 
1768
1872
  // rc.10 diagnostic: surface every inbound tool call BEFORE any dedup /
1769
1873
  // rate-limit / chat-id-mismatch path. Live shumorobot 2026-05-26 23:44
@@ -3789,6 +3893,162 @@ class CliProcess extends Process {
3789
3893
  this._logEvent('cli-bg-work-stall-selfcheck', { idle_ms: idleMs, shell_count: count, fired });
3790
3894
  }
3791
3895
 
3896
+ _classifyCleanRestart(deliveryEvidence) {
3897
+ if (this.pendingTurns.size === 0) return ['no-active-turn', null];
3898
+ if (this.pendingTurns.size !== 1) return ['multiple-active-turns', null];
3899
+ const [[turnId, pending]] = this.pendingTurns;
3900
+ const queueEntries = this.pendingQueue.filter(entry => entry.turnId === turnId);
3901
+ const ledger = this.inputLedger.get(turnId);
3902
+ const sourceMsgId = queueEntries[0]?.context?.sourceMsgId ?? ledger?.msgId ?? null;
3903
+ if (
3904
+ queueEntries.length !== 1
3905
+ || ledger?.source !== 'primary'
3906
+ || sourceMsgId == null
3907
+ || ledger.msgId == null
3908
+ || String(sourceMsgId) !== String(ledger.msgId)
3909
+ ) {
3910
+ return ['uncorrelated-source', null];
3911
+ }
3912
+ if (
3913
+ !deliveryEvidence
3914
+ || typeof deliveryEvidence !== 'object'
3915
+ || Array.isArray(deliveryEvidence)
3916
+ || typeof deliveryEvidence.outputAttempted !== 'boolean'
3917
+ || typeof deliveryEvidence.pending !== 'number'
3918
+ || !Number.isInteger(deliveryEvidence.pending)
3919
+ || deliveryEvidence.pending < 0
3920
+ || deliveryEvidence.fenced !== true
3921
+ ) {
3922
+ return ['delivery-ambiguous', sourceMsgId];
3923
+ }
3924
+ if (pending.outputAttempted === true || pending.replies?.length > 0) {
3925
+ return ['prior-output', sourceMsgId];
3926
+ }
3927
+ if (deliveryEvidence.outputAttempted) {
3928
+ return ['prior-output', sourceMsgId];
3929
+ }
3930
+ if (
3931
+ deliveryEvidence.pending > 0
3932
+ || deliveryEvidence.ambiguous === true
3933
+ || deliveryEvidence.safe === false
3934
+ ) {
3935
+ return ['delivery-ambiguous', sourceMsgId];
3936
+ }
3937
+ if (pending.activeToolIds?.size > 0) return ['unresolved-tool', sourceMsgId];
3938
+ if (this._openQuestions.size > 0) return ['unresolved-question', sourceMsgId];
3939
+ if (this._openApprovals.size > 0) return ['unresolved-approval', sourceMsgId];
3940
+ if (this._pendingSubagentStarts.length > 0) return ['active-subagent', sourceMsgId];
3941
+ if (ledger.state !== 'seen') return ['hook-correlation-missing', sourceMsgId];
3942
+ if (this.hasPendingDeliveryWork()) return ['delivery-ambiguous', sourceMsgId];
3943
+ const nonterminal = [...this.inputLedger.entries()].filter(([, entry]) => (
3944
+ entry.state === 'written'
3945
+ || entry.state === 'seen'
3946
+ || entry.state === 'fold-suspected'
3947
+ ));
3948
+ if (
3949
+ nonterminal.length !== 1
3950
+ || nonterminal[0][0] !== turnId
3951
+ || this.pendingQueue.length !== 1
3952
+ ) {
3953
+ return ['other-action-owner', sourceMsgId];
3954
+ }
3955
+ if (this._cleanRestartEvidenceLost) return ['bridge-loss', sourceMsgId];
3956
+ return ['eligible', sourceMsgId];
3957
+ }
3958
+
3959
+ _cleanRestartSourceMsgId() {
3960
+ if (this.pendingTurns.size !== 1) return null;
3961
+ const [[turnId]] = this.pendingTurns;
3962
+ const queueEntries = this.pendingQueue.filter(entry => entry.turnId === turnId);
3963
+ const ledger = this.inputLedger.get(turnId);
3964
+ const sourceMsgId = queueEntries[0]?.context?.sourceMsgId ?? ledger?.msgId ?? null;
3965
+ if (
3966
+ queueEntries.length !== 1
3967
+ || ledger?.source !== 'primary'
3968
+ || sourceMsgId == null
3969
+ || ledger.msgId == null
3970
+ || String(sourceMsgId) !== String(ledger.msgId)
3971
+ ) {
3972
+ return null;
3973
+ }
3974
+ return sourceMsgId;
3975
+ }
3976
+
3977
+ async retireForCleanRestart({ getDeliveryEvidence } = {}) {
3978
+ if (typeof getDeliveryEvidence !== 'function') {
3979
+ throw new TypeError(
3980
+ 'CliProcess.retireForCleanRestart: getDeliveryEvidence function required',
3981
+ );
3982
+ }
3983
+ if (this._cleanRestartRetirement) return this._cleanRestartRetirement;
3984
+ this._cleanRestartOutputFenced = true;
3985
+ this._cleanRestartRetiring = true;
3986
+ this._cleanRestartRetirement = (async () => {
3987
+ const failures = [];
3988
+ let deliveryEvidence = null;
3989
+ try {
3990
+ deliveryEvidence = await getDeliveryEvidence(
3991
+ this.sessionKey,
3992
+ this._cleanRestartSourceMsgId(),
3993
+ );
3994
+ } catch (error) {
3995
+ failures.push(error);
3996
+ }
3997
+ if (this.tmuxSession) {
3998
+ try {
3999
+ await this.runner.killSession(this.tmuxSession, { strict: true });
4000
+ this.tmuxSession = null;
4001
+ } catch (error) {
4002
+ failures.push(error);
4003
+ }
4004
+ }
4005
+ if (this.bridgeServer) {
4006
+ try {
4007
+ await this.bridgeServer.close();
4008
+ this.bridgeServer = null;
4009
+ } catch (error) {
4010
+ failures.push(error);
4011
+ }
4012
+ }
4013
+ if (!this._hookTail || typeof this._hookTail.drain !== 'function') {
4014
+ failures.push(new Error('hook tail unavailable'));
4015
+ } else {
4016
+ try {
4017
+ await this._hookTail.drain();
4018
+ } catch (error) {
4019
+ failures.push(error);
4020
+ }
4021
+ try { this._hookTail.close(); } catch (error) { failures.push(error); }
4022
+ this._hookTail = null;
4023
+ }
4024
+
4025
+ const [reason, sourceMsgId] = this._classifyCleanRestart(deliveryEvidence);
4026
+ try {
4027
+ await this._doKill('clean-restart');
4028
+ } catch (error) {
4029
+ failures.push(error);
4030
+ }
4031
+ if (failures.length > 0) {
4032
+ this._cleanRestartEvidenceLost = true;
4033
+ const cause = failures[0];
4034
+ throw Object.assign(
4035
+ new Error(`clean restart retirement failed: ${cause.message}`, { cause }),
4036
+ {
4037
+ code: 'CLEAN_RESTART_RETIREMENT_FAILED',
4038
+ failures: Object.freeze([...failures]),
4039
+ },
4040
+ );
4041
+ }
4042
+ return Object.freeze({
4043
+ sessionKey: this.sessionKey,
4044
+ sourceMsgId,
4045
+ eligible: reason === 'eligible',
4046
+ reason,
4047
+ });
4048
+ })();
4049
+ return this._cleanRestartRetirement;
4050
+ }
4051
+
3792
4052
  async kill(reason = 'kill') {
3793
4053
  if (this.closed) return;
3794
4054
  // Parity P19: re-entry guard for concurrent kill() calls. Mirrors
@@ -3841,6 +4101,7 @@ class CliProcess extends Process {
3841
4101
  }
3842
4102
  });
3843
4103
  this._hookTail.on('error', (err) => {
4104
+ this._cleanRestartEvidenceLost = true;
3844
4105
  this.logger.warn?.(`[${this.label}] hook tail error: ${err.message}`);
3845
4106
  this.emit('hook-tail-error', { err: err.message });
3846
4107
  });
@@ -3981,6 +4242,14 @@ class CliProcess extends Process {
3981
4242
  return;
3982
4243
 
3983
4244
  case 'PreToolUse': {
4245
+ const activePending = this.pendingTurns.size === 1
4246
+ ? this.pendingTurns.values().next().value
4247
+ : null;
4248
+ if (activePending && ev.toolUseId) {
4249
+ (activePending.activeToolIds ||= new Set()).add(ev.toolUseId);
4250
+ } else if (this.pendingTurns.size > 0) {
4251
+ this._cleanRestartEvidenceLost = true;
4252
+ }
3984
4253
  // Phase 1.3: synthesize subagent-start from Agent PreToolUse so the
3985
4254
  // reactor can show a distinct subagent-specific reaction during long
3986
4255
  // subagent runs. agent_type lives in tool_input.subagent_type per
@@ -4029,6 +4298,9 @@ class CliProcess extends Process {
4029
4298
  }
4030
4299
 
4031
4300
  case 'PostToolUse':
4301
+ for (const pending of this.pendingTurns.values()) {
4302
+ pending.activeToolIds?.delete(ev.toolUseId);
4303
+ }
4032
4304
  this.emit('tool-result', {
4033
4305
  name: ev.toolName,
4034
4306
  durationMs: ev.durationMs,
@@ -4295,6 +4567,12 @@ class CliProcess extends Process {
4295
4567
  * timer on the dead instance).
4296
4568
  */
4297
4569
  async _handleBridgeDisconnected(reason = 'socket-close') {
4570
+ if (this._cleanRestartRetiring) {
4571
+ this.bridgeReady = false;
4572
+ this.mcpReady = false;
4573
+ return;
4574
+ }
4575
+ this._cleanRestartEvidenceLost = true;
4298
4576
  this.bridgeReady = false;
4299
4577
  this.mcpReady = false;
4300
4578
  this._stopStartupPingLoop();
@@ -4753,6 +5031,7 @@ class CliProcess extends Process {
4753
5031
  return;
4754
5032
  }
4755
5033
  this.respondedPermissions.add(requestId);
5034
+ this._openApprovals.delete(requestId);
4756
5035
  this._writeToBridge({ kind: 'perm_verdict', request_id: requestId, behavior });
4757
5036
  }
4758
5037
 
@@ -674,6 +674,12 @@ class ProcessManager {
674
674
  while (this.totalCost + newCost > this.budget) {
675
675
  const evicted = this._evictLRU(); // skips inFlight + background-job-pinned
676
676
  if (evicted) continue;
677
+ if (spawnContext?.noWaitForCapacity === true) {
678
+ throw managerError(
679
+ `process capacity is not immediately available for sessionKey ${sessionKey}`,
680
+ 'PROCESS_ADMISSION_UNAVAILABLE',
681
+ );
682
+ }
677
683
  // _evictLRU freed nothing. Policy C — split by WHY:
678
684
  if (this._hasPinnedSession()) {
679
685
  // A DURABLE blocker (live background job) holds a slot. Don't park on it (could be
@@ -1221,6 +1227,21 @@ class ProcessManager {
1221
1227
  const proc = this.procs.get(sessionKey);
1222
1228
  if (!proc) throw new Error(`no process for sessionKey ${sessionKey}`);
1223
1229
  proc.lastUsedTs = Date.now();
1230
+ const hasExpectedProcess = (
1231
+ opts != null
1232
+ && typeof opts === 'object'
1233
+ && Object.prototype.hasOwnProperty.call(opts, 'expectedProcess')
1234
+ );
1235
+ if (hasExpectedProcess) {
1236
+ if (this.procs.get(sessionKey) !== opts.expectedProcess || proc.closed) {
1237
+ throw managerError(
1238
+ `process precondition failed for sessionKey ${sessionKey}`,
1239
+ 'PROCESS_PRECONDITION_FAILED',
1240
+ );
1241
+ }
1242
+ const { expectedProcess: _expectedProcess, ...sendOpts } = opts;
1243
+ return proc.send(prompt, sendOpts);
1244
+ }
1224
1245
  return proc.send(prompt, opts);
1225
1246
  }
1226
1247
 
@@ -1230,6 +1251,40 @@ class ProcessManager {
1230
1251
  ));
1231
1252
  }
1232
1253
 
1254
+ retireExpectedProcess(
1255
+ sessionKey,
1256
+ expectedProcess,
1257
+ reason = 'expected-process-retirement',
1258
+ ) {
1259
+ if (this.procs.get(sessionKey) !== expectedProcess) {
1260
+ return Promise.reject(managerError(
1261
+ `process precondition failed for sessionKey ${sessionKey}`,
1262
+ 'PROCESS_PRECONDITION_FAILED',
1263
+ ));
1264
+ }
1265
+ return this._withRetirementIntent(sessionKey, async () => {
1266
+ if (this.procs.get(sessionKey) !== expectedProcess) {
1267
+ throw managerError(
1268
+ `process precondition failed for sessionKey ${sessionKey}`,
1269
+ 'PROCESS_PRECONDITION_FAILED',
1270
+ );
1271
+ }
1272
+ try {
1273
+ await this._strictRetire(expectedProcess, reason);
1274
+ } catch (error) {
1275
+ this._retiring.delete(expectedProcess);
1276
+ throw error;
1277
+ }
1278
+ if (this.procs.get(sessionKey) === expectedProcess) {
1279
+ this.procs.delete(sessionKey);
1280
+ }
1281
+ this._retiring.delete(expectedProcess);
1282
+ if (this._codexLeaseMatches(expectedProcess)) this._codexLease = null;
1283
+ this._maybeSignalLruWaiter();
1284
+ return true;
1285
+ });
1286
+ }
1287
+
1233
1288
  async _killLocked(sessionKey, reason = 'kill') {
1234
1289
  const proc = this.procs.get(sessionKey);
1235
1290
  if (!proc) return false;
@@ -1310,6 +1365,79 @@ class ProcessManager {
1310
1365
  }
1311
1366
  }
1312
1367
 
1368
+ async retireForCleanRestart({ getDeliveryEvidence } = {}) {
1369
+ if (typeof getDeliveryEvidence !== 'function') {
1370
+ throw new TypeError(
1371
+ 'ProcessManager.retireForCleanRestart: getDeliveryEvidence function required',
1372
+ );
1373
+ }
1374
+ this._shuttingDown = true;
1375
+ for (const w of this._lruWaiters) {
1376
+ clearTimeout(w.timer);
1377
+ w.reject(new Error('shutdown'));
1378
+ }
1379
+ this._lruWaiters.length = 0;
1380
+
1381
+ const admittedResults = await Promise.allSettled(
1382
+ [...this._lifecycleGates.values()],
1383
+ );
1384
+ const targets = [...this.procs.entries()]
1385
+ .filter(([, proc]) => !this._retiring.has(proc));
1386
+ for (const [, proc] of targets) this._retiring.add(proc);
1387
+
1388
+ let settled;
1389
+ try {
1390
+ settled = await Promise.allSettled(targets.map(async ([sessionKey, proc]) => {
1391
+ let snapshot;
1392
+ if (this._isCodex(proc)) {
1393
+ await getDeliveryEvidence(sessionKey, null);
1394
+ await this._strictRetire(proc, 'clean-restart');
1395
+ if (this._codexLeaseMatches(proc)) this._codexLease = null;
1396
+ snapshot = {
1397
+ sourceMsgId: null,
1398
+ eligible: false,
1399
+ reason: 'unsupported-backend',
1400
+ };
1401
+ } else {
1402
+ snapshot = await proc.retireForCleanRestart({
1403
+ getDeliveryEvidence: (_reportedSessionKey, sourceMsgId) => (
1404
+ getDeliveryEvidence(
1405
+ sessionKey,
1406
+ proc.backend === 'cli' ? sourceMsgId : null,
1407
+ )
1408
+ ),
1409
+ });
1410
+ }
1411
+ const cliEligible = proc.backend === 'cli' && snapshot?.eligible === true;
1412
+ return Object.freeze({
1413
+ sessionKey,
1414
+ sourceMsgId: proc.backend === 'cli'
1415
+ ? (snapshot?.sourceMsgId ?? null)
1416
+ : null,
1417
+ eligible: cliEligible,
1418
+ reason: proc.backend === 'cli'
1419
+ ? (snapshot?.reason || 'retirement-uncertain')
1420
+ : 'unsupported-backend',
1421
+ });
1422
+ }));
1423
+ } finally {
1424
+ for (const [sessionKey, proc] of targets) {
1425
+ if (proc.closed && this.procs.get(sessionKey) === proc) {
1426
+ this.procs.delete(sessionKey);
1427
+ }
1428
+ this._retiring.delete(proc);
1429
+ }
1430
+ this._maybeSignalLruWaiter();
1431
+ }
1432
+ const failure = [
1433
+ ...admittedResults,
1434
+ ...settled,
1435
+ ].find(result => result.status === 'rejected');
1436
+ if (failure) throw failure.reason;
1437
+ const results = settled.map(result => result.value);
1438
+ return Object.freeze(results);
1439
+ }
1440
+
1313
1441
  // ─── Optional async — feature-detect at call site if needed ──────
1314
1442
 
1315
1443
  /**
@@ -115,6 +115,25 @@ class Process extends EventEmitter {
115
115
  throw new Error(`${this.constructor.name}.kill() must be overridden`);
116
116
  }
117
117
 
118
+ async retireForCleanRestart({ getDeliveryEvidence } = {}) {
119
+ if (typeof getDeliveryEvidence === 'function') {
120
+ await getDeliveryEvidence(this.sessionKey, null);
121
+ }
122
+ await this.kill('clean-restart');
123
+ if (!this.closed) {
124
+ throw Object.assign(
125
+ new Error('clean restart retirement did not close the process'),
126
+ { code: 'CLEAN_RESTART_RETIREMENT_FAILED' },
127
+ );
128
+ }
129
+ return Object.freeze({
130
+ sessionKey: this.sessionKey,
131
+ sourceMsgId: null,
132
+ eligible: false,
133
+ reason: 'unsupported-backend',
134
+ });
135
+ }
136
+
118
137
  // ─── OPTIONAL async methods — caller awaits + try/catch ────────────
119
138
 
120
139
  async interrupt() {
@@ -107,6 +107,7 @@ class LogTail extends EventEmitter {
107
107
  this._initialised = false;
108
108
  this._readInFlight = false; // debounce concurrent _readNew triggers
109
109
  this._readPending = false;
110
+ this._draining = false;
110
111
  }
111
112
 
112
113
  start() {
@@ -194,6 +195,10 @@ class LogTail extends EventEmitter {
194
195
  */
195
196
  _triggerRead() {
196
197
  if (this._closed) return;
198
+ if (this._draining) {
199
+ this._readPending = true;
200
+ return;
201
+ }
197
202
  if (this._readInFlight) {
198
203
  this._readPending = true;
199
204
  return;
@@ -243,7 +248,7 @@ class LogTail extends EventEmitter {
243
248
  this._timer = setImmediate(tick);
244
249
  }
245
250
 
246
- async _readNew() {
251
+ async _readNew(maxOffset = null) {
247
252
  let stat;
248
253
  try {
249
254
  stat = await this.fs.promises.stat(this.path);
@@ -251,7 +256,8 @@ class LogTail extends EventEmitter {
251
256
  if (err.code === 'ENOENT') return; // not created yet
252
257
  throw err;
253
258
  }
254
- if (stat.size < this._offset) {
259
+ const observedSize = maxOffset == null ? stat.size : Math.min(stat.size, maxOffset);
260
+ if (observedSize < this._offset) {
255
261
  // File truncated (rare for claude debug-file but possible on log
256
262
  // rotation). Reset offset and re-read from the beginning.
257
263
  this.emit('truncated', { previous: this._offset, current: stat.size });
@@ -262,10 +268,10 @@ class LogTail extends EventEmitter {
262
268
  // post-truncation read.
263
269
  this._decoder = new StringDecoder('utf8');
264
270
  }
265
- if (stat.size <= this._offset) return; // unchanged
271
+ if (observedSize <= this._offset) return; // unchanged
266
272
  const fd = await this.fs.promises.open(this.path, 'r');
267
273
  try {
268
- const bytesToRead = stat.size - this._offset;
274
+ const bytesToRead = observedSize - this._offset;
269
275
  const buffer = Buffer.alloc(Math.min(bytesToRead, DEFAULT_CHUNK_BYTES));
270
276
  let totalRead = 0;
271
277
  while (totalRead < bytesToRead && !this._closed) {
@@ -314,6 +320,33 @@ class LogTail extends EventEmitter {
314
320
  }
315
321
  }
316
322
 
323
+ async drain() {
324
+ if (this._closed) throw new Error('LogTail: cannot drain a closed tail');
325
+ this._draining = true;
326
+ while (this._readInFlight) {
327
+ await new Promise(resolve => setImmediate(resolve));
328
+ }
329
+ let watermark;
330
+ try {
331
+ watermark = (await this.fs.promises.stat(this.path)).size;
332
+ } catch (err) {
333
+ if (err.code !== 'ENOENT') {
334
+ this._draining = false;
335
+ throw err;
336
+ }
337
+ watermark = 0;
338
+ }
339
+ this._readPending = false;
340
+ this._readInFlight = true;
341
+ try {
342
+ await this._readNew(watermark);
343
+ } finally {
344
+ this._readInFlight = false;
345
+ this._draining = false;
346
+ }
347
+ return Object.freeze({ offset: this._offset, watermark });
348
+ }
349
+
317
350
  close() {
318
351
  if (this._closed) return;
319
352
  this._closed = true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shumkov/orchestra",
3
- "version": "0.10.4",
3
+ "version": "0.10.6",
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",