@codyswann/lisa 4.107.8 → 4.107.10

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 (111) 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 +31 -2
  5. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  6. package/package.json +4 -4
  7. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  8. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  9. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  10. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  11. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  12. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  13. package/plugins/lisa/.codex-plugin/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  14. package/plugins/lisa/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  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/first-prompt.mjs +52 -6
  21. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  22. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  23. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  24. package/plugins/lisa-agy/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  25. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  26. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  27. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  28. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  29. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  30. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  31. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  32. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  33. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  34. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  35. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  36. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  37. package/plugins/lisa-copilot/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  38. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  40. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  41. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  42. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  43. package/plugins/lisa-cursor/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  44. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  46. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  47. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  48. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  49. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  50. package/plugins/lisa-devin/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
  51. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  53. package/plugins/lisa-expo-agy/plugin.json +1 -1
  54. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  55. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  57. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  58. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  60. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  61. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  62. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  64. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  65. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  67. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  68. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  69. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  71. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  72. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  74. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  75. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  76. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  78. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  79. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  81. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  82. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  83. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  85. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  86. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  88. package/plugins/lisa-rails-agy/plugin.json +1 -1
  89. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  90. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  92. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  93. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  95. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  96. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  97. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  98. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  99. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  100. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  102. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  103. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  104. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  105. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  106. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  107. package/plugins/src/base/skills/lisa-session-manager/scripts/first-prompt.mjs +52 -6
  108. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock-fs.mjs +124 -0
  109. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock-reclaim.mjs +266 -0
  110. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger-lock.mjs +228 -0
  111. package/plugins/src/base/skills/lisa-session-manager/scripts/ledger.mjs +24 -7
@@ -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
+ }
@@ -0,0 +1,228 @@
1
+ /**
2
+ * Cross-process lock serializing the ledger's read-modify-write
3
+ * (CodySwannGT/lisa#4828).
4
+ *
5
+ * Several `session-manager.mjs` processes write one ledger file (the cycle,
6
+ * worker finishes, answers, the per-cycle heartbeat). Each write reads the
7
+ * whole file, changes it and writes it back, so without a lock the later of
8
+ * two overlapping writers silently discarded the earlier one — a lost `finish`
9
+ * or `set-question` meant a duplicate dispatch or an unanswered question.
10
+ *
11
+ * Design, mirrored from the learnings-ledger lock (`src/core/learnings-lock.ts`,
12
+ * ported because plugin scripts ship standalone):
13
+ * - The lock is `<ledger>.lock`, beside the ledger. A holder writes its owner
14
+ * record (`{token, pid, createdAt}`) in full to a private `.owner` file, then
15
+ * publishes it with `link(owner, lock)`. The link is atomic and fails with
16
+ * EEXIST while someone holds the lock, so a reader never sees half a record.
17
+ * - Release unlinks the lock only while it is still the same inode as this
18
+ * holder's own owner file, so a writer never removes another's lock.
19
+ * - Defaults: retry for up to {@link LOCK_TIMEOUT_MS} (5s) with jittered
20
+ * exponential backoff starting at {@link BACKOFF_START_MS} (25ms), capped at
21
+ * {@link BACKOFF_MAX_MS}. On timeout the command fails with a clear error and
22
+ * writes nothing — never a write without the lock.
23
+ * - Staleness: a lock whose recorded pid is not alive on this host is stale,
24
+ * and so is one created before this boot (pids are reused after a reboot;
25
+ * no live process can have created a lock before the host booted, so this
26
+ * still never breaks a live holder).
27
+ * The ticket also said "or older than 30 seconds"; that is deliberately
28
+ * narrowed. Age ({@link STALE_UNOWNED_MS}) decides only when the owner record
29
+ * is unreadable, because reclaiming a LIVE holder by age would break the
30
+ * "a live lock is never broken" guarantee the same ticket requires.
31
+ * - Reclaim is atomic (see `ledger-lock-reclaim.mjs`): a live lock is never
32
+ * deleted, even by two reclaimers racing.
33
+ * @module ledger-lock
34
+ */
35
+
36
+ import { randomInt, randomUUID } from "node:crypto";
37
+ import { link, writeFile } from "node:fs/promises";
38
+
39
+ import {
40
+ bootTimeMs,
41
+ isProcessLive,
42
+ removeFileIfPresent,
43
+ sameFile,
44
+ } from "./ledger-lock-fs.mjs";
45
+ import { readLockOwner, reclaimStaleLock } from "./ledger-lock-reclaim.mjs";
46
+
47
+ /** Total wall-clock budget for one acquisition. */
48
+ export const LOCK_TIMEOUT_MS = 5_000;
49
+
50
+ /** First retry delay; each later one doubles, plus jitter. */
51
+ const BACKOFF_START_MS = 25;
52
+
53
+ /** Ceiling on one retry delay, so a waiter keeps probing a freed lock. */
54
+ const BACKOFF_MAX_MS = 250;
55
+
56
+ /** Age after which a lock with an unreadable owner record is stale. */
57
+ const STALE_UNOWNED_MS = 30_000;
58
+
59
+ /**
60
+ * Injectable lock seams; production uses the defaults.
61
+ * @typedef {object} LockSeams
62
+ * @property {number} [lockTimeoutMs] - Acquisition budget
63
+ * @property {(ms: number) => Promise<void>} [sleep] - Retry delay
64
+ * @property {(pid: number) => boolean} [isProcessLive] - Pid liveness probe
65
+ * @property {() => number} [bootTimeMs] - Host boot time (epoch ms)
66
+ */
67
+
68
+ /**
69
+ * Wait without blocking the event loop.
70
+ * @param {number} ms - Delay
71
+ * @returns {Promise<void>}
72
+ */
73
+ function defaultSleep(ms) {
74
+ return new Promise(resolve => {
75
+ setTimeout(resolve, ms);
76
+ });
77
+ }
78
+
79
+ /**
80
+ * Jittered exponential backoff for one retry: the base doubles from
81
+ * {@link BACKOFF_START_MS} up to {@link BACKOFF_MAX_MS}, and jitter of up to
82
+ * the base again keeps contenders that lost one race from colliding in step.
83
+ * @param {number} attempt - Zero-based retry count
84
+ * @returns {number} Delay in ms
85
+ */
86
+ function backoffMs(attempt) {
87
+ const base = Math.min(BACKOFF_START_MS * 2 ** attempt, BACKOFF_MAX_MS);
88
+ return base + randomInt(0, base + 1);
89
+ }
90
+
91
+ /**
92
+ * Try to publish the owner record as the lock.
93
+ * @param {string} ownerPath - Fully written owner file
94
+ * @param {string} lockPath - Lock path
95
+ * @returns {Promise<"acquired"|"held"|"owner-missing">} Outcome
96
+ */
97
+ async function tryPublish(ownerPath, lockPath) {
98
+ try {
99
+ await link(ownerPath, lockPath);
100
+ return "acquired";
101
+ } catch (error) {
102
+ if (error?.code === "EEXIST") return "held";
103
+ if (error?.code === "ENOENT") return "owner-missing";
104
+ throw error;
105
+ }
106
+ }
107
+
108
+ /**
109
+ * Write the owner record exclusively, so two acquisitions never share one.
110
+ * @param {string} ownerPath - Owner file path
111
+ * @param {string} record - Serialized owner record
112
+ * @returns {Promise<void>}
113
+ */
114
+ function writeOwner(ownerPath, record) {
115
+ return writeFile(ownerPath, record, { encoding: "utf8", flag: "wx" });
116
+ }
117
+
118
+ /**
119
+ * The error a writer fails with when the lock stays held past its budget.
120
+ * @param {string} lockPath - Lock path
121
+ * @param {number} timeoutMs - Budget that ran out
122
+ * @returns {Promise<Error>} Error naming the holder's pid when readable
123
+ */
124
+ async function timeoutError(lockPath, timeoutMs) {
125
+ const holder = await readLockOwner(lockPath);
126
+ const by = holder ? `held by pid ${holder.pid}` : "holder unknown";
127
+ const hint = holder
128
+ ? `if pid ${holder.pid} is not a running session-manager process, delete ${lockPath}`
129
+ : `if no session-manager process is running, delete ${lockPath}`;
130
+ return new Error(
131
+ `session-manager ledger lock timed out after ${timeoutMs}ms: ${lockPath} (${by}); ${hint}; no ledger change was written`
132
+ );
133
+ }
134
+
135
+ /**
136
+ * Retry publication until acquired or the budget ends.
137
+ * @param {{lockPath: string, ownerPath: string, record: string}} lease - Lease
138
+ * @param {Required<LockSeams>} seams - Resolved seams
139
+ * @returns {Promise<void>}
140
+ */
141
+ async function acquire(lease, seams) {
142
+ const { lockPath, ownerPath, record } = lease;
143
+ const policy = {
144
+ isLive: seams.isProcessLive,
145
+ staleMs: STALE_UNOWNED_MS,
146
+ bootTimeMs: seams.bootTimeMs,
147
+ };
148
+ const deadline = Date.now() + seams.lockTimeoutMs;
149
+ for (let attempt = 0; ; attempt += 1) {
150
+ const outcome = await tryPublish(ownerPath, lockPath);
151
+ if (outcome === "acquired") return;
152
+ if (outcome === "owner-missing") await writeOwner(ownerPath, record);
153
+ else if (await reclaimStaleLock(lockPath, policy)) continue;
154
+ if (Date.now() >= deadline)
155
+ throw await timeoutError(lockPath, seams.lockTimeoutMs);
156
+ await seams.sleep(backoffMs(attempt));
157
+ }
158
+ }
159
+
160
+ /**
161
+ * Remove the lock only while it is still this holder's inode.
162
+ * @param {string} lockPath - Lock path
163
+ * @param {string} ownerPath - This holder's owner file
164
+ * @returns {Promise<void>}
165
+ */
166
+ async function release(lockPath, ownerPath) {
167
+ try {
168
+ if (await sameFile(lockPath, ownerPath))
169
+ await removeFileIfPresent(lockPath);
170
+ } finally {
171
+ await removeFileIfPresent(ownerPath);
172
+ }
173
+ }
174
+
175
+ /**
176
+ * Run `operation` while holding the cross-process lock beside `target`.
177
+ * @template T
178
+ * @param {string} target - File the lock guards (the ledger)
179
+ * @param {LockSeams | undefined} seams - Injected seams
180
+ * @param {() => Promise<T>} operation - Whole read-modify-write
181
+ * @returns {Promise<T>} The operation's result
182
+ */
183
+ export async function withLedgerLock(target, seams, operation) {
184
+ const resolved = {
185
+ lockTimeoutMs: seams?.lockTimeoutMs ?? LOCK_TIMEOUT_MS,
186
+ sleep: seams?.sleep ?? defaultSleep,
187
+ isProcessLive: seams?.isProcessLive ?? isProcessLive,
188
+ bootTimeMs: seams?.bootTimeMs ?? bootTimeMs,
189
+ };
190
+ const lockPath = `${target}.lock`;
191
+ const token = randomUUID();
192
+ const ownerPath = `${lockPath}.${token}.owner`;
193
+ const record = JSON.stringify({
194
+ token,
195
+ pid: process.pid,
196
+ createdAt: Date.now(),
197
+ });
198
+ await writeOwner(ownerPath, record);
199
+ try {
200
+ await acquire({ lockPath, ownerPath, record }, resolved);
201
+ } catch (error) {
202
+ await removeFileIfPresent(ownerPath);
203
+ throw error;
204
+ }
205
+ try {
206
+ return await operation();
207
+ } finally {
208
+ await releaseQuietly(lockPath, ownerPath);
209
+ }
210
+ }
211
+
212
+ /**
213
+ * Release without letting a release failure replace the operation's result
214
+ * or mask its own error: the ledger write has already happened (or failed)
215
+ * by now, so a cleanup problem is reported as a one-line warning instead.
216
+ * @param {string} lockPath - Lock path
217
+ * @param {string} ownerPath - This holder's owner file
218
+ * @returns {Promise<void>}
219
+ */
220
+ async function releaseQuietly(lockPath, ownerPath) {
221
+ try {
222
+ await release(lockPath, ownerPath);
223
+ } catch (error) {
224
+ process.stderr.write(
225
+ `session-manager ledger lock release failed for ${lockPath}: ${error?.message ?? String(error)}\n`
226
+ );
227
+ }
228
+ }
@@ -12,8 +12,13 @@
12
12
  * is refused, not replaced, because replacing it would silently reset every
13
13
  * attempt count.
14
14
  *
15
+ * Several processes write the ledger, so `updateLedger` holds a cross-process
16
+ * lock (`ledger-lock.mjs`, #4828) across its whole read, change and write; an
17
+ * unlocked overlap let the later writer silently discard the earlier one.
18
+ *
15
19
  * File I/O and the clock are injected (`{fs, now}`) so tests can observe the
16
- * rename and pin timestamps. Nothing here reads `process.env` or a tracker.
20
+ * rename and pin timestamps; the lock's budget, sleep and pid probe are
21
+ * injectable too. Nothing here reads `process.env` or a tracker.
17
22
  * @module ledger
18
23
  */
19
24
 
@@ -21,6 +26,8 @@ import { randomUUID } from "node:crypto";
21
26
  import * as nodeFs from "node:fs/promises";
22
27
  import { dirname, join } from "node:path";
23
28
 
29
+ import { withLedgerLock } from "./ledger-lock.mjs";
30
+
24
31
  // The question writers live in ledger-questions.mjs (#4555), re-exported so
25
32
  // callers keep one import. They are called, never evaluated, at load time, so
26
33
  // the import cycle back to this module's primitives is safe.
@@ -42,6 +49,10 @@ const FINISH_STATUSES = new Set(["DONE", "FAILED"]);
42
49
  * @typedef {object} LedgerSeams
43
50
  * @property {Pick<typeof nodeFs, "readFile"|"writeFile"|"rename"|"mkdir"|"appendFile">} [fs] - File system
44
51
  * @property {() => Date} [now] - Clock
52
+ * @property {number} [lockTimeoutMs] - Ledger lock budget (default 5000)
53
+ * @property {(ms: number) => Promise<void>} [sleep] - Lock retry delay
54
+ * @property {(pid: number) => boolean} [isProcessLive] - Lock holder probe
55
+ * @property {() => number} [bootTimeMs] - Host boot time for the lock (epoch ms)
45
56
  */
46
57
 
47
58
  /**
@@ -220,7 +231,9 @@ export async function writeLedger(projectRoot, ledger, seams) {
220
231
  }
221
232
 
222
233
  /**
223
- * Read, transform and write the ledger in one step.
234
+ * Read, transform and write the ledger in one step, holding the ledger lock
235
+ * across all three so a concurrent writer cannot interleave (#4828). A lock
236
+ * that stays held past its budget throws and nothing is written.
224
237
  * @template T
225
238
  * @param {string} projectRoot - Absolute project root
226
239
  * @param {LedgerSeams | undefined} seams - Injected seams
@@ -228,11 +241,15 @@ export async function writeLedger(projectRoot, ledger, seams) {
228
241
  * @returns {Promise<T>} The transform's result
229
242
  */
230
243
  export async function updateLedger(projectRoot, seams, transform) {
231
- const { now } = resolveSeams(seams);
232
- const current = await readLedger(projectRoot, seams);
233
- const { ledger, result } = transform(current, now().toISOString());
234
- await writeLedger(projectRoot, ledger, seams);
235
- return result;
244
+ const { fs, now } = resolveSeams(seams);
245
+ const file = ledgerPath(projectRoot);
246
+ await fs.mkdir(dirname(file), { recursive: true });
247
+ return withLedgerLock(file, seams, async () => {
248
+ const current = await readLedger(projectRoot, seams);
249
+ const { ledger, result } = transform(current, now().toISOString());
250
+ await writeLedger(projectRoot, ledger, seams);
251
+ return result;
252
+ });
236
253
  }
237
254
 
238
255
  /**
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "lisa",
3
- "version": "4.107.8",
3
+ "version": "4.107.10",
4
4
  "description": "Universal governance — agents, skills, commands, hooks, and rules for all projects",
5
5
  "author": {
6
6
  "name": "Cody Swann"
@@ -19,9 +19,12 @@
19
19
  * setup gaps, not as a worker that is still working. The transcript lives at
20
20
  * `<config dir>/projects/<cwd, every non-alphanumeric character as "-">/
21
21
  * <full session id>.jsonl`; Claude Code files a symlinked cwd under its real
22
- * path. Only `system` entries count as the failure, so text a user or the
23
- * model typed can never trip it, and any assistant turn proves the worker is
24
- * alive. A missing transcript gives no verdict — never a failure.
22
+ * path. When that encoded name is longer than 200 characters, Claude Code
23
+ * keeps its first 200 and appends a hash (lisa#4821), so a deep checkout is
24
+ * found by that prefix instead (see {@link projectDirsFor}). Only `system`
25
+ * entries count as the failure, so text a user or the model typed can never
26
+ * trip it, and any assistant turn proves the worker is alive. A missing or
27
+ * ambiguous transcript gives no verdict — never a failure.
25
28
  * @module session-manager/first-prompt
26
29
  */
27
30
  import { readFileSync, readdirSync, realpathSync } from "node:fs";
@@ -127,6 +130,48 @@ export function encodeProjectDir(cwd) {
127
130
  return cwd.replace(/[^A-Za-z0-9]/g, "-");
128
131
  }
129
132
 
133
+ /**
134
+ * Longest `projects/` directory name Claude Code keeps whole.
135
+ *
136
+ * Rule read from the Claude Code 2.1.319 binary and confirmed with a real
137
+ * `claude -p` run in a 241-character cwd (lisa#4821): with `s` the encoded
138
+ * cwd, the name is `s` when `s.length <= 200`, else
139
+ * `${s.slice(0, 200)}-${Math.abs(h).toString(36)}`, where `h` is the 32-bit
140
+ * Java string hash of the raw cwd.
141
+ */
142
+ const PROJECT_DIR_LIMIT = 200;
143
+
144
+ /**
145
+ * The `projects/` directories that may hold a cwd's transcripts: the exact
146
+ * encoded name for a short cwd; for a long one, the exact untruncated name
147
+ * (in case a Claude Code version without the truncation rule wrote it) plus
148
+ * every directory whose name starts with the truncated prefix and a dash.
149
+ * The dash keeps out a parent whose own encoded name is exactly that
150
+ * 200-character prefix. The prefix is matched rather
151
+ * than the hash recomputed, so the hash is never relied on; the caller's
152
+ * exactly-one-match rule turns two directories that both (or neither) hold
153
+ * the session into no verdict.
154
+ * @param {string} projectsDir - `<config dir>/projects`
155
+ * @param {string} cwd - Session cwd
156
+ * @returns {string[]} Directory paths
157
+ */
158
+ function projectDirsFor(projectsDir, cwd) {
159
+ const encoded = encodeProjectDir(cwd);
160
+ if (encoded.length <= PROJECT_DIR_LIMIT) {
161
+ return [path.join(projectsDir, encoded)];
162
+ }
163
+ const exact = path.join(projectsDir, encoded);
164
+ const prefix = `${encoded.slice(0, PROJECT_DIR_LIMIT)}-`;
165
+ try {
166
+ const truncated = readdirSync(projectsDir)
167
+ .filter(name => name.startsWith(prefix))
168
+ .map(name => path.join(projectsDir, name));
169
+ return [...new Set([exact, ...truncated])];
170
+ } catch {
171
+ return [exact];
172
+ }
173
+ }
174
+
130
175
  /**
131
176
  * The cwd and, when different, its real path.
132
177
  * @param {string} cwd - Session cwd
@@ -172,9 +217,10 @@ function matchesIn(dir, id) {
172
217
  export function findTranscript({ configDir, cwd, sessionId }) {
173
218
  const id = String(sessionId ?? "").toLowerCase();
174
219
  if (!/^[0-9a-f]{8}(?:-[0-9a-f-]{27})?$/.test(id)) return null;
175
- const found = cwdCandidates(cwd).flatMap(candidate =>
176
- matchesIn(path.join(configDir, "projects", encodeProjectDir(candidate)), id)
177
- );
220
+ const projectsDir = path.join(configDir, "projects");
221
+ const found = cwdCandidates(cwd)
222
+ .flatMap(candidate => projectDirsFor(projectsDir, candidate))
223
+ .flatMap(dir => matchesIn(dir, id));
178
224
  const unique = [...new Set(found)];
179
225
  return unique.length === 1 ? unique[0] : null;
180
226
  }