owenloop 0.5.0 → 0.5.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 (229) hide show
  1. package/CHANGELOG.md +67 -0
  2. package/README.md +144 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +29 -4
  5. package/dist/packages/work/src/agent/brief.js +49 -4
  6. package/dist/packages/work/src/agent/capability-model.d.ts +123 -0
  7. package/dist/packages/work/src/agent/capability-model.js +148 -0
  8. package/dist/packages/work/src/agent/loop.d.ts +56 -7
  9. package/dist/packages/work/src/agent/loop.js +166 -9
  10. package/dist/packages/work/src/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +29 -1
  20. package/dist/packages/work/src/exec/loop.js +313 -35
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +84 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +30 -10
  38. package/dist/packages/work/src/harness/session-store.js +317 -89
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +134 -12
  41. package/dist/packages/work/src/hub/client.d.ts +8 -1
  42. package/dist/packages/work/src/hub/client.js +15 -1
  43. package/dist/packages/work/src/hub/types.d.ts +137 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +115 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +6 -0
  53. package/dist/packages/work/src/roles/hold.js +83 -13
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +19 -2
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +36 -2
  59. package/dist/packages/work/src/settings/settings.d.ts +70 -1
  60. package/dist/packages/work/src/settings/settings.js +90 -4
  61. package/dist/packages/work/src/shift/logretention.d.ts +253 -0
  62. package/dist/packages/work/src/shift/logretention.js +407 -0
  63. package/dist/packages/work/src/shift/logsink.d.ts +14 -0
  64. package/dist/packages/work/src/shift/logsink.js +98 -0
  65. package/dist/packages/work/src/shift/loop.d.ts +32 -4
  66. package/dist/packages/work/src/shift/loop.js +687 -166
  67. package/dist/packages/work/src/shift/protocol.d.ts +128 -1
  68. package/dist/packages/work/src/shift/protocol.js +14 -0
  69. package/dist/packages/work/src/shift/runtime.d.ts +16 -0
  70. package/dist/packages/work/src/shift/runtime.js +291 -5
  71. package/dist/packages/work/src/shift/server.d.ts +13 -0
  72. package/dist/packages/work/src/shift/server.js +61 -36
  73. package/dist/packages/work/src/shift/spawn.d.ts +115 -19
  74. package/dist/packages/work/src/shift/spawn.js +234 -30
  75. package/dist/packages/work/src/shift/state.d.ts +76 -49
  76. package/dist/packages/work/src/shift/state.js +350 -103
  77. package/dist/packages/work/src/shift/truncate.d.ts +35 -0
  78. package/dist/packages/work/src/shift/truncate.js +73 -0
  79. package/dist/packages/work/src/submit-proof.d.ts +61 -0
  80. package/dist/packages/work/src/submit-proof.js +119 -0
  81. package/dist/packages/work/src/submit-value.d.ts +48 -0
  82. package/dist/packages/work/src/submit-value.js +118 -0
  83. package/dist/packages/work/src/usage.d.ts +1 -1
  84. package/dist/packages/work/src/usage.js +11 -0
  85. package/dist/src/add.d.ts +64 -259
  86. package/dist/src/add.js +81 -615
  87. package/dist/src/archive.d.ts +97 -0
  88. package/dist/src/archive.js +591 -0
  89. package/dist/src/bundle/index.d.ts +64 -0
  90. package/dist/src/bundle/index.js +508 -0
  91. package/dist/src/bundle/manifest.d.ts +50 -0
  92. package/dist/src/bundle/manifest.js +435 -0
  93. package/dist/src/bundle/runtime.d.ts +26 -0
  94. package/dist/src/bundle/runtime.js +64 -0
  95. package/dist/src/bundle/tar.d.ts +62 -0
  96. package/dist/src/bundle/tar.js +238 -0
  97. package/dist/src/bundle/types.d.ts +105 -0
  98. package/dist/src/bundle/types.js +21 -0
  99. package/dist/src/capabilities.d.ts +93 -0
  100. package/dist/src/capabilities.js +101 -0
  101. package/dist/src/cli.d.ts +90 -20
  102. package/dist/src/cli.js +2421 -374
  103. package/dist/src/credentials.d.ts +4 -3
  104. package/dist/src/credentials.js +21 -19
  105. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  106. package/dist/src/crypto/allowed-signers.js +307 -0
  107. package/dist/src/crypto/canonical.d.ts +8 -0
  108. package/dist/src/crypto/canonical.js +92 -0
  109. package/dist/src/crypto/chain.d.ts +65 -0
  110. package/dist/src/crypto/chain.js +377 -0
  111. package/dist/src/crypto/dsse.d.ts +209 -0
  112. package/dist/src/crypto/dsse.js +282 -0
  113. package/dist/src/crypto/enrollment.d.ts +78 -0
  114. package/dist/src/crypto/enrollment.js +186 -0
  115. package/dist/src/crypto/index.d.ts +48 -0
  116. package/dist/src/crypto/index.js +44 -0
  117. package/dist/src/crypto/keys.d.ts +258 -0
  118. package/dist/src/crypto/keys.js +908 -0
  119. package/dist/src/crypto/org-root.d.ts +33 -0
  120. package/dist/src/crypto/org-root.js +78 -0
  121. package/dist/src/crypto/origin-rules.d.ts +56 -0
  122. package/dist/src/crypto/origin-rules.js +143 -0
  123. package/dist/src/crypto/policy-floor.d.ts +98 -0
  124. package/dist/src/crypto/policy-floor.js +353 -0
  125. package/dist/src/crypto/records.d.ts +319 -0
  126. package/dist/src/crypto/records.js +168 -0
  127. package/dist/src/crypto/scope.d.ts +49 -0
  128. package/dist/src/crypto/scope.js +83 -0
  129. package/dist/src/crypto/ssh.d.ts +171 -0
  130. package/dist/src/crypto/ssh.js +396 -0
  131. package/dist/src/crypto/submission.d.ts +33 -0
  132. package/dist/src/crypto/submission.js +47 -0
  133. package/dist/src/crypto/trust-roots.d.ts +29 -0
  134. package/dist/src/crypto/trust-roots.js +39 -0
  135. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  136. package/dist/src/crypto/verify-consumed.js +259 -0
  137. package/dist/src/crypto/verify-origin.d.ts +50 -0
  138. package/dist/src/crypto/verify-origin.js +151 -0
  139. package/dist/src/crypto/verify-publication.d.ts +60 -0
  140. package/dist/src/crypto/verify-publication.js +150 -0
  141. package/dist/src/defs.d.ts +24 -1
  142. package/dist/src/defs.js +335 -27
  143. package/dist/src/engine.d.ts +211 -6
  144. package/dist/src/engine.js +459 -59
  145. package/dist/src/factory.d.ts +16 -0
  146. package/dist/src/factory.js +16 -4
  147. package/dist/src/global-config.d.ts +59 -0
  148. package/dist/src/global-config.js +84 -0
  149. package/dist/src/hub.d.ts +102 -32
  150. package/dist/src/hub.js +147 -58
  151. package/dist/src/index.d.ts +19 -2
  152. package/dist/src/index.js +23 -2
  153. package/dist/src/install.d.ts +538 -0
  154. package/dist/src/install.js +1981 -0
  155. package/dist/src/lock.d.ts +15 -57
  156. package/dist/src/lock.js +251 -143
  157. package/dist/src/mcp/serve.d.ts +46 -22
  158. package/dist/src/mcp/serve.js +174 -44
  159. package/dist/src/mcp/server.js +12 -1
  160. package/dist/src/model.d.ts +51 -0
  161. package/dist/src/model.js +157 -1
  162. package/dist/src/order-resolver.d.ts +184 -0
  163. package/dist/src/order-resolver.js +252 -0
  164. package/dist/src/package-version.d.ts +10 -0
  165. package/dist/src/package-version.js +42 -0
  166. package/dist/src/paths.d.ts +14 -1
  167. package/dist/src/paths.js +18 -0
  168. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  169. package/dist/src/schemas/index.d.ts +1433 -0
  170. package/dist/src/schemas/index.js +31 -0
  171. package/dist/src/schemas/order.v1.schema.json +120 -0
  172. package/dist/src/schemas/origin.v1.schema.json +68 -0
  173. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  174. package/dist/src/schemas/publication.v1.schema.json +31 -0
  175. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  176. package/dist/src/schemas/submission.v1.schema.json +61 -0
  177. package/dist/src/store/def-source.d.ts +52 -0
  178. package/dist/src/store/def-source.js +335 -0
  179. package/dist/src/store/index-file.d.ts +69 -0
  180. package/dist/src/store/index-file.js +151 -0
  181. package/dist/src/store/index.d.ts +27 -0
  182. package/dist/src/store/index.js +22 -0
  183. package/dist/src/store/ingestor.d.ts +43 -0
  184. package/dist/src/store/ingestor.js +211 -0
  185. package/dist/src/store/install.d.ts +228 -0
  186. package/dist/src/store/install.js +555 -0
  187. package/dist/src/store/instruction-source.d.ts +49 -0
  188. package/dist/src/store/instruction-source.js +298 -0
  189. package/dist/src/store/origin-evidence.d.ts +21 -0
  190. package/dist/src/store/origin-evidence.js +66 -0
  191. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  192. package/dist/src/store/pre-commit-verifier.js +418 -0
  193. package/dist/src/store/resolve.d.ts +138 -0
  194. package/dist/src/store/resolve.js +363 -0
  195. package/dist/src/store/types.d.ts +288 -0
  196. package/dist/src/store/types.js +356 -0
  197. package/dist/src/store.d.ts +33 -1
  198. package/dist/src/store.js +57 -4
  199. package/dist/src/types.d.ts +146 -12
  200. package/dist/src/untar.d.ts +8 -23
  201. package/dist/src/untar.js +10 -136
  202. package/docs/agent-runner.md +86 -0
  203. package/docs/authoring.md +64 -6
  204. package/docs/bundles.md +350 -0
  205. package/docs/cli.md +1298 -106
  206. package/docs/crypto.md +832 -0
  207. package/docs/design.md +342 -20
  208. package/docs/embedding.md +132 -25
  209. package/docs/shift-logs.md +642 -0
  210. package/docs/wire-contracts.md +395 -0
  211. package/package.json +6 -1
  212. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  213. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  214. package/plugins/claude-code/plugin/.mcp.json +14 -0
  215. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  216. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  217. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  218. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  219. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  220. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  221. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  222. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  223. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  224. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  225. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  226. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  227. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  228. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  229. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
@@ -1,80 +1,38 @@
1
- /**
2
- * Generic advisory FILE LOCK — an exclusive-create lockfile with liveness-aware
3
- * staleness, used to serialize a filesystem critical section across owenloop
4
- * processes.
5
- *
6
- * Extracted verbatim (logic-identical) from `src/add.ts`'s per-project install
7
- * lock: `add.ts` now consumes it through thin `acquireInstallLock` /
8
- * `releaseInstallLock` wrappers that preserve the old names, types, and the
9
- * "owenloop add" timeout wording; `src/credentials.ts` uses it to serialize the
10
- * OAuth refresh-and-persist critical section (`credentials.lock`). The only
11
- * behavioral addition during the move is the optional `label` (used in the
12
- * timeout message) so each caller names itself.
13
- *
14
- * Depends only on node builtins so the library barrel (`src/index.ts` →
15
- * `credentials.ts` → here) never drags the `add`/`untar` graph into its runtime
16
- * closure.
17
- */
18
1
  export interface FileLockHandle {
19
2
  lockPath: string;
20
3
  acquired: boolean;
21
- /** Per-acquisition ownership token — present when `acquired`; proof of ownership for release. */
4
+ /** Per-acquisition diagnostic identity. SQLite, not this token, owns exclusion. */
22
5
  token?: string;
23
6
  }
24
7
  export interface AcquireFileLockOpts {
25
- /** Max time to wait for a live lock before failing cleanly (default 10s). */
8
+ /** Max time to wait for the SQLite writer lock or legacy owner. */
26
9
  waitMs?: number;
27
- /**
28
- * Age (by mtime) past which an *unparseable/abandoned* lock may be reclaimed
29
- * (default 10m). Age NEVER reclaims a lock whose recorded pid is alive on
30
- * this host — it only governs the fail-closed fallback for a lock we cannot
31
- * attribute to a live owner (unparseable payload, or one without a pid).
32
- */
10
+ /** Retained for source compatibility. New clients never age-reclaim pathnames. */
33
11
  staleMs?: number;
34
- /** Poll interval while waiting on a live lock (default 100ms). */
12
+ /** Poll interval while waiting. */
35
13
  pollMs?: number;
36
- /** Liveness probe for the holder pid — injectable so tests are deterministic. */
14
+ /** Retained for source compatibility. New clients never reclaim by pid. */
37
15
  isPidAlive?: (pid: number) => boolean;
38
- /** Clock — injectable so tests are deterministic. */
16
+ /** Wall clock used only for diagnostic timestamps. */
39
17
  now?: () => number;
40
- /** Current hostname — injectable so cross-host tests are deterministic (default `os.hostname`). */
18
+ /** Current hostname used in diagnostic metadata. */
41
19
  hostname?: () => string;
42
- /**
43
- * Names the holder in the timeout message ("another ${label} is in
44
- * progress …"). Defaults to a generic phrase; `add` passes "owenloop add" so
45
- * its existing wording is byte-identical.
46
- */
20
+ /** Names the holder in timeout text. */
47
21
  label?: string;
22
+ /** Test barrier immediately before opening the versioned SQLite database. */
23
+ beforeOpen?: () => void;
48
24
  }
49
- /**
50
- * Thrown by `acquireFileLock` when it gives up after `waitMs` on a lock a live
51
- * owner still holds. A subclass of `Error` (not a plain `Error`) so a caller can
52
- * `instanceof`-distinguish a clean timeout from a real filesystem failure (an
53
- * EACCES/EROFS from the exclusive create) and map only the timeout to its own
54
- * domain error — while `.message` stays byte-identical to the pre-extraction
55
- * plain-`Error` message the `add` tests assert on.
56
- */
57
25
  export declare class FileLockTimeoutError extends Error {
58
26
  readonly lockPath: string;
59
27
  readonly holderPid: number | undefined;
60
28
  readonly waitMs: number;
61
- constructor(message: string, lockPath: string, holderPid: number | undefined, waitMs: number);
29
+ readonly legacy: boolean;
30
+ constructor(message: string, lockPath: string, holderPid: number | undefined, waitMs: number, legacy?: boolean);
62
31
  }
63
- /**
64
- * Acquire the file lock at `lockPath` (an exclusive-create of the file,
65
- * `openSync(..,'wx')` — the O_EXCL create is the real serialization point). The
66
- * payload carries an ownership token, the owner pid, a start timestamp, and the
67
- * host. If another process holds it: reclaim it only when liveness-aware
68
- * staleness says its owner is gone (see `lockIsStale`), otherwise poll until it
69
- * frees, and if it does not free within `waitMs` throw a `FileLockTimeoutError`.
70
- * Always pair with `releaseFileLock` in a `finally`.
71
- */
72
32
  export declare function acquireFileLock(lockPath: string, opts?: AcquireFileLockOpts): Promise<FileLockHandle>;
33
+ export declare function acquireFileLockSync(lockPath: string, opts?: AcquireFileLockOpts): FileLockHandle;
73
34
  /**
74
- * Release a lock acquired by `acquireFileLock`. Token-checked and best-effort: a
75
- * no-op if not acquired, if the lock is already gone/unparseable, or if its
76
- * token no longer matches this handle (someone else legitimately re-acquired it
77
- * — deleting would steal *their* lock). Never throws; it runs in a `finally` and
78
- * must not mask the real error.
35
+ * Release only the versioned SQLite transaction. The permanent compatibility
36
+ * guard is never deleted, renamed, or replaced.
79
37
  */
80
38
  export declare function releaseFileLock(handle: FileLockHandle): void;
package/dist/src/lock.js CHANGED
@@ -1,217 +1,325 @@
1
- /**
2
- * Generic advisory FILE LOCK — an exclusive-create lockfile with liveness-aware
3
- * staleness, used to serialize a filesystem critical section across owenloop
4
- * processes.
5
- *
6
- * Extracted verbatim (logic-identical) from `src/add.ts`'s per-project install
7
- * lock: `add.ts` now consumes it through thin `acquireInstallLock` /
8
- * `releaseInstallLock` wrappers that preserve the old names, types, and the
9
- * "owenloop add" timeout wording; `src/credentials.ts` uses it to serialize the
10
- * OAuth refresh-and-persist critical section (`credentials.lock`). The only
11
- * behavioral addition during the move is the optional `label` (used in the
12
- * timeout message) so each caller names itself.
13
- *
14
- * Depends only on node builtins so the library barrel (`src/index.ts` →
15
- * `credentials.ts` → here) never drags the `add`/`untar` graph into its runtime
16
- * closure.
17
- */
18
- import { closeSync, mkdirSync, openSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
19
- import { dirname } from 'node:path';
1
+ // Generic cross-process lock with a one-way mixed-version boundary.
2
+ //
3
+ // New clients hold a SQLite `BEGIN IMMEDIATE` transaction on the versioned
4
+ // database at `<lockPath>.sqlite-v2`. The logical legacy pathname remains a
5
+ // parseable JSON guard. Its deliberately impossible hostname makes pre-SQLite
6
+ // clients treat the guard as foreign-host-owned and therefore never reclaim it.
7
+ // Once a new client installs that guard, old clients fail closed and must be
8
+ // upgraded; new clients continue to serialize through SQLite.
9
+ //
10
+ // The guard is permanent. Release and crash cleanup affect only the SQLite
11
+ // transaction, so no compare/read/delete pathname race exists. A pre-existing
12
+ // old JSON owner is allowed to release normally before the guard is installed.
13
+ // A corrupt file or a pre-boundary SQLite database at the legacy pathname is
14
+ // never removed automatically: the operator must first verify that no old or
15
+ // pre-boundary process owns it, then remove that legacy pathname manually.
20
16
  import { randomBytes } from 'node:crypto';
17
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, writeFileSync, renameSync, } from 'node:fs';
21
18
  import { hostname } from 'node:os';
19
+ import { dirname } from 'node:path';
20
+ import { performance } from 'node:perf_hooks';
21
+ import { DatabaseSync } from 'node:sqlite';
22
22
  import { setTimeout as sleep } from 'node:timers/promises';
23
- /** Default wait/stale/poll timings for a file lock (overridable per acquire). */
24
23
  const LOCK_WAIT_MS = 10_000;
25
- const LOCK_STALE_MS = 10 * 60_000;
26
24
  const LOCK_POLL_MS = 100;
27
- /**
28
- * Thrown by `acquireFileLock` when it gives up after `waitMs` on a lock a live
29
- * owner still holds. A subclass of `Error` (not a plain `Error`) so a caller can
30
- * `instanceof`-distinguish a clean timeout from a real filesystem failure (an
31
- * EACCES/EROFS from the exclusive create) and map only the timeout to its own
32
- * domain error — while `.message` stays byte-identical to the pre-extraction
33
- * plain-`Error` message the `add` tests assert on.
34
- */
25
+ const LOCK_SYNC_SLEEP = new Int32Array(new SharedArrayBuffer(Int32Array.BYTES_PER_ELEMENT));
26
+ const COMPATIBILITY_GUARD_FORMAT = 'owenloop-sqlite-lock-v2';
27
+ // A slash cannot occur in an operating-system hostname. Old clients compare
28
+ // this field before probing the pid and therefore hold the guard forever.
29
+ const COMPATIBILITY_GUARD_HOST = 'owenloop/sqlite-lock/v2';
35
30
  export class FileLockTimeoutError extends Error {
36
31
  lockPath;
37
32
  holderPid;
38
33
  waitMs;
39
- constructor(message, lockPath, holderPid, waitMs) {
34
+ legacy;
35
+ constructor(message, lockPath, holderPid, waitMs, legacy = false) {
40
36
  super(message);
41
37
  this.name = 'FileLockTimeoutError';
42
38
  this.lockPath = lockPath;
43
39
  this.holderPid = holderPid;
44
40
  this.waitMs = waitMs;
41
+ this.legacy = legacy;
45
42
  }
46
43
  }
47
- /** `true` if a process with `pid` exists (signal 0 probes without delivering). */
48
- function defaultIsPidAlive(pid) {
49
- try {
50
- process.kill(pid, 0);
51
- return true;
52
- }
53
- catch (e) {
54
- // EPERM: the process exists but we may not signal it — treat as alive.
55
- // ESRCH (and anything else): no such process — dead.
56
- return e.code === 'EPERM';
57
- }
44
+ /** Connections are deliberately private so callers cannot commit the lock transaction. */
45
+ const heldConnections = new WeakMap();
46
+ function databasePath(lockPath) {
47
+ return `${lockPath}.sqlite-v2`;
58
48
  }
59
- /** Read the lock file's raw bytes, or `null` if it is gone/unreadable. */
60
- function readLockRaw(lockPath) {
49
+ function ownerPath(lockPath) {
50
+ return `${lockPath}.owner.json`;
51
+ }
52
+ function readRaw(path) {
61
53
  try {
62
- return readFileSync(lockPath, 'utf8');
54
+ return readFileSync(path, 'utf8');
63
55
  }
64
56
  catch {
65
57
  return null;
66
58
  }
67
59
  }
68
- /** Parse raw lock bytes into a holder, or `null` if absent/unparseable. */
69
- function parseLockHolder(raw) {
60
+ function parseHolder(raw) {
70
61
  if (raw === null)
71
62
  return null;
72
63
  try {
73
- return JSON.parse(raw);
64
+ const parsed = JSON.parse(raw);
65
+ return typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)
66
+ ? parsed
67
+ : null;
74
68
  }
75
69
  catch {
76
70
  return null;
77
71
  }
78
72
  }
79
- /** Read + parse the lock file in one step (fresh read). Used off the hot loop. */
80
- function readLockHolder(lockPath) {
81
- return parseLockHolder(readLockRaw(lockPath));
73
+ function isCompatibilityGuard(raw) {
74
+ const holder = parseHolder(raw);
75
+ return holder?.format === COMPATIBILITY_GUARD_FORMAT && holder.host === COMPATIBILITY_GUARD_HOST;
76
+ }
77
+ function readDiagnosticHolder(lockPath) {
78
+ return parseHolder(readRaw(ownerPath(lockPath)));
79
+ }
80
+ function legacyHolder(lockPath) {
81
+ return parseHolder(readRaw(lockPath));
82
+ }
83
+ function writeDiagnosticHolder(lockPath, holder) {
84
+ const path = ownerPath(lockPath);
85
+ const tmp = `${path}.${process.pid}.${randomBytes(8).toString('hex')}.tmp`;
86
+ writeFileSync(tmp, JSON.stringify(holder));
87
+ renameSync(tmp, path);
82
88
  }
83
89
  /**
84
- * Decide whether the lock described by `holder` (parsed from a raw read) may be
85
- * reclaimed, given the current host. Liveness-aware, not age-based:
86
- *
87
- * 1. `statSync` fails — the lock vanished mid-judgment → treat as reclaimable
88
- * (the acquire loop re-verifies and simply retries the exclusive create).
89
- * 2. Holder records a `host` that differs from ours → NOT stale, ever. A
90
- * foreign PID space means `process.kill(pid, 0)` proves nothing; a shared
91
- * filesystem could be locked by another machine. Held; caller refuses.
92
- * 3. Holder has a numeric `pid` and either matches our host or omits `host`
93
- * (a legacy same-machine payload) → stale iff that pid is dead. Age never
94
- * reclaims a live-pid lock — this is the core safety policy.
95
- * 4. Unparseable, or parses without a numeric pid → fail closed: held until
96
- * `now() - mtimeMs > staleMs` (age is the only abandonment signal left).
90
+ * Install the permanent old-client guard with one exclusive create. A crash or
91
+ * write failure may leave a partial guard, which is intentionally fail-closed
92
+ * and requires verified manual cleanup; this function never unlinks a pathname.
97
93
  */
98
- function lockIsStale(lockPath, holder, staleMs, isPidAlive, now, currentHost) {
99
- let mtimeMs;
94
+ function syncDirectory(path) {
95
+ if (process.platform === 'win32')
96
+ return;
97
+ const fd = openSync(dirname(path), 'r');
98
+ try {
99
+ fsyncSync(fd);
100
+ }
101
+ finally {
102
+ closeSync(fd);
103
+ }
104
+ }
105
+ function ensureCompatibilityGuard(lockPath, now) {
106
+ let fd;
100
107
  try {
101
- mtimeMs = statSync(lockPath).mtimeMs;
108
+ fd = openSync(lockPath, 'wx', 0o600);
109
+ }
110
+ catch (error) {
111
+ if (error.code !== 'EEXIST')
112
+ throw error;
113
+ return isCompatibilityGuard(readRaw(lockPath));
114
+ }
115
+ let failure;
116
+ try {
117
+ writeFileSync(fd, JSON.stringify({
118
+ format: COMPATIBILITY_GUARD_FORMAT,
119
+ host: COMPATIBILITY_GUARD_HOST,
120
+ startedAt: now(),
121
+ }));
122
+ fsyncSync(fd);
123
+ }
124
+ catch (error) {
125
+ failure = error;
126
+ }
127
+ try {
128
+ closeSync(fd);
129
+ }
130
+ catch (error) {
131
+ if (failure === undefined)
132
+ failure = error;
133
+ }
134
+ if (failure !== undefined)
135
+ throw failure;
136
+ syncDirectory(lockPath);
137
+ return true;
138
+ }
139
+ function openLockDatabase(lockPath) {
140
+ const db = new DatabaseSync(databasePath(lockPath));
141
+ db.exec('PRAGMA busy_timeout = 0');
142
+ return db;
143
+ }
144
+ function isBusy(error) {
145
+ const candidate = error;
146
+ return candidate.errcode === 5 || /database is (?:locked|busy)/iu.test(candidate.message ?? '');
147
+ }
148
+ function beginLock(db) {
149
+ db.exec('BEGIN IMMEDIATE;\n' +
150
+ 'CREATE TABLE IF NOT EXISTS __owenloop_lock_format (id INTEGER PRIMARY KEY CHECK (id = 1));\n' +
151
+ 'INSERT OR IGNORE INTO __owenloop_lock_format (id) VALUES (1);');
152
+ }
153
+ function closeAfterFailure(db) {
154
+ if (db === undefined)
155
+ return;
156
+ try {
157
+ db.exec('ROLLBACK');
102
158
  }
103
159
  catch {
104
- // Vanished between the EEXIST and here — someone else reclaimed it; retry.
105
- return true;
160
+ // No transaction began, or SQLite already rolled it back.
106
161
  }
107
- // Case 2: recorded on a different host — its pid tells us nothing. Held.
108
- if (holder && typeof holder.host === 'string' && holder.host !== currentHost) {
109
- return false;
162
+ try {
163
+ db.close();
110
164
  }
111
- // Case 3: same host (or legacy no-host payload) with a numeric pid — liveness decides.
112
- if (holder && typeof holder.pid === 'number') {
113
- return !isPidAlive(holder.pid);
165
+ catch {
166
+ // Preserve the acquisition error.
114
167
  }
115
- // Case 4: no attributable live owner — age is the only abandonment signal.
116
- return now() - mtimeMs > staleMs;
117
168
  }
118
- /**
119
- * Acquire the file lock at `lockPath` (an exclusive-create of the file,
120
- * `openSync(..,'wx')` — the O_EXCL create is the real serialization point). The
121
- * payload carries an ownership token, the owner pid, a start timestamp, and the
122
- * host. If another process holds it: reclaim it only when liveness-aware
123
- * staleness says its owner is gone (see `lockIsStale`), otherwise poll until it
124
- * frees, and if it does not free within `waitMs` throw a `FileLockTimeoutError`.
125
- * Always pair with `releaseFileLock` in a `finally`.
126
- */
169
+ function makeHandle(lockPath, db, now, currentHost) {
170
+ const token = randomBytes(16).toString('hex');
171
+ const holder = {
172
+ pid: process.pid,
173
+ startedAt: now(),
174
+ token,
175
+ host: currentHost,
176
+ active: true,
177
+ };
178
+ try {
179
+ writeDiagnosticHolder(lockPath, holder);
180
+ }
181
+ catch (error) {
182
+ closeAfterFailure(db);
183
+ throw error;
184
+ }
185
+ const handle = { lockPath, acquired: true, token };
186
+ heldConnections.set(handle, db);
187
+ return handle;
188
+ }
189
+ function timeoutError(lockPath, holder, waitMs, label, legacy) {
190
+ const suffix = legacy
191
+ ? '; found an old, corrupt, or pre-boundary lock pathname that Owenloop will not delete automatically — verify that no old process owns it, then remove it manually'
192
+ : '';
193
+ return new FileLockTimeoutError(`${inProgressMessage(lockPath, holder, waitMs, label)}${suffix}`, lockPath, typeof holder?.pid === 'number' ? holder.pid : undefined, waitMs, legacy);
194
+ }
127
195
  export async function acquireFileLock(lockPath, opts = {}) {
128
196
  const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
129
- const staleMs = opts.staleMs ?? LOCK_STALE_MS;
130
197
  const pollMs = opts.pollMs ?? LOCK_POLL_MS;
131
- const isPidAlive = opts.isPidAlive ?? defaultIsPidAlive;
132
198
  const now = opts.now ?? Date.now;
133
- const host = (opts.hostname ?? hostname)();
199
+ const currentHost = (opts.hostname ?? hostname)();
134
200
  const label = opts.label ?? 'owenloop process';
201
+ const deadline = performance.now() + waitMs;
135
202
  mkdirSync(dirname(lockPath), { recursive: true });
136
- const deadline = now() + waitMs;
137
203
  for (;;) {
204
+ let db;
138
205
  try {
139
- const fd = openSync(lockPath, 'wx');
140
- const token = randomBytes(16).toString('hex');
141
- try {
142
- writeFileSync(fd, JSON.stringify({ pid: process.pid, startedAt: now(), token, host }));
143
- }
144
- finally {
145
- closeSync(fd);
206
+ opts.beforeOpen?.();
207
+ db = openLockDatabase(lockPath);
208
+ beginLock(db);
209
+ if (!ensureCompatibilityGuard(lockPath, now)) {
210
+ closeAfterFailure(db);
211
+ db = undefined;
212
+ const holder = legacyHolder(lockPath);
213
+ if (performance.now() >= deadline)
214
+ throw timeoutError(lockPath, holder, waitMs, label, true);
215
+ await sleep(pollMs);
216
+ continue;
146
217
  }
147
- return { lockPath, acquired: true, token };
218
+ return makeHandle(lockPath, db, now, currentHost);
148
219
  }
149
- catch (e) {
150
- if (e.code !== 'EEXIST')
151
- throw e;
220
+ catch (error) {
221
+ closeAfterFailure(db);
222
+ if (error instanceof FileLockTimeoutError)
223
+ throw error;
224
+ if (!isBusy(error))
225
+ throw error;
152
226
  }
153
- // Judge staleness from a single captured raw read...
154
- const raw = readLockRaw(lockPath);
155
- const holder = parseLockHolder(raw);
156
- if (lockIsStale(lockPath, holder, staleMs, isPidAlive, now, host)) {
157
- // ...then re-verify the bytes are unchanged immediately before deleting.
158
- // Between judging stale and rmSync a third process could reclaim and
159
- // re-create the lock; deleting then would destroy a *fresh* owner's lock.
160
- // Residual window is a few syscalls (read-compare-delete) rather than the
161
- // poll interval — and the `wx` create below is the true arbiter: if two
162
- // reclaimers race, one wins the create and the other loops on EEXIST. A
163
- // rename-based reclaim was rejected: POSIX rename clobbers its target, so
164
- // any "rename back on mismatch" arm can itself destroy a newer lock.
165
- const raw2 = readLockRaw(lockPath);
166
- if (raw2 !== null && raw2 === raw) {
167
- rmSync(lockPath, { force: true });
168
- continue; // reclaimed — retry the exclusive create
227
+ const holder = readDiagnosticHolder(lockPath);
228
+ if (performance.now() >= deadline)
229
+ throw timeoutError(lockPath, holder, waitMs, label, false);
230
+ await sleep(pollMs);
231
+ }
232
+ }
233
+ export function acquireFileLockSync(lockPath, opts = {}) {
234
+ const waitMs = opts.waitMs ?? LOCK_WAIT_MS;
235
+ const pollMs = opts.pollMs ?? LOCK_POLL_MS;
236
+ const now = opts.now ?? Date.now;
237
+ const currentHost = (opts.hostname ?? hostname)();
238
+ const label = opts.label ?? 'owenloop process';
239
+ const deadline = performance.now() + waitMs;
240
+ mkdirSync(dirname(lockPath), { recursive: true });
241
+ for (;;) {
242
+ let db;
243
+ try {
244
+ opts.beforeOpen?.();
245
+ db = openLockDatabase(lockPath);
246
+ beginLock(db);
247
+ if (!ensureCompatibilityGuard(lockPath, now)) {
248
+ closeAfterFailure(db);
249
+ db = undefined;
250
+ const holder = legacyHolder(lockPath);
251
+ if (performance.now() >= deadline)
252
+ throw timeoutError(lockPath, holder, waitMs, label, true);
253
+ Atomics.wait(LOCK_SYNC_SLEEP, 0, 0, pollMs);
254
+ continue;
169
255
  }
170
- // Bytes changed under us, or the lock is stat-able but unreadable (a
171
- // root-owned 0600 lock: statSync needs only dir perms, readFileSync
172
- // EACCES → raw/raw2 null). Do NOT delete — fall through to the deadline
173
- // check and poll sleep below. Never `continue` here: with an unreadable,
174
- // backdated lock this branch would otherwise spin sleeplessly, starving
175
- // the event loop and never enforcing `waitMs`.
256
+ return makeHandle(lockPath, db, now, currentHost);
176
257
  }
177
- if (now() >= deadline) {
178
- throw new FileLockTimeoutError(inProgressMessage(lockPath, holder, waitMs, label), lockPath, typeof holder?.pid === 'number' ? holder.pid : undefined, waitMs);
258
+ catch (error) {
259
+ closeAfterFailure(db);
260
+ if (error instanceof FileLockTimeoutError)
261
+ throw error;
262
+ if (!isBusy(error))
263
+ throw error;
179
264
  }
180
- await sleep(pollMs);
265
+ const holder = readDiagnosticHolder(lockPath);
266
+ if (performance.now() >= deadline)
267
+ throw timeoutError(lockPath, holder, waitMs, label, false);
268
+ Atomics.wait(LOCK_SYNC_SLEEP, 0, 0, pollMs);
181
269
  }
182
270
  }
183
- /** Build the clear "another … is in progress" timeout error text, with graceful fallbacks. */
184
271
  function inProgressMessage(lockPath, holder, waitMs, label) {
185
272
  const who = typeof holder?.pid === 'number' ? `pid ${holder.pid}` : 'another process';
186
- // Lock content is untrusted input: a finite `startedAt` outside the ECMAScript
187
- // Date range (|t| > 8.64e15 ms) makes `new Date(t).toISOString()` throw
188
- // RangeError. Only render held-since when the value is a valid time value;
189
- // otherwise omit it (same graceful fallback as an absent startedAt).
190
273
  const heldSince = typeof holder?.startedAt === 'number' &&
191
274
  Number.isFinite(holder.startedAt) &&
192
275
  Math.abs(holder.startedAt) <= 8.64e15
193
276
  ? `, held since ${new Date(holder.startedAt).toISOString()}`
194
277
  : '';
195
- const s = Math.round(waitMs / 1000);
196
- return `another ${label} is in progress (${who}${heldSince}) — holds ${lockPath}; timed out waiting after ${s}s`;
278
+ const seconds = Math.round(waitMs / 1000);
279
+ return `another ${label} is in progress (${who}${heldSince}) — holds ${lockPath}; timed out waiting after ${seconds}s`;
197
280
  }
198
281
  /**
199
- * Release a lock acquired by `acquireFileLock`. Token-checked and best-effort: a
200
- * no-op if not acquired, if the lock is already gone/unparseable, or if its
201
- * token no longer matches this handle (someone else legitimately re-acquired it
202
- * — deleting would steal *their* lock). Never throws; it runs in a `finally` and
203
- * must not mask the real error.
282
+ * Release only the versioned SQLite transaction. The permanent compatibility
283
+ * guard is never deleted, renamed, or replaced.
204
284
  */
205
285
  export function releaseFileLock(handle) {
206
286
  if (!handle.acquired)
207
287
  return;
288
+ const db = heldConnections.get(handle);
289
+ if (db === undefined)
290
+ return;
208
291
  try {
209
- const holder = readLockHolder(handle.lockPath);
210
- if (!holder || holder.token !== handle.token)
211
- return;
212
- rmSync(handle.lockPath, { force: true });
292
+ try {
293
+ writeDiagnosticHolder(handle.lockPath, {
294
+ pid: process.pid,
295
+ token: handle.token,
296
+ host: hostname(),
297
+ active: false,
298
+ releasedAt: Date.now(),
299
+ });
300
+ }
301
+ catch {
302
+ // Diagnostics never outrank releasing the kernel lock.
303
+ }
304
+ try {
305
+ db.exec('COMMIT');
306
+ }
307
+ catch {
308
+ try {
309
+ db.exec('ROLLBACK');
310
+ }
311
+ catch {
312
+ // Closing the connection still releases the operating-system lock.
313
+ }
314
+ }
213
315
  }
214
- catch {
215
- // Already reclaimed/replaced, or an unexpected fs error — swallow.
316
+ finally {
317
+ heldConnections.delete(handle);
318
+ try {
319
+ db.close();
320
+ }
321
+ catch {
322
+ // Release is called from finally blocks and must not mask the real error.
323
+ }
216
324
  }
217
325
  }