@adhdev/session-host-core 1.0.82-rc.11 → 1.0.82-rc.110

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.11",
3
+ "version": "1.0.82-rc.110",
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",
@@ -21,7 +21,7 @@
21
21
  "scripts": {
22
22
  "build": "tsup",
23
23
  "dev": "tsup --watch",
24
- "test": "node --import tsx --test test/*.test.ts",
24
+ "test": "node --import ../../scripts/test-tmp-guard.mjs --import tsx --test test/*.test.ts",
25
25
  "typecheck": "tsc --noEmit -p tsconfig.json"
26
26
  },
27
27
  "files": [
@@ -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
+ }
@@ -0,0 +1,117 @@
1
+ import * as fs from 'node:fs';
2
+ import * as os from 'node:os';
3
+ import { hiddenSpawn } from './process/hidden-spawn.js';
4
+
5
+ /** Relative POSIX niceness adjustment for newly spawned agent workloads. */
6
+ export const CLI_CHILD_NICE_INCREMENT = 10;
7
+ /** Set to "0" in the daemon environment (or launch env) to disable lowering. */
8
+ export const CLI_CHILD_NICE_ENV = 'ADHDEV_CLI_CHILD_NICE';
9
+ /** Optional Darwin CPU + I/O background policy, in addition to baseline nice. */
10
+ export const CLI_CHILD_SCHEDULING_ENV = 'ADHDEV_CLI_CHILD_SCHEDULING';
11
+
12
+ function setDarwinBackground(pid: number, onFailure: (error: unknown) => void): void {
13
+ // A short control helper stays normal priority. Do not block the IPC owner.
14
+ const task = hiddenSpawn('/usr/sbin/taskpolicy', ['-b', '-p', String(pid)], { stdio: 'ignore' });
15
+ task.once('error', onFailure);
16
+ task.once('exit', (code, signal) => {
17
+ if (code !== 0) onFailure(new Error(`taskpolicy exited with ${signal ?? code}`));
18
+ });
19
+ }
20
+
21
+ const POSIX_NICE_BINARY = '/usr/bin/nice';
22
+
23
+ export interface NiceLaunch {
24
+ readonly command: string;
25
+ readonly args: string[];
26
+ /** True when the child will START at the lowered priority (spawnCliChild must not lower it again). */
27
+ readonly preApplied: boolean;
28
+ }
29
+
30
+ /**
31
+ * Launch through `nice -n <increment>` on macOS/Linux so the child runs at the
32
+ * lowered priority from its first instruction. `nice` execs the target in
33
+ * place: same pid, and every descendant inherits the niceness. This closes the
34
+ * spawn→setPriority race where a child forked before the post-spawn call and
35
+ * its early descendants escaped at NI=0. Windows (no nice) and shell-string
36
+ * launches keep the post-spawn path.
37
+ */
38
+ export function niceLaunch(
39
+ command: string,
40
+ args: readonly string[],
41
+ env: NodeJS.ProcessEnv = process.env,
42
+ platform: NodeJS.Platform = process.platform,
43
+ niceAvailable: () => boolean = () => fs.existsSync(POSIX_NICE_BINARY),
44
+ ): NiceLaunch {
45
+ if (env[CLI_CHILD_NICE_ENV] === '0' || (platform !== 'darwin' && platform !== 'linux') || !command || !niceAvailable()) {
46
+ return { command, args: [...args], preApplied: false };
47
+ }
48
+ return { command: POSIX_NICE_BINARY, args: ['-n', String(CLI_CHILD_NICE_INCREMENT), command, ...args], preApplied: true };
49
+ }
50
+
51
+ interface PriorityDependencies {
52
+ platform: NodeJS.Platform;
53
+ getPriority: typeof os.getPriority;
54
+ setPriority: typeof os.setPriority;
55
+ setDarwinBackground?: typeof setDarwinBackground;
56
+ }
57
+
58
+ /** Separate policy instances are useful for platform/error tests. */
59
+ export function createCliChildPriorityPolicy(deps: PriorityDependencies = {
60
+ platform: process.platform,
61
+ getPriority: os.getPriority,
62
+ setPriority: os.setPriority,
63
+ setDarwinBackground,
64
+ }) {
65
+ let failureLogged = false;
66
+ return function spawnCliChild<T extends { readonly pid?: number }>(
67
+ spawnChild: () => T,
68
+ env: NodeJS.ProcessEnv = process.env,
69
+ logInfo: (message: string) => void = console.info,
70
+ opts: { preApplied?: boolean } = {},
71
+ ): T {
72
+ const child = spawnChild();
73
+ const pid = child.pid;
74
+ // Never pass 0/undefined to setPriority: that would lower the IPC owner!
75
+ if (env[CLI_CHILD_NICE_ENV] === '0' || typeof pid !== 'number' || !Number.isInteger(pid) || pid <= 0) return child;
76
+ const onFailure = (error: unknown) => {
77
+ if (!failureLogged) {
78
+ failureLogged = true;
79
+ const detail = error instanceof Error ? error.message : String(error);
80
+ logInfo(`[cli-child-priority] Could not apply CLI child scheduling (pid ${pid}); continuing: ${detail}`);
81
+ }
82
+ };
83
+ // Launched through niceLaunch: already lowered from birth; lowering again
84
+ // would stack a second increment.
85
+ if (!opts.preApplied) {
86
+ try {
87
+ const priority = deps.platform === 'win32'
88
+ ? os.constants.priority.PRIORITY_BELOW_NORMAL
89
+ : Math.min(19, deps.getPriority(pid) + CLI_CHILD_NICE_INCREMENT);
90
+ deps.setPriority(pid, priority);
91
+ } catch (error) {
92
+ // EACCES/EPERM (policy/permissions) and ESRCH (already exited), as well
93
+ // as unexpected OS errors, are best effort. Never fail a CLI launch.
94
+ onFailure(error);
95
+ }
96
+ }
97
+ if (deps.platform === 'darwin' && env[CLI_CHILD_SCHEDULING_ENV] === 'darwin-bg') {
98
+ try { deps.setDarwinBackground?.(pid, onFailure); } catch (error) { onFailure(error); }
99
+ }
100
+ return child;
101
+ };
102
+ }
103
+
104
+ /**
105
+ * Only wrap agent workload spawns. Keep daemon, session-host IPC, P2P signal
106
+ * workers, version probes and git helpers at their existing priority.
107
+ *
108
+ * node-pty has no pre-spawn priority hook. Apply immediately on return, before
109
+ * registering listeners/doing other work. There is a spawn-to-setPriority race:
110
+ * a child can run (and fork) before this call. Later descendants inherit nice
111
+ * on POSIX; early descendants are not retroactively changed. Windows creation
112
+ * and ConPTY inheritance require verification on the DesktopA.
113
+ * Optional darwin-bg is applied asynchronously by taskpolicy after nice; the
114
+ * extra helper startup adds a further race before the background class takes
115
+ * effect. It also throttles I/O, so nice alone remains the default.
116
+ */
117
+ export const spawnCliChild = createCliChildPriorityPolicy();
@@ -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
@@ -1,4 +1,8 @@
1
1
  export type {
2
+ MeshWriterAssignment,
3
+ MeshWriterStopTarget,
4
+ StopMeshWriterPayload,
5
+ HostUpgradeLeasePayload,
2
6
  AcquireWritePayload,
3
7
  AttachSessionPayload,
4
8
  ClearSessionBufferPayload,
@@ -20,6 +24,7 @@ export type {
20
24
  SessionBufferSnapshot,
21
25
  SessionClientType,
22
26
  SessionHostDiagnostics,
27
+ SessionHostCensus,
23
28
  SessionHostDuplicateSessionGroup,
24
29
  SessionHostCategory,
25
30
  SessionHostSurfaceKind,
@@ -45,10 +50,24 @@ export type {
45
50
  SessionHostWireEnvelope,
46
51
  SessionWriteOwner,
47
52
  StopSessionPayload,
53
+ SessionCleanupExpectedAssignment,
54
+ StopSessionIfExpectedPayload,
55
+ DeleteSessionIfExpectedPayload,
48
56
  } from './types.js';
49
57
 
50
58
  export { SESSION_HOST_SUPPORTED_REQUEST_TYPES } from './types.js';
59
+ export {
60
+ CLEANUP_AFTER_STOP_SIDE_EFFECT_PREFIX,
61
+ tagCleanupAfterStopSideEffect,
62
+ stripCleanupAfterStopSideEffect,
63
+ hostBootIdFromStartedAt,
64
+ resolveHostBootId,
65
+ refuseCleanupExpectedStop,
66
+ refuseCleanupExpectedDelete,
67
+ } from './cleanup-expected.js';
51
68
  export { classifyTermination } from './termination.js';
69
+ export { CLI_CHILD_NICE_INCREMENT, CLI_CHILD_NICE_ENV, CLI_CHILD_SCHEDULING_ENV, createCliChildPriorityPolicy, niceLaunch, spawnCliChild, type NiceLaunch } from './cli-child-priority.js';
70
+ export { hiddenSpawn as hiddenSpawnProcess } from './process/hidden-spawn.js';
52
71
 
53
72
  export { DEFAULT_SESSION_RING_BUFFER_MAX_BYTES, SessionRingBuffer } from './buffer.js';
54
73
  export type { SessionRingBufferOptions } from './buffer.js';
@@ -73,7 +92,10 @@ export {
73
92
  SessionHostClient,
74
93
  createLineParser,
75
94
  createResponseEnvelope,
95
+ disconnectSessionHostClients,
96
+ findConnectedSessionHostClient,
76
97
  getDefaultSessionHostEndpoint,
98
+ validateSessionHostEndpoint,
77
99
  writeEnvelope,
78
100
  } from './ipc.js';
79
101
  export type {
@@ -85,6 +107,7 @@ export type {
85
107
  } from './ipc.js';
86
108
  export {
87
109
  DEFAULT_CONFIG_DIR_NAME,
110
+ assertTestStorageIsolated,
88
111
  canonicalizeInstancePath,
89
112
  isDefaultInstanceConfigDir,
90
113
  resolveInstanceConfigDir,
@@ -98,6 +121,7 @@ export {
98
121
  } from './defaults.js';
99
122
  export {
100
123
  sanitizeSpawnEnv,
124
+ replayLaunchEnv,
101
125
  applyTerminalColorEnv,
102
126
  ensureNodePtySpawnHelperPermissions,
103
127
  } from './spawn-env.js';
@@ -28,6 +28,23 @@ import * as path from 'path';
28
28
 
29
29
  export const DEFAULT_CONFIG_DIR_NAME = '.adhdev';
30
30
 
31
+ /** Last-line storage guard, shared by session-host and mesh persistence.
32
+ * Node's test runner propagates NODE_TEST_CONTEXT to children; Vitest marks
33
+ * its workers separately. Explicit temporary roots remain valid. */
34
+ export function assertTestStorageIsolated(destination: string): void {
35
+ const env = process.env;
36
+ if (!env.VITEST && env.NODE_ENV !== 'test' && !env.NODE_TEST_CONTEXT
37
+ && !process.execArgv.some(arg => arg === '--test' || arg.startsWith('--test='))) return;
38
+ const target = canonicalizeInstancePath(destination);
39
+ const home = os.userInfo().homedir;
40
+ for (const track of ['.adhdev', '.adhdev-preview']) {
41
+ const live = canonicalizeInstancePath(path.join(home, track));
42
+ if (target === live || target.startsWith(live + path.sep)) {
43
+ throw new Error('LIVE runtime storage is forbidden in a test process; pin ADHDEV_CONFIG_DIR or storageRootDir to a temporary directory');
44
+ }
45
+ }
46
+ }
47
+
31
48
  /**
32
49
  * Resolve the instance config dir from the environment: ADHDEV_CONFIG_DIR
33
50
  * when set (trimmed), else `<homeDir>/.adhdev`. Mirrors daemon-core's
@@ -49,7 +66,9 @@ export function resolveInstanceConfigDir(
49
66
  homeDir: string = os.homedir(),
50
67
  ): string {
51
68
  const override = typeof env.ADHDEV_CONFIG_DIR === 'string' ? env.ADHDEV_CONFIG_DIR.trim() : '';
52
- return override || path.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
69
+ const resolved = override || path.join(homeDir, DEFAULT_CONFIG_DIR_NAME);
70
+ if (env === process.env) assertTestStorageIsolated(resolved);
71
+ return resolved;
53
72
  }
54
73
 
55
74
  /**