@bitkyc08/opencodex 2.97.0 → 2.98.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/ocx.mjs +1 -1
- package/gui/dist/assets/App-6TFtZsUF.css +1 -0
- package/gui/dist/assets/App-FQ0OtiMJ.js +59 -0
- package/gui/dist/assets/Tray-D2d5wqLq.js +1 -0
- package/gui/dist/assets/WantedSansVariable.split.0-Dwvb1WRx.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.1-1wKD2RxI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.10-CAKA6LIP.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.11-k5H85R4b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.12-BHboLsUv.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.13-9GV377ix.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.14-DovDXnrj.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.15-DTdykCig.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.16-CKz2ccgK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.17-Z2RD_KRZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.18-BcKtfonJ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.19-DEQPOSZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.2-DryboyuA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.20-Bia5JMls.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.21-Cr4jFw-E.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.22-DjjB69TZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.23-CvUzJskt.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.24-i_eMg5ox.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.25-2aKHwPX-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.26-B6wXoCEL.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.27-D4h1WfGM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.28-kvRPCStd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.29-DHAiwleD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.3-7H--eyZi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.30-C66cfAY2.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.31-FDmtiNim.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.32-DouHt2Dd.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.33-B8HVvkJX.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.34-BtkRu1FN.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.35-DBylQbtk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.36-Sg089Kgh.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.37-CYtvbriS.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.38-DKkSLf8Z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.39-CecotKZD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.4-Bv8O3ZMb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.40-DdCvkmOU.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.41-ESn674Hc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.42-DL9V7NNV.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.43-yipO0cyk.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.44-6rTmLZhm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.45-BJAj8lrm.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.46-BDTzMn2c.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.47-Bxd4wGgi.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.48-DxnFBLnH.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.49-DnVD0aOD.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.5-B1wI2pp5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.50-D9JlkZd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.51-D9Vw6Bu3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.52-ClEJk4kn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.53-BSXU0vh-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.54-EcuxkR9v.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.55-CYiFhQX8.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.56--Gk9g8BK.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.57-DnkOPZcy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.58-9MB8504z.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.59-ByxIsN72.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.6-Bmk0dRVw.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.60-Bxwx_aWQ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.61-DA2z5sm7.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.62-C5iJPJZn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.63-DAqrmaEc.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.64-BgXFsljb.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.65-DKiWujvu.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.66-8po4vUZ4.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.67-Cy5qyI9O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.68-BKny7Fy3.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.69-B4VU4u_b.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.7-BuqwNpgA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.70-BCd4n346.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.71-CkQppaWn.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.72-Db7vaoFs.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.73-DI80TYWl.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.74-tMCtDAHB.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.75-Ciw0D5WG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.76-DoLjFgp-.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.77-CpT2uvMy.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.78-CkcJ4iZ1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.79-DsOUJjEM.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.8-DsjypPd6.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.80-C0VwHTte.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.81-DTelu57i.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.82-BiMndGN1.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.83-CVcC6eDG.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.84-DlhZVt_O.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.85-S8I2D3pA.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.86-DozXXpH5.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.87-Dsn0Vuuo.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.88-iNwxxDCr.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.89-B63u_9CZ.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.9-Bi3IzpMI.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.90-ByeH1Pqf.woff2 +0 -0
- package/gui/dist/assets/WantedSansVariable.split.91-UQLlagpm.woff2 +0 -0
- package/gui/dist/assets/brand-mark-A03mw_9y.js +1 -0
- package/gui/dist/assets/geist-cyrillic-ext-wght-normal-DjL33-gN.woff2 +0 -0
- package/gui/dist/assets/geist-cyrillic-wght-normal-BEAKL7Jp.woff2 +0 -0
- package/gui/dist/assets/geist-latin-ext-wght-normal-DC-KSUi6.woff2 +0 -0
- package/gui/dist/assets/geist-latin-wght-normal-BgDaEnEv.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-ext-wght-normal-X_5orZeX.woff2 +0 -0
- package/gui/dist/assets/geist-mono-cyrillic-wght-normal-DiZS0aHC.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-ext-wght-normal-Bwz-egvJ.woff2 +0 -0
- package/gui/dist/assets/geist-mono-latin-wght-normal-XN7g48iV.woff2 +0 -0
- package/gui/dist/assets/geist-mono-symbols2-wght-normal-CO5SzqOn.woff2 +0 -0
- package/gui/dist/assets/geist-mono-vietnamese-wght-normal-DadHysG0.woff2 +0 -0
- package/gui/dist/assets/geist-vietnamese-wght-normal-6IgcOCM7.woff2 +0 -0
- package/gui/dist/assets/index-5REODpG3.css +2 -0
- package/gui/dist/assets/index-BjTIN4to.js +94 -0
- package/gui/dist/assets/segment-thumb-features-Bf6vpwf8.js +1 -0
- package/gui/dist/classic/assets/App-C9Eg3nUo.js +58 -0
- package/gui/dist/{assets/Tray-CEw0y0jR.js → classic/assets/Tray-B8P8cokE.js} +1 -1
- package/gui/dist/classic/assets/index-DFAFnven.js +94 -0
- package/gui/dist/classic/assets/quota-summary-C-4HP4_5.js +1 -0
- package/gui/dist/classic/index.html +47 -0
- package/gui/dist/favicon.png +0 -0
- package/gui/dist/favicon.svg +14 -0
- package/gui/dist/index.html +15 -2
- package/package.json +1 -1
- package/src/adapters/anthropic.ts +17 -8
- package/src/adapters/google.ts +7 -7
- package/src/adapters/kiro/adapter.ts +18 -3
- package/src/adapters/kiro/conversation.ts +8 -8
- package/src/adapters/kiro/payload.ts +45 -12
- package/src/adapters/kiro/stream.ts +169 -12
- package/src/adapters/kiro/structured-output-json.ts +191 -0
- package/src/adapters/kiro/structured-output-schema.ts +542 -0
- package/src/adapters/kiro/structured-output.ts +367 -0
- package/src/adapters/kiro-constants.ts +9 -0
- package/src/adapters/kiro-tools.ts +14 -9
- package/src/adapters/kiro-wire.ts +9 -5
- package/src/adapters/openai-chat/messages.ts +58 -5
- package/src/adapters/openai-chat/mistral-image-limit.ts +50 -0
- package/src/adapters/openai-chat/passthrough.ts +5 -3
- package/src/adapters/openai-chat/tool-schema.ts +83 -13
- package/src/adapters/openai-responses/opengateway-input.ts +18 -6
- package/src/adapters/openai-responses/tool-output-recovery.ts +79 -0
- package/src/adapters/qoder/live-models.ts +115 -1
- package/src/claude/failure-verdict.ts +21 -0
- package/src/claude/inbound-content-options.ts +15 -2
- package/src/claude/inbound-model-options.ts +2 -1
- package/src/claude/inbound-records.ts +2 -0
- package/src/claude/inbound.ts +17 -11
- package/src/claude/outbound.ts +52 -23
- package/src/cli/capabilities-access-remote.ts +13 -0
- package/src/cli/capabilities-base.ts +1 -0
- package/src/cli/capabilities-provider-models.ts +3 -3
- package/src/cli/codex-shim-autorestore.ts +7 -0
- package/src/cli/config-command.ts +11 -2
- package/src/cli/connect.ts +17 -2
- package/src/cli/dispatch.ts +3 -1
- package/src/cli/doctor.ts +95 -7
- package/src/cli/index.ts +12 -7
- package/src/cli/link-apply-restart.ts +9 -2
- package/src/cli/models.ts +124 -38
- package/src/cli/registry.ts +1 -1
- package/src/cli/restart-failure.ts +17 -0
- package/src/cli/stop-approval.ts +2 -2
- package/src/cli/sync-command.ts +1 -1
- package/src/cli/sync-fanout.ts +15 -4
- package/src/cli/system-restart-client.ts +5 -0
- package/src/cli/uninstall-client-state.ts +12 -1
- package/src/cli/update-restart-child.ts +13 -3
- package/src/cli/update-restart-home.ts +6 -3
- package/src/cli/update-restart.ts +36 -19
- package/src/client/connect.ts +4 -1
- package/src/client/hub-client.ts +5 -0
- package/src/client/link-management-relay.ts +39 -2
- package/src/client/link-readiness.ts +3 -1
- package/src/client/machine-api.ts +2 -1
- package/src/client/machine-listener.ts +7 -0
- package/src/client/orphan-token-recovery.ts +322 -0
- package/src/codex/catalog/provider-models.ts +12 -4
- package/src/codex/native-profile-api.ts +27 -1
- package/src/codex/shim-diagnostics.ts +7 -0
- package/src/codex/shim-legacy-record.ts +290 -0
- package/src/codex/shim-windows-refresh.ts +9 -2
- package/src/codex/shim-wrapper-write.ts +7 -0
- package/src/codex/shim.ts +80 -21
- package/src/config/diagnostics.ts +9 -9
- package/src/config/load-degrade.ts +27 -27
- package/src/config/provider-validation.ts +9 -2
- package/src/config/removed-opencode-free-backup.ts +6 -3
- package/src/config/tracked-runtime-inspection.ts +3 -3
- package/src/generated/compatibility-version.json +219 -147
- package/src/images/loop.ts +2 -2
- package/src/lib/client-error-body.ts +37 -6
- package/src/lib/config-ownership-removal.ts +422 -0
- package/src/lib/config-ownership.ts +646 -81
- package/src/lib/context-overflow-verdict.ts +3 -3
- package/src/lib/crash-guard.ts +4 -2
- package/src/lib/desktop-cli-handoff.d.mts +3 -4
- package/src/lib/desktop-cli-handoff.mjs +7 -16
- package/src/lib/errors.ts +1 -0
- package/src/lib/local-management-capability.ts +3 -1
- package/src/lib/messages-error-body.ts +162 -0
- package/src/lib/messages-sse-error-presentation.ts +93 -0
- package/src/lib/passive-read.ts +9 -4
- package/src/lib/socks5-fetch.ts +21 -9
- package/src/lib/upstream-retry.ts +81 -1
- package/src/lib/windows-owner-acl.ts +9 -3
- package/src/lib/winsw.ts +5 -5
- package/src/lib/workflow-budget.ts +3 -1
- package/src/oauth/index.ts +7 -0
- package/src/oauth/store.ts +20 -10
- package/src/protocols/codecs/messages-ir.ts +15 -9
- package/src/protocols/encoders/adapter-events.ts +26 -7
- package/src/protocols/encoders/messages.ts +72 -28
- package/src/providers/antigravity-models.ts +45 -12
- package/src/providers/free-directory.ts +2 -2
- package/src/providers/reasoning-metadata.ts +2 -1
- package/src/providers/registry/entries-extended.ts +9 -0
- package/src/reasoning-effort.ts +7 -2
- package/src/remote/hub-usage.ts +3 -0
- package/src/server/admission-model-scope.ts +1 -1
- package/src/server/admitted-http-turn.ts +2 -1
- package/src/server/anthropic-rate-limit-headers.ts +75 -3
- package/src/server/claude-messages.ts +130 -67
- package/src/server/gui-static.ts +4 -1
- package/src/server/hub-usage.ts +7 -2
- package/src/server/index/link-management.ts +8 -0
- package/src/server/index/ollama-routes.ts +2 -0
- package/src/server/index/serve-options.ts +23 -20
- package/src/server/index/startup-warnings.ts +5 -12
- package/src/server/index/websocket-handler.ts +1 -0
- package/src/server/inference/client-encoder-delivery.ts +5 -1
- package/src/server/management/logs-usage-routes.ts +89 -4
- package/src/server/management/provider-routes.ts +2 -22
- package/src/server/management/qoder-provider-probe.ts +105 -0
- package/src/server/management/route-registry.ts +3 -0
- package/src/server/management/usage-aggregate-cache.ts +15 -5
- package/src/server/management/usage-source-facets.ts +38 -0
- package/src/server/messages-native-tool-guard.ts +11 -3
- package/src/server/messages-native.ts +111 -40
- package/src/server/messages-response-headers.ts +25 -11
- package/src/server/messages-shared.ts +94 -64
- package/src/server/messages-sse-error-filter.ts +199 -0
- package/src/server/request-log.ts +12 -0
- package/src/server/responses/adapter-continuation.ts +11 -5
- package/src/server/responses/adapter-delivery.ts +14 -8
- package/src/server/responses/adapter-dispatch.ts +8 -8
- package/src/server/responses/anthropic-thinking-recovery.ts +2 -2
- package/src/server/responses/codex-auth-error.ts +8 -4
- package/src/server/responses/codex-ws-wire.ts +19 -3
- package/src/server/responses/compact.ts +4 -1
- package/src/server/responses/core-auth.ts +1 -1
- package/src/server/responses/core-combo-failure.ts +2 -0
- package/src/server/responses/core-combo.ts +2 -0
- package/src/server/responses/core-errors.ts +5 -4
- package/src/server/responses/core-options.ts +2 -0
- package/src/server/responses/empty-completion-guard.ts +4 -1
- package/src/server/responses/pacing-overload.ts +1 -1
- package/src/server/responses/passthrough-dispatch.ts +5 -5
- package/src/server/responses/request-prepare.ts +3 -1
- package/src/server/responses/request-transport.ts +9 -8
- package/src/server/responses/response-effects.ts +3 -2
- package/src/server/responses/terminal-guard.ts +30 -0
- package/src/server/restart-replacement.ts +3 -1
- package/src/server/sse-payload-rewrite.ts +23 -11
- package/src/server/workflow-refusal.ts +1 -1
- package/src/server/ws-bridge.ts +4 -0
- package/src/service/definition.ts +36 -4
- package/src/service/launchd.ts +89 -32
- package/src/service/logging.ts +34 -7
- package/src/service/plist-xml.ts +59 -0
- package/src/service/state.ts +8 -0
- package/src/service/systemd-env.ts +2 -0
- package/src/service/systemd.ts +31 -7
- package/src/service/windows-taskxml.ts +16 -7
- package/src/service-manager-probe.ts +4 -10
- package/src/types/provider.ts +2 -0
- package/src/types/request.ts +13 -1
- package/src/update/config-preflight.ts +48 -0
- package/src/update/index.ts +15 -1
- package/src/usage/client.ts +43 -0
- package/src/usage/error-detail.ts +1 -1
- package/src/usage/log.ts +4 -0
- package/src/usage/source-facets.ts +51 -0
- package/src/usage/source-filter.ts +65 -0
- package/src/usage/summary.ts +50 -8
- package/src/web-search/anthropic-executor.ts +105 -24
- package/src/web-search/executor.ts +5 -3
- package/src/web-search/loop.ts +2 -1
- package/src/web-search/progress-stream.ts +64 -5
- package/gui/dist/assets/App-DuNhggE1.js +0 -58
- package/gui/dist/assets/index-CynE_Rue.js +0 -94
- package/gui/dist/assets/quota-summary-VHFSlUuM.js +0 -1
- /package/gui/dist/{assets → classic/assets}/App-B4j-Txmb.css +0 -0
- /package/gui/dist/{assets → classic/assets}/index-CHWwDo9L.css +0 -0
|
@@ -10,12 +10,49 @@ import {
|
|
|
10
10
|
writeFileSync,
|
|
11
11
|
} from "node:fs";
|
|
12
12
|
import { randomUUID } from "node:crypto";
|
|
13
|
+
import { Database } from "bun:sqlite";
|
|
13
14
|
import { isAbsolute, join, relative, resolve, sep } from "node:path";
|
|
14
15
|
import type { GenerationContext } from "./state-store-sweeper";
|
|
15
16
|
import { renameAtomicFile } from "./windows-atomic-replace";
|
|
17
|
+
import {
|
|
18
|
+
canonicalRootUnchanged,
|
|
19
|
+
elevatedRemovalRefusal,
|
|
20
|
+
ownedEntryPresent,
|
|
21
|
+
removeOwnedEntry,
|
|
22
|
+
rootIdentity,
|
|
23
|
+
uninstallRunsElevated,
|
|
24
|
+
type RootIdentity,
|
|
25
|
+
} from "./config-ownership-removal";
|
|
16
26
|
|
|
17
27
|
export const CONFIG_OWNER_FILE = ".opencodex-owner.json";
|
|
18
28
|
export const CONFIG_UNINSTALL_MANIFEST = ".opencodex-uninstall.json";
|
|
29
|
+
/**
|
|
30
|
+
* Cross-process lock for every manifest read-modify-write (#8093). It is the OS-held SQLite write
|
|
31
|
+
* lock that `src/config/mutation-lock.ts` uses: `BEGIN IMMEDIATE` on this file, released when the
|
|
32
|
+
* handle closes, including at process exit or crash, so there is no stale owner to recover.
|
|
33
|
+
*/
|
|
34
|
+
export const CONFIG_OWNERSHIP_LOCK = ".opencodex-uninstall.lock";
|
|
35
|
+
const OWNERSHIP_LOCK_SIDECARS = ["-journal", "-wal", "-shm"] as const;
|
|
36
|
+
/** The section under the lock is a few file operations; a longer wait means a stuck holder. */
|
|
37
|
+
const OWNERSHIP_LOCK_WAIT_MS = 50;
|
|
38
|
+
|
|
39
|
+
/** A registration found the uninstall tombstone and wrote nothing. */
|
|
40
|
+
export class ConfigUninstallInProgressError extends Error {
|
|
41
|
+
readonly code = "CONFIG_UNINSTALL_IN_PROGRESS";
|
|
42
|
+
constructor() {
|
|
43
|
+
// No path: this message can reach logs, and the config root can name the user.
|
|
44
|
+
super("opencodex uninstall is in progress for this config directory; run `ocx uninstall` again to finish it before writing new state there.");
|
|
45
|
+
this.name = "ConfigUninstallInProgressError";
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export class ConfigOwnershipLockError extends Error {
|
|
50
|
+
readonly code = "CONFIG_OWNERSHIP_LOCK_UNAVAILABLE";
|
|
51
|
+
constructor(message: string, options?: { cause?: unknown }) {
|
|
52
|
+
super(message, options);
|
|
53
|
+
this.name = "ConfigOwnershipLockError";
|
|
54
|
+
}
|
|
55
|
+
}
|
|
19
56
|
|
|
20
57
|
export type ConfigRemovalResult = {
|
|
21
58
|
status: "absent" | "removed" | "partial" | "refused";
|
|
@@ -31,6 +68,8 @@ type ConfigOwner = {
|
|
|
31
68
|
|
|
32
69
|
type ConfigUninstallManifest = ConfigOwner & {
|
|
33
70
|
paths: string[];
|
|
71
|
+
/** Tombstone: set under the lock before uninstall snapshots `paths`; registrations then refuse. */
|
|
72
|
+
uninstallStartedAt?: number;
|
|
34
73
|
};
|
|
35
74
|
|
|
36
75
|
const METADATA_MAX_BYTES = 64 * 1024;
|
|
@@ -90,11 +129,66 @@ const INITIAL_OWNED_PATHS = [
|
|
|
90
129
|
"version.json",
|
|
91
130
|
"winsw",
|
|
92
131
|
] as const;
|
|
132
|
+
/**
|
|
133
|
+
* Room an uninstall rerun may use past the usual caps, under its tombstone, to record the opencodex
|
|
134
|
+
* files its own cleanup recreates (the config mutation database, for one). Only initially owned
|
|
135
|
+
* names qualify, each at most once, so a full manifest from an older version cannot strand them and
|
|
136
|
+
* the manifest stays bounded.
|
|
137
|
+
*/
|
|
138
|
+
const RECOVERY_RESERVE_PATHS = INITIAL_OWNED_PATHS.length;
|
|
139
|
+
const RECOVERY_RESERVE_BYTES = INITIAL_OWNED_PATHS.reduce((total, name) => total + Buffer.byteLength(name) + 8, 0);
|
|
93
140
|
const ownershipCache = new Map<string, {
|
|
94
141
|
owner: ConfigOwner;
|
|
95
142
|
manifest: ConfigUninstallManifest;
|
|
96
143
|
} | null>();
|
|
97
144
|
let lastReconciledGeneration = 0;
|
|
145
|
+
/**
|
|
146
|
+
* Manifest identity (dev:ino:size:mtime) this process last observed under the ownership lock.
|
|
147
|
+
* A cached path returns without locking only while the manifest is still that file, so a
|
|
148
|
+
* tombstone written by another process sends even an already-recorded path to the locked check.
|
|
149
|
+
*/
|
|
150
|
+
const lockedManifestIdentity = new Map<string, string>();
|
|
151
|
+
const warnedFullManifest = new Set<string>();
|
|
152
|
+
/**
|
|
153
|
+
* Open while this process runs `ocx uninstall` itself. Its own registrations then skip the
|
|
154
|
+
* tombstone check: the same process runs removeOwnedConfigState afterwards, whose locked snapshot
|
|
155
|
+
* includes whatever they add, so nothing it records is orphaned. Without this, a rerun after an
|
|
156
|
+
* interrupted uninstall would refuse its own teardown steps (the config mutation lock records
|
|
157
|
+
* its database) before it reached the remover that finishes the job. Other processes still refuse.
|
|
158
|
+
*/
|
|
159
|
+
let teardownDepth = 0;
|
|
160
|
+
|
|
161
|
+
type UninstallStep = "snapshot-removed" | "owner-deleted" | "lock-retired";
|
|
162
|
+
let uninstallStepHookForTests: ((step: UninstallStep) => void) | undefined;
|
|
163
|
+
/**
|
|
164
|
+
* Test seam, called inside uninstall's single lock hold: after it removed its snapshot, and after it
|
|
165
|
+
* deleted the owner marker. A hook that throws stops the run there, as a crash would.
|
|
166
|
+
*/
|
|
167
|
+
export function setUninstallStepHookForTests(hook: ((step: UninstallStep) => void) | undefined): void {
|
|
168
|
+
uninstallStepHookForTests = hook;
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
/** Mark this process as the uninstaller until the returned release runs. */
|
|
172
|
+
export function beginConfigOwnershipTeardown(): () => void {
|
|
173
|
+
teardownDepth += 1;
|
|
174
|
+
let released = false;
|
|
175
|
+
return () => {
|
|
176
|
+
if (released) return;
|
|
177
|
+
released = true;
|
|
178
|
+
teardownDepth -= 1;
|
|
179
|
+
// Nothing this scope observed may let a later call skip the tombstone check.
|
|
180
|
+
lockedManifestIdentity.clear();
|
|
181
|
+
};
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
function manifestIdentity(configDir: string): string | undefined {
|
|
185
|
+
try {
|
|
186
|
+
const entry = lstatSync(join(configDir, CONFIG_UNINSTALL_MANIFEST), { bigint: true });
|
|
187
|
+
return entry.isFile() ? `${entry.dev}:${entry.ino}:${entry.size}:${entry.mtimeNs}` : undefined;
|
|
188
|
+
} catch {
|
|
189
|
+
return undefined;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
98
192
|
|
|
99
193
|
export function listLiveConfigOwnershipRoots(currentConfigDir: string): ReadonlySet<string> {
|
|
100
194
|
const currentRoot = ownershipCacheKey(currentConfigDir);
|
|
@@ -134,13 +228,21 @@ function samePath(left: string, right: string): boolean {
|
|
|
134
228
|
: left === right;
|
|
135
229
|
}
|
|
136
230
|
|
|
137
|
-
function readBoundedJson(path: string): unknown {
|
|
231
|
+
function readBoundedJson(path: string, maxBytes = METADATA_MAX_BYTES): unknown {
|
|
232
|
+
return readBoundedJsonSized(path, maxBytes).value;
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function readBoundedJsonSized(path: string, maxBytes: number): { value: unknown; size: number } {
|
|
138
236
|
const metadata = lstatSync(path);
|
|
139
237
|
if (!metadata.isFile() || metadata.isSymbolicLink()) {
|
|
140
238
|
throw new Error("ownership metadata is not a regular file");
|
|
141
239
|
}
|
|
142
|
-
|
|
143
|
-
|
|
240
|
+
// Size first, so an oversized file is refused before it is read; the read is rechecked for a
|
|
241
|
+
// file that grew in between.
|
|
242
|
+
if (metadata.size > maxBytes) throw new Error("ownership metadata is too large");
|
|
243
|
+
const bytes = readFileSync(path);
|
|
244
|
+
if (bytes.length > maxBytes) throw new Error("ownership metadata is too large");
|
|
245
|
+
return { value: JSON.parse(bytes.toString("utf8")) as unknown, size: bytes.length };
|
|
144
246
|
}
|
|
145
247
|
|
|
146
248
|
function isOwner(value: unknown): value is ConfigOwner {
|
|
@@ -154,25 +256,17 @@ function isOwner(value: unknown): value is ConfigOwner {
|
|
|
154
256
|
|
|
155
257
|
function isManifest(value: unknown): value is ConfigUninstallManifest {
|
|
156
258
|
if (!isOwner(value)) return false;
|
|
157
|
-
const paths =
|
|
259
|
+
const { paths, uninstallStartedAt } = value as Record<string, unknown>;
|
|
158
260
|
return Array.isArray(paths)
|
|
159
|
-
&& paths.length <= MANIFEST_MAX_PATHS
|
|
160
|
-
&& paths.every(path => typeof path === "string")
|
|
261
|
+
&& paths.length <= MANIFEST_MAX_PATHS + (uninstallStartedAt === undefined ? 0 : RECOVERY_RESERVE_PATHS)
|
|
262
|
+
&& paths.every(path => typeof path === "string")
|
|
263
|
+
&& (uninstallStartedAt === undefined || Number.isSafeInteger(uninstallStartedAt));
|
|
161
264
|
}
|
|
162
265
|
|
|
163
266
|
function canonicalRoot(configDir: string): string {
|
|
164
267
|
return realpathSync.native(resolve(configDir));
|
|
165
268
|
}
|
|
166
269
|
|
|
167
|
-
function isWithinRoot(root: string, candidate: string): boolean {
|
|
168
|
-
const rel = relative(root, candidate);
|
|
169
|
-
return rel === "" || (
|
|
170
|
-
rel !== ".."
|
|
171
|
-
&& !rel.startsWith(`..${sep}`)
|
|
172
|
-
&& !isAbsolute(rel)
|
|
173
|
-
);
|
|
174
|
-
}
|
|
175
|
-
|
|
176
270
|
function manifestRelativePath(configDir: string, candidatePath: string): string | null {
|
|
177
271
|
const root = resolve(configDir);
|
|
178
272
|
const candidate = resolve(candidatePath);
|
|
@@ -188,6 +282,9 @@ function manifestRelativePath(configDir: string, candidatePath: string): string
|
|
|
188
282
|
return null;
|
|
189
283
|
}
|
|
190
284
|
if (normalized === CONFIG_OWNER_FILE || normalized === CONFIG_UNINSTALL_MANIFEST) return null;
|
|
285
|
+
if (normalized === CONFIG_OWNERSHIP_LOCK || OWNERSHIP_LOCK_SIDECARS.some(suffix => normalized === `${CONFIG_OWNERSHIP_LOCK}${suffix}`)) {
|
|
286
|
+
return null;
|
|
287
|
+
}
|
|
191
288
|
return normalized;
|
|
192
289
|
}
|
|
193
290
|
|
|
@@ -197,7 +294,11 @@ function loadOwnership(configDir: string): { owner: ConfigOwner; manifest: Confi
|
|
|
197
294
|
if (!existsSync(ownerPath) || !existsSync(manifestPath)) return null;
|
|
198
295
|
try {
|
|
199
296
|
const owner = readBoundedJson(ownerPath);
|
|
200
|
-
|
|
297
|
+
// A tombstoned manifest may use the reserve: a home written by an older version can hold a
|
|
298
|
+
// manifest up to the limit, and uninstall must still resume after adding its tombstone.
|
|
299
|
+
const read = readBoundedJsonSized(manifestPath, TOMBSTONED_MANIFEST_MAX_BYTES);
|
|
300
|
+
const manifest = read.value;
|
|
301
|
+
if (isManifest(manifest) && manifest.uninstallStartedAt === undefined && read.size > METADATA_MAX_BYTES) return null;
|
|
201
302
|
const root = canonicalRoot(configDir);
|
|
202
303
|
if (
|
|
203
304
|
!isOwner(owner)
|
|
@@ -221,28 +322,61 @@ function createOwnership(configDir: string): { owner: ConfigOwner; manifest: Con
|
|
|
221
322
|
root: canonicalRoot(configDir),
|
|
222
323
|
};
|
|
223
324
|
const manifest: ConfigUninstallManifest = { ...owner, paths: [...INITIAL_OWNED_PATHS] };
|
|
224
|
-
|
|
325
|
+
// Manifest first, owner marker second; uninstall deletes them in the reverse order (owner marker,
|
|
326
|
+
// then manifest). Both leave a manifest without an owner marker in between, told apart by the
|
|
327
|
+
// tombstone: creation's manifest never carries one, so a home still being created is never
|
|
328
|
+
// mistaken for a stopped uninstall.
|
|
329
|
+
writeFileSync(join(configDir, CONFIG_UNINSTALL_MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`, {
|
|
225
330
|
encoding: "utf8",
|
|
226
331
|
flag: "wx",
|
|
227
332
|
mode: 0o600,
|
|
228
333
|
});
|
|
229
334
|
try {
|
|
230
|
-
writeFileSync(join(configDir,
|
|
335
|
+
writeFileSync(join(configDir, CONFIG_OWNER_FILE), `${JSON.stringify(owner, null, 2)}\n`, {
|
|
231
336
|
encoding: "utf8",
|
|
232
337
|
flag: "wx",
|
|
233
338
|
mode: 0o600,
|
|
234
339
|
});
|
|
235
340
|
} catch (error) {
|
|
236
|
-
try { unlinkSync(join(configDir,
|
|
341
|
+
try { unlinkSync(join(configDir, CONFIG_UNINSTALL_MANIFEST)); } catch { /* incomplete metadata fails closed */ }
|
|
237
342
|
throw error;
|
|
238
343
|
}
|
|
239
344
|
return { owner, manifest };
|
|
240
345
|
}
|
|
241
346
|
|
|
347
|
+
/** Temporary names `writeManifest` uses; one left behind means a write stopped before its rename. */
|
|
348
|
+
const MANIFEST_TEMP_PATTERN = new RegExp(`^${CONFIG_UNINSTALL_MANIFEST.replace(/\./g, "\\.")}\\.\\d+\\.[0-9a-f-]{36}\\.tmp$`);
|
|
349
|
+
|
|
350
|
+
/**
|
|
351
|
+
* Under the lock no manifest write is in progress, so such a temporary file is abandoned. It is
|
|
352
|
+
* removed only when its content shows `writeManifest` wrote it for this home: a manifest carrying
|
|
353
|
+
* this home's random owner id and root. Any other file with a matching name, a truncated write
|
|
354
|
+
* included, is kept, and uninstall reports it as a residual path.
|
|
355
|
+
*/
|
|
356
|
+
function removeAbandonedMetadataTemps(configDir: string, owner: ConfigOwner): void {
|
|
357
|
+
for (const name of readdirSync(configDir)) {
|
|
358
|
+
if (!MANIFEST_TEMP_PATTERN.test(name)) continue;
|
|
359
|
+
const path = join(configDir, name);
|
|
360
|
+
let content: unknown;
|
|
361
|
+
try { content = readBoundedJson(path, TOMBSTONED_MANIFEST_MAX_BYTES); } catch { continue; }
|
|
362
|
+
if (!isManifest(content) || content.ownerId !== owner.ownerId || !samePath(content.root, owner.root)) continue;
|
|
363
|
+
unlinkSync(path);
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
|
|
367
|
+
/** Room the `uninstallStartedAt` tombstone needs on top of a registration's manifest. */
|
|
368
|
+
const TOMBSTONE_RESERVE_BYTES = 64;
|
|
369
|
+
/** Largest manifest uninstall accepts once tombstoned: the tombstone and the recovery reserve on top. */
|
|
370
|
+
const TOMBSTONED_MANIFEST_MAX_BYTES = METADATA_MAX_BYTES + TOMBSTONE_RESERVE_BYTES + RECOVERY_RESERVE_BYTES;
|
|
371
|
+
|
|
372
|
+
function serializeManifest(manifest: ConfigUninstallManifest): string {
|
|
373
|
+
return `${JSON.stringify(manifest, null, 2)}\n`;
|
|
374
|
+
}
|
|
375
|
+
|
|
242
376
|
function writeManifest(configDir: string, manifest: ConfigUninstallManifest): void {
|
|
243
377
|
const path = join(configDir, CONFIG_UNINSTALL_MANIFEST);
|
|
244
378
|
const temp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
245
|
-
writeFileSync(temp,
|
|
379
|
+
writeFileSync(temp, serializeManifest(manifest), { encoding: "utf8", mode: 0o600 });
|
|
246
380
|
try {
|
|
247
381
|
// Same Windows sharing-violation tolerance the config writer has: a
|
|
248
382
|
// scanner holding the manifest must not turn uninstall bookkeeping into a
|
|
@@ -254,25 +388,136 @@ function writeManifest(configDir: string, manifest: ConfigUninstallManifest): vo
|
|
|
254
388
|
}
|
|
255
389
|
}
|
|
256
390
|
|
|
257
|
-
function
|
|
258
|
-
const entry = lstatSync(path);
|
|
259
|
-
if (entry.isSymbolicLink()) {
|
|
260
|
-
|
|
261
|
-
return;
|
|
391
|
+
function fileIdentity(path: string): string {
|
|
392
|
+
const entry = lstatSync(path, { bigint: true });
|
|
393
|
+
if (!entry.isFile() || entry.isSymbolicLink() || entry.nlink !== 1n) {
|
|
394
|
+
throw new ConfigOwnershipLockError("config ownership lock is not a single-link regular file");
|
|
262
395
|
}
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
396
|
+
return `${entry.dev}:${entry.ino}`;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Run `run` while holding the ownership lock. Callers create ownership metadata first: the lock
|
|
401
|
+
* file is never created in a root that has none, so a refused uninstall of a legacy home leaves it
|
|
402
|
+
* untouched. Returns `undefined` without running `run` when the root disappeared, which only
|
|
403
|
+
* happens once an uninstall has finished.
|
|
404
|
+
*/
|
|
405
|
+
function withOwnershipLock<T>(configDir: string, run: () => T): { value: T } | undefined {
|
|
406
|
+
const path = join(configDir, CONFIG_OWNERSHIP_LOCK);
|
|
407
|
+
const ownerPath = join(configDir, CONFIG_OWNER_FILE);
|
|
408
|
+
const manifestPath = join(configDir, CONFIG_UNINSTALL_MANIFEST);
|
|
409
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
410
|
+
// Never lock (and so never create the lock file in) a root without ownership metadata. A
|
|
411
|
+
// tombstoned manifest alone is an uninstall that stopped after deleting the owner marker.
|
|
412
|
+
if (!existsSync(ownerPath) && !existsSync(manifestPath)) return undefined;
|
|
413
|
+
try {
|
|
414
|
+
writeFileSync(path, "", { flag: "wx", mode: 0o600 });
|
|
415
|
+
} catch (error) {
|
|
416
|
+
const code = (error as NodeJS.ErrnoException).code;
|
|
417
|
+
if (code === "ENOENT") return undefined;
|
|
418
|
+
if (code !== "EEXIST") throw error;
|
|
419
|
+
}
|
|
420
|
+
let before: string;
|
|
421
|
+
try { before = fileIdentity(path); } catch (error) {
|
|
422
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") continue;
|
|
423
|
+
throw error;
|
|
424
|
+
}
|
|
425
|
+
let database: Database | undefined;
|
|
426
|
+
try {
|
|
427
|
+
database = new Database(path, { create: false, readwrite: true });
|
|
428
|
+
acquireImmediate(database);
|
|
429
|
+
} catch (cause) {
|
|
430
|
+
try { database?.close(); } catch { /* acquisition already failed */ }
|
|
431
|
+
// A waiter whose lock file was unlinked by a finishing uninstall fails on the stale handle
|
|
432
|
+
// (macOS reports SQLITE_IOERR_VNODE); it retries against whatever the path names now.
|
|
433
|
+
if (lockFileChanged(path, before)) continue;
|
|
434
|
+
const code = cause && typeof cause === "object" && "code" in cause ? String((cause as { code?: unknown }).code) : "";
|
|
435
|
+
throw new ConfigOwnershipLockError(
|
|
436
|
+
code === "SQLITE_BUSY" ? "config ownership metadata is busy in another opencodex process" : "could not lock config ownership metadata",
|
|
437
|
+
{ cause },
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
try {
|
|
441
|
+
// Uninstall unlinks the lock file last; a waiter that locked the unlinked file retries.
|
|
442
|
+
if (lockFileChanged(path, before)) continue;
|
|
443
|
+
return { value: run() };
|
|
444
|
+
} finally {
|
|
445
|
+
// A holder that finds the metadata gone (a finished uninstall) retires the lock it held, and
|
|
446
|
+
// only that file: a new installation may already have created its own lock at the same path.
|
|
447
|
+
// It unlinks the file while still holding it, so a process that takes the old file afterwards
|
|
448
|
+
// sees the path change and retries instead of working beside a new installation's lock.
|
|
449
|
+
// Windows refuses to delete a file any handle has open, this one included, so there the
|
|
450
|
+
// unlink is retried after release and succeeds only when no other process has the file open.
|
|
451
|
+
const finished = !existsSync(ownerPath) && !existsSync(manifestPath);
|
|
452
|
+
const retired = !finished || unlinkLockFile(path, before);
|
|
453
|
+
if (finished && retired) uninstallStepHookForTests?.("lock-retired");
|
|
454
|
+
try { database.exec("ROLLBACK"); } catch { /* close below still releases the OS lock */ }
|
|
455
|
+
try { database.close(); } catch { /* the OS lock is released with the handle */ }
|
|
456
|
+
if (!retired) unlinkLockFile(path, before);
|
|
457
|
+
if (finished) removeEmptyLockSidecars(configDir);
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
throw new ConfigOwnershipLockError("config ownership lock kept changing while it was acquired");
|
|
461
|
+
}
|
|
462
|
+
|
|
463
|
+
function lockFileChanged(path: string, before: string): boolean {
|
|
464
|
+
try { return fileIdentity(path) !== before; } catch (error) {
|
|
465
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return true;
|
|
466
|
+
throw error;
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* `BEGIN IMMEDIATE` with SQLite's own busy wait off, retried only briefly. A registration's section
|
|
472
|
+
* under the lock is a few file operations, so a cooperating holder usually releases within
|
|
473
|
+
* milliseconds. The retry is synchronous: while another process holds the lock (a paused holder, or
|
|
474
|
+
* an uninstall removing files) it blocks the calling thread for at most
|
|
475
|
+
* {@link OWNERSHIP_LOCK_WAIT_MS}, then throws, and the caller reports the registration or uninstall
|
|
476
|
+
* as busy.
|
|
477
|
+
*/
|
|
478
|
+
function acquireImmediate(database: Database): void {
|
|
479
|
+
database.exec("PRAGMA busy_timeout = 0");
|
|
480
|
+
const deadline = Date.now() + OWNERSHIP_LOCK_WAIT_MS;
|
|
481
|
+
for (;;) {
|
|
482
|
+
try {
|
|
483
|
+
database.exec("BEGIN IMMEDIATE");
|
|
484
|
+
return;
|
|
485
|
+
} catch (error) {
|
|
486
|
+
const code = error && typeof error === "object" && "code" in error ? String((error as { code?: unknown }).code) : "";
|
|
487
|
+
if (code !== "SQLITE_BUSY" || Date.now() >= deadline) throw error;
|
|
488
|
+
Bun.sleepSync(2);
|
|
489
|
+
}
|
|
266
490
|
}
|
|
491
|
+
}
|
|
267
492
|
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
493
|
+
/**
|
|
494
|
+
* Unlink the lock file `before` identifies; a file another installation put at the path is left
|
|
495
|
+
* alone. True once the path no longer names that file.
|
|
496
|
+
*/
|
|
497
|
+
function unlinkLockFile(path: string, before: string): boolean {
|
|
498
|
+
try {
|
|
499
|
+
if (lockFileChanged(path, before)) return true;
|
|
500
|
+
unlinkSync(path);
|
|
501
|
+
return true;
|
|
502
|
+
} catch {
|
|
503
|
+
return false; // uninstall reports what remains
|
|
271
504
|
}
|
|
272
|
-
|
|
273
|
-
|
|
505
|
+
}
|
|
506
|
+
|
|
507
|
+
/**
|
|
508
|
+
* Remove the lock's SQLite sidecars once released. SQLite deletes the journal its own transaction
|
|
509
|
+
* created when that transaction ends, and the lock never writes data, so a sidecar this module left
|
|
510
|
+
* is empty. A sidecar name holding data, or a link, is not provably ours: it stays and uninstall
|
|
511
|
+
* reports it.
|
|
512
|
+
*/
|
|
513
|
+
function removeEmptyLockSidecars(configDir: string): void {
|
|
514
|
+
for (const suffix of OWNERSHIP_LOCK_SIDECARS) {
|
|
515
|
+
const path = join(configDir, `${CONFIG_OWNERSHIP_LOCK}${suffix}`);
|
|
516
|
+
try {
|
|
517
|
+
const entry = lstatSync(path);
|
|
518
|
+
if (entry.isFile() && !entry.isSymbolicLink() && entry.nlink === 1 && entry.size === 0) unlinkSync(path);
|
|
519
|
+
} catch { /* absent, or uninstall reports it */ }
|
|
274
520
|
}
|
|
275
|
-
rmdirSync(path);
|
|
276
521
|
}
|
|
277
522
|
|
|
278
523
|
/** Initialize only an empty or already-owned root; do not claim a candidate path. */
|
|
@@ -284,31 +529,254 @@ export function initializeConfigOwnership(configDir: string): boolean {
|
|
|
284
529
|
}
|
|
285
530
|
let ownership = ownershipCache.get(cacheKey);
|
|
286
531
|
if (ownership === undefined) {
|
|
287
|
-
ownership =
|
|
532
|
+
ownership = loadOrCreateOwnership(configDir);
|
|
533
|
+
ownershipCache.set(cacheKey, ownership);
|
|
534
|
+
} else if (ownership === null) {
|
|
535
|
+
// A home cached as unowned may have finished being created by another process since: re-read
|
|
536
|
+
// the metadata (no waiting) so a late owner marker is picked up. A root that has become empty
|
|
537
|
+
// since is claimed like an absent one; a nonempty unowned root still never is.
|
|
538
|
+
ownership = loadOwnership(configDir);
|
|
539
|
+
if (!ownership) {
|
|
540
|
+
try {
|
|
541
|
+
ownership = createOwnership(configDir);
|
|
542
|
+
} catch (error) {
|
|
543
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
544
|
+
ownership = loadOwnership(configDir);
|
|
545
|
+
}
|
|
546
|
+
}
|
|
288
547
|
ownershipCache.set(cacheKey, ownership);
|
|
289
548
|
}
|
|
290
549
|
return ownership !== null;
|
|
291
550
|
}
|
|
292
551
|
|
|
552
|
+
/**
|
|
553
|
+
* The metadata of an uninstall that stopped after deleting the owner marker: a valid, tombstoned
|
|
554
|
+
* manifest for this root and no owner marker. Uninstall deletes the owner marker first and the
|
|
555
|
+
* manifest last, so this state carries the owner id, the root and the exact snapshot. Creation
|
|
556
|
+
* writes an untombstoned manifest first, so it never looks like this.
|
|
557
|
+
*/
|
|
558
|
+
function tombstonedManifestWithoutOwner(configDir: string): { owner: ConfigOwner; manifest: ConfigUninstallManifest } | null {
|
|
559
|
+
if (existsSync(join(configDir, CONFIG_OWNER_FILE))) return null;
|
|
560
|
+
const path = join(configDir, CONFIG_UNINSTALL_MANIFEST);
|
|
561
|
+
if (!existsSync(path)) return null;
|
|
562
|
+
try {
|
|
563
|
+
const manifest = readBoundedJsonSized(path, TOMBSTONED_MANIFEST_MAX_BYTES).value;
|
|
564
|
+
if (!isManifest(manifest) || manifest.uninstallStartedAt === undefined || !samePath(manifest.root, canonicalRoot(configDir))) return null;
|
|
565
|
+
return { owner: { version: 1, ownerId: manifest.ownerId, root: manifest.root }, manifest };
|
|
566
|
+
} catch {
|
|
567
|
+
return null;
|
|
568
|
+
}
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/** Ownership for uninstall: the usual pair, or the tombstoned manifest a stopped uninstall left. */
|
|
572
|
+
function loadOwnershipForUninstall(configDir: string): { owner: ConfigOwner; manifest: ConfigUninstallManifest } | null {
|
|
573
|
+
return loadOwnership(configDir) ?? tombstonedManifestWithoutOwner(configDir);
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
/** How long a first registration waits for another process that is creating the same home. */
|
|
577
|
+
const CONCURRENT_CREATION_WAIT_MS = 100;
|
|
578
|
+
|
|
579
|
+
/**
|
|
580
|
+
* Load the ownership metadata, or create it in an empty root. Two processes can start on the same
|
|
581
|
+
* absent home: the loser of the exclusive manifest write, or one that sees the manifest before the
|
|
582
|
+
* owner marker (creation writes them in that order), waits briefly and loads the winner's metadata
|
|
583
|
+
* instead of caching the home as unowned for the rest of its life.
|
|
584
|
+
*/
|
|
585
|
+
function loadOrCreateOwnership(configDir: string): { owner: ConfigOwner; manifest: ConfigUninstallManifest } | null {
|
|
586
|
+
const deadline = Date.now() + CONCURRENT_CREATION_WAIT_MS;
|
|
587
|
+
for (;;) {
|
|
588
|
+
const loaded = loadOwnership(configDir);
|
|
589
|
+
if (loaded) return loaded;
|
|
590
|
+
try {
|
|
591
|
+
const created = createOwnership(configDir);
|
|
592
|
+
if (created) return created;
|
|
593
|
+
} catch (error) {
|
|
594
|
+
if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
|
|
595
|
+
}
|
|
596
|
+
const creating = existsSync(join(configDir, CONFIG_UNINSTALL_MANIFEST)) && !existsSync(join(configDir, CONFIG_OWNER_FILE))
|
|
597
|
+
&& !tombstonedManifestWithoutOwner(configDir);
|
|
598
|
+
if (!creating || Date.now() >= deadline) return loadOwnership(configDir);
|
|
599
|
+
Bun.sleepSync(5);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
type RecordOutcome = {
|
|
604
|
+
ownership: { owner: ConfigOwner; manifest: ConfigUninstallManifest };
|
|
605
|
+
recorded: boolean;
|
|
606
|
+
identity: string | undefined;
|
|
607
|
+
};
|
|
608
|
+
|
|
609
|
+
/** What a registration did: recorded the path, found no ownership to record it in, or found the manifest full. */
|
|
610
|
+
export type OwnedPathRegistration = "recorded" | "unowned" | "full";
|
|
611
|
+
|
|
293
612
|
export function recordOwnedConfigPath(configDir: string, candidatePath: string): boolean {
|
|
613
|
+
return registerOwnedConfigPath(configDir, candidatePath) === "recorded";
|
|
614
|
+
}
|
|
615
|
+
|
|
616
|
+
function entryExists(path: string): boolean {
|
|
617
|
+
try {
|
|
618
|
+
lstatSync(path);
|
|
619
|
+
return true;
|
|
620
|
+
} catch (error) {
|
|
621
|
+
if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
|
|
622
|
+
throw error;
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
/**
|
|
627
|
+
* {@link recordOwnedConfigPath} with the reason a path was not recorded, for callers that must tell
|
|
628
|
+
* an unowned home (keep working as before) from an owned home whose manifest is full (whatever they
|
|
629
|
+
* create there survives uninstall).
|
|
630
|
+
*/
|
|
631
|
+
export function registerOwnedConfigPath(configDir: string, candidatePath: string): OwnedPathRegistration {
|
|
294
632
|
const rel = manifestRelativePath(configDir, candidatePath);
|
|
295
|
-
if (!rel) return
|
|
296
|
-
if (!initializeConfigOwnership(configDir)) return false;
|
|
633
|
+
if (!rel) return "unowned";
|
|
297
634
|
const cacheKey = ownershipCacheKey(configDir);
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
635
|
+
if (initializeConfigOwnership(configDir)) {
|
|
636
|
+
const ownership = ownershipCache.get(cacheKey);
|
|
637
|
+
if (!ownership) return "unowned";
|
|
638
|
+
if (ownership.manifest.paths.includes(rel)) {
|
|
639
|
+
const seen = lockedManifestIdentity.get(cacheKey);
|
|
640
|
+
if (seen !== undefined && seen === manifestIdentity(configDir)) return "recorded";
|
|
641
|
+
}
|
|
642
|
+
} else if (!tombstonedManifestWithoutOwner(configDir)) {
|
|
643
|
+
return "unowned";
|
|
644
|
+
} else if (teardownDepth === 0) {
|
|
645
|
+
// Between uninstall's two final unlinks only the tombstoned manifest remains. That is an
|
|
646
|
+
// uninstall finishing (or stopped there), not an unowned home.
|
|
647
|
+
throw new ConfigUninstallInProgressError();
|
|
648
|
+
}
|
|
649
|
+
// Read-modify-write against the manifest on disk, never the cache: another process may have
|
|
650
|
+
// recorded paths or started an uninstall since this one cached it (#8093).
|
|
651
|
+
let locked: { value: RecordOutcome | null } | undefined;
|
|
652
|
+
try {
|
|
653
|
+
locked = withOwnershipLock(configDir, (): RecordOutcome | null => {
|
|
654
|
+
let current = loadOwnership(configDir);
|
|
655
|
+
if (!current) {
|
|
656
|
+
// A process that cached the ownership before uninstall deleted the owner marker lands here.
|
|
657
|
+
const stopped = tombstonedManifestWithoutOwner(configDir);
|
|
658
|
+
if (!stopped) return null;
|
|
659
|
+
if (teardownDepth === 0) throw new ConfigUninstallInProgressError();
|
|
660
|
+
current = stopped;
|
|
661
|
+
}
|
|
662
|
+
const tombstoned = current.manifest.uninstallStartedAt !== undefined;
|
|
663
|
+
if (tombstoned && teardownDepth === 0) throw new ConfigUninstallInProgressError();
|
|
664
|
+
if (current.manifest.paths.includes(rel)) return { ownership: current, recorded: true, identity: manifestIdentity(configDir) };
|
|
665
|
+
// Under a tombstone only this process's own uninstall rerun registers: it records a path it is
|
|
666
|
+
// about to create, so its remover takes that path too, and never adopts an existing entry the
|
|
667
|
+
// snapshot does not list (with or without the owner marker).
|
|
668
|
+
if (tombstoned && entryExists(join(configDir, ...rel.split("/")))) return null;
|
|
669
|
+
const manifest = { ...current.manifest, paths: [...current.manifest.paths, rel].sort() };
|
|
670
|
+
// A manifest over either cap would fail validation and strand every recorded path. The byte
|
|
671
|
+
// check leaves room for the tombstone uninstall adds later. Under the tombstone, an initially
|
|
672
|
+
// owned name may use the recovery reserve instead.
|
|
673
|
+
const bytes = Buffer.byteLength(serializeManifest(manifest));
|
|
674
|
+
const withinCaps = manifest.paths.length <= MANIFEST_MAX_PATHS && bytes + TOMBSTONE_RESERVE_BYTES <= METADATA_MAX_BYTES;
|
|
675
|
+
const withinRecovery = tombstoned && (INITIAL_OWNED_PATHS as readonly string[]).includes(rel)
|
|
676
|
+
&& manifest.paths.length <= MANIFEST_MAX_PATHS + RECOVERY_RESERVE_PATHS && bytes <= TOMBSTONED_MANIFEST_MAX_BYTES;
|
|
677
|
+
if (!withinCaps && !withinRecovery) {
|
|
678
|
+
return { ownership: current, recorded: false, identity: manifestIdentity(configDir) };
|
|
679
|
+
}
|
|
680
|
+
writeManifest(configDir, manifest);
|
|
681
|
+
return { ownership: { owner: current.owner, manifest }, recorded: true, identity: manifestIdentity(configDir) };
|
|
682
|
+
});
|
|
683
|
+
} catch (error) {
|
|
684
|
+
if (!(error instanceof ConfigOwnershipLockError)) throw error;
|
|
685
|
+
// A busy lock blocks nothing for a path the manifest already lists. The manifest is replaced
|
|
686
|
+
// atomically, so an unlocked read is a consistent version: accept the path unless that version
|
|
687
|
+
// carries an uninstall tombstone. Only a new path needs the lock, and it still fails here.
|
|
688
|
+
const current = loadOwnership(configDir) ?? tombstonedManifestWithoutOwner(configDir);
|
|
689
|
+
if (current?.manifest.uninstallStartedAt !== undefined && teardownDepth === 0) throw new ConfigUninstallInProgressError();
|
|
690
|
+
if (current?.manifest.paths.includes(rel)) return "recorded";
|
|
691
|
+
throw error;
|
|
692
|
+
}
|
|
693
|
+
if (!locked?.value) {
|
|
694
|
+
ownershipCache.delete(cacheKey);
|
|
695
|
+
lockedManifestIdentity.delete(cacheKey);
|
|
696
|
+
return "unowned";
|
|
697
|
+
}
|
|
698
|
+
// A tombstoned manifest is never cached or remembered for the fast path: only the teardown scope
|
|
699
|
+
// may register under it, and once that scope ends every call must see the tombstone again.
|
|
700
|
+
if (locked.value.ownership.manifest.uninstallStartedAt !== undefined) {
|
|
701
|
+
ownershipCache.delete(cacheKey);
|
|
702
|
+
lockedManifestIdentity.delete(cacheKey);
|
|
703
|
+
} else {
|
|
704
|
+
ownershipCache.set(cacheKey, locked.value.ownership);
|
|
705
|
+
if (locked.value.identity === undefined) lockedManifestIdentity.delete(cacheKey);
|
|
706
|
+
else lockedManifestIdentity.set(cacheKey, locked.value.identity);
|
|
707
|
+
}
|
|
708
|
+
if (!locked.value.recorded && !warnedFullManifest.has(cacheKey)) {
|
|
709
|
+
warnedFullManifest.add(cacheKey);
|
|
710
|
+
// Uninstall still reports such a file as a residual path; it just cannot remove it.
|
|
711
|
+
console.warn("[opencodex] The config ownership manifest is full; new files will not be removed by uninstall.");
|
|
712
|
+
}
|
|
713
|
+
return locked.value.recorded ? "recorded" : "full";
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
/**
|
|
717
|
+
* What a finished uninstall can leave when a lock file could not be unlinked (Windows keeps a file
|
|
718
|
+
* another process holds open): nothing but this module's lock files. Without ownership metadata
|
|
719
|
+
* nothing proves where such a name came from, so only files that hold no data qualify: the lock is
|
|
720
|
+
* a SQLite transaction that never writes, so its file and any sidecar stay empty. The main lock file
|
|
721
|
+
* must be among them, and each one is a single-link regular file. Anything else is refused untouched.
|
|
722
|
+
*/
|
|
723
|
+
function onlyOwnershipLockFilesRemain(configDir: string): boolean {
|
|
724
|
+
const names = readdirSync(configDir);
|
|
725
|
+
const lockNames = new Set([CONFIG_OWNERSHIP_LOCK, ...OWNERSHIP_LOCK_SIDECARS.map(suffix => `${CONFIG_OWNERSHIP_LOCK}${suffix}`)]);
|
|
726
|
+
return names.includes(CONFIG_OWNERSHIP_LOCK) && names.every(name => {
|
|
727
|
+
if (!lockNames.has(name)) return false;
|
|
728
|
+
const entry = lstatSync(join(configDir, name));
|
|
729
|
+
return entry.isFile() && !entry.isSymbolicLink() && entry.nlink === 1 && entry.size === 0;
|
|
730
|
+
});
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
/** Remove leftover lock files only if no other process holds the lock (an uninstall still finishing). */
|
|
734
|
+
function removeIdleLockFiles(configDir: string): "removed" | "busy" {
|
|
735
|
+
const path = join(configDir, CONFIG_OWNERSHIP_LOCK);
|
|
736
|
+
const before = fileIdentity(path);
|
|
737
|
+
const database = new Database(path, { create: false, readwrite: true });
|
|
738
|
+
try {
|
|
739
|
+
acquireImmediate(database);
|
|
740
|
+
} catch (error) {
|
|
741
|
+
try { database.close(); } catch { /* acquisition already failed */ }
|
|
742
|
+
if (error && typeof error === "object" && "code" in error && (error as { code?: unknown }).code === "SQLITE_BUSY") return "busy";
|
|
743
|
+
throw error;
|
|
744
|
+
}
|
|
745
|
+
let same: boolean;
|
|
746
|
+
try {
|
|
747
|
+
same = !lockFileChanged(path, before);
|
|
748
|
+
} finally {
|
|
749
|
+
try { database.exec("ROLLBACK"); } catch { /* close releases it */ }
|
|
750
|
+
database.close();
|
|
751
|
+
}
|
|
752
|
+
// Taking the lock proved no process holds it. The files are checked again only after release,
|
|
753
|
+
// because while held SQLite keeps this transaction's own rollback journal beside the lock file and
|
|
754
|
+
// deletes it when the transaction ends. Nothing else takes the lock in between: without ownership
|
|
755
|
+
// metadata no registration locks this root, creation never claims a nonempty one, and a second run
|
|
756
|
+
// of this cleanup removes the same files.
|
|
757
|
+
if (!same || !onlyOwnershipLockFilesRemain(configDir)) return "busy";
|
|
758
|
+
if (!unlinkLockFile(path, before)) throw new Error("the ownership lock file could not be removed");
|
|
759
|
+
removeEmptyLockSidecars(configDir);
|
|
760
|
+
return "removed";
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
/** The elevated-run check; null when the run is not elevated. */
|
|
764
|
+
function privilegeCheck(configDir: string): { refusal: string | null } | null {
|
|
765
|
+
if (!uninstallRunsElevated()) return null;
|
|
766
|
+
return { refusal: elevatedRemovalRefusal(configDir) };
|
|
767
|
+
}
|
|
768
|
+
|
|
769
|
+
/**
|
|
770
|
+
* Read-only check `ocx uninstall` runs before its first teardown step: the reason an elevated run
|
|
771
|
+
* must not touch this home, or null. The remover repeats it before taking the lock.
|
|
772
|
+
*/
|
|
773
|
+
export function uninstallPrivilegeRefusal(configDir: string): string | null {
|
|
774
|
+
return privilegeCheck(configDir)?.refusal ?? null;
|
|
308
775
|
}
|
|
309
776
|
|
|
310
777
|
export function removeOwnedConfigState(configDir: string): ConfigRemovalResult {
|
|
311
778
|
ownershipCache.delete(ownershipCacheKey(configDir));
|
|
779
|
+
lockedManifestIdentity.delete(ownershipCacheKey(configDir));
|
|
312
780
|
if (!existsSync(configDir)) return { status: "absent", residualPaths: [] };
|
|
313
781
|
const root = lstatSync(configDir);
|
|
314
782
|
if (!root.isDirectory() || root.isSymbolicLink()) {
|
|
@@ -318,8 +786,65 @@ export function removeOwnedConfigState(configDir: string): ConfigRemovalResult {
|
|
|
318
786
|
residualPaths: [configDir],
|
|
319
787
|
};
|
|
320
788
|
}
|
|
321
|
-
|
|
322
|
-
|
|
789
|
+
// Everything below works on the canonical root, resolved once here, so no later step goes back
|
|
790
|
+
// through the spelling the caller passed. Residual paths are reported in that spelling.
|
|
791
|
+
let canonical: string;
|
|
792
|
+
let identity: RootIdentity;
|
|
793
|
+
try {
|
|
794
|
+
canonical = canonicalRoot(configDir);
|
|
795
|
+
identity = rootIdentity(canonical);
|
|
796
|
+
} catch {
|
|
797
|
+
return { status: "refused", reason: "config ownership root is not a real directory", residualPaths: [configDir] };
|
|
798
|
+
}
|
|
799
|
+
const result = removeCanonicalOwnedConfigState(canonical, identity);
|
|
800
|
+
return { ...result, residualPaths: result.residualPaths.map(path => callerSpelling(path, canonical, configDir)) };
|
|
801
|
+
}
|
|
802
|
+
|
|
803
|
+
function callerSpelling(path: string, canonical: string, configDir: string): string {
|
|
804
|
+
if (path === canonical) return configDir;
|
|
805
|
+
const rel = relative(canonical, path);
|
|
806
|
+
return rel && rel !== ".." && !rel.startsWith(`..${sep}`) && !isAbsolute(rel) ? join(configDir, rel) : path;
|
|
807
|
+
}
|
|
808
|
+
|
|
809
|
+
function removeCanonicalOwnedConfigState(configDir: string, identity: RootIdentity): ConfigRemovalResult {
|
|
810
|
+
// `configDir` is the canonical root resolved once by the caller, and `identity` the directory it
|
|
811
|
+
// named then. It is never resolved again: each step below that acts on it first confirms it is still
|
|
812
|
+
// that directory, a real one resolving to itself. A change before anything is written is refused;
|
|
813
|
+
// one found later ends the run partial, and the tombstone lets a rerun finish.
|
|
814
|
+
const rootChanged: ConfigRemovalResult = {
|
|
815
|
+
status: "refused",
|
|
816
|
+
reason: "the config directory changed while uninstall ran; run 'ocx uninstall' again",
|
|
817
|
+
residualPaths: [configDir],
|
|
818
|
+
};
|
|
819
|
+
const rootMoved: ConfigRemovalResult = {
|
|
820
|
+
status: "partial",
|
|
821
|
+
reason: "the config directory changed while uninstall ran; run 'ocx uninstall' again",
|
|
822
|
+
residualPaths: [configDir],
|
|
823
|
+
};
|
|
824
|
+
ownershipCache.delete(ownershipCacheKey(configDir));
|
|
825
|
+
lockedManifestIdentity.delete(ownershipCacheKey(configDir));
|
|
826
|
+
// Before the lock exists or anything is written, so a refused elevated run changes nothing.
|
|
827
|
+
const privilege = privilegeCheck(configDir);
|
|
828
|
+
if (privilege?.refusal) return { status: "refused", reason: privilege.refusal, residualPaths: [configDir] };
|
|
829
|
+
if (!canonicalRootUnchanged(configDir, identity)) return rootChanged;
|
|
830
|
+
if (!loadOwnershipForUninstall(configDir)) {
|
|
831
|
+
// A finished uninstall whose lock file could not be unlinked (Windows keeps a file another
|
|
832
|
+
// process holds open) leaves only lock files. They are removed once no process holds the lock.
|
|
833
|
+
if (onlyOwnershipLockFilesRemain(configDir)) {
|
|
834
|
+
try {
|
|
835
|
+
if (removeIdleLockFiles(configDir) === "busy") {
|
|
836
|
+
return { status: "refused", reason: "another opencodex process holds the ownership lock; retry shortly", residualPaths: [configDir] };
|
|
837
|
+
}
|
|
838
|
+
rmdirSync(configDir);
|
|
839
|
+
return { status: "removed", residualPaths: [] };
|
|
840
|
+
} catch (error) {
|
|
841
|
+
return {
|
|
842
|
+
status: "partial",
|
|
843
|
+
reason: `could not remove the ownership lock: ${error instanceof Error ? error.message : String(error)}`,
|
|
844
|
+
residualPaths: readdirSync(configDir).map(name => join(configDir, name)),
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
}
|
|
323
848
|
return {
|
|
324
849
|
status: "refused",
|
|
325
850
|
reason: "config ownership metadata is missing or invalid",
|
|
@@ -327,42 +852,82 @@ export function removeOwnedConfigState(configDir: string): ConfigRemovalResult {
|
|
|
327
852
|
};
|
|
328
853
|
}
|
|
329
854
|
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
};
|
|
338
|
-
}
|
|
339
|
-
}
|
|
340
|
-
|
|
341
|
-
const rootPath = canonicalRoot(configDir);
|
|
342
|
-
for (const rel of ownership.manifest.paths) {
|
|
343
|
-
const path = join(configDir, ...rel.split("/"));
|
|
344
|
-
if (!existsSync(path)) continue;
|
|
345
|
-
try {
|
|
346
|
-
removeOwnedEntry(rootPath, path);
|
|
347
|
-
} catch (error) {
|
|
348
|
-
return {
|
|
349
|
-
status: "partial",
|
|
350
|
-
reason: `could not remove owned path ${rel}: ${error instanceof Error ? error.message : String(error)}`,
|
|
351
|
-
residualPaths: [path],
|
|
352
|
-
};
|
|
353
|
-
}
|
|
354
|
-
}
|
|
355
|
-
|
|
855
|
+
// One lock hold covers the whole run: validate, tombstone, snapshot, remove the snapshot, delete
|
|
856
|
+
// the owner marker and then the manifest. While it is held no other process can record a path (a
|
|
857
|
+
// listed path read without the lock sees the tombstone and refuses, a new path needs the lock),
|
|
858
|
+
// and a second uninstall is refused as busy, so nothing can be recorded or recreated behind this
|
|
859
|
+
// run. A run interrupted at any point leaves the tombstoned manifest, which carries the owner id,
|
|
860
|
+
// the root and the exact snapshot, so a rerun finishes from it.
|
|
861
|
+
let outcome: ConfigRemovalResult;
|
|
356
862
|
try {
|
|
357
|
-
|
|
358
|
-
|
|
863
|
+
const locked = withOwnershipLock(configDir, (): ConfigRemovalResult => {
|
|
864
|
+
const ownership = loadOwnershipForUninstall(configDir);
|
|
865
|
+
if (!ownership) {
|
|
866
|
+
return { status: "refused", reason: "config ownership metadata is missing or invalid", residualPaths: [configDir] };
|
|
867
|
+
}
|
|
868
|
+
for (const rel of ownership.manifest.paths) {
|
|
869
|
+
if (manifestRelativePath(configDir, join(configDir, ...rel.split("/"))) !== rel) {
|
|
870
|
+
return { status: "refused", reason: "config ownership manifest contains an unsafe path", residualPaths: [configDir] };
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
// Checked again under the lock and before the tombstone: the manifest, ownership, modes and the
|
|
874
|
+
// tree may all have changed since the unlocked check.
|
|
875
|
+
const lockedRefusal = privilege ? elevatedRemovalRefusal(configDir) : null;
|
|
876
|
+
if (lockedRefusal) return { status: "refused", reason: lockedRefusal, residualPaths: [configDir] };
|
|
877
|
+
if (!canonicalRootUnchanged(configDir, identity)) return rootChanged;
|
|
878
|
+
if (ownership.manifest.uninstallStartedAt === undefined) {
|
|
879
|
+
writeManifest(configDir, { ...ownership.manifest, uninstallStartedAt: Date.now() });
|
|
880
|
+
}
|
|
881
|
+
if (!canonicalRootUnchanged(configDir, identity)) return rootMoved;
|
|
882
|
+
removeAbandonedMetadataTemps(configDir, ownership.owner);
|
|
883
|
+
const rootPath = configDir;
|
|
884
|
+
const elevatedUid = process.platform !== "win32" && uninstallRunsElevated() ? process.geteuid?.() : undefined;
|
|
885
|
+
for (const rel of ownership.manifest.paths) {
|
|
886
|
+
const parts = rel.split("/");
|
|
887
|
+
const path = join(configDir, ...parts);
|
|
888
|
+
try {
|
|
889
|
+
// lstat-based: a listed symlink whose target is gone is still ours to unlink, and a link on
|
|
890
|
+
// the way to an entry is reported rather than read as absence.
|
|
891
|
+
if (ownedEntryPresent(rootPath, parts)) removeOwnedEntry(rootPath, parts, { elevatedUid, rootIdentity: identity });
|
|
892
|
+
} catch (error) {
|
|
893
|
+
return {
|
|
894
|
+
status: "partial",
|
|
895
|
+
reason: `could not remove owned path ${rel}: ${error instanceof Error ? error.message : String(error)}`,
|
|
896
|
+
residualPaths: [path],
|
|
897
|
+
};
|
|
898
|
+
}
|
|
899
|
+
}
|
|
900
|
+
uninstallStepHookForTests?.("snapshot-removed");
|
|
901
|
+
if (!canonicalRootUnchanged(configDir, identity)) return rootMoved;
|
|
902
|
+
try {
|
|
903
|
+
// Owner marker first, manifest last: until the end the tombstoned manifest stays as the record
|
|
904
|
+
// a rerun resumes from, and creation (manifest first) never leaves that state.
|
|
905
|
+
try { unlinkSync(join(configDir, CONFIG_OWNER_FILE)); } catch (error) {
|
|
906
|
+
if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error;
|
|
907
|
+
}
|
|
908
|
+
uninstallStepHookForTests?.("owner-deleted");
|
|
909
|
+
unlinkSync(join(configDir, CONFIG_UNINSTALL_MANIFEST));
|
|
910
|
+
} catch (error) {
|
|
911
|
+
return {
|
|
912
|
+
status: "partial",
|
|
913
|
+
reason: `could not remove ownership metadata: ${error instanceof Error ? error.message : String(error)}`,
|
|
914
|
+
residualPaths: readdirSync(configDir).map(name => join(configDir, name)),
|
|
915
|
+
};
|
|
916
|
+
}
|
|
917
|
+
return { status: "removed", residualPaths: [] };
|
|
918
|
+
});
|
|
919
|
+
outcome = locked?.value
|
|
920
|
+
?? { status: "refused", reason: "config ownership metadata is missing or invalid", residualPaths: [configDir] };
|
|
359
921
|
} catch (error) {
|
|
360
|
-
|
|
361
|
-
status: "
|
|
362
|
-
reason: `could not
|
|
363
|
-
residualPaths:
|
|
922
|
+
outcome = {
|
|
923
|
+
status: "refused",
|
|
924
|
+
reason: `could not lock the ownership manifest: ${error instanceof Error ? error.message : String(error)}`,
|
|
925
|
+
residualPaths: [configDir],
|
|
364
926
|
};
|
|
365
927
|
}
|
|
928
|
+
if (outcome.status !== "removed") return outcome;
|
|
929
|
+
if (!canonicalRootUnchanged(configDir, identity)) return rootMoved;
|
|
930
|
+
// The lock holder retired its own lock file on release; one that remains (Windows) is reported.
|
|
366
931
|
const residualPaths = readdirSync(configDir).map(name => join(configDir, name));
|
|
367
932
|
if (residualPaths.length > 0) {
|
|
368
933
|
return {
|