@wildo-ai/platform-config-lib 1.1.8 → 1.1.9

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 (28) hide show
  1. package/dist/esm/bootstrap/bootstrap.schemas.d.ts +12 -5
  2. package/dist/esm/bootstrap/bootstrap.schemas.d.ts.map +1 -1
  3. package/dist/esm/bootstrap/bootstrap.schemas.js +21 -5
  4. package/dist/esm/bootstrap/bootstrap.schemas.js.map +1 -1
  5. package/dist/esm/index.d.ts +1 -0
  6. package/dist/esm/index.d.ts.map +1 -1
  7. package/dist/esm/index.js +1 -0
  8. package/dist/esm/index.js.map +1 -1
  9. package/dist/esm/lockfile/file-lock-hold.d.ts +87 -0
  10. package/dist/esm/lockfile/file-lock-hold.d.ts.map +1 -0
  11. package/dist/esm/lockfile/file-lock-hold.js +279 -0
  12. package/dist/esm/lockfile/file-lock-hold.js.map +1 -0
  13. package/dist/esm/lockfile/lockfile-io.d.ts +21 -3
  14. package/dist/esm/lockfile/lockfile-io.d.ts.map +1 -1
  15. package/dist/esm/lockfile/lockfile-io.js +8 -16
  16. package/dist/esm/lockfile/lockfile-io.js.map +1 -1
  17. package/dist/esm/project-config/loader.d.ts +16 -1
  18. package/dist/esm/project-config/loader.d.ts.map +1 -1
  19. package/dist/esm/project-config/loader.js +35 -1
  20. package/dist/esm/project-config/loader.js.map +1 -1
  21. package/dist/esm/project-config/provider-companion-discovery.d.ts.map +1 -1
  22. package/dist/esm/project-config/provider-companion-discovery.js +1 -0
  23. package/dist/esm/project-config/provider-companion-discovery.js.map +1 -1
  24. package/dist/esm/project-config/shared/infra-providers.schemas.d.ts +13 -0
  25. package/dist/esm/project-config/shared/infra-providers.schemas.d.ts.map +1 -1
  26. package/dist/esm/project-config/shared/infra-providers.schemas.js.map +1 -1
  27. package/dist/tsconfig.build.tsbuildinfo +1 -1
  28. package/package.json +7 -7
@@ -0,0 +1,279 @@
1
+ /**
2
+ * The one way this package acquires a `proper-lockfile` lock, so every holder gets the same two
3
+ * guarantees (#2225):
4
+ *
5
+ * 1. **A waiter never reclaims the lock of a holder that is still alive.** proper-lockfile decides a
6
+ * lock is stale from its directory's mtime alone (`stale`, 5 s by default here). A holder whose
7
+ * refresh is merely LATE — an event-loop stall, a saturated libuv threadpool, a laptop waking up —
8
+ * recovers on its own as long as nobody touched the lock directory (proper-lockfile 4.1.2,
9
+ * `lockfile.js` `updateLock`: a successful `utimes` carries no threshold check). What turns a late
10
+ * refresh into a lost lock is a WAITER judging the mtime stale and removing the directory. So the
11
+ * reclaim itself is guarded: the removal is refused while the recorded holder is alive on this host.
12
+ * 2. **Losing the lock is an error in that critical section, never a process exit.** proper-lockfile's
13
+ * default `onCompromised` throws inside an `fs` callback, which is an uncaught exception. On
14
+ * 2026-10-01 that killed the dev companion mid build wave, with every in-flight coding run in it.
15
+ *
16
+ * Why a liveness check and not simply a larger `stale`: the reclaim that matters most is by the SAME
17
+ * process — proper-lockfile keeps no in-process guard, so a second `lock()` in the companion (a
18
+ * concurrent run's commit retrying for minutes) takes the same mtime path as a stranger would. Any
19
+ * fixed window is one stall away from being too short, and a long window makes a CRASHED holder's lock
20
+ * block everyone for that long. Asking "is the holder alive" keeps dead-holder recovery at 5 s and makes
21
+ * the live-holder case independent of timing. Rejected: writing the holder record INSIDE the lock
22
+ * directory (it changes the directory's mtime, which proper-lockfile reads as another owner, and makes a
23
+ * plain `rmdir` from an older library fail `ENOTEMPTY`) and BESIDE it (the shared
24
+ * `.wildo-saas/wildo-saas.lock.json.lock` sits in a committed, un-ignored directory, so a record there is
25
+ * an untracked file in the very `git status` the companion attributes writes from).
26
+ */
27
+ import nodeFs from 'node:fs';
28
+ import { promises as fs } from 'node:fs';
29
+ import { AsyncLocalStorage } from 'node:async_hooks';
30
+ import { createHash, randomUUID } from 'node:crypto';
31
+ import * as os from 'node:os';
32
+ import * as path from 'node:path';
33
+ import lockfile from 'proper-lockfile';
34
+ import { z } from 'zod';
35
+ /**
36
+ * How long a LIVE holder may go without refreshing its lock before a waiter may reclaim it anyway.
37
+ *
38
+ * Ten minutes without a single mtime refresh (normally every 2.5 s) means the holder is wedged, or its
39
+ * pid was reused by an unrelated process. Past this the reclaim proceeds, and the wedged holder learns it
40
+ * lost the lock through {@link FileLockCompromisedError} rather than by dying.
41
+ */
42
+ export const LIVE_HOLDER_RECLAIM_CEILING_MS = 10 * 60_000;
43
+ /**
44
+ * The lock was taken from this holder while it still held it — another acquirer removed it, or the lock
45
+ * directory was deleted. The holder no longer has exclusivity, so whatever it was about to do as the
46
+ * exclusive writer must not happen. `code` is `ECOMPROMISED`, the code proper-lockfile itself uses.
47
+ */
48
+ export class FileLockCompromisedError extends Error {
49
+ code = 'ECOMPROMISED';
50
+ lockTargetPath;
51
+ /** What the critical section itself failed with, when it failed too; `cause` is the lock's loss. */
52
+ sectionError;
53
+ constructor(lockTargetPath, cause) {
54
+ super(`The lock on ${lockTargetPath} was lost while it was held (${cause instanceof Error ? cause.message : String(cause)}). `
55
+ + 'The critical section it guarded did not keep exclusive access and was refused.', { cause });
56
+ this.name = 'FileLockCompromisedError';
57
+ this.lockTargetPath = lockTargetPath;
58
+ }
59
+ }
60
+ /** The holds the current async call chain is running inside, outermost first. */
61
+ const heldFileLocks = new AsyncLocalStorage();
62
+ /**
63
+ * Throw if a lock the current call chain is running inside has been lost.
64
+ *
65
+ * Call it immediately before an act that is only safe as the lock's exclusive holder — a git commit, a
66
+ * file write the lock serializes. Outside any lock, or with every enclosing lock intact, it does nothing.
67
+ */
68
+ export function assertHeldFileLocksIntact() {
69
+ for (const hold of heldFileLocks.getStore() ?? []) {
70
+ if (hold.compromise)
71
+ throw hold.compromise;
72
+ }
73
+ }
74
+ const FileLockHolderRecordSchema = z.object({
75
+ pid: z.number().int().positive(),
76
+ hostname: z.string(),
77
+ token: z.string(),
78
+ acquiredAt: z.string(),
79
+ });
80
+ /** lock directory → token of the hold THIS process currently has on it. */
81
+ const heldInThisProcess = new Map();
82
+ /**
83
+ * Where a lock's holder is recorded: a per-USER temp directory (created `0700`), keyed by the lock
84
+ * directory's path. Outside every worktree (see the module comment), and shared by every process of one
85
+ * user on one host — which is exactly the population whose liveness `process.kill(pid, 0)` can answer.
86
+ * Per user, not merely per `$TMPDIR`: where `os.tmpdir()` is a shared `/tmp`, another account could
87
+ * otherwise plant a record naming a live pid and hold a crashed lock for the whole ceiling.
88
+ */
89
+ export function fileLockHolderRecordPath(lockDirPath) {
90
+ const key = createHash('sha256').update(lockDirPath).digest('hex').slice(0, 32);
91
+ return path.join(fileLockHolderRecordDirectory(), `${key}.json`);
92
+ }
93
+ function fileLockHolderRecordDirectory() {
94
+ const user = typeof process.getuid === 'function' ? String(process.getuid()) : os.userInfo().username;
95
+ return path.join(os.tmpdir(), `wildo-file-lock-holders-${user}`);
96
+ }
97
+ /**
98
+ * Whether the record directory belongs to this user. `mkdir`'s `0700` holds only for a directory this
99
+ * process CREATED; on a shared `/tmp` another account could have created it first. A directory owned by
100
+ * someone else is never written to and never believed: the lock then keeps plain mtime staleness.
101
+ */
102
+ async function holderRecordDirectoryIsOurs() {
103
+ if (typeof process.getuid !== 'function')
104
+ return true;
105
+ try {
106
+ return (await fs.lstat(fileLockHolderRecordDirectory())).uid === process.getuid();
107
+ }
108
+ catch {
109
+ return false;
110
+ }
111
+ }
112
+ async function readHolderRecord(lockDirPath) {
113
+ if (!(await holderRecordDirectoryIsOurs()))
114
+ return null;
115
+ try {
116
+ const parsed = FileLockHolderRecordSchema.safeParse(JSON.parse(await fs.readFile(fileLockHolderRecordPath(lockDirPath), 'utf8')));
117
+ return parsed.success ? parsed.data : null;
118
+ }
119
+ catch {
120
+ return null;
121
+ }
122
+ }
123
+ function isProcessAlive(pid) {
124
+ try {
125
+ process.kill(pid, 0);
126
+ return true;
127
+ }
128
+ catch (error) {
129
+ // EPERM: the process exists but belongs to someone else — alive.
130
+ return error.code === 'EPERM';
131
+ }
132
+ }
133
+ /**
134
+ * The holder a reclaim of `lockDirPath` would take the lock from, when that holder is alive and
135
+ * refreshed within {@link LIVE_HOLDER_RECLAIM_CEILING_MS}; otherwise `null`, and the reclaim may proceed.
136
+ *
137
+ * No record, a record from another host, or a record naming a dead process all mean proper-lockfile's own
138
+ * mtime judgement stands — the dead-holder recovery this lock has always had.
139
+ */
140
+ async function liveHolderBlockingReclaim(lockDirPath) {
141
+ const record = await readHolderRecord(lockDirPath);
142
+ if (!record || record.hostname !== os.hostname())
143
+ return null;
144
+ const alive = record.pid === process.pid
145
+ // In this process the map is the truth: a record naming this pid with another token is left over
146
+ // from a hold that has already ended here.
147
+ ? heldInThisProcess.get(lockDirPath) === record.token
148
+ : isProcessAlive(record.pid);
149
+ if (!alive)
150
+ return null;
151
+ try {
152
+ const { mtimeMs } = await fs.stat(lockDirPath);
153
+ if (Date.now() - mtimeMs > LIVE_HOLDER_RECLAIM_CEILING_MS)
154
+ return null;
155
+ }
156
+ catch {
157
+ return null;
158
+ }
159
+ return record;
160
+ }
161
+ /**
162
+ * The `fs` proper-lockfile is given. Identical to `node:fs` except `rmdir`, which proper-lockfile calls
163
+ * for exactly two reasons: to REMOVE A STALE LOCK before taking it (while acquiring) and to RELEASE its
164
+ * own lock (once held, including its exit-time cleanup). Only the first is guarded, and a refusal is
165
+ * returned as `ELOCKED` so the caller's retry policy and conflict mapping apply unchanged.
166
+ */
167
+ function createReclaimGuardedFs(phase) {
168
+ const rmdir = (lockDirPath, callback) => {
169
+ if (!phase.acquiring) {
170
+ nodeFs.rmdir(lockDirPath, callback);
171
+ return;
172
+ }
173
+ liveHolderBlockingReclaim(lockDirPath).then((holder) => {
174
+ if (!holder) {
175
+ nodeFs.rmdir(lockDirPath, callback);
176
+ return;
177
+ }
178
+ callback(Object.assign(new Error(`Lock file is already being held by live process ${holder.pid} (its refresh is late, so it is not reclaimed)`), { code: 'ELOCKED', file: lockDirPath }));
179
+ }, () => nodeFs.rmdir(lockDirPath, callback));
180
+ };
181
+ return { ...nodeFs, rmdir };
182
+ }
183
+ function reportCompromiseToStderr(error) {
184
+ process.stderr.write(`[wildo] ${error.message}\n`);
185
+ }
186
+ /**
187
+ * Acquire `lockTargetPath` (which must exist), run `fn` holding it, release it.
188
+ *
189
+ * - A lost lock never throws asynchronously. It marks the hold, `assertHeldFileLocksIntact()` refuses from
190
+ * then on inside `fn`'s call chain, and the call rejects with {@link FileLockCompromisedError} once `fn`
191
+ * settles — with `fn`'s own error as the cause when it failed too.
192
+ * - Contention is still proper-lockfile's `ELOCKED`, including a refused reclaim of a live holder.
193
+ */
194
+ export async function holdFileLock(lockTargetPath, fn, options) {
195
+ const canonicalTarget = options.realpath ? await fs.realpath(lockTargetPath) : path.resolve(lockTargetPath);
196
+ const lockDirPath = `${canonicalTarget}.lock`;
197
+ const hold = { lockTargetPath, compromise: null };
198
+ const token = randomUUID();
199
+ const phase = { acquiring: true };
200
+ const release = await lockfile.lock(lockTargetPath, {
201
+ retries: options.retries,
202
+ stale: options.stale,
203
+ realpath: options.realpath,
204
+ fs: createReclaimGuardedFs(phase),
205
+ onCompromised: (cause) => {
206
+ hold.compromise = new FileLockCompromisedError(lockTargetPath, cause);
207
+ if (heldInThisProcess.get(lockDirPath) === token)
208
+ heldInThisProcess.delete(lockDirPath);
209
+ try {
210
+ (options.onCompromised ?? reportCompromiseToStderr)(hold.compromise);
211
+ }
212
+ catch {
213
+ // A logging callback must not reintroduce the uncaught exception this handler exists to remove.
214
+ }
215
+ },
216
+ });
217
+ phase.acquiring = false;
218
+ heldInThisProcess.set(lockDirPath, token);
219
+ const recordPath = fileLockHolderRecordPath(lockDirPath);
220
+ try {
221
+ await fs.mkdir(path.dirname(recordPath), { recursive: true, mode: 0o700 });
222
+ if (!(await holderRecordDirectoryIsOurs()))
223
+ throw new Error('holder record directory belongs to another user');
224
+ const record = { pid: process.pid, hostname: os.hostname(), token, acquiredAt: new Date().toISOString() };
225
+ await fs.writeFile(recordPath, JSON.stringify(record), 'utf8');
226
+ }
227
+ catch {
228
+ // Without a record the lock keeps proper-lockfile's plain mtime judgement — what it had before #2225.
229
+ }
230
+ const enclosing = heldFileLocks.getStore() ?? [];
231
+ let value;
232
+ let sectionFailed = false;
233
+ let sectionError;
234
+ try {
235
+ value = await heldFileLocks.run([...enclosing, hold], fn);
236
+ }
237
+ catch (error) {
238
+ sectionFailed = true;
239
+ sectionError = error;
240
+ }
241
+ if (heldInThisProcess.get(lockDirPath) === token)
242
+ heldInThisProcess.delete(lockDirPath);
243
+ /*
244
+ * The record goes AFTER the release, never before: the release is what the next acquirer is waiting
245
+ * for, and a caller that saw this section settle may acquire again at once with no retries. A record
246
+ * outliving its lock is harmless — the token check means it is only ever removed by its own hold, and
247
+ * a stale record defends nothing once the directory it names is gone.
248
+ */
249
+ // Residual, accepted: the read and the remove are two steps, so an acquirer whose record lands between
250
+ // them loses it and falls back to plain mtime staleness for that one hold — what every hold had before
251
+ // #2225. The window is the gap between two filesystem calls, after this hold has already released.
252
+ const forgetHolderRecord = async () => {
253
+ if ((await readHolderRecord(lockDirPath))?.token === token)
254
+ await fs.rm(recordPath, { force: true }).catch(() => undefined);
255
+ };
256
+ if (hold.compromise) {
257
+ // proper-lockfile has already dropped a compromised lock, so there is nothing of ours to release —
258
+ // and the directory now belongs to whoever took it.
259
+ await forgetHolderRecord();
260
+ if (sectionFailed && sectionError !== hold.compromise)
261
+ hold.compromise.sectionError = sectionError;
262
+ throw hold.compromise;
263
+ }
264
+ try {
265
+ await release();
266
+ }
267
+ catch (error) {
268
+ // Lost between the check above and the release: same answer as a loss during the section.
269
+ await forgetHolderRecord();
270
+ if (hold.compromise)
271
+ throw hold.compromise;
272
+ throw error;
273
+ }
274
+ await forgetHolderRecord();
275
+ if (sectionFailed)
276
+ throw sectionError;
277
+ return value;
278
+ }
279
+ //# sourceMappingURL=file-lock-hold.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"file-lock-hold.js","sourceRoot":"","sources":["../../../../src/lockfile/file-lock-hold.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;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;;OAKG;IACH,uGAAuG;IACvG,uGAAuG;IACvG,mGAAmG;IACnG,MAAM,kBAAkB,GAAG,KAAK,IAAmB,EAAE;QACnD,IAAI,CAAC,MAAM,gBAAgB,CAAC,WAAW,CAAC,CAAC,EAAE,KAAK,KAAK,KAAK;YAAE,MAAM,EAAE,CAAC,EAAE,CAAC,UAAU,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,SAAS,CAAC,CAAC;IAC9H,CAAC,CAAC;IAEF,IAAI,IAAI,CAAC,UAAU,EAAE,CAAC;QACpB,mGAAmG;QACnG,oDAAoD;QACpD,MAAM,kBAAkB,EAAE,CAAC;QAC3B,IAAI,aAAa,IAAI,YAAY,KAAK,IAAI,CAAC,UAAU;YAAE,IAAI,CAAC,UAAU,CAAC,YAAY,GAAG,YAAY,CAAC;QACnG,MAAM,IAAI,CAAC,UAAU,CAAC;IACxB,CAAC;IACD,IAAI,CAAC;QACH,MAAM,OAAO,EAAE,CAAC;IAClB,CAAC;IAAC,OAAO,KAAK,EAAE,CAAC;QACf,0FAA0F;QAC1F,MAAM,kBAAkB,EAAE,CAAC;QAC3B,IAAI,IAAI,CAAC,UAAU;YAAE,MAAM,IAAI,CAAC,UAAU,CAAC;QAC3C,MAAM,KAAK,CAAC;IACd,CAAC;IACD,MAAM,kBAAkB,EAAE,CAAC;IAC3B,IAAI,aAAa;QAAE,MAAM,YAAY,CAAC;IACtC,OAAO,KAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * The one way this package acquires a `proper-lockfile` lock, so every holder gets the same two\n * guarantees (#2225):\n *\n * 1. **A waiter never reclaims the lock of a holder that is still alive.** proper-lockfile decides a\n * lock is stale from its directory's mtime alone (`stale`, 5 s by default here). A holder whose\n * refresh is merely LATE — an event-loop stall, a saturated libuv threadpool, a laptop waking up —\n * recovers on its own as long as nobody touched the lock directory (proper-lockfile 4.1.2,\n * `lockfile.js` `updateLock`: a successful `utimes` carries no threshold check). What turns a late\n * refresh into a lost lock is a WAITER judging the mtime stale and removing the directory. So the\n * reclaim itself is guarded: the removal is refused while the recorded holder is alive on this host.\n * 2. **Losing the lock is an error in that critical section, never a process exit.** proper-lockfile's\n * default `onCompromised` throws inside an `fs` callback, which is an uncaught exception. On\n * 2026-10-01 that killed the dev companion mid build wave, with every in-flight coding run in it.\n *\n * Why a liveness check and not simply a larger `stale`: the reclaim that matters most is by the SAME\n * process — proper-lockfile keeps no in-process guard, so a second `lock()` in the companion (a\n * concurrent run's commit retrying for minutes) takes the same mtime path as a stranger would. Any\n * fixed window is one stall away from being too short, and a long window makes a CRASHED holder's lock\n * block everyone for that long. Asking \"is the holder alive\" keeps dead-holder recovery at 5 s and makes\n * the live-holder case independent of timing. Rejected: writing the holder record INSIDE the lock\n * directory (it changes the directory's mtime, which proper-lockfile reads as another owner, and makes a\n * plain `rmdir` from an older library fail `ENOTEMPTY`) and BESIDE it (the shared\n * `.wildo-saas/wildo-saas.lock.json.lock` sits in a committed, un-ignored directory, so a record there is\n * an untracked file in the very `git status` the companion attributes writes from).\n */\n\nimport nodeFs from 'node:fs';\nimport { promises as fs } from 'node:fs';\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { createHash, randomUUID } from 'node:crypto';\nimport * as os from 'node:os';\nimport * as path from 'node:path';\nimport lockfile from 'proper-lockfile';\nimport { z } from 'zod';\n\n/**\n * How long a LIVE holder may go without refreshing its lock before a waiter may reclaim it anyway.\n *\n * Ten minutes without a single mtime refresh (normally every 2.5 s) means the holder is wedged, or its\n * pid was reused by an unrelated process. Past this the reclaim proceeds, and the wedged holder learns it\n * lost the lock through {@link FileLockCompromisedError} rather than by dying.\n */\nexport const LIVE_HOLDER_RECLAIM_CEILING_MS = 10 * 60_000;\n\n/** Options every acquisition in this package resolves to. */\nexport interface FileLockAcquireOptions {\n readonly retries: number | { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n readonly stale: number;\n readonly realpath: boolean;\n /**\n * Told once when the lock is lost while held. The critical section still fails with\n * {@link FileLockCompromisedError}; this is for the caller's own log. Omitted, one line goes to stderr.\n */\n readonly onCompromised?: (error: FileLockCompromisedError) => void;\n}\n\n/**\n * The lock was taken from this holder while it still held it — another acquirer removed it, or the lock\n * directory was deleted. The holder no longer has exclusivity, so whatever it was about to do as the\n * exclusive writer must not happen. `code` is `ECOMPROMISED`, the code proper-lockfile itself uses.\n */\nexport class FileLockCompromisedError extends Error {\n readonly code = 'ECOMPROMISED';\n readonly lockTargetPath: string;\n /** What the critical section itself failed with, when it failed too; `cause` is the lock's loss. */\n sectionError?: unknown;\n\n constructor(lockTargetPath: string, cause: unknown) {\n super(\n `The lock on ${lockTargetPath} was lost while it was held (${cause instanceof Error ? cause.message : String(cause)}). `\n + 'The critical section it guarded did not keep exclusive access and was refused.',\n { cause },\n );\n this.name = 'FileLockCompromisedError';\n this.lockTargetPath = lockTargetPath;\n }\n}\n\ninterface FileLockHold {\n readonly lockTargetPath: string;\n compromise: FileLockCompromisedError | null;\n}\n\n/** The holds the current async call chain is running inside, outermost first. */\nconst heldFileLocks = new AsyncLocalStorage<readonly FileLockHold[]>();\n\n/**\n * Throw if a lock the current call chain is running inside has been lost.\n *\n * Call it immediately before an act that is only safe as the lock's exclusive holder — a git commit, a\n * file write the lock serializes. Outside any lock, or with every enclosing lock intact, it does nothing.\n */\nexport function assertHeldFileLocksIntact(): void {\n for (const hold of heldFileLocks.getStore() ?? []) {\n if (hold.compromise) throw hold.compromise;\n }\n}\n\nconst FileLockHolderRecordSchema = z.object({\n pid: z.number().int().positive(),\n hostname: z.string(),\n token: z.string(),\n acquiredAt: z.string(),\n});\ntype FileLockHolderRecord = z.infer<typeof FileLockHolderRecordSchema>;\n\n/** lock directory → token of the hold THIS process currently has on it. */\nconst heldInThisProcess = new Map<string, string>();\n\n/**\n * Where a lock's holder is recorded: a per-USER temp directory (created `0700`), keyed by the lock\n * directory's path. Outside every worktree (see the module comment), and shared by every process of one\n * user on one host — which is exactly the population whose liveness `process.kill(pid, 0)` can answer.\n * Per user, not merely per `$TMPDIR`: where `os.tmpdir()` is a shared `/tmp`, another account could\n * otherwise plant a record naming a live pid and hold a crashed lock for the whole ceiling.\n */\nexport function fileLockHolderRecordPath(lockDirPath: string): string {\n const key = createHash('sha256').update(lockDirPath).digest('hex').slice(0, 32);\n return path.join(fileLockHolderRecordDirectory(), `${key}.json`);\n}\n\nfunction fileLockHolderRecordDirectory(): string {\n const user = typeof process.getuid === 'function' ? String(process.getuid()) : os.userInfo().username;\n return path.join(os.tmpdir(), `wildo-file-lock-holders-${user}`);\n}\n\n/**\n * Whether the record directory belongs to this user. `mkdir`'s `0700` holds only for a directory this\n * process CREATED; on a shared `/tmp` another account could have created it first. A directory owned by\n * someone else is never written to and never believed: the lock then keeps plain mtime staleness.\n */\nasync function holderRecordDirectoryIsOurs(): Promise<boolean> {\n if (typeof process.getuid !== 'function') return true;\n try {\n return (await fs.lstat(fileLockHolderRecordDirectory())).uid === process.getuid();\n } catch {\n return false;\n }\n}\n\nasync function readHolderRecord(lockDirPath: string): Promise<FileLockHolderRecord | null> {\n if (!(await holderRecordDirectoryIsOurs())) return null;\n try {\n const parsed = FileLockHolderRecordSchema.safeParse(JSON.parse(await fs.readFile(fileLockHolderRecordPath(lockDirPath), 'utf8')));\n return parsed.success ? parsed.data : null;\n } catch {\n return null;\n }\n}\n\nfunction isProcessAlive(pid: number): boolean {\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n // EPERM: the process exists but belongs to someone else — alive.\n return (error as NodeJS.ErrnoException).code === 'EPERM';\n }\n}\n\n/**\n * The holder a reclaim of `lockDirPath` would take the lock from, when that holder is alive and\n * refreshed within {@link LIVE_HOLDER_RECLAIM_CEILING_MS}; otherwise `null`, and the reclaim may proceed.\n *\n * No record, a record from another host, or a record naming a dead process all mean proper-lockfile's own\n * mtime judgement stands — the dead-holder recovery this lock has always had.\n */\nasync function liveHolderBlockingReclaim(lockDirPath: string): Promise<FileLockHolderRecord | null> {\n const record = await readHolderRecord(lockDirPath);\n if (!record || record.hostname !== os.hostname()) return null;\n const alive = record.pid === process.pid\n // In this process the map is the truth: a record naming this pid with another token is left over\n // from a hold that has already ended here.\n ? heldInThisProcess.get(lockDirPath) === record.token\n : isProcessAlive(record.pid);\n if (!alive) return null;\n try {\n const { mtimeMs } = await fs.stat(lockDirPath);\n if (Date.now() - mtimeMs > LIVE_HOLDER_RECLAIM_CEILING_MS) return null;\n } catch {\n return null;\n }\n return record;\n}\n\n/**\n * The `fs` proper-lockfile is given. Identical to `node:fs` except `rmdir`, which proper-lockfile calls\n * for exactly two reasons: to REMOVE A STALE LOCK before taking it (while acquiring) and to RELEASE its\n * own lock (once held, including its exit-time cleanup). Only the first is guarded, and a refusal is\n * returned as `ELOCKED` so the caller's retry policy and conflict mapping apply unchanged.\n */\nfunction createReclaimGuardedFs(phase: { acquiring: boolean }): typeof nodeFs {\n const rmdir = (lockDirPath: string, callback: (error: NodeJS.ErrnoException | null) => void): void => {\n if (!phase.acquiring) {\n nodeFs.rmdir(lockDirPath, callback);\n return;\n }\n liveHolderBlockingReclaim(lockDirPath).then(\n (holder) => {\n if (!holder) {\n nodeFs.rmdir(lockDirPath, callback);\n return;\n }\n callback(Object.assign(\n new Error(`Lock file is already being held by live process ${holder.pid} (its refresh is late, so it is not reclaimed)`),\n { code: 'ELOCKED', file: lockDirPath },\n ));\n },\n () => nodeFs.rmdir(lockDirPath, callback),\n );\n };\n return { ...nodeFs, rmdir } as typeof nodeFs;\n}\n\nfunction reportCompromiseToStderr(error: FileLockCompromisedError): void {\n process.stderr.write(`[wildo] ${error.message}\\n`);\n}\n\n/**\n * Acquire `lockTargetPath` (which must exist), run `fn` holding it, release it.\n *\n * - A lost lock never throws asynchronously. It marks the hold, `assertHeldFileLocksIntact()` refuses from\n * then on inside `fn`'s call chain, and the call rejects with {@link FileLockCompromisedError} once `fn`\n * settles — with `fn`'s own error as the cause when it failed too.\n * - Contention is still proper-lockfile's `ELOCKED`, including a refused reclaim of a live holder.\n */\nexport async function holdFileLock<T>(lockTargetPath: string, fn: () => Promise<T>, options: FileLockAcquireOptions): Promise<T> {\n const canonicalTarget = options.realpath ? await fs.realpath(lockTargetPath) : path.resolve(lockTargetPath);\n const lockDirPath = `${canonicalTarget}.lock`;\n const hold: FileLockHold = { lockTargetPath, compromise: null };\n const token = randomUUID();\n const phase = { acquiring: true };\n\n const release = await lockfile.lock(lockTargetPath, {\n retries: options.retries,\n stale: options.stale,\n realpath: options.realpath,\n fs: createReclaimGuardedFs(phase),\n onCompromised: (cause: Error) => {\n hold.compromise = new FileLockCompromisedError(lockTargetPath, cause);\n if (heldInThisProcess.get(lockDirPath) === token) heldInThisProcess.delete(lockDirPath);\n try {\n (options.onCompromised ?? reportCompromiseToStderr)(hold.compromise);\n } catch {\n // A logging callback must not reintroduce the uncaught exception this handler exists to remove.\n }\n },\n });\n phase.acquiring = false;\n heldInThisProcess.set(lockDirPath, token);\n const recordPath = fileLockHolderRecordPath(lockDirPath);\n try {\n await fs.mkdir(path.dirname(recordPath), { recursive: true, mode: 0o700 });\n if (!(await holderRecordDirectoryIsOurs())) throw new Error('holder record directory belongs to another user');\n const record: FileLockHolderRecord = { pid: process.pid, hostname: os.hostname(), token, acquiredAt: new Date().toISOString() };\n await fs.writeFile(recordPath, JSON.stringify(record), 'utf8');\n } catch {\n // Without a record the lock keeps proper-lockfile's plain mtime judgement — what it had before #2225.\n }\n\n const enclosing = heldFileLocks.getStore() ?? [];\n let value: T | undefined;\n let sectionFailed = false;\n let sectionError: unknown;\n try {\n value = await heldFileLocks.run([...enclosing, hold], fn);\n } catch (error) {\n sectionFailed = true;\n sectionError = error;\n }\n\n if (heldInThisProcess.get(lockDirPath) === token) heldInThisProcess.delete(lockDirPath);\n /*\n * The record goes AFTER the release, never before: the release is what the next acquirer is waiting\n * for, and a caller that saw this section settle may acquire again at once with no retries. A record\n * outliving its lock is harmless — the token check means it is only ever removed by its own hold, and\n * a stale record defends nothing once the directory it names is gone.\n */\n // Residual, accepted: the read and the remove are two steps, so an acquirer whose record lands between\n // them loses it and falls back to plain mtime staleness for that one hold — what every hold had before\n // #2225. The window is the gap between two filesystem calls, after this hold has already released.\n const forgetHolderRecord = async (): Promise<void> => {\n if ((await readHolderRecord(lockDirPath))?.token === token) await fs.rm(recordPath, { force: true }).catch(() => undefined);\n };\n\n if (hold.compromise) {\n // proper-lockfile has already dropped a compromised lock, so there is nothing of ours to release —\n // and the directory now belongs to whoever took it.\n await forgetHolderRecord();\n if (sectionFailed && sectionError !== hold.compromise) hold.compromise.sectionError = sectionError;\n throw hold.compromise;\n }\n try {\n await release();\n } catch (error) {\n // Lost between the check above and the release: same answer as a loss during the section.\n await forgetHolderRecord();\n if (hold.compromise) throw hold.compromise;\n throw error;\n }\n await forgetHolderRecord();\n if (sectionFailed) throw sectionError;\n return value as T;\n}\n"]}
@@ -36,6 +36,7 @@
36
36
  */
37
37
  import { z } from 'zod';
38
38
  import { type SaasLockfileEnvelope } from './wildo-saas-lock.shared.schemas';
39
+ import { type FileLockCompromisedError } from './file-lock-hold';
39
40
  /**
40
41
  * Canonical path of the saas-app lockfile, relative to the saas root.
41
42
  */
@@ -91,6 +92,8 @@ export type ResolvedLockOptions = {
91
92
  };
92
93
  readonly stale: number;
93
94
  readonly realpath: boolean;
95
+ /** See {@link DedicatedFileLockOptions.onCompromised}. */
96
+ readonly onCompromised?: (error: FileLockCompromisedError) => void;
94
97
  };
95
98
  export interface LockfileMutateOptions {
96
99
  /** Absolute path to the saas application root. */
@@ -176,9 +179,19 @@ export declare function withLockfileMutate(options: LockfileMutateOptions, mutat
176
179
  * - Parent directory + an empty placeholder file are created if missing
177
180
  * (`proper-lockfile` refuses ENOENT targets). The file content is never
178
181
  * read or written by this helper — it is a pure lock anchor.
179
- * - `proper-lockfile` auto-refreshes the lock mtime while the holder is
180
- * alive, so long-running holds survive the `stale` window; a crashed
181
- * holder's lock goes stale and is reclaimed by the next acquirer.
182
+ * - `proper-lockfile` refreshes the lock mtime every `stale / 2` while the
183
+ * holder is alive. That refresh can be LATE — an event-loop stall or a
184
+ * saturated threadpool — and the mtime alone would then read as stale.
185
+ * So a waiter's reclaim is refused while the recorded holder process is
186
+ * alive on this host (`holdFileLock`, #2225); a CRASHED holder's lock is
187
+ * still reclaimed after `stale`. Until #2225 this said long holds
188
+ * "survive the `stale` window" unconditionally, and a 2026-10-01 build
189
+ * wave showed they did not.
190
+ * - Losing the lock while held never exits the process: the call rejects
191
+ * with `FileLockCompromisedError` (`code: 'ECOMPROMISED'`) once `fn`
192
+ * settles, and `assertHeldFileLocksIntact()` refuses inside `fn` from
193
+ * the moment of the loss — call it before a commit or a write the lock
194
+ * serializes.
182
195
  * - Lock options merge over {@link DEFAULT_LOCK_OPTIONS}. Callers that
183
196
  * want fail-fast contention (HTTP 409 instead of queueing) pass
184
197
  * `{ retries: { retries: 0 } }`.
@@ -201,6 +214,11 @@ export interface DedicatedFileLockOptions {
201
214
  stale?: number;
202
215
  /** Keep `false` for symlinked (pnpm-injected) workspaces. */
203
216
  realpath?: boolean;
217
+ /**
218
+ * Told once if the lock is lost while held, for the caller's own log. The section still fails with
219
+ * `FileLockCompromisedError`. Omitted, one line goes to stderr.
220
+ */
221
+ onCompromised?: (error: FileLockCompromisedError) => void;
204
222
  }
205
223
  export declare function withDedicatedFileLock<T>(lockTargetPath: string, fn: () => Promise<T>, lockOptions?: DedicatedFileLockOptions): Promise<T>;
206
224
  /**
@@ -1 +1 @@
1
- {"version":3,"file":"lockfile-io.d.ts","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAMH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAEL,KAAK,oBAAoB,EAE1B,MAAM,kCAAkC,CAAC;AAE1C;;GAEG;AACH,eAAO,MAAM,6BAA6B,qCAAqC,CAAC;AAEhF;;GAEG;AACH,w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AC,CAAC,CAAC,CAAC;IAC5B,yDAAyD;IACzD,cAAc,EAAE,MAAM,CAAC,CAAC;CACzB,EACD,OAAO,EAAE,CAAC,OAAO,EAAE,CAAC,KAAK,CAAC,GAAG,IAAI,GAAG,OAAO,CAAC,CAAC,GAAG,IAAI,CAAC,GACpD,OAAO,CAAC,CAAC,CAAC,CAuBZ"}
@@ -36,9 +36,9 @@
36
36
  */
37
37
  import { promises as fs } from 'node:fs';
38
38
  import * as path from 'node:path';
39
- import lockfile from 'proper-lockfile';
40
39
  import writeFileAtomic from 'write-file-atomic';
41
40
  import { SaasLockfileEnvelopeSchema, } from './wildo-saas-lock.shared.schemas.js';
41
+ import { assertHeldFileLocksIntact, holdFileLock } from './file-lock-hold.js';
42
42
  /**
43
43
  * Canonical path of the saas-app lockfile, relative to the saas root.
44
44
  */
@@ -155,11 +155,13 @@ function validateAndNormalizeSections(sections, sectionSchemas) {
155
155
  /**
156
156
  * Acquire the OS-level lockfile lock, run `fn`, then release it.
157
157
  *
158
- * Wrapper around `proper-lockfile` that:
158
+ * Wrapper around `holdFileLock` (`./file-lock-hold`) that:
159
159
  * - Creates the parent dir + an empty file if missing (proper-lockfile
160
160
  * refuses to lock a non-existent file).
161
161
  * - Forwards `realpath: false` so symlinked workspaces lock correctly.
162
162
  * - Always releases the lock, even on error.
163
+ * - Inherits the live-holder reclaim guard and the compromise-as-error
164
+ * handling (#2225).
163
165
  */
164
166
  async function withLock(filePath, fn,
165
167
  // A MERGED value, not the defaults — see `ResolvedLockOptions`. Typing this as
@@ -175,13 +177,7 @@ lockOptions) {
175
177
  catch {
176
178
  await writeFileAtomicAsync(filePath, JSON.stringify(emptyEnvelope(), null, 2));
177
179
  }
178
- const release = await lockfile.lock(filePath, lockOptions);
179
- try {
180
- return await fn();
181
- }
182
- finally {
183
- await release();
184
- }
180
+ return holdFileLock(filePath, fn, lockOptions);
185
181
  }
186
182
  /** The one on-disk form of the envelope: two-space JSON with a trailing newline. */
187
183
  function serializeLockfile(envelope) {
@@ -248,6 +244,8 @@ export async function withLockfileMutate(options, mutator) {
248
244
  return { ...next, generatedAt: before.generatedAt };
249
245
  }
250
246
  next.generatedAt = new Date().toISOString();
247
+ // A writer that lost the lock mid-mutation would overwrite whoever took it (#2225).
248
+ assertHeldFileLocksIntact();
251
249
  await writeFileAtomicAsync(filePath, serializeLockfile(next));
252
250
  return next;
253
251
  }, lockOptions);
@@ -260,13 +258,7 @@ export async function withDedicatedFileLock(lockTargetPath, fn, lockOptions) {
260
258
  catch {
261
259
  await writeFileAtomicAsync(lockTargetPath, '');
262
260
  }
263
- const release = await lockfile.lock(lockTargetPath, mergeLockOptions(lockOptions));
264
- try {
265
- return await fn();
266
- }
267
- finally {
268
- await release();
269
- }
261
+ return holdFileLock(lockTargetPath, fn, mergeLockOptions(lockOptions));
270
262
  }
271
263
  /**
272
264
  * Canonical workspace-mutation lock target, app-root-relative. ONE constant
@@ -1 +1 @@
1
- {"version":3,"file":"lockfile-io.js","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAmCG;AAEH,OAAO,EAAE,QAAQ,IAAI,EAAE,EAAE,MAAM,SAAS,CAAC;AACzC,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,QAAQ,MAAM,iBAAiB,CAAC;AACvC,OAAO,eAAe,MAAM,mBAAmB,CAAC;AAEhD,OAAO,EACL,0BAA0B,GAG3B,MAAM,kCAAkC,CAAC;AAE1C;;GAEG;AACH,MAAM,CAAC,MAAM,6BAA6B,GAAG,kCAAkC,CAAC;AAEhF;;GAEG;AACH,MAAM,UAAU,oBAAoB,CAAC,QAAgB;IACnD,OAAO,IAAI,CAAC,OAAO,CAAC,QAAQ,EAAE,6BAA6B,CAAC,CAAC;AAC/D,CAAC;AAED;;;;;;;;;GASG;AACH,MAAM,CAAC,MAAM,oBAAoB,GAAG;IAClC,OAAO,EAAE,EAA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AAG,CAAC,GAAG,IAAI,MAAM,CAAM,CAAC;QAClC,sEAAsE;QACtE,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/C,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;IAC5C,CAAC,CACF,CAAC;IACF,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * Shared `wildo-saas.lock.json` IO primitives.\n *\n * Phase 1 graduates the locking + atomic-write surface validated by\n * the Phase 0.B contention spike (`module-registry-analysis.md`)\n * into `platform-config-lib`. Both the dev companion's\n * `WildoSaasLockCompanionService` and the CLI-side\n * `RegistryLockfileService` consume this module so concurrent\n * writers — across processes (CLI + companion + minions) — never\n * lose updates and never observe a half-written envelope.\n *\n * Exposes two layers:\n *\n * 1. `withLockfileMutate(opts, mutator)` — full-envelope mutate\n * under `proper-lockfile` + `write-file-atomic`. The companion\n * uses this so it can preserve its full-envelope contract and\n * validate its companion-owned i18n schema in the same pass.\n *\n * 2. `withLockfileSectionMutate(opts, mutator)` — section-scoped\n * mutate. The CLI uses this so it can ONLY touch one section\n * (e.g. `sections.modules`) and never accidentally clobber a\n * sibling section.\n *\n * Both layers preserve unknown sections verbatim — every consumer\n * MUST round-trip every `sections.*` key it does not recognize.\n *\n * Hard contract (KD-4 / KD-15 / KD-18):\n * - The library NEVER writes provider runtime artifacts under\n * `.wildo-saas/generated/providers/*.runtime-providers.generated.json` or\n * `src/generated/wildo-provider-runtime.generated.ts`. Those are\n * produced by the provider materialization workflow alone.\n * - `sections.providers.runtimeScopes` is owned end-to-end by the\n * provider workstream; module-registry callers MUST NOT mutate it.\n * This module is unaware of the provider section beyond\n * preserving its bytes.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport lockfile from 'proper-lockfile';\nimport writeFileAtomic from 'write-file-atomic';\nimport { z } from 'zod';\nimport {\n SaasLockfileEnvelopeSchema,\n type SaasLockfileEnvelope,\n type SaasLockfileKnownSections,\n} from './wildo-saas-lock.shared.schemas';\n\n/**\n * Canonical path of the saas-app lockfile, relative to the saas root.\n */\nexport const WILDO_SAAS_LOCK_RELATIVE_PATH = '.wildo-saas/wildo-saas.lock.json';\n\n/**\n * Build the absolute lockfile path for a given saas root.\n */\nexport function getWildoSaasLockPath(saasRoot: string): string {\n return path.resolve(saasRoot, WILDO_SAAS_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Default `proper-lockfile` options. The 5s `stale` window matches\n * the Phase 0.B spike (`module-registry-analysis.md` Phase 0.B\n * Findings): typical lock-hold time is < 50ms; 5s is generous enough\n * to absorb a CI pause without compromising legitimate locks. Tests\n * 4a-4d all passed under these settings.\n *\n * `realpath: false` is required when the saas root is symlinked\n * (common with pnpm `dependenciesMeta.injected: true` workspaces).\n */\nexport const DEFAULT_LOCK_OPTIONS = {\n retries: { retries: 200, minTimeout: 5, maxTimeout: 50, factor: 1.2 },\n stale: 5000,\n realpath: false,\n} as const satisfies Parameters<typeof lockfile.lock>[1];\n\n/**\n * The result of merging caller options over {@link DEFAULT_LOCK_OPTIONS}.\n *\n * Its leaves are WIDENED (`number` / `boolean`) and that is the point: the\n * defaults are `as const`, so `typeof DEFAULT_LOCK_OPTIONS` describes those exact\n * literals — `stale: 5000`, `realpath: false`. A merge that honours a caller\n * override cannot satisfy it, because an overridden `stale` is not `5000`.\n *\n * Annotating the merge as `typeof DEFAULT_LOCK_OPTIONS` claimed the result was\n * always the defaults, which is true only when nothing was overridden — i.e. in\n * the one case the function exists to avoid.\n */\nexport type ResolvedLockOptions = {\n /**\n * Either a retry POLICY or a bare attempt count — `proper-lockfile` accepts\n * both, and the merge passes a bare number straight through\n * (`overrideRetries ?? baseRetries`). Omitting `number` made the merge unable to\n * describe its own fallback branch.\n */\n readonly retries: number | { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n readonly stale: number;\n readonly realpath: boolean;\n};\n\n/**\n * Deep-merge caller-supplied lock options on top of `DEFAULT_LOCK_OPTIONS`.\n *\n * Phase 1 review (M-2.1): a shallow merge replaced the entire\n * `retries` object whenever a caller passed a partial — so\n * `lockOptions: { retries: { retries: 5 } }` silently lost the\n * `minTimeout`/`maxTimeout`/`factor` defaults that Phase 0.B\n * validated. The deep merge keeps every default intact unless\n * the caller explicitly overrides each leaf.\n */\nfunction mergeLockOptions(\n // `DedicatedFileLockOptions`, NOT `Partial<typeof DEFAULT_LOCK_OPTIONS>`: that constant is\n // `as const`, so every leaf is a LITERAL type and `Partial` only reaches the top level — which\n // made the very call shape this merge exists to support (`{ retries: { retries: 5 } }`) a type\n // error, because `5` is not `200`. It also removes the cast the dedicated-lock caller needed.\n override?: DedicatedFileLockOptions,\n): ResolvedLockOptions {\n if (!override) return DEFAULT_LOCK_OPTIONS;\n const baseRetries = DEFAULT_LOCK_OPTIONS.retries;\n const overrideRetries = override.retries;\n const mergedRetries =\n typeof overrideRetries === 'object' && overrideRetries !== null\n ? { ...baseRetries, ...overrideRetries }\n : overrideRetries ?? baseRetries;\n return {\n ...DEFAULT_LOCK_OPTIONS,\n ...override,\n retries: mergedRetries,\n };\n}\n\nexport interface LockfileMutateOptions {\n /** Absolute path to the saas application root. */\n saasRoot: string;\n /**\n * Optional Zod schemas to validate sibling sections at parse time.\n * Companion-owned sections (e.g. `i18n`) are validated by passing\n * them here. CLI callers can pass\n * `DEFAULT_REGISTRY_SECTION_SCHEMAS` to validate `modules`.\n *\n * Sections not listed here are still PRESERVED on round-trip via\n * the envelope's `.catchall(z.unknown())` — they are simply not\n * type-narrowed.\n */\n sectionSchemas?: Record<string, z.ZodTypeAny>;\n /**\n * Override `proper-lockfile` options. Phase 0.B's measurements\n * suggest the defaults are fine for both CLI and companion\n * call patterns; this hook exists for tests + tuning.\n */\n lockOptions?: DedicatedFileLockOptions;\n /**\n * If true (default), the lockfile is created on first read with an\n * empty `sections` map. Set to false to fail with ENOENT.\n */\n createIfMissing?: boolean;\n}\n\n/**\n * Read the lockfile envelope, applying schema validation.\n *\n * - Returns a fresh empty envelope if the file does not exist\n * (and `createIfMissing` is not explicitly false).\n * - Validates the canonical envelope shape (schemaVersion, generatedAt,\n * sections) against `SaasLockfileEnvelopeSchema`.\n * - Applies caller-supplied `sectionSchemas` after the envelope\n * shape passes — failures throw a `ZodError` so the caller knows\n * exactly which section + field rejected.\n *\n * Does NOT acquire a lock; reads are unsynchronized. Callers that\n * need read-after-write coherence must read INSIDE `withLockfileMutate`.\n */\nexport async function readWildoSaasLock(\n options: Pick<LockfileMutateOptions, 'saasRoot' | 'sectionSchemas' | 'createIfMissing'>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT' && options.createIfMissing !== false) {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n }\n throw err;\n }\n const json = JSON.parse(raw) as unknown;\n const envelope = SaasLockfileEnvelopeSchema.parse(json);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(envelope.sections, options.sectionSchemas);\n }\n return envelope;\n}\n\n/**\n * Validate every present `sections.<key>` against its caller-supplied\n * Zod schema AND write the parsed (default-expanded) value back so\n * defaults declared in those schemas actually persist on disk.\n *\n * Phase 1 review (H-2.1 / M-1.2): the prior implementation called\n * `.parse(value)` and discarded the result, which meant\n * `.default(...)` clauses in section schemas were only ever applied\n * during validation — never written. Schemas with shallow defaults\n * (e.g. `installed: z.record(...).default({})`) tolerated the bug\n * because mutators always set `installed` directly, but a future\n * schema with deep defaults would silently lose them.\n */\nfunction validateAndNormalizeSections(\n sections: SaasLockfileKnownSections,\n sectionSchemas: Record<string, z.ZodTypeAny>,\n): void {\n const mutable = sections as Record<string, unknown>;\n for (const [key, schema] of Object.entries(sectionSchemas)) {\n const value = mutable[key];\n if (value === undefined) continue;\n mutable[key] = schema.parse(value);\n }\n}\n\n/**\n * Acquire the OS-level lockfile lock, run `fn`, then release it.\n *\n * Wrapper around `proper-lockfile` that:\n * - Creates the parent dir + an empty file if missing (proper-lockfile\n * refuses to lock a non-existent file).\n * - Forwards `realpath: false` so symlinked workspaces lock correctly.\n * - Always releases the lock, even on error.\n */\nasync function withLock<T>(\n filePath: string,\n fn: () => Promise<T>,\n // A MERGED value, not the defaults — see `ResolvedLockOptions`. Typing this as\n // `typeof DEFAULT_LOCK_OPTIONS` demanded the literal `200`/`5000`/`false`, so any\n // caller-overridden option was a type error at the point of USE rather than at\n // the point of override, which is why it read as a failure in the merge.\n lockOptions: ResolvedLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n // Ensure the file exists; `proper-lockfile.lock` refuses ENOENT.\n try {\n await fs.access(filePath);\n } catch {\n await writeFileAtomicAsync(filePath, JSON.stringify(emptyEnvelope(), null, 2));\n }\n const release = await lockfile.lock(filePath, lockOptions);\n try {\n return await fn();\n } finally {\n await release();\n }\n}\n\n/** The one on-disk form of the envelope: two-space JSON with a trailing newline. */\nfunction serializeLockfile(envelope: SaasLockfileEnvelope): string {\n return JSON.stringify(envelope, null, 2) + '\\n';\n}\n\nfunction emptyEnvelope(): SaasLockfileEnvelope {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n}\n\nasync function writeFileAtomicAsync(filePath: string, content: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n writeFileAtomic(filePath, content, (err: Error | undefined) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n\n/**\n * Read-modify-write a lockfile under an OS-level lock.\n *\n * The mutator receives a deep-cloned, schema-validated envelope —\n * any in-place mutation is safe and won't bleed back into the\n * pre-write copy. After the mutator returns, the result is\n * re-validated against the envelope schema (and any caller-supplied\n * `sectionSchemas`) before being atomically written.\n *\n * `generatedAt` is refreshed only when the mutation changes the file. When the bytes that would be\n * written — with the previous `generatedAt` — equal the bytes on disk, nothing is written and the\n * envelope is returned as it was. The lockfile is committed, and a timestamp that moved on every no-op\n * sync dirtied the tree with nothing in it: a `wildo registry add` + `remove` round trip left exactly\n * one diff, this field (#1765). The comparison is on BYTES rather than on the parsed sections so a\n * no-op mutation still writes back what normalization changed (schema defaults, a missing trailing\n * newline).\n *\n * The library never inspects `sections.providers.runtimeScopes`,\n * `sections.modules`, or `sections.i18n` — it only enforces the\n * envelope shape. Concrete section semantics live in their owning\n * subsystems.\n */\nexport async function withLockfileMutate(\n options: LockfileMutateOptions,\n mutator: (envelope: SaasLockfileEnvelope) => void | Promise<void>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n const lockOptions = mergeLockOptions(options.lockOptions);\n return withLock(filePath, async () => {\n const before = await readWildoSaasLock({\n saasRoot: options.saasRoot,\n sectionSchemas: options.sectionSchemas,\n createIfMissing: true,\n });\n const next: SaasLockfileEnvelope = structuredClone(before);\n await mutator(next);\n // Re-validate AFTER mutation; the mutator may have introduced\n // structurally-invalid input.\n SaasLockfileEnvelopeSchema.parse(next);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(next.sections, options.sectionSchemas);\n }\n const onDisk = await fs.readFile(filePath, 'utf8').catch(() => null);\n if (onDisk === serializeLockfile({ ...next, generatedAt: before.generatedAt })) {\n return { ...next, generatedAt: before.generatedAt };\n }\n next.generatedAt = new Date().toISOString();\n await writeFileAtomicAsync(filePath, serializeLockfile(next));\n return next;\n }, lockOptions);\n}\n\n/**\n * Hold an OS-level `proper-lockfile` lock on an ARBITRARY dedicated lock\n * target while `fn` runs — the path-parameterized sibling of\n * `withLockfileMutate` for callers that need cross-process mutual\n * exclusion WITHOUT the `wildo-saas.lock.json` envelope semantics.\n *\n * Why this exists (meta-workflows P-20, 2026-07-03): the companion's\n * coding-agent dispatch lane serializes workspace mutations on a\n * dedicated target (`<saasRoot>/.wildo-saas/state/workspace-mutation.lock`)\n * held for the WHOLE agent run (minutes). Routing that through\n * `withLockfileMutate` would hold the shared saas lockfile hostage —\n * starving i18n/registry writers — and the envelope re-validation is\n * meaningless for a pure mutex. The primitive lives HERE (not\n * companion-local) so the CLI can adopt the SAME lock target with the\n * SAME semantics when its worktree-mutating commands learn to respect it.\n *\n * Semantics:\n * - Parent directory + an empty placeholder file are created if missing\n * (`proper-lockfile` refuses ENOENT targets). The file content is never\n * read or written by this helper — it is a pure lock anchor.\n * - `proper-lockfile` auto-refreshes the lock mtime while the holder is\n * alive, so long-running holds survive the `stale` window; a crashed\n * holder's lock goes stale and is reclaimed by the next acquirer.\n * - Lock options merge over {@link DEFAULT_LOCK_OPTIONS}. Callers that\n * want fail-fast contention (HTTP 409 instead of queueing) pass\n * `{ retries: { retries: 0 } }`.\n * - The lock is always released (or at least attempted) on completion,\n * including the error path.\n *\n * Contention surfaces as the `proper-lockfile` `ELOCKED` error\n * (`error.code === 'ELOCKED'`) — callers map it to their own conflict\n * vocabulary.\n */\nexport interface DedicatedFileLockOptions {\n /** `proper-lockfile` retry policy — `{ retries: { retries: 0 } }` = fail-fast contention. */\n retries?: { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n /** Stale window in ms (lock mtime auto-refreshes while the holder lives). */\n stale?: number;\n /** Keep `false` for symlinked (pnpm-injected) workspaces. */\n realpath?: boolean;\n}\n\nexport async function withDedicatedFileLock<T>(\n lockTargetPath: string,\n fn: () => Promise<T>,\n lockOptions?: DedicatedFileLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(lockTargetPath), { recursive: true });\n try {\n await fs.access(lockTargetPath);\n } catch {\n await writeFileAtomicAsync(lockTargetPath, '');\n }\n const release = await lockfile.lock(\n lockTargetPath,\n mergeLockOptions(lockOptions),\n );\n try {\n return await fn();\n } finally {\n await release();\n }\n}\n\n/**\n * Canonical workspace-mutation lock target, app-root-relative. ONE constant\n * shared by every process that mutates the application worktree in a way\n * that must serialize against coding-agent dispatch runs (meta-workflows\n * P-20): the companion's dispatch lane holds it for the whole agent run;\n * CLI worktree-writers (e.g. `wildo config sync`) acquire it fail-fast\n * around their write phase. Deliberately NOT taken by human/parallel-session\n * edits (P-19b — per-file attribution compensates, never exclusion).\n * Keep companion and CLI on THIS constant — a hand-copied path is drift.\n */\nexport const WORKSPACE_MUTATION_LOCK_RELATIVE_PATH: string =\n '.wildo-saas/state/workspace-mutation.lock';\n\n/** Absolute workspace-mutation lock target for an application root. */\nexport function getWorkspaceMutationLockPath(saasRoot: string): string {\n return path.join(saasRoot, WORKSPACE_MUTATION_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Section-scoped mutate. The mutator only sees one section's payload\n * (`sections.<sectionKey>`) and CANNOT reach sibling sections —\n * preventing accidental clobbers. Returns the mutated section.\n *\n * Use this from CLI callers (`RegistryLockfileService`) so cross-\n * section bugs are impossible by construction. Companion callers\n * that legitimately need full-envelope access keep using\n * `withLockfileMutate` directly.\n */\nexport async function withLockfileSectionMutate<S>(\n options: LockfileMutateOptions & {\n /** Section key under `sections` (e.g. `'modules'`, `'i18n'`). */\n sectionKey: string;\n /** Zod schema validating the section payload. Required. */\n sectionSchema: z.ZodType<S>;\n /** Initial value when the section does not yet exist. */\n initialSection: () => S;\n },\n mutator: (section: S) => S | void | Promise<S | void>,\n): Promise<S> {\n let mutatedOut!: S;\n await withLockfileMutate(\n {\n saasRoot: options.saasRoot,\n lockOptions: options.lockOptions,\n sectionSchemas: {\n ...options.sectionSchemas,\n [options.sectionKey]: options.sectionSchema,\n },\n },\n async (envelope) => {\n const sections = envelope.sections as Record<string, unknown>;\n const current = (sections[options.sectionKey] as S | undefined) ?? options.initialSection();\n const cloned = structuredClone(current);\n const ret = await mutator(cloned);\n const next = (ret ?? cloned) as S;\n // Per-section validation (also covers initial-default re-validation).\n mutatedOut = options.sectionSchema.parse(next);\n sections[options.sectionKey] = mutatedOut;\n },\n );\n return mutatedOut;\n}\n"]}
1
+ {"version":3,"file":"lockfile-io.js","sourceRoot":"","sources":["../../../../src/lockfile/lockfile-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;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O,CAAC,aAAa;SAC5C;KACF,EACD,KAAK,EAAE,QAAQ,EAAE,EAAE;QACjB,MAAM,QAAQ,GAAG,QAAQ,CAAC,QAAmC,CAAC;QAC9D,MAAM,OAAO,GAAI,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAmB,IAAI,OAAO,CAAC,cAAc,EAAE,CAAC;QAC5F,MAAM,MAAM,GAAG,eAAe,CAAC,OAAO,CAAC,CAAC;QACxC,MAAM,GAAG,GAAG,MAAM,OAAO,CAAC,MAAM,CAAC,CAAC;QAClC,MAAM,IAAI,GAAG,CAAC,GAAG,IAAI,MAAM,CAAM,CAAC;QAClC,sEAAsE;QACtE,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC;QAC/C,QAAQ,CAAC,OAAO,CAAC,UAAU,CAAC,GAAG,UAAU,CAAC;IAC5C,CAAC,CACF,CAAC;IACF,OAAO,UAAU,CAAC;AACpB,CAAC","sourcesContent":["/**\n * Shared `wildo-saas.lock.json` IO primitives.\n *\n * Phase 1 graduates the locking + atomic-write surface validated by\n * the Phase 0.B contention spike (`module-registry-analysis.md`)\n * into `platform-config-lib`. Both the dev companion's\n * `WildoSaasLockCompanionService` and the CLI-side\n * `RegistryLockfileService` consume this module so concurrent\n * writers — across processes (CLI + companion + minions) — never\n * lose updates and never observe a half-written envelope.\n *\n * Exposes two layers:\n *\n * 1. `withLockfileMutate(opts, mutator)` — full-envelope mutate\n * under `proper-lockfile` + `write-file-atomic`. The companion\n * uses this so it can preserve its full-envelope contract and\n * validate its companion-owned i18n schema in the same pass.\n *\n * 2. `withLockfileSectionMutate(opts, mutator)` — section-scoped\n * mutate. The CLI uses this so it can ONLY touch one section\n * (e.g. `sections.modules`) and never accidentally clobber a\n * sibling section.\n *\n * Both layers preserve unknown sections verbatim — every consumer\n * MUST round-trip every `sections.*` key it does not recognize.\n *\n * Hard contract (KD-4 / KD-15 / KD-18):\n * - The library NEVER writes provider runtime artifacts under\n * `.wildo-saas/generated/providers/*.runtime-providers.generated.json` or\n * `src/generated/wildo-provider-runtime.generated.ts`. Those are\n * produced by the provider materialization workflow alone.\n * - `sections.providers.runtimeScopes` is owned end-to-end by the\n * provider workstream; module-registry callers MUST NOT mutate it.\n * This module is unaware of the provider section beyond\n * preserving its bytes.\n */\n\nimport { promises as fs } from 'node:fs';\nimport * as path from 'node:path';\nimport type lockfile from 'proper-lockfile';\nimport writeFileAtomic from 'write-file-atomic';\nimport { z } from 'zod';\nimport {\n SaasLockfileEnvelopeSchema,\n type SaasLockfileEnvelope,\n type SaasLockfileKnownSections,\n} from './wildo-saas-lock.shared.schemas';\nimport { assertHeldFileLocksIntact, holdFileLock, type FileLockCompromisedError } from './file-lock-hold';\n\n/**\n * Canonical path of the saas-app lockfile, relative to the saas root.\n */\nexport const WILDO_SAAS_LOCK_RELATIVE_PATH = '.wildo-saas/wildo-saas.lock.json';\n\n/**\n * Build the absolute lockfile path for a given saas root.\n */\nexport function getWildoSaasLockPath(saasRoot: string): string {\n return path.resolve(saasRoot, WILDO_SAAS_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Default `proper-lockfile` options. The 5s `stale` window matches\n * the Phase 0.B spike (`module-registry-analysis.md` Phase 0.B\n * Findings): typical lock-hold time is < 50ms; 5s is generous enough\n * to absorb a CI pause without compromising legitimate locks. Tests\n * 4a-4d all passed under these settings.\n *\n * `realpath: false` is required when the saas root is symlinked\n * (common with pnpm `dependenciesMeta.injected: true` workspaces).\n */\nexport const DEFAULT_LOCK_OPTIONS = {\n retries: { retries: 200, minTimeout: 5, maxTimeout: 50, factor: 1.2 },\n stale: 5000,\n realpath: false,\n} as const satisfies Parameters<typeof lockfile.lock>[1];\n\n/**\n * The result of merging caller options over {@link DEFAULT_LOCK_OPTIONS}.\n *\n * Its leaves are WIDENED (`number` / `boolean`) and that is the point: the\n * defaults are `as const`, so `typeof DEFAULT_LOCK_OPTIONS` describes those exact\n * literals — `stale: 5000`, `realpath: false`. A merge that honours a caller\n * override cannot satisfy it, because an overridden `stale` is not `5000`.\n *\n * Annotating the merge as `typeof DEFAULT_LOCK_OPTIONS` claimed the result was\n * always the defaults, which is true only when nothing was overridden — i.e. in\n * the one case the function exists to avoid.\n */\nexport type ResolvedLockOptions = {\n /**\n * Either a retry POLICY or a bare attempt count — `proper-lockfile` accepts\n * both, and the merge passes a bare number straight through\n * (`overrideRetries ?? baseRetries`). Omitting `number` made the merge unable to\n * describe its own fallback branch.\n */\n readonly retries: number | { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n readonly stale: number;\n readonly realpath: boolean;\n /** See {@link DedicatedFileLockOptions.onCompromised}. */\n readonly onCompromised?: (error: FileLockCompromisedError) => void;\n};\n\n/**\n * Deep-merge caller-supplied lock options on top of `DEFAULT_LOCK_OPTIONS`.\n *\n * Phase 1 review (M-2.1): a shallow merge replaced the entire\n * `retries` object whenever a caller passed a partial — so\n * `lockOptions: { retries: { retries: 5 } }` silently lost the\n * `minTimeout`/`maxTimeout`/`factor` defaults that Phase 0.B\n * validated. The deep merge keeps every default intact unless\n * the caller explicitly overrides each leaf.\n */\nfunction mergeLockOptions(\n // `DedicatedFileLockOptions`, NOT `Partial<typeof DEFAULT_LOCK_OPTIONS>`: that constant is\n // `as const`, so every leaf is a LITERAL type and `Partial` only reaches the top level — which\n // made the very call shape this merge exists to support (`{ retries: { retries: 5 } }`) a type\n // error, because `5` is not `200`. It also removes the cast the dedicated-lock caller needed.\n override?: DedicatedFileLockOptions,\n): ResolvedLockOptions {\n if (!override) return DEFAULT_LOCK_OPTIONS;\n const baseRetries = DEFAULT_LOCK_OPTIONS.retries;\n const overrideRetries = override.retries;\n const mergedRetries =\n typeof overrideRetries === 'object' && overrideRetries !== null\n ? { ...baseRetries, ...overrideRetries }\n : overrideRetries ?? baseRetries;\n return {\n ...DEFAULT_LOCK_OPTIONS,\n ...override,\n retries: mergedRetries,\n };\n}\n\nexport interface LockfileMutateOptions {\n /** Absolute path to the saas application root. */\n saasRoot: string;\n /**\n * Optional Zod schemas to validate sibling sections at parse time.\n * Companion-owned sections (e.g. `i18n`) are validated by passing\n * them here. CLI callers can pass\n * `DEFAULT_REGISTRY_SECTION_SCHEMAS` to validate `modules`.\n *\n * Sections not listed here are still PRESERVED on round-trip via\n * the envelope's `.catchall(z.unknown())` — they are simply not\n * type-narrowed.\n */\n sectionSchemas?: Record<string, z.ZodTypeAny>;\n /**\n * Override `proper-lockfile` options. Phase 0.B's measurements\n * suggest the defaults are fine for both CLI and companion\n * call patterns; this hook exists for tests + tuning.\n */\n lockOptions?: DedicatedFileLockOptions;\n /**\n * If true (default), the lockfile is created on first read with an\n * empty `sections` map. Set to false to fail with ENOENT.\n */\n createIfMissing?: boolean;\n}\n\n/**\n * Read the lockfile envelope, applying schema validation.\n *\n * - Returns a fresh empty envelope if the file does not exist\n * (and `createIfMissing` is not explicitly false).\n * - Validates the canonical envelope shape (schemaVersion, generatedAt,\n * sections) against `SaasLockfileEnvelopeSchema`.\n * - Applies caller-supplied `sectionSchemas` after the envelope\n * shape passes — failures throw a `ZodError` so the caller knows\n * exactly which section + field rejected.\n *\n * Does NOT acquire a lock; reads are unsynchronized. Callers that\n * need read-after-write coherence must read INSIDE `withLockfileMutate`.\n */\nexport async function readWildoSaasLock(\n options: Pick<LockfileMutateOptions, 'saasRoot' | 'sectionSchemas' | 'createIfMissing'>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n let raw: string;\n try {\n raw = await fs.readFile(filePath, 'utf8');\n } catch (err) {\n if ((err as NodeJS.ErrnoException).code === 'ENOENT' && options.createIfMissing !== false) {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n }\n throw err;\n }\n const json = JSON.parse(raw) as unknown;\n const envelope = SaasLockfileEnvelopeSchema.parse(json);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(envelope.sections, options.sectionSchemas);\n }\n return envelope;\n}\n\n/**\n * Validate every present `sections.<key>` against its caller-supplied\n * Zod schema AND write the parsed (default-expanded) value back so\n * defaults declared in those schemas actually persist on disk.\n *\n * Phase 1 review (H-2.1 / M-1.2): the prior implementation called\n * `.parse(value)` and discarded the result, which meant\n * `.default(...)` clauses in section schemas were only ever applied\n * during validation — never written. Schemas with shallow defaults\n * (e.g. `installed: z.record(...).default({})`) tolerated the bug\n * because mutators always set `installed` directly, but a future\n * schema with deep defaults would silently lose them.\n */\nfunction validateAndNormalizeSections(\n sections: SaasLockfileKnownSections,\n sectionSchemas: Record<string, z.ZodTypeAny>,\n): void {\n const mutable = sections as Record<string, unknown>;\n for (const [key, schema] of Object.entries(sectionSchemas)) {\n const value = mutable[key];\n if (value === undefined) continue;\n mutable[key] = schema.parse(value);\n }\n}\n\n/**\n * Acquire the OS-level lockfile lock, run `fn`, then release it.\n *\n * Wrapper around `holdFileLock` (`./file-lock-hold`) that:\n * - Creates the parent dir + an empty file if missing (proper-lockfile\n * refuses to lock a non-existent file).\n * - Forwards `realpath: false` so symlinked workspaces lock correctly.\n * - Always releases the lock, even on error.\n * - Inherits the live-holder reclaim guard and the compromise-as-error\n * handling (#2225).\n */\nasync function withLock<T>(\n filePath: string,\n fn: () => Promise<T>,\n // A MERGED value, not the defaults — see `ResolvedLockOptions`. Typing this as\n // `typeof DEFAULT_LOCK_OPTIONS` demanded the literal `200`/`5000`/`false`, so any\n // caller-overridden option was a type error at the point of USE rather than at\n // the point of override, which is why it read as a failure in the merge.\n lockOptions: ResolvedLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(filePath), { recursive: true });\n // Ensure the file exists; `proper-lockfile.lock` refuses ENOENT.\n try {\n await fs.access(filePath);\n } catch {\n await writeFileAtomicAsync(filePath, JSON.stringify(emptyEnvelope(), null, 2));\n }\n return holdFileLock(filePath, fn, lockOptions);\n}\n\n/** The one on-disk form of the envelope: two-space JSON with a trailing newline. */\nfunction serializeLockfile(envelope: SaasLockfileEnvelope): string {\n return JSON.stringify(envelope, null, 2) + '\\n';\n}\n\nfunction emptyEnvelope(): SaasLockfileEnvelope {\n return {\n schemaVersion: 2,\n generatedAt: new Date().toISOString(),\n sections: {},\n };\n}\n\nasync function writeFileAtomicAsync(filePath: string, content: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n writeFileAtomic(filePath, content, (err: Error | undefined) => {\n if (err) reject(err);\n else resolve();\n });\n });\n}\n\n/**\n * Read-modify-write a lockfile under an OS-level lock.\n *\n * The mutator receives a deep-cloned, schema-validated envelope —\n * any in-place mutation is safe and won't bleed back into the\n * pre-write copy. After the mutator returns, the result is\n * re-validated against the envelope schema (and any caller-supplied\n * `sectionSchemas`) before being atomically written.\n *\n * `generatedAt` is refreshed only when the mutation changes the file. When the bytes that would be\n * written — with the previous `generatedAt` — equal the bytes on disk, nothing is written and the\n * envelope is returned as it was. The lockfile is committed, and a timestamp that moved on every no-op\n * sync dirtied the tree with nothing in it: a `wildo registry add` + `remove` round trip left exactly\n * one diff, this field (#1765). The comparison is on BYTES rather than on the parsed sections so a\n * no-op mutation still writes back what normalization changed (schema defaults, a missing trailing\n * newline).\n *\n * The library never inspects `sections.providers.runtimeScopes`,\n * `sections.modules`, or `sections.i18n` — it only enforces the\n * envelope shape. Concrete section semantics live in their owning\n * subsystems.\n */\nexport async function withLockfileMutate(\n options: LockfileMutateOptions,\n mutator: (envelope: SaasLockfileEnvelope) => void | Promise<void>,\n): Promise<SaasLockfileEnvelope> {\n const filePath = getWildoSaasLockPath(options.saasRoot);\n const lockOptions = mergeLockOptions(options.lockOptions);\n return withLock(filePath, async () => {\n const before = await readWildoSaasLock({\n saasRoot: options.saasRoot,\n sectionSchemas: options.sectionSchemas,\n createIfMissing: true,\n });\n const next: SaasLockfileEnvelope = structuredClone(before);\n await mutator(next);\n // Re-validate AFTER mutation; the mutator may have introduced\n // structurally-invalid input.\n SaasLockfileEnvelopeSchema.parse(next);\n if (options.sectionSchemas) {\n validateAndNormalizeSections(next.sections, options.sectionSchemas);\n }\n const onDisk = await fs.readFile(filePath, 'utf8').catch(() => null);\n if (onDisk === serializeLockfile({ ...next, generatedAt: before.generatedAt })) {\n return { ...next, generatedAt: before.generatedAt };\n }\n next.generatedAt = new Date().toISOString();\n // A writer that lost the lock mid-mutation would overwrite whoever took it (#2225).\n assertHeldFileLocksIntact();\n await writeFileAtomicAsync(filePath, serializeLockfile(next));\n return next;\n }, lockOptions);\n}\n\n/**\n * Hold an OS-level `proper-lockfile` lock on an ARBITRARY dedicated lock\n * target while `fn` runs — the path-parameterized sibling of\n * `withLockfileMutate` for callers that need cross-process mutual\n * exclusion WITHOUT the `wildo-saas.lock.json` envelope semantics.\n *\n * Why this exists (meta-workflows P-20, 2026-07-03): the companion's\n * coding-agent dispatch lane serializes workspace mutations on a\n * dedicated target (`<saasRoot>/.wildo-saas/state/workspace-mutation.lock`)\n * held for the WHOLE agent run (minutes). Routing that through\n * `withLockfileMutate` would hold the shared saas lockfile hostage —\n * starving i18n/registry writers — and the envelope re-validation is\n * meaningless for a pure mutex. The primitive lives HERE (not\n * companion-local) so the CLI can adopt the SAME lock target with the\n * SAME semantics when its worktree-mutating commands learn to respect it.\n *\n * Semantics:\n * - Parent directory + an empty placeholder file are created if missing\n * (`proper-lockfile` refuses ENOENT targets). The file content is never\n * read or written by this helper — it is a pure lock anchor.\n * - `proper-lockfile` refreshes the lock mtime every `stale / 2` while the\n * holder is alive. That refresh can be LATE — an event-loop stall or a\n * saturated threadpool — and the mtime alone would then read as stale.\n * So a waiter's reclaim is refused while the recorded holder process is\n * alive on this host (`holdFileLock`, #2225); a CRASHED holder's lock is\n * still reclaimed after `stale`. Until #2225 this said long holds\n * \"survive the `stale` window\" unconditionally, and a 2026-10-01 build\n * wave showed they did not.\n * - Losing the lock while held never exits the process: the call rejects\n * with `FileLockCompromisedError` (`code: 'ECOMPROMISED'`) once `fn`\n * settles, and `assertHeldFileLocksIntact()` refuses inside `fn` from\n * the moment of the loss — call it before a commit or a write the lock\n * serializes.\n * - Lock options merge over {@link DEFAULT_LOCK_OPTIONS}. Callers that\n * want fail-fast contention (HTTP 409 instead of queueing) pass\n * `{ retries: { retries: 0 } }`.\n * - The lock is always released (or at least attempted) on completion,\n * including the error path.\n *\n * Contention surfaces as the `proper-lockfile` `ELOCKED` error\n * (`error.code === 'ELOCKED'`) — callers map it to their own conflict\n * vocabulary.\n */\nexport interface DedicatedFileLockOptions {\n /** `proper-lockfile` retry policy — `{ retries: { retries: 0 } }` = fail-fast contention. */\n retries?: { retries?: number; minTimeout?: number; maxTimeout?: number; factor?: number };\n /** Stale window in ms (lock mtime auto-refreshes while the holder lives). */\n stale?: number;\n /** Keep `false` for symlinked (pnpm-injected) workspaces. */\n realpath?: boolean;\n /**\n * Told once if the lock is lost while held, for the caller's own log. The section still fails with\n * `FileLockCompromisedError`. Omitted, one line goes to stderr.\n */\n onCompromised?: (error: FileLockCompromisedError) => void;\n}\n\nexport async function withDedicatedFileLock<T>(\n lockTargetPath: string,\n fn: () => Promise<T>,\n lockOptions?: DedicatedFileLockOptions,\n): Promise<T> {\n await fs.mkdir(path.dirname(lockTargetPath), { recursive: true });\n try {\n await fs.access(lockTargetPath);\n } catch {\n await writeFileAtomicAsync(lockTargetPath, '');\n }\n return holdFileLock(lockTargetPath, fn, mergeLockOptions(lockOptions));\n}\n\n/**\n * Canonical workspace-mutation lock target, app-root-relative. ONE constant\n * shared by every process that mutates the application worktree in a way\n * that must serialize against coding-agent dispatch runs (meta-workflows\n * P-20): the companion's dispatch lane holds it for the whole agent run;\n * CLI worktree-writers (e.g. `wildo config sync`) acquire it fail-fast\n * around their write phase. Deliberately NOT taken by human/parallel-session\n * edits (P-19b — per-file attribution compensates, never exclusion).\n * Keep companion and CLI on THIS constant — a hand-copied path is drift.\n */\nexport const WORKSPACE_MUTATION_LOCK_RELATIVE_PATH: string =\n '.wildo-saas/state/workspace-mutation.lock';\n\n/** Absolute workspace-mutation lock target for an application root. */\nexport function getWorkspaceMutationLockPath(saasRoot: string): string {\n return path.join(saasRoot, WORKSPACE_MUTATION_LOCK_RELATIVE_PATH);\n}\n\n/**\n * Section-scoped mutate. The mutator only sees one section's payload\n * (`sections.<sectionKey>`) and CANNOT reach sibling sections —\n * preventing accidental clobbers. Returns the mutated section.\n *\n * Use this from CLI callers (`RegistryLockfileService`) so cross-\n * section bugs are impossible by construction. Companion callers\n * that legitimately need full-envelope access keep using\n * `withLockfileMutate` directly.\n */\nexport async function withLockfileSectionMutate<S>(\n options: LockfileMutateOptions & {\n /** Section key under `sections` (e.g. `'modules'`, `'i18n'`). */\n sectionKey: string;\n /** Zod schema validating the section payload. Required. */\n sectionSchema: z.ZodType<S>;\n /** Initial value when the section does not yet exist. */\n initialSection: () => S;\n },\n mutator: (section: S) => S | void | Promise<S | void>,\n): Promise<S> {\n let mutatedOut!: S;\n await withLockfileMutate(\n {\n saasRoot: options.saasRoot,\n lockOptions: options.lockOptions,\n sectionSchemas: {\n ...options.sectionSchemas,\n [options.sectionKey]: options.sectionSchema,\n },\n },\n async (envelope) => {\n const sections = envelope.sections as Record<string, unknown>;\n const current = (sections[options.sectionKey] as S | undefined) ?? options.initialSection();\n const cloned = structuredClone(current);\n const ret = await mutator(cloned);\n const next = (ret ?? cloned) as S;\n // Per-section validation (also covers initial-default re-validation).\n mutatedOut = options.sectionSchema.parse(next);\n sections[options.sectionKey] = mutatedOut;\n },\n );\n return mutatedOut;\n}\n"]}
@@ -58,6 +58,11 @@ export interface LoadConfigOptions {
58
58
  * Off by default: one-shot CLI processes gain nothing from re-evaluation,
59
59
  * and module identity within a single load stays shared either way. Turn it
60
60
  * on at read sites whose CONTRACT is "the working tree as it is right now".
61
+ *
62
+ * It reaches only what jiti TRANSPILES. An ESM `.js` file in a `"type": "module"`
63
+ * package is imported natively by Node and pinned in its process-global ESM
64
+ * registry, whatever this says — so {@link loadPackageCompanionExport} answers
65
+ * a fresh read from the package's authored source, not its `dist`.
61
66
  */
62
67
  freshModuleCache?: boolean;
63
68
  }
@@ -83,7 +88,17 @@ export declare function loadConfig<T>(filePath: string, options?: LoadConfigOpti
83
88
  * application authors. Returns `undefined` when the module does not export `exportName`.
84
89
  */
85
90
  export declare function loadConfigExport<T>(filePath: string, exportName: string, options?: LoadConfigOptions): Promise<T | undefined>;
86
- export declare function resolvePackageCompanionEntryPath(packageRoot: string, subpath?: string, options?: Pick<LoadConfigOptions, 'moduleResolution'>): string;
91
+ /**
92
+ * Which file a package's companion subpath resolves to.
93
+ *
94
+ * Authored source wins when either option asks for it: `moduleResolution: 'framework-source'` (a package inside the
95
+ * framework workspace), or `preferAuthoredSource` (a reader whose contract is the working tree, wherever the package
96
+ * lives — see {@link loadPackageCompanionExport}). Otherwise the declared `exports` entry wins, and authored source
97
+ * is only the fallback when nothing is built.
98
+ */
99
+ export declare function resolvePackageCompanionEntryPath(packageRoot: string, subpath?: string, options?: Pick<LoadConfigOptions, 'moduleResolution'> & {
100
+ readonly preferAuthoredSource?: boolean;
101
+ }): string;
87
102
  /**
88
103
  * Normalize tsconfig-shaped compiler path aliases into the exact-prefix form
89
104
  * `LoadConfigOptions.packageModuleAliases` expects.
@@ -1 +1 @@
1
- {"version":3,"file":"loader.d.ts","sourceRoot":"","sources":["../../../../src/project-config/loader.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,oBAAoB,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,sBAAsB,CAAC;AAC5D,OAAO,EAIL,KAAK,mBAAmB,EACzB,MAAM,2BAA2B,CAAC;AAInC,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,KAAK,EAAE,iBAAiB,EAAE,MAAM,wBAAwB,CAAC;AAChE,OAAO,EAIL,KAAK,8BAA8B,EACpC,MAAM,4CAA4C,CAAC;AAEpD,MAAM,WAAW,iBAAiB;IAChC;;;;;OAKG;IACH,gBAAgB,CAAC,EAAE,8BAA8B,CAAC;IAClD;;;;;;;;;;;;;OAaG;IACH,gBAAgB,CAAC,EAAE,SA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