Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Use GetProcessTimes for Windows uninstall identity checks (#4344)
Nick Gomez9f80cafce0ce
diff --git a/.changeset/windows-native-process-start-read.md b/.changeset/windows-native-process-start-read.mdnew file mode 100644index 000000000..7aadca416--- /dev/null+++ b/.changeset/windows-native-process-start-read.md@@ -0,0 +1,7 @@+---+"@inkeep/open-knowledge": patch+---++On Windows, `ok uninstall` and `ok deinit` read the live process creation time through the native addon instead of launching PowerShell. Cleanup continues to refuse a reused or unverifiable PID. POSIX process checks retain `ps`.++A Windows addon that is missing, unusable, or unable to complete the query refuses removal without a PowerShell fallback, and the refusal names the action for the fault it hit: reinstall OpenKnowledge when the component could not be loaded, or rerun from an account that can inspect the process when the component loaded and Windows refused the query, where reinstalling would not help. Either way you can stop the server yourself and confirm it exited. The failure detail is recorded in `~/.ok/logs` rather than printed.diff --git a/.github/scripts/select-native-config-prebuild.mjs b/.github/scripts/select-native-config-prebuild.mjsindex 9392001d8..4cbe5dc07 100644--- a/.github/scripts/select-native-config-prebuild.mjs+++ b/.github/scripts/select-native-config-prebuild.mjs@@ -47,33 +47,48 @@ export function describeSelectionFailure({ candidates = [], treeAt, releaseRef =return describeNoSelection(candidates);}-export function listPrebuildRuns({ limit = DEFAULT_CANDIDATE_LIMIT, run = spawnSync } = {}) {- const res = run(- 'gh',- [- 'run',- 'list',- `--workflow=${PREBUILD_WORKFLOW}`,- '--branch',- 'main',- '--event',- 'push',- '--status',- 'success',- '--limit',- String(limit),- '--json',- 'databaseId,headSha',- ],- { encoding: 'utf8' },- );- if (res.status !== 0) {- throw new Error(- `gh run list for ${PREBUILD_WORKFLOW} failed: ${res.error?.message ?? String(res.stderr || '').trim()}`,+const LIST_ATTEMPTS = 3;++function sleepSyncMs(ms) {+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);+}++export function listPrebuildRuns({+ limit = DEFAULT_CANDIDATE_LIMIT,+ run = spawnSync,+ sleep = sleepSyncMs,+} = {}) {+ let lastFailure = '';+ for (let attempt = 1; attempt <= LIST_ATTEMPTS; attempt += 1) {+ const res = run(+ 'gh',+ [+ 'run',+ 'list',+ `--workflow=${PREBUILD_WORKFLOW}`,+ '--branch',+ 'main',+ '--event',+ 'push',+ '--status',+ 'success',+ '--limit',+ String(limit),+ '--json',+ 'databaseId,headSha',+ ],+ { encoding: 'utf8' },);+ if (res.status === 0) {+ const parsed = JSON.parse(String(res.stdout || '[]').trim() || '[]');+ return Array.isArray(parsed) ? parsed : [];+ }+ lastFailure = res.error?.message ?? String(res.stderr || '').trim();+ if (attempt < LIST_ATTEMPTS) sleep(attempt * 1000);}- const parsed = JSON.parse(String(res.stdout || '[]').trim() || '[]');- return Array.isArray(parsed) ? parsed : [];+ throw new Error(+ `gh run list for ${PREBUILD_WORKFLOW} failed after ${LIST_ATTEMPTS} attempts: ${lastFailure}`,+ );}export function makeIsAncestor(run = spawnSync) {diff --git a/.github/scripts/select-native-config-prebuild.test.mjs b/.github/scripts/select-native-config-prebuild.test.mjsindex c63c2ae56..f6f920bd9 100644--- a/.github/scripts/select-native-config-prebuild.test.mjs+++ b/.github/scripts/select-native-config-prebuild.test.mjs@@ -1,4 +1,6 @@-import { readFileSync } from 'node:fs';+import { spawnSync } from 'node:child_process';+import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';import { dirname, join } from 'node:path';import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';@@ -24,6 +26,90 @@ const stagingStep = (yaml) => {return end === -1 ? rest : rest.slice(0, end);};+const stagingFunctions = (yaml) => {+ const step = stagingStep(yaml);+ const start = step.indexOf(' summarize() {');+ const close = '\n }\n';+ const end = step.indexOf(close, step.indexOf(' degrade_or_fail() {'));+ if (start === -1 || end === -1) throw new Error('no staging function block in the step');+ return step+ .slice(start, end + close.length)+ .split('\n')+ .map((line) => line.replace(/^ {10}/, ''))+ .join('\n');+};++const runDegradeOrFail = (functions, { isStable, staged }) => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-native-staging-'));+ try {+ mkdirSync(join(dir, 'packages', 'native-config'), { recursive: true });+ for (const target of staged) {+ writeFileSync(join(dir, 'packages', 'native-config', `native-config.${target}.node`), '');+ }+ const script = join(dir, 'staging.sh');+ writeFileSync(+ script,+ `${functions}\ndegrade_or_fail "could not download native-config-bindings-all from run 1" "0/8"\n`,+ );+ const result = spawnSync('bash', [script], {+ encoding: 'utf8',+ timeout: 10_000,+ cwd: dir,+ env: {+ ...process.env,+ IS_STABLE: String(isStable),+ GITHUB_STEP_SUMMARY: join(dir, 'step-summary.txt'),+ },+ });+ return { status: result.status, output: `${result.stdout}${result.stderr}` };+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+};++const runDownloadBindings = (functions, { failures }) => {+ const dir = mkdtempSync(join(tmpdir(), 'ok-native-download-'));+ try {+ const bin = join(dir, 'bin');+ mkdirSync(bin, { recursive: true });+ const attempts = join(dir, 'attempts');+ const bindingsDir = join(dir, 'nc-bindings');+ writeFileSync(+ join(bin, 'gh'),+ `#!/bin/bash\necho x >> "${attempts}"\nif [ -n "$(ls -A "${bindingsDir}" 2>/dev/null)" ]; then exit 1; fi\nif [ "$(wc -l < "${attempts}" | tr -d ' ')" -le ${failures} ]; then mkdir -p "${bindingsDir}"; touch "${bindingsDir}/partial.node"; exit 1; fi\nexit 0\n`,+ );+ spawnSync('chmod', ['+x', join(bin, 'gh')]);+ const script = join(dir, 'download.sh');+ if (!functions.includes('/tmp/nc-bindings')) {+ throw new Error('staging bytes no longer name /tmp/nc-bindings; the rescope would silently no-op');+ }+ const scoped = functions.replaceAll('/tmp/nc-bindings', bindingsDir);+ writeFileSync(script, `${scoped}\ndownload_bindings 1\n`);+ const result = spawnSync('bash', [script], {+ encoding: 'utf8',+ timeout: 60_000,+ cwd: dir,+ env: {+ ...process.env,+ PATH: `${bin}:${process.env.PATH}`,+ IS_STABLE: 'false',+ NC_RETRY_BACKOFF_S: '0',+ },+ });+ const calls = readFileSync(attempts, 'utf8').trim().split('\n').filter(Boolean).length;+ return { status: result.status, calls };+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+};++const BOTH_WINDOWS_TARGETS = ['win32-x64-msvc', 'win32-arm64-msvc'];++const REFUSAL_RECOVERY_SECTION = {+ 'release.yml': 'Native addon staging (Windows is mandatory)',+ 'desktop-release.yml': 'Resuming a blocked cut',+};+const chainFixture = (chain) => {const index = new Map(chain.map((c, i) => [c.sha, { ...c, position: i }]));return {@@ -217,19 +303,69 @@ describe('listPrebuildRuns', () => {expect(DEFAULT_CANDIDATE_LIMIT).toBeGreaterThan(1);});+ test('the lane whose job restates token scopes keeps the Actions read it stages with', () => {+ const yaml = workflow('desktop-release.yml');+ const jobStart = yaml.indexOf('\n prepare:');+ expect(jobStart).toBeGreaterThan(-1);+ const block = yaml.slice(jobStart);+ const permissionsStart = block.indexOf('permissions:');+ expect(permissionsStart).toBeGreaterThan(-1);+ const permissions = block.slice(permissionsStart);+ const permissionsEnd = permissions.indexOf('\n defaults:');+ expect(permissionsEnd).toBeGreaterThan(-1);+ const declared = permissions.slice(0, permissionsEnd);+ expect(declared).toContain('actions: read');+ expect(stagingStep(yaml)).toContain('gh run download');+ });+test('reports a spawn failure, which leaves stderr empty', () => {expect(() =>listPrebuildRuns({run: () => ({ status: null, stdout: '', stderr: '', error: new Error('spawn gh ENOENT') }),+ sleep: () => {},}),).toThrow(/spawn gh ENOENT/);});test('throws on an unreadable answer rather than reading it as "no runs"', () => {expect(() =>- listPrebuildRuns({ run: () => ({ status: 1, stdout: '', stderr: 'rate limited' }) }),+ listPrebuildRuns({+ run: () => ({ status: 1, stdout: '', stderr: 'rate limited' }),+ sleep: () => {},+ }),).toThrow(/rate limited/);});++ test('a transient gh failure never reaches the caller as a refusal', () => {+ let calls = 0;+ const slept = [];+ const runs = listPrebuildRuns({+ run: () => {+ calls += 1;+ return calls < 3+ ? { status: 1, stdout: '', stderr: 'API rate limit exceeded' }+ : { status: 0, stdout: '[{"databaseId":7,"headSha":"abc1234"}]', stderr: '' };+ },+ sleep: (ms) => slept.push(ms),+ });+ expect(runs).toEqual([{ databaseId: 7, headSha: 'abc1234' }]);+ expect(calls).toBe(3);+ expect(slept).toEqual([1000, 2000]);+ });++ test('gives up after a bounded number of attempts instead of retrying forever', () => {+ let calls = 0;+ expect(() =>+ listPrebuildRuns({+ run: () => {+ calls += 1;+ return { status: 1, stdout: '', stderr: 'API rate limit exceeded' };+ },+ sleep: () => {},+ }),+ ).toThrow(/failed after 3 attempts: API rate limit exceeded/);+ expect(calls).toBe(3);+ });});describe('main', () => {@@ -297,6 +433,67 @@ describe('workflow wiring', () => {expect(step).toMatch(/echo "::warning::[^\n]+\n\s+exit 0/);});+ test(`${name} requires both Windows binaries at every staging outcome`, () => {+ const step = stagingStep(workflow(name));+ for (const target of BOTH_WINDOWS_TARGETS) {+ expect(step).toContain(`native-config.${target}.node`);+ }+ expect(step).toMatch(/summarize "\$2 — \$1"\n\s+require_windows_targets "\$1"/);+ expect(step).toMatch(/-lt 8 \]; then\n(?:.*\n)*?\s+fi\n\s+require_windows_targets /);+ });++ test(`${name} refuses a beta cut whose staged set lacks either Windows binary`, () => {+ const functions = stagingFunctions(workflow(name));+ expect(functions).toContain('require_windows_targets');++ const recovered = runDownloadBindings(functions, { failures: 2 });+ expect(recovered.status).toBe(0);+ expect(recovered.calls).toBe(3);+ const exhausted = runDownloadBindings(functions, { failures: 99 });+ expect(exhausted.status).not.toBe(0);+ expect(exhausted.calls).toBe(3);++ const complete = runDegradeOrFail(functions, {+ isStable: false,+ staged: BOTH_WINDOWS_TARGETS,+ });+ expect(complete.status).toBe(0);+ expect(complete.output).toContain('::warning::');+ expect(complete.output).not.toContain('::error::');++ for (const missing of BOTH_WINDOWS_TARGETS) {+ const staged = BOTH_WINDOWS_TARGETS.filter((target) => target !== missing);+ const refused = runDegradeOrFail(functions, { isStable: false, staged });+ expect(refused.status).toBe(1);+ expect(refused.output).toContain(`native-config.${missing}.node was not staged`);+ expect(refused.output).not.toContain('::warning::');+ expect(refused.output).toContain(+ `resume per RELEASES.md '${REFUSAL_RECOVERY_SECTION[name]}'`,+ );+ }+ });++ test(`${name} still refuses a stable cut with a complete Windows pair`, () => {+ const refused = runDegradeOrFail(stagingFunctions(workflow(name)), {+ isStable: true,+ staged: BOTH_WINDOWS_TARGETS,+ });+ expect(refused.status).toBe(1);+ expect(refused.output).toContain('incomplete native-config binary set');+ expect(refused.output).not.toContain('::warning::');+ });++ test(`${name} names the missing Windows binary on the stable channel too`, () => {+ const functions = stagingFunctions(workflow(name));+ for (const missing of BOTH_WINDOWS_TARGETS) {+ const staged = BOTH_WINDOWS_TARGETS.filter((target) => target !== missing);+ const refused = runDegradeOrFail(functions, { isStable: true, staged });+ expect(refused.status).toBe(1);+ expect(refused.output).toContain(`native-config.${missing}.node was not staged`);+ expect(refused.output).not.toContain('incomplete native-config binary set');+ }+ });+test(`${name} asserts the selector's output shape, not just non-emptiness`, () => {const step = stagingStep(workflow(name));expect(step).toContain("selection_shape='^[0-9]+'$'\\t''[0-9a-f]{7,40}$'");diff --git a/.github/workflows/desktop-build-win-linux.yml b/.github/workflows/desktop-build-win-linux.ymlindex 390fa5d87..5d17983f9 100644--- a/.github/workflows/desktop-build-win-linux.yml+++ b/.github/workflows/desktop-build-win-linux.yml@@ -93,12 +93,6 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfile- # Best-effort staging of the 8-target native-config prebuilt set- # (mirrors release.yml's step in spirit, but always degrades instead- # of failing: these are QA artifacts, not published releases, and the- # smol-toml fallback keeps the CLI functional without the addon —- # only the Codex TOML write degrades to a decline). The host `napi- # build` below still produces the linux-x64 binary either way.- name: Stage native-config prebuilt binaries (best-effort)env:GH_TOKEN: ${{ github.token }}@@ -107,11 +101,11 @@ jobs:run_id=$(gh run list --workflow=native-config-prebuild.yml --branch main --event push \--status success --limit 1 --json databaseId --jq '.[0].databaseId // empty' 2>/dev/null || true)if [ -z "$run_id" ]; then- echo "::warning::no successful native-config-prebuild run found; win/arm64 targets ship without the toml_edit addon (smol-toml fallback)"+ echo "::warning::no successful native-config-prebuild run found; Windows cleanup requires the native addon; QA artifacts may lack it"exit 0fiif ! gh run download "$run_id" --name native-config-bindings-all --dir /tmp/nc-bindings; then- echo "::warning::could not download native-config-bindings-all from run $run_id; continuing with host binary only"+ echo "::warning::could not download native-config-bindings-all from run $run_id; Windows cleanup requires the native addon; QA artifacts may lack it"exit 0fifind /tmp/nc-bindings -name '*.node' -exec cp -f {} packages/native-config/ \;diff --git a/.github/workflows/desktop-release.yml b/.github/workflows/desktop-release.ymlindex 7d9fbb593..5cc22c9a2 100644--- a/.github/workflows/desktop-release.yml+++ b/.github/workflows/desktop-release.yml@@ -148,10 +148,6 @@ jobs:# and GitHub's releases API only returns drafts to push-level tokens# (contents: read gets a 404 and the assert would block every release).contents: write- # A job-level permissions block REPLACES the default token scopes, so- # the native-config staging step's `gh run list/view/download` needs- # its scope restated or it 403s (beta degrades to host-only; stable- # hard-fails the cut).actions: readdefaults:run:@@ -323,16 +319,6 @@ jobs:- name: Install dependenciesrun: pnpm install --frozen-lockfile- # The cross-platform native-config `.node` binaries are produced by the- # standalone native-config-prebuild workflow. Stage the latest successful- # run's bundle into packages/native-config/ so the cli `build:native`- # step copies all eight platforms into dist/native/ — the Windows/Linux- # installers packaged from this bundle then carry their own arch's- # toml_edit addon. Provenance + degrade-vs-fail semantics mirror- # release.yml's step: beta warns and ships host-only (non-host platforms- # use the non-destructive smol-toml fallback), stable hard-fails rather- # than silently shipping degraded native fidelity to the default install- # channel.- name: Stage native-config prebuilt binariesenv:GH_TOKEN: ${{ github.token }}@@ -341,14 +327,32 @@ jobs:summarize() {echo "Staged native-config binaries: $1" >> "$GITHUB_STEP_SUMMARY"}+ require_windows_targets() {+ for required in native-config.win32-x64-msvc.node native-config.win32-arm64-msvc.node; do+ if [ -f "packages/native-config/$required" ]; then continue; fi+ echo "::error::$1; $required was not staged, and the Windows installer built from this bundle would refuse removal without it. If no prebuild run matches this commit's packages/native-config tree, re-run native-config-prebuild.yml on an ancestor of this commit; if staging failed for another reason, re-run this workflow. Either way resume per RELEASES.md 'Resuming a blocked cut'."+ exit 1+ done+ }+ download_bindings() {+ for attempt in 1 2 3; do+ rm -rf /tmp/nc-bindings+ if gh run download "$1" --name native-config-bindings-all --dir /tmp/nc-bindings; then+ return 0+ fi+ if [ "$attempt" -lt 3 ]; then sleep $((attempt * ${NC_RETRY_BACKOFF_S:-5})); fi+ done+ return 1+ }degrade_or_fail() {# $1: human-readable reason, $2: staged-count label for the summarysummarize "$2 — $1"+ require_windows_targets "$1"if [ "$IS_STABLE" = "true" ]; thenecho "::error::$1; refusing to cut a stable release with an incomplete native-config binary set"exit 1fi- echo "::warning::$1; installers ship the host binary only (other platforms use the smol-toml fallback)"+ echo "::warning::$1; both Windows binaries were staged, so only other targets are missing"exit 0}@@ -397,8 +401,8 @@ jobs:run_id="${selection%%$'\t'*}"head_sha="${selection##*$'\t'}"- if ! gh run download "$run_id" --name native-config-bindings-all --dir /tmp/nc-bindings; then- degrade_or_fail "could not download native-config-bindings-all from run $run_id" "0/8"+ if ! download_bindings "$run_id"; then+ degrade_or_fail "could not download native-config-bindings-all from run $run_id after 3 attempts" "0/8"fifind /tmp/nc-bindings -name '*.node' -exec cp -f {} packages/native-config/ \;count=$(find packages/native-config -maxdepth 1 -name '*.node' | wc -l | tr -d ' ')@@ -406,6 +410,7 @@ jobs:if [ "$count" -lt 8 ]; thendegrade_or_fail "staged only $count/8 native-config binaries" "$count/8"fi+ require_windows_targets "staged $count/8 native-config binaries from run $run_id"summarize "$count/8 from run $run_id (commit $head_sha)"# The workspace build produces native-config's host `.node` via `napidiff --git a/.github/workflows/native-config-prebuild.yml b/.github/workflows/native-config-prebuild.ymlindex 61aae0ef8..833fe8db8 100644--- a/.github/workflows/native-config-prebuild.yml+++ b/.github/workflows/native-config-prebuild.yml@@ -150,6 +150,12 @@ jobs:# `build` script.run: pnpm exec napi build --platform --release --target ${{ matrix.settings.target }} ${{ matrix.settings.napiFlags }}+ - name: Test the crate on the one Windows target this x64 host can execute+ if: matrix.settings.target == 'x86_64-pc-windows-msvc'+ working-directory: packages/native-config+ shell: bash+ run: cargo test+- name: Upload bindinguses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1with:diff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 30c997da0..0a81d597a 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -192,45 +192,40 @@ jobs:- name: Installrun: pnpm install --frozen-lockfile- # The cross-platform native-config `.node` binaries are produced by the- # standalone native-config-prebuild workflow (kept separate so the beta- # cadence stays pure-JS-fast). Stage the newest qualifying run's bundle- # into packages/native-config/ so the cli `build:native` step copies all- # eight platforms into dist/native/ before publish. The bundle must come- # from a prebuild run whose head commit is an ancestor of the release- # commit (provenance), so the native code we ship was built from source- # actually in this release rather than a later main commit racing the cut.- # Beta is resilient by design: a missing, failed, stale, or incomplete- # bundle warns and ships host-only, with non-host platforms on the- # non-destructive smol-toml fallback, so a beta is never worse than- # host-only and the cadence never blocks. Stable @latest is held higher:- # an incomplete set hard-fails the cut rather than silently shipping- # degraded native fidelity to the default install channel. Binaries are- # ABI-stable (napi6); the latest qualifying run's set is reused until- # native-config changes and a fresh prebuild run completes.- name: Stage native-config prebuilt binariesenv:GH_TOKEN: ${{ github.token }}- # Stable @latest cuts arrive as repository_dispatch (publish-stable);- # beta + manual recovery arrive as push/workflow_dispatch. Only stable- # hard-fails on an incomplete native-config set.IS_STABLE: ${{ github.event_name == 'repository_dispatch' }}run: |- # Record the staged-binary outcome in the job summary, then either- # warn-and-proceed (beta) or hard-fail (stable). A stable @latest- # publish shipping host-only native binaries is a fidelity regression,- # so it pages rather than ships silently degraded.summarize() {echo "Staged native-config binaries: $1" >> "$GITHUB_STEP_SUMMARY"}+ require_windows_targets() {+ for required in native-config.win32-x64-msvc.node native-config.win32-arm64-msvc.node; do+ if [ -f "packages/native-config/$required" ]; then continue; fi+ echo "::error::$1; $required was not staged, and Windows removal reads process identity through the native addon, so this cut cannot publish. If no prebuild run matches this commit's packages/native-config tree, re-run native-config-prebuild.yml on an ancestor of this commit; if staging failed for another reason, re-run this workflow. Either way resume per RELEASES.md 'Native addon staging (Windows is mandatory)'."+ exit 1+ done+ }+ download_bindings() {+ for attempt in 1 2 3; do+ rm -rf /tmp/nc-bindings+ if gh run download "$1" --name native-config-bindings-all --dir /tmp/nc-bindings; then+ return 0+ fi+ if [ "$attempt" -lt 3 ]; then sleep $((attempt * ${NC_RETRY_BACKOFF_S:-5})); fi+ done+ return 1+ }degrade_or_fail() {# $1: human-readable reason, $2: staged-count label for the summarysummarize "$2 — $1"+ require_windows_targets "$1"if [ "$IS_STABLE" = "true" ]; thenecho "::error::$1; refusing to cut a stable @latest release with an incomplete native-config binary set"exit 1fi- echo "::warning::$1; CLI ships the host binary only (other platforms use the smol-toml fallback)"+ echo "::warning::$1; both Windows binaries were staged, so only other targets are missing"exit 0}@@ -279,8 +274,8 @@ jobs:run_id="${selection%%$'\t'*}"head_sha="${selection##*$'\t'}"- if ! gh run download "$run_id" --name native-config-bindings-all --dir /tmp/nc-bindings; then- degrade_or_fail "could not download native-config-bindings-all from run $run_id" "0/8"+ if ! download_bindings "$run_id"; then+ degrade_or_fail "could not download native-config-bindings-all from run $run_id after 3 attempts" "0/8"fifind /tmp/nc-bindings -name '*.node' -exec cp -f {} packages/native-config/ \;count=$(find packages/native-config -maxdepth 1 -name '*.node' | wc -l | tr -d ' ')@@ -288,6 +283,7 @@ jobs:if [ "$count" -lt 8 ]; thendegrade_or_fail "staged only $count/8 native-config binaries" "$count/8"fi+ require_windows_targets "staged $count/8 native-config binaries from run $run_id"summarize "$count/8 from run $run_id (commit $head_sha)"# `pnpm run build` builds the native-config addon's host `.node` viadiff --git a/docs/content/reference/cli.mdx b/docs/content/reference/cli.mdxindex 8b1aefd1b..c013d9ac7 100644--- a/docs/content/reference/cli.mdx+++ b/docs/content/reference/cli.mdx@@ -162,6 +162,8 @@ The rest of the CLI exists mostly for tooling and automation. Your AI editor spaBoth `ok deinit` and `ok uninstall` wait for servers to exit before deleting their state. If a server cannot be safely stopped or an integration cannot be cleaned up, the command reports the problem and retains state needed for repair and retry. Applied cleanup exits `1` when anything remains unresolved. With `--yes --json`, inspect `failed[]` for those items and their reasons; `skipped[]` covers intentionally preserved entries. Repair the reported problem and rerun the command.+On Windows, confirming that a running server really is the process the lock names uses OpenKnowledge's bundled native component. Removal refuses rather than signalling a process it has not identified, and the refusal names which of two things went wrong. If the component could not be loaded, reinstalling OpenKnowledge restores it — the same remedy as for [its TOML writer](#set-up-a-project). If the component loaded but Windows refused the query, reinstalling will not help: that is usually a permissions difference, so rerun from an account that can inspect the server process. Either way you can instead stop the server yourself and confirm it has exited, then rerun. The failure detail itself is recorded in `~/.ok/logs`, not printed.+`ok deinit` needs the project's `.ok/` directory; once that directory is gone, it reports nothing to remove. Remove any retained Pi trust entry manually using its reported exact key and file, as described in [installation details](./what-open-knowledge-writes.mdx#pi-folder-trust).Malformed filesystem residue does not by itself establish a running server. Cleanup can skip it after process and listener inspection succeeds and finds no associated live candidate. A read failure, incomplete inspection, or associated live server remains a blocker. Global-only uninstall can retain foreign-owned or ownership-unverified project state after the same local inspection; selecting project deinitialization keeps those ownership checks strict. Dead PID-only locks are recoverable. Human output lists root blockers once; JSON `failed[]` includes both direct failures and blocked dependent operations, with `blocked[]` providing the dependent subset.diff --git a/docs/content/reference/what-open-knowledge-writes.mdx b/docs/content/reference/what-open-knowledge-writes.mdxindex 73b34ffe1..8d80a2a93 100644--- a/docs/content/reference/what-open-knowledge-writes.mdx+++ b/docs/content/reference/what-open-knowledge-writes.mdx@@ -165,7 +165,7 @@ Installing `@inkeep/open-knowledge` from npm (or invoking it with `npx`) drops t| Path | What it is | Scope || --- | --- | --- || `ok`, `open-knowledge` (on your `PATH`) | The two CLI binaries (identical entry point) | Outside-project (npm global/bin) |-| `<pkg>/dist/native/` | Bundled native TOML-editing addon, shipped inside the package | Outside-project (package dir) |+| `<pkg>/dist/native/` | Bundled native addon, shipped inside the package: TOML editing on all platforms, plus a Windows-only reader that checks a running server's process creation time during `ok uninstall` / `ok deinit` | Outside-project (package dir) |<Callout type="info" title="Opt out">Installing the package writes nothing outside its own directory, so there is nothing to opt out of here. The user-global skills are installed by `ok init`, and `ok init --no-skills` skips installing them for that run.diff --git a/knip.config.ts b/knip.config.tsindex 802352af8..64cd89860 100644--- a/knip.config.ts+++ b/knip.config.ts@@ -139,11 +139,15 @@ export default {'packages/server': {entry: ['src/**/*.test.ts', 'src/parse-worker.ts'],project: 'src/**',- ignoreDependencies: ['@types/shell-quote'],+ ignoreDependencies: [+ '@types/shell-quote',+ ],},'packages/cli': {entry: ['src/**/*.test.ts', 'scripts/*.ts', 'tests/**/*.ts', 'src/parse-worker.ts'],- ignoreDependencies: ['yjs'],+ ignoreDependencies: [+ 'yjs',+ ],},'packages/desktop': {entry: [diff --git a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts b/packages/app/tests/integration/bug3-source-mode-writeback.test.tsindex 8a60e5826..a28cc2b18 100644--- a/packages/app/tests/integration/bug3-source-mode-writeback.test.ts+++ b/packages/app/tests/integration/bug3-source-mode-writeback.test.ts@@ -1,3 +1,4 @@+import { readFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts b/packages/app/tests/integration/indented-jsx-byte-sacred.test.tsindex 6fcdc23f2..4fc2c11f9 100644--- a/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts+++ b/packages/app/tests/integration/indented-jsx-byte-sacred.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { normalizeBridge } from '@inkeep/open-knowledge-core';import { updateYFragment } from '@tiptap/y-tiptap';diff --git a/packages/app/tests/integration/interior-edit-freshness.test.ts b/packages/app/tests/integration/interior-edit-freshness.test.tsindex 40b5cdfd6..9f2f6feb6 100644--- a/packages/app/tests/integration/interior-edit-freshness.test.ts+++ b/packages/app/tests/integration/interior-edit-freshness.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts b/packages/app/tests/integration/keystroke-cadence-danger-space.test.tsindex 93666af70..2a085742b 100644--- a/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts+++ b/packages/app/tests/integration/keystroke-cadence-danger-space.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/producer-guard-wiring.test.ts b/packages/app/tests/integration/producer-guard-wiring.test.tsindex 867598d34..878d5196b 100644--- a/packages/app/tests/integration/producer-guard-wiring.test.ts+++ b/packages/app/tests/integration/producer-guard-wiring.test.ts@@ -1,3 +1,4 @@+import { setTimeout as wait } from 'node:timers/promises';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';import { afterAll, beforeAll, describe, expect, test } from 'vitest';diff --git a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.tsindex 0970ac12f..4ada3cf26 100644--- a/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts+++ b/packages/app/tests/integration/qa-039-reconciliation-counters-http.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterEach, describe, expect, test } from 'vitest';import { agentWriteMd, createTestServer, type TestServer } from './test-harness';diff --git a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts b/packages/app/tests/integration/qa-045-restore-after-gc.test.tsindex b632185e1..cbe2b705f 100644--- a/packages/app/tests/integration/qa-045-restore-after-gc.test.ts+++ b/packages/app/tests/integration/qa-045-restore-after-gc.test.ts@@ -1,3 +1,4 @@+import { execFileSync } from 'node:child_process';import { randomUUID } from 'node:crypto';import { join } from 'node:path';diff --git a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.tsindex c530ce4ba..89bc9b4d9 100644--- a/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts+++ b/packages/app/tests/integration/qa-050-rollback-undo-shipped-path.test.ts@@ -1,3 +1,4 @@+import { randomUUID } from 'node:crypto';import { afterAll, afterEach, beforeAll, describe, expect, test } from 'vitest';import type * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-after-rollback.test.ts b/packages/app/tests/integration/undo-after-rollback.test.tsindex d3767adc9..a78aeb0e4 100644--- a/packages/app/tests/integration/undo-after-rollback.test.ts+++ b/packages/app/tests/integration/undo-after-rollback.test.ts@@ -1,3 +1,4 @@+import { ROLLBACK_ORIGIN } from '@inkeep/open-knowledge-server';import { afterAll, beforeAll, describe, expect, test } from 'vitest';import * as Y from 'yjs';diff --git a/packages/app/tests/integration/undo-recycle-reset.test.ts b/packages/app/tests/integration/undo-recycle-reset.test.tsindex b076f955c..e7cc69c3f 100644--- a/packages/app/tests/integration/undo-recycle-reset.test.ts+++ b/packages/app/tests/integration/undo-recycle-reset.test.ts@@ -1,3 +1,4 @@+import { writeFileSync } from 'node:fs';import { join } from 'node:path';import { setTimeout as wait } from 'node:timers/promises';diff --git a/packages/app/tests/integration/undo-rederive-survival.test.ts b/packages/app/tests/integration/undo-rederive-survival.test.tsindex 7935e35f8..9ddcd0730 100644--- a/packages/app/tests/integration/undo-rederive-survival.test.ts+++ b/packages/app/tests/integration/undo-rederive-survival.test.ts@@ -1,3 +1,4 @@+import { prependFrontmatter } from '@inkeep/open-knowledge-core';import { Plugin, PluginKey } from '@tiptap/pm/state';import { updateYFragment, yXmlFragmentToProseMirrorRootNode } from '@tiptap/y-tiptap';diff --git a/packages/cli/scripts/verify-package-surface.mjs b/packages/cli/scripts/verify-package-surface.mjsindex 2d42029b3..f485f458a 100644--- a/packages/cli/scripts/verify-package-surface.mjs+++ b/packages/cli/scripts/verify-package-surface.mjs@@ -5,7 +5,13 @@ import { fileURLToPath } from 'node:url';const PACKAGE_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');-export const REQUIRED_PACK_FILES = ['README.md', 'dist/LICENSE', 'dist/THIRD_PARTY_NOTICES.md'];+export const REQUIRED_PACK_FILES = [+ 'README.md',+ 'dist/LICENSE',+ 'dist/THIRD_PARTY_NOTICES.md',+ 'dist/native/native-config.win32-x64-msvc.node',+ 'dist/native/native-config.win32-arm64-msvc.node',+];export const REQUIRED_KEYWORDS = ['knowledge-base', 'markdown', 'local-first', 'mcp', 'ai', 'cli'];diff --git a/packages/cli/src/commands/removal-process-start.test.ts b/packages/cli/src/commands/removal-process-start.test.tsindex 51cae5cb0..82044f90f 100644--- a/packages/cli/src/commands/removal-process-start.test.ts+++ b/packages/cli/src/commands/removal-process-start.test.ts@@ -24,42 +24,81 @@ describe('readRemovalProcessStart', () => {},);- test('reads a Windows process creation time without losing milliseconds', () => {- const run = vi.fn(() => '\uFEFF2026-09-08T20:21:34.4567890Z\r\n');+ test('reads Windows creation time through the native addon without launching a shell', () => {+ const readProcessStart = vi.fn(() => 1_789_000_000_456);+ const run = vi.fn(() => '');expect(readRemovalProcessStart(123, {platform: 'win32',- env: { SYSTEMROOT: 'D:\\Windows' },+ nativeResolver: { requireModule: () => ({ readProcessStart }) },run,}),- ).toBe(Date.parse('2026-09-08T20:21:34.456Z'));- expect(run).toHaveBeenCalledWith(- 'D:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',- expect.arrayContaining([- '-NoProfile',- '-NonInteractive',- expect.stringContaining('(Get-Process -Id 123).StartTime.ToUniversalTime()'),- ]),- expect.objectContaining({ timeout: 15_000, windowsHide: true }),- );+ ).toBe(1_789_000_000_456);+ expect(readProcessStart).toHaveBeenCalledWith(123);+ expect(run).not.toHaveBeenCalled();});- test.each([undefined, '', ' ', 'relative-windows'])(- 'uses an absolute PowerShell fallback for an unusable SystemRoot %j',- (systemRoot) => {- const run = vi.fn(() => '2026-09-08T20:21:34.000Z');+ test.each([null, {}, { readProcessStart: 'invalid' }])(+ 'refuses an unavailable Windows addon %j',+ (binding) => {+ const run = vi.fn(() => '');+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ nativeResolver: { requireModule: () => binding },+ run,+ }),+ ).toBeNull();+ expect(run).not.toHaveBeenCalled();+ },+ );++ test.each([null, undefined, Number.NaN, Number.POSITIVE_INFINITY, -1, '123'])(+ 'refuses an invalid native process time %j',+ (value) => {+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ nativeResolver: { requireModule: () => ({ readProcessStart: () => value }) },+ }),+ ).toBeNull();+ },+ );++ test('refuses a Windows native query error without a shell fallback', () => {+ const run = vi.fn(() => '');+ expect(readRemovalProcessStart(123, {platform: 'win32',- env: { SystemRoot: systemRoot },+ nativeResolver: {+ requireModule: () => ({+ readProcessStart() {+ throw new Error('Access denied');+ },+ }),+ },run,- });- expect(run).toHaveBeenCalledWith(- 'C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe',- expect.any(Array),- expect.any(Object),- );- },- );+ }),+ ).toBeNull();+ expect(run).not.toHaveBeenCalled();+ });++ test('refuses a PID outside the 32-bit process-id range before loading native code', () => {+ const requireModule = vi.fn();+ expect(+ readRemovalProcessStart(0x1_0000_0000, {+ platform: 'win32',+ nativeResolver: { requireModule },+ }),+ ).toBeNull();+ expect(requireModule).not.toHaveBeenCalled();+ });++ test('refuses a PID outside the 32-bit process-id range before querying ps', () => {+ const run = vi.fn(() => 'Tue Sep 8 20:21:34 2026\n');+ expect(readRemovalProcessStart(0x1_0000_0000, { platform: 'darwin', run })).toBeNull();+ expect(run).not.toHaveBeenCalled();+ });test.each(['', 'permission denied', 'Tue Sep 8 20:21:34 2026\nTue Sep 8 20:21:34 2026'])('refuses unusable process start output %j',@@ -71,6 +110,7 @@ describe('readRemovalProcessStart', () => {test('refuses an unavailable, unsuccessful, or timed out probe', () => {expect(readRemovalProcessStart(123, {+ platform: 'darwin',run: () => {throw new Error('process query failed');},@@ -84,6 +124,177 @@ describe('readRemovalProcessStart', () => {expect(run).not.toHaveBeenCalled();});+ test.each([+ ['unavailable', () => null, 'did not load or does not export readProcessStart'],+ [+ 'invalid result',+ () => ({ readProcessStart: () => 1.5 }),+ 'readProcessStart returned an invalid value',+ ],+ [+ 'query error',+ () => ({+ readProcessStart: () => {+ throw new Error('OpenProcess: os error 5');+ },+ }),+ 'OpenProcess: os error 5',+ ],+ [+ 'loader error',+ () => {+ throw new Error('loader failed');+ },+ 'loader failed',+ ],+ [+ 'wrong-shaped binding',+ () => ({ readProcessStart: 'invalid' }),+ 'object keys=[readProcessStart] readProcessStart=string',+ ],+ [+ 'non-primitive result',+ () => ({ readProcessStart: () => ({ startedAt: 1 }) }),+ 'readProcessStart returned an invalid value: object keys=[startedAt]',+ ],+ ] as const)('reports %s with native debugging enabled', (_name, requireModule, message) => {+ vi.stubEnv('OK_DEBUG_NATIVE', '1');+ const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+ const onNativeFailure = vi.fn();+ try {+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ nativeResolver: { requireModule },+ onNativeFailure,+ }),+ ).toBeNull();+ const written = stderr.mock.calls.map(([value]) => String(value)).join('');+ expect(written).toContain(message);+ expect(written).not.toContain('[object Object]');+ expect(+ onNativeFailure.mock.calls.map(([failure]) => String(failure.reason)).join('; '),+ ).toContain(message);+ } finally {+ stderr.mockRestore();+ vi.unstubAllEnvs();+ }+ });++ test.each([+ ['x64', 'native-config.win32-x64-msvc.node'],+ ['arm64', 'native-config.win32-arm64-msvc.node'],+ ['ia32', 'native-config.win32-ia32-msvc.node'],+ ] as const)('names the %s addon it looked for when none was found', (arch, target) => {+ const onNativeFailure = vi.fn();+ const stderr = vi.spyOn(process.stderr, 'write').mockImplementation(() => true);+ try {+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ arch,+ nativeResolver: { requireModule: () => null },+ onNativeFailure,+ }),+ ).toBeNull();+ expect(onNativeFailure).toHaveBeenCalledWith({+ kind: 'unavailable',+ reason: `the Windows native addon (${target}) did not load or does not export readProcessStart: the addon was not found`,+ });+ expect(stderr).not.toHaveBeenCalled();+ } finally {+ stderr.mockRestore();+ }+ });++ test('describes an undefined binding as absent rather than rendering the value', () => {+ const onNativeFailure = vi.fn();+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ arch: 'x64',+ nativeResolver: { requireModule: () => undefined },+ onNativeFailure,+ }),+ ).toBeNull();+ expect(onNativeFailure).toHaveBeenCalledWith({+ kind: 'unavailable',+ reason:+ 'the Windows native addon (native-config.win32-x64-msvc.node) did not load or does not export readProcessStart: the addon was not found',+ });+ });++ test('leads the native failure record with the message that names the fault', () => {+ const onNativeFailure = vi.fn();+ const dlopen = Object.assign(+ new Error(+ '\\\\?\\C:\\app\\dist\\native\\native-config.win32-x64-msvc.node is not a valid Win32 application.',+ ),+ { code: 'ERR_DLOPEN_FAILED' },+ );+ const missingPackage = Object.assign(+ new Error("Cannot find module '@inkeep/open-knowledge-native-config-win32-x64-msvc'"),+ { code: 'MODULE_NOT_FOUND', cause: dlopen },+ );+ const requireModule = () => {+ throw Object.assign(+ new Error(+ 'Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.',+ ),+ { cause: missingPackage },+ );+ };+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ arch: 'x64',+ nativeResolver: { requireModule },+ onNativeFailure,+ }),+ ).toBeNull();+ const reasons = onNativeFailure.mock.calls.map(([failure]) => String(failure.reason));+ expect(reasons).toHaveLength(3);+ expect(reasons[0]).toContain('bundled loader failed to load: ');+ expect(reasons[1]).toContain('workspace addon failed to load: ');+ expect(reasons.at(-1)).toBe(+ 'the Windows native addon (native-config.win32-x64-msvc.node) did not load or does not export readProcessStart: no usable binding was returned',+ );+ for (const earlier of ['is not a valid Win32 application.', "Cannot find module '@inkeep"]) {+ expect(reasons[0]).toContain(earlier);+ expect(reasons[0].indexOf(earlier)).toBeLessThan(+ reasons[0].indexOf('Cannot find native binding.'),+ );+ }+ expect(reasons[0]).toContain('Cannot find native binding.');+ });++ test.each([+ [+ 'query-failed',+ 'a thrown query',+ () => ({+ readProcessStart: () => {+ throw new Error('OpenProcess: os error 5');+ },+ }),+ ],+ ['unavailable', 'an absent addon', () => null],+ ['unavailable', 'a wrong-shaped binding', () => ({ readProcessStart: 'invalid' })],+ ['unavailable', 'an invalid result', () => ({ readProcessStart: () => 1.5 })],+ ] as const)('classifies %s for %s', (kind, _name, requireModule) => {+ const onNativeFailure = vi.fn();+ expect(+ readRemovalProcessStart(123, {+ platform: 'win32',+ arch: 'x64',+ nativeResolver: { requireModule },+ onNativeFailure,+ }),+ ).toBeNull();+ expect(onNativeFailure).toHaveBeenCalled();+ expect(onNativeFailure.mock.calls.at(-1)?.[0]).toMatchObject({ kind });+ });+test('reads the current process start on the current operating system', () => {const startedAt = readRemovalProcessStart(process.pid);expect(startedAt).not.toBeNull();diff --git a/packages/cli/src/commands/removal-process-start.ts b/packages/cli/src/commands/removal-process-start.tsindex f6e4caf13..83449dc44 100644--- a/packages/cli/src/commands/removal-process-start.ts+++ b/packages/cli/src/commands/removal-process-start.ts@@ -1,61 +1,100 @@import { type ExecFileSyncOptionsWithStringEncoding, execFileSync } from 'node:child_process';-import { win32 } from 'node:path';+import {+ debugNativeLoadFailure,+ describeNativeFailure,+ describeValue,+ type NativeConfigResolver,+ requireNativeConfigModule,+} from '../native/load-native-config.ts';-interface ProcessStartOptions {+const PS_PROCESS_START_QUERY_TIMEOUT_MS = 5000;+const MAX_PROCESS_ID = 0xffff_ffff;++type NativeFailureKind = 'unavailable' | 'query-failed';++export interface NativeFailure {+ kind: NativeFailureKind;+ reason: string;+}++export interface ProcessStartOptions {platform?: NodeJS.Platform;+ arch?: NodeJS.Architecture;+ nativeResolver?: Partial<NativeConfigResolver>;env?: NodeJS.ProcessEnv;run?: (command: string, args: string[], options: ExecFileSyncOptionsWithStringEncoding) => string;+ onNativeFailure?: (failure: NativeFailure) => void;+}++function describeBinding(binding: unknown): string {+ if (!binding || typeof binding !== 'object') return String(binding);+ const exported = typeof (binding as Record<string, unknown>).readProcessStart;+ return `${describeValue(binding)} readProcessStart=${exported}`;}export function readRemovalProcessStart(pid: number,options: ProcessStartOptions = {},): number | null {- if (!Number.isSafeInteger(pid) || pid <= 0) return null;+ if (!Number.isSafeInteger(pid) || pid <= 0 || pid > MAX_PROCESS_ID) return null;const platform = options.platform ?? process.platform;- const env = options.env ?? process.env;- const run = options.run ?? execFileSync;+ const arch = options.arch ?? process.arch;+ const reportNativeFailure = (kind: NativeFailureKind, context: string, detail: unknown): void => {+ debugNativeLoadFailure(context, detail);+ options.onNativeFailure?.({ kind, reason: describeNativeFailure(context, detail) });+ };try {- let output: string;- const commandOptions: ExecFileSyncOptionsWithStringEncoding = {- encoding: 'utf8',- stdio: ['ignore', 'pipe', 'pipe'],- timeout: platform === 'win32' ? 15_000 : 5000,- windowsHide: true,- env: { ...env, LC_ALL: 'C', TZ: 'UTC0' },- };if (platform === 'win32') {- const systemRoot = Object.entries(env)- .find(([key]) => key.toLowerCase() === 'systemroot')?.[1]- ?.trim();- const powershell = win32.join(- systemRoot && win32.isAbsolute(systemRoot) ? systemRoot : 'C:\\Windows',- 'System32',- 'WindowsPowerShell',- 'v1.0',- 'powershell.exe',+ let loadFailureReported = false;+ const binding = requireNativeConfigModule(options.nativeResolver, (context, detail) => {+ loadFailureReported = true;+ reportNativeFailure('unavailable', context, detail);+ });+ if (+ !binding ||+ typeof binding !== 'object' ||+ !('readProcessStart' in binding) ||+ typeof binding.readProcessStart !== 'function'+ ) {+ let detail: string;+ if (binding !== null && binding !== undefined) detail = describeBinding(binding);+ else if (loadFailureReported) detail = 'no usable binding was returned';+ else detail = 'the addon was not found';+ reportNativeFailure(+ 'unavailable',+ `the Windows native addon (native-config.win32-${arch}-msvc.node) did not load or does not export readProcessStart`,+ detail,+ );+ return null;+ }+ const startedAt: unknown = binding.readProcessStart(pid);+ if (typeof startedAt === 'number' && Number.isSafeInteger(startedAt) && startedAt >= 0)+ return startedAt;+ reportNativeFailure(+ 'unavailable',+ 'readProcessStart returned an invalid value',+ describeValue(startedAt),);- output = run(- powershell,- [- '-NoLogo',- '-NoProfile',- '-NonInteractive',- '-Command',- `$ErrorActionPreference = 'Stop'; (Get-Process -Id ${pid}).StartTime.ToUniversalTime().ToString('O')`,- ],- commandOptions,- ).trim();+ return null;} else if (platform === 'darwin' || platform === 'linux') {+ const env = options.env ?? process.env;+ const run = options.run ?? execFileSync;+ const commandOptions: ExecFileSyncOptionsWithStringEncoding = {+ encoding: 'utf8',+ stdio: ['ignore', 'pipe', 'pipe'],+ timeout: PS_PROCESS_START_QUERY_TIMEOUT_MS,+ windowsHide: true,+ env: { ...env, LC_ALL: 'C', TZ: 'UTC0' },+ };const raw = run('/bin/ps', ['-p', String(pid), '-o', 'lstart='], commandOptions).trim();if (!/^\w{3}\s+\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2}\s+\d{4}$/.test(raw)) return null;- output = `${raw} UTC`;+ const startedAt = Date.parse(`${raw} UTC`);+ return Number.isFinite(startedAt) ? startedAt : null;} else {return null;}- const startedAt = Date.parse(output);- return Number.isFinite(startedAt) ? startedAt : null;- } catch {+ } catch (err) {+ if (platform === 'win32') reportNativeFailure('query-failed', 'readProcessStart failed', err);return null;}}diff --git a/packages/cli/src/commands/stop-for-removal.test.ts b/packages/cli/src/commands/stop-for-removal.test.tsindex 35cf3efbb..8bb469f26 100644--- a/packages/cli/src/commands/stop-for-removal.test.ts+++ b/packages/cli/src/commands/stop-for-removal.test.ts@@ -85,6 +85,7 @@ describe('stopServerForRemoval', () => {await expect(stopServerForRemoval(dir, { isAlive: () => true })).rejects.toThrow('does not record its owning machine',);+ expect(warnings[0]).toMatchObject({ status: 'unverified-owner', lockPid: 4242 });});test('reports no server when no lock exists', async () => {@@ -310,19 +311,216 @@ describe('stopServerForRemoval', () => {expectRefusalLogged('alive', 'valid start time');});- test('does not signal when the process start probe is unavailable and explains recovery', async () => {+ test.each([+ ['linux', 'ps supporting -p and -o lstart='],+ ['darwin', 'Stop the server manually.'],+ ] as const)(+ 'explains the %s probe recovery when the process start probe is unavailable',+ async (platform, expected) => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(+ stopServerForRemoval(dir, { platform, readProcessStart: () => null }),+ ).rejects.toThrow('Confirm the OpenKnowledge server has exited before retrying cleanup');+ expect(isProcessAlive(pid)).toBe(true);+ expectRefusalLogged('alive', 'Cannot verify the identity');+ expect(warnings[0]).toMatchObject({ lockPid: pid });+ expect(warnings[0]?.msg).toContain(expected);+ },+ );++ test('records the native identity failure cause in the CLI log, never in the refusal a user reads', async () => {const pid = await startServer(`process.send('ready');setInterval(() => {}, 1000);`);- await expect(stopServerForRemoval(dir, { readProcessStart: () => null })).rejects.toThrow(- 'Confirm the OpenKnowledge server has exited before retrying cleanup',+ await expect(+ stopServerForRemoval(dir, {+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({+ kind: 'query-failed',+ reason: 'readProcessStart failed: OpenProcess: os error 5',+ });+ return null;+ },+ }),+ ).rejects.toThrow('Cannot verify the identity');+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toMatchObject({+ nativeFailures: [+ { kind: 'query-failed', reason: 'readProcessStart failed: OpenProcess: os error 5' },+ ],+ });+ expect(warnings[0]?.msg).toContain(lockFilePath(dir, 'server'));+ expect(warnings[0]?.msg).not.toContain('OpenProcess: os error 5');+ expect(warnings[0]?.msg).toContain('recorded in the CLI log under ~/.ok/logs');+ });++ test.each([+ [+ 'unavailable',+ 'Reinstall OpenKnowledge to restore the Windows component that verifies process identity',+ 'the operating system refused the query',+ ],+ [+ 'query-failed',+ 'the operating system refused the query, so reinstalling will not help',+ 'Reinstall OpenKnowledge',+ ],+ ] as const)(+ 'picks the win32 remedy for a %s fault on any host',+ async (kind, expected, absent) => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(+ stopServerForRemoval(dir, {+ platform: 'win32',+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({ kind, reason: 'probe detail' });+ return null;+ },+ }),+ ).rejects.toThrow(expected);+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings[0]?.msg).not.toContain(absent);+ },+ );++ test('names no remedy on win32 when nothing was reported', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(+ stopServerForRemoval(dir, { platform: 'win32', readProcessStart: () => null }),+ ).rejects.toThrow('Stop the server manually.');+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings[0]?.msg).not.toContain('Reinstall OpenKnowledge');+ expect(warnings[0]?.msg).not.toContain('refused the query');+ });++ test('does not prescribe a reinstall when the component loaded and the OS refused the query', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(+ stopServerForRemoval(dir, {+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({+ kind: 'query-failed',+ reason: 'readProcessStart failed: OpenProcess: os error 5',+ });+ return null;+ },+ }),+ ).rejects.toThrow('Cannot verify the identity');+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings[0]).toMatchObject({+ nativeFailures: [{ kind: 'query-failed' }],+ });+ });++ test('never repeats upstream install advice to a user removing the product', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const napiAdvisory =+ 'bundled loader failed to load: \\\\?\\C:\\app\\dist\\native\\native-config.win32-x64-msvc.node is not a valid Win32 application. -> Cannot find native binding. npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). Please try `npm i` again after removing both package-lock.json and node_modules directory.';+ const error = await stopServerForRemoval(dir, {+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({ kind: 'unavailable', reason: napiAdvisory });+ return null;+ },+ }).then(+ () => undefined,+ (err: unknown) => err as Error,);expect(isProcessAlive(pid)).toBe(true);- expectRefusalLogged('alive', 'Cannot verify the identity');- if (process.platform === 'linux') {- expect(warnings[0]?.msg).toContain('ps supporting -p and -o lstart=');+ expect(error?.message).toContain('Cannot verify the identity');+ for (const upstreamOnly of ['package-lock.json', 'node_modules', 'npm i', 'npm/cli/issues']) {+ expect(error?.message).not.toContain(upstreamOnly);}+ expect(warnings[0]).toMatchObject({+ nativeFailures: [{ kind: 'unavailable', reason: napiAdvisory }],+ });+ });++ test('keeps every native failure cause, not only the last one', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(+ stopServerForRemoval(dir, {+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({+ kind: 'unavailable',+ reason: 'bundled loader failed to load: invalid ELF header',+ });+ options?.onNativeFailure?.({+ kind: 'unavailable',+ reason: 'the Windows native addon did not load',+ });+ return null;+ },+ }),+ ).rejects.toThrow('Cannot verify the identity');+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings).toHaveLength(1);+ expect(warnings[0]).toMatchObject({+ level: 40,+ lockDir: dir,+ lockPath: lockFilePath(dir, 'server'),+ lockPid: pid,+ status: 'alive',+ nativeFailures: [+ { kind: 'unavailable', reason: 'bundled loader failed to load: invalid ELF header' },+ { kind: 'unavailable', reason: 'the Windows native addon did not load' },+ ],+ });+ });++ test('omits the log pointer and the cause field when the reader reported none', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ await expect(stopServerForRemoval(dir, { readProcessStart: () => null })).rejects.toThrow(+ 'Cannot verify the identity',+ );+ expect(isProcessAlive(pid)).toBe(true);+ expect(warnings[0]?.msg).not.toContain('~/.ok/logs');+ expect(warnings[0]).not.toHaveProperty('nativeFailures');+ });++ test('does not log a native failure when the liveness recheck accepts an exited process', async () => {+ const pid = await startServer(`+ process.send('ready');+ setInterval(() => {}, 1000);+ `);+ const isAlive = vi.fn().mockReturnValueOnce(true).mockReturnValueOnce(false);+ expect(+ await stopServerForRemoval(dir, {+ readProcessStart: (_pid, options) => {+ options?.onNativeFailure?.({+ kind: 'query-failed',+ reason: 'readProcessStart failed: OpenProcess: os error 87',+ });+ return null;+ },+ isAlive,+ }),+ ).toEqual({ stopped: 0, failed: [] });+ expect(warnings).toEqual([]);+ expect(isAlive).toHaveBeenCalledTimes(2);+ expect(isProcessAlive(pid)).toBe(true);});test('requires a liveness recheck to accept an exited process after an unavailable identity probe', async () => {@@ -377,6 +575,7 @@ describe('stopServerForRemoval', () => {);expect(isProcessAlive(pid)).toBe(true);expectRefusalLogged('foreign-host', 'another machine');+ expect(warnings[0]).toMatchObject({ lockPid: pid });expect(warnings[0]?.msg).toContain(lockFilePath(dir, 'server'));});diff --git a/packages/cli/src/commands/stop-for-removal.ts b/packages/cli/src/commands/stop-for-removal.tsindex 37bc4d9c7..6cf7e3b52 100644--- a/packages/cli/src/commands/stop-for-removal.ts+++ b/packages/cli/src/commands/stop-for-removal.ts@@ -8,7 +8,11 @@ import {} from '@inkeep/open-knowledge-server';import { getCliLogger } from '../cli-logger.ts';import { describeLockOwnershipRefusal, inspectLock } from './lock-state.ts';-import { readRemovalProcessStart } from './removal-process-start.ts';+import {+ type NativeFailure,+ type ProcessStartOptions,+ readRemovalProcessStart,+} from './removal-process-start.ts';import { runStop } from './stop.ts';interface StopForRemovalOptions {@@ -16,8 +20,12 @@ interface StopForRemovalOptions {scanProcesses?: () => Promise<LockProcessScan>;timeoutMs?: number;pollIntervalMs?: number;- readProcessStart?: (pid: number) => number | null;+ readProcessStart?: (+ pid: number,+ options?: Pick<ProcessStartOptions, 'platform' | 'onNativeFailure'>,+ ) => number | null;isAlive?: (pid: number) => boolean;+ platform?: NodeJS.Platform;}export async function stopServerForRemoval(@@ -29,8 +37,38 @@ export async function stopServerForRemoval(const lockRecovery ='Quit OpenKnowledge and stop any OpenKnowledge server processes. ' +`Once you have confirmed they have exited, remove the stale lock file at ${state.lockPath} and retry cleanup.`;- const refusal = (message: string): Error => {- getCliLogger()?.warn({ lockDir, lockPath: state.lockPath, status: state.status }, message);+ const recordedPid = (): number | undefined => {+ switch (state.status) {+ case 'alive':+ case 'dead-pid':+ case 'foreign-host':+ return state.lock.pid;+ case 'unverified-owner':+ return state.pid;+ case 'missing':+ case 'corrupt':+ case 'read-error':+ return undefined;+ default: {+ const exhaustive: never = state;+ return exhaustive;+ }+ }+ };+ const logContext = (): Record<string, unknown> => {+ const lockPid = recordedPid();+ return {+ ...(lockPid === undefined ? {} : { lockPid }),+ lockDir,+ lockPath: state.lockPath,+ status: state.status,+ };+ };+ const refusal = (message: string, nativeFailures: NativeFailure[] = []): Error => {+ getCliLogger()?.warn(+ nativeFailures.length > 0 ? { ...logContext(), nativeFailures } : logContext(),+ message,+ );return new Error(message);};if (state.status === 'read-error') {@@ -97,17 +135,50 @@ export async function stopServerForRemoval(if (!Number.isFinite(lockStartedAt)) {throw refusal(`The server lock has no valid start time. ${lockRecovery}`);}- const processStartedAt = (options.readProcessStart ?? readRemovalProcessStart)(state.lock.pid);+ const nativeFailures: NativeFailure[] = [];+ const platform = options.platform ?? process.platform;+ const processStartedAt = (options.readProcessStart ?? readRemovalProcessStart)(state.lock.pid, {+ platform,+ onNativeFailure: (failure) => {+ nativeFailures.push(failure);+ },+ });if (processStartedAt === null) {if (!isAlive(state.lock.pid)) return { stopped: 0, failed: [] };+ const componentUnavailable = nativeFailures.some((failure) => {+ switch (failure.kind) {+ case 'unavailable':+ return true;+ case 'query-failed':+ return false;+ default: {+ const exhaustive: never = failure.kind;+ return exhaustive;+ }+ }+ });+ const windowsRecovery =+ nativeFailures.length === 0+ ? 'Stop the server manually. '+ : componentUnavailable+ ? 'Reinstall OpenKnowledge to restore the Windows component that verifies process identity, or stop the server manually. '+ : 'The Windows component loaded but the operating system refused the query, so reinstalling will not help; retry from an account that can inspect that process, or stop the server manually. ';const probeRecovery =- process.platform === 'linux'+ platform === 'linux'? 'Linux requires ps supporting -p and -o lstart= (such as procps). Install a compatible ps and retry, or stop the server manually. '- : 'Stop the server manually. ';+ : platform === 'win32'+ ? windowsRecovery+ : 'Stop the server manually. ';+ const causeRecord =+ nativeFailures.length > 0+ ? 'The failure detail is recorded in the CLI log under ~/.ok/logs. '+ : '';throw refusal(- `Cannot verify the identity of process ${state.lock.pid}; the OS process-start query failed or is unavailable, so it was not signalled. ` ++ `Cannot verify the identity of process ${state.lock.pid} recorded in the server lock at ${state.lockPath}; the OS process-start query failed or is unavailable, so it was not signalled. ` +probeRecovery ++ causeRecord +'Confirm the OpenKnowledge server has exited before retrying cleanup after a manual stop.',+ nativeFailures,);}if (processStartedAt > lockStartedAt) {diff --git a/packages/cli/src/commands/stop.ts b/packages/cli/src/commands/stop.tsindex be1997081..f3a22208c 100644--- a/packages/cli/src/commands/stop.ts+++ b/packages/cli/src/commands/stop.ts@@ -26,6 +26,7 @@ export async function probeCollabClients(try {const res = await fetch(`${baseUrl}/api/server-info`, {signal: AbortSignal.timeout(CLIENT_PROBE_TIMEOUT_MS),+ redirect: 'manual',});if (!res.ok) {logger?.warn(diff --git a/packages/cli/src/native/load-native-config.test.ts b/packages/cli/src/native/load-native-config.test.tsindex c45a935dc..33840d598 100644--- a/packages/cli/src/native/load-native-config.test.ts+++ b/packages/cli/src/native/load-native-config.test.ts@@ -1,6 +1,6 @@import { fileURLToPath } from 'node:url';import { describe, expect, test } from 'vitest';-import { requireNativeConfigModule } from './load-native-config.ts';+import { describeNativeFailure, requireNativeConfigModule } from './load-native-config.ts';function withCapturedStderr(fn: () => void): string {const original = process.stderr.write.bind(process.stderr);@@ -119,3 +119,28 @@ describe('broken-binary diagnostic (OK_DEBUG_NATIVE)', () => {expect(captured).toBe('');});});++describe('describeNativeFailure', () => {+ test('renders the innermost cause first and drops the outermost past the bound', () => {+ let err = new Error('link-1');+ for (let i = 2; i <= 6; i++) err = Object.assign(new Error(`link-${i}`), { cause: err });+ const rendered = describeNativeFailure('load failed', err);+ expect(rendered).toBe('load failed: link-1 -> link-2 -> link-3 -> link-4 -> link-5');+ expect(rendered).not.toContain('link-6');+ });++ test('terminates on a cause chain that points back into itself', () => {+ const outer = new Error('outer');+ const inner = Object.assign(new Error('inner'), { cause: outer });+ outer.cause = inner;+ const rendered = describeNativeFailure('load failed', outer);+ expect(rendered).toBe('load failed: inner -> outer');+ });++ test('renders a non-Error without a chain', () => {+ expect(describeNativeFailure('load failed', null)).toBe('load failed: null');+ expect(describeNativeFailure('load failed', { code: 'EACCES' })).toBe(+ 'load failed: object keys=[code]',+ );+ });+});diff --git a/packages/cli/src/native/load-native-config.ts b/packages/cli/src/native/load-native-config.tsindex 67ead24d1..72ffe3c2b 100644--- a/packages/cli/src/native/load-native-config.ts+++ b/packages/cli/src/native/load-native-config.ts@@ -10,10 +10,29 @@ function isModuleNotFound(err: unknown): boolean {return code === 'MODULE_NOT_FOUND' || code === 'ERR_MODULE_NOT_FOUND';}+const MAX_CAUSE_DEPTH = 5;++export function describeValue(value: unknown): string {+ if (!value || typeof value !== 'object') return String(value);+ return `${typeof value} keys=[${Object.keys(value).join(',')}]`;+}++export function describeNativeFailure(context: string, err: unknown): string {+ const messages: string[] = [];+ const seen = new WeakSet<object>();+ let current: unknown = err;+ while (current instanceof Error && !seen.has(current)) {+ seen.add(current);+ messages.push(current.message);+ current = current.cause;+ }+ if (messages.length === 0) return `${context}: ${describeValue(err)}`;+ return `${context}: ${messages.reverse().slice(0, MAX_CAUSE_DEPTH).join(' -> ')}`;+}+export function debugNativeLoadFailure(context: string, err: unknown): void {if (!process.env.OK_DEBUG_NATIVE) return;- const message = err instanceof Error ? err.message : String(err);- process.stderr.write(`[ok] native-config ${context}: ${message}\n`);+ process.stderr.write(`[ok] native-config ${describeNativeFailure(context, err)}\n`);}const BUNDLED_LOADER_SUBPATH = ['native', 'index.js'];@@ -25,6 +44,7 @@ export interface NativeConfigResolver {export function requireNativeConfigModule(resolver: Partial<NativeConfigResolver> = {},+ onLoadFailure: (context: string, err: unknown) => void = debugNativeLoadFailure,): unknown | null {const moduleUrl = resolver.moduleUrl ?? import.meta.url;const requireModule = resolver.requireModule ?? createRequire(moduleUrl);@@ -33,13 +53,13 @@ export function requireNativeConfigModule(const here = dirname(fileURLToPath(moduleUrl));return requireModule(join(here, ...BUNDLED_LOADER_SUBPATH));} catch (err) {- if (!isModuleNotFound(err)) debugNativeLoadFailure('bundled loader failed to load', err);+ if (!isModuleNotFound(err)) onLoadFailure('bundled loader failed to load', err);}try {return requireModule(NATIVE_CONFIG_PACKAGE);} catch (err) {- if (!isModuleNotFound(err)) debugNativeLoadFailure('workspace addon failed to load', err);+ if (!isModuleNotFound(err)) onLoadFailure('workspace addon failed to load', err);return null;}}diff --git a/packages/core/src/bridge/compose.ts b/packages/core/src/bridge/compose.tsindex f4cc8a286..2a597ec3d 100644--- a/packages/core/src/bridge/compose.ts+++ b/packages/core/src/bridge/compose.ts@@ -1,3 +1,4 @@+import { prependFrontmatter, stripFrontmatter } from '../extensions/frontmatter.ts';export type ComposeAdjustment = 'none' | 'body' | 'frontmatter' | 'unresolved';diff --git a/packages/core/src/bridge/doc-boundary-space.ts b/packages/core/src/bridge/doc-boundary-space.tsindex 8fb428b90..01ef76a9f 100644--- a/packages/core/src/bridge/doc-boundary-space.ts+++ b/packages/core/src/bridge/doc-boundary-space.ts@@ -1,3 +1,4 @@+import { FRONTMATTER_RE, stripFrontmatter } from '../extensions/frontmatter.ts';import { carriedEdgeEmpties, type DocEdgeEmpties } from '../markdown/doc-edge-blank-runs.ts';diff --git a/packages/core/src/markdown/comment-promoter.ts b/packages/core/src/markdown/comment-promoter.tsindex bfbd5a2e8..20a68d2a1 100644--- a/packages/core/src/markdown/comment-promoter.ts+++ b/packages/core/src/markdown/comment-promoter.ts@@ -1,3 +1,4 @@+import type { Nodes, Paragraph, PhrasingContent, Root, RootContent, Text } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/merged-walker.ts b/packages/core/src/markdown/merged-walker.tsindex bfd7e3109..fa3cfcd86 100644--- a/packages/core/src/markdown/merged-walker.ts+++ b/packages/core/src/markdown/merged-walker.ts@@ -1,3 +1,4 @@+import type { Nodes, Parent, Root } from 'mdast';import { SKIP, visit } from 'unist-util-visit';import type { VFile } from 'vfile';diff --git a/packages/core/src/markdown/safe-url.ts b/packages/core/src/markdown/safe-url.tsindex 4d3250d3a..8be632ba4 100644--- a/packages/core/src/markdown/safe-url.ts+++ b/packages/core/src/markdown/safe-url.ts@@ -1,3 +1,4 @@+export const SAFE_URL_SCHEMES = ['https', 'http', 'mailto', 'tel', 'ftp', 'sms'] as const;const SCHEME_ALT = SAFE_URL_SCHEMES.map((s) => `${s}:`).join('|');diff --git a/packages/native-config/src/lib.rs b/packages/native-config/src/lib.rsindex 1a1970109..6db3f46e2 100644--- a/packages/native-config/src/lib.rs+++ b/packages/native-config/src/lib.rs@@ -14,6 +14,7 @@ use napi_derive::napi;mod document_helpers;mod mcp_edit;mod path_resolve;+mod process_start;mod toml_json;use std::path::Path;@@ -111,3 +112,14 @@ pub fn resolve_symlink_write_path(path: String) -> napi::Result<SymlinkWritePathwrite_path: resolved.write_path.to_string_lossy().into_owned(),})}++/// Read the creation time of the process at `pid`, in milliseconds since the+/// Unix epoch, for comparing a running process against the lock that claims+/// it. `None` on every platform but Windows, and on Windows when the creation+/// time predates the epoch. Throws `OpenProcess: <os error>` when the process+/// cannot be opened and `GetProcessTimes: <os error>` when the times cannot be+/// read.+#[napi]+pub fn read_process_start(pid: u32) -> napi::Result<Option<i64>> {+ process_start::read(pid).map_err(napi::Error::from_reason)+}diff --git a/packages/native-config/src/process_start.rs b/packages/native-config/src/process_start.rsnew file mode 100644index 000000000..0b4d42147--- /dev/null+++ b/packages/native-config/src/process_start.rs@@ -0,0 +1,98 @@+//! Pure (N-API-free) read of a process's creation time, used by the removal+//! path to verify a lock's recorded process before signalling it. Kept free of+//! any `napi` types so it is directly unit-testable under a plain `cargo test`+//! binary; the thin `#[napi]` wrapper lives in `lib.rs`. Windows reads+//! `GetProcessTimes` through `OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION)`;+//! every other platform reports no reading.++#[cfg(any(windows, test))]+fn filetime_to_epoch_ms(low: u32, high: u32) -> Option<i64> {+ let ticks = (u64::from(high) << 32) | u64::from(low);+ ticks+ .checked_sub(116_444_736_000_000_000)+ .map(|value| (value / 10_000) as i64)+}++#[cfg(windows)]+pub fn read(pid: u32) -> Result<Option<i64>, String> {+ use std::ffi::c_void;++ #[repr(C)]+ #[derive(Default)]+ struct FileTime {+ low: u32,+ high: u32,+ }++ #[link(name = "kernel32")]+ extern "system" {+ fn OpenProcess(access: u32, inherit: i32, pid: u32) -> *mut c_void;+ fn GetProcessTimes(+ handle: *mut c_void,+ creation: *mut FileTime,+ exit: *mut FileTime,+ kernel: *mut FileTime,+ user: *mut FileTime,+ ) -> i32;+ fn CloseHandle(handle: *mut c_void) -> i32;+ }++ const PROCESS_QUERY_LIMITED_INFORMATION: u32 = 0x1000;+ let handle = unsafe { OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid) };+ if handle.is_null() {+ return Err(format!("OpenProcess: {}", std::io::Error::last_os_error()));+ }+ let mut creation = FileTime::default();+ let mut exit = FileTime::default();+ let mut kernel = FileTime::default();+ let mut user = FileTime::default();+ let success =+ unsafe { GetProcessTimes(handle, &mut creation, &mut exit, &mut kernel, &mut user) };+ let result = if success == 0 {+ Err(format!(+ "GetProcessTimes: {}",+ std::io::Error::last_os_error()+ ))+ } else {+ Ok(filetime_to_epoch_ms(creation.low, creation.high))+ };+ unsafe { CloseHandle(handle) };+ result+}++#[cfg(not(windows))]+pub fn read(_pid: u32) -> Result<Option<i64>, String> {+ Ok(None)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn converts_filetime_to_unix_milliseconds() {+ let ticks = 116_444_736_000_000_000u64 + 1_234_567 * 10_000 + 9999;+ assert_eq!(+ filetime_to_epoch_ms(ticks as u32, (ticks >> 32) as u32),+ Some(1_234_567)+ );+ assert_eq!(filetime_to_epoch_ms(0, 0), None);+ }++ #[cfg(windows)]+ #[test]+ fn reads_current_process_and_refuses_invalid_pid() {+ let start = read(std::process::id())+ .expect("current process is queryable")+ .expect("current process has a creation time");+ let now = std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .unwrap()+ .as_millis() as i64;+ assert!(start <= now);+ assert!(start > 0);+ assert_eq!(read(std::process::id()), Ok(Some(start)));+ assert!(read(0).unwrap_err().starts_with("OpenProcess:"));+ assert!(read(u32::MAX).unwrap_err().starts_with("OpenProcess:"));+ }+}