Skip to content

Beautiful, AI-native markdown IDE and LLM wiki

feat(lint-rules): gate sentinel-fed signal targets (ok/no-sentinel-signal-target) (#4764)

Nick Gomez118b23b472f0
diff --git a/lint-plugins/ok-rules/README.md b/lint-plugins/ok-rules/README.md
index f42fc3c4d..61464ffb3 100644
--- a/lint-plugins/ok-rules/README.md
+++ b/lint-plugins/ok-rules/README.md
@@ -374,7 +374,7 @@ Flags `animate-spin` in any `className` / `*ClassName` attribute value. Loading
Suppress a legitimately non-`Spinner` spin (a decorative flourish, a non-loading rotation) with `// oxlint-disable-next-line ok/no-hand-rolled-spinner -- <reason>` on the line above the class attribute; the attribute must be on its own line for the suppression to attach.
-Unscoped, like the other five rules in `UNSCOPED_RULES` — it applies wherever a class string can appear.
+Unscoped, like the other rules in `UNSCOPED_RULES` — it applies wherever a class string can appear.
The `\b` delimiter is asymmetric in a way that is easy to misread: `animate-spinner` does NOT fire (the trailing boundary fails against a word character) but `animate-spin-slow` DOES (`-` is a boundary). That is the retired pattern's behaviour, kept deliberately — a slowed hand-rolled spin is still hand-rolled — and both halves are pinned in the fixture.
@@ -637,6 +637,36 @@ The behavioural backstop is [`packages/server/src/git-pathspec-name-invariance.t
Rule: [`lint-plugins/ok-rules/rules/no-unconverted-git-pathspec.mjs`](rules/no-unconverted-git-pathspec.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-unconverted-git-pathspec.fixture.tsx`](__fixtures__/no-unconverted-git-pathspec.fixture.tsx). Test: [`packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts`](../../packages/app/tests/lint-plugins/no-unconverted-git-pathspec.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.
+### `no-sentinel-signal-target`
+
+Owned-process signalling. `process.kill(target, signal)` — and the desktop test-support reaper seam `signalOwnedGroup` / `signalOwnedPids` / `reapOwnedTree` when no sender is injected (that seam is not on `main` yet — it lives on the unmerged `feat/ok-update-relaunch-substrate` branch, and the rule covers it ahead of time so the gate is in place the day it lands) — never receive a target that is (a) a literal `0`, `1` or `-1`, (b) a `?? <n>` / `|| <n>` fallback to a number, or (c) an unvalidated parse of text — `Number(...)`, `parseInt(...)`, `parseFloat(...)`, or the `Number.` spellings of the latter two. A signal-`0` liveness probe (`process.kill(pid, 0)`) sends nothing and is exempt, whatever the target.
+
+**Why.** On POSIX, `kill(0, sig)` signals the caller's whole process group, `kill(-1, sig)` every process the user owns, and `kill(-pid, sig)` a group. On 2026-09-20 and 21 a desktop unit test killed every process on a developer's Mac three times, Terminal included: it called `signalOwnedGroup(1, 'SIGKILL')` to prove a guard refused it, a mutation loop had weakened the guard to `pid > 0`, and `process.kill(-1, …)` went through. The mutation loop was killed before its own revert step, so the mutant stayed on disk and every later run of the suite repeated the kill. The same sentinel shape was already live on `main`: `process.kill(pid ?? 0, 'SIGKILL')` in a test reaper, and `process.kill(Number(readFileSync(pidFile)), 'SIGKILL')` in a `finally` — an empty pidfile parses to `0`. Both shipped green: nothing in `pnpm lint` or `pnpm check` looked at what a kill was fed. Canonical prose: the "Never signal a pid you did not spawn" STOP rule in the workspace `AGENTS.md`, an internal guide the public mirror does not carry; this rule encodes its decidable subset and the two are kept in step by the fixture test.
+
+**Sanctioned shapes.** Every shape in this list works on this head and needs no seam; only the injected sender below waits on one.
+
+- **Signal the handle you spawned** — `child.kill(signal)`.
+- **Or a pid you took from that handle** — `child.pid`, wrapped or negated for its group. Negation reaches a group only if you spawned it detached, since `-pid` addresses the group whose pgid is that pid and an ordinary child leads none; on a non-detached child it raises `ESRCH`, which a `catch {}` around the kill turns into a surviving process.
+- **Negation is not laundering.** `-<expr>` is judged by exactly the same tests as `<expr>`, so `-(pid ?? 0)` fires just as `pid ?? 0` does, and only a pid already taken from a handle or already validated survives the minus sign.
+- **Filter a nullable pid out of a list** instead of substituting a sentinel.
+- **Validate a pid parsed from a file or a `ps` row** with `isValidLockPid()` from `@inkeep/open-knowledge-server` before signalling it.
+- **Worked exemplar, on this head.** `spawnDeck`'s reaper in [`ok-bin-child-spawn-path.test.ts`](../../packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts) signals an `isValidLockPid`-validated `ps` row with `process.kill(pid, 'SIGKILL')` and takes its group down with `process.kill(-shellPid, 'SIGKILL')`, the negation sound there because that child came from `spawnDetachedInteractiveChild`. That reaper is itself one of the sites the **Direct `process.kill` of spawned-child pids in tests outside the seam** bullet below schedules for seam migration: sanctioned to write on this head, expected to move once the seam lands, and not a defect in the meantime.
+
+**The reaper seam is what is absent.** `signalOwnedGroup`, `signalOwnedPids`, `reapOwnedTree` and `recordingSignalSender` have no definition on this head, so the seam's own sanctioned shape — an injected sender — is the one thing you cannot write here yet. Once the seam lands, a guard test that must feed it a sentinel passes `recordingSignalSender().send` — not the recorder itself — in the sender slot, which is the third argument to `signalOwnedGroup` and `signalOwnedPids` but the fourth to `reapOwnedTree`, and asserts the recorded calls. The rule stops firing only when a real sender value occupies that slot: passing `undefined` or `void 0` explicitly injects nothing and still fires, and passing `process.kill` itself is no escape either.
+
+The rule does NOT catch:
+
+- **A sentinel held in a variable** (`const target = 1; process.kill(target, …)`) or a `ps`-parsed pid that reaches a kill through an untyped variable — data flow the untyped AST cannot see, left to the STOP rule and review.
+- **A guard weakened inside the seam** — that is what the seam's injected sender exists for, since the mutant then fails a test instead of the host.
+- **Direct `process.kill` of spawned-child pids in tests outside the seam** — 27 such sites exist on `main` and a structural rule routing them through the seam waits until the seam itself lands on `main`.
+- **Anything `oxlint.config.ts` excludes from selection** — `ignorePatterns` drops `/reports/**` and `/specs/**` before any rule sees them, and naming such a file positionally on the command line does not override it. Those two trees hold 110 executable `.ts`/`.mjs`/`.js` files, 5 of which call `process.kill` today; they are the local spike-harness class of script this incident came from, and no oxlint rule reaches them. See [§3 of the authoring guide](#3-scope-it-if-it-is-not-workspace-wide) for the measurement.
+
+**Unscoped** (workspace-wide in the scope table's sense — it carries no `RULE_SCOPES` entry and sits in `UNSCOPED_RULES` in [`scope.mjs`](scope.mjs), so nothing here narrows it; selection still excludes the trees named just above): a fabricated signal target is wrong in every package, and in test code most of all.
+
+**Opting out.** There is no legitimate sentinel signal target. A liveness probe is already exempt by its signal argument; anything else is fixed at the source, not suppressed.
+
+Rule: [`lint-plugins/ok-rules/rules/no-sentinel-signal-target.mjs`](rules/no-sentinel-signal-target.mjs). Fixture: [`lint-plugins/ok-rules/__fixtures__/no-sentinel-signal-target.fixture.tsx`](__fixtures__/no-sentinel-signal-target.fixture.tsx). Test: [`packages/server/src/lint-plugins/no-sentinel-signal-target.test.ts`](../../packages/server/src/lint-plugins/no-sentinel-signal-target.test.ts). See [PRECEDENTS.md #42](../../PRECEDENTS.md#custom-lint-enforcement-precedent-42) for the custom-rule convention.
+
## Suppression
Inline `// oxlint-disable-next-line` comments silence individual diagnostics. The form names the plugin, the rule and the reason:
@@ -714,6 +744,8 @@ Add a `RULE_SCOPES['<rule-name>']` entry in [`scope.mjs`](scope.mjs): an array o
Scope lives here rather than in `oxlint.config.ts#overrides` because **oxlint's `overrides[].files` does not honour `!` negation** (measured on oxlint 1.66.0: with the rule `off` at root and an override of `files: ['lint-plugins/ok-rules/__fixtures__/**', '!**/*.fixture.tsx']`, the rule still fired on the excluded fixture — the negative glob did not subtract from the positive one. Re-check this on an oxlint upgrade; if negation lands, this whole scope table becomes revisitable) — a negative glob in that list does not subtract from a positive one, so an override-scoped rule silently fires on its exclusions. Biome's `includes` did honour it, which is why the rules this replaced could scope in config.
+**Workspace-wide is a claim about this table, not about oxlint.** A rule with no `RULE_SCOPES` entry is one no entry here narrows; it is not a rule oxlint feeds every file in the repo. Selection happens first and is narrower: `ignorePatterns` in [`oxlint.config.ts`](../../oxlint.config.ts) drops `/reports/**`, `/specs/**`, `.agents/skills/**`, `.codex/skills/**` and the fixtures directory before any rule sees them, and naming one of those files positionally on the command line does not override it (measured on oxlint 1.80.0: `--debug=files` prints nothing for such a file while a control under `packages/` is listed, and `--no-ignore` does not rescue it — that flag governs `.gitignore`, not this list). The pre-push lane is narrower still, since `lint-staged` routes only `packages/**`, `docs/**`, `{scripts,.github/scripts}/**/*.mjs` and root `*.ts` through oxlint.
+
### 4. Author the fixture file
Drop `<rule-name>.fixture.tsx` in `__fixtures__/`, pairing positive cases (must fire) with negative cases (must NOT fire), each labelled. Include a boundary negative: the nearest shape the rule must NOT match. The directory is in `oxlint.config.ts#ignorePatterns` so the deliberately-bad content does not break the main lint; `__fixtures__/oxlint.fixtures.json` re-enables every rule for the tests.
diff --git a/lint-plugins/ok-rules/__fixtures__/no-sentinel-signal-target.fixture.tsx b/lint-plugins/ok-rules/__fixtures__/no-sentinel-signal-target.fixture.tsx
new file mode 100644
index 000000000..2ccdd73a9
--- /dev/null
+++ b/lint-plugins/ok-rules/__fixtures__/no-sentinel-signal-target.fixture.tsx
@@ -0,0 +1,110 @@
+// FIXTURE — drives `no-sentinel-signal-target.test.ts` via shell-out to
+// `pnpm exec oxlint`. Not part of the main lint: `__fixtures__/` is in
+// `oxlint.config.ts#ignorePatterns`; `__fixtures__/oxlint.fixtures.json`
+// re-enables the rules for the test.
+//
+// 20 expected diagnostic fires, split by message branch:
+// literal target (10): P1 process.kill(0), P2 process.kill(1), P3 process.kill(-1),
+// P8 signalOwnedGroup(1), P9 signalOwnedPids([0, 1, -1]), P11 reapOwnedTree(1),
+// P12 signalOwnedGroup(1, …, process.kill) — a real sender passed explicitly,
+// P18 signalOwnedGroup(1, …, undefined), P19 signalOwnedGroup(1, …, void 0),
+// P20 reapOwnedTree(1, 500, undefined, undefined) — an explicit `undefined`
+// injects no sender, so it must not suppress
+// fallback target (4): P4 `pid ?? 0`, P5 `supervisor || -1`,
+// P10 signalOwnedPids([…, supervisor ?? -1]), P13 `-(pid ?? 0)`
+// parsed target (6): P6 Number(readFileSync(...)), P7 parseInt(...),
+// P14 `-Number(readFileSync(...))`, P15 Number.parseInt(...),
+// P16 Number.parseFloat(...), P17 parseFloat(...)
+//
+// Negatives (0 fires): the signal-0 liveness probe on pid 1 (boundary pair with
+// P2), an `as number`-wrapped spawned pid, a group kill of a spawned pid
+// (`-(child.pid as number)` and bare `-spawnedPid`), the ChildProcess handle, `kill` on
+// a non-`process` object, the method in a type declaration, the seam with an injected
+// recorder — including one threaded past an explicit `undefined` pollMs — a
+// null-filtered pid list, a validated parsed pid, and `?? -1` outside a kill.
+// Exact-equality (`toBe(20)` plus the per-branch counts) catches false-negative
+// regressions and false-positive widenings alike.
+
+type Signal = 'SIGKILL' | 'SIGTERM';
+type SignalSender = (pid: number, signal: Signal) => void;
+declare function readFileSync(path: string, encoding: 'utf8'): string;
+declare function signalOwnedGroup(pid: number, signal: Signal, send?: SignalSender): boolean;
+declare function signalOwnedPids(
+ pids: readonly number[],
+ signal: Signal,
+ send?: SignalSender,
+): number[];
+declare function reapOwnedTree(
+ rootPid: number,
+ graceMs: number,
+ pollMs?: number,
+ send?: SignalSender,
+): Promise<string>;
+declare function isValidLockPid(value: unknown): value is number;
+declare const pid: number | undefined;
+declare const supervisor: number | null;
+declare const descendant: number;
+declare const spawnedPid: number;
+declare const pidFile: string;
+declare const raw: string;
+declare const child: { pid?: number; kill(signal: Signal): boolean };
+declare const killer: { kill(pid: number, signal: Signal): void };
+declare const sender: { send: SignalSender };
+declare const hit: { start?: number } | undefined;
+declare const BODY: string;
+
+// === Positive cases — must fire (20 total) ===
+
+export const p1 = process.kill(0, 'SIGKILL');
+export const p2 = process.kill(1, 'SIGTERM');
+export const p3 = process.kill(-1, 'SIGKILL');
+export const p4 = process.kill(pid ?? 0, 'SIGKILL');
+export const p5 = process.kill(supervisor || -1, 'SIGKILL');
+export const p6 = process.kill(Number(readFileSync(pidFile, 'utf8')), 'SIGKILL');
+export const p7 = process.kill(parseInt(raw, 10), 'SIGTERM');
+export const p8 = signalOwnedGroup(1, 'SIGKILL');
+export const p9 = signalOwnedPids([0, 1, -1], 'SIGKILL');
+export const p10 = signalOwnedPids([descendant, spawnedPid, supervisor ?? -1], 'SIGKILL');
+export const p11 = reapOwnedTree(1, 500);
+export const p12 = signalOwnedGroup(1, 'SIGKILL', process.kill);
+export const p13 = process.kill(-(pid ?? 0), 'SIGKILL');
+export const p14 = process.kill(-Number(readFileSync(pidFile, 'utf8')), 'SIGKILL');
+export const p15 = process.kill(Number.parseInt(raw, 10), 'SIGKILL');
+export const p16 = process.kill(Number.parseFloat(raw), 'SIGTERM');
+export const p17 = process.kill(parseFloat(raw), 'SIGKILL');
+export const p18 = signalOwnedGroup(1, 'SIGKILL', undefined);
+export const p19 = signalOwnedGroup(1, 'SIGKILL', void 0);
+export const p20 = reapOwnedTree(1, 500, undefined, undefined);
+
+// === Negative cases — must NOT fire ===
+
+// (1) Signal 0 sends nothing — the liveness probe, even on pid 1 (boundary pair with P2).
+export const n1 = process.kill(1, 0);
+// (2-3) A spawned pid behind TS wrappers, singly and as its own process group.
+export const n2 = process.kill(child.pid as number, 'SIGKILL');
+export const n3 = process.kill(-(child.pid as number), 'SIGTERM');
+// (4) The ChildProcess handle signals exactly that child.
+export const n4 = child.kill('SIGKILL');
+// (5) Same method name on a non-`process` object — different AST.
+export const n5 = killer.kill(0, 'SIGKILL');
+// (6) The method in a type declaration, not a call.
+export interface Signaller {
+ kill(pid: 0 | 1, signal: Signal): void;
+}
+// (7-8) The seam with an injected recorder — the guard test's sanctioned shape.
+export const n7 = signalOwnedGroup(1, 'SIGKILL', sender.send);
+export const n8 = signalOwnedPids([0, 1, -1], 'SIGKILL', sender.send);
+// (9) A nullable pid filtered out instead of substituted.
+export const n9 = signalOwnedPids(
+ [descendant, spawnedPid, ...(supervisor === null ? [] : [supervisor])],
+ 'SIGKILL',
+);
+// (10) A parsed pid validated before it is signalled.
+const parsed = Number(readFileSync(pidFile, 'utf8'));
+export const n10 = isValidLockPid(parsed) ? process.kill(parsed, 'SIGKILL') : false;
+// (11) `?? -1` outside a kill — an index, not a signal target.
+export const n11 = BODY[hit?.start ?? -1];
+// (12) The same group kill without the TS wrapper — a bare negated spawned pid.
+export const n12 = process.kill(-spawnedPid, 'SIGKILL');
+// (13) The seam's injected recorder threaded past an explicit `undefined` pollMs.
+export const n13 = reapOwnedTree(1, 500, undefined, sender.send);
diff --git a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
index ed5fde4c3..80d86c37e 100644
--- a/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
+++ b/lint-plugins/ok-rules/__fixtures__/oxlint.fixtures.json
@@ -15,6 +15,7 @@
"ok/no-raw-route-hash-construction": "error",
"ok/no-resolved-value-theme-source": "error",
"ok/no-roundtrip-identity-oracle": "error",
+ "ok/no-sentinel-signal-target": "error",
"ok/no-split-suggestion-dispatch": "error",
"ok/no-themeless-pierre-diff": "error",
"ok/no-unconverted-git-pathspec": "error",
diff --git a/lint-plugins/ok-rules/index.mjs b/lint-plugins/ok-rules/index.mjs
index 6830736b6..94054fd0e 100644
--- a/lint-plugins/ok-rules/index.mjs
+++ b/lint-plugins/ok-rules/index.mjs
@@ -14,6 +14,7 @@ import { noRawHtmlInteractiveElement } from './rules/no-raw-html-interactive-ele
import { noRawRouteHashConstruction } from './rules/no-raw-route-hash-construction.mjs';
import { noResolvedValueThemeSource } from './rules/no-resolved-value-theme-source.mjs';
import { noRoundtripIdentityOracle } from './rules/no-roundtrip-identity-oracle.mjs';
+import { noSentinelSignalTarget } from './rules/no-sentinel-signal-target.mjs';
import { noSplitSuggestionDispatch } from './rules/no-split-suggestion-dispatch.mjs';
import { noThemelessPierreDiff } from './rules/no-themeless-pierre-diff.mjs';
import { noUnconvertedGitPathspec } from './rules/no-unconverted-git-pathspec.mjs';
@@ -45,6 +46,7 @@ const declared = {
'no-raw-route-hash-construction': noRawRouteHashConstruction,
'no-resolved-value-theme-source': noResolvedValueThemeSource,
'no-roundtrip-identity-oracle': noRoundtripIdentityOracle,
+ 'no-sentinel-signal-target': noSentinelSignalTarget,
'no-split-suggestion-dispatch': noSplitSuggestionDispatch,
'no-themeless-pierre-diff': noThemelessPierreDiff,
'no-unconverted-git-pathspec': noUnconvertedGitPathspec,
diff --git a/lint-plugins/ok-rules/rules/no-sentinel-signal-target.mjs b/lint-plugins/ok-rules/rules/no-sentinel-signal-target.mjs
new file mode 100644
index 000000000..796802653
--- /dev/null
+++ b/lint-plugins/ok-rules/rules/no-sentinel-signal-target.mjs
@@ -0,0 +1,136 @@
+import { docsUrl } from '../docs.mjs';
+
+const URL = docsUrl('no-sentinel-signal-target');
+
+const LITERAL_MESSAGE = `Signal target is a literal 0, 1 or -1 — on POSIX that addresses the caller's whole process group, init, or every process the user owns, never a child. Signal only a pid you spawned — the ChildProcess handle, or its pid taken from that handle, negated for the group only if you spawned it detached. See ${URL}`;
+const FALLBACK_MESSAGE = `A \`?? <n>\` / \`|| <n>\` fallback fabricates a signal target when the pid is missing, and \`kill(0, …)\` reaches the caller's own process group. Filter the nullable pid out instead of substituting a sentinel. See ${URL}`;
+const PARSED_MESSAGE = `A pid parsed from text reaches \`process.kill\` unvalidated — an empty pidfile yields \`0\` or \`NaN\` depending on the parser, and a stale one yields a pid that now belongs to some other process. Validate it with \`isValidLockPid()\` from @inkeep/open-knowledge-server before signalling. See ${URL}`;
+
+const SEAM_SENDER_INDEX = new Map([
+ ['signalOwnedGroup', 2],
+ ['signalOwnedPids', 2],
+ ['reapOwnedTree', 3],
+]);
+
+const PARSERS = new Set(['Number', 'parseInt', 'parseFloat']);
+
+const WRAPPERS = new Set([
+ 'TSAsExpression',
+ 'TSNonNullExpression',
+ 'TSSatisfiesExpression',
+ 'TSTypeAssertion',
+ 'ParenthesizedExpression',
+]);
+
+function unwrap(node) {
+ let current = node;
+ while (current && WRAPPERS.has(current.type)) current = current.expression;
+ return current;
+}
+
+function isMember(node) {
+ return node?.type === 'MemberExpression';
+}
+
+function numericLiteralValue(node) {
+ const inner = unwrap(node);
+ if (!inner) return undefined;
+ if (inner.type === 'Literal' && typeof inner.value === 'number') return inner.value;
+ if (inner.type === 'UnaryExpression' && inner.operator === '-') {
+ const argument = unwrap(inner.argument);
+ if (argument?.type === 'Literal' && typeof argument.value === 'number') return -argument.value;
+ }
+ return undefined;
+}
+
+function isSentinelLiteral(node) {
+ const value = numericLiteralValue(node);
+ return value === 0 || value === 1 || value === -1;
+}
+
+function isFallbackToLiteral(node) {
+ const inner = unwrap(node);
+ if (inner?.type !== 'LogicalExpression') return false;
+ if (inner.operator !== '??' && inner.operator !== '||') return false;
+ return numericLiteralValue(inner.right) !== undefined;
+}
+
+function isRawParse(node) {
+ const inner = unwrap(node);
+ if (inner?.type !== 'CallExpression') return false;
+ const callee = inner.callee;
+ if (callee?.type === 'Identifier') return PARSERS.has(callee.name);
+ if (isMember(callee) && callee.object?.type === 'Identifier' && callee.object.name === 'Number') {
+ return callee.property?.type === 'Identifier' && PARSERS.has(callee.property.name);
+ }
+ return false;
+}
+
+function classify(node) {
+ if (isSentinelLiteral(node)) return LITERAL_MESSAGE;
+ if (isFallbackToLiteral(node)) return FALLBACK_MESSAGE;
+ if (isRawParse(node)) return PARSED_MESSAGE;
+ const inner = unwrap(node);
+ if (inner?.type === 'UnaryExpression' && inner.operator === '-') return classify(inner.argument);
+ return undefined;
+}
+
+function classifyTarget(node) {
+ const inner = unwrap(node);
+ if (inner?.type !== 'ArrayExpression') return classify(inner);
+ for (const element of inner.elements ?? []) {
+ const message = classify(element);
+ if (message) return message;
+ }
+ return undefined;
+}
+
+function isProcessKill(callee) {
+ return (
+ isMember(callee) &&
+ callee.object?.type === 'Identifier' &&
+ callee.object.name === 'process' &&
+ callee.property?.type === 'Identifier' &&
+ callee.property.name === 'kill'
+ );
+}
+
+function isRealSender(node) {
+ return isProcessKill(unwrap(node));
+}
+
+export const noSentinelSignalTarget = {
+ meta: {
+ type: 'problem',
+ docs: {
+ description:
+ 'process.kill and the owned-process reaper never receive a literal, fallback-fabricated or unvalidated-parsed pid.',
+ url: URL,
+ },
+ },
+ create(context) {
+ return {
+ CallExpression(node) {
+ const callee = node.callee;
+ const args = node.arguments ?? [];
+ if (isProcessKill(callee)) {
+ if (numericLiteralValue(args[1]) === 0) return;
+ const message = classify(args[0]);
+ if (message) context.report({ node, message });
+ return;
+ }
+ if (callee?.type !== 'Identifier') return;
+ const senderIndex = SEAM_SENDER_INDEX.get(callee.name);
+ if (senderIndex === undefined) return;
+ const sender = unwrap(args[senderIndex]);
+ const omitted =
+ !sender ||
+ (sender.type === 'Identifier' && sender.name === 'undefined') ||
+ (sender.type === 'UnaryExpression' && sender.operator === 'void');
+ if (!omitted && !isRealSender(sender)) return;
+ const message = classifyTarget(args[0]);
+ if (message) context.report({ node, message });
+ },
+ };
+ },
+};
diff --git a/lint-plugins/ok-rules/scope.mjs b/lint-plugins/ok-rules/scope.mjs
index aea8c6bf6..1a1244930 100644
--- a/lint-plugins/ok-rules/scope.mjs
+++ b/lint-plugins/ok-rules/scope.mjs
@@ -17,6 +17,7 @@ export const UNSCOPED_RULES = new Set([
'no-hand-rolled-spinner',
'no-loosely-typed-webcontents-ipc',
'no-resolved-value-theme-source',
+ 'no-sentinel-signal-target',
'no-split-suggestion-dispatch',
'no-unportaled-editor-content',
]);
diff --git a/oxlint.config.ts b/oxlint.config.ts
index 37ef515fe..9aa60d0b6 100644
--- a/oxlint.config.ts
+++ b/oxlint.config.ts
@@ -63,6 +63,7 @@ export default defineConfig({
'ok/no-raw-route-hash-construction': 'error',
'ok/no-resolved-value-theme-source': 'error',
'ok/no-roundtrip-identity-oracle': 'error',
+ 'ok/no-sentinel-signal-target': 'error',
'ok/no-split-suggestion-dispatch': 'error',
'ok/no-themeless-pierre-diff': 'error',
'ok/no-unconverted-git-pathspec': 'error',
diff --git a/packages/app/tests/lint-plugins/ok-rules-scope-partition.test.ts b/packages/app/tests/lint-plugins/ok-rules-scope-partition.test.ts
index 936c4bce2..defd7c1e5 100644
--- a/packages/app/tests/lint-plugins/ok-rules-scope-partition.test.ts
+++ b/packages/app/tests/lint-plugins/ok-rules-scope-partition.test.ts
@@ -18,12 +18,13 @@ describe('ok-rules scope table', () => {
expect(scoped.filter((r) => UNSCOPED_RULES.has(r))).toEqual([]);
});
- test('UNSCOPED_RULES holds exactly the six rules that are deliberately global', () => {
+ test('UNSCOPED_RULES holds exactly the rules that are deliberately global', () => {
expect([...UNSCOPED_RULES].sort()).toEqual([
'microcopy-ellipsis',
'no-hand-rolled-spinner',
'no-loosely-typed-webcontents-ipc',
'no-resolved-value-theme-source',
+ 'no-sentinel-signal-target',
'no-split-suggestion-dispatch',
'no-unportaled-editor-content',
]);
diff --git a/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
index 42600740a..727103133 100644
--- a/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
+++ b/packages/desktop/tests/integration/ok-bin-child-spawn-path.test.ts
@@ -12,6 +12,7 @@ import {
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { TERMINAL_CLI_IDS, TERMINAL_CLIS } from '@inkeep/open-knowledge-core';
+import { isValidLockPid } from '@inkeep/open-knowledge-server';
import { afterAll, beforeAll, describe, expect, test, vi } from 'vitest';
const desktopLog = vi.hoisted(() => ({
@@ -299,7 +300,8 @@ function spawnDeck(
env?: NodeJS.ProcessEnv,
) {
const child = spawnDetachedInteractiveChild(shell, [...args.slice(0, -1), command], env);
- const shellPid = child.pid ?? 0;
+ const shellPid = child.pid;
+ if (!isValidLockPid(shellPid)) throw new Error(`no pid for detached ${shell}`);
const descendants = () =>
spawnSync('/bin/ps', ['-eo', 'pid,ppid,pgid'], { encoding: 'utf8' })
.stdout.split('\n')
@@ -307,8 +309,14 @@ function spawnDeck(
.filter((row) => row.length === 3 && row[1] === shellPid);
const reap = () => {
for (const [pid] of descendants()) {
+ if (!isValidLockPid(pid)) {
+ console.warn(
+ `[spawnDeck] skipped a ps row under ppid ${shellPid}: pid column parsed to ${JSON.stringify(pid)}, which isValidLockPid rejects`,
+ );
+ continue;
+ }
try {
- process.kill(pid ?? 0, 'SIGKILL');
+ process.kill(pid, 'SIGKILL');
} catch {}
}
try {
diff --git a/packages/server/src/acp/thread-manager.integration.test.ts b/packages/server/src/acp/thread-manager.integration.test.ts
index fcfe5e718..51696a2e1 100644
--- a/packages/server/src/acp/thread-manager.integration.test.ts
+++ b/packages/server/src/acp/thread-manager.integration.test.ts
@@ -17,6 +17,7 @@ import codexFixture from '../../../../test-support/fixtures/codex-legacy-warning
import type { AgentPresenceBroadcaster } from '../agent-presence.ts';
import type { AgentSessionManager } from '../agent-sessions.ts';
import { getLogger, type PinoLogger } from '../logger.ts';
+import { isValidLockPid } from '../process-alive.ts';
import { RUNTIME_VERSION } from '../version-constants.ts';
import { withLocalAcquisitionRegistry } from './acquisition-contract.test-helper.ts';
import {
@@ -4997,6 +4998,10 @@ describe('diagnostic stream lifetime', () => {
try {
expect(await resumed).toMatchObject({ code: 'spawn-failed' });
const pid = Number(readFileSync(pidFile, 'utf8'));
+ expect(
+ isValidLockPid(pid),
+ `resumed-pid held ${JSON.stringify(readFileSync(pidFile, 'utf8'))}`,
+ ).toBe(true);
await expect
.poll(
() => {
@@ -5018,9 +5023,21 @@ describe('diagnostic stream lifetime', () => {
expect(replay.at(-1)).toMatchObject({ kind: 'status', detail: 'thread closed' });
} finally {
if (existsSync(pidFile)) {
- try {
- process.kill(Number(readFileSync(pidFile, 'utf8')), 'SIGKILL');
- } catch {}
+ const raw = readFileSync(pidFile, 'utf8');
+ const pid = Number(raw);
+ if (isValidLockPid(pid)) {
+ try {
+ process.kill(pid, 'SIGKILL');
+ } catch {}
+ } else {
+ console.warn(
+ `[resume-after-close cleanup] left a spawned child unreaped: ${pidFile} held ${JSON.stringify(raw)}, which isValidLockPid rejects`,
+ );
+ }
+ } else {
+ console.warn(
+ `[resume-after-close cleanup] no pidfile at ${pidFile}: either the resume failed before spawning, or a child was spawned and this test threw before the child's first write — in that case it is still running`,
+ );
}
}
}, 15_000);
diff --git a/packages/server/src/lint-plugins/no-sentinel-signal-target.test.ts b/packages/server/src/lint-plugins/no-sentinel-signal-target.test.ts
new file mode 100644
index 000000000..ad29b6168
--- /dev/null
+++ b/packages/server/src/lint-plugins/no-sentinel-signal-target.test.ts
@@ -0,0 +1,88 @@
+import { spawnSync } from 'node:child_process';
+import { existsSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { describe, expect, test } from 'vitest';
+import {
+ oxlintFixtureArgs,
+ parseOxlintDiagnostics,
+ readEnabledRuleIds,
+ readRegisteredRuleNames,
+ readRuleScope,
+} from '../../../../test-support/read-ok-rules-config.test-helper';
+
+const REPO_ROOT = join(__dirname, '..', '..', '..', '..');
+const RULE = 'no-sentinel-signal-target';
+const FIXTURE_REL = `lint-plugins/ok-rules/__fixtures__/${RULE}.fixture.tsx`;
+const README_REL = 'lint-plugins/ok-rules/README.md';
+const AGENTS_REL = 'AGENTS.md';
+
+function lintFixture() {
+ const result = spawnSync('pnpm', oxlintFixtureArgs(FIXTURE_REL), {
+ cwd: REPO_ROOT,
+ encoding: 'utf-8',
+ windowsHide: true,
+ maxBuffer: 64 * 1024 * 1024,
+ });
+ expect(result.error).toBeUndefined();
+ expect(typeof result.status).toBe('number');
+ expect(result.status).not.toBe(0);
+ const output = `${result.stdout}\n${result.stderr}`;
+ return parseOxlintDiagnostics(output).filter((d) => d.code === `ok(${RULE})`);
+}
+
+describe('no-sentinel-signal-target oxlint rule', () => {
+ test('fires exactly 20 times, split 10 literal / 4 fallback / 6 parsed, and on no negative case', () => {
+ const fires = lintFixture();
+ expect(fires.length).toBe(20);
+ const literal = fires.filter((d) => d.message.includes('Signal only a pid you spawned'));
+ const fallback = fires.filter((d) => d.message.includes('Filter the nullable pid out'));
+ const parsed = fires.filter((d) => d.message.includes('Validate it with `isValidLockPid()`'));
+ expect(literal.length).toBe(10);
+ expect(fallback.length).toBe(4);
+ expect(parsed.length).toBe(6);
+ for (const fire of fires) {
+ expect(fire.message).toMatch(/https?:\/\/[^\s]+/);
+ expect(fire.message).toContain(`${README_REL}#${RULE}`);
+ }
+ });
+
+ test('the literal remedy sanctions a handle-derived pid negated for its group and names the detached precondition, in the diagnostic and the README alike', () => {
+ const literal = lintFixture().filter((d) =>
+ d.message.includes('Signal only a pid you spawned'),
+ );
+ expect(literal.length).toBe(10);
+ for (const fire of literal) {
+ expect(fire.message).toContain('its pid taken from that handle');
+ expect(fire.message).toContain('negated for the group only if you spawned it detached');
+ }
+ const readme = readFileSync(join(REPO_ROOT, README_REL), 'utf8');
+ expect(readme).toContain('only if you spawned it detached');
+ });
+
+ test('every fire lands on a positive case and none on the negatives', () => {
+ const source = readFileSync(join(REPO_ROOT, FIXTURE_REL), 'utf8').split('\n');
+ const firedLines = lintFixture()
+ .map((d) => d.labels?.[0]?.span?.line)
+ .filter((line): line is number => typeof line === 'number');
+ expect(firedLines.length).toBe(20);
+ for (const line of firedLines) {
+ expect(source[line - 1]).toMatch(/^export const p\d+ = /);
+ }
+ });
+
+ test('rule is registered, enabled at error, and carries no scope entry — the registration wrapper rejects a rule that is in neither table, so an empty scope means workspace-wide', async () => {
+ expect(await readRegisteredRuleNames(REPO_ROOT)).toContain(RULE);
+ expect(await readEnabledRuleIds(REPO_ROOT)).toContain(`ok/${RULE}`);
+ expect(readRuleScope(REPO_ROOT, RULE)).toEqual([]);
+ });
+
+ test('the prose and the rule cite each other and the cited README heading exists', () => {
+ const readme = readFileSync(join(REPO_ROOT, README_REL), 'utf8');
+ expect(readme).toContain(`### \`${RULE}\``);
+ expect(readme).toContain('Never signal a pid you did not spawn');
+ const agents = readFileSync(join(REPO_ROOT, AGENTS_REL), 'utf8');
+ expect(agents).toContain('Never signal a pid you did not spawn');
+ expect(agents).toContain(`ok/${RULE}`);
+ expect(existsSync(join(REPO_ROOT, `lint-plugins/ok-rules/rules/${RULE}.mjs`))).toBe(true);
+ });
+});
diff --git a/scripts/check-server-test-inputs.mjs b/scripts/check-server-test-inputs.mjs
index 3586876cd..f506fdfe9 100644
--- a/scripts/check-server-test-inputs.mjs
+++ b/scripts/check-server-test-inputs.mjs
@@ -21,6 +21,8 @@ export const KNOWN_UNSWEPT = {
'same helper, plus fixture paths built from a bare root-relative constant',
'../app/src/editor/observers.ts':
'bridge-no-wallclock.test.ts reaches it via a lowercase repoRoot and a root-relative literal',
+ '../../AGENTS.md':
+ 'no-sentinel-signal-target.test.ts reaches it through join(REPO_ROOT, AGENTS_REL), a named constant the sweep cannot resolve',
};
function walkTestFiles(dir, out = []) {
diff --git a/turbo.json b/turbo.json
index 2ade975e5..b4bce4a5c 100644
--- a/turbo.json
+++ b/turbo.json
@@ -128,6 +128,7 @@
"!README.md",
"../../test-support/*.ts",
"../../oxlint.config.ts",
+ "../../AGENTS.md",
"../../lint-plugins/**",
"../plugin/**",
"../../plugins/ok/**",