@adhdev/session-host-core 1.0.82-rc.36 → 1.0.82-rc.37

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": "@adhdev/session-host-core",
3
- "version": "1.0.82-rc.36",
3
+ "version": "1.0.82-rc.37",
4
4
  "description": "ADHDev local session host core — session registry, protocol, buffers",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -0,0 +1,114 @@
1
+ /** Shared cleanup expected-assignment / host-boot helpers (daemon + host). */
2
+ import type { SessionCleanupExpectedAssignment, SessionHostRecord } from './types.js';
3
+
4
+ /**
5
+ * Prefix on delete_session_if_expected refusals after runtime.stop was requested.
6
+ * Client durable fences must not abort on these — the writer may already be dying.
7
+ * Before-action refusals keep the bare CLEANUP_HOST_REFUSAL_CODES (abort-safe proof).
8
+ */
9
+ export const CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX = 'cleanup_after_stop_side_effect:';
10
+
11
+ export function tagCleanupAfterStopSideEffect(code: string): string {
12
+ return `${CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX}${code}`;
13
+ }
14
+
15
+ export function stripCleanupAfterStopSideEffect(raw: string): { afterStop: boolean; code: string } {
16
+ if (raw.startsWith(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX)) {
17
+ return { afterStop: true, code: raw.slice(CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX.length) };
18
+ }
19
+ return { afterStop: false, code: raw };
20
+ }
21
+
22
+ export function hostBootIdFromStartedAt(hostStartedAt: number): string {
23
+ return `hs:${hostStartedAt}`;
24
+ }
25
+
26
+ export function resolveHostBootId(opts: { upgradeBootId?: string | null; hostStartedAt: number }): string | null {
27
+ if (typeof opts.upgradeBootId === 'string' && opts.upgradeBootId) return opts.upgradeBootId;
28
+ if (!Number.isFinite(opts.hostStartedAt) || opts.hostStartedAt <= 0) return null;
29
+ return hostBootIdFromStartedAt(opts.hostStartedAt);
30
+ }
31
+
32
+ function refuseCleanupExpectedIdentity(
33
+ record: SessionHostRecord | null | undefined,
34
+ expected: SessionCleanupExpectedAssignment,
35
+ currentHostBootId: string | null,
36
+ ): string | null {
37
+ if (!expected || expected.sessionId !== (record?.sessionId ?? '')
38
+ || typeof expected.hostBootId !== 'string' || !expected.hostBootId
39
+ || typeof expected.runtimeKey !== 'string' || !expected.runtimeKey
40
+ || !Number.isSafeInteger(expected.startedAt) || expected.startedAt <= 0) {
41
+ return 'cleanup_expected_malformed';
42
+ }
43
+ if (!currentHostBootId) return 'cleanup_host_boot_unknown';
44
+ if (expected.hostBootId !== currentHostBootId) return 'cleanup_host_boot_mismatch';
45
+ if (!record) return 'cleanup_session_not_running';
46
+ if (record.runtimeKey !== expected.runtimeKey || record.startedAt !== expected.startedAt) {
47
+ return 'cleanup_native_incarnation_mismatch';
48
+ }
49
+ return null;
50
+ }
51
+
52
+ function refuseCleanupExpectedAssignment(
53
+ record: SessionHostRecord,
54
+ expected: SessionCleanupExpectedAssignment,
55
+ opts: { allowClearedBound?: boolean } = {},
56
+ ): string | null {
57
+ const active = record.meta?.meshActiveAssignment as Record<string, unknown> | undefined;
58
+ // taskId null is the unbound intent; attempt/generation/nonce may still be present as
59
+ // sticky fence fields on an idle worker and must not be treated as a live assignment.
60
+ if (expected.taskId === null) {
61
+ if (active && typeof active.taskId === 'string' && active.taskId) return 'cleanup_expected_unbound_now_bound';
62
+ return null;
63
+ }
64
+ if (!active || typeof active.taskId !== 'string' || !active.taskId) {
65
+ // After a proven stop the assignment may clear on the same incarnation — allow delete.
66
+ return opts.allowClearedBound ? null : 'cleanup_expected_bound_now_unbound';
67
+ }
68
+ if (active.taskId !== expected.taskId || active.attemptId !== expected.attemptId
69
+ || active.generation !== expected.generation || active.dispatchNonce !== expected.dispatchNonce) {
70
+ return 'cleanup_assignment_mismatch';
71
+ }
72
+ return null;
73
+ }
74
+
75
+ /** Sanitized refusal codes only — never echo assignment contents. */
76
+ export function refuseCleanupExpectedStop(
77
+ record: SessionHostRecord | null | undefined,
78
+ expected: SessionCleanupExpectedAssignment,
79
+ currentHostBootId: string | null,
80
+ hasRuntime: boolean,
81
+ ): string | null {
82
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
83
+ if (identity) return identity;
84
+ if (!record || record.termination || !hasRuntime || record.lifecycle !== 'running') {
85
+ return 'cleanup_session_not_running';
86
+ }
87
+ return refuseCleanupExpectedAssignment(record, expected);
88
+ }
89
+
90
+ /**
91
+ * Delete CAS: same identity/assignment proof as stop. A replaced incarnation or a
92
+ * newly bound writer must survive — never delete a record that no longer matches
93
+ * the captured expected tuple. `force` is required to stop a still-live runtime
94
+ * before deleting that exact incarnation.
95
+ */
96
+ export function refuseCleanupExpectedDelete(
97
+ record: SessionHostRecord | null | undefined,
98
+ expected: SessionCleanupExpectedAssignment,
99
+ currentHostBootId: string | null,
100
+ hasRuntime: boolean,
101
+ force: boolean,
102
+ ): string | null {
103
+ // Missing record after a proven stop is handled by the caller as idempotent delete.
104
+ if (!record) return 'cleanup_session_not_running';
105
+ const identity = refuseCleanupExpectedIdentity(record, expected, currentHostBootId);
106
+ if (identity) return identity;
107
+ if (hasRuntime) {
108
+ if (!force) return 'cleanup_session_still_running';
109
+ if (record.termination || record.lifecycle !== 'running') return 'cleanup_session_not_running';
110
+ return refuseCleanupExpectedAssignment(record, expected);
111
+ }
112
+ // Stopped/failed record: protect unbound→bound and reassignment on the same incarnation.
113
+ return refuseCleanupExpectedAssignment(record, expected, { allowClearedBound: true });
114
+ }
@@ -1,9 +1,11 @@
1
+ import { resolveHostBootId } from './cleanup-expected.js';
1
2
  import type {
2
3
  AcquireWritePayload,
3
4
  GetHostDiagnosticsPayload,
4
5
  GetSnapshotPayload,
5
6
  PruneDuplicateSessionsPayload,
6
7
  ReleaseWritePayload,
8
+ SessionCleanupExpectedAssignment,
7
9
  SessionHostDiagnostics,
8
10
  SessionHostPruneDuplicatesResult,
9
11
  SessionHostRecord,
@@ -28,9 +30,24 @@ export interface SessionHostSnapshot {
28
30
  */
29
31
  export interface SessionHostControlPlane {
30
32
  getDiagnostics(payload?: GetHostDiagnosticsPayload): Promise<SessionHostDiagnostics>;
33
+ /**
34
+ * Authoritative host boot identity for idle inventory / cleanup expected CAS.
35
+ * Prefers diagnostics.hostBootId (host SoT), else proves upgrade lease bootId
36
+ * via get_upgrade_lease, else hs:<hostStartedAt> for non-upgrade / old hosts.
37
+ * Ambiguous upgrade-lease failures fail closed (null) — never invent a UUID.
38
+ */
39
+ resolveHostBootId(): Promise<string | null>;
31
40
  listSessions(): Promise<SessionHostRecord[]>;
32
41
  stopSession(sessionId: string): Promise<SessionHostRecord | null>;
42
+ /** Host CAS stop: refuses without mutating when expected assignment/boot/incarnation drift. */
43
+ stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null>;
33
44
  deleteSession(sessionId: string, opts?: { force?: boolean }): Promise<SessionHostRecord | null>;
45
+ /** Host CAS delete: refuses without mutating when expected assignment/boot/incarnation drift. */
46
+ deleteSessionIfExpected(
47
+ sessionId: string,
48
+ expected: SessionCleanupExpectedAssignment,
49
+ opts?: { force?: boolean },
50
+ ): Promise<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null>;
34
51
  resumeSession(sessionId: string): Promise<SessionHostRecord | null>;
35
52
  restartSession(sessionId: string): Promise<SessionHostRecord | null>;
36
53
  sendSignal(sessionId: string, signal: string): Promise<SessionHostRecord | null>;
@@ -76,15 +93,56 @@ export function createSessionHostControlPlane(
76
93
  getDiagnostics(payload: GetHostDiagnosticsPayload = {}): Promise<SessionHostDiagnostics> {
77
94
  return transport.request<SessionHostDiagnostics>('get_host_diagnostics', payload as Record<string, unknown>);
78
95
  },
96
+ async resolveHostBootId(): Promise<string | null> {
97
+ let diagnostics: SessionHostDiagnostics;
98
+ try {
99
+ diagnostics = await transport.request<SessionHostDiagnostics>('get_host_diagnostics', {});
100
+ } catch {
101
+ return null;
102
+ }
103
+ if (typeof diagnostics.hostBootId === 'string' && diagnostics.hostBootId) {
104
+ return diagnostics.hostBootId;
105
+ }
106
+ // Host omitted hostBootId (older binary). Prove upgrade lease or fall back to hs:.
107
+ try {
108
+ const proof = await transport.request<{ bootId?: string }>('get_upgrade_lease', {});
109
+ return resolveHostBootId({
110
+ upgradeBootId: typeof proof?.bootId === 'string' ? proof.bootId : null,
111
+ hostStartedAt: diagnostics.hostStartedAt,
112
+ });
113
+ } catch (error) {
114
+ const msg = error instanceof Error ? error.message : String(error);
115
+ if (
116
+ msg.includes('native_host_upgrade_binding_unavailable')
117
+ || /unsupported|unknown request/i.test(msg)
118
+ ) {
119
+ return resolveHostBootId({ hostStartedAt: diagnostics.hostStartedAt });
120
+ }
121
+ return null;
122
+ }
123
+ },
79
124
  listSessions(): Promise<SessionHostRecord[]> {
80
125
  return transport.request<SessionHostRecord[]>('list_sessions', {});
81
126
  },
82
127
  stopSession(sessionId: string): Promise<SessionHostRecord | null> {
83
128
  return transport.request<SessionHostRecord | null>('stop_session', { sessionId });
84
129
  },
130
+ stopSessionIfExpected(sessionId: string, expected: SessionCleanupExpectedAssignment): Promise<SessionHostRecord | null> {
131
+ return transport.request<SessionHostRecord | null>('stop_session_if_expected', { sessionId, expected });
132
+ },
85
133
  deleteSession(sessionId: string, opts: { force?: boolean } = {}): Promise<SessionHostRecord | null> {
86
134
  return transport.request<SessionHostRecord | null>('delete_session', { sessionId, force: opts.force === true });
87
135
  },
136
+ deleteSessionIfExpected(
137
+ sessionId: string,
138
+ expected: SessionCleanupExpectedAssignment,
139
+ opts: { force?: boolean } = {},
140
+ ): Promise<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null> {
141
+ return transport.request<{ sessionId: string; deleted: boolean; alreadyAbsent?: boolean } | null>(
142
+ 'delete_session_if_expected',
143
+ { sessionId, expected, force: opts.force === true },
144
+ );
145
+ },
88
146
  resumeSession(sessionId: string): Promise<SessionHostRecord | null> {
89
147
  return transport.request<SessionHostRecord | null>('resume_session', { sessionId });
90
148
  },
package/src/index.ts CHANGED
@@ -52,9 +52,21 @@ export type {
52
52
  SessionHostWireEnvelope,
53
53
  SessionWriteOwner,
54
54
  StopSessionPayload,
55
+ SessionCleanupExpectedAssignment,
56
+ StopSessionIfExpectedPayload,
57
+ DeleteSessionIfExpectedPayload,
55
58
  } from './types.js';
56
59
 
57
60
  export { SESSION_HOST_SUPPORTED_REQUEST_TYPES } from './types.js';
61
+ export {
62
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
63
+ tagCleanupAfterStopSideEffect,
64
+ stripCleanupAfterStopSideEffect,
65
+ hostBootIdFromStartedAt,
66
+ resolveHostBootId,
67
+ refuseCleanupExpectedStop,
68
+ refuseCleanupExpectedDelete,
69
+ } from './cleanup-expected.js';
58
70
  export { classifyTermination } from './termination.js';
59
71
  export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, niceLaunch, spawnCliChild, type NiceLaunch } from './cli-child-priority.js';
60
72
  export { hiddenSpawn as hiddenSpawnProcess } from './process/hidden-spawn.js';
package/src/types.ts CHANGED
@@ -195,6 +195,26 @@ export interface ResizeSessionPayload {
195
195
  export interface StopSessionPayload {
196
196
  sessionId: string;
197
197
  }
198
+ /**
199
+ * Expected logical + physical identity for a cleanup stop. Captured before any
200
+ * async host RPC and re-checked inside the host stop critical section.
201
+ * All of taskId/attemptId/generation/dispatchNonce null means expected unbound
202
+ * (no meshActiveAssignment) so a later claim cannot be stopped by stale cleanup.
203
+ */
204
+ export interface SessionCleanupExpectedAssignment {
205
+ sessionId: string;
206
+ hostBootId: string;
207
+ runtimeKey: string;
208
+ startedAt: number;
209
+ taskId: string | null;
210
+ attemptId: string | null;
211
+ generation: number | null;
212
+ dispatchNonce: number | null;
213
+ }
214
+ export interface StopSessionIfExpectedPayload {
215
+ sessionId: string;
216
+ expected: SessionCleanupExpectedAssignment;
217
+ }
198
218
  export interface MeshWriterAssignment {
199
219
  meshId: string; nodeId: string; taskId: string; attemptId: string;
200
220
  generation: number; dispatchNonce: number; ownerDaemonId: string;
@@ -210,6 +230,13 @@ export interface DeleteSessionPayload {
210
230
  /** Stop a live runtime before deleting the persisted record. */
211
231
  force?: boolean;
212
232
  }
233
+ /** Expected identity for record deletion; old hosts must refuse this distinct kind. */
234
+ export interface DeleteSessionIfExpectedPayload {
235
+ sessionId: string;
236
+ expected: SessionCleanupExpectedAssignment;
237
+ /** Stop the matching live runtime before deleting that exact incarnation. */
238
+ force?: boolean;
239
+ }
213
240
 
214
241
  export interface ResumeSessionPayload {
215
242
  sessionId: string;
@@ -347,6 +374,13 @@ export interface SessionHostDiagnostics {
347
374
  * must treat `undefined` as "unknown", never as a match.
348
375
  */
349
376
  hostEntryPath?: string;
377
+ /**
378
+ * Authoritative host boot identity used by cleanup expected-assignment CAS.
379
+ * Same value `stop_session_if_expected` refuses against: upgrade-lease bootId
380
+ * when the host was launched with a native upgrade binding, otherwise `hs:<hostStartedAt>`.
381
+ * Optional so older hosts omit it; callers must not invent an upgrade UUID.
382
+ */
383
+ hostBootId?: string;
350
384
  runtimeCount: number;
351
385
  supportedRequestTypes?: SessionHostRequestType[];
352
386
  sessions?: SessionHostRecord[];
@@ -382,8 +416,12 @@ export type SessionHostRequest =
382
416
  | { type: 'get_input_state'; payload: GetInputStatePayload }
383
417
  | { type: 'resize_session'; payload: ResizeSessionPayload }
384
418
  | { type: 'stop_session'; payload: StopSessionPayload }
419
+ /** Distinct kind: old hosts must refuse instead of stopping by session id alone. */
420
+ | { type: 'stop_session_if_expected'; payload: StopSessionIfExpectedPayload }
385
421
  | { type: 'stop_mesh_writer'; payload: StopMeshWriterPayload }
386
422
  | { type: 'delete_session'; payload: DeleteSessionPayload }
423
+ /** Distinct kind: old hosts must refuse instead of deleting by session id alone. */
424
+ | { type: 'delete_session_if_expected'; payload: DeleteSessionIfExpectedPayload }
387
425
  | { type: 'resume_session'; payload: ResumeSessionPayload }
388
426
  | { type: 'acquire_write'; payload: AcquireWritePayload }
389
427
  | { type: 'release_write'; payload: ReleaseWritePayload }
@@ -420,8 +458,10 @@ export const SESSION_HOST_SUPPORTED_REQUEST_TYPES: readonly SessionHostRequestTy
420
458
  'get_input_state',
421
459
  'resize_session',
422
460
  'stop_session',
461
+ 'stop_session_if_expected',
423
462
  'stop_mesh_writer',
424
463
  'delete_session',
464
+ 'delete_session_if_expected',
425
465
  'resume_session',
426
466
  'acquire_write',
427
467
  'release_write',