@chroxy/server 0.11.10 → 0.11.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 (153) hide show
  1. package/CONFIG.md +4 -2
  2. package/package.json +3 -3
  3. package/src/acp-session.js +5 -1
  4. package/src/agent-connections.js +12 -1
  5. package/src/agent-control/client.js +29 -0
  6. package/src/agent-control/events.js +8 -4
  7. package/src/agent-control/local-connection.js +34 -16
  8. package/src/agent-control/mcp-server.js +2 -0
  9. package/src/anthropic-compatible-config.js +1 -0
  10. package/src/anthropic-gemini-shim.js +444 -0
  11. package/src/anthropic-gemini-translate.js +1030 -0
  12. package/src/base-session.js +319 -2
  13. package/src/bound-client-policy.js +12 -0
  14. package/src/byok-mcp-config.js +9 -5
  15. package/src/byok-mcp-trust.js +34 -20
  16. package/src/byok-session.js +62 -9
  17. package/src/byok-tool-executor.js +81 -1
  18. package/src/claude-setting-sources.js +74 -0
  19. package/src/claude-tui/pty-driver.js +5 -1
  20. package/src/claude-tui/usage-limit.js +2 -2
  21. package/src/claude-tui-session.js +57 -4
  22. package/src/cli/agent-cmd.js +236 -0
  23. package/src/cli/connection-state.js +54 -0
  24. package/src/cli/freshness-cmd.js +53 -0
  25. package/src/cli/pages-cmd.js +6 -4
  26. package/src/cli/pair-code-cmd.js +7 -6
  27. package/src/cli/pair-discord-cmd.js +7 -6
  28. package/src/cli/schedule-cmd.js +25 -3
  29. package/src/cli/server-cmd.js +6 -0
  30. package/src/cli/shell-cmd.js +7 -4
  31. package/src/cli/status-cmd.js +19 -5
  32. package/src/cli-session.js +190 -11
  33. package/src/cli.js +4 -0
  34. package/src/codex-app-server-session.js +78 -17
  35. package/src/codex-error-text.js +114 -0
  36. package/src/config-dir-migration.js +11 -6
  37. package/src/config.js +23 -3
  38. package/src/connection-info.js +73 -14
  39. package/src/continuations.js +153 -40
  40. package/src/conversation-scanner.js +2 -21
  41. package/src/conversation-search.js +4 -17
  42. package/src/dev-preview.js +2 -1
  43. package/src/docker-session.js +10 -1
  44. package/src/doctor.js +14 -3
  45. package/src/durable-write.js +35 -0
  46. package/src/environments/authority.js +7 -1
  47. package/src/event-normalizer.js +35 -2
  48. package/src/folder-trust-wire.js +137 -0
  49. package/src/folder-trust-worker.js +17 -0
  50. package/src/folder-trust.js +1572 -0
  51. package/src/freshness/activity-meter.js +101 -0
  52. package/src/freshness/adapter.js +199 -0
  53. package/src/freshness/checks.js +239 -0
  54. package/src/freshness/config.js +98 -0
  55. package/src/freshness/core.js +185 -0
  56. package/src/freshness/derive.js +680 -0
  57. package/src/freshness/exchange.js +305 -0
  58. package/src/freshness/file-ledger.js +400 -0
  59. package/src/freshness/grade.js +81 -0
  60. package/src/freshness/hash.js +45 -0
  61. package/src/freshness/inbox.js +163 -0
  62. package/src/freshness/index.js +20 -0
  63. package/src/freshness/investigation.js +474 -0
  64. package/src/freshness/keys.js +177 -0
  65. package/src/freshness/ledger.js +122 -0
  66. package/src/freshness/outbox.js +131 -0
  67. package/src/freshness/policy.js +599 -0
  68. package/src/freshness/queue.js +843 -0
  69. package/src/freshness/read-errors.js +23 -0
  70. package/src/freshness/render.js +153 -0
  71. package/src/freshness/runtime.js +113 -0
  72. package/src/freshness/session-registry-adapter.js +161 -0
  73. package/src/freshness/state-file-adapter.js +167 -0
  74. package/src/freshness-runner/build-info.js +139 -0
  75. package/src/freshness-runner/cli.js +105 -0
  76. package/src/freshness-runner/run-tick.js +109 -0
  77. package/src/freshness-runner/stamp.js +57 -0
  78. package/src/freshness-sources/claude-transcript-adapter.js +211 -0
  79. package/src/freshness-sources/codex-transcript-adapter.js +33 -0
  80. package/src/freshness-sources/index.js +8 -0
  81. package/src/gemini-byok-session.js +292 -0
  82. package/src/gemini-credentials.js +67 -0
  83. package/src/gemini-key-safety.js +246 -0
  84. package/src/gemini-models.js +386 -0
  85. package/src/handler-utils.js +6 -13
  86. package/src/handlers/checkpoint-handlers.js +8 -0
  87. package/src/handlers/folder-trust-handlers.js +90 -0
  88. package/src/handlers/input-handlers.js +40 -11
  89. package/src/handlers/principal-admin-handlers.js +229 -0
  90. package/src/handlers/principal-handlers.js +262 -0
  91. package/src/handlers/scheduler-handlers.js +4 -4
  92. package/src/handlers/session-handlers.js +10 -1
  93. package/src/handlers/settings-handlers.js +42 -8
  94. package/src/handlers/skills-handlers.js +7 -0
  95. package/src/history-page.js +8 -0
  96. package/src/jsonl-reader.js +90 -10
  97. package/src/jsonl-subprocess-session.js +4 -1
  98. package/src/logger.js +105 -15
  99. package/src/mailbox-route.js +102 -0
  100. package/src/notification-prefs.js +15 -0
  101. package/src/orchestration/orchestration-manager.js +38 -9
  102. package/src/orchestration/permission-gate.js +4 -1
  103. package/src/orchestration/run-record.js +11 -0
  104. package/src/orchestration/turn-driver.js +151 -33
  105. package/src/orphan-reaper.js +77 -20
  106. package/src/outgoing-policy.js +10 -4
  107. package/src/permission-floor.js +54 -2
  108. package/src/permission-manager.js +32 -13
  109. package/src/permission-resolved-by.js +89 -0
  110. package/src/permission-resolver.js +7 -3
  111. package/src/platform.js +156 -4
  112. package/src/principal-audit.js +189 -0
  113. package/src/principal-binding.js +25 -0
  114. package/src/principal-brakes.js +21 -0
  115. package/src/principal-effect.js +101 -0
  116. package/src/principal-journal.js +905 -0
  117. package/src/principal-kill-switch.js +183 -0
  118. package/src/principal-label.js +5 -0
  119. package/src/principal-pending-permissions.js +177 -0
  120. package/src/principal-policy.js +1094 -0
  121. package/src/principal-sessions-snapshot.js +208 -0
  122. package/src/principal-store.js +488 -0
  123. package/src/principal-subscriptions.js +283 -0
  124. package/src/providers.js +2 -0
  125. package/src/redaction.js +181 -22
  126. package/src/scheduled-task-store.js +12 -0
  127. package/src/scheduler.js +304 -17
  128. package/src/sdk-session.js +60 -7
  129. package/src/server-cli/push-notification-handler.js +6 -1
  130. package/src/server-cli.js +30 -1
  131. package/src/session-ci-watcher.js +210 -37
  132. package/src/session-manager.js +590 -19
  133. package/src/session-message-history.js +121 -2
  134. package/src/session-name-allocator.js +685 -0
  135. package/src/statusline.js +78 -19
  136. package/src/summarize-session.js +2 -0
  137. package/src/turn-outcome.js +5 -2
  138. package/src/utils/argv-safety.js +29 -0
  139. package/src/utils/binary-package-manifest.js +57 -15
  140. package/src/utils/bounded-regex-worker.js +4 -0
  141. package/src/utils/bounded-regex.js +16 -7
  142. package/src/utils/pid-liveness.js +47 -0
  143. package/src/web-task-manager.js +45 -4
  144. package/src/worktree-gc.js +195 -4
  145. package/src/ws-auth.js +103 -19
  146. package/src/ws-broadcaster.js +39 -7
  147. package/src/ws-client-manager.js +8 -0
  148. package/src/ws-file-ops/browser.js +35 -3
  149. package/src/ws-forwarding.js +23 -3
  150. package/src/ws-handler-context.js +18 -0
  151. package/src/ws-history.js +79 -12
  152. package/src/ws-message-handlers.js +10 -2
  153. package/src/ws-server.js +253 -13
@@ -0,0 +1,400 @@
1
+ /**
2
+ * A durable, single-writer file ledger for the freshness model.
3
+ *
4
+ * Layout, inside one directory the caller names (kept outside the daemon's own
5
+ * state directory by the caller):
6
+ *
7
+ * ledger.jsonl one JSON record per line, in the model's record envelope
8
+ * ledger.lock the writer lock (see below)
9
+ *
10
+ * The records are the model's (ledger.js): a record's `id` is its idempotency
11
+ * key, an append whose key exists with the same payload is ignored, one with a
12
+ * different payload writes an `idempotency_conflict` record, and each record
13
+ * carries the hash of the one before it. This module adds only durability and
14
+ * the writer guard. Keys are durable because the in-memory index is rebuilt
15
+ * from the file on open, so a repeat after a restart is still a repeat.
16
+ *
17
+ * Durability. Each record is written as one line with one write and `fsync`ed
18
+ * before `append` returns. On open, a last line with no newline is the tail of
19
+ * a write a crash cut off; it was never acknowledged, so it is dropped (the
20
+ * step that wrote it runs again and writes the same key). A bad line anywhere
21
+ * else, a gap in `seq` or a broken hash chain is corruption: the open is
22
+ * refused with `LedgerCorruptError` and nothing is rewritten.
23
+ *
24
+ * THE SINGLE-WRITER GUARD. Decision: a second writer is REFUSED, not fenced
25
+ * out after the fact, and a STALE holder is fenced.
26
+ *
27
+ * - `ledger.lock` is created with `O_EXCL`, so exactly one process creates
28
+ * it. A process that finds it present and its holder live throws
29
+ * `LedgerHeldError` before it reads or writes the ledger.
30
+ * - Staleness depends on where the holder runs. On this host, a holder is
31
+ * stale only if its pid no longer exists: a live pid is never stale,
32
+ * however old its lock, because a tick can legitimately outlast any lease.
33
+ * On another host (or when the lock cannot be read) the pid cannot be
34
+ * checked, so a holder is stale when its lock has not been touched for
35
+ * `leaseMs` (every append touches it). The lease must exceed the tick
36
+ * cadence; `openReconciler` enforces that.
37
+ * - A takeover bumps the lock's `epoch`, and is written to the ledger as a
38
+ * `writer_takeover` system record.
39
+ * - Before every append the writer re-reads the lock and writes only if the
40
+ * lock still names it, and checks that the file is the size this writer
41
+ * left it at. A holder that was paused, taken over, and woke finds the lock
42
+ * changed, or the file grown, and its append throws `LedgerFencedError`,
43
+ * writing nothing.
44
+ * - The lock's mtime only moves forward, whatever `now` a caller supplies.
45
+ *
46
+ * Residual window, stated rather than hidden: the lock check, the size check
47
+ * and the write are separate steps. A holder taken over, and a successor that
48
+ * writes, inside the microseconds between this writer's size check and its
49
+ * write can still land a duplicate sequence number. The next open then refuses
50
+ * the ledger with `LedgerCorruptError` rather than repairing it, so the damage
51
+ * is detected, not silent, and needs an operator. Pid reuse can make a dead
52
+ * same-host holder look live; the lock is then refused until that pid exits.
53
+ */
54
+
55
+ import fs from 'node:fs'
56
+ import os from 'node:os'
57
+ import path from 'node:path'
58
+ import { randomUUID } from 'node:crypto'
59
+ import { canonical, sha256 } from './hash.js'
60
+ import { append as ledgerAppend, loadLedger } from './ledger.js'
61
+ import { systemKey } from './keys.js'
62
+
63
+ export class LedgerHeldError extends Error {
64
+ constructor(message) {
65
+ super(message)
66
+ this.name = 'LedgerHeldError'
67
+ }
68
+ }
69
+
70
+ export class LedgerFencedError extends Error {
71
+ constructor(message) {
72
+ super(message)
73
+ this.name = 'LedgerFencedError'
74
+ }
75
+ }
76
+
77
+ export class LedgerCorruptError extends Error {
78
+ constructor(message) {
79
+ super(message)
80
+ this.name = 'LedgerCorruptError'
81
+ }
82
+ }
83
+
84
+ export const LEDGER_FILE = 'ledger.jsonl'
85
+ export const LOCK_FILE = 'ledger.lock'
86
+ export const DEFAULT_LEASE_MS = 15 * 60_000
87
+
88
+ function pidAlive(pid) {
89
+ try {
90
+ process.kill(pid, 0)
91
+ return true
92
+ } catch (err) {
93
+ return err?.code === 'EPERM'
94
+ }
95
+ }
96
+
97
+ /** The rules the guard applies. A test replaces one at a time to prove each is load-bearing. */
98
+ export const DEFAULT_GUARD_RULES = Object.freeze({
99
+ /**
100
+ * Is this lock's holder gone? `holder` is the parsed lock (null when it
101
+ * could not be parsed), `mtimeMs` the lock file's last touch.
102
+ */
103
+ isStale({ holder, mtimeMs, now, leaseMs, host, isAlive }) {
104
+ // On this host the pid decides: a live pid is never stale, whatever the age.
105
+ if (holder && holder.host === host && Number.isSafeInteger(holder.pid)) return !isAlive(holder.pid)
106
+ // Elsewhere the pid cannot be checked; only silence for the lease counts.
107
+ return now - mtimeMs > leaseMs
108
+ },
109
+ /** May this process write? The lock must still name it (holder ids are unique per acquire). */
110
+ holdsLock({ holder, token }) {
111
+ return Boolean(holder) && holder.holder_id === token.holder_id
112
+ },
113
+ })
114
+
115
+ function inside(child, parent) {
116
+ const rel = path.relative(path.resolve(parent), path.resolve(child))
117
+ return rel === '' || (!rel.startsWith('..') && !path.isAbsolute(rel))
118
+ }
119
+
120
+ /**
121
+ * The real path of `p`: the real path of its deepest existing ancestor with the
122
+ * names below it (which do not exist yet) appended. A symlink anywhere above
123
+ * the path is resolved, so two spellings of one directory compare equal.
124
+ */
125
+ function realish(p) {
126
+ let cur = path.resolve(p)
127
+ const tail = []
128
+ for (;;) {
129
+ try {
130
+ return path.join(fs.realpathSync(cur), ...tail.reverse())
131
+ } catch (err) {
132
+ const parent = path.dirname(cur)
133
+ if (parent === cur || (err?.code !== 'ENOENT' && err?.code !== 'ENOTDIR')) return path.resolve(p)
134
+ tail.push(path.basename(cur))
135
+ cur = parent
136
+ }
137
+ }
138
+ }
139
+
140
+ function readLock(lockPath) {
141
+ let text
142
+ let mtimeMs
143
+ try {
144
+ mtimeMs = fs.statSync(lockPath).mtimeMs
145
+ text = fs.readFileSync(lockPath, 'utf8')
146
+ } catch {
147
+ return null
148
+ }
149
+ try {
150
+ const holder = JSON.parse(text)
151
+ if (holder && typeof holder === 'object' && typeof holder.holder_id === 'string' && Number.isSafeInteger(holder.epoch)) return { holder, text, mtimeMs }
152
+ } catch {
153
+ // A lock whose creator died between creating and writing it has no content.
154
+ }
155
+ return { holder: null, text, mtimeMs }
156
+ }
157
+
158
+ function createLock(lockPath, content) {
159
+ const fd = fs.openSync(lockPath, 'wx', 0o600)
160
+ try {
161
+ fs.writeSync(fd, JSON.stringify(content))
162
+ fs.fsyncSync(fd)
163
+ } finally {
164
+ fs.closeSync(fd)
165
+ }
166
+ // The lease is measured on the caller's clock, so the lock is stamped with it.
167
+ const t = new Date(content.acquired_at)
168
+ fs.utimesSync(lockPath, t, t)
169
+ }
170
+
171
+ /**
172
+ * The writer guard: `acquire`, `assertHeld`, `release`. `rules` are the
173
+ * decisions (DEFAULT_GUARD_RULES); the rest is mechanism.
174
+ */
175
+ export function createWriterGuard(rules = DEFAULT_GUARD_RULES) {
176
+ return Object.freeze({
177
+ /** Returns the token this writer holds, or throws `LedgerHeldError`. */
178
+ acquire(lockPath, { now, leaseMs = DEFAULT_LEASE_MS, pid = process.pid, host = os.hostname(), isAlive = pidAlive } = {}) {
179
+ const token = { holder_id: randomUUID(), pid, host, epoch: 1, acquired_at: now, took_over_from: null }
180
+ try {
181
+ createLock(lockPath, token)
182
+ return token
183
+ } catch (err) {
184
+ if (err?.code !== 'EEXIST') throw err
185
+ }
186
+ const found = readLock(lockPath)
187
+ if (!found) {
188
+ // It vanished between our create and our read: try once more from scratch.
189
+ createLockOrHeld(lockPath, token)
190
+ return token
191
+ }
192
+ if (!rules.isStale({ holder: found.holder, mtimeMs: found.mtimeMs, now, leaseMs, host, isAlive })) {
193
+ const who = found.holder ? `pid ${found.holder.pid} on ${found.holder.host}` : 'an unknown process'
194
+ throw new LedgerHeldError(`ledger is held by ${who}; a second writer is refused`)
195
+ }
196
+ // Take over a stale lock. Move it aside so that only one contender can
197
+ // have removed it, check that what we moved is the lock we judged
198
+ // stale, then create ours exclusively.
199
+ const aside = `${lockPath}.stale-${token.holder_id}`
200
+ try {
201
+ fs.renameSync(lockPath, aside)
202
+ } catch {
203
+ throw new LedgerHeldError('ledger lock changed while taking it over; a second writer is refused')
204
+ }
205
+ let movedText = null
206
+ try {
207
+ movedText = fs.readFileSync(aside, 'utf8')
208
+ } catch {
209
+ // fall through: treated as "not the lock we judged"
210
+ }
211
+ if (movedText !== found.text) {
212
+ // We moved a lock another contender had just created. Put it back if its path is free.
213
+ try {
214
+ if (!fs.existsSync(lockPath)) fs.renameSync(aside, lockPath)
215
+ } catch {
216
+ // Nothing more can be done safely; the caller is refused below.
217
+ }
218
+ throw new LedgerHeldError('ledger lock was replaced while taking it over; a second writer is refused')
219
+ }
220
+ try {
221
+ fs.unlinkSync(aside)
222
+ } catch {
223
+ // A leftover `.stale-` file is harmless.
224
+ }
225
+ token.epoch = (found.holder?.epoch ?? 0) + 1
226
+ token.took_over_from = found.holder ? found.holder.holder_id : 'unreadable'
227
+ createLockOrHeld(lockPath, token)
228
+ return token
229
+ },
230
+
231
+ /** Throws `LedgerFencedError` unless the lock still names this writer. Touches it as the lease heartbeat. */
232
+ assertHeld(lockPath, token, now) {
233
+ const found = readLock(lockPath)
234
+ if (!found || !rules.holdsLock({ holder: found.holder, token })) {
235
+ throw new LedgerFencedError('this writer no longer holds the ledger lock; nothing was written')
236
+ }
237
+ try {
238
+ const t = new Date(Math.max(now, found.mtimeMs))
239
+ fs.utimesSync(lockPath, t, t)
240
+ } catch {
241
+ // The heartbeat is best effort; the next append re-checks the lock.
242
+ }
243
+ },
244
+
245
+ /** Remove the lock if it is still ours. */
246
+ release(lockPath, token) {
247
+ const found = readLock(lockPath)
248
+ if (found && rules.holdsLock({ holder: found.holder, token })) {
249
+ try {
250
+ fs.unlinkSync(lockPath)
251
+ } catch {
252
+ // Already gone.
253
+ }
254
+ }
255
+ },
256
+ })
257
+ }
258
+
259
+ function createLockOrHeld(lockPath, token) {
260
+ try {
261
+ createLock(lockPath, token)
262
+ } catch (err) {
263
+ if (err?.code === 'EEXIST') throw new LedgerHeldError('another writer took the ledger first; a second writer is refused')
264
+ throw err
265
+ }
266
+ }
267
+
268
+ export const writerGuard = createWriterGuard()
269
+
270
+ function loadRecords(file) {
271
+ let fd
272
+ try {
273
+ fd = fs.openSync(file, 'r+')
274
+ } catch (err) {
275
+ if (err?.code === 'ENOENT') return []
276
+ throw err
277
+ }
278
+ try {
279
+ const text = fs.readFileSync(fd, 'utf8')
280
+ if (text === '') return []
281
+ const lines = text.split('\n')
282
+ const tail = lines.pop()
283
+ if (tail !== '') {
284
+ // A write the crash cut off: it was never acknowledged. Drop it.
285
+ const keep = Buffer.byteLength(lines.length ? lines.join('\n') + '\n' : '')
286
+ fs.ftruncateSync(fd, keep)
287
+ fs.fsyncSync(fd)
288
+ }
289
+ const records = []
290
+ let prev = null
291
+ lines.forEach((line, i) => {
292
+ let r
293
+ try {
294
+ r = JSON.parse(line)
295
+ } catch {
296
+ throw new LedgerCorruptError(`ledger line ${i + 1} is not valid JSON; refusing to open`)
297
+ }
298
+ if (!r || r.seq !== i + 1 || r.prev !== prev || typeof r.id !== 'string') {
299
+ throw new LedgerCorruptError(`ledger record ${i + 1} breaks the sequence or hash chain; refusing to open`)
300
+ }
301
+ prev = sha256(canonical(r))
302
+ records.push(r)
303
+ })
304
+ return records
305
+ } finally {
306
+ fs.closeSync(fd)
307
+ }
308
+ }
309
+
310
+ function writeAll(fd, buf) {
311
+ let off = 0
312
+ while (off < buf.length) off += fs.writeSync(fd, buf, off, buf.length - off)
313
+ }
314
+
315
+ /** Throw unless `dir` is outside every directory of `keepOutOf`, by lexical and by real path. */
316
+ export function assertKeptOutOf(dir, keepOutOf, what) {
317
+ for (const p of keepOutOf) {
318
+ if (inside(dir, p) || inside(realish(dir), realish(p))) throw new TypeError(`openFileLedger: ${what} must be kept outside ${p}`)
319
+ }
320
+ }
321
+
322
+ /**
323
+ * Open the ledger in `dir` for writing, holding the writer lock.
324
+ *
325
+ * @param {object} opts
326
+ * @param {string} opts.dir directory for ledger.jsonl and ledger.lock
327
+ * @param {string} opts.ledgerId the ledger's identity (part of every tick id)
328
+ * @param {number} opts.now time of the open, ms
329
+ * @param {number} [opts.leaseMs]
330
+ * @param {string[]} [opts.keepOutOf] directories the ledger must not be in or under (the daemon's own state directory)
331
+ * @param {object} [opts.guard] the writer guard (writerGuard)
332
+ * @param {number} [opts.pid] for tests
333
+ * @param {string} [opts.host] for tests
334
+ * @param {(pid:number)=>boolean} [opts.isAlive] for tests
335
+ * @returns {{ ledger, append(draft, at), close(), epoch, tookOver, path }}
336
+ */
337
+ export function openFileLedger({ dir, ledgerId, now, leaseMs = DEFAULT_LEASE_MS, guard = writerGuard, keepOutOf = [], pid, host, isAlive }) {
338
+ if (!dir || !ledgerId) throw new TypeError('openFileLedger: dir and ledgerId are required')
339
+ assertKeptOutOf(dir, keepOutOf, 'the ledger')
340
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 })
341
+ const file = path.join(dir, LEDGER_FILE)
342
+ const lockPath = path.join(dir, LOCK_FILE)
343
+ const token = guard.acquire(lockPath, { now, leaseMs, ...(pid !== undefined ? { pid } : {}), ...(host !== undefined ? { host } : {}), ...(isAlive ? { isAlive } : {}) })
344
+ let fd = null
345
+ let broken = false
346
+ const handle = {}
347
+ try {
348
+ const records = loadRecords(file)
349
+ const ledger = loadLedger({ ledgerId, records })
350
+ fd = fs.openSync(file, 'a', 0o600)
351
+ // The file is the size this writer left it at, or someone else wrote to it.
352
+ let size = fs.fstatSync(fd).size
353
+ const persist = (record) => {
354
+ const line = Buffer.from(JSON.stringify(record) + '\n')
355
+ writeAll(fd, line)
356
+ fs.fsyncSync(fd)
357
+ size += line.length
358
+ }
359
+ const write = (draft, at) => {
360
+ if (broken) throw new Error('ledger handle is broken by an earlier failed write; reopen it')
361
+ guard.assertHeld(lockPath, token, at)
362
+ if (fs.fstatSync(fd).size !== size) throw new LedgerFencedError('the ledger changed under this writer; nothing was written')
363
+ const reply = ledgerAppend(ledger, draft, at)
364
+ if (reply.record) {
365
+ try {
366
+ persist(reply.record)
367
+ } catch (err) {
368
+ broken = true
369
+ throw err
370
+ }
371
+ }
372
+ return reply
373
+ }
374
+ const first = records[0]
375
+ if (first && !(first.kind === 'system' && first.body?.event === 'ledger_created' && first.body.detail?.ids?.[0] === ledgerId)) {
376
+ throw new LedgerCorruptError('ledger was created under a different ledger id; refusing to open')
377
+ }
378
+ if (!first) write({ kind: 'system', id: systemKey('ledger_created', [ledgerId]), body: { event: 'ledger_created', detail: { ids: [ledgerId] } } }, now)
379
+ if (token.took_over_from) {
380
+ write({ kind: 'system', id: systemKey('writer_takeover', [ledgerId, String(token.epoch)]), body: { event: 'writer_takeover', detail: { ids: [ledgerId, String(token.epoch)], previous_holder: token.took_over_from } } }, now)
381
+ }
382
+ Object.assign(handle, {
383
+ ledger,
384
+ append: write,
385
+ epoch: token.epoch,
386
+ tookOver: Boolean(token.took_over_from),
387
+ path: file,
388
+ close() {
389
+ if (fd != null) fs.closeSync(fd)
390
+ fd = null
391
+ guard.release(lockPath, token)
392
+ },
393
+ })
394
+ return handle
395
+ } catch (err) {
396
+ if (fd != null) fs.closeSync(fd)
397
+ guard.release(lockPath, token)
398
+ throw err
399
+ }
400
+ }
@@ -0,0 +1,81 @@
1
+ /**
2
+ * Freshness grading from report age and the configured thresholds.
3
+ *
4
+ * Freshness is computed from the report's age alone: the reconciler's check
5
+ * time minus the host's report time. A check never moves the report time, so
6
+ * for a fixed report under a fixed configuration the graded value can only get
7
+ * worse as time passes. Times are milliseconds since the epoch and are always
8
+ * arguments; nothing here reads a clock.
9
+ */
10
+
11
+ export const FRESHNESS = Object.freeze(['fresh', 'aging', 'stale', 'unknown', 'error', 'blocked'])
12
+
13
+ /** The age-graded values, in the order in which they get worse. */
14
+ export const AGE_ORDER = Object.freeze({ fresh: 0, aging: 1, stale: 2 })
15
+
16
+ /**
17
+ * The age rule: check time minus report time. Kept as a separate
18
+ * function so that a test can swap it (a check that refreshes a report is the
19
+ * failure this rule exists to prevent).
20
+ */
21
+ export function reportAgeMs({ lastReportAt, checkedAt }) {
22
+ return checkedAt - lastReportAt
23
+ }
24
+
25
+ /**
26
+ * Bands for one age (ms) under one threshold row (seconds): fresh means age <= fresh_max;
27
+ * stale means age > stale_after; aging is everything between, including
28
+ * exactly stale_after.
29
+ */
30
+ export function band(ageMs, row) {
31
+ if (ageMs <= row.fresh_max_s * 1000) return 'fresh'
32
+ if (ageMs > row.stale_after_s * 1000) return 'stale'
33
+ return 'aging'
34
+ }
35
+
36
+ /**
37
+ * Grade one read.
38
+ *
39
+ * input:
40
+ * outcome 'ok' | 'no_report' | 'error' | 'blocked'
41
+ * state the parsed state, or 'none'
42
+ * declaredVia 'marker' | 'transcript' | 'api' | 'hook'
43
+ * timeTrusted false when the host time cannot be trusted
44
+ * lastReportAt host time of the report (ms)
45
+ * checkedAt reconciler time of the check (ms)
46
+ * previousCheckedAt the previous check of the same report, if any (ms)
47
+ * sourceNow the source's own current time, if it supplies one (ms)
48
+ * remoteWithoutClock a source on another host that supplies no time
49
+ * errorCode, notReadReason passed through for error and blocked reads
50
+ *
51
+ * returns { freshness, reason, ageS, errorCode, notReadReason }
52
+ */
53
+ export function gradeRead(input, config, ageFn = reportAgeMs) {
54
+ const skewMs = config.max_source_skew_seconds * 1000
55
+ const out = { freshness: null, reason: null, ageS: null, errorCode: null, notReadReason: null }
56
+ if (input.outcome === 'error') return { ...out, freshness: 'error', errorCode: input.errorCode ?? 'adapter_fault' }
57
+ if (input.outcome === 'blocked') return { ...out, freshness: 'blocked', notReadReason: input.notReadReason ?? 'policy' }
58
+ if (input.sourceNow != null && Math.abs(input.sourceNow - input.checkedAt) > skewMs) {
59
+ return { ...out, freshness: 'error', errorCode: 'clock_skew' }
60
+ }
61
+ if (input.outcome === 'no_report' || input.state === 'none' || input.state == null) {
62
+ return { ...out, freshness: 'unknown', reason: input.reason ?? 'no_status_line' }
63
+ }
64
+ if (input.timeTrusted === false) return { ...out, freshness: 'unknown', reason: 'time_untrusted' }
65
+ if (input.declaredVia === 'api' || input.declaredVia === 'hook') {
66
+ return { ...out, freshness: 'unknown', reason: 'relayed_declaration' }
67
+ }
68
+ if (input.lastReportAt - input.checkedAt > skewMs) {
69
+ return { ...out, freshness: 'error', errorCode: 'clock_skew' }
70
+ }
71
+ const row = config.freshness[input.state]
72
+ if (!row) return { ...out, freshness: 'unknown', reason: 'no_status_line' }
73
+ // DESIGN-GAP: a report time later than the check time by no more than the
74
+ // skew limit is allowed, but the rules define no age for it. The model
75
+ // clamps the age at zero so that no negative age is ever recorded.
76
+ const ageMs = Math.max(0, ageFn({ lastReportAt: input.lastReportAt, checkedAt: input.checkedAt, previousCheckedAt: input.previousCheckedAt }))
77
+ const ageS = Math.floor(ageMs / 1000)
78
+ let freshness = band(ageMs, row)
79
+ if (input.remoteWithoutClock && freshness === 'fresh') freshness = 'aging'
80
+ return { ...out, freshness, ageS }
81
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Canonical encoding and hashing for the session-freshness model.
3
+ *
4
+ * Every idempotency key in the model is `H(...parts)`: sha256 over a canonical
5
+ * JSON encoding of the parts array. Canonical means object keys are sorted and
6
+ * `undefined` members are dropped, so two values that are equal as data always
7
+ * hash the same, whatever order their keys were written in.
8
+ *
9
+ * Pure: no I/O, no clock, no randomness.
10
+ */
11
+
12
+ import { createHash } from 'node:crypto'
13
+
14
+ /**
15
+ * Deterministic JSON. Objects are emitted with sorted keys; `undefined`
16
+ * object members are omitted; arrays keep their order (an `undefined` array
17
+ * element is encoded as `null`, as JSON.stringify does). Non-finite numbers
18
+ * are rejected so a NaN can never hide inside a key.
19
+ */
20
+ export function canonical(value) {
21
+ if (value === null) return 'null'
22
+ const t = typeof value
23
+ if (t === 'number') {
24
+ if (!Number.isFinite(value)) throw new TypeError('canonical: non-finite number')
25
+ return JSON.stringify(value)
26
+ }
27
+ if (t === 'string' || t === 'boolean') return JSON.stringify(value)
28
+ if (t === 'undefined') return 'null'
29
+ if (Array.isArray(value)) return '[' + value.map(canonical).join(',') + ']'
30
+ if (t === 'object') {
31
+ const keys = Object.keys(value).filter((k) => value[k] !== undefined).sort()
32
+ return '{' + keys.map((k) => JSON.stringify(k) + ':' + canonical(value[k])).join(',') + '}'
33
+ }
34
+ throw new TypeError(`canonical: unsupported type ${t}`)
35
+ }
36
+
37
+ /** sha256 hex of a string. */
38
+ export function sha256(text) {
39
+ return createHash('sha256').update(text).digest('hex')
40
+ }
41
+
42
+ /** `H(...)`: a hash over the canonical encoding of its parts (README, keys). */
43
+ export function H(...parts) {
44
+ return sha256(canonical(parts))
45
+ }
@@ -0,0 +1,163 @@
1
+ /**
2
+ * Reading the two files a consumer writes: delivery receipts and operator
3
+ * acknowledgements. Both are untrusted input. They are read bounded, line by
4
+ * line, and every line is shape-checked; a line that fails is described by a
5
+ * fixed reason, never by its content, and is ignored.
6
+ *
7
+ * Format of both files: UTF-8 text, one JSON object per line, appended by the
8
+ * consumer. A last line with no newline is a write in flight and is not read
9
+ * until its newline arrives. A line is read once ever: its identity is the hash
10
+ * of its text, recorded in the ledger, so a truncation replays no line. A
11
+ * consumer should rotate its files: a file past the size bound is read only that
12
+ * far, and the lines after it are never seen.
13
+ *
14
+ * Pure of the clock; the only I/O is a read-only read of the named file.
15
+ */
16
+
17
+ import fs from 'node:fs'
18
+ import { sha256 } from './hash.js'
19
+ import { HEX_ID } from './render.js'
20
+
21
+ export const RECEIPT_OUTCOMES = Object.freeze(['delivered', 'failed'])
22
+ export const ACK_INTENTS = Object.freeze(['done', 'dismiss', 'defer'])
23
+
24
+ const RECEIPT_FIELDS = ['v', 'key', 'rec', 'outcome']
25
+ const ACK_FIELDS = ['v', 'key', 'rec', 'intent', 'until', 'at']
26
+ const MAX_OUTCOME = 40
27
+
28
+ /** The identity of a line: the hash of its text. */
29
+ export function lineId(text) {
30
+ return sha256(text).slice(0, 32)
31
+ }
32
+
33
+ /**
34
+ * What names this file as against a replacement of it: device, inode and
35
+ * creation time of the path itself (a link is not followed). Empty when it
36
+ * cannot be told, which is then one identity for every such file.
37
+ */
38
+ export function inputIdentity(file) {
39
+ try {
40
+ const st = fs.lstatSync(file)
41
+ return `${st.dev}:${st.ino}:${Math.trunc(st.birthtimeMs)}`
42
+ } catch {
43
+ return ''
44
+ }
45
+ }
46
+
47
+ /**
48
+ * Read the lines of one input file, bounded.
49
+ *
50
+ * Returns `{ lines, problem }`. `lines` are `{ id, text | null, tooLong }` in
51
+ * file order; `problem` is null, `unsafe` (not a regular file), `unreadable`,
52
+ * or `oversize` (more than `maxFileBytes`: only the first `maxFileBytes` are
53
+ * read and lines are those wholly inside them). A missing file is no lines.
54
+ */
55
+ export function readInput(file, { maxFileBytes, maxLineBytes }, { beforeOpen } = {}) {
56
+ let st
57
+ try {
58
+ st = fs.lstatSync(file)
59
+ } catch (err) {
60
+ return { lines: [], problem: err?.code === 'ENOENT' ? null : 'unreadable' }
61
+ }
62
+ if (!st.isFile()) return { lines: [], problem: 'unsafe' }
63
+ let buf
64
+ let fd = null
65
+ let oversize = false
66
+ try {
67
+ beforeOpen?.(file)
68
+ // Where the platform has them: refuse a link swapped in after the check, and
69
+ // never block on a FIFO swapped in there. (The shared open-nofollow helper is
70
+ // asynchronous and lives outside this directory, which may import nothing
71
+ // from the daemon, so the same two flags are used here.)
72
+ fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0))
73
+ const open = fs.fstatSync(fd)
74
+ if (!open.isFile()) return { lines: [], problem: 'unsafe' }
75
+ oversize = open.size > maxFileBytes
76
+ const want = Math.min(open.size, maxFileBytes)
77
+ buf = Buffer.alloc(want)
78
+ let got = 0
79
+ while (got < want) {
80
+ const n = fs.readSync(fd, buf, got, want - got, got)
81
+ if (n <= 0) break
82
+ got += n
83
+ }
84
+ buf = buf.subarray(0, got)
85
+ } catch {
86
+ return { lines: [], problem: 'unreadable' }
87
+ } finally {
88
+ if (fd !== null) {
89
+ try {
90
+ fs.closeSync(fd)
91
+ } catch {
92
+ // nothing more to do for a read-only descriptor
93
+ }
94
+ }
95
+ }
96
+ // Only lines whose newline has arrived: a cut-off tail is not a line yet.
97
+ const complete = buf.subarray(0, buf.lastIndexOf(0x0a) + 1)
98
+ const lines = []
99
+ let start = 0
100
+ while (start < complete.length) {
101
+ let stop = complete.indexOf(0x0a, start)
102
+ if (stop < 0) stop = complete.length
103
+ let raw = complete.subarray(start, stop)
104
+ start = stop + 1
105
+ if (raw.length && raw[raw.length - 1] === 0x0d) raw = raw.subarray(0, raw.length - 1)
106
+ if (raw.length === 0) continue
107
+ if (raw.length > maxLineBytes) {
108
+ lines.push({ id: lineId(raw.subarray(0, maxLineBytes + 1).toString('latin1')), text: null, tooLong: true })
109
+ continue
110
+ }
111
+ const text = raw.toString('utf8')
112
+ lines.push({ id: lineId(text), text, tooLong: false })
113
+ }
114
+ return { lines, problem: oversize ? 'oversize' : null }
115
+ }
116
+
117
+ function plainObject(text) {
118
+ let v
119
+ try {
120
+ v = JSON.parse(text)
121
+ } catch {
122
+ return { reason: 'not_json' }
123
+ }
124
+ if (v === null || typeof v !== 'object' || Array.isArray(v)) return { reason: 'shape' }
125
+ return { value: v }
126
+ }
127
+
128
+ function validIds(v) {
129
+ return typeof v.key === 'string' && HEX_ID.test(v.key) && typeof v.rec === 'string' && HEX_ID.test(v.rec)
130
+ }
131
+
132
+ function onlyFields(v, allowed) {
133
+ return Object.keys(v).every((k) => allowed.includes(k))
134
+ }
135
+
136
+ /** A receipt line: `{ v: 1, key, rec, outcome }`. */
137
+ export function parseReceipt(text) {
138
+ const p = plainObject(text)
139
+ if (!p.value) return { reason: p.reason }
140
+ const v = p.value
141
+ if (!onlyFields(v, RECEIPT_FIELDS) || v.v !== 1) return { reason: 'shape' }
142
+ if (!validIds(v)) return { reason: 'shape' }
143
+ if (typeof v.outcome !== 'string' || v.outcome.length < 1 || v.outcome.length > MAX_OUTCOME) return { reason: 'shape' }
144
+ // Anything other than a known outcome is unclear, and is never kept as text.
145
+ return { key: v.key, rec: v.rec, outcome: RECEIPT_OUTCOMES.includes(v.outcome) ? v.outcome : 'unclear' }
146
+ }
147
+
148
+ /** An acknowledgement line: `{ v: 1, key, rec, intent, until?, at? }`. */
149
+ export function parseAck(text) {
150
+ const p = plainObject(text)
151
+ if (!p.value) return { reason: p.reason }
152
+ const v = p.value
153
+ if (!onlyFields(v, ACK_FIELDS) || v.v !== 1) return { reason: 'shape' }
154
+ if (!validIds(v)) return { reason: 'shape' }
155
+ if (!ACK_INTENTS.includes(v.intent)) return { reason: 'shape' }
156
+ if (v.at !== undefined && !(Number.isSafeInteger(v.at) && v.at >= 0)) return { reason: 'shape' }
157
+ if (v.intent === 'defer') {
158
+ if (!Number.isSafeInteger(v.until) || v.until < 0) return { reason: 'shape' }
159
+ } else if (v.until !== undefined) {
160
+ return { reason: 'shape' }
161
+ }
162
+ return { key: v.key, rec: v.rec, intent: v.intent, until: v.intent === 'defer' ? v.until : null }
163
+ }