@aiwayds/dsh-opentui 0.27.2 → 0.28.1
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 +39 -15
- package/README.md +59 -178
- package/bin/dsh-opentui.mjs +70 -258
- package/bin/lib/launcher.mjs +36 -187
- package/dist/client/index.js +7636 -16519
- package/dist/client/index.js.map +28 -53
- package/dist/locales/en.json +15 -2
- package/dist/locales/zh-CN.json +15 -2
- 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 +634 -286
- package/scripts/upgrade.mjs +445 -1110
- 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
|
@@ -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
|
*/
|
|
@@ -900,6 +839,35 @@ const desiredManifest = (existing) => ({
|
|
|
900
839
|
},
|
|
901
840
|
})
|
|
902
841
|
|
|
842
|
+
/**
|
|
843
|
+
* A real `dsh plugin add` lets pnpm write `dependencies` in sorted key order
|
|
844
|
+
* and dsh appends the newly installed companions to `dsh.profile.bundles` in
|
|
845
|
+
* that same order (see dsh-plugin-manager `reconcile()`), which differs from
|
|
846
|
+
* `managedBundles()`' catalog order. Bundle order is not semantic — dsh reads
|
|
847
|
+
* the array as a set — so a replay after a successful install must not rewrite
|
|
848
|
+
* (and back up) an otherwise-converged manifest. Compare bundle membership
|
|
849
|
+
* order-insensitively; keep every other field byte-exact so genuine drift
|
|
850
|
+
* (missing/extra bundle, malformed array, or any other content change) still
|
|
851
|
+
* goes through the backup + rewrite fail-fast path.
|
|
852
|
+
*/
|
|
853
|
+
function manifestAlreadyConverged(existing, desired) {
|
|
854
|
+
if (existing === undefined || desired === undefined) return false
|
|
855
|
+
const current = existing?.dsh?.profile?.bundles
|
|
856
|
+
const wanted = desired?.dsh?.profile?.bundles
|
|
857
|
+
if (!Array.isArray(current) || !Array.isArray(wanted) || current.length !== wanted.length) return false
|
|
858
|
+
const currentSet = new Set(current)
|
|
859
|
+
if (currentSet.size !== wanted.length || !wanted.every((name) => currentSet.has(name))) return false
|
|
860
|
+
// desiredManifest() copies every non-bundle field verbatim. Assert that
|
|
861
|
+
// explicitly so a future widening of desiredManifest cannot silently disable
|
|
862
|
+
// convergence of those fields.
|
|
863
|
+
const stripBundles = (manifest) => {
|
|
864
|
+
const profile = { ...(manifest?.dsh?.profile ?? {}) }
|
|
865
|
+
delete profile.bundles
|
|
866
|
+
return JSON.stringify({ ...manifest, dsh: { ...(manifest?.dsh ?? {}), profile } })
|
|
867
|
+
}
|
|
868
|
+
return stripBundles(existing) === stripBundles(desired)
|
|
869
|
+
}
|
|
870
|
+
|
|
903
871
|
/** Version actually mounted in the profile node_modules, or undefined. */
|
|
904
872
|
function installedCompanionVersion(name) {
|
|
905
873
|
try {
|
|
@@ -911,34 +879,46 @@ function installedCompanionVersion(name) {
|
|
|
911
879
|
|
|
912
880
|
/**
|
|
913
881
|
* A failed `dsh plugin add` can leave a dependency + bundle row behind without
|
|
914
|
-
* ever installing node_modules. Left alone, step [
|
|
882
|
+
* ever installing node_modules. Left alone, step [6/8] would turn that
|
|
915
883
|
* half-write into a permanent boot blocker on later (offline) starts, with no
|
|
916
884
|
* self-heal path. Drop only the stale declarations — healthy companions and
|
|
917
885
|
* the user's own dependencies are untouched — so the failure stays a WARN and
|
|
918
886
|
* provisioning always yields a usable profile.
|
|
919
887
|
*/
|
|
920
888
|
function dropUnmountedCompanions(reason, only = null) {
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
889
|
+
// N4: this late manifest write uses the SAME host lock as step 2's manifest
|
|
890
|
+
// convergence. We acquire it only for this short read-modify-write — step 5
|
|
891
|
+
// as a whole must NOT hold package.json.lock (the host holds it for all of
|
|
892
|
+
// pnpm during `dsh plugin add`). `dsh plugin add` itself writes the manifest
|
|
893
|
+
// under the host's lock; we never rewrite the manifest after a successful
|
|
894
|
+
// add, only clean up declarations that failed to mount.
|
|
895
|
+
return withProfileWriteLock(profileDir, () => {
|
|
896
|
+
const manifest = readManifest()
|
|
897
|
+
if (!manifest?.dependencies || typeof manifest.dependencies !== 'object') return 0
|
|
898
|
+
const bundles = Array.isArray(manifest.dsh?.profile?.bundles) ? manifest.dsh.profile.bundles : null
|
|
899
|
+
const stale = COMPANIONS.filter((entry) =>
|
|
900
|
+
(!only || only.includes(entry.name)) &&
|
|
901
|
+
Object.prototype.hasOwnProperty.call(manifest.dependencies, entry.name) &&
|
|
902
|
+
installedCompanionVersion(entry.name) === undefined)
|
|
903
|
+
if (stale.length === 0) return 0
|
|
904
|
+
for (const entry of stale) {
|
|
905
|
+
delete manifest.dependencies[entry.name]
|
|
906
|
+
if (bundles) {
|
|
907
|
+
const at = bundles.indexOf(entry.name)
|
|
908
|
+
if (at !== -1) bundles.splice(at, 1)
|
|
909
|
+
}
|
|
910
|
+
warn(`companion ${entry.name}: ${reason}; dropping stale declaration (companions are optional)`)
|
|
934
911
|
}
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
912
|
+
// Copy, never rename: a crash between moving away the live manifest and
|
|
913
|
+
// writing its replacement used to leave the profile with no manifest.
|
|
914
|
+
const backupPath = `${manifestPath}.bak-${Date.now()}`
|
|
915
|
+
copyFileSync(manifestPath, backupPath)
|
|
916
|
+
const tmpPath = `${manifestPath}.tmp-${process.pid}-${Date.now()}`
|
|
917
|
+
writeFileSync(tmpPath, `${JSON.stringify(manifest, null, 2)}\n`, { mode: 0o600 })
|
|
918
|
+
renameSync(tmpPath, manifestPath)
|
|
919
|
+
say(5, 'companions', `dropped ${stale.length} stale companion declaration(s) — profile stays usable`)
|
|
920
|
+
return stale.length
|
|
921
|
+
})
|
|
942
922
|
}
|
|
943
923
|
|
|
944
924
|
/**
|
|
@@ -957,7 +937,7 @@ function dshOnPath() {
|
|
|
957
937
|
}
|
|
958
938
|
|
|
959
939
|
/**
|
|
960
|
-
* Step [
|
|
940
|
+
* Step [5/8] — install the minimal companion set.
|
|
961
941
|
*
|
|
962
942
|
* The install is done through `dsh plugin add`, which is the one supported way
|
|
963
943
|
* to put a @aiwayds package into a profile: it writes the dependency, appends
|
|
@@ -966,35 +946,45 @@ function dshOnPath() {
|
|
|
966
946
|
* registry's `dsh-jev-core` dependency, which the client's spin-attention
|
|
967
947
|
* probe then finds in the profile. With `nodeLinker: hoisted` +
|
|
968
948
|
* `autoInstallPeers: false` in this profile, no @deepseek-ai peer is copied
|
|
969
|
-
* into the profile, so step [
|
|
949
|
+
* into the profile, so step [6/8]'s no-@deepseek-ai guard still holds.
|
|
970
950
|
*
|
|
971
951
|
* Companions are optional: an install failure is a WARN, never a boot blocker.
|
|
972
952
|
* A half-write (dependency declared, package missing) is cleaned up here —
|
|
973
|
-
* immediately after a failed add, and on later offline starts — so step [
|
|
953
|
+
* immediately after a failed add, and on later offline starts — so step [6/8]
|
|
974
954
|
* never hard-fails on a state this step itself could not resolve.
|
|
975
955
|
*/
|
|
976
|
-
function provisionCompanions() {
|
|
956
|
+
async function provisionCompanions() {
|
|
977
957
|
const selected = selectCompanions(process.env)
|
|
978
958
|
if (selected.length === 0) {
|
|
979
959
|
const off = ['0', 'false', 'off'].includes(String(process.env[COMPANION_LATEST_ENV] ?? '').trim().toLowerCase())
|
|
980
|
-
say(
|
|
960
|
+
say(5, 'companions', off ? `skipped (${COMPANION_LATEST_ENV}=off)` : 'none selected')
|
|
981
961
|
return
|
|
982
962
|
}
|
|
983
963
|
|
|
984
964
|
const manifest = readManifest() ?? {}
|
|
965
|
+
// One bounded concurrent pass replaces 11 serial `npm view` calls. Results
|
|
966
|
+
// are indexed by input position, so every note below stays in roster order
|
|
967
|
+
// no matter which lookup finishes first.
|
|
968
|
+
const resolvedList = await queryDistTagLatestBatch(
|
|
969
|
+
selected.map((entry) => entry.name),
|
|
970
|
+
{ cwd: profileDir, env: process.env },
|
|
971
|
+
)
|
|
985
972
|
const specs = []
|
|
986
973
|
let unavailable = 0
|
|
987
|
-
|
|
974
|
+
const skipped = []
|
|
975
|
+
for (let index = 0; index < selected.length; index++) {
|
|
976
|
+
const entry = selected[index]
|
|
977
|
+
const resolved = resolvedList[index]
|
|
988
978
|
const currentPin = installedCompanionVersion(entry.name)
|
|
989
|
-
const resolved = queryDistTagLatest(entry.name, { cwd: profileDir, env: process.env })
|
|
990
979
|
if (resolved === null && currentPin === undefined &&
|
|
991
980
|
Object.prototype.hasOwnProperty.call(manifest.dependencies ?? {}, entry.name)) {
|
|
992
981
|
// A previous add left the dependency behind but never mounted the
|
|
993
982
|
// package. Offline there is no way to heal it: drop the stale declaration
|
|
994
|
-
// instead of handing step [
|
|
983
|
+
// instead of handing step [6/8] an unrecoverable hard fail.
|
|
995
984
|
dropUnmountedCompanions('declared but not installed, and offline', [entry.name])
|
|
996
985
|
note(`companion ${entry.name}: skip (offline-stale)`)
|
|
997
986
|
unavailable++
|
|
987
|
+
skipped.push(entry.short)
|
|
998
988
|
continue
|
|
999
989
|
}
|
|
1000
990
|
const decision = decideCompanionInstall({
|
|
@@ -1005,14 +995,23 @@ function provisionCompanions() {
|
|
|
1005
995
|
})
|
|
1006
996
|
if (decision.action === 'skip') {
|
|
1007
997
|
note(`companion ${entry.name}: skip (${decision.reason})`)
|
|
998
|
+
// idempotent means already satisfied — a success, not a skip worth
|
|
999
|
+
// warning about. Everything else is a query failure or a version guard.
|
|
1000
|
+
if (resolved === null || decision.reason !== 'idempotent') skipped.push(entry.short)
|
|
1008
1001
|
} else {
|
|
1009
1002
|
note(`companion ${entry.name}: ${currentPin ?? 'absent'} -> ${decision.spec} (${decision.reason})`)
|
|
1010
1003
|
specs.push(decision.spec)
|
|
1004
|
+
// `resolved === null` keeps the existing @latest fallback, but the
|
|
1005
|
+
// version check itself was skipped — report it once in the summary.
|
|
1006
|
+
if (resolved === null) skipped.push(entry.short)
|
|
1011
1007
|
}
|
|
1012
1008
|
}
|
|
1013
1009
|
|
|
1010
|
+
const summary = formatSkippedCompanionsWarning(skipped)
|
|
1011
|
+
if (summary) warn(summary)
|
|
1012
|
+
|
|
1014
1013
|
if (specs.length === 0) {
|
|
1015
|
-
say(
|
|
1014
|
+
say(5, 'companions', unavailable > 0
|
|
1016
1015
|
? `skipped ${unavailable} of ${selected.length} (unavailable)`
|
|
1017
1016
|
: `already satisfied (${selected.length}/${selected.length})`)
|
|
1018
1017
|
return
|
|
@@ -1026,12 +1025,12 @@ function provisionCompanions() {
|
|
|
1026
1025
|
`Install dsh and re-run provisioning to auto-install them, or set ${COMPANION_LATEST_ENV}=off to skip them permanently.`,
|
|
1027
1026
|
)
|
|
1028
1027
|
// A previous failed add may have left a half-written declaration. Drop it
|
|
1029
|
-
// so step [
|
|
1028
|
+
// so step [6/8] never blocks a boot over a package we cannot install here.
|
|
1030
1029
|
dropUnmountedCompanions('no global dsh on PATH')
|
|
1031
|
-
say(
|
|
1030
|
+
say(5, 'companions', 'skipped (no global `dsh` on PATH; companions are optional)')
|
|
1032
1031
|
return
|
|
1033
1032
|
}
|
|
1034
|
-
const run = spawnSync('dsh', ['plugin', '--profile',
|
|
1033
|
+
const run = spawnSync('dsh', ['plugin', '--profile', activeProfile(), 'add', ...specs], {
|
|
1035
1034
|
stdio: 'inherit',
|
|
1036
1035
|
env: { ...process.env, DSH_HOME: dshHome },
|
|
1037
1036
|
cwd: profileDir,
|
|
@@ -1040,13 +1039,13 @@ function provisionCompanions() {
|
|
|
1040
1039
|
if (run.error) {
|
|
1041
1040
|
warn(`companion install failed to start: ${run.error.message}`)
|
|
1042
1041
|
dropUnmountedCompanions('install failed to start')
|
|
1043
|
-
say(
|
|
1042
|
+
say(5, 'companions', `installed 0 of ${specs.length} (failed to start)`)
|
|
1044
1043
|
return
|
|
1045
1044
|
}
|
|
1046
1045
|
if (run.status !== 0) {
|
|
1047
1046
|
warn(`dsh plugin add exited ${run.status}; companions are optional — the client still launches`)
|
|
1048
1047
|
dropUnmountedCompanions(`dsh plugin add exited ${run.status}`)
|
|
1049
|
-
say(
|
|
1048
|
+
say(5, 'companions', `installed 0 of ${specs.length} (exit ${run.status})`)
|
|
1050
1049
|
return
|
|
1051
1050
|
}
|
|
1052
1051
|
|
|
@@ -1063,11 +1062,11 @@ function provisionCompanions() {
|
|
|
1063
1062
|
warn(`companion version readback mismatch: ${missing.join(', ')}`)
|
|
1064
1063
|
dropUnmountedCompanions('version readback mismatch')
|
|
1065
1064
|
}
|
|
1066
|
-
say(
|
|
1065
|
+
say(5, 'companions', `installed ${landed.length} of ${specs.length}`)
|
|
1067
1066
|
}
|
|
1068
1067
|
|
|
1069
1068
|
/**
|
|
1070
|
-
* Step [
|
|
1069
|
+
* Step [6/8] cross-check: the companion state has three views — manifest
|
|
1071
1070
|
* dependencies, manifest bundles and installed node_modules. A provisioning
|
|
1072
1071
|
* pass that updated only one of them is a "two-state drift"; refuse to boot
|
|
1073
1072
|
* rather than booting a profile that composes a bundle it cannot resolve.
|
|
@@ -1208,7 +1207,7 @@ function verifyBridgeIdentity() {
|
|
|
1208
1207
|
)
|
|
1209
1208
|
}
|
|
1210
1209
|
|
|
1211
|
-
say(
|
|
1210
|
+
say(7, 'identity', `name=${fp.name} version=${fp.version} sha256=${fp.sha256.slice(0, 12)}…`)
|
|
1212
1211
|
note(`bridge identity OK — ${resolved}`)
|
|
1213
1212
|
}
|
|
1214
1213
|
|
|
@@ -1260,65 +1259,359 @@ function verifyHostCompatibility(bridgeDir) {
|
|
|
1260
1259
|
}
|
|
1261
1260
|
}
|
|
1262
1261
|
|
|
1263
|
-
//
|
|
1264
|
-
//
|
|
1265
|
-
//
|
|
1266
|
-
|
|
1262
|
+
// T4 — static imports placed AFTER the template block (ESM imports are hoisted
|
|
1263
|
+
// and may sit at any top-level position) so the ledger-evidenced template lines
|
|
1264
|
+
// 566-578 never shift. The old line-based mergeRuntimeFields writer is retired:
|
|
1265
|
+
// converge owns the patch now (design 06 R0-R29).
|
|
1266
|
+
import { converge, managedIds, splitPatch } from './lib/patch-ownership.mjs'
|
|
1267
|
+
import { readState, writeState } from './lib/patch-ownership-state.mjs'
|
|
1268
|
+
import { withProfileWriteLock } from './lib/profile-lock.mjs'
|
|
1269
|
+
import { acquireProvisionRunLock, ProvisionLockError, releaseProvisionRunLock } from './lib/provision-run-lock.mjs'
|
|
1270
|
+
// T8b — one-shot migration: the pure planner and its FS helper. Both are only
|
|
1271
|
+
// called from runProvision(), i.e. inside the whole-run `.provision.lock`.
|
|
1272
|
+
import { planMigration } from './lib/migration.mjs'
|
|
1273
|
+
import { applyMigrationPlan, BACKUP_DIR, MARKER_NAME, readMigrationInputs } from './lib/migration-io.mjs'
|
|
1267
1274
|
|
|
1268
1275
|
// --- Inproc cordis.patch.yml ownership ------------------------------------
|
|
1269
|
-
|
|
1270
|
-
|
|
1271
|
-
|
|
1272
|
-
|
|
1276
|
+
function readPatchText() {
|
|
1277
|
+
try {
|
|
1278
|
+
return readFileSync(patchPath, 'utf8')
|
|
1279
|
+
} catch (error) {
|
|
1280
|
+
if (error?.code !== 'ENOENT') throw error
|
|
1281
|
+
return undefined
|
|
1282
|
+
}
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
/** Parse + completeness check. Used both before writing (refuse a bad plan)
|
|
1286
|
+
* and after the rename (detect a concurrent host write / truncated file). */
|
|
1287
|
+
function verifyPatchContent(content) {
|
|
1288
|
+
try {
|
|
1289
|
+
const written = managedIds(content)
|
|
1290
|
+
for (const id of managedIds(PATCH_CONTENT)) {
|
|
1291
|
+
if (!written.has(id)) return `missing managed id '${id}' after write`
|
|
1292
|
+
}
|
|
1293
|
+
// splitPatch also enforces the R28 structural assertions.
|
|
1294
|
+
splitPatch(content)
|
|
1295
|
+
return undefined
|
|
1296
|
+
} catch (error) {
|
|
1297
|
+
return `${error?.message ?? error} (line ${error?.line ?? 1}:${error?.col ?? 1})`
|
|
1298
|
+
}
|
|
1299
|
+
}
|
|
1300
|
+
|
|
1301
|
+
/**
|
|
1302
|
+
* Converge the patch to the embedded inproc template (design 06 §4.6).
|
|
1303
|
+
* Called ONLY from inside the package.json.lock critical section. A parse
|
|
1304
|
+
* failure is fatal and never overwrites; backups are copies, not renames;
|
|
1305
|
+
* the sidecar is written on write:true AND on N1's sidecar-only self-heal.
|
|
1306
|
+
*/
|
|
1307
|
+
function provisionPatch({ externalCarry } = {}) {
|
|
1308
|
+
const current = readPatchText()
|
|
1309
|
+
const sidecar = readState(profileDir)
|
|
1310
|
+
let plan
|
|
1311
|
+
try {
|
|
1312
|
+
plan = converge({
|
|
1313
|
+
template: PATCH_CONTENT,
|
|
1314
|
+
current,
|
|
1315
|
+
sidecar,
|
|
1316
|
+
templateRevision: PATCH_REVISION,
|
|
1317
|
+
externalCarry,
|
|
1318
|
+
})
|
|
1319
|
+
} catch (error) {
|
|
1320
|
+
fail(`cordis.patch.yml: converge failed: ${error?.message ?? error}`)
|
|
1321
|
+
}
|
|
1322
|
+
if (plan.error) {
|
|
1323
|
+
fail(
|
|
1324
|
+
`cordis.patch.yml:${plan.error.line}:${plan.error.col}: ${plan.error.message}`,
|
|
1325
|
+
'Refusing to overwrite a file we cannot parse; repair it by hand (or restore a .bak) first.',
|
|
1326
|
+
)
|
|
1327
|
+
}
|
|
1328
|
+
for (const warning of plan.warnings) warn(`cordis.patch.yml: ${warning}`)
|
|
1329
|
+
|
|
1330
|
+
// A sidecar-only self-heal has no patch write, so it must never back up the
|
|
1331
|
+
// file (converge may still report a base-unknown reason on that path).
|
|
1332
|
+
if (plan.write && plan.backupReason && current !== undefined && current.length > 0) {
|
|
1333
|
+
const backupPath = `${patchPath}.bak-${Date.now()}`
|
|
1334
|
+
copyFileSync(patchPath, backupPath)
|
|
1335
|
+
warn(`cordis.patch.yml: backup (${plan.backupReason}) -> ${backupPath}`)
|
|
1336
|
+
for (const path of plan.backupPaths) warn(`cordis.patch.yml: ${path}`)
|
|
1337
|
+
}
|
|
1338
|
+
|
|
1339
|
+
if (!plan.write) {
|
|
1340
|
+
if (plan.writeSidecarOnly) {
|
|
1341
|
+
writeState(profileDir, plan.sidecar)
|
|
1342
|
+
say(2, 'patch', 'already current; rewrote missing/stale ownership sidecar')
|
|
1343
|
+
} else {
|
|
1344
|
+
say(2, 'patch', 'already current, skipping')
|
|
1345
|
+
}
|
|
1346
|
+
return
|
|
1347
|
+
}
|
|
1348
|
+
|
|
1349
|
+
const invalid = verifyPatchContent(plan.content)
|
|
1350
|
+
if (invalid) fail(`cordis.patch.yml: converged content failed validation: ${invalid}; refusing to write`)
|
|
1351
|
+
|
|
1352
|
+
const tmpPath = `${patchPath}.tmp-${process.pid}-${Date.now()}`
|
|
1353
|
+
writeFileSync(tmpPath, plan.content, { mode: 0o600 })
|
|
1354
|
+
renameSync(tmpPath, patchPath)
|
|
1355
|
+
|
|
1356
|
+
// Write-after verification: re-parse the file on disk, then re-read and
|
|
1357
|
+
// compare bytes. A structurally bad result is fatal (exit 1); a fully valid
|
|
1358
|
+
// but different file means a non-cooperating host writer landed (R16) —
|
|
1359
|
+
// WARN, skip the sidecar, and let the next pass converge it.
|
|
1360
|
+
const after = readPatchText()
|
|
1361
|
+
if (after === undefined) fail('cordis.patch.yml: write verification failed: file disappeared after rename')
|
|
1362
|
+
const postInvalid = verifyPatchContent(after)
|
|
1363
|
+
if (postInvalid) fail(`cordis.patch.yml: write verification failed: ${postInvalid}`)
|
|
1364
|
+
if (after !== plan.content) {
|
|
1365
|
+
warn('concurrent-write: another host writer landed during the patch write; skipping the sidecar (next pass will converge)')
|
|
1366
|
+
say(2, 'patch', `wrote ${patchPath} (external write detected; sidecar unchanged)`)
|
|
1367
|
+
return
|
|
1368
|
+
}
|
|
1369
|
+
writeState(profileDir, plan.sidecar)
|
|
1370
|
+
say(2, 'patch', `wrote ${patchPath} (profileRevision ${PATCH_REVISION}, reason ${plan.reason})`)
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
// --- D7 workspace contract: pnpm-workspace.yaml -----------------------------
|
|
1374
|
+
// Mid-file import follows the existing migration import pattern below and
|
|
1375
|
+
// keeps the ledger-anchored PATCH_TEMPLATE block above byte-stable.
|
|
1376
|
+
import { isMap, isScalar, isSeq, parseDocument } from 'yaml'
|
|
1377
|
+
|
|
1378
|
+
const WORKSPACE_FILE = 'pnpm-workspace.yaml'
|
|
1379
|
+
// Byte-for-byte template: the trailing newline is part of the contract; no
|
|
1380
|
+
// mode is declared. Extra keys in a conforming file are preserved (never
|
|
1381
|
+
// rewritten here).
|
|
1382
|
+
const WORKSPACE_TEMPLATE = `packages:
|
|
1383
|
+
- .
|
|
1384
|
+
|
|
1385
|
+
nodeLinker: hoisted
|
|
1386
|
+
autoInstallPeers: false
|
|
1387
|
+
`
|
|
1388
|
+
|
|
1389
|
+
/** Human-readable description of the "got" side of a contract mismatch. */
|
|
1390
|
+
function describeWorkspaceNode(node) {
|
|
1391
|
+
if (node === undefined) return 'missing key'
|
|
1392
|
+
if (isSeq(node)) {
|
|
1393
|
+
return `sequence [${node.items.map((item) => isScalar(item) ? JSON.stringify(item.value) : '<non-scalar>').join(', ')}]`
|
|
1394
|
+
}
|
|
1395
|
+
if (isScalar(node)) return `${typeof node.value} ${JSON.stringify(node.value)}`
|
|
1396
|
+
if (isMap(node)) return 'mapping'
|
|
1397
|
+
return node?.constructor?.name ?? 'unknown node'
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
/** Self-contained fail-fast: filename + key + expected/got + two repair paths.
|
|
1401
|
+
* The repair command name is the shared bridge wording, not a new string. */
|
|
1402
|
+
function workspaceContractError({ file, key, expected, got }) {
|
|
1403
|
+
const diagnosis = `${file}: ${key} — expected ${expected}, got ${got}`
|
|
1404
|
+
return new ProvisionError(
|
|
1405
|
+
diagnosis,
|
|
1406
|
+
[
|
|
1407
|
+
`Diagnosis: ${diagnosis}; refusing to start with a conflicting workspace contract.`,
|
|
1408
|
+
`Repair by hand: edit ${file} and set ${key} to ${expected}; provisioning left the file untouched.`,
|
|
1409
|
+
`Repair with backup + rewrite: run \`${BRIDGE_REPAIR_COMMAND}\` (backs up a conflicting ${file} to ${file}.bak-<timestamp>, then rewrites the managed template).`,
|
|
1410
|
+
].join('\n'),
|
|
1411
|
+
)
|
|
1412
|
+
}
|
|
1413
|
+
|
|
1414
|
+
/** Validate an EXISTING workspace file against the contract. Throws the
|
|
1415
|
+
* self-contained ProvisionError on any conflict; returns normally when the
|
|
1416
|
+
* file conforms. Kept separate so `ensureWorkspaceContract` can decide whether
|
|
1417
|
+
* a conflict is fatal or recoverable without duplicating the checks. */
|
|
1418
|
+
function assertWorkspaceContract(current, file) {
|
|
1419
|
+
let doc
|
|
1420
|
+
try {
|
|
1421
|
+
doc = parseDocument(current)
|
|
1422
|
+
} catch (error) {
|
|
1423
|
+
throw workspaceContractError({
|
|
1424
|
+
file,
|
|
1425
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1426
|
+
expected: 'parseable YAML mapping',
|
|
1427
|
+
got: `parse error: ${error?.message ?? error}`,
|
|
1428
|
+
})
|
|
1429
|
+
}
|
|
1430
|
+
if (doc.errors.length > 0) {
|
|
1431
|
+
throw workspaceContractError({
|
|
1432
|
+
file,
|
|
1433
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1434
|
+
expected: 'parseable YAML mapping',
|
|
1435
|
+
got: `parse error: ${doc.errors[0].message}`,
|
|
1436
|
+
})
|
|
1437
|
+
}
|
|
1438
|
+
if (!isMap(doc.contents)) {
|
|
1439
|
+
throw workspaceContractError({
|
|
1440
|
+
file,
|
|
1441
|
+
key: '<document> (packages/nodeLinker/autoInstallPeers)',
|
|
1442
|
+
expected: 'a YAML mapping with packages/nodeLinker/autoInstallPeers',
|
|
1443
|
+
got: describeWorkspaceNode(doc.contents),
|
|
1444
|
+
})
|
|
1445
|
+
}
|
|
1446
|
+
|
|
1447
|
+
const packages = doc.get('packages', true)
|
|
1448
|
+
if (!isSeq(packages)
|
|
1449
|
+
|| !packages.items.every((item) => isScalar(item) && typeof item.value === 'string')
|
|
1450
|
+
|| !packages.items.some((item) => item.value === '.')) {
|
|
1451
|
+
throw workspaceContractError({
|
|
1452
|
+
file,
|
|
1453
|
+
key: 'packages',
|
|
1454
|
+
expected: 'a string sequence containing "."',
|
|
1455
|
+
got: describeWorkspaceNode(packages),
|
|
1456
|
+
})
|
|
1457
|
+
}
|
|
1458
|
+
const nodeLinker = doc.get('nodeLinker', true)
|
|
1459
|
+
if (!isScalar(nodeLinker) || nodeLinker.value !== 'hoisted') {
|
|
1460
|
+
throw workspaceContractError({
|
|
1461
|
+
file,
|
|
1462
|
+
key: 'nodeLinker',
|
|
1463
|
+
expected: 'hoisted',
|
|
1464
|
+
got: describeWorkspaceNode(nodeLinker),
|
|
1465
|
+
})
|
|
1466
|
+
}
|
|
1467
|
+
const autoInstallPeers = doc.get('autoInstallPeers', true)
|
|
1468
|
+
if (!isScalar(autoInstallPeers) || typeof autoInstallPeers.value !== 'boolean' || autoInstallPeers.value !== false) {
|
|
1469
|
+
throw workspaceContractError({
|
|
1470
|
+
file,
|
|
1471
|
+
key: 'autoInstallPeers',
|
|
1472
|
+
expected: 'false (boolean)',
|
|
1473
|
+
got: describeWorkspaceNode(autoInstallPeers),
|
|
1474
|
+
})
|
|
1475
|
+
}
|
|
1273
1476
|
}
|
|
1274
1477
|
|
|
1275
|
-
/**
|
|
1276
|
-
* -
|
|
1277
|
-
*
|
|
1278
|
-
|
|
1478
|
+
/** Atomic tmp+rename commit of the fixed workspace template. Shared by the
|
|
1479
|
+
* absent-file ("wrote") and repair ("repaired") paths: no window in which a
|
|
1480
|
+
* reader can observe a partially written workspace file. */
|
|
1481
|
+
function writeWorkspaceTemplate(file) {
|
|
1482
|
+
mkdirSync(dirname(file), { recursive: true })
|
|
1483
|
+
const tmpPath = `${file}.tmp-${process.pid}-${Date.now()}`
|
|
1484
|
+
writeFileSync(tmpPath, WORKSPACE_TEMPLATE)
|
|
1485
|
+
renameSync(tmpPath, file)
|
|
1486
|
+
}
|
|
1487
|
+
|
|
1488
|
+
/**
|
|
1489
|
+
* D7 workspace contract — ensure `pnpm-workspace.yaml` under `profileDir`.
|
|
1490
|
+
* Reads the real FS. Three states:
|
|
1491
|
+
* - absent -> write the fixed template, return "wrote";
|
|
1492
|
+
* - conforming -> left byte-identical (allowBuilds / strictDepBuilds /
|
|
1493
|
+
* unknown keys survive), return "ok";
|
|
1494
|
+
* - conflicting -> fail fast, UNLESS `repair` is true: back up the original
|
|
1495
|
+
* to `pnpm-workspace.yaml.bak-<timestamp>` with a WARN,
|
|
1496
|
+
* atomically rewrite the whole file to the fixed template,
|
|
1497
|
+
* and return "repaired".
|
|
1498
|
+
* `repair` affects only this conflict recovery; the bridge copy converges
|
|
1499
|
+
* unconditionally either way. Callers run this inside their write lock.
|
|
1279
1500
|
*
|
|
1280
|
-
*
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1501
|
+
* @returns {'wrote'|'ok'|'repaired'}
|
|
1502
|
+
*/
|
|
1503
|
+
export function ensureWorkspaceContract({ profileDir: dir = profileDir, repair = false } = {}) {
|
|
1504
|
+
const file = join(dir, WORKSPACE_FILE)
|
|
1284
1505
|
let current
|
|
1285
1506
|
try {
|
|
1286
|
-
current = readFileSync(
|
|
1507
|
+
current = readFileSync(file, 'utf8')
|
|
1287
1508
|
} catch (error) {
|
|
1288
|
-
if (error?.code !== 'ENOENT')
|
|
1509
|
+
if (error?.code !== 'ENOENT') {
|
|
1510
|
+
throw workspaceContractError({
|
|
1511
|
+
file,
|
|
1512
|
+
key: WORKSPACE_FILE,
|
|
1513
|
+
expected: 'a readable file',
|
|
1514
|
+
got: `${error?.code ?? 'read error'}: ${error?.message ?? error}`,
|
|
1515
|
+
})
|
|
1516
|
+
}
|
|
1289
1517
|
current = undefined
|
|
1290
1518
|
}
|
|
1291
1519
|
|
|
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
|
|
1520
|
+
if (current === undefined) {
|
|
1521
|
+
writeWorkspaceTemplate(file)
|
|
1522
|
+
return 'wrote'
|
|
1302
1523
|
}
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1524
|
+
|
|
1525
|
+
try {
|
|
1526
|
+
assertWorkspaceContract(current, file)
|
|
1527
|
+
} catch (error) {
|
|
1528
|
+
if (!repair) throw error
|
|
1529
|
+
// Conflict + repair: preserve the foreign bytes first, then converge the
|
|
1530
|
+
// whole file. Both happen inside the caller's withProfileWriteLock section
|
|
1531
|
+
// (provisionProfileFiles), so a concurrent host rewrite cannot interleave.
|
|
1532
|
+
// Backup naming matches the manifest/patch/shim writers in this script.
|
|
1533
|
+
const backupPath = `${file}.bak-${Date.now()}`
|
|
1534
|
+
copyFileSync(file, backupPath)
|
|
1535
|
+
warn(`pnpm-workspace.yaml: contract conflict; backed up ${file} to ${backupPath}`)
|
|
1536
|
+
writeWorkspaceTemplate(file)
|
|
1537
|
+
return 'repaired'
|
|
1306
1538
|
}
|
|
1539
|
+
return 'ok'
|
|
1540
|
+
}
|
|
1307
1541
|
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1542
|
+
/** Manifest + patch + sidecar in ONE host-lock critical section (R7), before
|
|
1543
|
+
* step 4's bridge copy and well before step 5's package-manager call. */
|
|
1544
|
+
function provisionProfileFiles({ externalCarry, repair } = {}) {
|
|
1545
|
+
return withProfileWriteLock(profileDir, () => {
|
|
1546
|
+
const existing = existsSync(manifestPath) ? readManifest() : undefined
|
|
1547
|
+
if (existsSync(manifestPath) && existing === undefined) {
|
|
1548
|
+
fail(`${manifestPath} is not a valid JSON object manifest — leaving it untouched`)
|
|
1549
|
+
}
|
|
1550
|
+
const desired = desiredManifest(existing ?? { name: `dsh-profile-${activeProfile()}`, private: true })
|
|
1551
|
+
// A real dsh plugin add writes bundles in pnpm's sorted key order, not the
|
|
1552
|
+
// catalog order managedBundles() produces. Treat a converged set in any
|
|
1553
|
+
// order as already correct; every other difference still takes the
|
|
1554
|
+
// backup + rewrite path (see manifestAlreadyConverged).
|
|
1555
|
+
if (manifestAlreadyConverged(existing, desired)) {
|
|
1556
|
+
say(2, 'manifest', 'already correct, skipping')
|
|
1557
|
+
} else {
|
|
1558
|
+
mkdirSync(profileDir, { recursive: true })
|
|
1559
|
+
if (existsSync(manifestPath)) {
|
|
1560
|
+
const backupPath = `${manifestPath}.bak-${Date.now()}`
|
|
1561
|
+
copyFileSync(manifestPath, backupPath)
|
|
1562
|
+
console.log(`${PREFIX}backed up ${manifestPath} to ${backupPath}`)
|
|
1563
|
+
}
|
|
1564
|
+
// Copy-backup + tmp/rename commit: no window with a missing manifest.
|
|
1565
|
+
const tmpPath = `${manifestPath}.tmp-${process.pid}-${Date.now()}`
|
|
1566
|
+
writeFileSync(tmpPath, `${JSON.stringify(desired, null, 2)}\n`, { mode: 0o600 })
|
|
1567
|
+
renameSync(tmpPath, manifestPath)
|
|
1568
|
+
say(2, 'manifest', `wrote bundles [${managedBundles(existing ?? {}).join(', ')}]`)
|
|
1314
1569
|
}
|
|
1570
|
+
// D7 step 3 (N5): workspace contract is checked in the SAME host lock,
|
|
1571
|
+
// immediately after the manifest write and before the patch copy — a
|
|
1572
|
+
// whole-file host rewrite can therefore never drop this update.
|
|
1573
|
+
const workspaceState = ensureWorkspaceContract({ profileDir, repair })
|
|
1574
|
+
say(3, 'workspace', workspaceState === 'wrote'
|
|
1575
|
+
? `wrote ${join(profileDir, WORKSPACE_FILE)}`
|
|
1576
|
+
: workspaceState === 'repaired'
|
|
1577
|
+
? `repaired ${join(profileDir, WORKSPACE_FILE)} (backup + rewrite)`
|
|
1578
|
+
: 'already correct, skipping')
|
|
1579
|
+
provisionPatch({ externalCarry })
|
|
1580
|
+
})
|
|
1581
|
+
}
|
|
1582
|
+
|
|
1583
|
+
// --- T8b — one-shot migration (06 §7.4/§7.5) --------------------------------
|
|
1584
|
+
/** The marker's `version` comes from the shell package, never hardcoded. */
|
|
1585
|
+
function migrationVersion() {
|
|
1586
|
+
const version = readJsonObject(join(pkgRoot, 'package.json'))?.version
|
|
1587
|
+
if (typeof version !== 'string' || version.length === 0) {
|
|
1588
|
+
fail(
|
|
1589
|
+
'cannot determine the migration marker version',
|
|
1590
|
+
`${join(pkgRoot, 'package.json')} must declare a non-empty string "version".`,
|
|
1591
|
+
)
|
|
1315
1592
|
}
|
|
1593
|
+
return version
|
|
1594
|
+
}
|
|
1316
1595
|
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1596
|
+
/** Why a migration is incomplete (undefined = complete / already migrated). */
|
|
1597
|
+
function migrationFailure(plan) {
|
|
1598
|
+
if (plan.canWriteMarker === false) return 'a legacy patch failed to parse'
|
|
1599
|
+
if (plan.config?.invalid === true) return 'the legacy config.json is not valid JSON'
|
|
1600
|
+
if (plan.keybindings?.invalid === true) return 'the legacy keybindings.json is not valid JSON'
|
|
1601
|
+
return undefined
|
|
1602
|
+
}
|
|
1603
|
+
|
|
1604
|
+
/** Self-contained error: diagnosis + repair action + legacy directory paths. */
|
|
1605
|
+
function migrationIncompleteError(reason) {
|
|
1606
|
+
const legacyRoot = join(dshHome, 'profiles')
|
|
1607
|
+
return new ProvisionError(
|
|
1608
|
+
`migration incomplete — ${reason}`,
|
|
1609
|
+
[
|
|
1610
|
+
`Diagnosis: no ${MARKER_NAME} was written, so the next start retries the one-shot migration.`,
|
|
1611
|
+
`Repair: fix the source file under ${join(legacyRoot, 'opentui')} or ${join(legacyRoot, 'opentui-inproc')}, then start dsh-opentui again.`,
|
|
1612
|
+
`The legacy directories are read-only to the migration: nothing there is modified, deleted or renamed. Recovered copies are in ${join(profileDir, BACKUP_DIR)}.`,
|
|
1613
|
+
].join('\n'),
|
|
1614
|
+
)
|
|
1322
1615
|
}
|
|
1323
1616
|
|
|
1324
1617
|
// --- Standalone sessionController shim ownership ---------------------------
|
|
@@ -1373,10 +1666,11 @@ function provisionShim() {
|
|
|
1373
1666
|
}
|
|
1374
1667
|
|
|
1375
1668
|
// --- The provision pass itself (runs under the lock) ------------------------
|
|
1376
|
-
function runProvision({ repair = false } = {}) {
|
|
1377
|
-
//
|
|
1378
|
-
//
|
|
1379
|
-
|
|
1669
|
+
async function runProvision({ repair = false } = {}) {
|
|
1670
|
+
// The bridge copy converges unconditionally on every provision (no symlink
|
|
1671
|
+
// to repair). --repair is NOT a no-op overall: with it, a conflicting
|
|
1672
|
+
// pnpm-workspace.yaml is backed up and rewritten in step [3/8].
|
|
1673
|
+
if (repair) note('repair mode: a conflicting workspace contract will be backed up and rewritten')
|
|
1380
1674
|
// Prerequisites (read-only) are checked before any mutation.
|
|
1381
1675
|
if (!existsSync(bridgeDirRaw) || !statSync(bridgeDirRaw).isDirectory()) {
|
|
1382
1676
|
fail(
|
|
@@ -1401,33 +1695,65 @@ function runProvision({ repair = false } = {}) {
|
|
|
1401
1695
|
// grant the exact-version exemption when it is in-window but not exempted.
|
|
1402
1696
|
verifyHostCompatibility(bridgeDir)
|
|
1403
1697
|
|
|
1404
|
-
//
|
|
1405
|
-
//
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1698
|
+
// --- T8b one-shot migration (06 §7.4) --------------------------------------
|
|
1699
|
+
// This whole function runs inside main()'s `.provision.lock`, so planning here
|
|
1700
|
+
// means neither step [2/8]'s patch converge nor step [5/8]'s companion install
|
|
1701
|
+
// can bypass migration. A present marker makes the planner a no-op (no legacy
|
|
1702
|
+
// read, no carry) and makes the helper short-circuit all writes and notices.
|
|
1703
|
+
const migrationInputs = readMigrationInputs({ dshHome, profileDir, templatePatchText: PATCH_CONTENT })
|
|
1704
|
+
const migrationPlan = planMigration(migrationInputs)
|
|
1705
|
+
const version = migrationVersion()
|
|
1706
|
+
const incompleteReason = migrationInputs.markerExists ? undefined : migrationFailure(migrationPlan)
|
|
1707
|
+
// Bad JSON is the same "not migrated" state as a bad patch: keep backups and
|
|
1708
|
+
// valid payloads, but suppress the marker before failing fast.
|
|
1709
|
+
const applyPlan = incompleteReason ? { ...migrationPlan, canWriteMarker: false } : migrationPlan
|
|
1710
|
+
|
|
1711
|
+
// Production targets `profiles/opentui-monday`; legacy source B
|
|
1712
|
+
// (`profiles/opentui-inproc`) is a separate read-only directory. Snapshot the
|
|
1713
|
+
// legacy bytes FIRST (backups only — no config/keybindings/marker). Any I/O
|
|
1714
|
+
// failure here is fatal: converge must not run on an unsnapshotted source.
|
|
1715
|
+
// Only the test seam (runAsB) can still make source B == the target.
|
|
1716
|
+
// Crash re-entry: if a prior pass already snapshotted every source (e.g. it
|
|
1717
|
+
// converged but crashed before the marker), keep those bytes. Re-reading a
|
|
1718
|
+
// converged source B would otherwise present generated text as "legacy" and
|
|
1719
|
+
// rotate/overwrite the genuine pre-migration backup.
|
|
1720
|
+
const planBackups = Array.isArray(applyPlan.backups) ? applyPlan.backups : []
|
|
1721
|
+
const alreadySnapshotted = planBackups.length > 0 && planBackups.every((entry) =>
|
|
1722
|
+
entry && entry.source && entry.kind &&
|
|
1723
|
+
existsSync(join(profileDir, BACKUP_DIR, `${entry.source}-${entry.kind}`)))
|
|
1724
|
+
if (!alreadySnapshotted) {
|
|
1725
|
+
try {
|
|
1726
|
+
applyMigrationPlan({ profileDir, plan: applyPlan, version, backupsOnly: true })
|
|
1727
|
+
} catch (error) {
|
|
1728
|
+
throw new ProvisionError(
|
|
1729
|
+
'migration pre-backup failed; the legacy patch was NOT converged',
|
|
1730
|
+
[
|
|
1731
|
+
`Diagnosis: ${error instanceof Error ? error.message : String(error)}`,
|
|
1732
|
+
`The original patch is left untouched. Repair the backup target under ${join(profileDir, BACKUP_DIR)} and restart.`,
|
|
1733
|
+
].join('\n'),
|
|
1734
|
+
)
|
|
1427
1735
|
}
|
|
1428
1736
|
}
|
|
1429
1737
|
|
|
1430
|
-
// [
|
|
1738
|
+
// [2/8] Manifest + patch + sidecar: the ONLY managed-segment writer, and it
|
|
1739
|
+
// consumes migration externalCarry in the same converge pass (06 §4.5).
|
|
1740
|
+
provisionProfileFiles({ externalCarry: migrationPlan.externalCarry, repair })
|
|
1741
|
+
|
|
1742
|
+
// Config -> keybindings -> backups -> marker. applyMigrationPlan writes the
|
|
1743
|
+
// marker LAST and only when allowed; the pre-backup above already wrote the
|
|
1744
|
+
// same bytes (or an existing snapshot was kept on re-entry), so backups are
|
|
1745
|
+
// never rewritten here and that order stays unchanged.
|
|
1746
|
+
const migrationResult = applyMigrationPlan({ profileDir, plan: applyPlan, version, skipBackups: alreadySnapshotted })
|
|
1747
|
+
|
|
1748
|
+
// Print notices exactly once from the apply result. On a marker hit the
|
|
1749
|
+
// helper returns no notices, so "already migrated" is never replayed.
|
|
1750
|
+
for (const notice of migrationResult.notices) note(notice)
|
|
1751
|
+
|
|
1752
|
+
// Fail-fast on an incomplete migration. The marker was withheld, so the next
|
|
1753
|
+
// start retries after the user repairs the legacy file.
|
|
1754
|
+
if (incompleteReason) throw migrationIncompleteError(incompleteReason)
|
|
1755
|
+
|
|
1756
|
+
// [4/8] Materialize the bridge as a REAL DIRECTORY COPY (S6 symlink-debt
|
|
1431
1757
|
// retirement). The old design wrote an ABSOLUTE symlink to THIS
|
|
1432
1758
|
// installation's dist/bridge: that bound the profile to one install path and
|
|
1433
1759
|
// let multiple worktrees sharing a DSH_HOME leave the link pointing at
|
|
@@ -1451,17 +1777,17 @@ function runProvision({ repair = false } = {}) {
|
|
|
1451
1777
|
} catch (error) {
|
|
1452
1778
|
fail(`could not materialize bridge copy at ${linkPath}: ${error?.message ?? error}`)
|
|
1453
1779
|
}
|
|
1454
|
-
say(
|
|
1780
|
+
say(4, 'bridge-copy', `copied ${bridgeDir} -> ${linkPath}`)
|
|
1455
1781
|
} else {
|
|
1456
|
-
say(
|
|
1782
|
+
say(4, 'bridge-copy', `${linkPath} already matches this install, skipping`)
|
|
1457
1783
|
}
|
|
1458
1784
|
}
|
|
1459
1785
|
|
|
1460
|
-
// [
|
|
1461
|
-
// verify step so a half-provisioned manifest is caught by step [
|
|
1462
|
-
provisionCompanions()
|
|
1786
|
+
// [5/8] Companion installation. Runs after the bridge copy and before the
|
|
1787
|
+
// verify step so a half-provisioned manifest is caught by step [6/8].
|
|
1788
|
+
await provisionCompanions()
|
|
1463
1789
|
|
|
1464
|
-
// [
|
|
1790
|
+
// [6/8] Verify: linkPath is a REAL directory (never a symlink) carrying the
|
|
1465
1791
|
// shipped bridge files, and no @deepseek-ai package leaked into the profile.
|
|
1466
1792
|
// Companion state is cross-checked too (deps <-> bundles <-> node_modules).
|
|
1467
1793
|
{
|
|
@@ -1484,22 +1810,24 @@ function runProvision({ repair = false } = {}) {
|
|
|
1484
1810
|
)
|
|
1485
1811
|
}
|
|
1486
1812
|
const companionCount = verifyCompanionState()
|
|
1487
|
-
say(
|
|
1813
|
+
say(6, 'verify', `bridge resolves to ${bridgeDir}; no @deepseek-ai copy in profile; ${companionCount} companion(s) consistent`)
|
|
1488
1814
|
}
|
|
1489
1815
|
|
|
1490
|
-
// [
|
|
1816
|
+
// [7/8] Identity guard always runs, including on the conflict path, so a
|
|
1491
1817
|
// repointed / replaced bridge cannot slip through as a mere WARN.
|
|
1492
1818
|
verifyBridgeIdentity()
|
|
1493
1819
|
|
|
1494
|
-
//
|
|
1495
|
-
//
|
|
1496
|
-
|
|
1820
|
+
// The patch was already converged in step 2's critical section (R7). No
|
|
1821
|
+
// manifest rewrite here: `dsh plugin add` writes it itself under the host's
|
|
1822
|
+
// lock, and the only late cleanup (dropUnmountedCompanions) takes that same
|
|
1823
|
+
// lock for its short read-modify-write (N4).
|
|
1824
|
+
// [8/8] The local shim package the patch row resolves. S6: unconditional.
|
|
1497
1825
|
provisionShim()
|
|
1498
1826
|
|
|
1499
1827
|
console.log(`${PREFIX}PASS`)
|
|
1500
1828
|
}
|
|
1501
1829
|
|
|
1502
|
-
function main(argv = []) {
|
|
1830
|
+
async function main(argv = []) {
|
|
1503
1831
|
// --repair is passed by `dsh-opentui --repair-bridge`; accept the long form
|
|
1504
1832
|
// too so the underlying mode is unambiguous when invoked directly.
|
|
1505
1833
|
const repair = argv.includes('--repair') || argv.includes('--repair-bridge')
|
|
@@ -1507,7 +1835,7 @@ function main(argv = []) {
|
|
|
1507
1835
|
if (!existsSync(dshHome)) {
|
|
1508
1836
|
fail(
|
|
1509
1837
|
`DSH_HOME directory does not exist: ${dshHome}`,
|
|
1510
|
-
`Create it first (e.g. mkdir -p "${dshHome}"). The
|
|
1838
|
+
`Create it first (e.g. mkdir -p "${dshHome}"). The ${activeProfile()} profile must share the existing Harness home, not create an isolated one.`,
|
|
1511
1839
|
)
|
|
1512
1840
|
}
|
|
1513
1841
|
if (!statSync(dshHome).isDirectory()) {
|
|
@@ -1517,29 +1845,49 @@ function main(argv = []) {
|
|
|
1517
1845
|
// The lock lives inside the profile dir, so make sure it exists first.
|
|
1518
1846
|
mkdirSync(profileDir, { recursive: true })
|
|
1519
1847
|
|
|
1520
|
-
|
|
1521
|
-
|
|
1522
|
-
|
|
1523
|
-
|
|
1524
|
-
|
|
1525
|
-
return
|
|
1526
|
-
}
|
|
1527
|
-
|
|
1848
|
+
// R14: wait for a live holder, then FAIL with exit 2. There is no SKIP-0
|
|
1849
|
+
// path — launching a host on a half-provisioned profile is the bug P0-1.
|
|
1850
|
+
const token = acquireProvisionRunLock(profileDir, {
|
|
1851
|
+
onWait: (message) => note(message),
|
|
1852
|
+
})
|
|
1528
1853
|
try {
|
|
1529
|
-
runProvision({ repair })
|
|
1854
|
+
await runProvision({ repair })
|
|
1530
1855
|
} finally {
|
|
1531
|
-
|
|
1856
|
+
releaseProvisionRunLock(token, (message) => warn(message))
|
|
1532
1857
|
}
|
|
1533
1858
|
}
|
|
1534
1859
|
|
|
1535
|
-
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
|
|
1540
|
-
|
|
1541
|
-
|
|
1542
|
-
|
|
1860
|
+
// Importable seam for workspace-contract.test.ts: the exported helpers are
|
|
1861
|
+
// imported in-process, so main() must only run when THIS file is the entry
|
|
1862
|
+
// point (both `bun script.mjs` and `node script.mjs` set argv[1] to it).
|
|
1863
|
+
function isDirectInvocation() {
|
|
1864
|
+
const entry = process.argv[1]
|
|
1865
|
+
if (typeof entry !== 'string' || entry.length === 0) return false
|
|
1866
|
+
const self = fileURLToPath(import.meta.url)
|
|
1867
|
+
try {
|
|
1868
|
+
return realpathSync(entry) === realpathSync(self)
|
|
1869
|
+
} catch {
|
|
1870
|
+
return resolvePath(entry) === self
|
|
1543
1871
|
}
|
|
1544
|
-
|
|
1872
|
+
}
|
|
1873
|
+
|
|
1874
|
+
if (isDirectInvocation()) {
|
|
1875
|
+
// main() is async (the companion step's registry query is a bounded concurrent
|
|
1876
|
+
// batch). Its rejection is handled exactly like a synchronous throw used to be,
|
|
1877
|
+
// so the lock-release `finally` still runs before this handler sets exitCode.
|
|
1878
|
+
main(process.argv.slice(2)).catch((error) => {
|
|
1879
|
+
if (error instanceof ProvisionLockError || error?.name === 'ProfileLockTimeoutError') {
|
|
1880
|
+
console.error(`${PREFIX}FAIL — ${error.message}`)
|
|
1881
|
+
if (error.detail) console.error(error.detail)
|
|
1882
|
+
} else if (error instanceof ProvisionError) {
|
|
1883
|
+
console.error(`${PREFIX}FAIL — ${error.message}`)
|
|
1884
|
+
if (error.detail) console.error(error.detail.trimEnd())
|
|
1885
|
+
} else {
|
|
1886
|
+
console.error(`${PREFIX}FAIL — unexpected error: ${error?.stack ?? String(error)}`)
|
|
1887
|
+
}
|
|
1888
|
+
// Lock timeouts carry exitCode 2 (distinct from a general provisioning
|
|
1889
|
+
// failure) so the launcher can tell "another live run owns this profile"
|
|
1890
|
+
// from a real error; either way the host is never started.
|
|
1891
|
+
process.exitCode = Number.isInteger(error?.exitCode) ? error.exitCode : 1
|
|
1892
|
+
})
|
|
1545
1893
|
}
|