@aiwayds/dsh-opentui 0.27.1 → 0.28.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/CHANGELOG.md +38 -15
- package/README.md +38 -182
- package/bin/dsh-opentui.mjs +54 -258
- package/bin/lib/launcher.mjs +29 -187
- package/dist/client/index.js +7585 -16584
- package/dist/client/index.js.map +26 -51
- package/dist/locales/en.json +21 -8
- package/dist/locales/zh-CN.json +21 -8
- package/package.json +7 -11
- package/scripts/lib/companion-policy.mjs +16 -0
- package/scripts/lib/inproc-companions.mjs +128 -38
- package/scripts/lib/migration-io.mjs +231 -0
- package/scripts/lib/migration.mjs +724 -0
- package/scripts/lib/patch-ownership-state.mjs +42 -0
- package/scripts/lib/patch-ownership.mjs +1428 -0
- package/scripts/lib/profile-lock.mjs +185 -0
- package/scripts/lib/profile-name.d.mts +1 -0
- package/scripts/lib/profile-name.mjs +2 -0
- package/scripts/lib/provision-run-lock.mjs +223 -0
- package/scripts/provision-inproc-profile.mjs +601 -286
- package/dist/host-launch.mjs +0 -1293
- package/dist/host-launch.mjs.map +0 -19
- package/dist/scripts/idle-reaper.mjs +0 -173
- package/dist/watchdog.mjs +0 -476
- package/dist/watchdog.mjs.map +0 -16
- package/scripts/e2e-client.mjs +0 -1122
- package/scripts/e2e-sweep.mjs +0 -932
- package/scripts/idle-reaper.mjs +0 -173
- package/scripts/lib/provision-plan.mjs +0 -899
- package/scripts/lib/provision-state.mjs +0 -294
- package/scripts/lib/upgrade-plan.mjs +0 -489
- package/scripts/provision-opentui-profile.mjs +0 -806
- package/scripts/upgrade.mjs +0 -1149
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// provision-inproc-profile.mjs — idempotent provisioning of the fixed
|
|
3
|
-
// `opentui-
|
|
3
|
+
// `opentui-monday` host profile (ADR-0009 decision 3; T3 of the in-process
|
|
4
4
|
// bridge plan).
|
|
5
5
|
//
|
|
6
6
|
// Invoked by the launcher on EVERY start (S6: bridge is the sole seam; the
|
|
7
7
|
// former env escape hatch that skipped provisioning is removed with it).
|
|
8
8
|
// The `opentui` profile path is otherwise untouched.
|
|
9
|
-
// Eight steps (the first is the host-version gate). Steps 1-
|
|
10
|
-
// local-FS only; step
|
|
9
|
+
// Eight steps (the first is the host-version gate). Steps 1-4 and 6-8 are
|
|
10
|
+
// local-FS only; step 5 (companions) is the one unfrozen step that MAY run a
|
|
11
11
|
// package manager (user decision 2026-11-22 — "npm 安装好的时候,registry 和其他几个依赖插件,默认装好").
|
|
12
12
|
//
|
|
13
13
|
// [1/8] host — detect the running dsh version. OUTSIDE the supported
|
|
@@ -19,22 +19,23 @@
|
|
|
19
19
|
// exact-version exemption in compatibility.json. Never
|
|
20
20
|
// grants outside the window: --accept-risk is not a way to
|
|
21
21
|
// mask a genuine incompatibility.
|
|
22
|
-
// [2/8] manifest — write $DSH_HOME/profiles/opentui-
|
|
22
|
+
// [2/8] manifest — write $DSH_HOME/profiles/opentui-monday/package.json with
|
|
23
23
|
// dsh.profile.bundles = [@deepseek-ai/dsh-base,
|
|
24
24
|
// @aiwayds/dsh-opentui-bridge] PLUS any companion bundles
|
|
25
25
|
// already declared in dependencies. NO @deepseek-ai
|
|
26
|
-
// dependency
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
|
|
26
|
+
// dependency (wild-package shadowing guard): the host's
|
|
27
|
+
// installation-first resolution supplies them; ONE lock section.
|
|
28
|
+
// [3/8] workspace — ensure pnpm-workspace.yaml: packages [.], nodeLinker
|
|
29
|
+
// hoisted, autoInstallPeers false. Write the fixed template
|
|
30
|
+
// when absent; fail-fast on conflicts (or, with --repair,
|
|
31
|
+
// back up as .bak-<timestamp> + rewrite) before companions.
|
|
32
|
+
// [4/8] copy — materialize node_modules/@aiwayds/dsh-opentui-bridge as a
|
|
32
33
|
// REAL DIRECTORY COPY of THIS installation's dist/bridge.
|
|
33
34
|
// S6 symlink-debt retirement: no absolute symlink (no path
|
|
34
35
|
// binding, no multi-worktree last-writer-wins, no dangling
|
|
35
36
|
// link when a worktree is removed). Converged every launch;
|
|
36
37
|
// idempotent when the copy's index.js hash matches.
|
|
37
|
-
// [
|
|
38
|
+
// [5/8] companions — install the minimal companion set (default: the
|
|
38
39
|
// @aiwayds/dsh-subagent-registry bundle, which self-mounts
|
|
39
40
|
// the `use_agent` tool through its own cordis.patch.yml).
|
|
40
41
|
// Resolves `latest`, guards major/downgrade, skips when
|
|
@@ -43,28 +44,28 @@
|
|
|
43
44
|
// missing global `dsh` is a WARN (never a boot blocker):
|
|
44
45
|
// stale manifest declarations from a half-write are removed
|
|
45
46
|
// and hosts without dsh skip companions with a warning.
|
|
46
|
-
// Step
|
|
47
|
+
// Step 6 then verifies that whatever remains declared in
|
|
47
48
|
// the manifest is fully mounted.
|
|
48
|
-
// [
|
|
49
|
+
// [6/8] verify — confirm the bridge is a real directory carrying the
|
|
49
50
|
// shipped files; refuse any @deepseek-ai copy in the profile;
|
|
50
51
|
// cross-check companion manifest deps <-> bundle entries <-
|
|
51
52
|
// -> installed node_modules (no half-provisioned state).
|
|
52
|
-
// Step
|
|
53
|
+
// Step 5 drops stale declarations an unsuccessful add left
|
|
53
54
|
// behind, so this guard never blocks a boot for something
|
|
54
55
|
// the provisioning pass itself could not install offline.
|
|
55
|
-
// [
|
|
56
|
+
// [7/8] identity — T5 guard: hash the materialized bridge's index.js and
|
|
56
57
|
// compare with the build-time fingerprint shipped in THIS
|
|
57
58
|
// installation's dist/bridge/bundle-fingerprint.json, plus
|
|
58
59
|
// name / version. No realpath-prefix hard binding.
|
|
59
|
-
// [
|
|
60
|
-
//
|
|
60
|
+
// [2/8] patch — converge cordis.patch.yml with the embedded template in the
|
|
61
|
+
// SAME lock as the manifest (web-app
|
|
61
62
|
// compensation rows removed, profileRevision stamped). The
|
|
62
63
|
// template also registers the standalone sessionController
|
|
63
64
|
// shim plus the real @deepseek-ai/dsh-api-session-controller
|
|
64
65
|
// plugin — no dsh-web-app bundle is pulled in. Companion
|
|
65
66
|
// mounts ride their own bundle patches (activated by the
|
|
66
67
|
// manifest bundle entries), so no duplicate rows are added
|
|
67
|
-
// here.
|
|
68
|
+
// here; the lock is released before step 4.
|
|
68
69
|
// [8/8] shim — generate the local shim package under the profile's
|
|
69
70
|
// node_modules (@aiwayds scope) that the patch row resolves.
|
|
70
71
|
// Its
|
|
@@ -72,25 +73,27 @@
|
|
|
72
73
|
// the profile scope, exactly like the bridge. revision +
|
|
73
74
|
// backup converge it.
|
|
74
75
|
//
|
|
75
|
-
// T4 — cross-instance mutual exclusion:
|
|
76
|
-
//
|
|
77
|
-
//
|
|
78
|
-
//
|
|
79
|
-
//
|
|
80
|
-
//
|
|
81
|
-
//
|
|
76
|
+
// T4 — cross-instance mutual exclusion (R14/R15):
|
|
77
|
+
// `.provision.lock` serializes the WHOLE run (O_EXCL). A live holder is
|
|
78
|
+
// waited for (<=30s, 50->500ms backoff) and then FAILS with exit 2 — never
|
|
79
|
+
// SKIP-0. Liveness is pid-only; a live record is never aged out, including
|
|
80
|
+
// a reused pid (manual recovery only); a dead holder is reclaimed under a sha256
|
|
81
|
+
// claim. `package.json.lock` replicates the host's `${pid}\n` protocol and is
|
|
82
|
+
// held only for the manifest+patch critical section, never across pnpm installs.
|
|
82
83
|
//
|
|
83
84
|
// Idempotency: an existing bridge directory whose index.js hash matches THIS
|
|
84
85
|
// install's build-time fingerprint is left untouched; a stale directory, a
|
|
85
86
|
// leftover symlink, or a missing entry is replaced with a fresh copy.
|
|
86
87
|
//
|
|
87
|
-
// `--repair` / `--repair-bridge`:
|
|
88
|
-
// but a no-op
|
|
89
|
-
//
|
|
90
|
-
//
|
|
88
|
+
// `--repair` / `--repair-bridge`: a no-op for BRIDGE materialization (the copy
|
|
89
|
+
// converges unconditionally on every provision), but NOT a no-op overall — with
|
|
90
|
+
// the flag, a conflicting pnpm-workspace.yaml (step [3/8]) is backed up as
|
|
91
|
+
// `pnpm-workspace.yaml.bak-<timestamp>` with a WARN and rewritten to the managed
|
|
92
|
+
// template. The T5 identity guard always runs after convergence, so a
|
|
93
|
+
// fingerprint mismatch still fails loud.
|
|
91
94
|
//
|
|
92
95
|
// Hard guard: this script only ever touches the ONE profile named
|
|
93
|
-
// `opentui-
|
|
96
|
+
// `opentui-monday`. The ONLY package-manager call is step [5/8], scoped to the
|
|
94
97
|
// explicit companion catalog; it never writes a @deepseek-ai dependency into
|
|
95
98
|
// the manifest (those bundles come from the running dsh closure).
|
|
96
99
|
|
|
@@ -102,7 +105,7 @@ import {
|
|
|
102
105
|
existsSync,
|
|
103
106
|
lstatSync,
|
|
104
107
|
mkdirSync,
|
|
105
|
-
|
|
108
|
+
copyFileSync,
|
|
106
109
|
readFileSync,
|
|
107
110
|
readlinkSync,
|
|
108
111
|
realpathSync,
|
|
@@ -121,7 +124,7 @@ import { fileURLToPath } from 'node:url'
|
|
|
121
124
|
// BridgeBootstrapError (handshake) now carry the same three elements.
|
|
122
125
|
import {
|
|
123
126
|
BRIDGE_APPEND_PRESET_NOTICE,
|
|
124
|
-
BRIDGE_REPAIR_HINT,
|
|
127
|
+
BRIDGE_REPAIR_COMMAND, BRIDGE_REPAIR_HINT,
|
|
125
128
|
} from './lib/bridge-failfast-text.mjs'
|
|
126
129
|
// Host-version gate. The host only records an incompatible profile bundle in
|
|
127
130
|
// `skippedBundles` (no stderr on this path), so the pre-boot check here is the
|
|
@@ -134,25 +137,26 @@ import {
|
|
|
134
137
|
isHostVersionSupported,
|
|
135
138
|
} from './lib/host-compat.mjs'
|
|
136
139
|
// Companion policy is a pure table; only the spawn and registry query live
|
|
137
|
-
// here (see step [
|
|
140
|
+
// here (see step [5/8]). Mirrors dsh-tui-pi's companion-latest pattern.
|
|
138
141
|
import {
|
|
139
142
|
COMPANIONS,
|
|
140
143
|
COMPANION_LATEST_ENV,
|
|
141
144
|
decideCompanionInstall,
|
|
142
|
-
|
|
145
|
+
formatSkippedCompanionsWarning,
|
|
146
|
+
queryDistTagLatestBatch,
|
|
143
147
|
selectCompanions,
|
|
144
148
|
} from './lib/inproc-companions.mjs'
|
|
145
149
|
|
|
146
150
|
const PREFIX = 'dsh-opentui(inproc): '
|
|
147
|
-
|
|
151
|
+
import { DEFAULT_PROFILE as PROFILE } from './lib/profile-name.mjs'
|
|
148
152
|
const BRIDGE_NAME = '@aiwayds/dsh-opentui-bridge'
|
|
149
153
|
const BUNDLES = ['@deepseek-ai/dsh-base', BRIDGE_NAME]
|
|
150
154
|
|
|
151
|
-
// ---
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
155
|
+
// --- Provision-run lock (R14): live holders are NEVER aged out ---------------
|
|
156
|
+
// The protocol, claim file and constants live in scripts/lib/provision-run-lock.mjs.
|
|
157
|
+
// A live holder is waited for up to 30s, then the run exits 2 (never SKIP-0).
|
|
158
|
+
// The host-compatible lock lives in scripts/lib/profile-lock.mjs.
|
|
159
|
+
// Lock order is always .provision.lock -> package.json.lock (never reversed).
|
|
156
160
|
|
|
157
161
|
const pkgRoot = dirname(dirname(fileURLToPath(import.meta.url)))
|
|
158
162
|
// Testability seam: the fail-fast tests point this at a bogus bridge dir to
|
|
@@ -162,10 +166,10 @@ const bridgeDirRaw = process.env.DSH_OPENTUI_TEST_BRIDGE_DIR || join(pkgRoot, 'd
|
|
|
162
166
|
const fingerprintPath = join(bridgeDirRaw, 'bundle-fingerprint.json')
|
|
163
167
|
|
|
164
168
|
const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
|
|
165
|
-
const profileDir = join(dshHome, 'profiles',
|
|
169
|
+
const profileDir = join(dshHome, 'profiles', activeProfile())
|
|
166
170
|
const manifestPath = join(profileDir, 'package.json')
|
|
167
171
|
const linkPath = join(profileDir, 'node_modules', ...BRIDGE_NAME.split('/'))
|
|
168
|
-
|
|
172
|
+
// .provision.lock is owned by scripts/lib/provision-run-lock.mjs (R14).
|
|
169
173
|
|
|
170
174
|
// --- Inproc patch ownership ------------------------------------------------
|
|
171
175
|
// S6: the patch/shim steps are unconditional (the env escape hatch that used
|
|
@@ -177,7 +181,7 @@ const PATCH_NAME = 'cordis.patch.yml'
|
|
|
177
181
|
const patchPath = join(profileDir, PATCH_NAME)
|
|
178
182
|
const PATCH_REVISION_MARKER = '# profileRevision: '
|
|
179
183
|
// Local shim package generated under the profile's node_modules. It lives in
|
|
180
|
-
// the @aiwayds scope (never @deepseek-ai — see the guard in step [
|
|
184
|
+
// the @aiwayds scope (never @deepseek-ai — see the guard in step [6/8]) so the
|
|
181
185
|
// host resolves it from the profile scope; its own @deepseek-ai/cordis import
|
|
182
186
|
// is routed by the host's runtime interception to the same dsh closure that
|
|
183
187
|
// serves the bridge. The patch row uses this bare package name.
|
|
@@ -190,7 +194,8 @@ const SHIM_REVISION_MARKER = '// shimRevision: '
|
|
|
190
194
|
// body must be escaped (\`), otherwise it terminates the string and the
|
|
191
195
|
// provisioner dies with a syntax error at runtime (the R2-3 maxDepth comment
|
|
192
196
|
// hit exactly this). Keep template-body prose backtick-free or escaped.
|
|
193
|
-
const PATCH_TEMPLATE = `# model route (managed by provision-
|
|
197
|
+
const PATCH_TEMPLATE = `# model route (managed by provision-inproc-profile.mjs — provider zai-coding-cn, key read by the host from ZAI_CODING_CN_API_KEY):
|
|
198
|
+
|
|
194
199
|
- id: llm-pi-ai
|
|
195
200
|
name: "@deepseek-ai/dsh-llm-pi-ai"
|
|
196
201
|
config:
|
|
@@ -579,7 +584,7 @@ const PATCH_TEMPLATE = `# model route (managed by provision-opentui-profile.mjs
|
|
|
579
584
|
edit: ask
|
|
580
585
|
apply_patch: ask
|
|
581
586
|
|
|
582
|
-
# MCP (managed by provision-
|
|
587
|
+
# MCP (managed by provision-inproc-profile.mjs — the adapter's mcp_list/mcp_call need a client row; context7 needs no key and a failed/offline connection is non-fatal):
|
|
583
588
|
- insert:
|
|
584
589
|
- id: mcp-context7
|
|
585
590
|
name: '@deepseek-ai/dsh-mcp-client'
|
|
@@ -612,7 +617,7 @@ const PATCH_TEMPLATE = `# model route (managed by provision-opentui-profile.mjs
|
|
|
612
617
|
maxDepth: 1
|
|
613
618
|
|
|
614
619
|
# Companion mounts (2026-11-22 unfreeze). The minimal set installed by
|
|
615
|
-
# provision-inproc-profile.mjs step [4/
|
|
620
|
+
# provision-inproc-profile.mjs step [4/7] is @aiwayds/dsh-subagent-registry,
|
|
616
621
|
# which registers the use_agent / ask_agent tools globally and carries its OWN
|
|
617
622
|
# cordis.patch.yml mount row. That row is activated by the dsh.profile.bundles
|
|
618
623
|
# entry that dsh plugin add writes into package.json — no duplicate row is added
|
|
@@ -623,7 +628,7 @@ const PATCH_TEMPLATE = `# model route (managed by provision-opentui-profile.mjs
|
|
|
623
628
|
# Standalone sessionController support (no dsh-web-app bundle). The real
|
|
624
629
|
# controller needs 13 injects; 11 come from dsh-base, and the two web-only ones
|
|
625
630
|
# (fileUploads, workspaceRegistry) are satisfied by the local shim package
|
|
626
|
-
# generated in step [
|
|
631
|
+
# generated in step [7/7]. No connection shim: dsh-api-gateway's optional
|
|
627
632
|
# ctx.inject(['connection']) calls connection.rpc.intercept(...), which a no-op
|
|
628
633
|
# stub cannot honor; leaving connection absent only keeps the controller's
|
|
629
634
|
# SessionMediaReferences sub-plugin pending, which does not block list().
|
|
@@ -644,10 +649,40 @@ const PATCH_TEMPLATE = `# model route (managed by provision-opentui-profile.mjs
|
|
|
644
649
|
name: "@deepseek-ai/dsh-session-log-deepseek"
|
|
645
650
|
config:
|
|
646
651
|
enabled: true
|
|
652
|
+
|
|
653
|
+
# D2: approval-policy windowSeconds:300 (design 06 §5.2 / L1). Append at END to
|
|
654
|
+
# keep approval-gate line anchors. windowSeconds defaults to 60 (range 0-86400,
|
|
655
|
+
# volatile); 0 skips forwarding and immediately adopts defaultOutcome. The
|
|
656
|
+
# explicit 300 below is intentional. defaultOutcome (default 'rejected', or
|
|
657
|
+
# 'unavailable') applies only on timeout; an earlier downstream outcome wins.
|
|
658
|
+
# When origins is unset, the plugin uses ['subagent','scheduled'] by default;
|
|
659
|
+
# schedule is scheduled, cron needs explicit opt-in, and human steer returns to
|
|
660
|
+
# the interactive path.
|
|
661
|
+
- insert:
|
|
662
|
+
- id: dsh-approval-policy
|
|
663
|
+
name: '@aiwayds/dsh-approval-policy'
|
|
664
|
+
config:
|
|
665
|
+
windowSeconds: 300
|
|
647
666
|
`
|
|
648
667
|
const PATCH_REVISION = createHash('sha256').update(PATCH_TEMPLATE).digest('hex').slice(0, 16)
|
|
649
668
|
const PATCH_HEADER = `# dsh-opentui inproc profile patch — GENERATED by provision-inproc-profile.mjs; edit the script, not this file.\n${PATCH_REVISION_MARKER}${PATCH_REVISION}\n`
|
|
650
669
|
const PATCH_CONTENT = `${PATCH_HEADER}${PATCH_TEMPLATE}`
|
|
670
|
+
|
|
671
|
+
// Testability seam for scratch-HOME migration tests: the shipped name constant
|
|
672
|
+
// stays authoritative in production; an explicit override keeps the two legacy
|
|
673
|
+
// source dirs (opentui / opentui-inproc) separate and provably read-only.
|
|
674
|
+
// P1-3: the override requires NODE_ENV=test as well. A leaked
|
|
675
|
+
// DSH_OPENTUI_TEST_PROFILE_NAME in a user's shell must NOT redirect the
|
|
676
|
+
// provisioner away from the profile the client actually launches.
|
|
677
|
+
// Hoisted so the profile constants above can use it without shifting the
|
|
678
|
+
// ledger-anchored template block at lines 567-579.
|
|
679
|
+
function activeProfile() {
|
|
680
|
+
if (process.env.NODE_ENV === 'test' && process.env.DSH_OPENTUI_TEST_PROFILE_NAME) {
|
|
681
|
+
return process.env.DSH_OPENTUI_TEST_PROFILE_NAME
|
|
682
|
+
}
|
|
683
|
+
return PROFILE
|
|
684
|
+
}
|
|
685
|
+
|
|
651
686
|
// MD5 of the web/opentui template this profile used to copy verbatim (see
|
|
652
687
|
// tickets/2026-11-18-inproc-profile-inventory.md §0). A local file matching it
|
|
653
688
|
// is an unowned legacy copy and is replaced without a backup.
|
|
@@ -659,7 +694,7 @@ const KNOWN_PATCH_MD5 = new Set(['54b66bf37fbbb93a6f9dd204a24473f7'])
|
|
|
659
694
|
// The real controller imports fileUploads / workspaceRegistry as TYPES ONLY;
|
|
660
695
|
// only the narrow methods below are ever called, so no dsh-web-app closure is
|
|
661
696
|
// needed. No `connection` shim on purpose (see the patch template comment).
|
|
662
|
-
const SHIM_INDEX_TEMPLATE = `// Standalone sessionController support for the opentui-
|
|
697
|
+
const SHIM_INDEX_TEMPLATE = `// Standalone sessionController support for the opentui-monday profile.
|
|
663
698
|
// GENERATED by provision-inproc-profile.mjs; edit the script, not this file.
|
|
664
699
|
import { Service } from '@deepseek-ai/cordis'
|
|
665
700
|
|
|
@@ -765,7 +800,7 @@ function sleepSync(ms) {
|
|
|
765
800
|
Atomics.wait(buf, 0, 0, ms)
|
|
766
801
|
}
|
|
767
802
|
|
|
768
|
-
// ---
|
|
803
|
+
// --- JSON helpers (locks now live in scripts/lib/*-lock.mjs) ----------------
|
|
769
804
|
function readJsonObject(path) {
|
|
770
805
|
try {
|
|
771
806
|
const parsed = JSON.parse(readFileSync(path, 'utf8'))
|
|
@@ -775,102 +810,6 @@ function readJsonObject(path) {
|
|
|
775
810
|
}
|
|
776
811
|
}
|
|
777
812
|
|
|
778
|
-
function readLock() {
|
|
779
|
-
const raw = readJsonObject(lockPath)
|
|
780
|
-
if (!raw || !Number.isInteger(raw.pid) || !Number.isFinite(raw.ts)) return undefined
|
|
781
|
-
return raw
|
|
782
|
-
}
|
|
783
|
-
|
|
784
|
-
/** process.kill(pid, 0) probes existence without signalling. EPERM means the
|
|
785
|
-
* process exists but belongs to another user — treat it as alive (no
|
|
786
|
-
* cross-user takeover semantics by design). */
|
|
787
|
-
function pidAlive(pid) {
|
|
788
|
-
if (!Number.isInteger(pid) || pid <= 0) return false
|
|
789
|
-
try {
|
|
790
|
-
process.kill(pid, 0)
|
|
791
|
-
return true
|
|
792
|
-
} catch (error) {
|
|
793
|
-
return error?.code === 'EPERM'
|
|
794
|
-
}
|
|
795
|
-
}
|
|
796
|
-
|
|
797
|
-
function staleReason(lock) {
|
|
798
|
-
if (lock === undefined) return 'lock file is unreadable or corrupt'
|
|
799
|
-
if (lock.pid === process.pid) return `held by self (pid ${lock.pid})`
|
|
800
|
-
if (!pidAlive(lock.pid)) return `holder pid ${lock.pid} no longer exists`
|
|
801
|
-
return `holder pid ${lock.pid} alive but lock age ${Date.now() - lock.ts}ms > ${LOCK_STALE_MS}ms`
|
|
802
|
-
}
|
|
803
|
-
|
|
804
|
-
function isStale(lock) {
|
|
805
|
-
if (lock === undefined) return true
|
|
806
|
-
if (lock.pid === process.pid) return true
|
|
807
|
-
if (!pidAlive(lock.pid)) return true
|
|
808
|
-
return Date.now() - lock.ts > LOCK_STALE_MS
|
|
809
|
-
}
|
|
810
|
-
|
|
811
|
-
/** Exclusive-create the lock. Returns the owned token, or undefined when a
|
|
812
|
-
* live peer kept it through all retries (caller then SKIPs). Stale locks are
|
|
813
|
-
* removed and re-contended. Ownership is re-read after create so a concurrent
|
|
814
|
-
* stale-takeover cannot make two processes both believe they hold it. */
|
|
815
|
-
function acquireLock() {
|
|
816
|
-
for (let attempt = 1; attempt <= LOCK_MAX_ATTEMPTS; attempt++) {
|
|
817
|
-
const token = { pid: process.pid, ts: Date.now() }
|
|
818
|
-
let created = false
|
|
819
|
-
try {
|
|
820
|
-
const fd = openSync(lockPath, 'wx', 0o600)
|
|
821
|
-
try {
|
|
822
|
-
writeSync(fd, JSON.stringify(token))
|
|
823
|
-
} finally {
|
|
824
|
-
closeSync(fd)
|
|
825
|
-
}
|
|
826
|
-
created = true
|
|
827
|
-
} catch (error) {
|
|
828
|
-
if (error?.code !== 'EEXIST') throw error
|
|
829
|
-
}
|
|
830
|
-
|
|
831
|
-
if (created) {
|
|
832
|
-
const held = readLock()
|
|
833
|
-
if (held && held.pid === token.pid && held.ts === token.ts) {
|
|
834
|
-
if (attempt > 1) note(`acquired provisioning lock on attempt ${attempt}`)
|
|
835
|
-
return token
|
|
836
|
-
}
|
|
837
|
-
// Our create was immediately replaced by another process — do NOT
|
|
838
|
-
// unlink (the lock now belongs to them); just retry.
|
|
839
|
-
sleepSync(LOCK_RETRY_MS)
|
|
840
|
-
continue
|
|
841
|
-
}
|
|
842
|
-
|
|
843
|
-
// EEXIST: inspect the holder.
|
|
844
|
-
const lock = readLock()
|
|
845
|
-
if (isStale(lock)) {
|
|
846
|
-
note(`stale provisioning lock (${staleReason(lock)}); taking over`)
|
|
847
|
-
try {
|
|
848
|
-
unlinkSync(lockPath)
|
|
849
|
-
} catch (error) {
|
|
850
|
-
if (error?.code !== 'ENOENT') throw error
|
|
851
|
-
}
|
|
852
|
-
continue
|
|
853
|
-
}
|
|
854
|
-
if (attempt === 1 || attempt % 5 === 0) {
|
|
855
|
-
note(`waiting for provisioning lock (holder pid ${lock.pid}, age ${Date.now() - lock.ts}ms) — attempt ${attempt}/${LOCK_MAX_ATTEMPTS}`)
|
|
856
|
-
}
|
|
857
|
-
sleepSync(LOCK_RETRY_MS)
|
|
858
|
-
}
|
|
859
|
-
return undefined
|
|
860
|
-
}
|
|
861
|
-
|
|
862
|
-
/** Only unlink a lock that is still ours, so a peer that took over after our
|
|
863
|
-
* stale threshold never loses its own lock to our cleanup. */
|
|
864
|
-
function releaseLock(token) {
|
|
865
|
-
if (!token) return
|
|
866
|
-
try {
|
|
867
|
-
const held = readLock()
|
|
868
|
-
if (held && held.pid === token.pid && held.ts === token.ts) unlinkSync(lockPath)
|
|
869
|
-
} catch {
|
|
870
|
-
/* best effort cleanup: never mask the primary provisioning result */
|
|
871
|
-
}
|
|
872
|
-
}
|
|
873
|
-
|
|
874
813
|
// --- Provisioning helpers ---------------------------------------------------
|
|
875
814
|
function readManifest() {
|
|
876
815
|
return readJsonObject(manifestPath)
|
|
@@ -878,7 +817,7 @@ function readManifest() {
|
|
|
878
817
|
|
|
879
818
|
/**
|
|
880
819
|
* Companion bundles already declared in the manifest must survive the step-2
|
|
881
|
-
* convergence: otherwise every launch would strip them and step
|
|
820
|
+
* convergence: otherwise every launch would strip them and step 5 would
|
|
882
821
|
* reinstall. Only packages from OUR catalog that the manifest already declares
|
|
883
822
|
* are preserved, so a stray dependency can never smuggle a bundle in.
|
|
884
823
|
*/
|
|
@@ -911,34 +850,46 @@ function installedCompanionVersion(name) {
|
|
|
911
850
|
|
|
912
851
|
/**
|
|
913
852
|
* A failed `dsh plugin add` can leave a dependency + bundle row behind without
|
|
914
|
-
* ever installing node_modules. Left alone, step [
|
|
853
|
+
* ever installing node_modules. Left alone, step [6/8] would turn that
|
|
915
854
|
* half-write into a permanent boot blocker on later (offline) starts, with no
|
|
916
855
|
* self-heal path. Drop only the stale declarations — healthy companions and
|
|
917
856
|
* the user's own dependencies are untouched — so the failure stays a WARN and
|
|
918
857
|
* provisioning always yields a usable profile.
|
|
919
858
|
*/
|
|
920
859
|
function dropUnmountedCompanions(reason, only = null) {
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
860
|
+
// N4: this late manifest write uses the SAME host lock as step 2's manifest
|
|
861
|
+
// convergence. We acquire it only for this short read-modify-write — step 5
|
|
862
|
+
// as a whole must NOT hold package.json.lock (the host holds it for all of
|
|
863
|
+
// pnpm during `dsh plugin add`). `dsh plugin add` itself writes the manifest
|
|
864
|
+
// under the host's lock; we never rewrite the manifest after a successful
|
|
865
|
+
// add, only clean up declarations that failed to mount.
|
|
866
|
+
return withProfileWriteLock(profileDir, () => {
|
|
867
|
+
const manifest = readManifest()
|
|
868
|
+
if (!manifest?.dependencies || typeof manifest.dependencies !== 'object') return 0
|
|
869
|
+
const bundles = Array.isArray(manifest.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : null
|
|
870
|
+
const stale = COMPANIONS.filter((entry) =>
|
|
871
|
+
(!only || only.includes(entry.name)) &&
|
|
872
|
+
Object.prototype.hasOwnProperty.call(manifest.dependencies, entry.name) &&
|
|
873
|
+
installedCompanionVersion(entry.name) === undefined)
|
|
874
|
+
if (stale.length === 0) return 0
|
|
875
|
+
for (const entry of stale) {
|
|
876
|
+
delete manifest.dependencies[entry.name]
|
|
877
|
+
if (bundles) {
|
|
878
|
+
const at = bundles.indexOf(entry.name)
|
|
879
|
+
if (at !== -1) bundles.splice(at, 1)
|
|
880
|
+
}
|
|
881
|
+
warn(`companion ${entry.name}: ${reason}; dropping stale declaration (companions are optional)`)
|
|
934
882
|
}
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
883
|
+
// Copy, never rename: a crash between moving away the live manifest and
|
|
884
|
+
// writing its replacement used to leave the profile with no manifest.
|
|
885
|
+
const backupPath = `${manifestPath}.bak-${Date.now()}`
|
|
886
|
+
copyFileSync(manifestPath, backupPath)
|
|
887
|
+
const tmpPath = `${manifestPath}.tmp-${process.pid}-${Date.now()}`
|
|
888
|
+
writeFileSync(tmpPath, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
|
|
889
|
+
renameSync(tmpPath, manifestPath)
|
|
890
|
+
say(5, 'companions', `dropped ${stale.length} stale companion declaration(s) — profile stays usable`)
|
|
891
|
+
return stale.length
|
|
892
|
+
})
|
|
942
893
|
}
|
|
943
894
|
|
|
944
895
|
/**
|
|
@@ -957,7 +908,7 @@ function dshOnPath() {
|
|
|
957
908
|
}
|
|
958
909
|
|
|
959
910
|
/**
|
|
960
|
-
* Step [
|
|
911
|
+
* Step [5/8] — install the minimal companion set.
|
|
961
912
|
*
|
|
962
913
|
* The install is done through `dsh plugin add`, which is the one supported way
|
|
963
914
|
* to put a @aiwayds package into a profile: it writes the dependency, appends
|
|
@@ -966,35 +917,45 @@ function dshOnPath() {
|
|
|
966
917
|
* registry's `dsh-jev-core` dependency, which the client's spin-attention
|
|
967
918
|
* probe then finds in the profile. With `nodeLinker: hoisted` +
|
|
968
919
|
* `autoInstallPeers: false` in this profile, no @deepseek-ai peer is copied
|
|
969
|
-
* into the profile, so step [
|
|
920
|
+
* into the profile, so step [6/8]'s no-@deepseek-ai guard still holds.
|
|
970
921
|
*
|
|
971
922
|
* Companions are optional: an install failure is a WARN, never a boot blocker.
|
|
972
923
|
* A half-write (dependency declared, package missing) is cleaned up here —
|
|
973
|
-
* immediately after a failed add, and on later offline starts — so step [
|
|
924
|
+
* immediately after a failed add, and on later offline starts — so step [6/8]
|
|
974
925
|
* never hard-fails on a state this step itself could not resolve.
|
|
975
926
|
*/
|
|
976
|
-
function provisionCompanions() {
|
|
927
|
+
async function provisionCompanions() {
|
|
977
928
|
const selected = selectCompanions(process.env)
|
|
978
929
|
if (selected.length === 0) {
|
|
979
930
|
const off = ['0', 'false', 'off'].includes(String(process.env[COMPANION_LATEST_ENV] ?? '').trim().toLowerCase())
|
|
980
|
-
say(
|
|
931
|
+
say(5, 'companions', off ? `skipped (${COMPANION_LATEST_ENV}=off)` : 'none selected')
|
|
981
932
|
return
|
|
982
933
|
}
|
|
983
934
|
|
|
984
935
|
const manifest = readManifest() ?? {}
|
|
936
|
+
// One bounded concurrent pass replaces 11 serial `npm view` calls. Results
|
|
937
|
+
// are indexed by input position, so every note below stays in roster order
|
|
938
|
+
// no matter which lookup finishes first.
|
|
939
|
+
const resolvedList = await queryDistTagLatestBatch(
|
|
940
|
+
selected.map((entry) => entry.name),
|
|
941
|
+
{ cwd: profileDir, env: process.env },
|
|
942
|
+
)
|
|
985
943
|
const specs = []
|
|
986
944
|
let unavailable = 0
|
|
987
|
-
|
|
945
|
+
const skipped = []
|
|
946
|
+
for (let index = 0; index < selected.length; index++) {
|
|
947
|
+
const entry = selected[index]
|
|
948
|
+
const resolved = resolvedList[index]
|
|
988
949
|
const currentPin = installedCompanionVersion(entry.name)
|
|
989
|
-
const resolved = queryDistTagLatest(entry.name, { cwd: profileDir, env: process.env })
|
|
990
950
|
if (resolved === null && currentPin === undefined &&
|
|
991
951
|
Object.prototype.hasOwnProperty.call(manifest.dependencies ?? {}, entry.name)) {
|
|
992
952
|
// A previous add left the dependency behind but never mounted the
|
|
993
953
|
// package. Offline there is no way to heal it: drop the stale declaration
|
|
994
|
-
// instead of handing step [
|
|
954
|
+
// instead of handing step [6/8] an unrecoverable hard fail.
|
|
995
955
|
dropUnmountedCompanions('declared but not installed, and offline', [entry.name])
|
|
996
956
|
note(`companion ${entry.name}: skip (offline-stale)`)
|
|
997
957
|
unavailable++
|
|
958
|
+
skipped.push(entry.short)
|
|
998
959
|
continue
|
|
999
960
|
}
|
|
1000
961
|
const decision = decideCompanionInstall({
|
|
@@ -1005,14 +966,23 @@ function provisionCompanions() {
|
|
|
1005
966
|
})
|
|
1006
967
|
if (decision.action === 'skip') {
|
|
1007
968
|
note(`companion ${entry.name}: skip (${decision.reason})`)
|
|
969
|
+
// idempotent means already satisfied — a success, not a skip worth
|
|
970
|
+
// warning about. Everything else is a query failure or a version guard.
|
|
971
|
+
if (resolved === null || decision.reason !== 'idempotent') skipped.push(entry.short)
|
|
1008
972
|
} else {
|
|
1009
973
|
note(`companion ${entry.name}: ${currentPin ?? 'absent'} -> ${decision.spec} (${decision.reason})`)
|
|
1010
974
|
specs.push(decision.spec)
|
|
975
|
+
// `resolved === null` keeps the existing @latest fallback, but the
|
|
976
|
+
// version check itself was skipped — report it once in the summary.
|
|
977
|
+
if (resolved === null) skipped.push(entry.short)
|
|
1011
978
|
}
|
|
1012
979
|
}
|
|
1013
980
|
|
|
981
|
+
const summary = formatSkippedCompanionsWarning(skipped)
|
|
982
|
+
if (summary) warn(summary)
|
|
983
|
+
|
|
1014
984
|
if (specs.length === 0) {
|
|
1015
|
-
say(
|
|
985
|
+
say(5, 'companions', unavailable > 0
|
|
1016
986
|
? `skipped ${unavailable} of ${selected.length} (unavailable)`
|
|
1017
987
|
: `already satisfied (${selected.length}/${selected.length})`)
|
|
1018
988
|
return
|
|
@@ -1026,12 +996,12 @@ function provisionCompanions() {
|
|
|
1026
996
|
`Install dsh and re-run provisioning to auto-install them, or set ${COMPANION_LATEST_ENV}=off to skip them permanently.`,
|
|
1027
997
|
)
|
|
1028
998
|
// A previous failed add may have left a half-written declaration. Drop it
|
|
1029
|
-
// so step [
|
|
999
|
+
// so step [6/8] never blocks a boot over a package we cannot install here.
|
|
1030
1000
|
dropUnmountedCompanions('no global dsh on PATH')
|
|
1031
|
-
say(
|
|
1001
|
+
say(5, 'companions', 'skipped (no global `dsh` on PATH; companions are optional)')
|
|
1032
1002
|
return
|
|
1033
1003
|
}
|
|
1034
|
-
const run = spawnSync('dsh', ['plugin', '--profile',
|
|
1004
|
+
const run = spawnSync('dsh', ['plugin', '--profile', activeProfile(), 'add', ...specs], {
|
|
1035
1005
|
stdio: 'inherit',
|
|
1036
1006
|
env: { ...process.env, DSH_HOME: dshHome },
|
|
1037
1007
|
cwd: profileDir,
|
|
@@ -1040,13 +1010,13 @@ function provisionCompanions() {
|
|
|
1040
1010
|
if (run.error) {
|
|
1041
1011
|
warn(`companion install failed to start: ${run.error.message}`)
|
|
1042
1012
|
dropUnmountedCompanions('install failed to start')
|
|
1043
|
-
say(
|
|
1013
|
+
say(5, 'companions', `installed 0 of ${specs.length} (failed to start)`)
|
|
1044
1014
|
return
|
|
1045
1015
|
}
|
|
1046
1016
|
if (run.status !== 0) {
|
|
1047
1017
|
warn(`dsh plugin add exited ${run.status}; companions are optional — the client still launches`)
|
|
1048
1018
|
dropUnmountedCompanions(`dsh plugin add exited ${run.status}`)
|
|
1049
|
-
say(
|
|
1019
|
+
say(5, 'companions', `installed 0 of ${specs.length} (exit ${run.status})`)
|
|
1050
1020
|
return
|
|
1051
1021
|
}
|
|
1052
1022
|
|
|
@@ -1063,11 +1033,11 @@ function provisionCompanions() {
|
|
|
1063
1033
|
warn(`companion version readback mismatch: ${missing.join(', ')}`)
|
|
1064
1034
|
dropUnmountedCompanions('version readback mismatch')
|
|
1065
1035
|
}
|
|
1066
|
-
say(
|
|
1036
|
+
say(5, 'companions', `installed ${landed.length} of ${specs.length}`)
|
|
1067
1037
|
}
|
|
1068
1038
|
|
|
1069
1039
|
/**
|
|
1070
|
-
* Step [
|
|
1040
|
+
* Step [6/8] cross-check: the companion state has three views — manifest
|
|
1071
1041
|
* dependencies, manifest bundles and installed node_modules. A provisioning
|
|
1072
1042
|
* pass that updated only one of them is a "two-state drift"; refuse to boot
|
|
1073
1043
|
* rather than booting a profile that composes a bundle it cannot resolve.
|
|
@@ -1208,7 +1178,7 @@ function verifyBridgeIdentity() {
|
|
|
1208
1178
|
)
|
|
1209
1179
|
}
|
|
1210
1180
|
|
|
1211
|
-
say(
|
|
1181
|
+
say(7, 'identity', `name=${fp.name} version=${fp.version} sha256=${fp.sha256.slice(0, 12)}…`)
|
|
1212
1182
|
note(`bridge identity OK — ${resolved}`)
|
|
1213
1183
|
}
|
|
1214
1184
|
|
|
@@ -1260,65 +1230,355 @@ function verifyHostCompatibility(bridgeDir) {
|
|
|
1260
1230
|
}
|
|
1261
1231
|
}
|
|
1262
1232
|
|
|
1263
|
-
//
|
|
1264
|
-
//
|
|
1265
|
-
//
|
|
1266
|
-
|
|
1233
|
+
// T4 — static imports placed AFTER the template block (ESM imports are hoisted
|
|
1234
|
+
// and may sit at any top-level position) so the ledger-evidenced template lines
|
|
1235
|
+
// 566-578 never shift. The old line-based mergeRuntimeFields writer is retired:
|
|
1236
|
+
// converge owns the patch now (design 06 R0-R29).
|
|
1237
|
+
import { converge, managedIds, splitPatch } from './lib/patch-ownership.mjs'
|
|
1238
|
+
import { readState, writeState } from './lib/patch-ownership-state.mjs'
|
|
1239
|
+
import { withProfileWriteLock } from './lib/profile-lock.mjs'
|
|
1240
|
+
import { acquireProvisionRunLock, ProvisionLockError, releaseProvisionRunLock } from './lib/provision-run-lock.mjs'
|
|
1241
|
+
// T8b — one-shot migration: the pure planner and its FS helper. Both are only
|
|
1242
|
+
// called from runProvision(), i.e. inside the whole-run `.provision.lock`.
|
|
1243
|
+
import { planMigration } from './lib/migration.mjs'
|
|
1244
|
+
import { applyMigrationPlan, BACKUP_DIR, MARKER_NAME, readMigrationInputs } from './lib/migration-io.mjs'
|
|
1267
1245
|
|
|
1268
1246
|
// --- Inproc cordis.patch.yml ownership ------------------------------------
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1247
|
+
function readPatchText() {
|
|
1248
|
+
try {
|
|
1249
|
+
return readFileSync(patchPath, 'utf8')
|
|
1250
|
+
} catch (error) {
|
|
1251
|
+
if (error?.code !== 'ENOENT') throw error
|
|
1252
|
+
return undefined
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/** Parse + completeness check. Used both before writing (refuse a bad plan)
|
|
1257
|
+
* and after the rename (detect a concurrent host write / truncated file). */
|
|
1258
|
+
function verifyPatchContent(content) {
|
|
1259
|
+
try {
|
|
1260
|
+
const written = managedIds(content)
|
|
1261
|
+
for (const id of managedIds(PATCH_CONTENT)) {
|
|
1262
|
+
if (!written.has(id)) return `missing managed id '${id}' after write`
|
|
1263
|
+
}
|
|
1264
|
+
// splitPatch also enforces the R28 structural assertions.
|
|
1265
|
+
splitPatch(content)
|
|
1266
|
+
return undefined
|
|
1267
|
+
} catch (error) {
|
|
1268
|
+
return `${error?.message ?? error} (line ${error?.line ?? 1}:${error?.col ?? 1})`
|
|
1269
|
+
}
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
/**
|
|
1273
|
+
* Converge the patch to the embedded inproc template (design 06 §4.6).
|
|
1274
|
+
* Called ONLY from inside the package.json.lock critical section. A parse
|
|
1275
|
+
* failure is fatal and never overwrites; backups are copies, not renames;
|
|
1276
|
+
* the sidecar is written on write:true AND on N1's sidecar-only self-heal.
|
|
1277
|
+
*/
|
|
1278
|
+
function provisionPatch({ externalCarry } = {}) {
|
|
1279
|
+
const current = readPatchText()
|
|
1280
|
+
const sidecar = readState(profileDir)
|
|
1281
|
+
let plan
|
|
1282
|
+
try {
|
|
1283
|
+
plan = converge({
|
|
1284
|
+
template: PATCH_CONTENT,
|
|
1285
|
+
current,
|
|
1286
|
+
sidecar,
|
|
1287
|
+
templateRevision: PATCH_REVISION,
|
|
1288
|
+
externalCarry,
|
|
1289
|
+
})
|
|
1290
|
+
} catch (error) {
|
|
1291
|
+
fail(`cordis.patch.yml: converge failed: ${error?.message ?? error}`)
|
|
1292
|
+
}
|
|
1293
|
+
if (plan.error) {
|
|
1294
|
+
fail(
|
|
1295
|
+
`cordis.patch.yml:${plan.error.line}:${plan.error.col}: ${plan.error.message}`,
|
|
1296
|
+
'Refusing to overwrite a file we cannot parse; repair it by hand (or restore a .bak) first.',
|
|
1297
|
+
)
|
|
1298
|
+
}
|
|
1299
|
+
for (const warning of plan.warnings) warn(`cordis.patch.yml: ${warning}`)
|
|
1300
|
+
|
|
1301
|
+
// A sidecar-only self-heal has no patch write, so it must never back up the
|
|
1302
|
+
// file (converge may still report a base-unknown reason on that path).
|
|
1303
|
+
if (plan.write && plan.backupReason && current !== undefined && current.length > 0) {
|
|
1304
|
+
const backupPath = `${patchPath}.bak-${Date.now()}`
|
|
1305
|
+
copyFileSync(patchPath, backupPath)
|
|
1306
|
+
warn(`cordis.patch.yml: backup (${plan.backupReason}) -> ${backupPath}`)
|
|
1307
|
+
for (const path of plan.backupPaths) warn(`cordis.patch.yml: ${path}`)
|
|
1308
|
+
}
|
|
1309
|
+
|
|
1310
|
+
if (!plan.write) {
|
|
1311
|
+
if (plan.writeSidecarOnly) {
|
|
1312
|
+
writeState(profileDir, plan.sidecar)
|
|
1313
|
+
say(2, 'patch', 'already current; rewrote missing/stale ownership sidecar')
|
|
1314
|
+
} else {
|
|
1315
|
+
say(2, 'patch', 'already current, skipping')
|
|
1316
|
+
}
|
|
1317
|
+
return
|
|
1318
|
+
}
|
|
1319
|
+
|
|
1320
|
+
const invalid = verifyPatchContent(plan.content)
|
|
1321
|
+
if (invalid) fail(`cordis.patch.yml: converged content failed validation: ${invalid}; refusing to write`)
|
|
1322
|
+
|
|
1323
|
+
const tmpPath = `${patchPath}.tmp-${process.pid}-${Date.now()}`
|
|
1324
|
+
writeFileSync(tmpPath, plan.content, { mode: 0o600 })
|
|
1325
|
+
renameSync(tmpPath, patchPath)
|
|
1326
|
+
|
|
1327
|
+
// Write-after verification: re-parse the file on disk, then re-read and
|
|
1328
|
+
// compare bytes. A structurally bad result is fatal (exit 1); a fully valid
|
|
1329
|
+
// but different file means a non-cooperating host writer landed (R16) —
|
|
1330
|
+
// WARN, skip the sidecar, and let the next pass converge it.
|
|
1331
|
+
const after = readPatchText()
|
|
1332
|
+
if (after === undefined) fail('cordis.patch.yml: write verification failed: file disappeared after rename')
|
|
1333
|
+
const postInvalid = verifyPatchContent(after)
|
|
1334
|
+
if (postInvalid) fail(`cordis.patch.yml: write verification failed: ${postInvalid}`)
|
|
1335
|
+
if (after !== plan.content) {
|
|
1336
|
+
warn('concurrent-write: another host writer landed during the patch write; skipping the sidecar (next pass will converge)')
|
|
1337
|
+
say(2, 'patch', `wrote ${patchPath} (external write detected; sidecar unchanged)`)
|
|
1338
|
+
return
|
|
1339
|
+
}
|
|
1340
|
+
writeState(profileDir, plan.sidecar)
|
|
1341
|
+
say(2, 'patch', `wrote ${patchPath} (profileRevision ${PATCH_REVISION}, reason ${plan.reason})`)
|
|
1273
1342
|
}
|
|
1274
1343
|
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1344
|
+
// --- D7 workspace contract: pnpm-workspace.yaml -----------------------------
|
|
1345
|
+
// Mid-file import follows the existing migration import pattern below and
|
|
1346
|
+
// keeps the ledger-anchored PATCH_TEMPLATE block above byte-stable.
|
|
1347
|
+
import { isMap, isScalar, isSeq, parseDocument } from 'yaml'
|
|
1348
|
+
|
|
1349
|
+
const WORKSPACE_FILE = 'pnpm-workspace.yaml'
|
|
1350
|
+
// Byte-for-byte template: the trailing newline is part of the contract; no
|
|
1351
|
+
// mode is declared. Extra keys in a conforming file are preserved (never
|
|
1352
|
+
// rewritten here).
|
|
1353
|
+
const WORKSPACE_TEMPLATE = `packages:
|
|
1354
|
+
- .
|
|
1355
|
+
|
|
1356
|
+
nodeLinker: hoisted
|
|
1357
|
+
autoInstallPeers: false
|
|
1358
|
+
`
|
|
1359
|
+
|
|
1360
|
+
/** Human-readable description of the "got" side of a contract mismatch. */
|
|
1361
|
+
function describeWorkspaceNode(node) {
|
|
1362
|
+
if (node === undefined) return 'missing key'
|
|
1363
|
+
if (isSeq(node)) {
|
|
1364
|
+
return `sequence [${node.items.map((item) => isScalar(item) ? JSON.stringify(item.value) : '<non-scalar>').join(', ')}]`
|
|
1365
|
+
}
|
|
1366
|
+
if (isScalar(node)) return `${typeof node.value} ${JSON.stringify(node.value)}`
|
|
1367
|
+
if (isMap(node)) return 'mapping'
|
|
1368
|
+
return node?.constructor?.name ?? 'unknown node'
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
/** Self-contained fail-fast: filename + key + expected/got + two repair paths.
|
|
1372
|
+
* The repair command name is the shared bridge wording, not a new string. */
|
|
1373
|
+
function workspaceContractError({ file, key, expected, got }) {
|
|
1374
|
+
const diagnosis = `${file}: ${key} — expected ${expected}, got ${got}`
|
|
1375
|
+
return new ProvisionError(
|
|
1376
|
+
diagnosis,
|
|
1377
|
+
[
|
|
1378
|
+
`Diagnosis: ${diagnosis}; refusing to start with a conflicting workspace contract.`,
|
|
1379
|
+
`Repair by hand: edit ${file} and set ${key} to ${expected}; provisioning left the file untouched.`,
|
|
1380
|
+
`Repair with backup + rewrite: run \`${BRIDGE_REPAIR_COMMAND}\` (backs up a conflicting ${file} to ${file}.bak-<timestamp>, then rewrites the managed template).`,
|
|
1381
|
+
].join('\n'),
|
|
1382
|
+
)
|
|
1383
|
+
}
|
|
1384
|
+
|
|
1385
|
+
/** Validate an EXISTING workspace file against the contract. Throws the
|
|
1386
|
+
* self-contained ProvisionError on any conflict; returns normally when the
|
|
1387
|
+
* file conforms. Kept separate so `ensureWorkspaceContract` can decide whether
|
|
1388
|
+
* a conflict is fatal or recoverable without duplicating the checks. */
|
|
1389
|
+
function assertWorkspaceContract(current, file) {
|
|
1390
|
+
let doc
|
|
1391
|
+
try {
|
|
1392
|
+
doc = parseDocument(current)
|
|
1393
|
+
} catch (error) {
|
|
1394
|
+
throw workspaceContractError({
|
|
1395
|
+
file,
|
|
1396
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1397
|
+
expected: 'parseable YAML mapping',
|
|
1398
|
+
got: `parse error: ${error?.message ?? error}`,
|
|
1399
|
+
})
|
|
1400
|
+
}
|
|
1401
|
+
if (doc.errors.length > 0) {
|
|
1402
|
+
throw workspaceContractError({
|
|
1403
|
+
file,
|
|
1404
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1405
|
+
expected: 'parseable YAML mapping',
|
|
1406
|
+
got: `parse error: ${doc.errors[0].message}`,
|
|
1407
|
+
})
|
|
1408
|
+
}
|
|
1409
|
+
if (!isMap(doc.contents)) {
|
|
1410
|
+
throw workspaceContractError({
|
|
1411
|
+
file,
|
|
1412
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1413
|
+
expected: 'a YAML mapping with packages/nodeLinker/autoInstallPeers',
|
|
1414
|
+
got: describeWorkspaceNode(doc.contents),
|
|
1415
|
+
})
|
|
1416
|
+
}
|
|
1417
|
+
|
|
1418
|
+
const packages = doc.get('packages', true)
|
|
1419
|
+
if (!isSeq(packages)
|
|
1420
|
+
|| !packages.items.every((item) => isScalar(item) && typeof item.value === 'string')
|
|
1421
|
+
|| !packages.items.some((item) => item.value === '.')) {
|
|
1422
|
+
throw workspaceContractError({
|
|
1423
|
+
file,
|
|
1424
|
+
key: 'packages',
|
|
1425
|
+
expected: 'a string sequence containing "."',
|
|
1426
|
+
got: describeWorkspaceNode(packages),
|
|
1427
|
+
})
|
|
1428
|
+
}
|
|
1429
|
+
const nodeLinker = doc.get('nodeLinker', true)
|
|
1430
|
+
if (!isScalar(nodeLinker) || nodeLinker.value !== 'hoisted') {
|
|
1431
|
+
throw workspaceContractError({
|
|
1432
|
+
file,
|
|
1433
|
+
key: 'nodeLinker',
|
|
1434
|
+
expected: 'hoisted',
|
|
1435
|
+
got: describeWorkspaceNode(nodeLinker),
|
|
1436
|
+
})
|
|
1437
|
+
}
|
|
1438
|
+
const autoInstallPeers = doc.get('autoInstallPeers', true)
|
|
1439
|
+
if (!isScalar(autoInstallPeers) || typeof autoInstallPeers.value !== 'boolean' || autoInstallPeers.value !== false) {
|
|
1440
|
+
throw workspaceContractError({
|
|
1441
|
+
file,
|
|
1442
|
+
key: 'autoInstallPeers',
|
|
1443
|
+
expected: 'false (boolean)',
|
|
1444
|
+
got: describeWorkspaceNode(autoInstallPeers),
|
|
1445
|
+
})
|
|
1446
|
+
}
|
|
1447
|
+
}
|
|
1448
|
+
|
|
1449
|
+
/** Atomic tmp+rename commit of the fixed workspace template. Shared by the
|
|
1450
|
+
* absent-file ("wrote") and repair ("repaired") paths: no window in which a
|
|
1451
|
+
* reader can observe a partially written workspace file. */
|
|
1452
|
+
function writeWorkspaceTemplate(file) {
|
|
1453
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
1454
|
+
const tmpPath = `${file}.tmp-${process.pid}-${Date.now()}`
|
|
1455
|
+
writeFileSync(tmpPath, WORKSPACE_TEMPLATE)
|
|
1456
|
+
renameSync(tmpPath, file)
|
|
1457
|
+
}
|
|
1458
|
+
|
|
1459
|
+
/**
|
|
1460
|
+
* D7 workspace contract — ensure `pnpm-workspace.yaml` under `profileDir`.
|
|
1461
|
+
* Reads the real FS. Three states:
|
|
1462
|
+
* - absent -> write the fixed template, return "wrote";
|
|
1463
|
+
* - conforming -> left byte-identical (allowBuilds / strictDepBuilds /
|
|
1464
|
+
* unknown keys survive), return "ok";
|
|
1465
|
+
* - conflicting -> fail fast, UNLESS `repair` is true: back up the original
|
|
1466
|
+
* to `pnpm-workspace.yaml.bak-<timestamp>` with a WARN,
|
|
1467
|
+
* atomically rewrite the whole file to the fixed template,
|
|
1468
|
+
* and return "repaired".
|
|
1469
|
+
* `repair` affects only this conflict recovery; the bridge copy converges
|
|
1470
|
+
* unconditionally either way. Callers run this inside their write lock.
|
|
1279
1471
|
*
|
|
1280
|
-
*
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1472
|
+
* @returns {'wrote'|'ok'|'repaired'}
|
|
1473
|
+
*/
|
|
1474
|
+
export function ensureWorkspaceContract({ profileDir: dir = profileDir, repair = false } = {}) {
|
|
1475
|
+
const file = join(dir, WORKSPACE_FILE)
|
|
1284
1476
|
let current
|
|
1285
1477
|
try {
|
|
1286
|
-
current = readFileSync(
|
|
1478
|
+
current = readFileSync(file, 'utf8')
|
|
1287
1479
|
} catch (error) {
|
|
1288
|
-
if (error?.code !== 'ENOENT')
|
|
1480
|
+
if (error?.code !== 'ENOENT') {
|
|
1481
|
+
throw workspaceContractError({
|
|
1482
|
+
file,
|
|
1483
|
+
key: WORKSPACE_FILE,
|
|
1484
|
+
expected: 'a readable file',
|
|
1485
|
+
got: `${error?.code ?? 'read error'}: ${error?.message ?? error}`,
|
|
1486
|
+
})
|
|
1487
|
+
}
|
|
1289
1488
|
current = undefined
|
|
1290
1489
|
}
|
|
1291
1490
|
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
// is line-based and allow-listed (see lib/patch-runtime-merge.mjs); every
|
|
1296
|
-
// other byte — including the ledger-evidenced template section — is intact.
|
|
1297
|
-
const merged = mergeRuntimeFields(PATCH_CONTENT, current)
|
|
1298
|
-
const nextContent = merged.content
|
|
1299
|
-
if (current === nextContent && localRevision === PATCH_REVISION) {
|
|
1300
|
-
say(7, 'patch', 'already current, skipping')
|
|
1301
|
-
return
|
|
1491
|
+
if (current === undefined) {
|
|
1492
|
+
writeWorkspaceTemplate(file)
|
|
1493
|
+
return 'wrote'
|
|
1302
1494
|
}
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1495
|
+
|
|
1496
|
+
try {
|
|
1497
|
+
assertWorkspaceContract(current, file)
|
|
1498
|
+
} catch (error) {
|
|
1499
|
+
if (!repair) throw error
|
|
1500
|
+
// Conflict + repair: preserve the foreign bytes first, then converge the
|
|
1501
|
+
// whole file. Both happen inside the caller's withProfileWriteLock section
|
|
1502
|
+
// (provisionProfileFiles), so a concurrent host rewrite cannot interleave.
|
|
1503
|
+
// Backup naming matches the manifest/patch/shim writers in this script.
|
|
1504
|
+
const backupPath = `${file}.bak-${Date.now()}`
|
|
1505
|
+
copyFileSync(file, backupPath)
|
|
1506
|
+
warn(`pnpm-workspace.yaml: contract conflict; backed up ${file} to ${backupPath}`)
|
|
1507
|
+
writeWorkspaceTemplate(file)
|
|
1508
|
+
return 'repaired'
|
|
1306
1509
|
}
|
|
1510
|
+
return 'ok'
|
|
1511
|
+
}
|
|
1307
1512
|
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1513
|
+
/** Manifest + patch + sidecar in ONE host-lock critical section (R7), before
|
|
1514
|
+
* step 4's bridge copy and well before step 5's package-manager call. */
|
|
1515
|
+
function provisionProfileFiles({ externalCarry, repair } = {}) {
|
|
1516
|
+
return withProfileWriteLock(profileDir, () => {
|
|
1517
|
+
const existing = existsSync(manifestPath) ? readManifest() : undefined
|
|
1518
|
+
if (existsSync(manifestPath) && existing === undefined) {
|
|
1519
|
+
fail(`${manifestPath} is not a valid JSON object manifest — leaving it untouched`)
|
|
1520
|
+
}
|
|
1521
|
+
const desired = desiredManifest(existing ?? { name: `dsh-profile-${activeProfile()}`, private: true })
|
|
1522
|
+
if (existing !== undefined && JSON.stringify(existing) === JSON.stringify(desired)) {
|
|
1523
|
+
say(2, 'manifest', 'already correct, skipping')
|
|
1524
|
+
} else {
|
|
1525
|
+
mkdirSync(profileDir, { recursive: true })
|
|
1526
|
+
if (existsSync(manifestPath)) {
|
|
1527
|
+
const backupPath = `${manifestPath}.bak-${Date.now()}`
|
|
1528
|
+
copyFileSync(manifestPath, backupPath)
|
|
1529
|
+
console.log(`${PREFIX}backed up ${manifestPath} to ${backupPath}`)
|
|
1530
|
+
}
|
|
1531
|
+
// Copy-backup + tmp/rename commit: no window with a missing manifest.
|
|
1532
|
+
const tmpPath = `${manifestPath}.tmp-${process.pid}-${Date.now()}`
|
|
1533
|
+
writeFileSync(tmpPath, `${JSON.stringify(desired, null, 2)}\n`, { mode: 0o600 })
|
|
1534
|
+
renameSync(tmpPath, manifestPath)
|
|
1535
|
+
say(2, 'manifest', `wrote bundles [${managedBundles(existing ?? {}).join(', ')}]`)
|
|
1314
1536
|
}
|
|
1537
|
+
// D7 step 3 (N5): workspace contract is checked in the SAME host lock,
|
|
1538
|
+
// immediately after the manifest write and before the patch copy — a
|
|
1539
|
+
// whole-file host rewrite can therefore never drop this update.
|
|
1540
|
+
const workspaceState = ensureWorkspaceContract({ profileDir, repair })
|
|
1541
|
+
say(3, 'workspace', workspaceState === 'wrote'
|
|
1542
|
+
? `wrote ${join(profileDir, WORKSPACE_FILE)}`
|
|
1543
|
+
: workspaceState === 'repaired'
|
|
1544
|
+
? `repaired ${join(profileDir, WORKSPACE_FILE)} (backup + rewrite)`
|
|
1545
|
+
: 'already correct, skipping')
|
|
1546
|
+
provisionPatch({ externalCarry })
|
|
1547
|
+
})
|
|
1548
|
+
}
|
|
1549
|
+
|
|
1550
|
+
// --- T8b — one-shot migration (06 §7.4/§7.5) --------------------------------
|
|
1551
|
+
/** The marker's `version` comes from the shell package, never hardcoded. */
|
|
1552
|
+
function migrationVersion() {
|
|
1553
|
+
const version = readJsonObject(join(pkgRoot, 'package.json'))?.version
|
|
1554
|
+
if (typeof version !== 'string' || version.length === 0) {
|
|
1555
|
+
fail(
|
|
1556
|
+
'cannot determine the migration marker version',
|
|
1557
|
+
`${join(pkgRoot, 'package.json')} must declare a non-empty string "version".`,
|
|
1558
|
+
)
|
|
1315
1559
|
}
|
|
1560
|
+
return version
|
|
1561
|
+
}
|
|
1316
1562
|
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1563
|
+
/** Why a migration is incomplete (undefined = complete / already migrated). */
|
|
1564
|
+
function migrationFailure(plan) {
|
|
1565
|
+
if (plan.canWriteMarker === false) return 'a legacy patch failed to parse'
|
|
1566
|
+
if (plan.config?.invalid === true) return 'the legacy config.json is not valid JSON'
|
|
1567
|
+
if (plan.keybindings?.invalid === true) return 'the legacy keybindings.json is not valid JSON'
|
|
1568
|
+
return undefined
|
|
1569
|
+
}
|
|
1570
|
+
|
|
1571
|
+
/** Self-contained error: diagnosis + repair action + legacy directory paths. */
|
|
1572
|
+
function migrationIncompleteError(reason) {
|
|
1573
|
+
const legacyRoot = join(dshHome, 'profiles')
|
|
1574
|
+
return new ProvisionError(
|
|
1575
|
+
`migration incomplete — ${reason}`,
|
|
1576
|
+
[
|
|
1577
|
+
`Diagnosis: no ${MARKER_NAME} was written, so the next start retries the one-shot migration.`,
|
|
1578
|
+
`Repair: fix the source file under ${join(legacyRoot, 'opentui')} or ${join(legacyRoot, 'opentui-inproc')}, then start dsh-opentui again.`,
|
|
1579
|
+
`The legacy directories are read-only to the migration: nothing there is modified, deleted or renamed. Recovered copies are in ${join(profileDir, BACKUP_DIR)}.`,
|
|
1580
|
+
].join('\n'),
|
|
1581
|
+
)
|
|
1322
1582
|
}
|
|
1323
1583
|
|
|
1324
1584
|
// --- Standalone sessionController shim ownership ---------------------------
|
|
@@ -1373,10 +1633,11 @@ function provisionShim() {
|
|
|
1373
1633
|
}
|
|
1374
1634
|
|
|
1375
1635
|
// --- The provision pass itself (runs under the lock) ------------------------
|
|
1376
|
-
function runProvision({ repair = false } = {}) {
|
|
1377
|
-
//
|
|
1378
|
-
//
|
|
1379
|
-
|
|
1636
|
+
async function runProvision({ repair = false } = {}) {
|
|
1637
|
+
// The bridge copy converges unconditionally on every provision (no symlink
|
|
1638
|
+
// to repair). --repair is NOT a no-op overall: with it, a conflicting
|
|
1639
|
+
// pnpm-workspace.yaml is backed up and rewritten in step [3/8].
|
|
1640
|
+
if (repair) note('repair mode: a conflicting workspace contract will be backed up and rewritten')
|
|
1380
1641
|
// Prerequisites (read-only) are checked before any mutation.
|
|
1381
1642
|
if (!existsSync(bridgeDirRaw) || !statSync(bridgeDirRaw).isDirectory()) {
|
|
1382
1643
|
fail(
|
|
@@ -1401,33 +1662,65 @@ function runProvision({ repair = false } = {}) {
|
|
|
1401
1662
|
// grant the exact-version exemption when it is in-window but not exempted.
|
|
1402
1663
|
verifyHostCompatibility(bridgeDir)
|
|
1403
1664
|
|
|
1404
|
-
//
|
|
1405
|
-
//
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1665
|
+
// --- T8b one-shot migration (06 §7.4) --------------------------------------
|
|
1666
|
+
// This whole function runs inside main()'s `.provision.lock`, so planning here
|
|
1667
|
+
// means neither step [2/8]'s patch converge nor step [5/8]'s companion install
|
|
1668
|
+
// can bypass migration. A present marker makes the planner a no-op (no legacy
|
|
1669
|
+
// read, no carry) and makes the helper short-circuit all writes and notices.
|
|
1670
|
+
const migrationInputs = readMigrationInputs({ dshHome, profileDir, templatePatchText: PATCH_CONTENT })
|
|
1671
|
+
const migrationPlan = planMigration(migrationInputs)
|
|
1672
|
+
const version = migrationVersion()
|
|
1673
|
+
const incompleteReason = migrationInputs.markerExists ? undefined : migrationFailure(migrationPlan)
|
|
1674
|
+
// Bad JSON is the same "not migrated" state as a bad patch: keep backups and
|
|
1675
|
+
// valid payloads, but suppress the marker before failing fast.
|
|
1676
|
+
const applyPlan = incompleteReason ? { ...migrationPlan, canWriteMarker: false } : migrationPlan
|
|
1677
|
+
|
|
1678
|
+
// Production targets `profiles/opentui-monday`; legacy source B
|
|
1679
|
+
// (`profiles/opentui-inproc`) is a separate read-only directory. Snapshot the
|
|
1680
|
+
// legacy bytes FIRST (backups only — no config/keybindings/marker). Any I/O
|
|
1681
|
+
// failure here is fatal: converge must not run on an unsnapshotted source.
|
|
1682
|
+
// Only the test seam (runAsB) can still make source B == the target.
|
|
1683
|
+
// Crash re-entry: if a prior pass already snapshotted every source (e.g. it
|
|
1684
|
+
// converged but crashed before the marker), keep those bytes. Re-reading a
|
|
1685
|
+
// converged source B would otherwise present generated text as "legacy" and
|
|
1686
|
+
// rotate/overwrite the genuine pre-migration backup.
|
|
1687
|
+
const planBackups = Array.isArray(applyPlan.backups) ? applyPlan.backups : []
|
|
1688
|
+
const alreadySnapshotted = planBackups.length > 0 && planBackups.every((entry) =>
|
|
1689
|
+
entry && entry.source && entry.kind &&
|
|
1690
|
+
existsSync(join(profileDir, BACKUP_DIR, `${entry.source}-${entry.kind}`)))
|
|
1691
|
+
if (!alreadySnapshotted) {
|
|
1692
|
+
try {
|
|
1693
|
+
applyMigrationPlan({ profileDir, plan: applyPlan, version, backupsOnly: true })
|
|
1694
|
+
} catch (error) {
|
|
1695
|
+
throw new ProvisionError(
|
|
1696
|
+
'migration pre-backup failed; the legacy patch was NOT converged',
|
|
1697
|
+
[
|
|
1698
|
+
`Diagnosis: ${error instanceof Error ? error.message : String(error)}`,
|
|
1699
|
+
`The original patch is left untouched. Repair the backup target under ${join(profileDir, BACKUP_DIR)} and restart.`,
|
|
1700
|
+
].join('\n'),
|
|
1701
|
+
)
|
|
1427
1702
|
}
|
|
1428
1703
|
}
|
|
1429
1704
|
|
|
1430
|
-
// [
|
|
1705
|
+
// [2/8] Manifest + patch + sidecar: the ONLY managed-segment writer, and it
|
|
1706
|
+
// consumes migration externalCarry in the same converge pass (06 §4.5).
|
|
1707
|
+
provisionProfileFiles({ externalCarry: migrationPlan.externalCarry, repair })
|
|
1708
|
+
|
|
1709
|
+
// Config -> keybindings -> backups -> marker. applyMigrationPlan writes the
|
|
1710
|
+
// marker LAST and only when allowed; the pre-backup above already wrote the
|
|
1711
|
+
// same bytes (or an existing snapshot was kept on re-entry), so backups are
|
|
1712
|
+
// never rewritten here and that order stays unchanged.
|
|
1713
|
+
const migrationResult = applyMigrationPlan({ profileDir, plan: applyPlan, version, skipBackups: alreadySnapshotted })
|
|
1714
|
+
|
|
1715
|
+
// Print notices exactly once from the apply result. On a marker hit the
|
|
1716
|
+
// helper returns no notices, so "already migrated" is never replayed.
|
|
1717
|
+
for (const notice of migrationResult.notices) note(notice)
|
|
1718
|
+
|
|
1719
|
+
// Fail-fast on an incomplete migration. The marker was withheld, so the next
|
|
1720
|
+
// start retries after the user repairs the legacy file.
|
|
1721
|
+
if (incompleteReason) throw migrationIncompleteError(incompleteReason)
|
|
1722
|
+
|
|
1723
|
+
// [4/8] Materialize the bridge as a REAL DIRECTORY COPY (S6 symlink-debt
|
|
1431
1724
|
// retirement). The old design wrote an ABSOLUTE symlink to THIS
|
|
1432
1725
|
// installation's dist/bridge: that bound the profile to one install path and
|
|
1433
1726
|
// let multiple worktrees sharing a DSH_HOME leave the link pointing at
|
|
@@ -1451,17 +1744,17 @@ function runProvision({ repair = false } = {}) {
|
|
|
1451
1744
|
} catch (error) {
|
|
1452
1745
|
fail(`could not materialize bridge copy at ${linkPath}: ${error?.message ?? error}`)
|
|
1453
1746
|
}
|
|
1454
|
-
say(
|
|
1747
|
+
say(4, 'bridge-copy', `copied ${bridgeDir} -> ${linkPath}`)
|
|
1455
1748
|
} else {
|
|
1456
|
-
say(
|
|
1749
|
+
say(4, 'bridge-copy', `${linkPath} already matches this install, skipping`)
|
|
1457
1750
|
}
|
|
1458
1751
|
}
|
|
1459
1752
|
|
|
1460
|
-
// [
|
|
1461
|
-
// verify step so a half-provisioned manifest is caught by step [
|
|
1462
|
-
provisionCompanions()
|
|
1753
|
+
// [5/8] Companion installation. Runs after the bridge copy and before the
|
|
1754
|
+
// verify step so a half-provisioned manifest is caught by step [6/8].
|
|
1755
|
+
await provisionCompanions()
|
|
1463
1756
|
|
|
1464
|
-
// [
|
|
1757
|
+
// [6/8] Verify: linkPath is a REAL directory (never a symlink) carrying the
|
|
1465
1758
|
// shipped bridge files, and no @deepseek-ai package leaked into the profile.
|
|
1466
1759
|
// Companion state is cross-checked too (deps <-> bundles <-> node_modules).
|
|
1467
1760
|
{
|
|
@@ -1484,22 +1777,24 @@ function runProvision({ repair = false } = {}) {
|
|
|
1484
1777
|
)
|
|
1485
1778
|
}
|
|
1486
1779
|
const companionCount = verifyCompanionState()
|
|
1487
|
-
say(
|
|
1780
|
+
say(6, 'verify', `bridge resolves to ${bridgeDir}; no @deepseek-ai copy in profile; ${companionCount} companion(s) consistent`)
|
|
1488
1781
|
}
|
|
1489
1782
|
|
|
1490
|
-
// [
|
|
1783
|
+
// [7/8] Identity guard always runs, including on the conflict path, so a
|
|
1491
1784
|
// repointed / replaced bridge cannot slip through as a mere WARN.
|
|
1492
1785
|
verifyBridgeIdentity()
|
|
1493
1786
|
|
|
1494
|
-
//
|
|
1495
|
-
//
|
|
1496
|
-
|
|
1787
|
+
// The patch was already converged in step 2's critical section (R7). No
|
|
1788
|
+
// manifest rewrite here: `dsh plugin add` writes it itself under the host's
|
|
1789
|
+
// lock, and the only late cleanup (dropUnmountedCompanions) takes that same
|
|
1790
|
+
// lock for its short read-modify-write (N4).
|
|
1791
|
+
// [8/8] The local shim package the patch row resolves. S6: unconditional.
|
|
1497
1792
|
provisionShim()
|
|
1498
1793
|
|
|
1499
1794
|
console.log(`${PREFIX}PASS`)
|
|
1500
1795
|
}
|
|
1501
1796
|
|
|
1502
|
-
function main(argv = []) {
|
|
1797
|
+
async function main(argv = []) {
|
|
1503
1798
|
// --repair is passed by `dsh-opentui --repair-bridge`; accept the long form
|
|
1504
1799
|
// too so the underlying mode is unambiguous when invoked directly.
|
|
1505
1800
|
const repair = argv.includes('--repair') || argv.includes('--repair-bridge')
|
|
@@ -1507,7 +1802,7 @@ function main(argv = []) {
|
|
|
1507
1802
|
if (!existsSync(dshHome)) {
|
|
1508
1803
|
fail(
|
|
1509
1804
|
`DSH_HOME directory does not exist: ${dshHome}`,
|
|
1510
|
-
`Create it first (e.g. mkdir -p "${dshHome}"). The
|
|
1805
|
+
`Create it first (e.g. mkdir -p "${dshHome}"). The ${activeProfile()} profile must share the existing Harness home, not create an isolated one.`,
|
|
1511
1806
|
)
|
|
1512
1807
|
}
|
|
1513
1808
|
if (!statSync(dshHome).isDirectory()) {
|
|
@@ -1517,29 +1812,49 @@ function main(argv = []) {
|
|
|
1517
1812
|
// The lock lives inside the profile dir, so make sure it exists first.
|
|
1518
1813
|
mkdirSync(profileDir, { recursive: true })
|
|
1519
1814
|
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
return
|
|
1526
|
-
}
|
|
1527
|
-
|
|
1815
|
+
// R14: wait for a live holder, then FAIL with exit 2. There is no SKIP-0
|
|
1816
|
+
// path — launching a host on a half-provisioned profile is the bug P0-1.
|
|
1817
|
+
const token = acquireProvisionRunLock(profileDir, {
|
|
1818
|
+
onWait: (message) => note(message),
|
|
1819
|
+
})
|
|
1528
1820
|
try {
|
|
1529
|
-
runProvision({ repair })
|
|
1821
|
+
await runProvision({ repair })
|
|
1530
1822
|
} finally {
|
|
1531
|
-
|
|
1823
|
+
releaseProvisionRunLock(token, (message) => warn(message))
|
|
1532
1824
|
}
|
|
1533
1825
|
}
|
|
1534
1826
|
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1827
|
+
// Importable seam for workspace-contract.test.ts: the exported helpers are
|
|
1828
|
+
// imported in-process, so main() must only run when THIS file is the entry
|
|
1829
|
+
// point (both `bun script.mjs` and `node script.mjs` set argv[1] to it).
|
|
1830
|
+
function isDirectInvocation() {
|
|
1831
|
+
const entry = process.argv[1]
|
|
1832
|
+
if (typeof entry !== 'string' || entry.length === 0) return false
|
|
1833
|
+
const self = fileURLToPath(import.meta.url)
|
|
1834
|
+
try {
|
|
1835
|
+
return realpathSync(entry) === realpathSync(self)
|
|
1836
|
+
} catch {
|
|
1837
|
+
return resolvePath(entry) === self
|
|
1543
1838
|
}
|
|
1544
|
-
|
|
1839
|
+
}
|
|
1840
|
+
|
|
1841
|
+
if (isDirectInvocation()) {
|
|
1842
|
+
// main() is async (the companion step's registry query is a bounded concurrent
|
|
1843
|
+
// batch). Its rejection is handled exactly like a synchronous throw used to be,
|
|
1844
|
+
// so the lock-release `finally` still runs before this handler sets exitCode.
|
|
1845
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
1846
|
+
if (error instanceof ProvisionLockError || error?.name === 'ProfileLockTimeoutError') {
|
|
1847
|
+
console.error(`${PREFIX}FAIL — ${error.message}`)
|
|
1848
|
+
if (error.detail) console.error(error.detail)
|
|
1849
|
+
} else if (error instanceof ProvisionError) {
|
|
1850
|
+
console.error(`${PREFIX}FAIL — ${error.message}`)
|
|
1851
|
+
if (error.detail) console.error(error.detail.trimEnd())
|
|
1852
|
+
} else {
|
|
1853
|
+
console.error(`${PREFIX}FAIL — unexpected error: ${error?.stack ?? String(error)}`)
|
|
1854
|
+
}
|
|
1855
|
+
// Lock timeouts carry exitCode 2 (distinct from a general provisioning
|
|
1856
|
+
// failure) so the launcher can tell "another live run owns this profile"
|
|
1857
|
+
// from a real error; either way the host is never started.
|
|
1858
|
+
process.exitCode = Number.isInteger(error?.exitCode) ? error.exitCode : 1
|
|
1859
|
+
})
|
|
1545
1860
|
}
|