Skip to content

Commit bd15e4a

Browse files
committed
fix(host-kit): require a host-confirmed identity before SIGKILL
judgeProcessIdentity is the one rule for whether host facts name a recorded process: exited, reassigned, ours or unverified. stopProcessAndConfirmExit applies it before the graceful signal and again before SIGKILL, so a ps that stops answering during the grace period retains the process instead of sending SIGKILL blind. A stopped verdict reports reassigned when the proof was a pid that now names another process. The app-log terminate uses the stop's own proof as its only identity check and maps a reassigned pid to ownership-lost. The app-log inspect and the recording marker evidence keep their both-facts rule on top of the shared judgment. Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016qAu53rMak1bXMuR5U2gF4
1 parent 2fe6b73 commit bd15e4a

6 files changed

Lines changed: 142 additions & 93 deletions

‎packages/host-kit/src/internal/host-process-stop-confirm.test.ts‎

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,8 @@ type HostCase = Readonly<{
6666
psFails?: boolean;
6767
/** The command line the process shows once it has received this signal, as after an `exec`. */
6868
commandAfterSignal?: Readonly<{ signal: Signal; command: string }>;
69+
/** The signal after which the host refuses every `ps`, as one too loaded to answer. */
70+
psFailsAfterSignal?: Signal;
6971
/** The opening signal the caller names for its stop. */
7072
gracefulSignal?: 'SIGTERM' | 'SIGINT';
7173
/** The signals the stop must spend, in order, and the verdict each host answer earns. */
@@ -89,6 +91,8 @@ const STOPPED_BY_KILL: Expect = {
8991
signals: ['SIGTERM', 'SIGKILL'],
9092
};
9193
const NEVER_SIGNALED: Expect = { outcome: STOPPED, signals: [] };
94+
/** The pid was proven to name another process before anything was signaled. */
95+
const REASSIGNED: Expect = { outcome: { status: 'stopped', reassigned: true }, signals: [] };
9296
const REFUSED_ON_TERM: Expect = { outcome: refused('SIGTERM'), signals: ['SIGTERM'] };
9397
const REFUSED_ON_KILL: Expect = { outcome: refused('SIGKILL'), signals: STOPPED_BY_KILL.signals };
9498
const EXIT_TIMED_OUT: Expect = {
@@ -200,7 +204,10 @@ const STOP_CASES: HostCase[] = [
200204
name: 'execs another program while it is given its grace period',
201205
commandAfterSignal: { signal: 'SIGTERM', command: '/usr/bin/other --serve' },
202206
...HELD,
203-
expect: { outcome: STOPPED_BY_TERM.outcome, signals: ['SIGTERM'] },
207+
expect: {
208+
outcome: { status: 'stopped', signal: 'SIGTERM', reassigned: true },
209+
signals: ['SIGTERM'],
210+
},
204211
},
205212
{
206213
name: 'finalizes on the interrupt its caller opens with',
@@ -217,17 +224,26 @@ const STOP_CASES: HostCase[] = [
217224
{
218225
name: 'pid the host has handed to another lifetime',
219226
identity: { startTime: OTHER_START },
220-
expect: NEVER_SIGNALED,
227+
expect: REASSIGNED,
221228
},
222229
{
223230
name: 'pid whose command line names a different program',
224231
identity: { command: '/usr/bin/other --serve' },
225-
expect: NEVER_SIGNALED,
232+
expect: REASSIGNED,
233+
},
234+
{
235+
// A `ps` that stops answering under load after the grace period is not permission for SIGKILL:
236+
// every signal needs a host-confirmed identity.
237+
name: 'stops being described by the host during its grace period',
238+
psFailsAfterSignal: 'SIGTERM',
239+
...HELD,
240+
expect: { outcome: UNVERIFIED.outcome, signals: ['SIGTERM'] },
226241
},
227242
];
228243

229244
function driveHost(model: HostCase): { signals: Signal[] } {
230245
const signals: Signal[] = [];
246+
let psRefused = false;
231247
let ended = false;
232248
let probes = 0;
233249
const hasEnded = () =>
@@ -245,6 +261,7 @@ function driveHost(model: HostCase): { signals: Signal[] } {
245261
}
246262
const name = signal as Signal;
247263
signals.push(name);
264+
if (model.psFailsAfterSignal === name) psRefused = true;
248265
if (model.commandAfterSignal?.signal === name)
249266
identity.command = model.commandAfterSignal.command;
250267
const errno = model.answers?.[name];
@@ -260,7 +277,7 @@ function driveHost(model: HostCase): { signals: Signal[] } {
260277
command: model.identity?.command === undefined ? COMMAND : model.identity.command,
261278
};
262279
mockRunCmd.mockImplementation(async (_command: string, args: readonly string[]) => {
263-
if (model.psFails) return PS_REFUSED;
280+
if (model.psFails || psRefused) return PS_REFUSED;
264281
// A process the host has fully released, and one that left no row, both answer no fields.
265282
if (hasEnded() && model.afterExit !== 'zombie') return EMPTY;
266283
const field = String(args[3]);

‎packages/host-kit/src/internal/host-process.ts‎

Lines changed: 68 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -614,15 +614,16 @@ type StopSignal = GracefulStopSignal | 'SIGKILL';
614614
*
615615
* - `stopped`: the host released the pid, or proved the pid now names a different process.
616616
* `signal` is the last signal this stop sent before that proof, and is absent when the recorded
617-
* process was already gone before anything was signaled.
617+
* process was already gone before anything was signaled. `reassigned` says the proof was a pid
618+
* that now names a different process: the recorded process is gone, but nobody watched it leave.
618619
* - `retained` + `signal-failed`: `signal` was refused by `errno` while the process was there.
619620
* `EPERM` usually means another owner holds it, and later signals are refused by the same check.
620621
* - `retained` + `exit-timeout`: SIGKILL was accepted and the process outlived its budget.
621622
* - `retained` + `identity-unverified`: no recorded claim could be confirmed against a readable fact,
622623
* so nothing proves which process a signal would reach.
623624
*/
624625
export type ConfirmedProcessStop =
625-
| Readonly<{ status: 'stopped'; signal?: StopSignal }>
626+
| Readonly<{ status: 'stopped'; signal?: StopSignal; reassigned?: true }>
626627
| Readonly<{ status: 'retained'; reason: 'signal-failed'; signal: StopSignal; errno: string }>
627628
| Readonly<{ status: 'retained'; reason: 'exit-timeout'; signal: 'SIGKILL' }>
628629
| Readonly<{ status: 'retained'; reason: 'identity-unverified' }>;
@@ -721,13 +722,38 @@ export type ProcessStopBudget = Readonly<{
721722
gracefulSignal?: GracefulStopSignal;
722723
}>;
723724

725+
/**
726+
* What the host's facts say about the process a caller recorded. One rule answers every identity
727+
* question before a signal:
728+
*
729+
* - `exited`: the host shows the pid as a zombie, so the recorded process already terminated.
730+
* - `reassigned`: a readable start time or command contradicts the record, so the pid now names a
731+
* different process and the recorded one is gone.
732+
* - `ours`: at least one recorded claim is confirmed by a readable fact and none is contradicted.
733+
* - `unverified`: no recorded claim is confirmed. A silent host is never permission to signal.
734+
*/
735+
export type ProcessIdentityVerdict = 'ours' | 'exited' | 'reassigned' | 'unverified';
736+
737+
export function judgeProcessIdentity(
738+
expected: ProcessStopIdentity,
739+
facts: HostProcessIdentityFacts,
740+
): ProcessIdentityVerdict {
741+
if (facts.zombie) return 'exited';
742+
if (expected.startTime && facts.startTime && facts.startTime !== expected.startTime) {
743+
return 'reassigned';
744+
}
745+
if (expected.matches && facts.command && !expected.matches(facts.command)) return 'reassigned';
746+
const confirmedStartTime = Boolean(expected.startTime && facts.startTime);
747+
const confirmedCommand = Boolean(expected.matches && facts.command);
748+
return confirmedStartTime || confirmedCommand ? 'ours' : 'unverified';
749+
}
750+
724751
/**
725752
* The one TERM-then-KILL escalation in host-kit. Signals one process gracefully, waits the grace
726753
* period, re-proves identity, then sends SIGKILL, and proves which way the recorded process ended
727-
* so a caller only forgets one it watched leave. Identity settles it both ways: unreadable
728-
* identity retains rather than signaling a process this caller cannot name, while a released pid,
729-
* a zombie, a start time the host contradicts, or a command `identity.matches` rejects proves it
730-
* gone. A refusal is not absence, so each stage waits.
754+
* so a caller only forgets one it watched leave. Every signal needs a host-confirmed identity
755+
* ({@link judgeProcessIdentity}): an unreadable identity before either signal retains rather than
756+
* signaling a process this caller cannot name. A refusal is not absence, so each stage waits.
731757
*/
732758
export async function stopProcessAndConfirmExit(
733759
target: ProcessStopTarget,
@@ -736,39 +762,41 @@ export async function stopProcessAndConfirmExit(
736762
// Stale or malformed process state must never aim a signal at the caller itself.
737763
if (target.pid === process.pid) throw new RangeError('Cannot stop the current process');
738764
const identity = await proveStopTargetIdentity(target);
739-
if (identity === 'gone') return { status: 'stopped' };
765+
if (identity === 'released' || identity === 'exited') return { status: 'stopped' };
766+
if (identity === 'reassigned') return { status: 'stopped', reassigned: true };
740767
if (identity === 'unverified') return { status: 'retained', reason: 'identity-unverified' };
741768
const graceful = budget.gracefulSignal ?? 'SIGTERM';
742769
const term = await proveSignalStage(target, graceful, budget.termTimeoutMs);
743-
if (term.proof === 'exited') return { status: 'stopped', signal: graceful };
744-
// A refused graceful signal is the whole verdict: the host refuses SIGKILL by the same
745-
// permission check, so escalating would spend a second budget repeating it.
746-
if (term.proof === 'refused') return retainedSignalFailure(graceful, term.errno);
770+
if (term.proof !== 'survived') return stageVerdict(term, graceful);
747771
const kill = await proveSignalStage(target, 'SIGKILL', budget.killTimeoutMs);
748-
if (kill.proof === 'exited') return { status: 'stopped', signal: 'SIGKILL' };
749-
if (kill.proof === 'refused') return retainedSignalFailure('SIGKILL', kill.errno);
772+
if (kill.proof !== 'survived' && kill.proof !== 'unverified')
773+
return stageVerdict(kill, 'SIGKILL');
750774
return { status: 'retained', reason: 'exit-timeout', signal: 'SIGKILL' };
751775
}
752776

777+
/** The verdict a signal stage settles on its own, before any further signal. */
778+
function stageVerdict(
779+
stage: Exclude<SignalStageProof, { proof: 'survived' }>,
780+
signal: StopSignal,
781+
): ConfirmedProcessStop {
782+
if (stage.proof === 'exited') return { status: 'stopped', signal };
783+
if (stage.proof === 'reassigned') return { status: 'stopped', signal, reassigned: true };
784+
// A refused graceful signal is the whole verdict: the host refuses SIGKILL by the same
785+
// permission check, so escalating would spend a second budget repeating it.
786+
if (stage.proof === 'refused') return retainedSignalFailure(signal, stage.errno);
787+
// The pid outlived the grace period and the host will not say what it is now.
788+
return { status: 'retained', reason: 'identity-unverified' };
789+
}
790+
753791
/**
754792
* Whether the live pid still names the process the caller recorded, read once before anything is
755-
* signaled. `ours` needs a claim the host confirmed: two recorded facts that no readable fact
756-
* contradicts only prove the host is silent, and silence about a pid this caller may not own is
757-
* exactly what must not become permission to signal it.
793+
* signaled. `released` is a pid `kill(pid, 0)` no longer finds; the rest is {@link judgeProcessIdentity}.
758794
*/
759795
async function proveStopTargetIdentity(
760796
target: ProcessStopTarget,
761-
): Promise<'ours' | 'gone' | 'unverified'> {
762-
if (!isStopPidLive(target.pid)) return 'gone';
763-
const facts = await readProcessIdentityFacts(target.pid);
764-
if (facts.zombie) return 'gone';
765-
if (target.identity.startTime && facts.startTime && facts.startTime !== target.identity.startTime)
766-
return 'gone';
767-
if (target.identity.matches && facts.command && !target.identity.matches(facts.command))
768-
return 'gone';
769-
const confirmedStartTime = Boolean(target.identity.startTime && facts.startTime);
770-
const confirmedCommand = Boolean(target.identity.matches && facts.command);
771-
return confirmedStartTime || confirmedCommand ? 'ours' : 'unverified';
797+
): Promise<ProcessIdentityVerdict | 'released'> {
798+
if (!isStopPidLive(target.pid)) return 'released';
799+
return judgeProcessIdentity(target.identity, await readProcessIdentityFacts(target.pid));
772800
}
773801

774802
function retainedSignalFailure(signal: StopSignal, errno: string): ConfirmedProcessStop {
@@ -777,10 +805,15 @@ function retainedSignalFailure(signal: StopSignal, errno: string): ConfirmedProc
777805

778806
/** What one signal stage proved, within the budget that stage was given. */
779807
type SignalStageProof =
780-
| Readonly<{ proof: 'exited' }>
781-
| Readonly<{ proof: 'refused'; errno: string }>
782-
| Readonly<{ proof: 'survived' }>;
808+
| Readonly<{ proof: 'exited' | 'reassigned' | 'unverified' | 'survived' }>
809+
| Readonly<{ proof: 'refused'; errno: string }>;
783810

811+
/**
812+
* Sends one signal and waits its budget. A pid that outlives the budget is judged again, which is
813+
* also the identity proof the next signal needs: `kill(pid, 0)` cannot tell, because `EPERM` also
814+
* comes back for a zombie awaiting its parent, and on Windows for a process that exited while its
815+
* object still had handles.
816+
*/
784817
async function proveSignalStage(
785818
target: ProcessStopTarget,
786819
signal: StopSignal,
@@ -791,8 +824,11 @@ async function proveSignalStage(
791824
// owner may release it inside this budget, and a released pid is what the caller may forget.
792825
if (errno === 'ESRCH') return { proof: 'exited' };
793826
if (await waitForStopPidRelease(target.pid, timeoutMs)) return { proof: 'exited' };
794-
if (await proveRecordedProcessGone(target)) return { proof: 'exited' };
795-
return errno === undefined ? { proof: 'survived' } : { proof: 'refused', errno };
827+
const verdict = await proveStopTargetIdentity(target);
828+
if (verdict === 'released' || verdict === 'exited') return { proof: 'exited' };
829+
if (verdict === 'reassigned') return { proof: 'reassigned' };
830+
if (errno !== undefined) return { proof: 'refused', errno };
831+
return { proof: verdict === 'unverified' ? 'unverified' : 'survived' };
796832
}
797833

798834
const STOP_LIVENESS_POLL_MS = 50;
@@ -824,22 +860,6 @@ async function waitForStopPidRelease(pid: number, timeoutMs: number): Promise<bo
824860
}
825861
}
826862

827-
/**
828-
* Whether the pid outliving its budget still proves the recorded process is gone, which the answer to
829-
* `kill(pid, 0)` cannot: `EPERM` also comes back for a zombie awaiting its parent, and on Windows for
830-
* a process that exited while its object still had handles. A start time the host contradicts proves
831-
* the pid changed hands, and a command `identity.matches` rejects proves it no longer runs what this
832-
* stop was meant for, so the next stage never signals it; the process table holding no row does not,
833-
* because a hidden or unreadable process is missing from it too.
834-
*/
835-
async function proveRecordedProcessGone(target: ProcessStopTarget): Promise<boolean> {
836-
const facts = await readProcessIdentityFacts(target.pid);
837-
if (facts.zombie) return true;
838-
const { startTime, matches } = target.identity;
839-
if (startTime && facts.startTime && facts.startTime !== startTime) return true;
840-
return Boolean(matches && facts.command && !matches(facts.command));
841-
}
842-
843863
/** The errno that refused the signal, or `undefined` when the host accepted it. */
844864
function signalProcessForStop(pid: number, signal: StopSignal): string | undefined {
845865
// A non-positive pid is no process at all: `kill(0, …)` would address our own process group.

‎packages/host-kit/src/process.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ export {
1717
isProcessAlive,
1818
isProcessGroupAlive,
1919
isProcessZombie,
20+
judgeProcessIdentity,
2021
listHostProcesses,
22+
type ProcessIdentityVerdict,
2123
type ProcessStopBudget,
2224
type ProcessStopIdentity,
2325
type ProcessStopTarget,

‎src/platform-runtime-app-log-process.test.ts‎

Lines changed: 22 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -16,29 +16,31 @@ vi.mock('@agent-device/host-kit/command', async (importOriginal) => ({
1616
...(await importOriginal<typeof import('@agent-device/host-kit/command')>()),
1717
runCmdBackground: exec.run,
1818
}));
19-
vi.mock('@agent-device/host-kit/process', async (importOriginal) => ({
20-
...(await importOriginal<typeof import('@agent-device/host-kit/process')>()),
21-
isProcessAlive: () => processIdentity.alive,
22-
readProcessIdentityFacts: async () => ({
19+
vi.mock('@agent-device/host-kit/process', async (importOriginal) => {
20+
const actual = await importOriginal<typeof import('@agent-device/host-kit/process')>();
21+
const facts = () => ({
2322
startTime: processIdentity.startTime,
2423
command: processIdentity.command,
2524
zombie: processIdentity.alive ? false : null,
26-
}),
27-
// The shared escalation is host-kit's to prove; here it answers from the same fixture identity.
28-
stopProcessAndConfirmExit: async (target: {
29-
pid: number;
30-
identity: { startTime?: string; matches?: (command: string) => boolean };
31-
}) => {
32-
if (!processIdentity.alive) return { status: 'stopped' };
33-
const confirmed =
34-
processIdentity.startTime === target.identity.startTime &&
35-
processIdentity.command !== null &&
36-
target.identity.matches?.(processIdentity.command) === true;
37-
if (!confirmed) return { status: 'retained', reason: 'identity-unverified' };
38-
process.kill(target.pid, 'SIGTERM');
39-
return { status: 'stopped', signal: 'SIGTERM' };
40-
},
41-
}));
25+
});
26+
return {
27+
...actual,
28+
isProcessAlive: () => processIdentity.alive,
29+
readProcessIdentityFacts: async () => facts(),
30+
// The escalation's signal ladder is host-kit's to prove; here it answers from the fixture
31+
// identity through the same identity rule.
32+
stopProcessAndConfirmExit: async (
33+
target: Parameters<typeof actual.stopProcessAndConfirmExit>[0],
34+
) => {
35+
if (!processIdentity.alive) return { status: 'stopped' };
36+
const verdict = actual.judgeProcessIdentity(target.identity, facts());
37+
if (verdict === 'reassigned') return { status: 'stopped', reassigned: true };
38+
if (verdict !== 'ours') return { status: 'retained', reason: 'identity-unverified' };
39+
process.kill(target.pid, 'SIGTERM');
40+
return { status: 'stopped', signal: 'SIGTERM' };
41+
},
42+
};
43+
});
4244

4345
import {
4446
createManagedAppLogProcesses,

‎src/platform-runtime-app-log-process.ts‎

Lines changed: 17 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@ import { openVerifiedFileForRead } from '@agent-device/host-kit/file';
2020
import { runCmdBackground } from '@agent-device/host-kit/command';
2121
import {
2222
isProcessAlive,
23+
judgeProcessIdentity,
2324
readProcessIdentityFacts,
2425
stopProcessAndConfirmExit,
26+
type ProcessStopIdentity,
2527
} from '@agent-device/host-kit/process';
2628

2729
import { requireManagedSessionArtifactPath } from '@agent-device/daemon-contracts/session-artifact-paths';
@@ -401,35 +403,32 @@ function requireManagedMarkerPath(root: string, markerPath: string): string {
401403
});
402404
}
403405

406+
function markerIdentity(marker: AppLogProcessMarker): ProcessStopIdentity {
407+
return { startTime: marker.startTime, matches: (command) => command === marker.command };
408+
}
409+
410+
/** Owned only while both recorded facts are confirmed, under the shared identity rule. */
404411
async function inspectOwnedProcess(marker: AppLogProcessMarker): Promise<AppLogProcessOwnership> {
405412
if (!isProcessAlive(marker.pid)) return 'missing';
406413
const facts = await readProcessIdentityFacts(marker.pid);
407-
if (facts.zombie) return 'missing';
408-
const matches =
409-
marker.startTime.length > 0 &&
410-
marker.command.length > 0 &&
411-
facts.startTime === marker.startTime &&
412-
facts.command === marker.command;
413-
return matches ? 'owned-alive' : 'ownership-lost';
414+
const verdict = judgeProcessIdentity(markerIdentity(marker), facts);
415+
if (verdict === 'exited') return 'missing';
416+
const bothConfirmed = facts.startTime !== null && facts.command !== null;
417+
return verdict === 'ours' && bothConfirmed ? 'owned-alive' : 'ownership-lost';
414418
}
415419

416420
/**
417-
* Stops the marked process through the shared TERM-then-KILL escalation, which re-proves the
418-
* marker's identity before each signal. A marker the host does not confirm is never signaled.
421+
* Stops the marked process through the shared TERM-then-KILL escalation, whose own identity proof
422+
* before each signal is the only check. A pid proven to name another process is a lost fence, not
423+
* a missing process.
419424
*/
420425
async function terminateOwnedProcess(
421426
marker: AppLogProcessMarker,
422427
): Promise<'terminated' | 'already-missing' | 'ownership-lost'> {
423-
const ownership = await inspectOwnedProcess(marker);
424-
if (ownership === 'missing') return 'already-missing';
425-
if (ownership === 'ownership-lost') return 'ownership-lost';
426428
const stop = await stopProcessAndConfirmExit(
427-
{
428-
pid: marker.pid,
429-
identity: { startTime: marker.startTime, matches: (command) => command === marker.command },
430-
},
429+
{ pid: marker.pid, identity: markerIdentity(marker) },
431430
APP_LOG_STOP_BUDGET,
432431
);
433-
if (stop.status === 'stopped') return stop.signal ? 'terminated' : 'already-missing';
434-
return 'ownership-lost';
432+
if (stop.status !== 'stopped' || stop.reassigned) return 'ownership-lost';
433+
return stop.signal ? 'terminated' : 'already-missing';
435434
}

0 commit comments

Comments
 (0)