@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.
@@ -0,0 +1,185 @@
1
+ /**
2
+ * `profiles/<p>/package.json.lock` — the HOST's writer lock (design 06 R15).
3
+ *
4
+ * This is a byte-for-byte protocol replica of
5
+ * dsh-atomic-write/src/index.ts:100-273:
6
+ * - the lock is a sibling of package.json, named package.json.lock;
7
+ * - its content is exactly `${pid}\n` (NOT JSON — the host's holderExited
8
+ * only accepts /^\d+\n$/, so a JSON record would leave a crashed lock
9
+ * un-takeoverable by the host);
10
+ * - exclusive creation with `wx` (EEXIST, or EPERM + lstat on Windows, is
11
+ * contention);
12
+ * - a dead holder is reclaimed only through a sha256-named claim file, and
13
+ * only after re-reading the record and re-probing the pid under that claim;
14
+ * - liveness is pid-only (ESRCH == dead). A reused pid, EPERM, an incomplete
15
+ * record or a foreign process is NEVER taken over and NEVER aged out.
16
+ *
17
+ * This lock protects only the short profile-file critical section (manifest +
18
+ * patch + sidecar). It is deliberately NOT held across step 4's pnpm install.
19
+ * The whole-run mutex is `.provision.lock` (see provision-run-lock.mjs).
20
+ */
21
+
22
+ import { createHash } from 'node:crypto'
23
+ import { lstatSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
24
+ import { join } from 'node:path'
25
+
26
+ export const PROFILE_LOCK_WAIT_MS = 120_000
27
+ export const PROFILE_LOCK_NAME = 'package.json.lock'
28
+ export const WAIT_ENV = 'DSH_OPENTUI_PROFILE_LOCK_WAIT_MS'
29
+ export function waitMsFromEnv(env = process.env) {
30
+ const raw = env[WAIT_ENV]
31
+ if (raw === undefined || raw === '') return PROFILE_LOCK_WAIT_MS
32
+ const value = Number(raw)
33
+ return Number.isFinite(value) && value >= 0 ? value : PROFILE_LOCK_WAIT_MS
34
+ }
35
+ const RETRY_INITIAL_MS = 50
36
+ const RETRY_MAX_MS = 500
37
+ const PID_MAX = 0x7fffffff
38
+
39
+ /** Sleep without timers — the provisioner is a synchronous script. */
40
+ export function sleepSync(ms) {
41
+ const buf = new Int32Array(new SharedArrayBuffer(4))
42
+ Atomics.wait(buf, 0, 0, ms)
43
+ }
44
+
45
+ /** ESRCH proves the process is gone; EPERM proves it exists under another user. */
46
+ export function pidAlive(pid) {
47
+ if (!Number.isInteger(pid) || pid <= 0 || pid > PID_MAX) return false
48
+ try {
49
+ process.kill(pid, 0)
50
+ return true
51
+ } catch (error) {
52
+ return error?.code === 'EPERM'
53
+ }
54
+ }
55
+
56
+ /** Host `holderExited` (atomic-write/src/index.ts:112-127), verbatim semantics. */
57
+ export function holderExited(record) {
58
+ if (typeof record !== 'string' || !/^\d+\n$/.test(record)) return false
59
+ const pid = Number(record.trim())
60
+ if (pid === 0 || pid > PID_MAX || pid === process.pid) return false
61
+ try {
62
+ process.kill(pid, 0)
63
+ return false
64
+ } catch (error) {
65
+ return error?.code === 'ESRCH'
66
+ }
67
+ }
68
+
69
+ export function readLockRecord(lockPath) {
70
+ try {
71
+ return readFileSync(lockPath, 'utf8')
72
+ } catch {
73
+ // A vanishing lock (or Windows still deleting it) proves nothing.
74
+ return undefined
75
+ }
76
+ }
77
+
78
+ function isLockContention(error, lockPath) {
79
+ if (!error) return false
80
+ if (error.code === 'EEXIST') return true
81
+ if (error.code !== 'EPERM') return false
82
+ try {
83
+ lstatSync(lockPath)
84
+ return true
85
+ } catch {
86
+ return false
87
+ }
88
+ }
89
+
90
+ function claimPathFor(lockPath, record) {
91
+ return `${lockPath}.takeover-${createHash('sha256').update(record).digest('hex').slice(0, 16)}`
92
+ }
93
+
94
+ /** atomic-write/src/index.ts:150-178 — serialize contenders before removing a dead holder's lock. */
95
+ export function takeOverExitedHolder(lockPath) {
96
+ const record = readLockRecord(lockPath)
97
+ if (record === undefined || !holderExited(record)) return false
98
+ const claim = claimPathFor(lockPath, record)
99
+ try {
100
+ writeFileSync(claim, `${process.pid}\n`, { mode: 0o600, flag: 'wx' })
101
+ } catch (error) {
102
+ if (error?.code === 'EEXIST' || error?.code === 'EPERM') return false
103
+ throw error
104
+ }
105
+ try {
106
+ if (readLockRecord(lockPath) !== record || !holderExited(record)) return false
107
+ rmSync(lockPath, { force: true })
108
+ return true
109
+ } finally {
110
+ // A stale claim names a record that is no longer the lock; it blocks nothing.
111
+ rmSync(claim, { force: true })
112
+ }
113
+ }
114
+
115
+ export class ProfileLockTimeoutError extends Error {
116
+ constructor(lockPath, holderPid) {
117
+ super(
118
+ `timed out after ${PROFILE_LOCK_WAIT_MS}ms waiting for ${lockPath}` +
119
+ (holderPid === undefined ? '' : ` (holder pid ${holderPid})`) +
120
+ '. Another window may be running `dsh plugin install` (the host holds this lock for the whole pnpm run). ' +
121
+ 'Retry after it finishes; a pid-reused lock needs manual removal.',
122
+ )
123
+ this.name = 'ProfileLockTimeoutError'
124
+ this.lockPath = lockPath
125
+ this.holderPid = holderPid
126
+ this.exitCode = 2
127
+ }
128
+ }
129
+
130
+ /**
131
+ * Run `operation` under the host lock. Sync by design (the provisioner uses
132
+ * spawnSync throughout); the API shape otherwise matches the design's
133
+ * `withProfileWriteLock(profileDir, fn, { waitMs })`.
134
+ */
135
+ export function withProfileWriteLock(profileDir, operation, { waitMs = waitMsFromEnv(), sleep = sleepSync, now = Date.now } = {}) {
136
+ const lockPath = join(profileDir, PROFILE_LOCK_NAME)
137
+ const record = `${process.pid}\n`
138
+ const deadline = now() + waitMs
139
+ let delay = RETRY_INITIAL_MS
140
+ let retriedUnconfirmedPermissionError = false
141
+ for (;;) {
142
+ try {
143
+ writeFileSync(lockPath, record, { mode: 0o600, flag: 'wx' })
144
+ break
145
+ } catch (error) {
146
+ if (!isLockContention(error, lockPath)) {
147
+ // Windows can release a competing lock between exclusive create and lstat.
148
+ if (process.platform !== 'win32' || error?.code !== 'EPERM' || retriedUnconfirmedPermissionError) throw error
149
+ retriedUnconfirmedPermissionError = true
150
+ } else if (takeOverExitedHolder(lockPath)) {
151
+ continue
152
+ }
153
+ }
154
+ if (now() >= deadline) {
155
+ const current = readLockRecord(lockPath)
156
+ const holder = current && /^(\d+)\n$/.exec(current)
157
+ throw new ProfileLockTimeoutError(lockPath, holder ? Number(holder[1]) : undefined)
158
+ }
159
+ sleep(delay)
160
+ delay = Math.min(delay * 2, RETRY_MAX_MS)
161
+ }
162
+ try {
163
+ return operation()
164
+ } finally {
165
+ const current = readLockRecord(lockPath)
166
+ if (current !== undefined && current !== record) {
167
+ console.error(`dsh-opentui(inproc): WARN ${lockPath} was replaced while held; removing it anyway (host compatibility)`)
168
+ }
169
+ rmSync(lockPath, { force: true })
170
+ }
171
+ }
172
+
173
+ export default {
174
+ PROFILE_LOCK_WAIT_MS,
175
+ PROFILE_LOCK_NAME,
176
+ WAIT_ENV,
177
+ waitMsFromEnv,
178
+ pidAlive,
179
+ holderExited,
180
+ readLockRecord,
181
+ takeOverExitedHolder,
182
+ withProfileWriteLock,
183
+ ProfileLockTimeoutError,
184
+ sleepSync,
185
+ }
@@ -0,0 +1 @@
1
+ export declare const DEFAULT_PROFILE: string
@@ -0,0 +1,2 @@
1
+ // Single source of truth for the in-process host profile name.
2
+ export const DEFAULT_PROFILE = "opentui-monday"
@@ -0,0 +1,223 @@
1
+ /**
2
+ * Whole-run mutex for the inproc provisioner (design 06 R14, P0-1).
3
+ *
4
+ * `.provision.lock` is held for the ENTIRE provision pass, including step 4's
5
+ * companion install. Its record is JSON (our own protocol, not the host's):
6
+ * { pid, nonce, startedAt, heartbeatAt, step }
7
+ *
8
+ * Liveness is PID-ONLY: process.kill(pid, 0). A live holder is never aged out —
9
+ * there is no `LOCK_STALE_MS` and no mtime-based takeover of a live record,
10
+ * however old. Dead holders are reclaimed through a sha256-named claim file so
11
+ * two contenders cannot both take over. Corrupt/empty records get a 1s grace
12
+ * (the create→write window) before they can be reclaimed. A reused pid is
13
+ * indistinguishable from a live holder: we never take it over; we wait, then
14
+ * fail with exit code 2 and an explicit manual-recovery hint.
15
+ *
16
+ * Lock ORDER: `.provision.lock` first, then package.json.lock (profile-lock.mjs).
17
+ * Never the reverse — the host only takes the latter.
18
+ */
19
+
20
+ import { createHash } from 'node:crypto'
21
+ import { readFileSync, statSync, writeFileSync, rmSync, openSync, closeSync, writeSync } from 'node:fs'
22
+ import { join } from 'node:path'
23
+ import { pidAlive, sleepSync } from './profile-lock.mjs'
24
+
25
+ export const LOCK_NAME = '.provision.lock'
26
+ export const LOCK_CORRUPT_GRACE_MS = 1_000
27
+ export const PROVISION_LOCK_WAIT_MS = 30_000
28
+ export const WAIT_ENV = 'DSH_OPENTUI_PROVISION_LOCK_WAIT_MS'
29
+ const RETRY_INITIAL_MS = 50
30
+ const RETRY_MAX_MS = 500
31
+
32
+ export function waitMsFromEnv(env = process.env) {
33
+ const raw = env[WAIT_ENV]
34
+ if (raw === undefined || raw === '') return PROVISION_LOCK_WAIT_MS
35
+ const value = Number(raw)
36
+ return Number.isFinite(value) && value >= 0 ? value : PROVISION_LOCK_WAIT_MS
37
+ }
38
+
39
+ /** Pure classification used by the lock tests (#37/#38). `record` is the parsed
40
+ * lock record plus `mtimeMs`; a corrupt record has `corrupt:true`. Age is used
41
+ * ONLY for corrupt records, never for a record with a live pid. */
42
+ export function classifyLock(record, now = Date.now(), alive = pidAlive) {
43
+ if (record === undefined) return { state: 'absent', takeover: true, reason: 'lock file is absent or unreadable' }
44
+ if (record.corrupt || !Number.isInteger(record.pid)) {
45
+ const age = Math.max(0, now - (record.mtimeMs ?? now))
46
+ if (age > LOCK_CORRUPT_GRACE_MS) {
47
+ return { state: 'corrupt-stale', takeover: true, reason: `corrupt lock record, age ${age}ms > ${LOCK_CORRUPT_GRACE_MS}ms` }
48
+ }
49
+ return { state: 'corrupt-grace', takeover: false, reason: `corrupt lock record within the ${LOCK_CORRUPT_GRACE_MS}ms create/write grace` }
50
+ }
51
+ if (record.pid === process.pid) return { state: 'live', takeover: false, reason: `held by self (pid ${record.pid})` }
52
+ if (!alive(record.pid)) return { state: 'dead', takeover: true, reason: `holder pid ${record.pid} no longer exists` }
53
+ // A live holder is live forever from our point of view. `startedAt` is
54
+ // diagnostic context only; it must never influence takeover.
55
+ const age = Number.isFinite(record.startedAt) ? now - record.startedAt : undefined
56
+ return {
57
+ state: 'live',
58
+ takeover: false,
59
+ reason: `holder pid ${record.pid} alive (step ${record.step ?? 'unknown'}${age === undefined ? '' : `, age ${age}ms — age is NOT a stale signal`})`,
60
+ }
61
+ }
62
+
63
+ /** True when the record's pid is provably gone (or the record is absent/corrupt past grace). */
64
+ export function provisionHolderExited(record) {
65
+ return classifyLock(record).takeover
66
+ }
67
+
68
+ function readRawLock(lockPath) {
69
+ try {
70
+ return { raw: readFileSync(lockPath, 'utf8'), mtimeMs: statSync(lockPath).mtimeMs }
71
+ } catch {
72
+ return undefined
73
+ }
74
+ }
75
+
76
+ function parseRecord(entry) {
77
+ if (!entry) return undefined
78
+ try {
79
+ const parsed = JSON.parse(entry.raw)
80
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) throw new Error('not an object')
81
+ return { ...parsed, mtimeMs: entry.mtimeMs }
82
+ } catch {
83
+ return { corrupt: true, mtimeMs: entry.mtimeMs }
84
+ }
85
+ }
86
+
87
+ function claimPathFor(lockPath, raw) {
88
+ return `${lockPath}.takeover-${createHash('sha256').update(raw).digest('hex').slice(0, 16)}`
89
+ }
90
+
91
+ /** Take over a dead/corrupt holder under a claim, re-reading and re-probing. */
92
+ function takeOverLock(lockPath) {
93
+ const entry = readRawLock(lockPath)
94
+ if (!entry || !classifyLock(parseRecord(entry)).takeover) return false
95
+ const claim = claimPathFor(lockPath, entry.raw)
96
+ try {
97
+ writeFileSync(claim, `${process.pid}\n`, { mode: 0o600, flag: 'wx' })
98
+ } catch (error) {
99
+ if (error?.code === 'EEXIST' || error?.code === 'EPERM') return false
100
+ throw error
101
+ }
102
+ try {
103
+ const again = readRawLock(lockPath)
104
+ if (!again || again.raw !== entry.raw || !classifyLock(parseRecord(again)).takeover) return false
105
+ rmSync(lockPath, { force: true })
106
+ return true
107
+ } finally {
108
+ rmSync(claim, { force: true })
109
+ }
110
+ }
111
+
112
+ export class ProvisionLockError extends Error {
113
+ constructor(message, detail) {
114
+ super(message)
115
+ this.name = 'ProvisionLockError'
116
+ this.detail = detail
117
+ this.exitCode = 2
118
+ }
119
+ }
120
+
121
+ function makeToken(step) {
122
+ return {
123
+ pid: process.pid,
124
+ nonce: createHash('sha256').update(`${process.pid}:${Date.now()}:${Math.random()}`).digest('hex').slice(0, 16),
125
+ startedAt: Date.now(),
126
+ heartbeatAt: Date.now(),
127
+ step,
128
+ }
129
+ }
130
+
131
+ function readOwnLock(lockPath) {
132
+ try {
133
+ return JSON.parse(readFileSync(lockPath, 'utf8'))
134
+ } catch {
135
+ return undefined
136
+ }
137
+ }
138
+
139
+ /**
140
+ * Acquire the whole-run lock. Returns `{ pid, nonce, lockPath }`; throws
141
+ * ProvisionLockError (exitCode 2) on timeout. Never returns a SKIP token.
142
+ */
143
+ export function acquireProvisionRunLock(profileDir, { waitMs = waitMsFromEnv(), onWait = () => {}, sleep = sleepSync, now = Date.now } = {}) {
144
+ const lockPath = join(profileDir, LOCK_NAME)
145
+ const deadline = now() + waitMs
146
+ let delay = RETRY_INITIAL_MS
147
+ let lastStatusLine = 0
148
+ for (;;) {
149
+ const token = makeToken('1/7 host')
150
+ let created = false
151
+ try {
152
+ const fd = openSync(lockPath, 'wx', 0o600)
153
+ try {
154
+ writeSync(fd, JSON.stringify(token))
155
+ } finally {
156
+ closeSync(fd)
157
+ }
158
+ created = true
159
+ } catch (error) {
160
+ if (error?.code !== 'EEXIST') throw error
161
+ }
162
+ if (created) {
163
+ // Re-read before doing any work: a contender that took over while we were
164
+ // descheduled must not leave two processes believing they hold the lock.
165
+ const held = readOwnLock(lockPath)
166
+ if (held?.pid === token.pid && held.nonce === token.nonce) return { ...token, lockPath }
167
+ sleep(delay)
168
+ continue
169
+ }
170
+
171
+ const entry = readRawLock(lockPath)
172
+ const verdict = classifyLock(parseRecord(entry), now())
173
+ if (verdict.takeover) {
174
+ onWait(`stale provisioning lock (${verdict.reason}); taking over via claim`)
175
+ if (takeOverLock(lockPath)) continue
176
+ }
177
+ if (now() - lastStatusLine >= 5_000) {
178
+ onWait(`waiting for provisioning lock (${verdict.reason})`)
179
+ lastStatusLine = now()
180
+ }
181
+ if (now() >= deadline) {
182
+ const current = parseRecord(readRawLock(lockPath))
183
+ const who = current && !current.corrupt && Number.isInteger(current.pid)
184
+ ? `holder pid ${current.pid}, step ${current.step ?? 'unknown'}, age ${Math.max(0, now() - (current.startedAt ?? now()))}ms`
185
+ : 'an unreadable record'
186
+ throw new ProvisionLockError(
187
+ `could not acquire ${lockPath} within ${waitMs}ms (${who})`,
188
+ [
189
+ `The recorded holder is still considered alive — its age is deliberately NOT a stale signal, and a reused pid is never taken over.`,
190
+ `Confirm no provisioning is running, then remove ${lockPath} manually to recover.`,
191
+ `Lock path: ${lockPath}`,
192
+ ].join('\n'),
193
+ )
194
+ }
195
+ sleep(delay)
196
+ delay = Math.min(delay * 2, RETRY_MAX_MS)
197
+ }
198
+ }
199
+
200
+ /** Release only a lock that is still ours (pid + nonce). */
201
+ export function releaseProvisionRunLock(token, onWarn = () => {}) {
202
+ if (!token) return
203
+ try {
204
+ const held = readOwnLock(token.lockPath)
205
+ if (held?.pid === token.pid && held.nonce === token.nonce) rmSync(token.lockPath, { force: true })
206
+ else onWarn(`provisioning lock was replaced while held; leaving ${token.lockPath} untouched`)
207
+ } catch {
208
+ // Best-effort cleanup: never mask the primary provisioning result.
209
+ }
210
+ }
211
+
212
+ export default {
213
+ LOCK_NAME,
214
+ LOCK_CORRUPT_GRACE_MS,
215
+ PROVISION_LOCK_WAIT_MS,
216
+ WAIT_ENV,
217
+ waitMsFromEnv,
218
+ classifyLock,
219
+ provisionHolderExited,
220
+ acquireProvisionRunLock,
221
+ releaseProvisionRunLock,
222
+ ProvisionLockError,
223
+ }