iit-mcp-autotask 0.54.2

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 (164) hide show
  1. package/.env.example +123 -0
  2. package/LICENSE +21 -0
  3. package/README.md +788 -0
  4. package/capabilities.json +487 -0
  5. package/dist/access/gate.d.ts +34 -0
  6. package/dist/access/gate.js +76 -0
  7. package/dist/access/grants.d.ts +20 -0
  8. package/dist/access/grants.js +35 -0
  9. package/dist/access/write-env.d.ts +41 -0
  10. package/dist/access/write-env.js +166 -0
  11. package/dist/auth.d.ts +74 -0
  12. package/dist/auth.js +129 -0
  13. package/dist/base-hosts.d.ts +38 -0
  14. package/dist/base-hosts.js +70 -0
  15. package/dist/config/load.d.ts +28 -0
  16. package/dist/config/load.js +105 -0
  17. package/dist/config/schema.d.ts +166 -0
  18. package/dist/config/schema.js +311 -0
  19. package/dist/credential.d.ts +28 -0
  20. package/dist/credential.js +32 -0
  21. package/dist/doctor.d.ts +112 -0
  22. package/dist/doctor.js +154 -0
  23. package/dist/http-guard.d.ts +57 -0
  24. package/dist/http-guard.js +134 -0
  25. package/dist/http.d.ts +50 -0
  26. package/dist/http.js +290 -0
  27. package/dist/lifecycle.d.ts +29 -0
  28. package/dist/lifecycle.js +52 -0
  29. package/dist/logger.d.ts +26 -0
  30. package/dist/logger.js +28 -0
  31. package/dist/main.d.ts +12 -0
  32. package/dist/main.js +283 -0
  33. package/dist/policy.d.ts +54 -0
  34. package/dist/policy.js +80 -0
  35. package/dist/tools/aggregate.d.ts +16 -0
  36. package/dist/tools/aggregate.js +64 -0
  37. package/dist/tools/capabilities-manifest.d.ts +4 -0
  38. package/dist/tools/capabilities-manifest.js +94 -0
  39. package/dist/tools/catalog-data.d.ts +116 -0
  40. package/dist/tools/catalog-data.js +207 -0
  41. package/dist/tools/clock.d.ts +17 -0
  42. package/dist/tools/clock.js +43 -0
  43. package/dist/tools/composites.d.ts +36 -0
  44. package/dist/tools/composites.js +305 -0
  45. package/dist/tools/context/client.d.ts +41 -0
  46. package/dist/tools/context/client.js +139 -0
  47. package/dist/tools/context/derive.d.ts +9 -0
  48. package/dist/tools/context/derive.js +32 -0
  49. package/dist/tools/context/scope.d.ts +24 -0
  50. package/dist/tools/context/scope.js +180 -0
  51. package/dist/tools/context/types.d.ts +141 -0
  52. package/dist/tools/context/types.js +2 -0
  53. package/dist/tools/dispatch.d.ts +78 -0
  54. package/dist/tools/dispatch.js +272 -0
  55. package/dist/tools/field-pointer.d.ts +25 -0
  56. package/dist/tools/field-pointer.js +45 -0
  57. package/dist/tools/guide.d.ts +30 -0
  58. package/dist/tools/guide.js +97 -0
  59. package/dist/tools/lists.d.ts +9 -0
  60. package/dist/tools/lists.js +205 -0
  61. package/dist/tools/meta.d.ts +22 -0
  62. package/dist/tools/meta.js +709 -0
  63. package/dist/tools/output-file.d.ts +26 -0
  64. package/dist/tools/output-file.js +140 -0
  65. package/dist/tools/rank.d.ts +21 -0
  66. package/dist/tools/rank.js +57 -0
  67. package/dist/tools/reasons.d.ts +33 -0
  68. package/dist/tools/reasons.js +121 -0
  69. package/dist/tools/register.d.ts +23 -0
  70. package/dist/tools/register.js +50 -0
  71. package/dist/tools/resolves.d.ts +28 -0
  72. package/dist/tools/resolves.js +399 -0
  73. package/dist/tools/results/envelope.d.ts +55 -0
  74. package/dist/tools/results/envelope.js +63 -0
  75. package/dist/tools/results/errors.d.ts +147 -0
  76. package/dist/tools/results/errors.js +384 -0
  77. package/dist/tools/results/untrusted.d.ts +129 -0
  78. package/dist/tools/results/untrusted.js +218 -0
  79. package/dist/tools/revenue-rollup.d.ts +8 -0
  80. package/dist/tools/revenue-rollup.js +112 -0
  81. package/dist/tools/schemas.d.ts +467 -0
  82. package/dist/tools/schemas.js +444 -0
  83. package/dist/tools/scope-guard.d.ts +2 -0
  84. package/dist/tools/scope-guard.js +11 -0
  85. package/dist/tools/server-version.d.ts +3 -0
  86. package/dist/tools/server-version.js +14 -0
  87. package/dist/tools/server.d.ts +92 -0
  88. package/dist/tools/server.js +170 -0
  89. package/dist/tools/surface.d.ts +37 -0
  90. package/dist/tools/surface.js +94 -0
  91. package/dist/tools/tsv.d.ts +52 -0
  92. package/dist/tools/tsv.js +95 -0
  93. package/dist/tools/write/apply.d.ts +40 -0
  94. package/dist/tools/write/apply.js +500 -0
  95. package/dist/tools/write/checks.d.ts +39 -0
  96. package/dist/tools/write/checks.js +137 -0
  97. package/dist/tools/write/common.d.ts +23 -0
  98. package/dist/tools/write/common.js +33 -0
  99. package/dist/tools/write/facts.d.ts +52 -0
  100. package/dist/tools/write/facts.js +151 -0
  101. package/dist/tools/write/outcome.d.ts +23 -0
  102. package/dist/tools/write/outcome.js +67 -0
  103. package/dist/tools/write/parse.d.ts +37 -0
  104. package/dist/tools/write/parse.js +166 -0
  105. package/dist/tools/write/payload.d.ts +44 -0
  106. package/dist/tools/write/payload.js +119 -0
  107. package/dist/tools/write/preview.d.ts +3 -0
  108. package/dist/tools/write/preview.js +317 -0
  109. package/dist/tools/write/snapshot.d.ts +68 -0
  110. package/dist/tools/write/snapshot.js +360 -0
  111. package/dist/tools/write-guidance.d.ts +174 -0
  112. package/dist/tools/write-guidance.js +317 -0
  113. package/dist/tools/write.d.ts +9 -0
  114. package/dist/tools/write.js +10 -0
  115. package/dist/write/canonical.d.ts +12 -0
  116. package/dist/write/canonical.js +31 -0
  117. package/dist/write/evaluate.d.ts +77 -0
  118. package/dist/write/evaluate.js +91 -0
  119. package/dist/write/hard-rules.d.ts +49 -0
  120. package/dist/write/hard-rules.js +48 -0
  121. package/dist/write/runtime.d.ts +37 -0
  122. package/dist/write/runtime.js +72 -0
  123. package/dist/write/store/audit-log.d.ts +13 -0
  124. package/dist/write/store/audit-log.js +25 -0
  125. package/dist/write/store/constants.d.ts +34 -0
  126. package/dist/write/store/constants.js +35 -0
  127. package/dist/write/store/files.d.ts +44 -0
  128. package/dist/write/store/files.js +157 -0
  129. package/dist/write/store/heartbeat.d.ts +9 -0
  130. package/dist/write/store/heartbeat.js +65 -0
  131. package/dist/write/store/ledger.d.ts +15 -0
  132. package/dist/write/store/ledger.js +86 -0
  133. package/dist/write/store/lifecycle.d.ts +35 -0
  134. package/dist/write/store/lifecycle.js +114 -0
  135. package/dist/write/store/lock.d.ts +97 -0
  136. package/dist/write/store/lock.js +464 -0
  137. package/dist/write/store/op-lock.d.ts +13 -0
  138. package/dist/write/store/op-lock.js +175 -0
  139. package/dist/write/store/plan-store.d.ts +7 -0
  140. package/dist/write/store/plan-store.js +48 -0
  141. package/dist/write/store/plans.d.ts +5 -0
  142. package/dist/write/store/plans.js +19 -0
  143. package/dist/write/store/types.d.ts +195 -0
  144. package/dist/write/store/types.js +2 -0
  145. package/dist/write/store.d.ts +6 -0
  146. package/dist/write/store.js +182 -0
  147. package/examples/agentgateway.write-gate.yaml +29 -0
  148. package/package.json +71 -0
  149. package/server.json +69 -0
  150. package/skills/ar-aging.md +65 -0
  151. package/skills/company-360.md +69 -0
  152. package/skills/contract-profitability.md +65 -0
  153. package/skills/crm-management.md +87 -0
  154. package/skills/filter-semantics.md +75 -0
  155. package/skills/invoice-export.md +61 -0
  156. package/skills/log-time-entry.md +77 -0
  157. package/skills/non-chargeable-work.md +67 -0
  158. package/skills/portfolio-margin.md +66 -0
  159. package/skills/recurring-revenue.md +65 -0
  160. package/skills/revenue-rollup.md +65 -0
  161. package/skills/slim-reads.md +67 -0
  162. package/skills/ticket-triage.md +64 -0
  163. package/skills/unbilled-work-review.md +66 -0
  164. package/skills/wip-hours.md +68 -0
@@ -0,0 +1,464 @@
1
+ /** The state lock, the holder registry, leases and takeover (issues #55, #68, #88): no store dependency. */
2
+ import { randomBytes } from 'node:crypto';
3
+ import { closeSync, existsSync, fsyncSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, statSync, unlinkSync, writeSync } from 'node:fs';
4
+ import { hostname } from 'node:os';
5
+ import { join } from 'node:path';
6
+ import { LEASE_EXPIRY_MS, OP_LOCK_POLL_MS } from './constants.js';
7
+ import { refuse, sleepSync } from './files.js';
8
+ export function pidAlive(pid) {
9
+ try {
10
+ process.kill(pid, 0);
11
+ return true;
12
+ }
13
+ catch (err) {
14
+ return err.code !== 'ESRCH';
15
+ }
16
+ }
17
+ /**
18
+ * This process's boot identity, written into the lock and the holder registry (pre-release V5).
19
+ * A lock naming this process's own pid but another boot is a previous run's (in a container node
20
+ * is PID 1 on every start, so after a SIGKILL or an OOM kill the old lock names the new process's
21
+ * pid): it is stale. Another pid counts as live while that pid is alive (conservative: a recycled
22
+ * pid of an unrelated process refuses boot until an operator removes the lock, see the README).
23
+ */
24
+ export const BOOT_ID = randomBytes(16).toString('hex');
25
+ /**
26
+ * The host (container) this process runs on, written into the lock (final review R6). In a
27
+ * container the hostname is the container id unless the deployment overrides it.
28
+ */
29
+ export const HOST_ID = hostname();
30
+ export function holderAlive(pid, boot) {
31
+ return pid === process.pid ? boot === BOOT_ID : pidAlive(pid);
32
+ }
33
+ /**
34
+ * Whether this process still holds the lock: `held`, `lost` (deleted, or another holder), or
35
+ * `unknown` (the file could not be read just now, e.g. EIO or EMFILE: pre-release V7).
36
+ */
37
+ export function lockState(path) {
38
+ let text;
39
+ try {
40
+ text = readFileSync(path, 'utf8');
41
+ }
42
+ catch (err) {
43
+ return err.code === 'ENOENT' ? 'lost' : 'unknown';
44
+ }
45
+ try {
46
+ const h = JSON.parse(text);
47
+ return h.pid === process.pid && h.boot === BOOT_ID && h.host === HOST_ID ? 'held' : 'lost';
48
+ }
49
+ catch {
50
+ return 'unknown';
51
+ }
52
+ }
53
+ /**
54
+ * The process-scoped holder registration (issue #68): the registration is per PROCESS (one per
55
+ * state dir), and a process can hold more than one store instance (the unit tests) — the ref
56
+ * count keeps the first instance's close from unlinking the registration out from under the
57
+ * others.
58
+ */
59
+ export const holderRefs = new Map();
60
+ /**
61
+ * Register this boot in the holder registry (issue #68) BEFORE any other state work: the
62
+ * registration is what the boot rewrite consults when it decides which `sending` entries belong
63
+ * to live peers, and it is the runtime stop signal (a deleted registration stops this process's
64
+ * writes). The lease is written with the same per-writer-tmp idiom as the lock's.
65
+ */
66
+ export function registerHolder(holdersDir, now) {
67
+ mkdirSync(holdersDir, { recursive: true, mode: 0o700 });
68
+ const holderPath = join(holdersDir, BOOT_ID);
69
+ const refs = (holderRefs.get(holderPath) ?? 0) + 1;
70
+ holderRefs.set(holderPath, refs);
71
+ if (refs === 1) {
72
+ const fd = openSync(holderPath, 'wx', 0o600);
73
+ writeSync(fd, JSON.stringify({ pid: process.pid, boot: BOOT_ID, host: HOST_ID, startedAt: new Date(now()).toISOString() }));
74
+ fsyncSync(fd);
75
+ closeSync(fd);
76
+ writeLease(`${holderPath}.lease`, now());
77
+ }
78
+ return holderPath;
79
+ }
80
+ /** Release this store's ref on the registration; the file goes when the last ref goes. */
81
+ export function releaseHolder(holderPath) {
82
+ const refs = (holderRefs.get(holderPath) ?? 1) - 1;
83
+ if (refs <= 0)
84
+ holderRefs.delete(holderPath);
85
+ else
86
+ holderRefs.set(holderPath, refs);
87
+ if (refs > 0)
88
+ return; // another store of this process is still registered
89
+ try {
90
+ unlinkSync(holderPath);
91
+ }
92
+ catch {
93
+ // gone already (a runtime deletion): nothing to release
94
+ }
95
+ try {
96
+ unlinkSync(`${holderPath}.lease`);
97
+ }
98
+ catch {
99
+ // best-effort
100
+ }
101
+ }
102
+ /**
103
+ * The boot sweep (issue #68): remove the registry entries of peers that are no longer alive —
104
+ * another host's files are never touched (R6). A holder is DEAD when its entry names this
105
+ * process's own pid from an earlier boot (a live pid is unique, so that "holder" is a dead
106
+ * previous run — the container-PID-1 case, the same self-previous-boot exception the lock's
107
+ * takeover verdict has), when its pid answers ESRCH (a kill -9 / OOM restart inside the lease
108
+ * window: a same-host dead pid cannot be a live holder — the fresh-lease veto is liveness
109
+ * evidence for a LIVE-but-slow holder, not for a process that no longer exists), or when its
110
+ * lease is expired (the pid may be a recycled one — a recycled pid is no evidence). A live pid
111
+ * with a fresh lease stays, and a live pid with no readable lease (a legacy holder we cannot
112
+ * judge) stays, as before.
113
+ */
114
+ export function sweepHolders(holdersDir, log, now) {
115
+ let names;
116
+ try {
117
+ names = readdirSync(holdersDir);
118
+ }
119
+ catch {
120
+ return; // the registry is unreadable for the moment: nothing to sweep
121
+ }
122
+ for (const name of names) {
123
+ // Only the boot-id shape is a registration: the lease and the per-writer lease tmp never
124
+ // pass (a beat in flight is not a peer, and its tmp must never be unlinked out from under it).
125
+ if (!/^[0-9a-f]{32}$/.test(name) || name === BOOT_ID)
126
+ continue;
127
+ const holderPath = join(holdersDir, name);
128
+ const leasePath = `${holderPath}.lease`;
129
+ let holder;
130
+ try {
131
+ holder = JSON.parse(readFileSync(holderPath, 'utf8'));
132
+ }
133
+ catch {
134
+ continue; // gone (a concurrent close) or unreadable: leave it
135
+ }
136
+ if (typeof holder.pid !== 'number' || !Number.isInteger(holder.pid) || holder.pid <= 0)
137
+ continue;
138
+ if (holder.host !== HOST_ID)
139
+ continue; // R6: another host's registry is never swept
140
+ const lease = readLease(leasePath, now());
141
+ const selfPreviousBoot = holder.pid === process.pid && holder.boot !== BOOT_ID;
142
+ const pidDead = selfPreviousBoot || !pidAlive(holder.pid);
143
+ const leaseExpired = !pidDead && lease.kind === 'aged' && lease.age > LEASE_EXPIRY_MS;
144
+ if (!pidDead && !leaseExpired)
145
+ continue;
146
+ try {
147
+ unlinkSync(holderPath);
148
+ }
149
+ catch {
150
+ // best-effort
151
+ }
152
+ try {
153
+ unlinkSync(leasePath);
154
+ }
155
+ catch {
156
+ // best-effort
157
+ }
158
+ log.info('removed a dead peer from the holder registry', { boot: name, pid: holder.pid, reason: pidDead ? 'dead_pid' : 'lease_expired' });
159
+ }
160
+ }
161
+ /** The holder's lease heartbeat file, atomically rewritten (tmp + fsync + rename, 0600). */
162
+ export function writeLease(path, at) {
163
+ const body = JSON.stringify({ pid: process.pid, boot: BOOT_ID, host: HOST_ID, at });
164
+ // Per-writer tmp name: the holder's refresh timer and every taker's acquisition share the lease
165
+ // file. A fixed tmp name lets two writers race the same rename (the loser's rename is ENOENT)
166
+ // and lets a shorter body truncate a longer one mid-rename (S2-M3).
167
+ const tmp = `${path}.${process.pid}.tmp`;
168
+ const fd = openSync(tmp, 'w', 0o600);
169
+ try {
170
+ writeSync(fd, body);
171
+ fsyncSync(fd);
172
+ closeSync(fd);
173
+ renameSync(tmp, path);
174
+ }
175
+ catch (err) {
176
+ // A failed write/fsync/rename would otherwise leave the per-writer tmp behind: remove it
177
+ // best-effort before the error propagates (a failed unlink is swallowed silently).
178
+ try {
179
+ closeSync(fd);
180
+ }
181
+ catch {
182
+ // already closed
183
+ }
184
+ try {
185
+ unlinkSync(tmp);
186
+ }
187
+ catch {
188
+ // best-effort
189
+ }
190
+ throw err;
191
+ }
192
+ }
193
+ /**
194
+ * Read the holder's lease: `absent` when the file is not there (a pre-lease 0.6.0 holder — no
195
+ * veto, the pid probe decides), `corrupt` when it is but is unreadable or carries no numeric `at`
196
+ * (fail closed: refuse boot rather than open a takeover on a file the holder would never leave
197
+ * behind — our writes are atomic renames), or `aged` with its age in ms.
198
+ */
199
+ export function readLease(path, now) {
200
+ let text;
201
+ try {
202
+ text = readFileSync(path, 'utf8');
203
+ }
204
+ catch (err) {
205
+ // ENOENT: no lease file (a pre-lease 0.6.0 holder - no veto, the pid probe decides). Any other
206
+ // error (EACCES, EIO, EMFILE): fail closed, the same way the lock-body read does (S2-m2).
207
+ return err.code === 'ENOENT' ? { kind: 'absent' } : { kind: 'corrupt' };
208
+ }
209
+ try {
210
+ const lease = JSON.parse(text);
211
+ if (typeof lease.at !== 'number' || !Number.isFinite(lease.at))
212
+ return { kind: 'corrupt' };
213
+ return { kind: 'aged', age: now - lease.at, ...(lease.boot !== undefined ? { boot: lease.boot } : {}) };
214
+ }
215
+ catch {
216
+ return { kind: 'corrupt' };
217
+ }
218
+ }
219
+ /**
220
+ * The verdict on the current primary (throws ConfigError on the hard refusals; issue #68 added
221
+ * the `secondary` outcome — a LIVE same-host primary no longer refuses the boot, it is simply
222
+ * kept, and this process shares the dir under the op lock):
223
+ * - the lock is unreadable or names no pid: refuse (the operator removes it);
224
+ * - another host's lock: refuse, never taken (R6);
225
+ * - a corrupt lease: refuse (fail closed, S2-m2);
226
+ * - a FRESH lease (and not this process's own pid from an earlier boot): the holder is the live
227
+ * PRIMARY — boot as a SECONDARY (the fresh-lease veto, which used to refuse boot, now governs
228
+ * PRIMARY succession only);
229
+ * - a dead pid (ESRCH): take over (`dead_pid`), lease or no lease (the pre-lease 0.6.0 case);
230
+ * - a live pid with an EXPIRED lease: take over (`lease_expired`, the recycled-pid case);
231
+ * - a live pid with no lease (a pre-lease 0.6.0 holder): nothing to prove it dead — boot as a
232
+ * secondary alongside it (the shared-dir model makes that safe; the op lock serialises writes).
233
+ */
234
+ /** How long ago the lock file was written, by the file clock (an unreadable stat counts as old: the old verdict applies). */
235
+ function lockAgeMs(path) {
236
+ try {
237
+ return Date.now() - statSync(path).mtimeMs;
238
+ }
239
+ catch {
240
+ return Infinity;
241
+ }
242
+ }
243
+ export function primaryVerdict(path, now) {
244
+ const leasePath = `${path}.lease`;
245
+ let holder;
246
+ try {
247
+ holder = JSON.parse(readFileSync(path, 'utf8'));
248
+ }
249
+ catch (err) {
250
+ if (err.code === 'ENOENT') {
251
+ // It may have disappeared (a concurrent close) a moment before the read: the next
252
+ // iteration's tryCreate settles it — refuse only if it is still gone when the wait runs
253
+ // out (a mid-boot operator deletion used to refuse here without a retry).
254
+ return { kind: 'wait' };
255
+ }
256
+ if (err.code === undefined) {
257
+ // The body is empty or only partially written: a taker is MID-CREATE (the O_EXCL create
258
+ // and the write are not atomic) — wait out the window, the same verdict the op lock gives
259
+ // (two boots racing a fresh dir both create; the loser must not refuse on the winner's
260
+ // half-written body, issue #68).
261
+ return { kind: 'wait', midCreate: true };
262
+ }
263
+ refuse(`${path} disappeared or is unreadable; remove it if no server is running on this state dir`);
264
+ }
265
+ if (typeof holder.pid !== 'number' || !Number.isInteger(holder.pid) || holder.pid <= 0) {
266
+ refuse(`${path} names no pid; remove it if no server is running on this state dir`);
267
+ }
268
+ if (holder.host !== HOST_ID) {
269
+ // Final review R6: a pid means nothing across hosts or containers (each has its own pid
270
+ // space), so another host's lock is never taken over automatically.
271
+ refuse(`locked by host ${typeof holder.host === 'string' ? holder.host : '(unknown)'} (pid ${holder.pid}); one container per state dir. If that host's server is gone, delete ${path} and start again`);
272
+ }
273
+ const lease = readLease(leasePath, now());
274
+ if (lease.kind === 'corrupt') {
275
+ refuse(`${leasePath} exists but is not a readable lease; remove it if no server is running on this state dir`);
276
+ }
277
+ // One exception to the fresh-lease veto: a lock naming THIS process's own pid from an earlier
278
+ // boot. That "holder" is a dead previous run - a live pid is unique, so a live process cannot be
279
+ // this process - and its fresh lease is necessarily stale. The exception is what an OOM or
280
+ // SIGKILL restart needs: the pre-change V5 case took such a lock over at once (S2-m1).
281
+ const selfPreviousBoot = holder.pid === process.pid && holder.boot !== BOOT_ID;
282
+ if (lease.kind === 'aged' && lease.age <= LEASE_EXPIRY_MS && !selfPreviousBoot) {
283
+ return { kind: 'secondary' };
284
+ }
285
+ if (!holderAlive(holder.pid, holder.boot)) {
286
+ return { kind: 'dead', verdict: { pid: holder.pid, boot: holder.boot, reason: 'dead_pid' } };
287
+ }
288
+ if (lease.kind === 'aged') {
289
+ // A lease that names ANOTHER boot than the lock's holder is the previous holder's: the lock was created (O_EXCL) a moment ago
290
+ // and its holder has not written its own lease yet (create and lease are two steps). It is mid-start, not a recycled pid:
291
+ // wait for the lease, never take the lock over from a live holder (this made two boots both log a takeover under a race).
292
+ // Bounded: only while the LOCK itself is young (the real file clock, not the injected one). A holder that created the lock and then
293
+ // never wrote a lease (a failed write, a pid reused after a crash) must not block every boot forever: past the window it is the
294
+ // old `lease_expired` takeover again.
295
+ if (lease.boot !== undefined && holder.boot !== undefined && lease.boot !== holder.boot && lockAgeMs(path) <= LEASE_EXPIRY_MS) {
296
+ return { kind: 'wait', midStartPid: holder.pid };
297
+ }
298
+ // The lease is stale three refresh cycles over: the real holder cannot have been active that
299
+ // long; the live pid is a recycled one (a container replacement reset the pid namespace,
300
+ // issue #55).
301
+ return { kind: 'dead', verdict: { pid: holder.pid, boot: holder.boot, reason: 'lease_expired' } };
302
+ }
303
+ return { kind: 'secondary' }; // a live pid, no lease: a pre-lease (0.6.0) holder
304
+ }
305
+ export function takeLock(path, log, now, waitMs) {
306
+ const leasePath = `${path}.lease`;
307
+ const takeoverPath = `${path}.takeover`;
308
+ const body = JSON.stringify({ pid: process.pid, boot: BOOT_ID, host: HOST_ID, startedAt: new Date().toISOString() });
309
+ const waitRefusal = (w) => refuse(w.midStartPid !== undefined
310
+ ? `${path} names a live process (pid ${w.midStartPid}) that has not written its lease; if no server is starting on this state dir, remove it`
311
+ : w.midCreate
312
+ ? `${path} exists but is empty or partially written; a create or takeover may have crashed mid-write — remove it if no server is running on this state dir`
313
+ : `${path} disappeared or is unreadable; remove it if no server is running on this state dir`);
314
+ // A lease write that fails right after our create must not leave a lock with no lease of ours: peers would wait on it.
315
+ const leaseOrRelease = () => {
316
+ try {
317
+ writeLease(leasePath, now());
318
+ }
319
+ catch (err) {
320
+ if (lockState(path) === 'held')
321
+ unlinkSync(path);
322
+ throw err;
323
+ }
324
+ };
325
+ const logTaken = (v) => {
326
+ const detail = { deadPid: v.pid, deadBoot: v.boot };
327
+ if (v.reason === 'lease_expired')
328
+ log.warn("state lock taken over: the holder's lease is expired and a recycled pid answers at its number", detail);
329
+ else
330
+ log.warn('state lock taken over from a dead process', detail);
331
+ };
332
+ const create = (p) => {
333
+ const fd = openSync(p, 'wx', 0o600);
334
+ writeSync(fd, body);
335
+ fsyncSync(fd);
336
+ closeSync(fd);
337
+ };
338
+ const tryCreate = () => {
339
+ try {
340
+ create(path);
341
+ return true;
342
+ }
343
+ catch (err) {
344
+ if (err.code !== 'EEXIST')
345
+ throw err;
346
+ return false;
347
+ }
348
+ };
349
+ const deadline = now() + waitMs;
350
+ for (;;) {
351
+ if (tryCreate()) {
352
+ leaseOrRelease();
353
+ return { takeover: undefined, ownsLock: true }; // this process is the primary
354
+ }
355
+ const v = primaryVerdict(path, now);
356
+ if (v.kind === 'secondary') {
357
+ log.info('booting as a secondary: a live process holds the state lock; this one registers in the holder registry and shares the dir under the op lock (issue #68)', { file: 'lock' });
358
+ return { takeover: undefined, ownsLock: false };
359
+ }
360
+ if (v.kind === 'wait') {
361
+ // A mid-create body or a concurrent close: a bounded wait, then the same refusal the
362
+ // unwaited path gave (the wait exists so a racing winner's half-written body is never
363
+ // mistaken for a corrupt lock).
364
+ if (now() >= deadline)
365
+ waitRefusal(v);
366
+ sleepSync(OP_LOCK_POLL_MS);
367
+ continue;
368
+ }
369
+ try {
370
+ create(takeoverPath);
371
+ }
372
+ catch (err) {
373
+ if (err.code !== 'EEXIST')
374
+ throw err;
375
+ // Another boot is taking the stale lock over right now: wait for it (it leaves a fresh
376
+ // lease, and this process then boots as a secondary under it) — and only refuse when the
377
+ // wait runs out (a takeover file a crashed taker left behind needs an operator).
378
+ if (now() >= deadline) {
379
+ refuse(`another process is taking over the lock (${takeoverPath}); remove it if no server is starting on this state dir`);
380
+ }
381
+ sleepSync(OP_LOCK_POLL_MS);
382
+ continue;
383
+ }
384
+ try {
385
+ // Under the takeover file: re-run the whole verdict (a fresh lease or a live holder that
386
+ // started meanwhile wins), then replace the stale lock.
387
+ let verdict;
388
+ if (existsSync(path)) {
389
+ const again = primaryVerdict(path, now);
390
+ if (again.kind === 'secondary')
391
+ return { takeover: undefined, ownsLock: false }; // a live holder came up meanwhile: it keeps the lock
392
+ if (again.kind === 'wait') {
393
+ // A taker is mid-create (or the file is going away): it wins the window. Re-loop —
394
+ // the finally drops the takeover file (a peer taker may proceed meanwhile) and the
395
+ // outer loop enforces the deadline before refusing.
396
+ if (now() >= deadline)
397
+ waitRefusal(again);
398
+ sleepSync(OP_LOCK_POLL_MS);
399
+ continue;
400
+ }
401
+ verdict = again.verdict;
402
+ // Re-check immediately before the unlink (#154): a paused primary judged dead may have closed since the verdict, and a
403
+ // newcomer created the lock in that gap. A lock that no longer names the judged holder is a fresh primary: keep it.
404
+ // (A vanished lock needs no unlink; the create below settles it.) The microseconds between this read and the unlink remain.
405
+ let current;
406
+ let gone = false;
407
+ try {
408
+ current = JSON.parse(readFileSync(path, 'utf8'));
409
+ }
410
+ catch (err) {
411
+ gone = err.code === 'ENOENT';
412
+ }
413
+ if (!gone && (current?.pid !== verdict.pid || current?.boot !== verdict.boot)) {
414
+ log.info('booting as a secondary: the lock changed hands while this one was taking it over (issue #154)', { file: 'lock' });
415
+ return { takeover: undefined, ownsLock: false };
416
+ }
417
+ if (!gone)
418
+ unlinkSync(path);
419
+ else
420
+ verdict = undefined; // nothing of the judged holder was removed: no takeover to report
421
+ }
422
+ const taken = verdict === undefined ? undefined : { deadPid: verdict.pid, ...(typeof verdict.boot === 'string' ? { deadBoot: verdict.boot } : {}), reason: verdict.reason };
423
+ if (!tryCreate()) {
424
+ // The loop-top create is not guarded by the takeover file: another boot can create the lock in the gap after the unlink above.
425
+ // That boot is the primary now (a fresh lock); this one shares the dir as a secondary instead of refusing, and still reports the
426
+ // takeover it performed (the stale lock was ours to remove) so the audit chain carries it. Look at what is there first: a live or
427
+ // mid-create holder is a primary; a lock that is already dead again is not, and this boot fails closed as it always did.
428
+ if (primaryVerdict(path, now).kind === 'dead')
429
+ refuse('another process took the lock during the takeover');
430
+ if (verdict !== undefined)
431
+ logTaken(verdict);
432
+ log.info('booting as a secondary: another boot created the state lock while this one was taking it over (issue #68)', { file: 'lock' });
433
+ return { takeover: taken, ownsLock: false };
434
+ }
435
+ leaseOrRelease();
436
+ if (verdict !== undefined) {
437
+ logTaken(verdict);
438
+ return { takeover: taken, ownsLock: true };
439
+ }
440
+ return { takeover: undefined, ownsLock: true };
441
+ }
442
+ finally {
443
+ unlinkSync(takeoverPath);
444
+ }
445
+ }
446
+ }
447
+ /**
448
+ * The boot ids registered in `<state>/holders/` (no liveness filter, issue #68). Only the boot-id
449
+ * shape is a registration: the lease and the per-writer lease tmp never pass, so a beat in flight
450
+ * neither counts as a holder nor is ever read as a registry entry.
451
+ */
452
+ export function holderNames(holdersDir) {
453
+ try {
454
+ return readdirSync(holdersDir).filter((f) => /^[0-9a-f]{32}$/.test(f));
455
+ }
456
+ catch {
457
+ return [];
458
+ }
459
+ }
460
+ /** The /ready `holders` fact (issue #68): how many processes are registered, including this one. */
461
+ export function holderCount(holdersDir) {
462
+ return holderNames(holdersDir).length;
463
+ }
464
+ //# sourceMappingURL=lock.js.map
@@ -0,0 +1,13 @@
1
+ import type { OpLockBlocked } from './types.js';
2
+ export interface OpLock {
3
+ /** Undefined when acquired (the caller must then `release`), or the reason the bounded wait gave up. */
4
+ acquire: () => OpLockBlocked | undefined;
5
+ release: () => void;
6
+ /** True while THIS instance holds the lock (the audit append re-enters under it). */
7
+ held: () => boolean;
8
+ }
9
+ export declare function createOpLock({ dir, now, opLockWaitMs }: {
10
+ dir: string;
11
+ now: () => number;
12
+ opLockWaitMs: number;
13
+ }): OpLock;
@@ -0,0 +1,175 @@
1
+ /**
2
+ * The per-operation lock (issue #68, #88): the short critical sections that make one state dir safe to share.
3
+ * ONE instance per `openStateStore`: audit re-entrancy and the exported `acquireOpLock`/`releaseOpLock`
4
+ * must see the same `held()`, or an audit append under a held lock would wait on its own lock.
5
+ */
6
+ import { closeSync, existsSync, fsyncSync, openSync, readFileSync, unlinkSync, writeSync } from 'node:fs';
7
+ import { join } from 'node:path';
8
+ import { LEASE_EXPIRY_MS, OP_LOCK_POLL_MS } from './constants.js';
9
+ import { BOOT_ID, HOST_ID, holderAlive, readLease, writeLease } from './lock.js';
10
+ import { sleepSync } from './files.js';
11
+ export function createOpLock({ dir, now, opLockWaitMs }) {
12
+ const opLockPath = join(dir, 'op.lock');
13
+ const opLeasePath = `${opLockPath}.lease`;
14
+ const opTakeoverPath = `${opLockPath}.takeover`;
15
+ let opLockHeld = false;
16
+ const opLockCreate = (p) => {
17
+ const fd = openSync(p, 'wx', 0o600);
18
+ writeSync(fd, JSON.stringify({ pid: process.pid, boot: BOOT_ID, host: HOST_ID, startedAt: new Date(now()).toISOString() }));
19
+ fsyncSync(fd);
20
+ closeSync(fd);
21
+ };
22
+ /**
23
+ * The op lock's verdict on its current holder (issue #68): `absent` (released — take it),
24
+ * `wait` (a live holder — keep polling; holds are milliseconds — or a holder whose body is
25
+ * still being written: the O_EXCL create and the write are not atomic, so a racing reader
26
+ * waits out the window instead of failing closed), `blocked` (an operator must remove the
27
+ * file — fail closed, like the primary lock's unreadable-file refusals), `dead` (take it
28
+ * over under `op.lock.takeover`, the F7/R13 idiom).
29
+ */
30
+ const opLockVerdict = () => {
31
+ let holder;
32
+ try {
33
+ holder = JSON.parse(readFileSync(opLockPath, 'utf8'));
34
+ }
35
+ catch (err) {
36
+ if (err.code === 'ENOENT')
37
+ return { kind: 'absent' };
38
+ if (err.code === undefined) {
39
+ // The body is empty or only partially written: the current holder is MID-CREATE. The
40
+ // creator completes the write in milliseconds; a create that crashed mid-write reaches
41
+ // the wait cap (the operator removes the file then — refusing at once would turn a
42
+ // microsecond window into a boot failure under a 16-boot race).
43
+ return { kind: 'wait', midCreate: true };
44
+ }
45
+ return { kind: 'blocked', detail: `${opLockPath} exists but is unreadable; remove it if no server is running on this state dir` };
46
+ }
47
+ if (typeof holder.pid !== 'number' || !Number.isInteger(holder.pid) || holder.pid <= 0) {
48
+ // A half-written body (a crash between O_EXCL and the write): fail closed, like the primary
49
+ // lock does — a taker on a body it cannot read could race the still-running writer.
50
+ return { kind: 'blocked', detail: `${opLockPath} names no pid; remove it if no server is running on this state dir` };
51
+ }
52
+ const lease = readLease(opLeasePath, now());
53
+ if (holder.host !== HOST_ID) {
54
+ // R6: another host's op lock is never taken over (its pid means nothing here); wait while
55
+ // its lease is fresh, else give up — sharing a state dir across hosts is not supported.
56
+ if (lease.kind === 'aged' && lease.age <= LEASE_EXPIRY_MS)
57
+ return { kind: 'wait' };
58
+ return { kind: 'blocked', detail: `${opLockPath} belongs to host ${typeof holder.host === 'string' ? holder.host : '(unknown)'}: a state dir shared across hosts is not supported (remove the file once that host is gone)` };
59
+ }
60
+ if (lease.kind === 'corrupt') {
61
+ // Fail closed, deliberately asymmetric with the sweep: the op lock is a live mutual-
62
+ // exclusion gate (a corrupt lease is an operator case), while a registry entry is
63
+ // bookkeeping (a corrupt holder lease there falls back to the pid probe).
64
+ return { kind: 'blocked', detail: `${opLeasePath} exists but is not a readable lease; remove it if no server is running on this state dir` };
65
+ }
66
+ const selfPreviousBoot = holder.pid === process.pid && holder.boot !== BOOT_ID;
67
+ if (lease.kind === 'aged' && lease.age <= LEASE_EXPIRY_MS && !selfPreviousBoot)
68
+ return { kind: 'wait' };
69
+ if (!holderAlive(holder.pid, holder.boot))
70
+ return { kind: 'dead', verdict: { pid: holder.pid, boot: holder.boot, reason: 'dead_pid' } };
71
+ if (lease.kind === 'aged') {
72
+ // The lease went stale: holds are milliseconds, so a holder silent for three refresh
73
+ // cycles crashed mid-op — the stale lease is the dead-man's switch.
74
+ return { kind: 'dead', verdict: { pid: holder.pid, boot: holder.boot, reason: 'lease_expired' } };
75
+ }
76
+ return { kind: 'wait' }; // a live holder with no lease (legacy): wait out the cap
77
+ };
78
+ const acquireOpLock = () => {
79
+ const tryCreate = () => {
80
+ try {
81
+ opLockCreate(opLockPath);
82
+ return true;
83
+ }
84
+ catch (err) {
85
+ if (err.code !== 'EEXIST')
86
+ throw err;
87
+ return false;
88
+ }
89
+ };
90
+ const giveUp = (detail) => ({ code: 'STATE_UNAVAILABLE', next: 'retry', detail });
91
+ const deadline = now() + opLockWaitMs;
92
+ for (;;) {
93
+ if (tryCreate()) {
94
+ writeLease(opLeasePath, now());
95
+ opLockHeld = true;
96
+ return undefined;
97
+ }
98
+ const v = opLockVerdict();
99
+ if (v.kind === 'absent')
100
+ continue; // released in the meantime: take it
101
+ if (v.kind === 'blocked')
102
+ return giveUp(v.detail);
103
+ if (v.kind === 'wait') {
104
+ if (now() >= deadline) {
105
+ return giveUp(v.midCreate
106
+ ? `${opLockPath} exists but is empty or partially written; a create may have crashed mid-write — remove it if no server is running on this state dir`
107
+ : `a peer process holds ${opLockPath}; the wait ran out — retry`);
108
+ }
109
+ sleepSync(OP_LOCK_POLL_MS);
110
+ continue;
111
+ }
112
+ try {
113
+ opLockCreate(opTakeoverPath);
114
+ }
115
+ catch (err) {
116
+ if (err.code !== 'EEXIST')
117
+ throw err;
118
+ // Another process is taking the op lock over right now: wait for it, then re-loop.
119
+ if (now() >= deadline)
120
+ return giveUp(`another process is taking over ${opLockPath}; the wait ran out — retry`);
121
+ sleepSync(OP_LOCK_POLL_MS);
122
+ continue;
123
+ }
124
+ try {
125
+ // Under the takeover file: re-run the whole verdict (R13), then replace the stale lock.
126
+ if (existsSync(opLockPath)) {
127
+ const again = opLockVerdict();
128
+ if (again.kind === 'dead') {
129
+ unlinkSync(opLockPath);
130
+ try {
131
+ unlinkSync(opLeasePath);
132
+ }
133
+ catch {
134
+ // best-effort
135
+ }
136
+ }
137
+ // absent/wait/blocked: the holder changed underneath — re-loop (still bounded)
138
+ }
139
+ if (tryCreate()) {
140
+ writeLease(opLeasePath, now());
141
+ opLockHeld = true;
142
+ return undefined;
143
+ }
144
+ }
145
+ finally {
146
+ unlinkSync(opTakeoverPath);
147
+ }
148
+ if (now() >= deadline)
149
+ return giveUp(`${opLockPath} could not be taken; the wait ran out — retry`);
150
+ sleepSync(OP_LOCK_POLL_MS);
151
+ }
152
+ };
153
+ const releaseOpLock = () => {
154
+ if (!opLockHeld)
155
+ return;
156
+ opLockHeld = false;
157
+ try {
158
+ const h = JSON.parse(readFileSync(opLockPath, 'utf8'));
159
+ if (h.pid === process.pid && h.boot === BOOT_ID && h.host === HOST_ID) {
160
+ unlinkSync(opLockPath);
161
+ try {
162
+ unlinkSync(opLeasePath);
163
+ }
164
+ catch {
165
+ // best-effort
166
+ }
167
+ }
168
+ }
169
+ catch {
170
+ // gone or unreadable: nothing of ours to release
171
+ }
172
+ };
173
+ return { acquire: acquireOpLock, release: releaseOpLock, held: () => opLockHeld };
174
+ }
175
+ //# sourceMappingURL=op-lock.js.map
@@ -0,0 +1,7 @@
1
+ import type { StateStore } from './types.js';
2
+ export type PlanStore = Pick<StateStore, 'savePlan' | 'loadPlan'>;
3
+ export declare function createPlanStore({ dir, key, now }: {
4
+ dir: string;
5
+ key: Buffer;
6
+ now: () => number;
7
+ }): PlanStore;