create-principles-disciple 1.154.3 → 1.154.5

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.
Files changed (109) hide show
  1. package/_release/product-identity.json +2 -2
  2. package/codex-adapter/dist/worker/workspace-worker.js +7 -1
  3. package/codex-adapter/package.json +1 -1
  4. package/core/dist/runtime/feature-flags/feature-flag-contract.d.ts.map +1 -1
  5. package/core/dist/runtime/feature-flags/feature-flag-contract.js +1 -0
  6. package/core/dist/runtime/feature-flags/feature-flag-contract.js.map +1 -1
  7. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.d.ts.map +1 -1
  8. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js +8 -0
  9. package/core/dist/runtime/feature-flags/feature-flag-lifecycle.js.map +1 -1
  10. package/core/dist/runtime/pain-ingress-payload.d.ts +13 -0
  11. package/core/dist/runtime/pain-ingress-payload.d.ts.map +1 -1
  12. package/core/dist/runtime/pain-ingress-payload.js +26 -0
  13. package/core/dist/runtime/pain-ingress-payload.js.map +1 -1
  14. package/core/dist/runtime/pain-ingress.d.ts +1 -1
  15. package/core/dist/runtime/pain-ingress.d.ts.map +1 -1
  16. package/core/dist/runtime/pain-ingress.js +15 -2
  17. package/core/dist/runtime/pain-ingress.js.map +1 -1
  18. package/core/dist/runtime/pain-signal-bridge.d.ts +18 -0
  19. package/core/dist/runtime/pain-signal-bridge.d.ts.map +1 -1
  20. package/core/dist/runtime/pain-signal-bridge.js +49 -1
  21. package/core/dist/runtime/pain-signal-bridge.js.map +1 -1
  22. package/core/dist/runtime/pain-signal-runtime-factory.d.ts +7 -0
  23. package/core/dist/runtime/pain-signal-runtime-factory.d.ts.map +1 -1
  24. package/core/dist/runtime/pain-signal-runtime-factory.js +2 -0
  25. package/core/dist/runtime/pain-signal-runtime-factory.js.map +1 -1
  26. package/core/dist/runtime/pain-to-principle-service.d.ts +8 -0
  27. package/core/dist/runtime/pain-to-principle-service.d.ts.map +1 -1
  28. package/core/dist/runtime/pain-to-principle-service.js +21 -1
  29. package/core/dist/runtime/pain-to-principle-service.js.map +1 -1
  30. package/core/package.json +1 -1
  31. package/host-runtime/dist/auto-pain-authorization.d.ts +29 -0
  32. package/host-runtime/dist/auto-pain-authorization.js +32 -0
  33. package/host-runtime/dist/diagnostician-auto-run.d.ts +1 -1
  34. package/host-runtime/dist/diagnostician-auto-run.js +41 -0
  35. package/host-runtime/dist/governance-signal-admission.js +16 -0
  36. package/host-runtime/dist/index.d.ts +1 -0
  37. package/host-runtime/dist/index.js +1 -0
  38. package/host-runtime/package.json +1 -1
  39. package/install-layout/dist/active-release.d.ts +41 -0
  40. package/install-layout/dist/active-release.js +131 -0
  41. package/install-layout/dist/index.d.ts +56 -5
  42. package/install-layout/dist/index.js +166 -1
  43. package/install-layout/dist/mcp-binding-contract.d.ts +76 -12
  44. package/install-layout/dist/mcp-binding-contract.js +183 -75
  45. package/install-layout/package.json +1 -1
  46. package/package.json +3 -3
  47. package/pd-cli/dist/commands/pain-record.d.ts.map +1 -1
  48. package/pd-cli/dist/commands/pain-record.js +4 -1
  49. package/pd-cli/dist/commands/pain-record.js.map +1 -1
  50. package/pd-cli/dist/commands/pain-retry.d.ts.map +1 -1
  51. package/pd-cli/dist/commands/pain-retry.js +19 -1
  52. package/pd-cli/dist/commands/pain-retry.js.map +1 -1
  53. package/pd-cli/dist/commands/service-run-once.d.ts +6 -0
  54. package/pd-cli/dist/commands/service-run-once.d.ts.map +1 -0
  55. package/pd-cli/dist/commands/service-run-once.js +139 -0
  56. package/pd-cli/dist/commands/service-run-once.js.map +1 -0
  57. package/pd-cli/dist/program.d.ts.map +1 -1
  58. package/pd-cli/dist/program.js +21 -0
  59. package/pd-cli/dist/program.js.map +1 -1
  60. package/pd-cli/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  61. package/pd-cli/dist/services/pain-flood-simulation-runner.js +4 -0
  62. package/pd-cli/dist/services/pain-flood-simulation-runner.js.map +1 -1
  63. package/pd-cli/dist/services/service-host/index.d.ts +15 -0
  64. package/pd-cli/dist/services/service-host/index.d.ts.map +1 -0
  65. package/pd-cli/dist/services/service-host/index.js +15 -0
  66. package/pd-cli/dist/services/service-host/index.js.map +1 -0
  67. package/pd-cli/dist/services/service-host/install-identity.d.ts +79 -0
  68. package/pd-cli/dist/services/service-host/install-identity.d.ts.map +1 -0
  69. package/pd-cli/dist/services/service-host/install-identity.js +166 -0
  70. package/pd-cli/dist/services/service-host/install-identity.js.map +1 -0
  71. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts +134 -0
  72. package/pd-cli/dist/services/service-host/locking/service-run-lock.d.ts.map +1 -0
  73. package/pd-cli/dist/services/service-host/locking/service-run-lock.js +659 -0
  74. package/pd-cli/dist/services/service-host/locking/service-run-lock.js.map +1 -0
  75. package/pd-cli/dist/services/service-host/owner-projection.d.ts +47 -0
  76. package/pd-cli/dist/services/service-host/owner-projection.d.ts.map +1 -0
  77. package/pd-cli/dist/services/service-host/owner-projection.js +121 -0
  78. package/pd-cli/dist/services/service-host/owner-projection.js.map +1 -0
  79. package/pd-cli/dist/services/service-host/run-once.d.ts +96 -0
  80. package/pd-cli/dist/services/service-host/run-once.d.ts.map +1 -0
  81. package/pd-cli/dist/services/service-host/run-once.js +440 -0
  82. package/pd-cli/dist/services/service-host/run-once.js.map +1 -0
  83. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts +117 -0
  84. package/pd-cli/dist/services/service-host/status/service-run-status.d.ts.map +1 -0
  85. package/pd-cli/dist/services/service-host/status/service-run-status.js +150 -0
  86. package/pd-cli/dist/services/service-host/status/service-run-status.js.map +1 -0
  87. package/pd-cli/dist/services/service-host/workspace-discovery.d.ts +71 -0
  88. package/pd-cli/dist/services/service-host/workspace-discovery.d.ts.map +1 -0
  89. package/pd-cli/dist/services/service-host/workspace-discovery.js +288 -0
  90. package/pd-cli/dist/services/service-host/workspace-discovery.js.map +1 -0
  91. package/pd-cli/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  92. package/pd-cli/dist/services/synthetic-baseline-runner.js +4 -0
  93. package/pd-cli/dist/services/synthetic-baseline-runner.js.map +1 -1
  94. package/pd-cli/package.json +1 -1
  95. package/plugin/dist/bundle.js +420 -420
  96. package/plugin/dist/core/signal-collector-host.d.ts +12 -0
  97. package/plugin/dist/openclaw.plugin.json +1 -1
  98. package/plugin/dist/templates/langs/en/skills/pd-pain-signal/SKILL.md +10 -2
  99. package/plugin/dist/templates/langs/zh/skills/pd-pain-signal/SKILL.md +10 -2
  100. package/plugin/mcp/launcher.cjs +40 -4
  101. package/plugin/openclaw.plugin.json +1 -1
  102. package/plugin/package.json +1 -1
  103. package/plugin/templates/langs/en/skills/pd-pain-signal/SKILL.md +10 -2
  104. package/plugin/templates/langs/zh/skills/pd-pain-signal/SKILL.md +10 -2
  105. package/release-manager/package.json +1 -1
  106. package/workbuddy-adapter/dist/worker/workspace-worker.js +4 -1
  107. package/workbuddy-adapter/package.json +1 -1
  108. package/workbuddy-adapter/plugin/mcp/launcher.cjs +40 -4
  109. package/workbuddy-adapter/plugin/skills/pd-pain-signal/SKILL.md +10 -2
@@ -0,0 +1,659 @@
1
+ /**
2
+ * Install-level single-instance run lock (SPEC-PD-SERVICE-HOST-001 §8.2 step
3
+ * 2, FR-08; TD §2.1 `locking/service-run-lock.ts`).
4
+ *
5
+ * The protocol is the one proven by PRI-1151's cross-process control-state
6
+ * lock (`host-runtime/product-telemetry/control-state-lock.ts`): atomic
7
+ * `'wx'` create with an owner body `<pid> <token> <createdAtISO>`; ownership-
8
+ * checked release; stale takeover gated on holder-liveness proof. It is
9
+ * re-declared here rather than exported because the semantic contract
10
+ * genuinely differs (P7: a real variation axis, not a speculative seam):
11
+ *
12
+ * - The control-state lock guards millisecond-scale read-modify-write
13
+ * transactions (5s stale window). A run-once coordinator legitimately
14
+ * runs for minutes, so a second coordinator must NEVER take over a lock
15
+ * that may still be a live run — the stale window is 30 minutes by
16
+ * default.
17
+ * - Contention is an IMMEDIATE verdict, not a bounded wait: SPEC §8.2
18
+ * requires the second instance to report `already_running`, not to queue
19
+ * behind the first.
20
+ * - A stale mtime whose body cannot be read is `corrupt` (fail-closed,
21
+ * human decision), never silently takeover-able and never reported as a
22
+ * live run.
23
+ *
24
+ * ── Concurrency protocol (P1-4 round 4: SQLite arbitration) ────────────────
25
+ *
26
+ * Every acquisition, takeover and release decision is serialized through a
27
+ * dedicated arbitration gate: the stable, short-lived SQLite database
28
+ * `<pdHome>/service/service-run-gate.db`, guarded by `BEGIN IMMEDIATE`.
29
+ * While one process holds the transaction, a contender's `BEGIN IMMEDIATE`
30
+ * fails with SQLITE_BUSY — ACQUIRE waits zero milliseconds (SPEC §8.2
31
+ * immediate `already_running`, never a queue), RELEASE retries briefly and
32
+ * bounded. A gate that cannot be opened or transacted at all maps to
33
+ * `unwritable` (fail-closed).
34
+ *
35
+ * The state machine inside the transaction is:
36
+ *
37
+ * evaluateLock ─ 'absent' → 'wx' create → acquired
38
+ * ├ 'fresh' → held
39
+ * ├ 'dead' → re-evaluate → unlink → 'wx' create
40
+ * │ → acquired(staleTakenOver)
41
+ * ├ 'stale-alive' → held (live or inconclusive owner)
42
+ * ├ 'stale-unreadable' → corrupt (identity unverifiable)
43
+ * └ 'stale-anonymous' → corrupt (no holder identity)
44
+ *
45
+ * 'dead' means the recorded holder PID is PROVABLY dead — age does not
46
+ * matter: a verifiably-exited holder is recovered immediately rather than
47
+ * waiting out the stale window (§P0.8).
48
+ *
49
+ * Why this closes the file-mutex races:
50
+ *
51
+ * - No mutex file exists. The arbiter is a real cross-process lock held by
52
+ * the OS/SQLite, not a file whose mtime pretends to prove liveness — so
53
+ * "stale mutex" reclaim is impossible by construction, and a live
54
+ * coordinator's arbitration can never be reclaimed by file-age
55
+ * heuristics (P1-4A moot). File age only feeds `evaluateLock`, and only
56
+ * inside the serialized section where PID liveness remains the sole
57
+ * takeover authority.
58
+ * - verify→delete→create is one transaction: two stale breakers cannot
59
+ * interleave (P1-4B). The first commits before the second's BEGIN
60
+ * completes; the second re-evaluates AFTER the first's lock is already
61
+ * in place and reports `held`.
62
+ * - A crashed coordinator releases its transaction through the OS
63
+ * automatically — recovery is immediate and deterministic (P1-4B).
64
+ * - Release is verify-body + unlink inside the SAME transaction: a true
65
+ * compare-and-delete under the arbiter, never a read→compare→unlink
66
+ * window (P1-4C). A foreign body is never unlinked.
67
+ * - No generic sweep touches arbitration state: `sweepOrphanSidecars`
68
+ * only removes age-proven legacy sidecars (`.mtx`, `.take-*`, `.rel-*`),
69
+ * none of which the new protocol creates or reads (P1-4D). The gate
70
+ * database and its `-journal`/`-wal`/`-shm` sidecars are never swept.
71
+ *
72
+ * No heartbeat exists and none is needed for Phase 1: a run is bounded far
73
+ * below the stale window, and mid-run ownership is re-verified by
74
+ * `holdsServiceRunLock` (the body compare IS the heartbeat-identity check —
75
+ * a file no longer carrying our body means we lost the run). PID liveness
76
+ * remains the sole takeover authority — file age alone is never the sole
77
+ * eviction signal (same rule as `principles-core/ledger-file-lock.ts`).
78
+ *
79
+ * Cross-platform note: `BEGIN IMMEDIATE` is the same advisory-file-lock
80
+ * arbitration on POSIX and Windows (SQLite's POSIX fcntl locks and Windows
81
+ * LockFileEx regions are both released by the OS on process death), and the
82
+ * lock file itself still changes hands only via 'wx' create + unlink —
83
+ * never rename, whose overwrite semantics differ between the platforms. A
84
+ * file still open by its dead holder is not unlinkable on Windows — unlink
85
+ * failure aborts the takeover fail-closed inside the transaction.
86
+ */
87
+ import * as fs from 'node:fs';
88
+ import * as path from 'node:path';
89
+ import { randomUUID } from 'node:crypto';
90
+ import Database from 'better-sqlite3';
91
+ /**
92
+ * A lock older than this is treated as a crashed holder. A legitimate
93
+ * run-once (bounded cycles, Phase 2 per-workspace timeouts) must stay well
94
+ * below this window; the dry-run of Phase 1 finishes in seconds.
95
+ */
96
+ export const SERVICE_RUN_LOCK_STALE_MS = 30 * 60 * 1000;
97
+ /**
98
+ * Busy policy is split per role (SPEC §8.2 immediate `already_running`):
99
+ * ACQUIRE waits ZERO milliseconds — a second coordinator must never queue
100
+ * behind a finishing run and then execute a second dry-run. RELEASE gets
101
+ * its own bounded wait ({@link RELEASE_BUSY_TIMEOUT_MS} ×
102
+ * {@link RELEASE_MAX_ATTEMPTS}) because a release racing a concurrent
103
+ * arbiter should still complete when the gate frees momentarily.
104
+ */
105
+ const ACQUIRE_BUSY_TIMEOUT_MS = 0;
106
+ const RELEASE_BUSY_TIMEOUT_MS = 1500;
107
+ const RELEASE_MAX_ATTEMPTS = 2;
108
+ /** The one lock file per install: `<pdHome>/service/service-run.lock`. */
109
+ export function serviceRunLockPath(pdHome) {
110
+ return path.join(pdHome, 'service', 'service-run.lock');
111
+ }
112
+ /**
113
+ * The dedicated arbitration gate for every acquire/takeover/release of the
114
+ * lock at `lockPath`. A stable path (never per-attempt): all contenders
115
+ * must serialize on the SAME database.
116
+ */
117
+ function serviceRunGatePath(lockPath) {
118
+ return path.join(path.dirname(lockPath), 'service-run-gate.db');
119
+ }
120
+ /** A bounded, control-char-free echo of a lock body for diagnostics (rc-8). */
121
+ function bodyEcho(body) {
122
+ const clean = body.replace(/[^\x20-\x7E]+/g, ' ').trim();
123
+ return clean.length > 60 ? `${clean.slice(0, 59)}…` : clean;
124
+ }
125
+ export function readLockBodyStatus(lockPath) {
126
+ try {
127
+ return { kind: 'readable', body: fs.readFileSync(lockPath, 'utf8') };
128
+ }
129
+ catch (error) {
130
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
131
+ ? String(Reflect.get(error, 'code'))
132
+ : '';
133
+ if (code === 'ENOENT' || code === 'ENOTDIR')
134
+ return { kind: 'absent' };
135
+ return {
136
+ kind: 'unreadable',
137
+ detail: code || (error instanceof Error ? error.message : String(error)),
138
+ };
139
+ }
140
+ }
141
+ function readLockBody(lockPath) {
142
+ const read = readLockBodyStatus(lockPath);
143
+ return read.kind === 'readable' ? read.body : undefined;
144
+ }
145
+ /** Bounded echo of the current holder body for the `held` verdict. */
146
+ function heldVerdict(lockPath) {
147
+ const body = readLockBody(lockPath);
148
+ return { ok: false, kind: 'held', holderBodyHash: body === undefined ? 'unreadable' : bodyEcho(body) };
149
+ }
150
+ function lockBody(token) {
151
+ return `${process.pid} ${token} ${new Date().toISOString()}`;
152
+ }
153
+ /**
154
+ * Parse the recorded creation timestamp out of a lock/sidecar body
155
+ * (`<pid> <token> <createdAtISO>`); undefined when unverifiable.
156
+ */
157
+ function holderCreatedAtOf(body) {
158
+ const parts = body.trim().split(/\s+/);
159
+ const stamp = parts.length >= 3 ? parts[2] : undefined;
160
+ if (stamp === undefined)
161
+ return undefined;
162
+ const parsed = Date.parse(stamp);
163
+ return Number.isNaN(parsed) ? undefined : parsed;
164
+ }
165
+ /**
166
+ * Parse the holder PID out of a lock body (`<pid> <token> <createdAtISO>`).
167
+ * Returns undefined when the body carries no verifiable holder identity —
168
+ * a body we cannot attribute is treated as corrupt (fail-closed), never as
169
+ * takeover evidence.
170
+ */
171
+ function holderPidOf(body) {
172
+ const firstSpace = body.indexOf(' ');
173
+ const pidText = firstSpace === -1 ? body : body.slice(0, firstSpace);
174
+ if (!/^\d+$/.test(pidText))
175
+ return undefined;
176
+ const pid = Number(pidText);
177
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
178
+ }
179
+ /**
180
+ * The default liveness probe: `process.kill(pid, 0)`. ESRCH is the only
181
+ * "demonstrably dead" answer; EPERM means the process exists but cannot be
182
+ * signaled (still alive); any other outcome is 'unknown' (fail-closed).
183
+ */
184
+ function defaultProcessAlive(pid) {
185
+ try {
186
+ process.kill(pid, 0);
187
+ return 'alive';
188
+ }
189
+ catch (error) {
190
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
191
+ ? String(Reflect.get(error, 'code'))
192
+ : '';
193
+ if (code === 'ESRCH')
194
+ return 'dead';
195
+ if (code === 'EPERM')
196
+ return 'alive';
197
+ return 'unknown';
198
+ }
199
+ }
200
+ /**
201
+ * Atomic claim attempt: exactly one of N simultaneous contenders can create
202
+ * the file. EEXIST is contention; any other failure is `unwritable` (never
203
+ * misreported as contention). A body write failure after a successful
204
+ * create removes the fresh file — safe: it is younger than the stale
205
+ * window, so no other process can have taken it over yet.
206
+ */
207
+ function tryCreate(lockPath, body) {
208
+ let fd;
209
+ try {
210
+ fd = fs.openSync(lockPath, 'wx');
211
+ fs.writeSync(fd, body);
212
+ fs.closeSync(fd);
213
+ fd = undefined;
214
+ return 'created';
215
+ }
216
+ catch (error) {
217
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
218
+ ? String(Reflect.get(error, 'code'))
219
+ : undefined;
220
+ if (fd !== undefined) {
221
+ try {
222
+ fs.closeSync(fd);
223
+ }
224
+ catch {
225
+ // already closed
226
+ }
227
+ try {
228
+ fs.rmSync(lockPath, { force: true });
229
+ }
230
+ catch {
231
+ // orphan with our token; stale sweep cleans it later
232
+ }
233
+ }
234
+ if (code === 'EEXIST')
235
+ return 'busy';
236
+ const message = error instanceof Error ? error.message : String(error);
237
+ return { error: `${code ?? ''} ${message}`.trim() };
238
+ }
239
+ }
240
+ /**
241
+ * Legacy-protocol guard: the retired `.mtx` file mutex was held by a LIVE
242
+ * process for its whole critical section — a live `.mtx` therefore means an
243
+ * old-version coordinator may be mid-takeover right now, and proceeding
244
+ * would ignore arbitration the old protocol still honors (mixed-version
245
+ * double-run). Fail closed as 'occupied' when the recorded PID is alive OR
246
+ * unverifiable; only a demonstrably-dead owner lets us proceed. An
247
+ * unreadable `.mtx` is occupied-by-default: file age or absence of a
248
+ * parseable body never proves the old protocol's mutex is free.
249
+ */
250
+ function legacyMutexOccupied(lockPath, processAlive) {
251
+ let raw;
252
+ try {
253
+ raw = fs.readFileSync(`${lockPath}.mtx`, 'utf8');
254
+ }
255
+ catch (error) {
256
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
257
+ ? String(Reflect.get(error, 'code'))
258
+ : '';
259
+ // ENOENT/ENOTDIR: no legacy mutex exists — proceed.
260
+ if (code === 'ENOENT' || code === 'ENOTDIR')
261
+ return false;
262
+ return true; // exists but unreadable → unverifiable → fail closed
263
+ }
264
+ const pid = holderPidOf(raw);
265
+ if (pid === undefined)
266
+ return true; // corrupt ownership → cannot verify → fail closed
267
+ try {
268
+ return processAlive(pid) !== 'dead';
269
+ }
270
+ catch {
271
+ return true;
272
+ }
273
+ }
274
+ /**
275
+ * PID-verified sweep of legacy sidecar orphans (§六): `.mtx` (pre-
276
+ * arbitration file mutex), `.take-*` and `.rel-*` (the retired rename-aside
277
+ * protocol). The current protocol creates NONE of these — but they may
278
+ * still be held by an ACTIVE old-version process, so file age alone never
279
+ * justifies deletion: a sidecar is removed only when it is BOTH past the
280
+ * stale window AND its recorded holder PID is demonstrably dead. Alive,
281
+ * unknown, unparseable or unreadable ownership keeps the file (fail-closed;
282
+ * manual recovery remains the path for those). The arbitration gate
283
+ * database (`service-run-gate.db` plus `-journal`/`-wal`/`-shm`) never
284
+ * matches these patterns and is never touched.
285
+ */
286
+ function sweepOrphanSidecars(lockPath, staleMs, processAlive) {
287
+ const dir = path.dirname(lockPath);
288
+ const base = path.basename(lockPath);
289
+ let entries;
290
+ try {
291
+ entries = fs.readdirSync(dir);
292
+ }
293
+ catch {
294
+ return;
295
+ }
296
+ for (const entry of entries) {
297
+ if (entry !== `${base}.mtx` && !entry.startsWith(`${base}.take-`) && !entry.startsWith(`${base}.rel-`))
298
+ continue;
299
+ const sidecar = path.join(dir, entry);
300
+ try {
301
+ // Ownership check before any deletion: a dead recorded owner makes
302
+ // the orphan provably unheld; anything else is kept, never assumed.
303
+ // Staleness comes from the body's own createdAt, not an mtime stat —
304
+ // a stat-then-delete pair is a real check-then-act race (CodeQL
305
+ // js/file-system-race) and mtime never proved ownership anyway.
306
+ let sidecarBody;
307
+ try {
308
+ sidecarBody = fs.readFileSync(sidecar, 'utf8');
309
+ }
310
+ catch {
311
+ continue;
312
+ }
313
+ const recordedAt = holderCreatedAtOf(sidecarBody);
314
+ if (recordedAt === undefined || recordedAt >= Date.now() - staleMs)
315
+ continue;
316
+ const pid = holderPidOf(sidecarBody);
317
+ if (pid === undefined)
318
+ continue;
319
+ let liveness;
320
+ try {
321
+ liveness = processAlive(pid);
322
+ }
323
+ catch {
324
+ liveness = 'unknown';
325
+ }
326
+ if (liveness !== 'dead')
327
+ continue;
328
+ // Verify-then-delete bound to the verified inode (CodeQL
329
+ // js/file-system-race): rename is atomic — it moves the exact file
330
+ // whose body we just verified aside, so a writer recreating the
331
+ // original name afterwards creates a NEW file we never touch. The
332
+ // quarantined body is re-read and must match byte-for-byte before
333
+ // deletion; any mismatch restores it.
334
+ const quarantined = `${sidecar}.pd-quarantine-${randomUUID()}`;
335
+ try {
336
+ fs.renameSync(sidecar, quarantined);
337
+ }
338
+ catch {
339
+ continue; // vanished or immovable — keep it, never assume
340
+ }
341
+ let verifiedBody;
342
+ try {
343
+ verifiedBody = fs.readFileSync(quarantined, 'utf8');
344
+ }
345
+ catch {
346
+ verifiedBody = undefined;
347
+ }
348
+ if (verifiedBody !== sidecarBody) {
349
+ try {
350
+ fs.renameSync(quarantined, sidecar);
351
+ }
352
+ catch {
353
+ // leave it quarantined; manual recovery keeps the bytes
354
+ }
355
+ continue;
356
+ }
357
+ try {
358
+ fs.rmSync(quarantined, { force: true });
359
+ }
360
+ catch {
361
+ // best effort; a failed sweep never blocks locking
362
+ }
363
+ }
364
+ catch {
365
+ // best effort; a failed sweep never blocks locking
366
+ }
367
+ }
368
+ }
369
+ function evaluateLock(lockPath, staleMs, processAlive) {
370
+ let stats;
371
+ try {
372
+ stats = fs.statSync(lockPath);
373
+ }
374
+ catch {
375
+ return { kind: 'absent' };
376
+ }
377
+ const stale = stats.mtimeMs < Date.now() - staleMs;
378
+ const read = readLockBodyStatus(lockPath);
379
+ if (read.kind === 'absent')
380
+ return { kind: 'absent' }; // vanished under us
381
+ if (read.kind === 'unreadable')
382
+ return stale ? { kind: 'stale-unreadable' } : { kind: 'fresh' };
383
+ const { body } = read;
384
+ const holderPid = holderPidOf(body);
385
+ if (holderPid === undefined)
386
+ return stale ? { kind: 'stale-anonymous', body } : { kind: 'fresh' };
387
+ let liveness;
388
+ try {
389
+ liveness = processAlive(holderPid);
390
+ }
391
+ catch {
392
+ liveness = 'unknown';
393
+ }
394
+ // A PROVABLY-dead recorded holder is recoverable immediately — the stale
395
+ // window bounds only UNVERIFIABLE ownership, not verified death (§P0.8).
396
+ if (liveness === 'dead')
397
+ return { kind: 'dead', body };
398
+ return stale ? { kind: 'stale-alive' } : { kind: 'fresh' };
399
+ }
400
+ /** SQLITE_BUSY (and its extended variants) means a live contender holds the gate. */
401
+ function isBusyError(error) {
402
+ return (typeof error === 'object' &&
403
+ error !== null &&
404
+ Object.hasOwn(error, 'code') &&
405
+ String(Reflect.get(error, 'code')).startsWith('SQLITE_BUSY'));
406
+ }
407
+ function errorDetail(error) {
408
+ return error instanceof Error ? error.message : String(error);
409
+ }
410
+ /**
411
+ * Run `body` while holding the cross-process arbitration gate: open the
412
+ * gate database, `BEGIN IMMEDIATE`, run the body's serialized decisions,
413
+ * end the transaction. Any failure is fail-closed:
414
+ * - SQLITE_BUSY anywhere → 'busy' (a live arbiter exists);
415
+ * - gate unopenable / transaction error → 'unwritable' (unknown state —
416
+ * never decide outside arbitration).
417
+ * A process dying mid-transaction releases the gate through the OS (POSIX
418
+ * fcntl / Windows LockFileEx), so recovery needs no file heuristics at all.
419
+ *
420
+ * If ending the transaction fails AFTER the body created our lock file,
421
+ * compensation removes that file while it still carries our body — a
422
+ * same-path-exclusive compare-and-delete, never a blind unlink (§P0.6).
423
+ */
424
+ function withGateArbitration(lockPath, opts, body) {
425
+ let db;
426
+ try {
427
+ db = new Database(serviceRunGatePath(lockPath));
428
+ db.pragma(`busy_timeout = ${opts.busyTimeoutMs}`);
429
+ }
430
+ catch (error) {
431
+ return { ok: false, kind: 'unwritable', detail: `arbitration gate unavailable: ${errorDetail(error)}` };
432
+ }
433
+ try {
434
+ db.exec('BEGIN IMMEDIATE');
435
+ }
436
+ catch (error) {
437
+ try {
438
+ db.close();
439
+ }
440
+ catch {
441
+ // already closing
442
+ }
443
+ return {
444
+ ok: false,
445
+ kind: isBusyError(error) ? 'busy' : 'unwritable',
446
+ detail: `arbitration gate begin failed: ${errorDetail(error)}`,
447
+ };
448
+ }
449
+ try {
450
+ const value = body();
451
+ opts.insideTxn?.();
452
+ if (opts.injectEndFailure === true) {
453
+ const injected = new Error('injected gate transaction-end failure');
454
+ Reflect.set(injected, 'code', 'SQLITE_IOERR');
455
+ throw injected;
456
+ }
457
+ // No persistent gate data: ROLLBACK ends the transaction — a failed
458
+ // COMMIT can never orphan the filesystem writes made inside `body`.
459
+ db.exec('ROLLBACK');
460
+ return { ok: true, value };
461
+ }
462
+ catch (error) {
463
+ try {
464
+ db.exec('ROLLBACK');
465
+ }
466
+ catch {
467
+ // rollback best-effort; process death releases the gate anyway
468
+ }
469
+ if (opts.createdBody !== undefined) {
470
+ try {
471
+ if (readLockBody(lockPath) === opts.createdBody)
472
+ fs.unlinkSync(lockPath);
473
+ }
474
+ catch {
475
+ // Leave it — a dead-holder body recovers on PID evidence anyway.
476
+ }
477
+ }
478
+ return {
479
+ ok: false,
480
+ kind: isBusyError(error) ? 'busy' : 'unwritable',
481
+ detail: `arbitration gate transaction failed: ${errorDetail(error)}`,
482
+ };
483
+ }
484
+ finally {
485
+ try {
486
+ db.close();
487
+ }
488
+ catch {
489
+ // already closed
490
+ }
491
+ }
492
+ }
493
+ /** True when the lock file still carries OUR body (mid-run ownership re-check). */
494
+ export function holdsServiceRunLock(handle) {
495
+ return readLockBody(handle.lockPath) === handle.body;
496
+ }
497
+ /**
498
+ * Acquire the install-level single-instance run lock. Every decision —
499
+ * evaluate, stale takeover, create — runs inside the arbitration gate
500
+ * (§P1-4 round 4), immediate verdicts, no wait loop (`already_running`
501
+ * semantics, §8.2). A stale takeover additionally requires the recorded
502
+ * holder PID to be demonstrably DEAD; a live, unknown or unverifiable
503
+ * holder is NEVER taken over, and the verify→delete→create sequence is
504
+ * serialized by the same transaction that a second contender's BEGIN
505
+ * cannot enter.
506
+ */
507
+ export function acquireServiceRunLock(pdHome, options) {
508
+ const lockPath = serviceRunLockPath(pdHome);
509
+ const staleMs = options?.staleMs ?? SERVICE_RUN_LOCK_STALE_MS;
510
+ const processAlive = options?.probes?.processAlive ?? defaultProcessAlive;
511
+ const takeoverSync = options?.probes?.takeoverSync;
512
+ const token = randomUUID().replace(/-/g, '').slice(0, 16);
513
+ const body = lockBody(token);
514
+ try {
515
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
516
+ }
517
+ catch (error) {
518
+ const message = error instanceof Error ? error.message : String(error);
519
+ return { ok: false, kind: 'unwritable', detail: message };
520
+ }
521
+ const gated = withGateArbitration(lockPath, {
522
+ busyTimeoutMs: ACQUIRE_BUSY_TIMEOUT_MS,
523
+ createdBody: body,
524
+ injectEndFailure: options?.probes?.gateEndFailure === true,
525
+ }, () => {
526
+ // Mixed-version protection (§六): an old-protocol coordinator may be
527
+ // mid-takeover holding `.mtx`. A live/unverifiable legacy mutex means
528
+ // fail-closed held — never run a second instance beside it.
529
+ if (legacyMutexOccupied(lockPath, processAlive))
530
+ return heldVerdict(lockPath);
531
+ const evaluate = () => evaluateLock(lockPath, staleMs, processAlive);
532
+ const createOwned = (staleTakenOver) => {
533
+ const created = tryCreate(lockPath, body);
534
+ if (created === 'created') {
535
+ sweepOrphanSidecars(lockPath, staleMs, processAlive);
536
+ return { ok: true, handle: { lockPath, token, body }, staleTakenOver };
537
+ }
538
+ if (typeof created === 'object')
539
+ return { ok: false, kind: 'unwritable', detail: created.error };
540
+ return heldVerdict(lockPath);
541
+ };
542
+ const mapEvaluation = (evaluation) => {
543
+ switch (evaluation.kind) {
544
+ case 'absent':
545
+ return createOwned(false);
546
+ case 'fresh':
547
+ case 'stale-alive':
548
+ return heldVerdict(lockPath);
549
+ case 'stale-unreadable':
550
+ // Beyond the stale window yet unreadable: identity unverifiable —
551
+ // fail-closed (human decision), never a silent takeover.
552
+ return { ok: false, kind: 'corrupt', detail: 'lock age is beyond the stale window but its body is unreadable' };
553
+ case 'stale-anonymous':
554
+ // The stale body names no verifiable holder — cannot prove the
555
+ // old holder died, so takeover is refused fail-closed (P1-4).
556
+ return { ok: false, kind: 'corrupt', detail: `lock body carries no verifiable holder identity: ${bodyEcho(evaluation.body)}` };
557
+ case 'dead':
558
+ return 'takeover';
559
+ }
560
+ };
561
+ const first = mapEvaluation(evaluate());
562
+ if (first !== 'takeover')
563
+ return first;
564
+ // ── Arbitrated takeover: re-verify under the SAME transaction. The
565
+ // gate serializes us against every other contender, so the lock we
566
+ // verified is the lock we are about to remove — no second breaker can
567
+ // interleave a fresh create between our check and our unlink.
568
+ takeoverSync?.('mutex-acquired');
569
+ const inner = evaluate();
570
+ if (inner.kind !== 'dead') {
571
+ // Non-cooperating writers aside, the only reachable states here are
572
+ // 'dead' or 'absent' (a cooperating process cannot change the
573
+ // file under our transaction). Map defensively anyway.
574
+ if (inner.kind === 'absent')
575
+ return createOwned(true);
576
+ const mapped = mapEvaluation(inner);
577
+ if (mapped !== 'takeover')
578
+ return mapped;
579
+ }
580
+ takeoverSync?.('stale-verified');
581
+ // The lock still carries a provably-dead stale body under arbitration —
582
+ // deleting it cannot displace a live holder.
583
+ try {
584
+ fs.unlinkSync(lockPath);
585
+ }
586
+ catch (error) {
587
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
588
+ ? String(Reflect.get(error, 'code'))
589
+ : '';
590
+ if (code !== 'ENOENT') {
591
+ return { ok: false, kind: 'unwritable', detail: `could not remove stale lock: ${code}` };
592
+ }
593
+ // ENOENT: a non-cooperating writer already removed it; fall through
594
+ // to the 'wx' create, which still decides exactly once.
595
+ }
596
+ takeoverSync?.('lock-removed');
597
+ return createOwned(true);
598
+ });
599
+ if (!gated.ok) {
600
+ return gated.kind === 'busy'
601
+ ? heldVerdict(lockPath)
602
+ : { ok: false, kind: 'unwritable', detail: gated.detail };
603
+ }
604
+ return gated.value;
605
+ }
606
+ /**
607
+ * Ownership-checked release under the SAME arbitration gate: verify the
608
+ * lock body is OURS and unlink it inside one transaction — a true
609
+ * compare-and-delete, so the file a foreign holder just created can never
610
+ * be removed by our late release (P1-4). The release gets its own bounded
611
+ * retry (`RELEASE_BUSY_TIMEOUT_MS` × `RELEASE_MAX_ATTEMPTS`) independent of
612
+ * acquire's zero-wait policy, but NEVER bypasses the gate to unlink: a gate
613
+ * failure leaves the lock in place and reports it — the leftover carries
614
+ * our own PID, which the next contender recovers on death evidence.
615
+ */
616
+ export function releaseServiceRunLock(handle, options) {
617
+ for (let attempt = 0; attempt < RELEASE_MAX_ATTEMPTS; attempt += 1) {
618
+ let verdict = 'released';
619
+ const gated = withGateArbitration(handle.lockPath, {
620
+ busyTimeoutMs: RELEASE_BUSY_TIMEOUT_MS,
621
+ injectEndFailure: options?.injectEndFailure === true,
622
+ ...(options?.insideTxn !== undefined ? { insideTxn: options.insideTxn } : {}),
623
+ }, () => {
624
+ const read = (options?.readBody ?? readLockBodyStatus)(handle.lockPath);
625
+ if (read.kind === 'unreadable') {
626
+ // EACCES/EPERM/EIO/EISDIR and every other real read failure is a
627
+ // genuine release failure — NEVER `not_owned`, NEVER an unlink
628
+ // outside verification, and the lock file is left exactly as it
629
+ // is for human recovery or a later evidence-based takeover.
630
+ verdict = 'failed_unwritable';
631
+ return;
632
+ }
633
+ if (read.kind === 'absent' || read.body !== handle.body) {
634
+ verdict = 'not_owned'; // gone or foreign — never displace it
635
+ return;
636
+ }
637
+ try {
638
+ fs.unlinkSync(handle.lockPath);
639
+ }
640
+ catch (error) {
641
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
642
+ ? String(Reflect.get(error, 'code'))
643
+ : '';
644
+ if (code === 'ENOENT') {
645
+ verdict = 'not_owned'; // already gone — nothing left to release
646
+ return;
647
+ }
648
+ throw error; // real unlink failure → transaction fails → unwritable
649
+ }
650
+ });
651
+ if (gated.ok)
652
+ return verdict;
653
+ if (gated.kind === 'unwritable')
654
+ return 'failed_unwritable';
655
+ // 'busy': bounded retry — the concurrent arbiter usually frees shortly.
656
+ }
657
+ return 'failed_busy';
658
+ }
659
+ //# sourceMappingURL=service-run-lock.js.map