agent-recall-core 3.4.48 → 3.4.50

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 (234) hide show
  1. package/README.md +25 -0
  2. package/dist/digest/store.d.ts +15 -6
  3. package/dist/digest/store.d.ts.map +1 -1
  4. package/dist/digest/store.js +33 -20
  5. package/dist/digest/store.js.map +1 -1
  6. package/dist/embeddings/chunker.d.ts +102 -0
  7. package/dist/embeddings/chunker.d.ts.map +1 -0
  8. package/dist/embeddings/chunker.js +260 -0
  9. package/dist/embeddings/chunker.js.map +1 -0
  10. package/dist/embeddings/config.d.ts +93 -0
  11. package/dist/embeddings/config.d.ts.map +1 -0
  12. package/dist/embeddings/config.js +174 -0
  13. package/dist/embeddings/config.js.map +1 -0
  14. package/dist/embeddings/index-store.d.ts +61 -0
  15. package/dist/embeddings/index-store.d.ts.map +1 -0
  16. package/dist/embeddings/index-store.js +158 -0
  17. package/dist/embeddings/index-store.js.map +1 -0
  18. package/dist/embeddings/indexer.d.ts +75 -0
  19. package/dist/embeddings/indexer.d.ts.map +1 -0
  20. package/dist/embeddings/indexer.js +196 -0
  21. package/dist/embeddings/indexer.js.map +1 -0
  22. package/dist/embeddings/runtime.d.ts +66 -0
  23. package/dist/embeddings/runtime.d.ts.map +1 -0
  24. package/dist/embeddings/runtime.js +197 -0
  25. package/dist/embeddings/runtime.js.map +1 -0
  26. package/dist/helpers/associative-link.d.ts.map +1 -1
  27. package/dist/helpers/associative-link.js +26 -1
  28. package/dist/helpers/associative-link.js.map +1 -1
  29. package/dist/helpers/tokenize.d.ts +1 -0
  30. package/dist/helpers/tokenize.d.ts.map +1 -1
  31. package/dist/helpers/tokenize.js +18 -0
  32. package/dist/helpers/tokenize.js.map +1 -1
  33. package/dist/index.d.ts +27 -7
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +42 -5
  36. package/dist/index.js.map +1 -1
  37. package/dist/palace/awareness.d.ts +56 -10
  38. package/dist/palace/awareness.d.ts.map +1 -1
  39. package/dist/palace/awareness.js +279 -182
  40. package/dist/palace/awareness.js.map +1 -1
  41. package/dist/palace/consolidate.d.ts +1 -1
  42. package/dist/palace/consolidate.d.ts.map +1 -1
  43. package/dist/palace/consolidate.js +9 -9
  44. package/dist/palace/consolidate.js.map +1 -1
  45. package/dist/palace/decay-pass.d.ts +1 -1
  46. package/dist/palace/decay-pass.d.ts.map +1 -1
  47. package/dist/palace/decay-pass.js +2 -2
  48. package/dist/palace/decay-pass.js.map +1 -1
  49. package/dist/palace/fan-out.d.ts +1 -1
  50. package/dist/palace/fan-out.d.ts.map +1 -1
  51. package/dist/palace/fan-out.js +5 -5
  52. package/dist/palace/fan-out.js.map +1 -1
  53. package/dist/palace/index-manager.d.ts +1 -1
  54. package/dist/palace/index-manager.d.ts.map +1 -1
  55. package/dist/palace/index-manager.js +1 -1
  56. package/dist/palace/index-manager.js.map +1 -1
  57. package/dist/palace/insights-index.d.ts +19 -6
  58. package/dist/palace/insights-index.d.ts.map +1 -1
  59. package/dist/palace/insights-index.js +36 -13
  60. package/dist/palace/insights-index.js.map +1 -1
  61. package/dist/palace/keystone.d.ts +1 -1
  62. package/dist/palace/keystone.d.ts.map +1 -1
  63. package/dist/palace/keystone.js +2 -2
  64. package/dist/palace/keystone.js.map +1 -1
  65. package/dist/palace/rooms.d.ts +3 -3
  66. package/dist/palace/rooms.d.ts.map +1 -1
  67. package/dist/palace/rooms.js +34 -6
  68. package/dist/palace/rooms.js.map +1 -1
  69. package/dist/prompts/consolidation-prompt.d.ts.map +1 -1
  70. package/dist/prompts/consolidation-prompt.js +5 -0
  71. package/dist/prompts/consolidation-prompt.js.map +1 -1
  72. package/dist/retrieval/candidates.d.ts.map +1 -1
  73. package/dist/retrieval/candidates.js +17 -2
  74. package/dist/retrieval/candidates.js.map +1 -1
  75. package/dist/retrieval/query-memory.d.ts +65 -7
  76. package/dist/retrieval/query-memory.d.ts.map +1 -1
  77. package/dist/retrieval/query-memory.js +518 -78
  78. package/dist/retrieval/query-memory.js.map +1 -1
  79. package/dist/retrieval/semantic-leg.d.ts +74 -0
  80. package/dist/retrieval/semantic-leg.d.ts.map +1 -0
  81. package/dist/retrieval/semantic-leg.js +180 -0
  82. package/dist/retrieval/semantic-leg.js.map +1 -0
  83. package/dist/storage/archive-write.d.ts.map +1 -1
  84. package/dist/storage/archive-write.js +29 -8
  85. package/dist/storage/archive-write.js.map +1 -1
  86. package/dist/storage/capture-router.d.ts +1 -1
  87. package/dist/storage/capture-router.d.ts.map +1 -1
  88. package/dist/storage/capture-router.js +26 -9
  89. package/dist/storage/capture-router.js.map +1 -1
  90. package/dist/storage/consolidation-queue.d.ts +11 -2
  91. package/dist/storage/consolidation-queue.d.ts.map +1 -1
  92. package/dist/storage/consolidation-queue.js +45 -16
  93. package/dist/storage/consolidation-queue.js.map +1 -1
  94. package/dist/storage/corrections.d.ts +53 -5
  95. package/dist/storage/corrections.d.ts.map +1 -1
  96. package/dist/storage/corrections.js +412 -124
  97. package/dist/storage/corrections.js.map +1 -1
  98. package/dist/storage/dream-health.d.ts +56 -8
  99. package/dist/storage/dream-health.d.ts.map +1 -1
  100. package/dist/storage/dream-health.js +130 -35
  101. package/dist/storage/dream-health.js.map +1 -1
  102. package/dist/storage/dream-yield.d.ts +81 -0
  103. package/dist/storage/dream-yield.d.ts.map +1 -0
  104. package/dist/storage/dream-yield.js +77 -0
  105. package/dist/storage/dream-yield.js.map +1 -0
  106. package/dist/storage/durable-intent.d.ts.map +1 -1
  107. package/dist/storage/durable-intent.js +24 -1
  108. package/dist/storage/durable-intent.js.map +1 -1
  109. package/dist/storage/filelock.d.ts +92 -12
  110. package/dist/storage/filelock.d.ts.map +1 -1
  111. package/dist/storage/filelock.js +317 -47
  112. package/dist/storage/filelock.js.map +1 -1
  113. package/dist/storage/fs-utils.d.ts +20 -0
  114. package/dist/storage/fs-utils.d.ts.map +1 -1
  115. package/dist/storage/fs-utils.js +27 -0
  116. package/dist/storage/fs-utils.js.map +1 -1
  117. package/dist/storage/paths.d.ts +34 -0
  118. package/dist/storage/paths.d.ts.map +1 -1
  119. package/dist/storage/paths.js +71 -0
  120. package/dist/storage/paths.js.map +1 -1
  121. package/dist/storage/pending.d.ts +154 -0
  122. package/dist/storage/pending.d.ts.map +1 -0
  123. package/dist/storage/pending.js +454 -0
  124. package/dist/storage/pending.js.map +1 -0
  125. package/dist/storage/project.d.ts.map +1 -1
  126. package/dist/storage/project.js +68 -16
  127. package/dist/storage/project.js.map +1 -1
  128. package/dist/storage/session-card.d.ts +13 -0
  129. package/dist/storage/session-card.d.ts.map +1 -1
  130. package/dist/storage/session-card.js +34 -3
  131. package/dist/storage/session-card.js.map +1 -1
  132. package/dist/storage/unclaimed.d.ts +165 -0
  133. package/dist/storage/unclaimed.d.ts.map +1 -0
  134. package/dist/storage/unclaimed.js +442 -0
  135. package/dist/storage/unclaimed.js.map +1 -0
  136. package/dist/storage/working-memory.d.ts.map +1 -1
  137. package/dist/storage/working-memory.js +19 -1
  138. package/dist/storage/working-memory.js.map +1 -1
  139. package/dist/supabase/recall-backend.d.ts +28 -2
  140. package/dist/supabase/recall-backend.d.ts.map +1 -1
  141. package/dist/supabase/recall-backend.js +80 -23
  142. package/dist/supabase/recall-backend.js.map +1 -1
  143. package/dist/supabase/sync.d.ts.map +1 -1
  144. package/dist/supabase/sync.js +13 -0
  145. package/dist/supabase/sync.js.map +1 -1
  146. package/dist/tools-logic/alignment-check.js +1 -1
  147. package/dist/tools-logic/alignment-check.js.map +1 -1
  148. package/dist/tools-logic/awareness-update.d.ts.map +1 -1
  149. package/dist/tools-logic/awareness-update.js +25 -16
  150. package/dist/tools-logic/awareness-update.js.map +1 -1
  151. package/dist/tools-logic/check-action.js +1 -1
  152. package/dist/tools-logic/check-action.js.map +1 -1
  153. package/dist/tools-logic/check.d.ts +55 -1
  154. package/dist/tools-logic/check.d.ts.map +1 -1
  155. package/dist/tools-logic/check.js +230 -57
  156. package/dist/tools-logic/check.js.map +1 -1
  157. package/dist/tools-logic/confidence.d.ts +11 -6
  158. package/dist/tools-logic/confidence.d.ts.map +1 -1
  159. package/dist/tools-logic/confidence.js +11 -6
  160. package/dist/tools-logic/confidence.js.map +1 -1
  161. package/dist/tools-logic/context-synthesize.js +2 -2
  162. package/dist/tools-logic/context-synthesize.js.map +1 -1
  163. package/dist/tools-logic/digest-read.js +2 -2
  164. package/dist/tools-logic/digest-read.js.map +1 -1
  165. package/dist/tools-logic/digest-recall.js +1 -1
  166. package/dist/tools-logic/digest-recall.js.map +1 -1
  167. package/dist/tools-logic/dream-admission.d.ts +144 -0
  168. package/dist/tools-logic/dream-admission.d.ts.map +1 -0
  169. package/dist/tools-logic/dream-admission.js +537 -0
  170. package/dist/tools-logic/dream-admission.js.map +1 -0
  171. package/dist/tools-logic/insight-promotion.d.ts +19 -1
  172. package/dist/tools-logic/insight-promotion.d.ts.map +1 -1
  173. package/dist/tools-logic/insight-promotion.js +48 -14
  174. package/dist/tools-logic/insight-promotion.js.map +1 -1
  175. package/dist/tools-logic/journal-capture.js +3 -3
  176. package/dist/tools-logic/journal-capture.js.map +1 -1
  177. package/dist/tools-logic/journal-write.js +3 -3
  178. package/dist/tools-logic/journal-write.js.map +1 -1
  179. package/dist/tools-logic/knowledge-write.js +2 -2
  180. package/dist/tools-logic/knowledge-write.js.map +1 -1
  181. package/dist/tools-logic/palace-lint.js +1 -1
  182. package/dist/tools-logic/palace-lint.js.map +1 -1
  183. package/dist/tools-logic/palace-read.js +1 -1
  184. package/dist/tools-logic/palace-read.js.map +1 -1
  185. package/dist/tools-logic/palace-search.js +1 -1
  186. package/dist/tools-logic/palace-search.js.map +1 -1
  187. package/dist/tools-logic/palace-walk.js +3 -3
  188. package/dist/tools-logic/palace-walk.js.map +1 -1
  189. package/dist/tools-logic/palace-write.js +4 -4
  190. package/dist/tools-logic/palace-write.js.map +1 -1
  191. package/dist/tools-logic/predict-correction.js +1 -1
  192. package/dist/tools-logic/predict-correction.js.map +1 -1
  193. package/dist/tools-logic/recall-backend.d.ts +11 -2
  194. package/dist/tools-logic/recall-backend.d.ts.map +1 -1
  195. package/dist/tools-logic/recall-backend.js +2 -2
  196. package/dist/tools-logic/recall-backend.js.map +1 -1
  197. package/dist/tools-logic/resurrect.d.ts.map +1 -1
  198. package/dist/tools-logic/resurrect.js +9 -1
  199. package/dist/tools-logic/resurrect.js.map +1 -1
  200. package/dist/tools-logic/safety-consolidation.d.ts +15 -0
  201. package/dist/tools-logic/safety-consolidation.d.ts.map +1 -1
  202. package/dist/tools-logic/safety-consolidation.js +44 -31
  203. package/dist/tools-logic/safety-consolidation.js.map +1 -1
  204. package/dist/tools-logic/session-end-reflect.d.ts.map +1 -1
  205. package/dist/tools-logic/session-end-reflect.js +4 -1
  206. package/dist/tools-logic/session-end-reflect.js.map +1 -1
  207. package/dist/tools-logic/session-end.d.ts +8 -0
  208. package/dist/tools-logic/session-end.d.ts.map +1 -1
  209. package/dist/tools-logic/session-end.js +51 -13
  210. package/dist/tools-logic/session-end.js.map +1 -1
  211. package/dist/tools-logic/session-start.d.ts +23 -0
  212. package/dist/tools-logic/session-start.d.ts.map +1 -1
  213. package/dist/tools-logic/session-start.js +44 -1
  214. package/dist/tools-logic/session-start.js.map +1 -1
  215. package/dist/tools-logic/smart-recall.d.ts +185 -10
  216. package/dist/tools-logic/smart-recall.d.ts.map +1 -1
  217. package/dist/tools-logic/smart-recall.js +363 -85
  218. package/dist/tools-logic/smart-recall.js.map +1 -1
  219. package/dist/tools-logic/store-doctor.d.ts.map +1 -1
  220. package/dist/tools-logic/store-doctor.js +14 -5
  221. package/dist/tools-logic/store-doctor.js.map +1 -1
  222. package/dist/tools-logic/store-repair.js +1 -1
  223. package/dist/tools-logic/store-repair.js.map +1 -1
  224. package/dist/tools-logic/supersession.d.ts +1 -1
  225. package/dist/tools-logic/supersession.d.ts.map +1 -1
  226. package/dist/tools-logic/supersession.js +2 -2
  227. package/dist/tools-logic/supersession.js.map +1 -1
  228. package/dist/types.d.ts +1 -1
  229. package/dist/types.js +1 -1
  230. package/dist/vector/embedding.d.ts +8 -0
  231. package/dist/vector/embedding.d.ts.map +1 -1
  232. package/dist/vector/embedding.js +8 -0
  233. package/dist/vector/embedding.js.map +1 -1
  234. package/package.json +1 -1
@@ -1,87 +1,357 @@
1
1
  /**
2
- * Simple file-based locking for shared global files (awareness, insights-index).
2
+ * File-based locking for shared store files (awareness, insights-index,
3
+ * corrections, digest, palace index/rooms, journal, pipeline, feedback,
4
+ * alignment).
3
5
  *
4
- * Uses mkdir atomicity: mkdir fails if dir already exists, which is
5
- * atomic on all platforms. No external dependencies.
6
+ * Uses mkdir atomicity: mkdir fails if dir already exists, which is atomic
7
+ * on all platforms. No external dependencies.
6
8
  *
7
- * Lock timeout: 5 seconds. Stale lock cleanup: 30 seconds.
9
+ * fix6-locks redesign (2026-09-11, S6 remediation):
10
+ *
11
+ * 1. WAITING IS ASYNC. The old primitive busy-wait spun the CPU and blocked
12
+ * the event loop for up to 5 s. `acquireLock`/`withLock` now await a
13
+ * setTimeout-based backoff, so a waiting process keeps serving its event
14
+ * loop (timers, MCP traffic, hook I/O) while contended.
15
+ *
16
+ * 2. NO STEALING FROM A LIVE HOLDER. The old primitive force-broke the lock
17
+ * unconditionally at timeout (rmdir+mkdir while the holder could be
18
+ * mid-write — silent corruption). The lock dir now records the holder's
19
+ * pid + acquisition timestamp (`owner.json`); a contender may reclaim
20
+ * ONLY when the holder process is provably dead (`process.kill(pid, 0)`
21
+ * probe). A dead holder is reclaimed immediately (no reason to wait out
22
+ * the timeout on a corpse); a live holder is NEVER stolen from — at
23
+ * timeout the contender gets a descriptive `LockContentionError` that
24
+ * callers handle explicitly (log + best-effort skip, or propagate),
25
+ * never silent corruption. Boot-time guard (review MEDIUM-1): a lock
26
+ * whose acquired_at predates the current boot is reclaimed even if its
27
+ * recorded pid probes alive — pids recycle across reboots, and no lock
28
+ * legitimately survives one.
29
+ *
30
+ * 3. RECLAIM IS RACE-SAFE. Reclaim renames the lock dir aside before
31
+ * removing it — rename is atomic, so when several contenders spot the
32
+ * same dead holder, exactly one wins the rename; the rest simply retry
33
+ * mkdir. (The old rmdir+mkdir reclaim let two contenders both "win".)
34
+ *
35
+ * 4. LEGACY/CRASH FALLBACK. A lock dir with no readable owner.json (created
36
+ * by pre-fix code, or a holder that died between mkdir and the owner
37
+ * write) falls back to the old mtime rule: reclaimable once older than
38
+ * STALE_LOCK_MS.
39
+ *
40
+ * CRITICAL SECTIONS: keep them synchronous wherever possible — hold times
41
+ * stay bounded by one synchronous block. An async fn is permitted ONLY for
42
+ * the documented lock nesting below (awareness-state → awareness); a critical
43
+ * section must NEVER await anything that acquires the SAME lock (the lock is
44
+ * not reentrant — that is a guaranteed 5 s stall + LockContentionError).
45
+ * Cross-process safety does not depend on the fn being sync: the mkdir lock
46
+ * itself excludes concurrent critical sections either way.
47
+ *
48
+ * LOCK ORDERING (deadlock discipline — the complete nesting set):
49
+ * "awareness-state" → "awareness"
50
+ * "dream-admission" → "insights-index"
51
+ * "dream-admission" → "awareness-state" → "awareness"
52
+ * awareness.ts acquires "awareness" (awareness.md render) while holding
53
+ * "awareness-state" (awareness-state.json + awareness-archive.json RMW).
54
+ * fix10: dream-admission.ts wraps its whole nightly run (a long async
55
+ * critical section) in "dream-admission" and acquires "insights-index"
56
+ * (addIndexedInsight) and "awareness-state" (addInsight via
57
+ * promoteConfirmedInsights / the cap fallback) inside it. "dream-admission"
58
+ * has a SINGLE acquirer and is always the outermost lock — no cycle.
59
+ * Never acquire "awareness-state" while holding "awareness", and never
60
+ * acquire "dream-admission" while holding any other lock. Same-name
61
+ * nesting is a deadlock (the lock is NOT reentrant): modules expose
62
+ * *Unlocked internals for use inside their own critical sections instead.
63
+ *
64
+ * fix9 (2026-09-12): the synchronous twin (`acquireLockSync`/`withLockSync`,
65
+ * Atomics.wait-based — no CPU spin, but it parked the whole event loop) is
66
+ * RETIRED. It existed only to pin the published sync SDK signature
67
+ * `AgentRecall.digestInvalidate(): void`; the owner approved converting that
68
+ * signature to async, so the last sanctioned caller is gone. The async
69
+ * `withLock` is the only locking primitive.
8
70
  */
9
71
  import * as fs from "node:fs";
72
+ import * as os from "node:os";
10
73
  import * as path from "node:path";
11
74
  import { getRoot } from "../types.js";
12
75
  import { ensureDir } from "./fs-utils.js";
13
76
  const LOCK_TIMEOUT_MS = 5000;
14
77
  /**
15
- * A lock dir older than this (by mtime) is considered stale and force-broken on
16
- * the next acquire. Exported so the read-only store-doctor scans `.lock-*` dirs
17
- * against the SAME threshold the locker uses (single source of truth — no drift).
78
+ * A lock dir with NO readable owner.json (legacy pre-pid code, or a crash in
79
+ * the mkdir→owner-write window) older than this (by mtime) is considered
80
+ * stale and reclaimed on the next acquire. Locks WITH a live owner pid are
81
+ * never age-reclaimed. Exported so the read-only store-doctor scans
82
+ * `.lock-*` dirs against the SAME threshold the locker uses (single source
83
+ * of truth — no drift).
18
84
  */
19
85
  export const STALE_LOCK_MS = 30000;
86
+ const MAX_BACKOFF_MS = 200;
87
+ const OWNER_FILE = "owner.json";
88
+ /**
89
+ * Slack subtracted when comparing a lock's acquired_at against the current
90
+ * boot time (review MEDIUM-1, 2026-09-11): absorbs clock steps/NTP slew and
91
+ * os.uptime() coarseness so a lock acquired seconds before a suspend/resume
92
+ * is never misjudged as pre-boot.
93
+ */
94
+ const BOOT_SLACK_MS = 120_000;
95
+ /** Thrown when the lock timeout elapses while the holder process is still
96
+ * alive. NEVER a signal to force-break the lock: the holder may be mid-write.
97
+ * Callers either propagate (surfacing an explicit tool error) or catch it for
98
+ * advisory writes (log + best-effort skip) — silent corruption is not an
99
+ * option the primitive offers. */
100
+ export class LockContentionError extends Error {
101
+ lockName;
102
+ holderPid;
103
+ heldForMs;
104
+ constructor(lockName, holderPid, heldForMs) {
105
+ const held = heldForMs !== null ? `${Math.round(heldForMs)}ms` : "unknown duration";
106
+ // Review LOW-2 (2026-09-11): only claim "live process" when a pid was
107
+ // actually probed alive; a no-owner-record lock's holder is UNVERIFIABLE
108
+ // (young legacy lock / crash in the mkdir→owner-write window), not
109
+ // known-live.
110
+ const claim = holderPid !== null
111
+ ? `is held by a live process (pid ${holderPid}, held for ${held})`
112
+ : `appears to be held (no owner record — holder liveness unverifiable; held for ${held})`;
113
+ super(`Lock "${lockName}" ${claim} and was not ` +
114
+ `released within ${LOCK_TIMEOUT_MS}ms. Refusing to steal a possibly-live holder's lock (the holder ` +
115
+ `may be mid-write). agent_instruction: another AgentRecall process is writing this file; ` +
116
+ `retry the operation, or skip this advisory update and log the skip.`);
117
+ this.name = "LockContentionError";
118
+ this.lockName = lockName;
119
+ this.holderPid = holderPid;
120
+ this.heldForMs = heldForMs;
121
+ }
122
+ }
20
123
  function lockDir(name) {
21
- return path.join(getRoot(), `.lock-${name}`);
124
+ // Lock names embed project slugs (e.g. `corrections-${project}`); slugs are
125
+ // sanitized upstream, but a lock name reaches path.join — sanitize here too
126
+ // so no caller can ever traverse out of the root (defence in depth).
127
+ const safe = name.replace(/[^A-Za-z0-9._-]/g, "_");
128
+ return path.join(getRoot(), `.lock-${safe}`);
129
+ }
130
+ function ownerPath(dir) {
131
+ return path.join(dir, OWNER_FILE);
132
+ }
133
+ function readOwner(dir) {
134
+ try {
135
+ const parsed = JSON.parse(fs.readFileSync(ownerPath(dir), "utf-8"));
136
+ if (typeof parsed?.pid !== "number")
137
+ return null;
138
+ return parsed;
139
+ }
140
+ catch {
141
+ return null;
142
+ }
143
+ }
144
+ /** Signal-0 liveness probe. EPERM means "alive but not ours" — still alive. */
145
+ function isPidAlive(pid) {
146
+ if (!Number.isInteger(pid) || pid <= 0)
147
+ return false;
148
+ try {
149
+ process.kill(pid, 0);
150
+ return true;
151
+ }
152
+ catch (err) {
153
+ return err.code === "EPERM";
154
+ }
22
155
  }
23
156
  /**
24
- * Acquire a named lock. Retries with backoff until timeout.
25
- * Returns a release function.
157
+ * Review MEDIUM-1 (2026-09-11): pid liveness alone cannot distinguish the
158
+ * original holder from an UNRELATED process that recycled the pid after a
159
+ * reboot — that corner made the lock permanently unreclaimable (every acquire
160
+ * waits the full timeout, then throws, forever). No lock legitimately
161
+ * survives a reboot (the holder process died with it), so a lock whose
162
+ * acquired_at predates the current boot is reclaimable even when its recorded
163
+ * pid is alive today. Unparsable timestamps are conservatively treated as
164
+ * current-boot (never a steal).
26
165
  */
27
- export function acquireLock(name) {
28
- const dir = lockDir(name);
29
- const deadline = Date.now() + LOCK_TIMEOUT_MS;
30
- // Ensure root dir exists before attempting lock
31
- ensureDir(path.dirname(dir));
32
- // Clean stale locks
33
- if (fs.existsSync(dir)) {
166
+ function predatesBoot(acquiredAt) {
167
+ const t = Date.parse(acquiredAt);
168
+ if (!Number.isFinite(t))
169
+ return false;
170
+ return t < Date.now() - os.uptime() * 1000 - BOOT_SLACK_MS;
171
+ }
172
+ /**
173
+ * Try to remove a lock dir whose holder is dead (or which is legacy-stale).
174
+ * Rename-then-remove: rename is atomic, so of N contenders that all saw the
175
+ * same dead holder, exactly one wins; losers just retry mkdir.
176
+ * Returns true if this process removed (or observed the disappearance of)
177
+ * the lock dir.
178
+ */
179
+ function tryReclaim(dir) {
180
+ const owner = readOwner(dir);
181
+ if (owner) {
182
+ // Live holder from THIS boot — NEVER steal. A pre-boot acquired_at means
183
+ // the "live" pid is a post-reboot recycle, not the holder (see
184
+ // predatesBoot's doc comment).
185
+ if (isPidAlive(owner.pid) && !predatesBoot(owner.acquired_at))
186
+ return false;
187
+ }
188
+ else {
189
+ // No owner record: legacy lock or crash inside the mkdir→owner-write
190
+ // window. Fall back to the old mtime staleness rule.
191
+ let stat;
34
192
  try {
35
- const stat = fs.statSync(dir);
36
- if (Date.now() - stat.mtimeMs > STALE_LOCK_MS) {
37
- fs.rmdirSync(dir);
38
- }
193
+ stat = fs.statSync(dir);
39
194
  }
40
195
  catch {
41
- // race with another cleanup — fine
196
+ return true; // vanished — holder released; caller retries mkdir
42
197
  }
198
+ if (Date.now() - stat.mtimeMs <= STALE_LOCK_MS)
199
+ return false;
43
200
  }
44
- // Spin with backoff
45
- let delay = 5;
46
- while (Date.now() < deadline) {
201
+ const trash = `${dir}.reclaim-${process.pid}-${Date.now()}`;
202
+ try {
203
+ fs.renameSync(dir, trash);
204
+ }
205
+ catch {
206
+ return false; // lost the reclaim race (or holder released) — retry mkdir
207
+ }
208
+ // TOCTOU guard (review MEDIUM finding, 2026-09-11): between our readOwner
209
+ // above and the rename, ANOTHER contender may have completed this same
210
+ // reclaim AND a NEW holder may have acquired a fresh lock at the same path —
211
+ // in which case the rename we just won moved a LIVE holder's lock aside.
212
+ // Verify the dir we captured is still the one we observed: same dead (or
213
+ // pre-boot) owner, or still owner-less for the legacy branch. On mismatch,
214
+ // put it back and report no-reclaim.
215
+ const captured = readOwner(trash);
216
+ const sameAsObserved = owner
217
+ ? captured !== null && captured.pid === owner.pid && captured.acquired_at === owner.acquired_at
218
+ : captured === null;
219
+ if (!sameAsObserved) {
47
220
  try {
48
- fs.mkdirSync(dir, { recursive: false });
49
- // Got the lock — return release function
50
- return () => {
51
- try {
52
- fs.rmdirSync(dir);
53
- }
54
- catch { /* already released */ }
55
- };
221
+ fs.renameSync(trash, dir); // restore the displaced holder's lock
222
+ return false;
56
223
  }
57
224
  catch {
58
- // Lock held — wait and retry
59
- const waitUntil = Date.now() + delay;
60
- while (Date.now() < waitUntil) { /* busy wait — short durations only */ }
61
- delay = Math.min(delay * 2, 200);
225
+ // Restore collided with yet another acquirer taking the name. The
226
+ // displaced holder loses exclusion for the rest of its critical section
227
+ // — a sub-microsecond triple-race residual; surface it loudly.
228
+ console.error(`[agent-recall] filelock: reclaim race on ${path.basename(dir)} displaced a concurrent ` +
229
+ `acquirer's lock and could not restore it (displaced pid ${captured?.pid ?? "unknown"}).`);
230
+ try {
231
+ fs.rmSync(trash, { recursive: true, force: true });
232
+ }
233
+ catch { /* inert */ }
234
+ return true;
235
+ }
236
+ }
237
+ try {
238
+ fs.rmSync(trash, { recursive: true, force: true });
239
+ }
240
+ catch {
241
+ // Leftover trash dir is inert (never matches an active lock path); the
242
+ // store-doctor's .lock-* scan will surface it.
243
+ }
244
+ return true;
245
+ }
246
+ /** One non-blocking acquisition attempt. Returns a release fn or null.
247
+ * Only EEXIST means "contended"; ENOENT (store root vanished) is repaired and
248
+ * retried; any OTHER error (EACCES/EROFS/EMFILE, …) is rethrown immediately —
249
+ * spinning 5 s on a read-only store and then reporting "held by a live
250
+ * process" would misdiagnose an environment problem as contention. */
251
+ function tryAcquire(dir) {
252
+ try {
253
+ fs.mkdirSync(dir, { recursive: false });
254
+ }
255
+ catch (err) {
256
+ const code = err.code;
257
+ if (code === "ENOENT") {
258
+ // Parent (store root) vanished mid-wait — e.g. a test wiping its temp
259
+ // root while a straggler write is still queued. Recreate and retry once;
260
+ // without this, mkdir(ENOENT) + statSync(ENOENT)-as-"reclaimed" could
261
+ // loop instead of acquiring.
262
+ try {
263
+ ensureDir(path.dirname(dir));
264
+ fs.mkdirSync(dir, { recursive: false });
265
+ }
266
+ catch (err2) {
267
+ if (err2.code === "EEXIST")
268
+ return null;
269
+ throw err2;
270
+ }
271
+ }
272
+ else if (code === "EEXIST") {
273
+ return null;
274
+ }
275
+ else {
276
+ throw err;
62
277
  }
63
278
  }
64
- // Timeout — force-break the lock and take it
65
279
  try {
66
- fs.rmdirSync(dir);
280
+ fs.writeFileSync(ownerPath(dir), JSON.stringify({ pid: process.pid, acquired_at: new Date().toISOString() }), "utf-8");
67
281
  }
68
- catch { /* ok */ }
69
- fs.mkdirSync(dir, { recursive: false });
282
+ catch {
283
+ // Owner record is advisory: without it the lock degrades to the legacy
284
+ // mtime staleness rule instead of pid-liveness. NOTE (review LOW-2): in
285
+ // this degraded mode a LIVE holder that keeps the lock past STALE_LOCK_MS
286
+ // IS mtime-reclaimable by a contender — a double-failure corner
287
+ // (owner-write failed AND >30s hold) equivalent to the pre-fix behavior,
288
+ // accepted rather than failing the acquire on a full disk.
289
+ }
290
+ let released = false;
70
291
  return () => {
292
+ if (released)
293
+ return;
294
+ released = true;
295
+ // Guard: only remove the dir if it is still OURS (paranoia against the
296
+ // owner-write-failed + legacy-reclaimed corner).
297
+ const owner = readOwner(dir);
298
+ if (owner && owner.pid !== process.pid)
299
+ return;
71
300
  try {
72
- fs.rmdirSync(dir);
301
+ fs.rmSync(dir, { recursive: true, force: true });
302
+ }
303
+ catch {
304
+ /* already released */
73
305
  }
74
- catch { /* already released */ }
75
306
  };
76
307
  }
308
+ function contentionError(name, dir) {
309
+ const owner = readOwner(dir);
310
+ const heldForMs = owner ? Date.now() - Date.parse(owner.acquired_at) : null;
311
+ return new LockContentionError(name, owner?.pid ?? null, Number.isFinite(heldForMs) ? heldForMs : null);
312
+ }
313
+ function sleep(ms) {
314
+ return new Promise((resolve) => setTimeout(resolve, ms));
315
+ }
316
+ /**
317
+ * Acquire a named lock. Retries with async (event-loop-friendly) backoff
318
+ * until LOCK_TIMEOUT_MS; reclaims dead-holder / legacy-stale locks; throws
319
+ * LockContentionError if the holder is alive at timeout.
320
+ * Returns a release function (idempotent).
321
+ */
322
+ export async function acquireLock(name) {
323
+ const dir = lockDir(name);
324
+ const deadline = Date.now() + LOCK_TIMEOUT_MS;
325
+ // Ensure root dir exists before attempting lock
326
+ ensureDir(path.dirname(dir));
327
+ let delay = 5;
328
+ for (;;) {
329
+ const release = tryAcquire(dir);
330
+ if (release)
331
+ return release;
332
+ // Deadline is checked BEFORE the reclaim-retry shortcut so the loop is
333
+ // always bounded — a pathological reclaim-always-true state (e.g. the
334
+ // store root being deleted out from under us) can never spin forever.
335
+ if (Date.now() >= deadline) {
336
+ throw contentionError(name, dir);
337
+ }
338
+ // Held. Dead holder (or legacy-stale dir) → reclaim and retry at once.
339
+ if (tryReclaim(dir))
340
+ continue;
341
+ await sleep(Math.min(delay, Math.max(1, deadline - Date.now())));
342
+ delay = Math.min(delay * 2, MAX_BACKOFF_MS);
343
+ }
344
+ }
77
345
  /**
78
346
  * Execute a function while holding a lock.
79
- * Lock is always released, even on error.
347
+ * Lock is always released, even on error. Prefer a synchronous fn (bounded
348
+ * hold); an async fn is allowed only for the documented awareness nesting —
349
+ * see the header's lock-ordering section.
80
350
  */
81
- export function withLock(name, fn) {
82
- const release = acquireLock(name);
351
+ export async function withLock(name, fn) {
352
+ const release = await acquireLock(name);
83
353
  try {
84
- return fn();
354
+ return await fn();
85
355
  }
86
356
  finally {
87
357
  release();
@@ -1 +1 @@
1
- {"version":3,"file":"filelock.js","sourceRoot":"","sources":["../../src/storage/filelock.ts"],"names":[],"mappings":"AAAA;;;;;;;GAOG;AAEH,OAAO,KAAK,EAAE,MAAM,SAAS,CAAC;AAC9B,OAAO,KAAK,IAAI,MAAM,WAAW,CAAC;AAClC,OAAO,EAAE,OAAO,EAAE,MAAM,aAAa,CAAC;AACtC,OAAO,EAAE,SAAS,EAAE,MAAM,eAAe,CAAC;AAE1C,MAAM,eAAe,GAAG,IAAI,CAAC;AAC7B;;;;GAIG;AACH,MAAM,CAAC,MAAM,aAAa,GAAG,KAAK,CAAC;AAEnC,SAAS,OAAO,CAAC,IAAY;IAC3B,OAAO,IAAI,CAAC,IAAI,CAAC,OAAO,EAAE,EAAE,SAAS,IAAI,EAAE,CAAC,CAAC;AAC/C,CAAC;AAED;;;GAGG;AACH,MAAM,UAAU,WAAW,CAAC,IAAY;IACtC,MAAM,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;IAC1B,MAAM,QAAQ,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,eAAe,CAAC;IAE9C,gDAAgD;IAChD,SAAS,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,CAAC,CAAC,CAAC;IAE7B,oBAAoB;IACpB,IAAI,EAAE,CAAC,UAAU,CAAC,GAAG,CAAC,EAAE,CAAC;QACvB,IAAI,CAAC;YACH,MAAM,IAAI,GAAG,EAAE,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;YAC9B,IAAI,IAAI,CAAC,GAAG,EAAE,GAAG,IAAI,CAAC,OAAO,GAAG,aAAa,EAAE,CAAC;gBAC9C,EAAE,CAAC,SAAS,C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): string;
6
+ /**
7
+ * fix5 review MEDIUM-2 (2026-09-11): validate a caller-supplied ISO date
8
+ * before it is interpolated into a FILENAME (session cards, staged cards).
9
+ * `SessionCardResult.date` can originate from hook-stdin `meta.date` — an
10
+ * untrusted string — and both card write sites build
11
+ * `path.join(dir, `${date}--card--${sid}.md`)` with it; a value like
12
+ * `../../x` would escape the target dir. Strict `YYYY-MM-DD` shape or
13
+ * today's date — one shared helper so both write sites (and any future
14
+ * date-in-filename writer) apply the SAME rule (class-not-instance).
15
+ */
16
+ export declare function safeIsoDateOrToday(date: string | undefined | null): string;
6
17
  export declare function readJsonSafe<T>(filePath: string): T | null;
7
18
  export declare function writeJsonAtomic(filePath: string, data: unknown): void;
19
+ /**
20
+ * Atomic PRE-SERIALIZED text write (tmp + rename) — for callers that must
21
+ * transform the payload before it touches disk (e.g. scrubForCloud over the
22
+ * serialized JSON). fix6-locks review finding: a locked read-modify-write
23
+ * span that ends in plain writeFileSync (truncate-then-write) still exposes
24
+ * LOCK-FREE readers (and crash-mid-write) to torn files; rename-atomicity
25
+ * closes that without requiring readers to lock.
26
+ */
27
+ export declare function writeTextAtomic(filePath: string, text: string): void;
8
28
  /**
9
29
  * Largest N in [0, buf.length] such that `buf.subarray(0, N)` never ends
10
30
  * mid-way through a multi-byte UTF-8 sequence. Used both for a plain
@@ -1 +1 @@
1
- {"version":3,"file":"fs-utils.d.ts","sourceRoot":"","sources":["../../src/storage/fs-utils.ts"],"names":[],"mappings":"AAAA;;GAEG;AAKH,wBAAgB,SAAS,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAI3C;AAED,wBAAgB,QAAQ,IAAI,MAAM,CAEjC;AAED,wBAAgB,YAAY,CAAC,CAAC,EAAE,QAAQ,EAAE,MAAM,GAAG,CAAC,GAAG,IAAI,CAO1D;AAED,wBAAgB,eAAe,CAAC,QAAQ,EAAE,MAAM,EAAE,IAAI,EAAE,OAAO,GAAG,IAAI,CAKrE;AAgBD;;;;;GAKG;AACH,wBAA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dir) {
11
11
  export function todayISO() {
12
12
  return new Date().toISOString().slice(0, 10);
13
13
  }
14
+ /**
15
+ * fix5 review MEDIUM-2 (2026-09-11): validate a caller-supplied ISO date
16
+ * before it is interpolated into a FILENAME (session cards, staged cards).
17
+ * `SessionCardResult.date` can originate from hook-stdin `meta.date` — an
18
+ * untrusted string — and both card write sites build
19
+ * `path.join(dir, `${date}--card--${sid}.md`)` with it; a value like
20
+ * `../../x` would escape the target dir. Strict `YYYY-MM-DD` shape or
21
+ * today's date — one shared helper so both write sites (and any future
22
+ * date-in-filename writer) apply the SAME rule (class-not-instance).
23
+ */
24
+ export function safeIsoDateOrToday(date) {
25
+ return date && /^\d{4}-\d{2}-\d{2}$/.test(date) ? date : todayISO();
26
+ }
14
27
  export function readJsonSafe(filePath) {
15
28
  if (!fs.existsSync(filePath))
16
29
  return null;
@@ -27,6 +40,20 @@ export function writeJsonAtomic(filePath, data) {
27
40
  fs.writeFileSync(tmp, JSON.stringify(data, null, 2), "utf-8");
28
41
  fs.renameSync(tmp, filePath); // atomic on POSIX
29
42
  }
43
+ /**
44
+ * Atomic PRE-SERIALIZED text write (tmp + rename) — for callers that must
45
+ * transform the payload before it touches disk (e.g. scrubForCloud over the
46
+ * serialized JSON). fix6-locks review finding: a locked read-modify-write
47
+ * span that ends in plain writeFileSync (truncate-then-write) still exposes
48
+ * LOCK-FREE readers (and crash-mid-write) to torn files; rename-atomicity
49
+ * closes that without requiring readers to lock.
50
+ */
51
+ export function writeTextAtomic(filePath, text) {
52
+ ensureDir(path.dirname(filePath));
53
+ const tmp = filePath + ".tmp." + process.pid;
54
+ fs.writeFileSync(tmp, text, "utf-8");
55
+ fs.renameSync(tmp, filePath); // atomic on POSIX
56
+ }
30
57
  // ---------------------------------------------------------------------------
31
58
  // M8 (review fix, 2026-07-31) — shared UTF-8-safe byte-boundary helpers.
32
59
  //
@@ -1 +1 @@
1
- {"version":3,"file":"fs-utils.js","sourceRoot":"","sources":["../../src/storage/fs-utils.ts"],"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AC,CAAC;IACxC,IAAI,GAAG,CAAC,MAAM,IAAI,QAAQ;QAAE,OAAO,KAAK,CAAC;IACzC,MAAM,GAAG,GAAG,mBAAmB,CAAC,GAAG,EAAE,QAAQ,CAAC,CAAC;IAC/C,OAAO,GAAG,CAAC,QAAQ,CAAC,CAAC,EAAE,GAAG,CAAC,CAAC,QAAQ,CAAC,OAAO,CAAC,CAAC;AAChD,CAAC"}
@@ -5,6 +5,40 @@
5
5
  * AND verifies the resolved path stays under root with a trailing-separator check
6
6
  * (preventing `~/.agent-recallEVIL` prefix bypass).
7
7
  */
8
+ /**
9
+ * Root-level staging namespace for writes whose project resolution FAILED or
10
+ * carried zero confidence. Lives at `<AR_ROOT>/_unclaimed/` — deliberately a
11
+ * SIBLING of `projects/`, never inside it, so every scan that enumerates
12
+ * `projects/` (recall corpus, listAllProjects, the scoreboard script's
13
+ * ghost-dir census, ar-sync-status.py's wholesale registry regen) is
14
+ * structurally blind to it. The leading `_` is the same BY-NAME reserved-
15
+ * namespace convention the rest of the store already uses for infrastructure
16
+ * (`_index.md`, `_archive/`, fix4's `_pending/`/`_quarantine/` class):
17
+ * class-not-instance — one underscore rule, not one branch per known dir.
18
+ */
19
+ export declare const UNCLAIMED_DIRNAME = "_unclaimed";
20
+ /**
21
+ * The staging SENTINEL slug `resolveProject()` returns when resolution fails
22
+ * (blocked cwd, deny-listed detection, zero-confidence guess). It is NOT a
23
+ * valid project slug on purpose (`isValidProjectSlug` rejects the `_`
24
+ * prefix), so nothing downstream can register it into a cwd-allowlist or
25
+ * treat it as a real project — and `projectSubPath()` below routes every
26
+ * path built for it into `_unclaimed/<session>/` instead of `projects/`,
27
+ * which is the single choke point that closes ALL ~20 project-dir writers
28
+ * at once (journal, palace, corrections, digest, handoff, …) without
29
+ * per-writer gates.
30
+ */
31
+ export declare const UNCLAIMED_PROJECT = "_unclaimed";
32
+ /** Is this slug the staging sentinel? (Exact match — never a prefix test.) */
33
+ export declare function isUnclaimedProject(project: string | undefined | null): boolean;
34
+ /** `<AR_ROOT>/_unclaimed` — the staging namespace root. */
35
+ export declare function unclaimedRootDir(): string;
36
+ /**
37
+ * Per-session staging subdir: `<AR_ROOT>/_unclaimed/<sid>`. `sid` is
38
+ * UNTRUSTED (may arrive from hook stdin) → sanitized with the same
39
+ * `sanitizeSlug` grammar every other sid-derived path in this package uses.
40
+ */
41
+ export declare function unclaimedSessionDir(sid: string): string;
8
42
  /**
9
43
  * Sanitize a project name for safe use in path.join().
10
44
  *
@@ -1 +1 @@
1
- {"version":3,"file":"paths.d.ts","sourceRoot":"","sources":["../../src/storage/paths.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAOH;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,eAAe,CAAC,OAAO,EAAE,MAAM,GAAG,MAAM,CAGvD;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAoCG;AACH,MAAM,WAAW,qBAAqB;IACpC,iCAAiC;IACjC,MAAM,EAAE,MAAM,CAAC;IACf,oEAAoE;IACpE,QAAQ,EAAE,MAAM,EAAE,CAAC;IACnB,8EAA8E;IAC9E,SAAS,EAAE,OAAO,CAAC;CACpB;AAED;;;;;;;;;;GAUG;AACH,wBAAgB,mBAAmB,CAAC,SAAS,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,EAAE,GAAG,qBAAqB,GAAG,IAAI,CAatG;AAED,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,MAAM,CAuB3E;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,OAAO,EAAE,MAAM,EAAE,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,QAAQ,EAAE,MAAM,EAAE,CAAA;CAAE,CAAC,CAavG;AAED;;;;;;GAMG;AACH,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,MAAM,GAAG,KAAK,CAAC;IAAE,OAAO,EAAE,MAAM,CAAC;IAAC,Q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