@codyswann/lisa 4.107.9 → 4.107.11

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 (107) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/nightly-e2e-guard-behavior-certificate.js.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  4. package/dist/core/upstream-evidence-manifest.js +34 -4
  5. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  6. package/nestjs/create-only/.github/k6/README.md +18 -15
  7. package/nestjs/create-only/.github/k6/scenarios/smoke.js +4 -1
  8. package/package.json +4 -4
  9. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  10. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  11. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  12. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  13. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  14. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  15. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  16. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  17. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  18. package/plugins/lisa/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  19. package/plugins/lisa-agy/plugin.json +1 -1
  20. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  21. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  22. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  23. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  24. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  25. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  26. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  27. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  28. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  29. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  31. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  33. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  34. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  35. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  36. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  37. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  38. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  39. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  40. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  41. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  43. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  44. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  45. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  46. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  47. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  48. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  49. package/plugins/lisa-expo-agy/plugin.json +1 -1
  50. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  51. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  54. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  56. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  57. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  58. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  60. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  61. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  63. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  64. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  65. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  68. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  70. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  71. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  72. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  75. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  77. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  78. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  79. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  81. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  82. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  84. package/plugins/lisa-rails-agy/plugin.json +1 -1
  85. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  86. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  88. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  89. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  91. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  92. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  93. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  95. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  96. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  98. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  99. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  100. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  102. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  103. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  104. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  105. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  106. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  107. package/typescript/copy-overwrite/.github/GITHUB_ACTIONS.md +5 -0
@@ -38,22 +38,24 @@ You need one of the following:
38
38
 
39
39
  ### Direct Script Usage
40
40
 
41
- For more control, use the runner script directly:
41
+ For more control, run k6 on a scenario or script directly:
42
42
 
43
43
  ```bash
44
- # Show all options
45
- ./scripts/k6-run.sh --help
44
+ # Run the smoke scenario
45
+ k6 run .github/k6/scenarios/smoke.js
46
46
 
47
- # Run smoke test with JSON output
48
- ./scripts/k6-run.sh --scenario smoke --json
47
+ # Run the load scenario against staging with JSON output
48
+ K6_BASE_URL=https://staging.example.com k6 run --out json=results.json .github/k6/scenarios/load.js
49
49
 
50
- # Run load test against staging with HTML report
51
- ./scripts/k6-run.sh --scenario load --url https://staging.example.com --html
52
-
53
- # Run custom script
54
- ./scripts/k6-run.sh --script .github/k6/scripts/api-test.js --url http://localhost:3000
50
+ # Run a custom script
51
+ K6_BASE_URL=http://localhost:3000 k6 run .github/k6/scripts/api-test.js
55
52
  ```
56
53
 
54
+ Lisa does not ship a runner script. If your repository provides an executable
55
+ `./scripts/k6-run.sh`, the load-test workflow uses it for standard scenarios;
56
+ it must exit with k6's own status (99 for a threshold breach) for
57
+ `fail_on_threshold` to apply.
58
+
57
59
  ### Docker Compose
58
60
 
59
61
  For containerized testing:
@@ -141,10 +143,10 @@ jobs:
141
143
  | `base_url` | Base URL of the application to test | Yes | - |
142
144
  | `k6_version` | k6 version to use | No | latest |
143
145
  | `test_duration` | Override test duration (e.g., 5m, 1h) | No | Scenario default |
144
- | `virtual_users` | Override number of virtual users | No | Scenario default |
146
+ | `virtual_users` | Override number of virtual users (0 or omitted keeps the scenario's own) | No | Scenario default |
145
147
  | `thresholds_config` | Path to custom thresholds JSON | No | Built-in thresholds |
146
- | `test_script` | Path to custom k6 test script | No | default-test.js |
147
- | `fail_on_threshold` | Fail workflow if thresholds not met | No | true |
148
+ | `test_script` | Path to custom k6 test script; at its default, runs `scripts/k6-run.sh` if present, else `.github/k6/scenarios/<test_scenario>.js`. A missing file fails the job | No | default-test.js |
149
+ | `fail_on_threshold` | Fail workflow if thresholds not met (k6 exit 99). Never suppresses a run that could not start or errored | No | true |
148
150
  | `upload_results` | Upload results as artifacts | No | true |
149
151
  | `cloud_run` | Run on k6 Cloud (requires token) | No | false |
150
152
 
@@ -335,8 +337,9 @@ See the [examples directory](./examples/) for complete integration patterns.
335
337
  The k6 setup uses a **shared implementation** that works identically in local development and CI/CD:
336
338
 
337
339
  ```
338
- scripts/k6-run.sh # Unified runner script (entry point)
339
- │
340
+ k6 run .github/k6/scenarios/<name>.js # Entry point, locally and in CI/CD
341
+ │ # (or scripts/k6-run.sh, if your
342
+ │ # repository provides one)
340
343
  ├── Local: k6 binary or Docker
341
344
  └── CI/CD: GitHub Actions workflow
342
345
 
@@ -24,7 +24,10 @@ export default function () {
24
24
  check(response, {
25
25
  "status is 200": r => r.status === 200,
26
26
  "response time < 300ms": r => r.timings.duration < 300,
27
- "response has body": r => r.body.length > 0,
27
+ // A failed request (refused, DNS, timeout) has a null body. Reading
28
+ // `.length` on it throws, which ends the iteration before sleep(1) and
29
+ // spins the VU at thousands of requests per second.
30
+ "response has body": r => (r.body || "").length > 0,
28
31
  });
29
32
 
30
33
  sleep(1);
package/package.json CHANGED
@@ -188,7 +188,7 @@
188
188
  "qs": "^6.16.0"
189
189
  },
190
190
  "name": "@codyswann/lisa",
191
- "version": "4.107.9",
191
+ "version": "4.107.11",
192
192
  "description": "Governance-as-code for AI coding agents: turns a repository into agent-operated software factories with guardrails, guidance and automated enforcement for Claude Code, Codex, Cursor, OpenCode, Antigravity, Copilot and Devin",
193
193
  "main": "dist/index.js",
194
194
  "exports": {
@@ -351,7 +351,7 @@
351
351
  "test": "tests"
352
352
  },
353
353
  "types": "./dist/index.d.ts",
354
- "lisaReleaseCommit": "12dc33623cf08f9c54e18ae8fef18a9be0f66c4a",
355
- "gitHead": "12dc33623cf08f9c54e18ae8fef18a9be0f66c4a",
356
- "lisaReleaseTag": "v4.107.9"
354
+ "lisaReleaseCommit": "24d0d26b348446c2439035aaa96f3edc6a82ae93",
355
+ "gitHead": "24d0d26b348446c2439035aaa96f3edc6a82ae93",
356
+ "lisaReleaseTag": "v4.107.11"
357
357
  }
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lisa",
3
- "version": "4.107.9",
3
+ "version": "4.107.11",
4
4
  "description": "Universal governance — agents, skills, commands, hooks, and rules for all projects",
5
5
  "author": {
6
6
  "name": "Cody Swann"
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lisa",
3
- "version": "4.107.9",
3
+ "version": "4.107.11",
4
4
  "description": "Universal governance: agents, skills, commands, hooks, and rules for all projects.",
5
5
  "author": {
6
6
  "name": "Cody Swann"
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Filesystem and process probes shared by the ledger lock
3
+ * (`ledger-lock.mjs`) and its stale-lock reclaim (`ledger-lock-reclaim.mjs`).
4
+ *
5
+ * Ported from Lisa's learnings-ledger lock (`src/core/learnings-lock-fs.ts`)
6
+ * rather than imported, because plugin scripts ship standalone and cannot
7
+ * reach `src/`. Both lock halves use these exact probes: a second, subtly
8
+ * different "is this process alive" or "is an absent file an error" is how a
9
+ * lock grows a hole.
10
+ * @module ledger-lock-fs
11
+ */
12
+
13
+ import { lstat, readFile, unlink } from "node:fs/promises";
14
+ import { uptime } from "node:os";
15
+
16
+ /** Largest owner record worth parsing; anything bigger is not ours. */
17
+ const MAX_OWNER_BYTES = 512;
18
+
19
+ /**
20
+ * Read file metadata without treating an absent path as an error.
21
+ * @param {string} filePath - Filesystem path
22
+ * @returns {Promise<import("node:fs").Stats | undefined>} Metadata, or undefined
23
+ */
24
+ export async function statFile(filePath) {
25
+ try {
26
+ return await lstat(filePath);
27
+ } catch (error) {
28
+ if (error?.code === "ENOENT") return undefined;
29
+ throw error;
30
+ }
31
+ }
32
+
33
+ /**
34
+ * Remove one path, treating an already-absent path as success.
35
+ * @param {string} filePath - Regular file or hard-link path
36
+ * @returns {Promise<void>}
37
+ */
38
+ export async function removeFileIfPresent(filePath) {
39
+ try {
40
+ await unlink(filePath);
41
+ } catch (error) {
42
+ if (error?.code !== "ENOENT") throw error;
43
+ }
44
+ }
45
+
46
+ /**
47
+ * Whether a pid may still be alive on this host. Only `ESRCH` means dead; a
48
+ * permission error means the process exists but belongs to someone else.
49
+ * @param {number} pid - Declared owner process id
50
+ * @returns {boolean} Whether the process may be alive
51
+ */
52
+ export function isProcessLive(pid) {
53
+ try {
54
+ process.kill(pid, 0);
55
+ return true;
56
+ } catch (error) {
57
+ return error?.code !== "ESRCH";
58
+ }
59
+ }
60
+
61
+ /**
62
+ * When this host last booted, in epoch ms. A pid recorded before then names
63
+ * a process from an earlier boot, whatever now runs under that number.
64
+ * @returns {number} Boot time
65
+ */
66
+ export function bootTimeMs() {
67
+ return Date.now() - uptime() * 1000;
68
+ }
69
+
70
+ /**
71
+ * Whether two paths are the same regular-file inode.
72
+ * @param {string} left - First path
73
+ * @param {string} right - Second path
74
+ * @returns {Promise<boolean>} Whether both name one inode
75
+ */
76
+ export async function sameFile(left, right) {
77
+ const [a, b] = await Promise.all([statFile(left), statFile(right)]);
78
+ return (
79
+ a !== undefined &&
80
+ b !== undefined &&
81
+ a.isFile() &&
82
+ b.isFile() &&
83
+ a.dev === b.dev &&
84
+ a.ino === b.ino
85
+ );
86
+ }
87
+
88
+ /**
89
+ * Read a small JSON record; a missing, oversized, special or unparseable file
90
+ * is `undefined`, never an error.
91
+ * @param {string} filePath - Record path
92
+ * @returns {Promise<unknown>} Parsed value, or undefined
93
+ */
94
+ export async function readSmallJson(filePath) {
95
+ const metadata = await statFile(filePath);
96
+ if (!metadata?.isFile() || metadata.size > MAX_OWNER_BYTES) return undefined;
97
+ try {
98
+ return JSON.parse(await readFile(filePath, "utf8"));
99
+ } catch {
100
+ return undefined;
101
+ }
102
+ }
103
+
104
+ /**
105
+ * Whether a parsed value is a plain object with exactly these keys.
106
+ * @param {unknown} value - Parsed value
107
+ * @param {string[]} keys - Required keys, and the only ones allowed
108
+ * @returns {boolean} Whether the shape matches
109
+ */
110
+ export function hasExactKeys(value, keys) {
111
+ if (value === null || typeof value !== "object") return false;
112
+ if (Object.getPrototypeOf(value) !== Object.prototype) return false;
113
+ const own = Reflect.ownKeys(value);
114
+ return own.length === keys.length && keys.every(key => own.includes(key));
115
+ }
116
+
117
+ /**
118
+ * Whether a value is a positive safe integer (a usable pid).
119
+ * @param {unknown} value - Candidate
120
+ * @returns {boolean} Whether it is a pid
121
+ */
122
+ export function isPid(value) {
123
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
124
+ }
@@ -0,0 +1,266 @@
1
+ /**
2
+ * Atomic reclaim of a ledger lock whose holder is gone (CodySwannGT/lisa#4828).
3
+ *
4
+ * Ported from the learnings-ledger lock (`src/core/learnings-lock.ts` and
5
+ * `learnings-lock-capability.ts`); plugin scripts ship standalone, so the
6
+ * logic is copied, not imported. The argument for why this never deletes a
7
+ * live lock is the precedent's, restated briefly:
8
+ *
9
+ * Proving the lock path still holds the inode judged stale and unlinking it
10
+ * are two syscalls, and POSIX has no "unlink only if still this inode". So the
11
+ * RIGHT to delete one lock generation is made exclusive: a capability file
12
+ * created with `O_EXCL`, at a path derived from the generation's identity
13
+ * (dev, ino and the owner record, all immutable for that file's life). Two
14
+ * reclaimers of the same generation contend for one path and only one wins.
15
+ * While it is held, the lock path can only change if its owner releases it,
16
+ * and the owner was just proven dead. The winner then pins the inode with a
17
+ * hard link, re-proves identity and death, and only then unlinks.
18
+ * @module ledger-lock-reclaim
19
+ */
20
+
21
+ import { createHash, randomUUID } from "node:crypto";
22
+ import { link, rename, writeFile } from "node:fs/promises";
23
+
24
+ import {
25
+ hasExactKeys,
26
+ isPid,
27
+ readSmallJson,
28
+ removeFileIfPresent,
29
+ sameFile,
30
+ statFile,
31
+ } from "./ledger-lock-fs.mjs";
32
+
33
+ /**
34
+ * Owner record published atomically as the lock file's content.
35
+ * @typedef {object} LockOwner
36
+ * @property {string} token - Unique per acquisition
37
+ * @property {number} pid - Holder process id
38
+ * @property {number} createdAt - Epoch ms the record was written
39
+ */
40
+
41
+ /**
42
+ * A lock judged reclaimable, anchoring the reclaim to that exact inode.
43
+ * @typedef {object} StaleObservation
44
+ * @property {LockOwner|undefined} owner - Owner when readable
45
+ * @property {number} dev - Device of the judged inode
46
+ * @property {number} ino - Judged inode
47
+ */
48
+
49
+ /**
50
+ * How staleness is judged.
51
+ * @typedef {object} StalePolicy
52
+ * @property {(pid: number) => boolean} isLive - Pid liveness probe
53
+ * @property {number} staleMs - Age after which an UNOWNED lock is stale
54
+ * @property {() => number} bootTimeMs - When this host booted (epoch ms)
55
+ */
56
+
57
+ /**
58
+ * How far before boot a lock must have been created to count as pre-boot, so
59
+ * clock skew or uptime rounding never marks a lock from this boot stale.
60
+ */
61
+ const BOOT_MARGIN_MS = 1_000;
62
+
63
+ /**
64
+ * Read the lock's owner record; anything malformed is unowned.
65
+ * @param {string} lockPath - Lock (or pinned link) path
66
+ * @returns {Promise<LockOwner|undefined>} Owner, or undefined
67
+ */
68
+ export async function readLockOwner(lockPath) {
69
+ const parsed = await readSmallJson(lockPath);
70
+ if (!hasExactKeys(parsed, ["token", "pid", "createdAt"])) return undefined;
71
+ const { token, pid, createdAt } = /** @type {LockOwner} */ (parsed);
72
+ const valid =
73
+ typeof token === "string" &&
74
+ /^[A-Za-z0-9-]{1,128}$/u.test(token) &&
75
+ isPid(pid) &&
76
+ Number.isSafeInteger(createdAt);
77
+ return valid ? { token, pid, createdAt } : undefined;
78
+ }
79
+
80
+ /**
81
+ * Whether an observed lock (owner plus file age) may be reclaimed. A readable
82
+ * owner is stale when its pid is dead, or when it was created before this
83
+ * boot: pids are reused across reboots, so a live pid then proves nothing,
84
+ * and no process alive now can have created a lock before the host booted —
85
+ * so this still never breaks a live holder. Age alone never reclaims a
86
+ * readable owner; it decides only for a lock whose owner record is unreadable.
87
+ * @param {LockOwner|undefined} owner - Owner, when readable
88
+ * @param {number} mtimeMs - Lock file modification time
89
+ * @param {StalePolicy} policy - Staleness policy
90
+ * @returns {boolean} Whether it is stale
91
+ */
92
+ function isStale(owner, mtimeMs, policy) {
93
+ if (owner !== undefined)
94
+ return (
95
+ owner.createdAt < policy.bootTimeMs() - BOOT_MARGIN_MS ||
96
+ !policy.isLive(owner.pid)
97
+ );
98
+ return Date.now() - mtimeMs > policy.staleMs;
99
+ }
100
+
101
+ /**
102
+ * Observe the lock and decide whether it is reclaimable.
103
+ * @param {string} lockPath - Lock path
104
+ * @param {StalePolicy} policy - Staleness policy
105
+ * @returns {Promise<StaleObservation|null>} Observation, or null when held/absent
106
+ */
107
+ export async function observeStaleLock(lockPath, policy) {
108
+ const before = await statFile(lockPath);
109
+ if (before === undefined) return null;
110
+ if (!before.isFile() || before.isSymbolicLink())
111
+ throw new Error(`session-manager ledger lock path is unsafe: ${lockPath}`);
112
+ const owner = await readLockOwner(lockPath);
113
+ if (!isStale(owner, Number(before.mtimeMs), policy)) return null;
114
+ return { owner, dev: Number(before.dev), ino: Number(before.ino) };
115
+ }
116
+
117
+ /**
118
+ * Reclaim the lock if it is stale, deleting only the inode judged stale.
119
+ * @param {string} lockPath - Lock path
120
+ * @param {StalePolicy} policy - Staleness policy
121
+ * @returns {Promise<boolean>} Whether a stale lock was removed
122
+ */
123
+ export async function reclaimStaleLock(lockPath, policy) {
124
+ const observation = await observeStaleLock(lockPath, policy);
125
+ if (observation === null) return false;
126
+ const capability = capabilityPath(lockPath, observation);
127
+ if (!(await claimCapability(capability, policy))) return false;
128
+ try {
129
+ return await deleteObservedGeneration(lockPath, observation, policy);
130
+ } finally {
131
+ await removeFileIfPresent(capability);
132
+ }
133
+ }
134
+
135
+ /**
136
+ * The capability path for one lock generation: a pure function of its
137
+ * identity, so every observer of the same lock contends for the same path.
138
+ * @param {string} lockPath - Lock path
139
+ * @param {StaleObservation} observation - Judged generation
140
+ * @returns {string} Capability path
141
+ */
142
+ function capabilityPath(lockPath, { dev, ino, owner }) {
143
+ const identity = [dev, ino, owner?.token, owner?.pid, owner?.createdAt];
144
+ const serialized = JSON.stringify(identity.map(part => part ?? null));
145
+ const digest = createHash("sha256").update(serialized).digest("hex");
146
+ return `${lockPath}.${digest.slice(0, 32)}.reclaim`;
147
+ }
148
+
149
+ /**
150
+ * Take the capability, displacing it only from a provably dead holder.
151
+ * @param {string} capability - Capability path
152
+ * @param {StalePolicy} policy - Staleness policy
153
+ * @returns {Promise<boolean>} Whether this process holds it
154
+ */
155
+ async function claimCapability(capability, policy) {
156
+ if (await createCapability(capability)) return true;
157
+ if (!(await breakDeadCapability(capability, policy))) return false;
158
+ return createCapability(capability);
159
+ }
160
+
161
+ /**
162
+ * Publish this process as capability holder with an exclusive create.
163
+ * @param {string} capability - Capability path
164
+ * @returns {Promise<boolean>} Whether the create won
165
+ */
166
+ async function createCapability(capability) {
167
+ const holder = JSON.stringify({ pid: process.pid, createdAt: Date.now() });
168
+ try {
169
+ await writeFile(capability, holder, { encoding: "utf8", flag: "wx" });
170
+ return true;
171
+ } catch (error) {
172
+ if (error?.code === "EEXIST") return false;
173
+ throw error;
174
+ }
175
+ }
176
+
177
+ /**
178
+ * Free a capability abandoned by a reclaimer that died mid-reclaim. Only a
179
+ * dead holder is displaced (a dead process unlinks nothing), and the
180
+ * displacement is one atomic rename, so concurrent breakers cannot both win.
181
+ * @param {string} capability - Capability path
182
+ * @param {StalePolicy} policy - Staleness policy
183
+ * @returns {Promise<boolean>} Whether it was freed
184
+ */
185
+ async function breakDeadCapability(capability, policy) {
186
+ const holder = await readSmallJson(capability);
187
+ const pid = hasExactKeys(holder, ["pid", "createdAt"])
188
+ ? /** @type {{pid: unknown}} */ (holder).pid
189
+ : undefined;
190
+ if (!isPid(pid) || policy.isLive(/** @type {number} */ (pid))) return false;
191
+ const discarded = `${capability}.${randomUUID()}.broken`;
192
+ try {
193
+ await rename(capability, discarded);
194
+ } catch (error) {
195
+ if (error?.code === "ENOENT") return true;
196
+ throw error;
197
+ }
198
+ await removeFileIfPresent(discarded);
199
+ return true;
200
+ }
201
+
202
+ /**
203
+ * Hard-link the current lock to a quarantine path; false if it is gone.
204
+ * @param {string} lockPath - Lock path
205
+ * @param {string} quarantine - Quarantine path
206
+ * @returns {Promise<boolean>} Whether the pin was made
207
+ */
208
+ async function pin(lockPath, quarantine) {
209
+ try {
210
+ await link(lockPath, quarantine);
211
+ return true;
212
+ } catch (error) {
213
+ if (error?.code === "ENOENT" || error?.code === "EEXIST") return false;
214
+ throw error;
215
+ }
216
+ }
217
+
218
+ /**
219
+ * With the capability held, pin the inode now at the lock path, prove it is
220
+ * still the generation judged stale, and only then unlink it.
221
+ * @param {string} lockPath - Lock path
222
+ * @param {StaleObservation} observation - Judged generation
223
+ * @param {StalePolicy} policy - Staleness policy
224
+ * @returns {Promise<boolean>} Whether it was removed
225
+ */
226
+ async function deleteObservedGeneration(lockPath, observation, policy) {
227
+ const quarantine = `${lockPath}.${randomUUID()}.stale`;
228
+ if (!(await pin(lockPath, quarantine))) return false;
229
+ try {
230
+ if (!(await stillStale(lockPath, quarantine, observation, policy)))
231
+ return false;
232
+ await removeFileIfPresent(lockPath);
233
+ if (observation.owner !== undefined)
234
+ await removeFileIfPresent(`${lockPath}.${observation.owner.token}.owner`);
235
+ return true;
236
+ } finally {
237
+ await removeFileIfPresent(quarantine);
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Whether the pinned inode is still the judged generation and still stale.
243
+ * Identity alone is not enough: a released inode can be recycled by a live
244
+ * holder, so the owner record must match the observed one exactly.
245
+ * @param {string} lockPath - Lock path
246
+ * @param {string} quarantine - Pin of the inode now at the lock path
247
+ * @param {StaleObservation} observation - Judged generation
248
+ * @param {StalePolicy} policy - Staleness policy
249
+ * @returns {Promise<boolean>} Whether it is safe to delete
250
+ */
251
+ async function stillStale(lockPath, quarantine, observation, policy) {
252
+ const pinned = await statFile(quarantine);
253
+ const sameInode =
254
+ pinned?.isFile() === true &&
255
+ Number(pinned.dev) === observation.dev &&
256
+ Number(pinned.ino) === observation.ino &&
257
+ (await sameFile(lockPath, quarantine));
258
+ if (!sameInode) return false;
259
+ const owner = await readLockOwner(quarantine);
260
+ const expected = observation.owner;
261
+ const sameOwner =
262
+ owner?.token === expected?.token &&
263
+ owner?.pid === expected?.pid &&
264
+ owner?.createdAt === expected?.createdAt;
265
+ return sameOwner && isStale(owner, Number(pinned.mtimeMs), policy);
266
+ }