harness-reflex 0.1.0 → 0.3.0

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 (121) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +103 -23
  3. package/USER_GUIDE.md +121 -43
  4. package/dist/adapters/agy.js +1 -1
  5. package/dist/adapters/agy.js.map +1 -1
  6. package/dist/adapters/codex.d.ts +133 -4
  7. package/dist/adapters/codex.js +325 -2
  8. package/dist/adapters/codex.js.map +1 -1
  9. package/dist/backend/defaults.d.ts +31 -0
  10. package/dist/backend/defaults.js +32 -0
  11. package/dist/backend/defaults.js.map +1 -0
  12. package/dist/backend/jev.js +6 -5
  13. package/dist/backend/jev.js.map +1 -1
  14. package/dist/backend/mock.d.ts +12 -1
  15. package/dist/backend/mock.js +34 -0
  16. package/dist/backend/mock.js.map +1 -1
  17. package/dist/backend/simple-jev.js +5 -4
  18. package/dist/backend/simple-jev.js.map +1 -1
  19. package/dist/backend/types.d.ts +34 -0
  20. package/dist/backend/types.js.map +1 -1
  21. package/dist/cli/index.js +5 -3
  22. package/dist/cli/index.js.map +1 -1
  23. package/dist/core/closing.d.ts +90 -0
  24. package/dist/core/closing.js +111 -0
  25. package/dist/core/closing.js.map +1 -0
  26. package/dist/core/evidence.d.ts +119 -0
  27. package/dist/core/evidence.js +209 -0
  28. package/dist/core/evidence.js.map +1 -0
  29. package/dist/core/judge.d.ts +221 -0
  30. package/dist/core/judge.js +251 -0
  31. package/dist/core/judge.js.map +1 -0
  32. package/dist/core/orchestrate-closing.d.ts +237 -0
  33. package/dist/core/orchestrate-closing.js +250 -0
  34. package/dist/core/orchestrate-closing.js.map +1 -0
  35. package/dist/core/orchestrate-correction.d.ts +209 -0
  36. package/dist/core/orchestrate-correction.js +141 -0
  37. package/dist/core/orchestrate-correction.js.map +1 -0
  38. package/dist/core/orchestrate-host.d.ts +225 -0
  39. package/dist/core/orchestrate-host.js +80 -0
  40. package/dist/core/orchestrate-host.js.map +1 -0
  41. package/dist/core/orchestrate-stagnation.d.ts +259 -0
  42. package/dist/core/orchestrate-stagnation.js +270 -0
  43. package/dist/core/orchestrate-stagnation.js.map +1 -0
  44. package/dist/core/orchestrate.d.ts +357 -0
  45. package/dist/core/orchestrate.js +418 -0
  46. package/dist/core/orchestrate.js.map +1 -0
  47. package/dist/core/policy.d.ts +122 -0
  48. package/dist/core/policy.js +102 -0
  49. package/dist/core/policy.js.map +1 -0
  50. package/dist/core/prune-plan.d.ts +141 -0
  51. package/dist/core/prune-plan.js +390 -0
  52. package/dist/core/prune-plan.js.map +1 -0
  53. package/dist/core/score.d.ts +2 -2
  54. package/dist/core/score.js.map +1 -1
  55. package/dist/core/text.d.ts +36 -0
  56. package/dist/core/text.js +66 -0
  57. package/dist/core/text.js.map +1 -0
  58. package/dist/hook/cli.d.ts +9 -0
  59. package/dist/hook/cli.js +52 -0
  60. package/dist/hook/cli.js.map +1 -0
  61. package/dist/hook/contract.d.ts +125 -0
  62. package/dist/hook/contract.js +159 -0
  63. package/dist/hook/contract.js.map +1 -0
  64. package/dist/hook/decision.d.ts +97 -0
  65. package/dist/hook/decision.js +955 -0
  66. package/dist/hook/decision.js.map +1 -0
  67. package/dist/hook/memory-store.d.ts +81 -0
  68. package/dist/hook/memory-store.js +157 -0
  69. package/dist/hook/memory-store.js.map +1 -0
  70. package/dist/hook/payload.d.ts +55 -0
  71. package/dist/hook/payload.js +129 -0
  72. package/dist/hook/payload.js.map +1 -0
  73. package/dist/hook/run.d.ts +48 -0
  74. package/dist/hook/run.js +218 -0
  75. package/dist/hook/run.js.map +1 -0
  76. package/dist/hook/store-port.d.ts +72 -0
  77. package/dist/hook/store-port.js +2 -0
  78. package/dist/hook/store-port.js.map +1 -0
  79. package/dist/index.d.ts +1 -0
  80. package/dist/index.js +1 -0
  81. package/dist/index.js.map +1 -1
  82. package/dist/ports/audit.d.ts +18 -0
  83. package/dist/ports/audit.js +11 -0
  84. package/dist/ports/audit.js.map +1 -0
  85. package/dist/ports/clock.d.ts +14 -0
  86. package/dist/ports/clock.js +11 -0
  87. package/dist/ports/clock.js.map +1 -0
  88. package/dist/ports/decision.d.ts +75 -0
  89. package/dist/ports/decision.js +2 -0
  90. package/dist/ports/decision.js.map +1 -0
  91. package/dist/ports/index.d.ts +14 -0
  92. package/dist/ports/index.js +2 -0
  93. package/dist/ports/index.js.map +1 -0
  94. package/dist/ports/log.d.ts +22 -0
  95. package/dist/ports/log.js +12 -0
  96. package/dist/ports/log.js.map +1 -0
  97. package/dist/ports/state.d.ts +46 -0
  98. package/dist/ports/state.js +13 -0
  99. package/dist/ports/state.js.map +1 -0
  100. package/dist/state/clock.d.ts +40 -0
  101. package/dist/state/clock.js +43 -0
  102. package/dist/state/clock.js.map +1 -0
  103. package/dist/state/file-store.d.ts +340 -0
  104. package/dist/state/file-store.js +849 -0
  105. package/dist/state/file-store.js.map +1 -0
  106. package/dist/state/paths.d.ts +41 -0
  107. package/dist/state/paths.js +73 -0
  108. package/dist/state/paths.js.map +1 -0
  109. package/docs/USER_GUIDE.en.md +79 -36
  110. package/docs/claude-code.md +281 -0
  111. package/docs/design/v0.2.0-harness-plugins.md +381 -0
  112. package/docs/design/v0.3.0-orchestration-unification.md +580 -0
  113. package/docs/dsh-plugin.md +54 -54
  114. package/docs/release-checklist-v0.1.0.md +32 -21
  115. package/docs/release-handbook-porting-notes.md +11 -11
  116. package/docs/release-handbook.md +55 -30
  117. package/docs/release-notes-v0.1.0.md +27 -14
  118. package/docs/release-notes-v0.3.0.md +152 -0
  119. package/docs/research/claude-code-harness.md +607 -0
  120. package/docs/research/pi-harness.md +621 -0
  121. package/package.json +16 -7
@@ -0,0 +1,849 @@
1
+ /**
2
+ * The file-backed session state of the command-hook process.
3
+ *
4
+ * The contract this module implements is design §3: append-only JSONL is the
5
+ * authority, `state.json` is a discardable cache, the lock is an atomic `mkdir`
6
+ * with a five-second staleness rule, and nothing here may block a tool call.
7
+ * When a lock cannot be taken the caller is told so; when a cache file is
8
+ * corrupt it is deleted and rebuilt; when one JSONL line is unreadable it is
9
+ * isolated and the rest of the file is still read.
10
+ *
11
+ * Concurrency assumptions, stated explicitly because they are the whole point:
12
+ * - `events.jsonl` / `ledger.jsonl` lines are each appended with a single write
13
+ * syscall to an `O_APPEND` file descriptor, so interleaving is impossible and
14
+ * a reader never triggers a second write per line.
15
+ * - `state.json` and decision caches are written to a temporary file, fsynced,
16
+ * and renamed into place, so a reader sees the old file or the new one.
17
+ * - A directory (not a file) is the lock: `mkdir` is atomic on every POSIX
18
+ * filesystem the design targets.
19
+ *
20
+ * @module state/file-store
21
+ */
22
+ import * as fs from 'node:fs';
23
+ import * as path from 'node:path';
24
+ import { SystemClock } from './clock.js';
25
+ import { DEFAULT_HARNESS, resolveStateRoot, sessionDirName, sessionHash } from './paths.js';
26
+ /** Longest JSONL line this store will append, in bytes (design §3.3). */
27
+ export const MAX_JSONL_LINE_BYTES = 4 * 1024;
28
+ /** Bad lines read from one file before the file is treated as unusable. */
29
+ export const MAX_BAD_LINES = 5;
30
+ /** Default lifetime of a session directory, seven days. */
31
+ export const SESSION_RETENTION_MS = 7 * 24 * 60 * 60 * 1000;
32
+ /** Default cap on one session's retained originals: 32 MiB. */
33
+ export const MAX_ORIGINAL_BYTES = 32 * 1024 * 1024;
34
+ /** Default staleness of a `lock/` directory before it may be taken over. */
35
+ export const LOCK_STALE_MS = 5 * 1000;
36
+ /** Version recorded in `meta.json`; kept in step with package.json by hand. */
37
+ export const HARNESS_STATE_VERSION = '0.1.0-alpha.2';
38
+ /** Tail window for reads, so a large log is never loaded whole. */
39
+ export const READ_TAIL_BYTES = 256 * 1024;
40
+ /** A record with the fields the store validates before appending. */
41
+ function isObject(value) {
42
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
43
+ }
44
+ /** Whether a pid still exists (EPERM means it exists but is not ours). */
45
+ function isProcessAlive(pid) {
46
+ if (!Number.isInteger(pid) || pid <= 0)
47
+ return false;
48
+ try {
49
+ process.kill(pid, 0);
50
+ return true;
51
+ }
52
+ catch (error) {
53
+ return error.code === 'EPERM';
54
+ }
55
+ }
56
+ /** Random suffix for temporary and tombstone names. */
57
+ function randomSuffix() {
58
+ return `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
59
+ }
60
+ /**
61
+ * The file-backed implementation of the hook's external state.
62
+ *
63
+ * Every mutating operation is either an append (safe for concurrent writers) or
64
+ * guarded by the directory lock. Readers never throw on corrupt data: they
65
+ * isolate, rebuild, or return an empty view, because a hook that throws is a
66
+ * hook that might be misread as a decision.
67
+ */
68
+ export class FileStateStore {
69
+ root;
70
+ harness;
71
+ clock;
72
+ lockStaleMs;
73
+ sessionRetentionMs;
74
+ maxOriginalBytes;
75
+ /**
76
+ * @param options - root, harness, clock, and the retention/lock knobs.
77
+ */
78
+ constructor(options = {}) {
79
+ this.root = options.root ?? resolveStateRoot();
80
+ this.harness = options.harness ?? DEFAULT_HARNESS;
81
+ this.clock = options.clock ?? new SystemClock();
82
+ this.lockStaleMs = options.lockStaleMs ?? LOCK_STALE_MS;
83
+ this.sessionRetentionMs = options.sessionRetentionMs ?? SESSION_RETENTION_MS;
84
+ this.maxOriginalBytes = options.maxOriginalBytes ?? MAX_ORIGINAL_BYTES;
85
+ }
86
+ /** The directory all session directories live in. */
87
+ sessionsRoot() {
88
+ return path.join(this.root, 'sessions');
89
+ }
90
+ /** The directory quarantined sessions are moved into. */
91
+ orphansRoot() {
92
+ return path.join(this.root, 'orphans');
93
+ }
94
+ /** The directory of one session (`<root>/sessions/cc-<sha16>`). */
95
+ sessionDir(sessionId) {
96
+ return path.join(this.sessionsRoot(), sessionDirName(this.harness, sessionId));
97
+ }
98
+ /** The paths of one session without creating anything. */
99
+ sessionPaths(sessionId) {
100
+ const dir = this.sessionDir(sessionId);
101
+ return {
102
+ dir,
103
+ meta: path.join(dir, 'meta.json'),
104
+ state: path.join(dir, 'state.json'),
105
+ events: path.join(dir, 'events.jsonl'),
106
+ ledger: path.join(dir, 'ledger.jsonl'),
107
+ originals: path.join(dir, 'originals'),
108
+ decisions: path.join(dir, 'decisions'),
109
+ lock: path.join(dir, 'lock')
110
+ };
111
+ }
112
+ /**
113
+ * Create the session directory and its metadata if they are missing.
114
+ *
115
+ * A directory whose `meta.json` does not hash back to its own name is
116
+ * quarantined under `orphans/` rather than trusted (design §3.2/§3.4).
117
+ * @param sessionId - the host's session id.
118
+ * @param mode - the effective three-state mode, for `meta.json`.
119
+ * @returns the ensured session paths.
120
+ */
121
+ ensureSession(sessionId, mode) {
122
+ const paths = this.sessionPaths(sessionId);
123
+ this.ensureDir(this.root);
124
+ this.ensureDir(this.sessionsRoot());
125
+ const expectedHash = sessionHash(this.harness, sessionId);
126
+ let exists = false;
127
+ try {
128
+ exists = fs.statSync(paths.dir).isDirectory();
129
+ }
130
+ catch {
131
+ exists = false;
132
+ }
133
+ if (exists) {
134
+ const meta = this.readMeta(paths.meta);
135
+ if (meta !== undefined && sessionHash(this.harness, meta.sessionId) !== expectedHash) {
136
+ // A directory that hashes somewhere else is genuinely not this session.
137
+ this.quarantine(paths.dir);
138
+ exists = false;
139
+ }
140
+ // A missing or unreadable meta is the ordinary creation race: several
141
+ // processes can see a new directory before the first one has renamed its
142
+ // meta into place, and an interrupted writer can leave a bad one. The
143
+ // directory's name already carries the session hash, so the safe repair is
144
+ // to adopt it and rewrite the meta atomically — never to quarantine a
145
+ // directory another process is actively appending to.
146
+ }
147
+ if (!exists)
148
+ this.ensureDir(paths.dir);
149
+ const meta = {
150
+ harness: this.harness,
151
+ sessionId,
152
+ createdAt: this.clock.iso(),
153
+ harnessVersion: HARNESS_STATE_VERSION,
154
+ mode
155
+ };
156
+ if (this.readMeta(paths.meta) === undefined) {
157
+ // Temp + rename, never a half-written meta for another process to read.
158
+ this.writeAtomic(paths.meta, `${JSON.stringify(meta)}\n`);
159
+ }
160
+ this.ensureDir(paths.originals);
161
+ this.ensureDir(paths.decisions);
162
+ for (const file of [paths.events, paths.ledger])
163
+ this.ensureFile(file);
164
+ return paths;
165
+ }
166
+ /**
167
+ * Append one observation to `events.jsonl`.
168
+ * @param sessionId - the session.
169
+ * @param record - the event line.
170
+ */
171
+ appendEvent(sessionId, record) {
172
+ this.appendLine(this.sessionPaths(sessionId).events, record);
173
+ }
174
+ /**
175
+ * Append one decision or skip to `ledger.jsonl`.
176
+ *
177
+ * A record is bounded before it is written: an oversized details object is
178
+ * dropped rather than split, so a line is always one atomic write.
179
+ * @param sessionId - the session.
180
+ * @param record - the ledger line.
181
+ */
182
+ appendLedger(sessionId, record) {
183
+ this.appendLine(this.sessionPaths(sessionId).ledger, this.bounded(record));
184
+ }
185
+ /**
186
+ * Read the newest events of one session, oldest first.
187
+ * @param sessionId - the session.
188
+ * @param limit - maximum events to return.
189
+ * @returns parseable events, newest tail only.
190
+ */
191
+ readEvents(sessionId, limit = 60) {
192
+ const paths = this.sessionPaths(sessionId);
193
+ const records = this.readTail(paths, paths.events, limit);
194
+ return records.filter((record) => isObject(record) && typeof record.kind === 'string');
195
+ }
196
+ /**
197
+ * Read the newest ledger lines of one session, oldest first.
198
+ * @param sessionId - the session.
199
+ * @param limit - maximum lines to return.
200
+ * @returns parseable ledger records.
201
+ */
202
+ readLedger(sessionId, limit = 60) {
203
+ const paths = this.sessionPaths(sessionId);
204
+ const records = this.readTail(paths, paths.ledger, limit);
205
+ return records.filter((record) => isObject(record) && typeof record.type === 'string');
206
+ }
207
+ /**
208
+ * Read the cached state, rebuilding it from the logs when it is missing or
209
+ * corrupt. Never throws.
210
+ * @param sessionId - the session.
211
+ * @returns the derived state (a fresh one when nothing could be read).
212
+ */
213
+ readState(sessionId) {
214
+ const paths = this.sessionPaths(sessionId);
215
+ try {
216
+ const parsed = JSON.parse(fs.readFileSync(paths.state, 'utf8'));
217
+ const state = this.normalizeState(parsed);
218
+ if (state)
219
+ return state;
220
+ }
221
+ catch {
222
+ // missing or truncated: fall through to a rebuild
223
+ }
224
+ this.safeUnlink(paths.state);
225
+ const rebuilt = this.rebuildState(sessionId);
226
+ this.writeState(paths, rebuilt);
227
+ return rebuilt;
228
+ }
229
+ /**
230
+ * Run one read-modify-write of `state.json` under the directory lock.
231
+ *
232
+ * A caller that does not get the lock must skip its turn, not queue: a tool
233
+ * call is never worth blocking (design §3.3).
234
+ * @param sessionId - the session.
235
+ * @param mutate - pure update of the state in place.
236
+ * @returns whether the lock was acquired, plus the callback's value.
237
+ */
238
+ updateState(sessionId, mutate) {
239
+ const paths = this.sessionPaths(sessionId);
240
+ const lock = this.acquireLock(paths);
241
+ if (!lock.acquired)
242
+ return { acquired: false, reason: lock.reason };
243
+ try {
244
+ const state = this.readState(sessionId);
245
+ const value = mutate(state);
246
+ state.updatedAt = this.clock.iso();
247
+ this.writeState(paths, state);
248
+ return { acquired: true, value };
249
+ }
250
+ finally {
251
+ lock.release?.();
252
+ }
253
+ }
254
+ /**
255
+ * Whether a dedupe key was already accounted for in the ledger.
256
+ *
257
+ * Only the tail is scanned: a hook is never asked about an ancient call, and
258
+ * an unbounded scan would turn a fast command into a slow one. Error records
259
+ * do not count — a duplicate delivery after a transient failure is allowed to
260
+ * decide again.
261
+ * @param sessionId - the session.
262
+ * @param key - the dedupe key.
263
+ * @param limit - how many trailing ledger lines to inspect.
264
+ * @returns whether a non-error record already carries this key.
265
+ */
266
+ ledgerHasKey(sessionId, key, limit = 512) {
267
+ return this.readLedger(sessionId, limit).some((record) => record.dedupeKey === key && record.type !== 'error');
268
+ }
269
+ /**
270
+ * Whether a dedupe key was already written to the event log.
271
+ *
272
+ * This is the crash window after the observation was appended and before the
273
+ * ledger line was: the retry must not append the observation twice.
274
+ * @param sessionId - the session.
275
+ * @param key - the dedupe key.
276
+ * @param limit - how many trailing events to inspect.
277
+ * @returns whether the event log already carries this key.
278
+ */
279
+ eventsHaveKey(sessionId, key, limit = 512) {
280
+ return this.readEvents(sessionId, limit).some((record) => record.dedupeKey === key);
281
+ }
282
+ /**
283
+ * Read one cached decision output.
284
+ * @param sessionId - the session.
285
+ * @param key - the dedupe key.
286
+ * @returns the cached output, or `undefined` when absent/corrupt.
287
+ */
288
+ readDecision(sessionId, key) {
289
+ const file = path.join(this.sessionPaths(sessionId).decisions, `${key}.json`);
290
+ try {
291
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
292
+ return isObject(parsed) ? parsed : undefined;
293
+ }
294
+ catch {
295
+ return undefined;
296
+ }
297
+ }
298
+ /**
299
+ * Commit one decision output atomically.
300
+ *
301
+ * The decision cache doubles as the idempotency marker: a duplicate delivery
302
+ * of the same dedupe key replays this object instead of deciding again.
303
+ * @param sessionId - the session.
304
+ * @param key - the dedupe key.
305
+ * @param output - the exact stdout object of the command.
306
+ */
307
+ writeDecision(sessionId, key, output) {
308
+ const paths = this.sessionPaths(sessionId);
309
+ this.ensureDir(paths.decisions);
310
+ this.writeAtomic(path.join(paths.decisions, `${key}.json`), JSON.stringify(output));
311
+ }
312
+ /**
313
+ * Claim the right to decide one dedupe key before the expensive path runs.
314
+ *
315
+ * The decision cache is the commit, but it can only be written after the
316
+ * judgment. Two processes delivering the same `tool_use_id` concurrently would
317
+ * both decide in that window; this exclusive-create claim makes the loser an
318
+ * explicit no-op (or a replay, when the winner has already committed). A claim
319
+ * older than `staleMs` is taken over, so a crashed process cannot wedge a key
320
+ * forever.
321
+ * @param sessionId - the session.
322
+ * @param key - the dedupe key.
323
+ * @param staleMs - age after which a claim is considered abandoned.
324
+ * @returns whether this process may decide the key.
325
+ */
326
+ claimDecision(sessionId, key, staleMs = 10_000) {
327
+ const paths = this.sessionPaths(sessionId);
328
+ this.ensureDir(paths.decisions);
329
+ const file = path.join(paths.decisions, `${key}.claim`);
330
+ for (let attempt = 0; attempt < 2; attempt += 1) {
331
+ try {
332
+ fs.writeFileSync(file, JSON.stringify({ pid: process.pid, startedMs: this.clock.now() }), {
333
+ flag: 'wx',
334
+ mode: 0o600
335
+ });
336
+ return { acquired: true };
337
+ }
338
+ catch (error) {
339
+ if (error.code !== 'EEXIST')
340
+ return { acquired: false };
341
+ let startedMs = this.clock.now();
342
+ let ownerAlive = true;
343
+ try {
344
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
345
+ if (isObject(parsed)) {
346
+ if (typeof parsed.startedMs === 'number')
347
+ startedMs = parsed.startedMs;
348
+ if (typeof parsed.pid === 'number')
349
+ ownerAlive = isProcessAlive(parsed.pid);
350
+ }
351
+ }
352
+ catch {
353
+ // unreadable claim: its mtime is the best age estimate
354
+ try {
355
+ startedMs = fs.statSync(file).mtimeMs;
356
+ }
357
+ catch {
358
+ continue;
359
+ }
360
+ }
361
+ // A dead owner's claim is recoverable at once: that is what makes a
362
+ // `kill -9` followed by an immediate replay decide rather than no-op.
363
+ if (ownerAlive && this.clock.now() - startedMs <= staleMs)
364
+ return { acquired: false };
365
+ const tombstone = `${file}.stale-${randomSuffix()}`;
366
+ try {
367
+ fs.renameSync(file, tombstone);
368
+ fs.rmSync(tombstone, { force: true });
369
+ }
370
+ catch {
371
+ return { acquired: false };
372
+ }
373
+ }
374
+ }
375
+ return { acquired: false };
376
+ }
377
+ /** Release a claim; never throws. */
378
+ releaseDecisionClaim(sessionId, key) {
379
+ this.safeUnlink(path.join(this.sessionPaths(sessionId).decisions, `${key}.claim`));
380
+ }
381
+ /**
382
+ * Retain one pre-prune payload, evicting the oldest copies when the cap is
383
+ * exceeded.
384
+ *
385
+ * The cap applies to the whole `originals/` directory of one session. Evicted
386
+ * names are returned so the caller can record the downgrade; when the new
387
+ * payload itself cannot fit the result is `retained: false` and the caller must
388
+ * install the reduction without a locator and without counting a saving.
389
+ * @param sessionId - the session.
390
+ * @param digest - content digest (the file stem).
391
+ * @param text - the payload, verbatim.
392
+ * @returns what happened.
393
+ */
394
+ retainOriginal(sessionId, digest, text) {
395
+ const paths = this.sessionPaths(sessionId);
396
+ this.ensureDir(paths.originals);
397
+ const target = path.join(paths.originals, `${digest}.txt`);
398
+ if (fs.existsSync(target))
399
+ return { retained: true, evicted: [] };
400
+ const size = Buffer.byteLength(text, 'utf8');
401
+ // A payload larger than the whole allowance can never fit; evicting older
402
+ // copies for it would only destroy data, so it is refused before any eviction.
403
+ if (size > this.maxOriginalBytes)
404
+ return { retained: false, evicted: [], reason: 'retention-cap' };
405
+ const entries = this.originalEntries(paths.originals);
406
+ let total = entries.reduce((sum, entry) => sum + entry.size, 0);
407
+ const evicted = [];
408
+ if (total + size > this.maxOriginalBytes) {
409
+ for (const entry of entries) {
410
+ if (total + size <= this.maxOriginalBytes)
411
+ break;
412
+ try {
413
+ fs.unlinkSync(path.join(paths.originals, entry.name));
414
+ total -= entry.size;
415
+ evicted.push(entry.name.replace(/\.txt$/, ''));
416
+ }
417
+ catch {
418
+ // A concurrent eviction took it first; the accounting stays honest.
419
+ }
420
+ }
421
+ }
422
+ if (total + size > this.maxOriginalBytes) {
423
+ return { retained: false, evicted, reason: 'retention-cap' };
424
+ }
425
+ try {
426
+ fs.writeFileSync(target, text, { flag: 'wx', mode: 0o600 });
427
+ }
428
+ catch (error) {
429
+ if (error.code !== 'EEXIST') {
430
+ return { retained: false, evicted, reason: 'retention-failed' };
431
+ }
432
+ }
433
+ return { retained: true, evicted };
434
+ }
435
+ /**
436
+ * Read one retained payload back.
437
+ *
438
+ * The locator a pruned result carries names this record; reading it is what
439
+ * makes the reduction reversible, so a missing or unreadable file answers
440
+ * `undefined` instead of throwing into a decision path.
441
+ * @param sessionId - the session.
442
+ * @param digest - content digest (the file stem).
443
+ * @returns the verbatim payload, or `undefined`.
444
+ */
445
+ readOriginal(sessionId, digest) {
446
+ try {
447
+ const paths = this.sessionPaths(sessionId);
448
+ if (!/^[0-9a-f]{8,64}$/.test(digest))
449
+ return undefined;
450
+ return fs.readFileSync(path.join(paths.originals, `${digest}.txt`), 'utf8');
451
+ }
452
+ catch {
453
+ return undefined;
454
+ }
455
+ }
456
+ /** Enforce one session's original cap without retaining anything new. */
457
+ gcOriginals(sessionId) {
458
+ const paths = this.sessionPaths(sessionId);
459
+ let entries;
460
+ try {
461
+ entries = this.originalEntries(paths.originals);
462
+ }
463
+ catch {
464
+ return [];
465
+ }
466
+ let total = entries.reduce((sum, entry) => sum + entry.size, 0);
467
+ const evicted = [];
468
+ for (const entry of entries) {
469
+ if (total <= this.maxOriginalBytes)
470
+ break;
471
+ try {
472
+ fs.unlinkSync(path.join(paths.originals, entry.name));
473
+ total -= entry.size;
474
+ evicted.push(entry.name.replace(/\.txt$/, ''));
475
+ }
476
+ catch {
477
+ // best effort
478
+ }
479
+ }
480
+ return evicted;
481
+ }
482
+ /**
483
+ * Remove session directories older than the retention window.
484
+ * @param nowMs - clock reading to compare against (defaults to the store clock).
485
+ * @param keepSessionId - a session that must survive even if its mtime looks
486
+ * old (a pinned test clock must never garbage-collect the turn being served).
487
+ * @returns the removed directory names.
488
+ */
489
+ gcSessions(nowMs, keepSessionId) {
490
+ const now = nowMs ?? this.clock.now();
491
+ const keep = keepSessionId === undefined ? undefined : path.basename(this.sessionDir(keepSessionId));
492
+ let entries;
493
+ try {
494
+ entries = fs.readdirSync(this.sessionsRoot(), { withFileTypes: true });
495
+ }
496
+ catch {
497
+ return [];
498
+ }
499
+ const removed = [];
500
+ for (const entry of entries) {
501
+ if (!entry.isDirectory())
502
+ continue;
503
+ if (entry.name === keep)
504
+ continue;
505
+ const dir = path.join(this.sessionsRoot(), entry.name);
506
+ const mtime = this.latestMtime(dir);
507
+ if (now - mtime <= this.sessionRetentionMs)
508
+ continue;
509
+ try {
510
+ fs.rmSync(dir, { recursive: true, force: true });
511
+ removed.push(entry.name);
512
+ }
513
+ catch {
514
+ // best effort: a concurrently opened session is left for the next gc
515
+ }
516
+ }
517
+ return removed;
518
+ }
519
+ /** The quarantine log path for a session, created on demand. */
520
+ corruptLog(sessionId) {
521
+ return path.join(this.sessionPaths(sessionId).dir, `corrupt-${this.clock.now()}.log`);
522
+ }
523
+ // ---------------------------------------------------------------- internals
524
+ /** Create one directory with user-only permissions, best effort. */
525
+ ensureDir(dir) {
526
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
527
+ try {
528
+ fs.chmodSync(dir, 0o700);
529
+ }
530
+ catch {
531
+ // Existing ownership/permissions outside our control; keep going.
532
+ }
533
+ }
534
+ /** Create an empty file with 0600 if it does not exist yet. */
535
+ ensureFile(file) {
536
+ if (fs.existsSync(file))
537
+ return;
538
+ try {
539
+ fs.writeFileSync(file, '', { flag: 'wx', mode: 0o600 });
540
+ }
541
+ catch (error) {
542
+ if (error.code !== 'EEXIST')
543
+ throw error;
544
+ }
545
+ }
546
+ /** Single-write append of one JSON line. */
547
+ appendLine(file, record) {
548
+ const line = `${JSON.stringify(record)}\n`;
549
+ if (Buffer.byteLength(line, 'utf8') > MAX_JSONL_LINE_BYTES) {
550
+ throw new Error(`refusing to append a ${Buffer.byteLength(line, 'utf8')}-byte JSONL line (max ${MAX_JSONL_LINE_BYTES})`);
551
+ }
552
+ const fd = fs.openSync(file, 'a', 0o600);
553
+ try {
554
+ fs.writeSync(fd, line);
555
+ }
556
+ finally {
557
+ fs.closeSync(fd);
558
+ }
559
+ }
560
+ /** Read only the tail of a JSONL file, isolating unreadable lines. */
561
+ readTail(paths, file, limit) {
562
+ let fd;
563
+ try {
564
+ fd = fs.openSync(file, 'r');
565
+ }
566
+ catch {
567
+ return [];
568
+ }
569
+ try {
570
+ const size = fs.fstatSync(fd).size;
571
+ if (size === 0)
572
+ return [];
573
+ const start = Math.max(0, size - READ_TAIL_BYTES);
574
+ const buffer = Buffer.alloc(size - start);
575
+ fs.readSync(fd, buffer, 0, buffer.length, start);
576
+ let text = buffer.toString('utf8');
577
+ if (start > 0) {
578
+ const newline = text.indexOf('\n');
579
+ text = newline >= 0 ? text.slice(newline + 1) : '';
580
+ }
581
+ const lines = text.split('\n').filter((line) => line.trim().length > 0);
582
+ const window = limit > 0 ? lines.slice(Math.max(0, lines.length - limit)) : lines;
583
+ const good = [];
584
+ const bad = [];
585
+ for (const line of window) {
586
+ try {
587
+ good.push(JSON.parse(line));
588
+ }
589
+ catch {
590
+ bad.push(line);
591
+ }
592
+ }
593
+ if (bad.length > 0)
594
+ this.isolateBadLines(paths, bad);
595
+ if (bad.length > MAX_BAD_LINES)
596
+ return [];
597
+ return good;
598
+ }
599
+ catch {
600
+ return [];
601
+ }
602
+ finally {
603
+ fs.closeSync(fd);
604
+ }
605
+ }
606
+ /** Append unreadable lines to `corrupt-<ts>.log`; never grow it unbounded. */
607
+ isolateBadLines(paths, bad) {
608
+ try {
609
+ const payload = bad.map((line) => line.slice(0, 1000)).join('\n');
610
+ fs.appendFileSync(this.corruptLogFor(paths.dir), `${payload}\n`, { encoding: 'utf8', mode: 0o600 });
611
+ }
612
+ catch {
613
+ // diagnostics are best effort
614
+ }
615
+ }
616
+ /** `corrupt-<ts>.log` in a session directory. */
617
+ corruptLogFor(dir) {
618
+ return path.join(dir, `corrupt-${this.clock.now()}.log`);
619
+ }
620
+ /** Validate and normalize a parsed `state.json`. */
621
+ normalizeState(value) {
622
+ if (!isObject(value))
623
+ return undefined;
624
+ if (value.version !== 1)
625
+ return undefined;
626
+ if (typeof value.turnNo !== 'number' || !Number.isFinite(value.turnNo) || value.turnNo < 0)
627
+ return undefined;
628
+ if (!isObject(value.budgets))
629
+ return undefined;
630
+ const budgets = value.budgets;
631
+ if (typeof budgets.interventions !== 'number' ||
632
+ typeof budgets.judgmentsTurn !== 'number' ||
633
+ typeof budgets.judgmentsSession !== 'number') {
634
+ return undefined;
635
+ }
636
+ return {
637
+ version: 1,
638
+ turnNo: value.turnNo,
639
+ appliedSignatures: Array.isArray(value.appliedSignatures)
640
+ ? value.appliedSignatures.filter((item) => typeof item === 'string').slice(-50)
641
+ : [],
642
+ budgets: {
643
+ interventions: budgets.interventions,
644
+ judgmentsTurn: budgets.judgmentsTurn,
645
+ judgmentsSession: budgets.judgmentsSession
646
+ },
647
+ continues: isObject(value.continues)
648
+ ? Object.fromEntries(Object.entries(value.continues).filter(([, count]) => typeof count === 'number'))
649
+ : {},
650
+ updatedAt: typeof value.updatedAt === 'string' ? value.updatedAt : this.clock.iso()
651
+ };
652
+ }
653
+ /** Rebuild the discardable state from the two authoritative logs. */
654
+ rebuildState(sessionId) {
655
+ const events = this.readEvents(sessionId, 5000);
656
+ const ledger = this.readLedger(sessionId, 5000);
657
+ let turnNo = 0;
658
+ for (const event of events) {
659
+ if (event.kind === 'stop' && typeof event.turnNo === 'number')
660
+ turnNo = Math.max(turnNo, event.turnNo);
661
+ }
662
+ const judgmentsSession = ledger.filter((record) => record.judged === true).length;
663
+ return {
664
+ version: 1,
665
+ turnNo,
666
+ appliedSignatures: [],
667
+ budgets: { interventions: 0, judgmentsTurn: 0, judgmentsSession },
668
+ continues: {},
669
+ updatedAt: this.clock.iso()
670
+ };
671
+ }
672
+ /** Write `state.json` via temp + fsync + rename. */
673
+ writeState(paths, state) {
674
+ this.writeAtomic(paths.state, JSON.stringify(state));
675
+ }
676
+ /** Atomic replacement of a small file. */
677
+ writeAtomic(file, content) {
678
+ const tmp = `${file}.${randomSuffix()}.tmp`;
679
+ const fd = fs.openSync(tmp, 'w', 0o600);
680
+ try {
681
+ fs.writeSync(fd, content);
682
+ fs.fsyncSync(fd);
683
+ }
684
+ finally {
685
+ fs.closeSync(fd);
686
+ }
687
+ try {
688
+ fs.renameSync(tmp, file);
689
+ }
690
+ catch {
691
+ // Windows-style rename-over-existing; POSIX never takes this branch.
692
+ this.safeUnlink(file);
693
+ fs.renameSync(tmp, file);
694
+ }
695
+ }
696
+ /** Unlink without throwing. */
697
+ safeUnlink(file) {
698
+ try {
699
+ fs.unlinkSync(file);
700
+ }
701
+ catch {
702
+ // already gone
703
+ }
704
+ }
705
+ /** Read and validate `meta.json`. */
706
+ readMeta(file) {
707
+ try {
708
+ const parsed = JSON.parse(fs.readFileSync(file, 'utf8'));
709
+ if (!isObject(parsed))
710
+ return undefined;
711
+ if (typeof parsed.sessionId !== 'string' || typeof parsed.harness !== 'string')
712
+ return undefined;
713
+ return parsed;
714
+ }
715
+ catch {
716
+ return undefined;
717
+ }
718
+ }
719
+ /** Move a directory whose meta does not match its name into `orphans/`. */
720
+ quarantine(dir) {
721
+ try {
722
+ this.ensureDir(this.orphansRoot());
723
+ const target = path.join(this.orphansRoot(), `${path.basename(dir)}-${this.clock.now()}`);
724
+ fs.renameSync(dir, target);
725
+ }
726
+ catch {
727
+ // If it cannot be moved, leave it; ensureSession recreates the missing path.
728
+ }
729
+ }
730
+ /** Newest mtime under one directory, for the seven-day rule. */
731
+ latestMtime(dir) {
732
+ let latest = 0;
733
+ try {
734
+ latest = fs.statSync(dir).mtimeMs;
735
+ for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
736
+ try {
737
+ const stat = fs.statSync(path.join(dir, entry.name));
738
+ if (stat.mtimeMs > latest)
739
+ latest = stat.mtimeMs;
740
+ }
741
+ catch {
742
+ // raced with a unlink
743
+ }
744
+ }
745
+ }
746
+ catch {
747
+ latest = 0;
748
+ }
749
+ return latest;
750
+ }
751
+ /** The retained originals, oldest first. */
752
+ originalEntries(dir) {
753
+ let names;
754
+ try {
755
+ names = fs.readdirSync(dir);
756
+ }
757
+ catch {
758
+ return [];
759
+ }
760
+ const entries = [];
761
+ for (const name of names) {
762
+ if (!name.endsWith('.txt'))
763
+ continue;
764
+ try {
765
+ const stat = fs.statSync(path.join(dir, name));
766
+ entries.push({ name, size: stat.size, mtimeMs: stat.mtimeMs });
767
+ }
768
+ catch {
769
+ // raced with an eviction
770
+ }
771
+ }
772
+ entries.sort((left, right) => left.mtimeMs - right.mtimeMs);
773
+ return entries;
774
+ }
775
+ /** Take the directory lock, taking over one that is older than the stale rule. */
776
+ acquireLock(paths) {
777
+ for (let attempt = 0; attempt < 2; attempt += 1) {
778
+ try {
779
+ fs.mkdirSync(paths.lock, { mode: 0o700 });
780
+ try {
781
+ fs.writeFileSync(path.join(paths.lock, 'owner.json'), JSON.stringify({ pid: process.pid, startedAt: this.clock.iso(), startedMs: this.clock.now() }), { mode: 0o600 });
782
+ }
783
+ catch {
784
+ // The lock is still held; owner metadata is diagnostics only.
785
+ }
786
+ return { acquired: true, release: () => this.releaseLock(paths.lock) };
787
+ }
788
+ catch (error) {
789
+ if (error.code !== 'EEXIST')
790
+ return { acquired: false, reason: 'lock-error' };
791
+ const startedMs = this.lockStartedMs(paths.lock);
792
+ const age = this.clock.now() - startedMs;
793
+ if (!Number.isFinite(age) || age <= this.lockStaleMs)
794
+ return { acquired: false, reason: 'lock-contention' };
795
+ const tombstone = `${paths.lock}.stale-${randomSuffix()}`;
796
+ try {
797
+ fs.renameSync(paths.lock, tombstone);
798
+ fs.rmSync(tombstone, { recursive: true, force: true });
799
+ }
800
+ catch {
801
+ return { acquired: false, reason: 'lock-contention' };
802
+ }
803
+ }
804
+ }
805
+ return { acquired: false, reason: 'lock-contention' };
806
+ }
807
+ /** Release the lock directory. */
808
+ releaseLock(lock) {
809
+ try {
810
+ fs.rmSync(lock, { recursive: true, force: true });
811
+ }
812
+ catch {
813
+ // already gone
814
+ }
815
+ }
816
+ /** When the current lock owner started, from its metadata or its mtime. */
817
+ lockStartedMs(lock) {
818
+ try {
819
+ const owner = JSON.parse(fs.readFileSync(path.join(lock, 'owner.json'), 'utf8'));
820
+ if (isObject(owner) && typeof owner.startedMs === 'number' && Number.isFinite(owner.startedMs)) {
821
+ return owner.startedMs;
822
+ }
823
+ }
824
+ catch {
825
+ // fall through to mtime
826
+ }
827
+ try {
828
+ return fs.statSync(lock).mtimeMs;
829
+ }
830
+ catch {
831
+ return this.clock.now();
832
+ }
833
+ }
834
+ /** Bound one ledger record to the line budget before it can be appended. */
835
+ bounded(record) {
836
+ const line = `${JSON.stringify(record)}\n`;
837
+ if (Buffer.byteLength(line, 'utf8') <= MAX_JSONL_LINE_BYTES)
838
+ return record;
839
+ const minimal = {
840
+ ...record,
841
+ details: { truncated: true },
842
+ skipReason: (record.skipReason ?? '').slice(0, 120)
843
+ };
844
+ if (Buffer.byteLength(`${JSON.stringify(minimal)}\n`, 'utf8') <= MAX_JSONL_LINE_BYTES)
845
+ return minimal;
846
+ return { ...minimal, details: undefined };
847
+ }
848
+ }
849
+ //# sourceMappingURL=file-store.js.map