@principles/pd-cli 2.9.1 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (187) hide show
  1. package/dist/commands/candidate.d.ts.map +1 -1
  2. package/dist/commands/candidate.js +16 -5
  3. package/dist/commands/candidate.js.map +1 -1
  4. package/dist/commands/codex-setup.d.ts.map +1 -1
  5. package/dist/commands/codex-setup.js +17 -1
  6. package/dist/commands/codex-setup.js.map +1 -1
  7. package/dist/commands/codex-worker.d.ts.map +1 -1
  8. package/dist/commands/codex-worker.js +8 -4
  9. package/dist/commands/codex-worker.js.map +1 -1
  10. package/dist/commands/consent-sweep-revoked.d.ts +20 -0
  11. package/dist/commands/consent-sweep-revoked.d.ts.map +1 -0
  12. package/dist/commands/consent-sweep-revoked.js +85 -0
  13. package/dist/commands/consent-sweep-revoked.js.map +1 -0
  14. package/dist/commands/context.d.ts.map +1 -1
  15. package/dist/commands/context.js +9 -1
  16. package/dist/commands/context.js.map +1 -1
  17. package/dist/commands/diagnose.d.ts.map +1 -1
  18. package/dist/commands/diagnose.js +12 -6
  19. package/dist/commands/diagnose.js.map +1 -1
  20. package/dist/commands/openclaw-worker.d.ts +11 -0
  21. package/dist/commands/openclaw-worker.d.ts.map +1 -0
  22. package/dist/commands/openclaw-worker.js +199 -0
  23. package/dist/commands/openclaw-worker.js.map +1 -0
  24. package/dist/commands/pain-explicit.d.ts.map +1 -1
  25. package/dist/commands/pain-explicit.js +1 -0
  26. package/dist/commands/pain-explicit.js.map +1 -1
  27. package/dist/commands/pain-recall.d.ts +2 -2
  28. package/dist/commands/pain-recall.d.ts.map +1 -1
  29. package/dist/commands/pain-recall.js +7 -1
  30. package/dist/commands/pain-recall.js.map +1 -1
  31. package/dist/commands/pain-record.d.ts.map +1 -1
  32. package/dist/commands/pain-record.js +4 -1
  33. package/dist/commands/pain-record.js.map +1 -1
  34. package/dist/commands/pain-retry.d.ts.map +1 -1
  35. package/dist/commands/pain-retry.js +30 -6
  36. package/dist/commands/pain-retry.js.map +1 -1
  37. package/dist/commands/runtime-internalization-enqueue-successors.d.ts.map +1 -1
  38. package/dist/commands/runtime-internalization-enqueue-successors.js +2 -1
  39. package/dist/commands/runtime-internalization-enqueue-successors.js.map +1 -1
  40. package/dist/commands/runtime-internalization-run-once.d.ts +1 -0
  41. package/dist/commands/runtime-internalization-run-once.d.ts.map +1 -1
  42. package/dist/commands/runtime-internalization-run-once.js +32 -8
  43. package/dist/commands/runtime-internalization-run-once.js.map +1 -1
  44. package/dist/commands/runtime-internalization-wake-once.d.ts.map +1 -1
  45. package/dist/commands/runtime-internalization-wake-once.js +2 -1
  46. package/dist/commands/runtime-internalization-wake-once.js.map +1 -1
  47. package/dist/commands/service-handover.d.ts +12 -0
  48. package/dist/commands/service-handover.d.ts.map +1 -0
  49. package/dist/commands/service-handover.js +117 -0
  50. package/dist/commands/service-handover.js.map +1 -0
  51. package/dist/commands/service-lifecycle.d.ts +31 -0
  52. package/dist/commands/service-lifecycle.d.ts.map +1 -0
  53. package/dist/commands/service-lifecycle.js +207 -0
  54. package/dist/commands/service-lifecycle.js.map +1 -0
  55. package/dist/commands/service-run-once.d.ts +102 -0
  56. package/dist/commands/service-run-once.d.ts.map +1 -0
  57. package/dist/commands/service-run-once.js +558 -0
  58. package/dist/commands/service-run-once.js.map +1 -0
  59. package/dist/commands/workbuddy-setup.d.ts.map +1 -1
  60. package/dist/commands/workbuddy-setup.js +22 -2
  61. package/dist/commands/workbuddy-setup.js.map +1 -1
  62. package/dist/program.d.ts.map +1 -1
  63. package/dist/program.js +180 -1
  64. package/dist/program.js.map +1 -1
  65. package/dist/services/admission-write-gate.d.ts +3 -1
  66. package/dist/services/admission-write-gate.d.ts.map +1 -1
  67. package/dist/services/admission-write-gate.js +1 -0
  68. package/dist/services/admission-write-gate.js.map +1 -1
  69. package/dist/services/pain-flood-simulation-runner.d.ts.map +1 -1
  70. package/dist/services/pain-flood-simulation-runner.js +4 -0
  71. package/dist/services/pain-flood-simulation-runner.js.map +1 -1
  72. package/dist/services/service-host/coordinator-common.d.ts +49 -0
  73. package/dist/services/service-host/coordinator-common.d.ts.map +1 -0
  74. package/dist/services/service-host/coordinator-common.js +158 -0
  75. package/dist/services/service-host/coordinator-common.js.map +1 -0
  76. package/dist/services/service-host/handover-claims.d.ts +14 -0
  77. package/dist/services/service-host/handover-claims.d.ts.map +1 -0
  78. package/dist/services/service-host/handover-claims.js +50 -0
  79. package/dist/services/service-host/handover-claims.js.map +1 -0
  80. package/dist/services/service-host/index.d.ts +31 -0
  81. package/dist/services/service-host/index.d.ts.map +1 -0
  82. package/dist/services/service-host/index.js +33 -0
  83. package/dist/services/service-host/index.js.map +1 -0
  84. package/dist/services/service-host/install-identity.d.ts +99 -0
  85. package/dist/services/service-host/install-identity.d.ts.map +1 -0
  86. package/dist/services/service-host/install-identity.js +176 -0
  87. package/dist/services/service-host/install-identity.js.map +1 -0
  88. package/dist/services/service-host/locking/service-run-lock.d.ts +255 -0
  89. package/dist/services/service-host/locking/service-run-lock.d.ts.map +1 -0
  90. package/dist/services/service-host/locking/service-run-lock.js +739 -0
  91. package/dist/services/service-host/locking/service-run-lock.js.map +1 -0
  92. package/dist/services/service-host/managed-run.d.ts +75 -0
  93. package/dist/services/service-host/managed-run.d.ts.map +1 -0
  94. package/dist/services/service-host/managed-run.js +550 -0
  95. package/dist/services/service-host/managed-run.js.map +1 -0
  96. package/dist/services/service-host/owner-projection.d.ts +47 -0
  97. package/dist/services/service-host/owner-projection.d.ts.map +1 -0
  98. package/dist/services/service-host/owner-projection.js +121 -0
  99. package/dist/services/service-host/owner-projection.js.map +1 -0
  100. package/dist/services/service-host/progress-evidence.d.ts +38 -0
  101. package/dist/services/service-host/progress-evidence.d.ts.map +1 -0
  102. package/dist/services/service-host/progress-evidence.js +155 -0
  103. package/dist/services/service-host/progress-evidence.js.map +1 -0
  104. package/dist/services/service-host/run-once.d.ts +96 -0
  105. package/dist/services/service-host/run-once.d.ts.map +1 -0
  106. package/dist/services/service-host/run-once.js +308 -0
  107. package/dist/services/service-host/run-once.js.map +1 -0
  108. package/dist/services/service-host/scheduler/contract.d.ts +184 -0
  109. package/dist/services/service-host/scheduler/contract.d.ts.map +1 -0
  110. package/dist/services/service-host/scheduler/contract.js +86 -0
  111. package/dist/services/service-host/scheduler/contract.js.map +1 -0
  112. package/dist/services/service-host/scheduler/index.d.ts +76 -0
  113. package/dist/services/service-host/scheduler/index.d.ts.map +1 -0
  114. package/dist/services/service-host/scheduler/index.js +128 -0
  115. package/dist/services/service-host/scheduler/index.js.map +1 -0
  116. package/dist/services/service-host/scheduler/linux.d.ts +27 -0
  117. package/dist/services/service-host/scheduler/linux.d.ts.map +1 -0
  118. package/dist/services/service-host/scheduler/linux.js +1010 -0
  119. package/dist/services/service-host/scheduler/linux.js.map +1 -0
  120. package/dist/services/service-host/scheduler/macos.d.ts +13 -0
  121. package/dist/services/service-host/scheduler/macos.d.ts.map +1 -0
  122. package/dist/services/service-host/scheduler/macos.js +819 -0
  123. package/dist/services/service-host/scheduler/macos.js.map +1 -0
  124. package/dist/services/service-host/scheduler/runtime-io.d.ts +13 -0
  125. package/dist/services/service-host/scheduler/runtime-io.d.ts.map +1 -0
  126. package/dist/services/service-host/scheduler/runtime-io.js +141 -0
  127. package/dist/services/service-host/scheduler/runtime-io.js.map +1 -0
  128. package/dist/services/service-host/scheduler/service-status.d.ts +99 -0
  129. package/dist/services/service-host/scheduler/service-status.d.ts.map +1 -0
  130. package/dist/services/service-host/scheduler/service-status.js +202 -0
  131. package/dist/services/service-host/scheduler/service-status.js.map +1 -0
  132. package/dist/services/service-host/scheduler/windows.d.ts +40 -0
  133. package/dist/services/service-host/scheduler/windows.d.ts.map +1 -0
  134. package/dist/services/service-host/scheduler/windows.js +688 -0
  135. package/dist/services/service-host/scheduler/windows.js.map +1 -0
  136. package/dist/services/service-host/shadow-progress-store.d.ts +43 -0
  137. package/dist/services/service-host/shadow-progress-store.d.ts.map +1 -0
  138. package/dist/services/service-host/shadow-progress-store.js +156 -0
  139. package/dist/services/service-host/shadow-progress-store.js.map +1 -0
  140. package/dist/services/service-host/shadow-run.d.ts +87 -0
  141. package/dist/services/service-host/shadow-run.d.ts.map +1 -0
  142. package/dist/services/service-host/shadow-run.js +549 -0
  143. package/dist/services/service-host/shadow-run.js.map +1 -0
  144. package/dist/services/service-host/status/service-run-status.d.ts +227 -0
  145. package/dist/services/service-host/status/service-run-status.d.ts.map +1 -0
  146. package/dist/services/service-host/status/service-run-status.js +187 -0
  147. package/dist/services/service-host/status/service-run-status.js.map +1 -0
  148. package/dist/services/service-host/worker-adapter-codex.d.ts +2 -0
  149. package/dist/services/service-host/worker-adapter-codex.d.ts.map +1 -0
  150. package/dist/services/service-host/worker-adapter-codex.js +76 -0
  151. package/dist/services/service-host/worker-adapter-codex.js.map +1 -0
  152. package/dist/services/service-host/worker-adapter-openclaw.d.ts +2 -0
  153. package/dist/services/service-host/worker-adapter-openclaw.d.ts.map +1 -0
  154. package/dist/services/service-host/worker-adapter-openclaw.js +49 -0
  155. package/dist/services/service-host/worker-adapter-openclaw.js.map +1 -0
  156. package/dist/services/service-host/worker-adapter-workbuddy.d.ts +2 -0
  157. package/dist/services/service-host/worker-adapter-workbuddy.d.ts.map +1 -0
  158. package/dist/services/service-host/worker-adapter-workbuddy.js +36 -0
  159. package/dist/services/service-host/worker-adapter-workbuddy.js.map +1 -0
  160. package/dist/services/service-host/worker-adapter.d.ts +187 -0
  161. package/dist/services/service-host/worker-adapter.d.ts.map +1 -0
  162. package/dist/services/service-host/worker-adapter.js +609 -0
  163. package/dist/services/service-host/worker-adapter.js.map +1 -0
  164. package/dist/services/service-host/worker-env.d.ts +84 -0
  165. package/dist/services/service-host/worker-env.d.ts.map +1 -0
  166. package/dist/services/service-host/worker-env.js +195 -0
  167. package/dist/services/service-host/worker-env.js.map +1 -0
  168. package/dist/services/service-host/worker-process.d.ts +75 -0
  169. package/dist/services/service-host/worker-process.d.ts.map +1 -0
  170. package/dist/services/service-host/worker-process.js +225 -0
  171. package/dist/services/service-host/worker-process.js.map +1 -0
  172. package/dist/services/service-host/workspace-discovery.d.ts +71 -0
  173. package/dist/services/service-host/workspace-discovery.d.ts.map +1 -0
  174. package/dist/services/service-host/workspace-discovery.js +288 -0
  175. package/dist/services/service-host/workspace-discovery.js.map +1 -0
  176. package/dist/services/service-host/workspace-dispatch.d.ts +61 -0
  177. package/dist/services/service-host/workspace-dispatch.d.ts.map +1 -0
  178. package/dist/services/service-host/workspace-dispatch.js +105 -0
  179. package/dist/services/service-host/workspace-dispatch.js.map +1 -0
  180. package/dist/services/service-host/workspace-handover.d.ts +190 -0
  181. package/dist/services/service-host/workspace-handover.d.ts.map +1 -0
  182. package/dist/services/service-host/workspace-handover.js +1393 -0
  183. package/dist/services/service-host/workspace-handover.js.map +1 -0
  184. package/dist/services/synthetic-baseline-runner.d.ts.map +1 -1
  185. package/dist/services/synthetic-baseline-runner.js +4 -0
  186. package/dist/services/synthetic-baseline-runner.js.map +1 -1
  187. package/package.json +10 -9
@@ -0,0 +1,739 @@
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 { createHash, 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 per-workspace consumer mutex: `<pdHome>/service/workspace-runs/<hash>.lock`.
114
+ *
115
+ * A consuming Worker child holds this for the whole cycle, so an
116
+ * orchestrator (handover resume / rollback) can prove "an old worker is
117
+ * still running on THIS workspace" by holder-PID liveness instead of
118
+ * guessing from the coordinator's own lock. The workspace is addressed by
119
+ * its canonical real directory — the same spelling-or-alias identity rule
120
+ * the §8.4 ownership projection uses — so either path spelling reaches the
121
+ * same mutex (PRI-1282 review).
122
+ */
123
+ export function workspaceServiceRunLockPath(pdHome, workspaceDir) {
124
+ let canonical = path.resolve(workspaceDir);
125
+ try {
126
+ canonical = fs.realpathSync.native(canonical);
127
+ }
128
+ catch {
129
+ // Missing/unresolvable directory: the lexical spelling still keys ONE
130
+ // mutex — better than diverging aliases while the dir is absent.
131
+ }
132
+ const key = createHash('sha256').update(canonical).digest('hex').slice(0, 16);
133
+ return path.join(pdHome, 'service', 'workspace-runs', `${key}.lock`);
134
+ }
135
+ /**
136
+ * The dedicated arbitration gate for every acquire/takeover/release of the
137
+ * lock at `lockPath`. A stable path (never per-attempt): all contenders
138
+ * must serialize on the SAME database.
139
+ */
140
+ function serviceRunGatePath(lockPath) {
141
+ return path.join(path.dirname(lockPath), 'service-run-gate.db');
142
+ }
143
+ /** A bounded, control-char-free echo of a lock body for diagnostics (rc-8). */
144
+ function bodyEcho(body) {
145
+ const clean = body.replace(/[^\x20-\x7E]+/g, ' ').trim();
146
+ return clean.length > 60 ? `${clean.slice(0, 59)}…` : clean;
147
+ }
148
+ export function readLockBodyStatus(lockPath) {
149
+ try {
150
+ return { kind: 'readable', body: fs.readFileSync(lockPath, 'utf8') };
151
+ }
152
+ catch (error) {
153
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
154
+ ? String(Reflect.get(error, 'code'))
155
+ : '';
156
+ // ONLY ENOENT means "no lock". ENOTDIR/EACCES/EPERM/EIO/EISDIR are a
157
+ // path-structure anomaly or a degraded read — fail-closed `unreadable`,
158
+ // never `absent` (PRI-1282 review round 4).
159
+ if (code === 'ENOENT')
160
+ return { kind: 'absent' };
161
+ return {
162
+ kind: 'unreadable',
163
+ detail: code || (error instanceof Error ? error.message : String(error)),
164
+ };
165
+ }
166
+ }
167
+ function readLockBody(lockPath) {
168
+ const read = readLockBodyStatus(lockPath);
169
+ return read.kind === 'readable' ? read.body : undefined;
170
+ }
171
+ /** Bounded echo of the current holder body for the `held` verdict. */
172
+ function heldVerdict(lockPath) {
173
+ const body = readLockBody(lockPath);
174
+ return { ok: false, kind: 'held', holderBodyHash: body === undefined ? 'unreadable' : bodyEcho(body) };
175
+ }
176
+ function lockBody(token) {
177
+ return `${process.pid} ${token} ${new Date().toISOString()}`;
178
+ }
179
+ /**
180
+ * Parse the recorded creation timestamp out of a lock/sidecar body
181
+ * (`<pid> <token> <createdAtISO>`); undefined when unverifiable.
182
+ */
183
+ function holderCreatedAtOf(body) {
184
+ const parts = body.trim().split(/\s+/);
185
+ const stamp = parts.length >= 3 ? parts[2] : undefined;
186
+ if (stamp === undefined)
187
+ return undefined;
188
+ const parsed = Date.parse(stamp);
189
+ return Number.isNaN(parsed) ? undefined : parsed;
190
+ }
191
+ /**
192
+ * Parse the holder PID out of a lock body (`<pid> <token> <createdAtISO>`).
193
+ * Returns undefined when the body carries no verifiable holder identity —
194
+ * a body we cannot attribute is treated as corrupt (fail-closed), never as
195
+ * takeover evidence.
196
+ */
197
+ function holderPidOf(body) {
198
+ const firstSpace = body.indexOf(' ');
199
+ const pidText = firstSpace === -1 ? body : body.slice(0, firstSpace);
200
+ if (!/^\d+$/.test(pidText))
201
+ return undefined;
202
+ const pid = Number(pidText);
203
+ return Number.isSafeInteger(pid) && pid > 0 ? pid : undefined;
204
+ }
205
+ /**
206
+ * The default liveness probe: `process.kill(pid, 0)`. ESRCH is the only
207
+ * "demonstrably dead" answer; EPERM means the process exists but cannot be
208
+ * signaled (still alive); any other outcome is 'unknown' (fail-closed).
209
+ */
210
+ function defaultProcessAlive(pid) {
211
+ try {
212
+ process.kill(pid, 0);
213
+ return 'alive';
214
+ }
215
+ catch (error) {
216
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
217
+ ? String(Reflect.get(error, 'code'))
218
+ : '';
219
+ if (code === 'ESRCH')
220
+ return 'dead';
221
+ if (code === 'EPERM')
222
+ return 'alive';
223
+ return 'unknown';
224
+ }
225
+ }
226
+ /**
227
+ * Atomic claim attempt: exactly one of N simultaneous contenders can create
228
+ * the file. EEXIST is contention; any other failure is `unwritable` (never
229
+ * misreported as contention). A body write failure after a successful
230
+ * create removes the fresh file — safe: it is younger than the stale
231
+ * window, so no other process can have taken it over yet.
232
+ */
233
+ function tryCreate(lockPath, body) {
234
+ let fd;
235
+ try {
236
+ fd = fs.openSync(lockPath, 'wx');
237
+ fs.writeSync(fd, body);
238
+ fs.closeSync(fd);
239
+ fd = undefined;
240
+ return 'created';
241
+ }
242
+ catch (error) {
243
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
244
+ ? String(Reflect.get(error, 'code'))
245
+ : undefined;
246
+ if (fd !== undefined) {
247
+ try {
248
+ fs.closeSync(fd);
249
+ }
250
+ catch {
251
+ // already closed
252
+ }
253
+ try {
254
+ fs.rmSync(lockPath, { force: true });
255
+ }
256
+ catch {
257
+ // orphan with our token; stale sweep cleans it later
258
+ }
259
+ }
260
+ if (code === 'EEXIST')
261
+ return 'busy';
262
+ const message = error instanceof Error ? error.message : String(error);
263
+ return { error: `${code ?? ''} ${message}`.trim() };
264
+ }
265
+ }
266
+ /**
267
+ * Legacy-protocol guard: the retired `.mtx` file mutex was held by a LIVE
268
+ * process for its whole critical section — a live `.mtx` therefore means an
269
+ * old-version coordinator may be mid-takeover right now, and proceeding
270
+ * would ignore arbitration the old protocol still honors (mixed-version
271
+ * double-run). Fail closed as 'occupied' when the recorded PID is alive OR
272
+ * unverifiable; only a demonstrably-dead owner lets us proceed. An
273
+ * unreadable `.mtx` is occupied-by-default: file age or absence of a
274
+ * parseable body never proves the old protocol's mutex is free.
275
+ */
276
+ function legacyMutexOccupied(lockPath, processAlive) {
277
+ let raw;
278
+ try {
279
+ raw = fs.readFileSync(`${lockPath}.mtx`, 'utf8');
280
+ }
281
+ catch (error) {
282
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
283
+ ? String(Reflect.get(error, 'code'))
284
+ : '';
285
+ // ONLY ENOENT proves no legacy mutex. ENOTDIR/EACCES/EIO/EPERM are a
286
+ // structural/degraded-read anomaly → unverifiable → fail closed.
287
+ if (code === 'ENOENT')
288
+ return false;
289
+ return true; // exists but unreadable → unverifiable → fail closed
290
+ }
291
+ const pid = holderPidOf(raw);
292
+ if (pid === undefined)
293
+ return true; // corrupt ownership → cannot verify → fail closed
294
+ try {
295
+ return processAlive(pid) !== 'dead';
296
+ }
297
+ catch {
298
+ return true;
299
+ }
300
+ }
301
+ /**
302
+ * PID-verified sweep of legacy sidecar orphans (§六): `.mtx` (pre-
303
+ * arbitration file mutex), `.take-*` and `.rel-*` (the retired rename-aside
304
+ * protocol). The current protocol creates NONE of these — but they may
305
+ * still be held by an ACTIVE old-version process, so file age alone never
306
+ * justifies deletion: a sidecar is removed only when it is BOTH past the
307
+ * stale window AND its recorded holder PID is demonstrably dead. Alive,
308
+ * unknown, unparseable or unreadable ownership keeps the file (fail-closed;
309
+ * manual recovery remains the path for those). The arbitration gate
310
+ * database (`service-run-gate.db` plus `-journal`/`-wal`/`-shm`) never
311
+ * matches these patterns and is never touched.
312
+ */
313
+ function sweepOrphanSidecars(lockPath, staleMs, processAlive) {
314
+ const dir = path.dirname(lockPath);
315
+ const base = path.basename(lockPath);
316
+ let entries;
317
+ try {
318
+ entries = fs.readdirSync(dir);
319
+ }
320
+ catch {
321
+ return;
322
+ }
323
+ for (const entry of entries) {
324
+ if (entry !== `${base}.mtx` && !entry.startsWith(`${base}.take-`) && !entry.startsWith(`${base}.rel-`))
325
+ continue;
326
+ const sidecar = path.join(dir, entry);
327
+ try {
328
+ // Ownership check before any deletion: a dead recorded owner makes
329
+ // the orphan provably unheld; anything else is kept, never assumed.
330
+ // Staleness comes from the body's own createdAt, not an mtime stat —
331
+ // a stat-then-delete pair is a real check-then-act race (CodeQL
332
+ // js/file-system-race) and mtime never proved ownership anyway.
333
+ let sidecarBody;
334
+ try {
335
+ sidecarBody = fs.readFileSync(sidecar, 'utf8');
336
+ }
337
+ catch {
338
+ continue;
339
+ }
340
+ const recordedAt = holderCreatedAtOf(sidecarBody);
341
+ if (recordedAt === undefined || recordedAt >= Date.now() - staleMs)
342
+ continue;
343
+ const pid = holderPidOf(sidecarBody);
344
+ if (pid === undefined)
345
+ continue;
346
+ let liveness;
347
+ try {
348
+ liveness = processAlive(pid);
349
+ }
350
+ catch {
351
+ liveness = 'unknown';
352
+ }
353
+ if (liveness !== 'dead')
354
+ continue;
355
+ // Verify-then-delete bound to the verified inode (CodeQL
356
+ // js/file-system-race): rename is atomic — it moves the exact file
357
+ // whose body we just verified aside, so a writer recreating the
358
+ // original name afterwards creates a NEW file we never touch. The
359
+ // quarantined body is re-read and must match byte-for-byte before
360
+ // deletion; any mismatch restores it.
361
+ const quarantined = `${sidecar}.pd-quarantine-${randomUUID()}`;
362
+ try {
363
+ fs.renameSync(sidecar, quarantined);
364
+ }
365
+ catch {
366
+ continue; // vanished or immovable — keep it, never assume
367
+ }
368
+ let verifiedBody;
369
+ try {
370
+ verifiedBody = fs.readFileSync(quarantined, 'utf8');
371
+ }
372
+ catch {
373
+ verifiedBody = undefined;
374
+ }
375
+ if (verifiedBody !== sidecarBody) {
376
+ try {
377
+ fs.renameSync(quarantined, sidecar);
378
+ }
379
+ catch {
380
+ // leave it quarantined; manual recovery keeps the bytes
381
+ }
382
+ continue;
383
+ }
384
+ try {
385
+ fs.rmSync(quarantined, { force: true });
386
+ }
387
+ catch {
388
+ // best effort; a failed sweep never blocks locking
389
+ }
390
+ }
391
+ catch {
392
+ // best effort; a failed sweep never blocks locking
393
+ }
394
+ }
395
+ }
396
+ function evaluateLock(lockPath, ctx) {
397
+ const { staleMs, processAlive, statLock } = ctx;
398
+ let stats;
399
+ try {
400
+ stats = (statLock ?? ((p) => fs.statSync(p)))(lockPath);
401
+ }
402
+ catch (error) {
403
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
404
+ ? String(Reflect.get(error, 'code'))
405
+ : '';
406
+ // ONLY ENOENT proves absence. EACCES/EPERM/EIO/ENOTDIR are degraded
407
+ // evidence — fail-closed, never a silent 'free' (PRI-1282 review r4).
408
+ if (code === 'ENOENT')
409
+ return { kind: 'absent' };
410
+ return { kind: 'stat-error', detail: code || (error instanceof Error ? error.message : String(error)) };
411
+ }
412
+ const stale = stats.mtimeMs < Date.now() - staleMs;
413
+ const read = readLockBodyStatus(lockPath);
414
+ if (read.kind === 'absent')
415
+ return { kind: 'absent' }; // vanished under us
416
+ if (read.kind === 'unreadable')
417
+ return stale ? { kind: 'stale-unreadable' } : { kind: 'fresh' };
418
+ const { body } = read;
419
+ const holderPid = holderPidOf(body);
420
+ if (holderPid === undefined)
421
+ return stale ? { kind: 'stale-anonymous', body } : { kind: 'fresh' };
422
+ let liveness;
423
+ try {
424
+ liveness = processAlive(holderPid);
425
+ }
426
+ catch {
427
+ liveness = 'unknown';
428
+ }
429
+ // A PROVABLY-dead recorded holder is recoverable immediately — the stale
430
+ // window bounds only UNVERIFIABLE ownership, not verified death (§P0.8).
431
+ if (liveness === 'dead')
432
+ return { kind: 'dead', body };
433
+ return stale ? { kind: 'stale-alive' } : { kind: 'fresh' };
434
+ }
435
+ /** SQLITE_BUSY (and its extended variants) means a live contender holds the gate. */
436
+ function isBusyError(error) {
437
+ return (typeof error === 'object' &&
438
+ error !== null &&
439
+ Object.hasOwn(error, 'code') &&
440
+ String(Reflect.get(error, 'code')).startsWith('SQLITE_BUSY'));
441
+ }
442
+ function errorDetail(error) {
443
+ return error instanceof Error ? error.message : String(error);
444
+ }
445
+ /**
446
+ * Run `body` while holding the cross-process arbitration gate: open the
447
+ * gate database, `BEGIN IMMEDIATE`, run the body's serialized decisions,
448
+ * end the transaction. Any failure is fail-closed:
449
+ * - SQLITE_BUSY anywhere → 'busy' (a live arbiter exists);
450
+ * - gate unopenable / transaction error → 'unwritable' (unknown state —
451
+ * never decide outside arbitration).
452
+ * A process dying mid-transaction releases the gate through the OS (POSIX
453
+ * fcntl / Windows LockFileEx), so recovery needs no file heuristics at all.
454
+ *
455
+ * If ending the transaction fails AFTER the body created our lock file,
456
+ * compensation removes that file while it still carries our body — a
457
+ * same-path-exclusive compare-and-delete, never a blind unlink (§P0.6).
458
+ */
459
+ function withGateArbitration(lockPath, opts, body) {
460
+ let db;
461
+ try {
462
+ db = new Database(serviceRunGatePath(lockPath));
463
+ db.pragma(`busy_timeout = ${opts.busyTimeoutMs}`);
464
+ }
465
+ catch (error) {
466
+ return { ok: false, kind: 'unwritable', detail: `arbitration gate unavailable: ${errorDetail(error)}` };
467
+ }
468
+ try {
469
+ db.exec('BEGIN IMMEDIATE');
470
+ }
471
+ catch (error) {
472
+ try {
473
+ db.close();
474
+ }
475
+ catch {
476
+ // already closing
477
+ }
478
+ return {
479
+ ok: false,
480
+ kind: isBusyError(error) ? 'busy' : 'unwritable',
481
+ detail: `arbitration gate begin failed: ${errorDetail(error)}`,
482
+ };
483
+ }
484
+ try {
485
+ const value = body();
486
+ opts.insideTxn?.();
487
+ if (opts.injectEndFailure === true) {
488
+ const injected = new Error('injected gate transaction-end failure');
489
+ Reflect.set(injected, 'code', 'SQLITE_IOERR');
490
+ throw injected;
491
+ }
492
+ // No persistent gate data: ROLLBACK ends the transaction — a failed
493
+ // COMMIT can never orphan the filesystem writes made inside `body`.
494
+ db.exec('ROLLBACK');
495
+ return { ok: true, value };
496
+ }
497
+ catch (error) {
498
+ try {
499
+ db.exec('ROLLBACK');
500
+ }
501
+ catch {
502
+ // rollback best-effort; process death releases the gate anyway
503
+ }
504
+ if (opts.createdBody !== undefined) {
505
+ try {
506
+ if (readLockBody(lockPath) === opts.createdBody)
507
+ fs.unlinkSync(lockPath);
508
+ }
509
+ catch {
510
+ // Leave it — a dead-holder body recovers on PID evidence anyway.
511
+ }
512
+ }
513
+ return {
514
+ ok: false,
515
+ kind: isBusyError(error) ? 'busy' : 'unwritable',
516
+ detail: `arbitration gate transaction failed: ${errorDetail(error)}`,
517
+ };
518
+ }
519
+ finally {
520
+ try {
521
+ db.close();
522
+ }
523
+ catch {
524
+ // already closed
525
+ }
526
+ }
527
+ }
528
+ /** True when the lock file still carries OUR body (mid-run ownership re-check). */
529
+ export function holdsServiceRunLock(handle) {
530
+ return readLockBody(handle.lockPath) === handle.body;
531
+ }
532
+ /**
533
+ * Shared lock engine behind {@link acquireServiceRunLock} and
534
+ * {@link acquireWorkspaceServiceRunLock}. Every decision — evaluate, stale
535
+ * takeover, create — runs inside the arbitration gate (§P1-4 round 4),
536
+ * immediate verdicts, no wait loop (`already_running` semantics, §8.2). A
537
+ * stale takeover additionally requires the recorded holder PID to be
538
+ * demonstrably DEAD; a live, unknown or unverifiable holder is NEVER taken
539
+ * over, and the verify→delete→create sequence is serialized by the same
540
+ * transaction that a second contender's BEGIN cannot enter.
541
+ */
542
+ function acquireLockAt(lockPath, options) {
543
+ const staleMs = options?.staleMs ?? SERVICE_RUN_LOCK_STALE_MS;
544
+ const processAlive = options?.probes?.processAlive ?? defaultProcessAlive;
545
+ const statLock = options?.probes?.statLock;
546
+ const takeoverSync = options?.probes?.takeoverSync;
547
+ const token = randomUUID().replace(/-/g, '').slice(0, 16);
548
+ const body = lockBody(token);
549
+ try {
550
+ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
551
+ }
552
+ catch (error) {
553
+ const message = error instanceof Error ? error.message : String(error);
554
+ return { ok: false, kind: 'unwritable', detail: message };
555
+ }
556
+ const gated = withGateArbitration(lockPath, {
557
+ busyTimeoutMs: ACQUIRE_BUSY_TIMEOUT_MS,
558
+ createdBody: body,
559
+ injectEndFailure: options?.probes?.gateEndFailure === true,
560
+ }, () => {
561
+ // Mixed-version protection (§六): an old-protocol coordinator may be
562
+ // mid-takeover holding `.mtx`. A live/unverifiable legacy mutex means
563
+ // fail-closed held — never run a second instance beside it.
564
+ if (legacyMutexOccupied(lockPath, processAlive))
565
+ return heldVerdict(lockPath);
566
+ const evaluate = () => evaluateLock(lockPath, { staleMs, processAlive, statLock });
567
+ const createOwned = (staleTakenOver) => {
568
+ const created = tryCreate(lockPath, body);
569
+ if (created === 'created') {
570
+ sweepOrphanSidecars(lockPath, staleMs, processAlive);
571
+ return { ok: true, handle: { lockPath, token, body }, staleTakenOver };
572
+ }
573
+ if (typeof created === 'object')
574
+ return { ok: false, kind: 'unwritable', detail: created.error };
575
+ return heldVerdict(lockPath);
576
+ };
577
+ const mapEvaluation = (evaluation) => {
578
+ switch (evaluation.kind) {
579
+ case 'absent':
580
+ return createOwned(false);
581
+ case 'stat-error':
582
+ // stat itself failed non-ENOENT: the lock may exist and be held —
583
+ // fail-closed, never acquire over degraded evidence.
584
+ return { ok: false, kind: 'corrupt', detail: `lock state unverifiable: ${evaluation.detail}` };
585
+ case 'fresh':
586
+ case 'stale-alive':
587
+ return heldVerdict(lockPath);
588
+ case 'stale-unreadable':
589
+ // Beyond the stale window yet unreadable: identity unverifiable —
590
+ // fail-closed (human decision), never a silent takeover.
591
+ return { ok: false, kind: 'corrupt', detail: 'lock age is beyond the stale window but its body is unreadable' };
592
+ case 'stale-anonymous':
593
+ // The stale body names no verifiable holder — cannot prove the
594
+ // old holder died, so takeover is refused fail-closed (P1-4).
595
+ return { ok: false, kind: 'corrupt', detail: `lock body carries no verifiable holder identity: ${bodyEcho(evaluation.body)}` };
596
+ case 'dead':
597
+ return 'takeover';
598
+ }
599
+ };
600
+ const first = mapEvaluation(evaluate());
601
+ if (first !== 'takeover')
602
+ return first;
603
+ // ── Arbitrated takeover: re-verify under the SAME transaction. The
604
+ // gate serializes us against every other contender, so the lock we
605
+ // verified is the lock we are about to remove — no second breaker can
606
+ // interleave a fresh create between our check and our unlink.
607
+ takeoverSync?.('mutex-acquired');
608
+ const inner = evaluate();
609
+ if (inner.kind !== 'dead') {
610
+ // Non-cooperating writers aside, the only reachable states here are
611
+ // 'dead' or 'absent' (a cooperating process cannot change the
612
+ // file under our transaction). Map defensively anyway.
613
+ if (inner.kind === 'absent')
614
+ return createOwned(true);
615
+ const mapped = mapEvaluation(inner);
616
+ if (mapped !== 'takeover')
617
+ return mapped;
618
+ }
619
+ takeoverSync?.('stale-verified');
620
+ // The lock still carries a provably-dead stale body under arbitration —
621
+ // deleting it cannot displace a live holder.
622
+ try {
623
+ fs.unlinkSync(lockPath);
624
+ }
625
+ catch (error) {
626
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
627
+ ? String(Reflect.get(error, 'code'))
628
+ : '';
629
+ if (code !== 'ENOENT') {
630
+ return { ok: false, kind: 'unwritable', detail: `could not remove stale lock: ${code}` };
631
+ }
632
+ // ENOENT: a non-cooperating writer already removed it; fall through
633
+ // to the 'wx' create, which still decides exactly once.
634
+ }
635
+ takeoverSync?.('lock-removed');
636
+ return createOwned(true);
637
+ });
638
+ if (!gated.ok) {
639
+ return gated.kind === 'busy'
640
+ ? heldVerdict(lockPath)
641
+ : { ok: false, kind: 'unwritable', detail: gated.detail };
642
+ }
643
+ return gated.value;
644
+ }
645
+ /** Acquire the install-level single-instance run lock (see {@link acquireLockAt}). */
646
+ export function acquireServiceRunLock(pdHome, options) {
647
+ return acquireLockAt(serviceRunLockPath(pdHome), options);
648
+ }
649
+ /**
650
+ * Acquire the per-workspace consumer mutex (see
651
+ * {@link workspaceServiceRunLockPath}). Same protocol as the install-level
652
+ * lock; the Worker child holds it for its whole consuming cycle so a
653
+ * handover resume / rollback can prove the old worker is still running
654
+ * (PRI-1282 review).
655
+ */
656
+ export function acquireWorkspaceServiceRunLock(pdHome, workspaceDir, options) {
657
+ return acquireLockAt(workspaceServiceRunLockPath(pdHome, workspaceDir), options);
658
+ }
659
+ /**
660
+ * Non-mutating liveness probe: is a CONSUMING worker holding this lock
661
+ * right now? 'free' means no holder or a provably-dead one (recoverable);
662
+ * 'held' means a live or inconclusive holder — an orchestrator must refuse
663
+ * to overlap it; 'corrupt' means the body cannot be verified (fail-closed).
664
+ */
665
+ export function probeServiceRunLockState(lockPath, options) {
666
+ const evaluation = evaluateLock(lockPath, {
667
+ staleMs: options?.staleMs ?? SERVICE_RUN_LOCK_STALE_MS,
668
+ processAlive: options?.probes?.processAlive ?? defaultProcessAlive,
669
+ statLock: options?.probes?.statLock,
670
+ });
671
+ switch (evaluation.kind) {
672
+ case 'absent':
673
+ case 'dead':
674
+ return { state: 'free' };
675
+ case 'stat-error':
676
+ return { state: 'corrupt', detail: `lock state unverifiable: ${evaluation.detail}` };
677
+ case 'fresh':
678
+ case 'stale-alive':
679
+ return { state: 'held' };
680
+ case 'stale-unreadable':
681
+ return { state: 'corrupt', detail: 'lock body unreadable beyond the stale window' };
682
+ case 'stale-anonymous':
683
+ return { state: 'corrupt', detail: `lock body carries no verifiable holder identity: ${bodyEcho(evaluation.body)}` };
684
+ }
685
+ }
686
+ /**
687
+ * Ownership-checked release under the SAME arbitration gate: verify the
688
+ * lock body is OURS and unlink it inside one transaction — a true
689
+ * compare-and-delete, so the file a foreign holder just created can never
690
+ * be removed by our late release (P1-4). The release gets its own bounded
691
+ * retry (`RELEASE_BUSY_TIMEOUT_MS` × `RELEASE_MAX_ATTEMPTS`) independent of
692
+ * acquire's zero-wait policy, but NEVER bypasses the gate to unlink: a gate
693
+ * failure leaves the lock in place and reports it — the leftover carries
694
+ * our own PID, which the next contender recovers on death evidence.
695
+ */
696
+ export function releaseServiceRunLock(handle, options) {
697
+ for (let attempt = 0; attempt < RELEASE_MAX_ATTEMPTS; attempt += 1) {
698
+ let verdict = 'released';
699
+ const gated = withGateArbitration(handle.lockPath, {
700
+ busyTimeoutMs: RELEASE_BUSY_TIMEOUT_MS,
701
+ injectEndFailure: options?.injectEndFailure === true,
702
+ ...(options?.insideTxn !== undefined ? { insideTxn: options.insideTxn } : {}),
703
+ }, () => {
704
+ const read = (options?.readBody ?? readLockBodyStatus)(handle.lockPath);
705
+ if (read.kind === 'unreadable') {
706
+ // EACCES/EPERM/EIO/EISDIR and every other real read failure is a
707
+ // genuine release failure — NEVER `not_owned`, NEVER an unlink
708
+ // outside verification, and the lock file is left exactly as it
709
+ // is for human recovery or a later evidence-based takeover.
710
+ verdict = 'failed_unwritable';
711
+ return;
712
+ }
713
+ if (read.kind === 'absent' || read.body !== handle.body) {
714
+ verdict = 'not_owned'; // gone or foreign — never displace it
715
+ return;
716
+ }
717
+ try {
718
+ fs.unlinkSync(handle.lockPath);
719
+ }
720
+ catch (error) {
721
+ const code = typeof error === 'object' && error !== null && Object.hasOwn(error, 'code')
722
+ ? String(Reflect.get(error, 'code'))
723
+ : '';
724
+ if (code === 'ENOENT') {
725
+ verdict = 'not_owned'; // already gone — nothing left to release
726
+ return;
727
+ }
728
+ throw error; // real unlink failure → transaction fails → unwritable
729
+ }
730
+ });
731
+ if (gated.ok)
732
+ return verdict;
733
+ if (gated.kind === 'unwritable')
734
+ return 'failed_unwritable';
735
+ // 'busy': bounded retry — the concurrent arbiter usually frees shortly.
736
+ }
737
+ return 'failed_busy';
738
+ }
739
+ //# sourceMappingURL=service-run-lock.js.map