@namzu/sdk 20.4.0 → 21.1.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 (98) hide show
  1. package/CHANGELOG.md +223 -0
  2. package/dist/bridge/sse/mapper.d.ts +19 -0
  3. package/dist/bridge/sse/mapper.d.ts.map +1 -1
  4. package/dist/bridge/sse/mapper.js +9 -1
  5. package/dist/bridge/sse/mapper.js.map +1 -1
  6. package/dist/contracts/schemas.d.ts +10 -10
  7. package/dist/manager/run/persistence.d.ts +26 -0
  8. package/dist/manager/run/persistence.d.ts.map +1 -1
  9. package/dist/manager/run/persistence.js +40 -0
  10. package/dist/manager/run/persistence.js.map +1 -1
  11. package/dist/public-runtime.d.ts +8 -0
  12. package/dist/public-runtime.d.ts.map +1 -1
  13. package/dist/public-runtime.js +31 -0
  14. package/dist/public-runtime.js.map +1 -1
  15. package/dist/run/command-gate.d.ts +107 -0
  16. package/dist/run/command-gate.d.ts.map +1 -0
  17. package/dist/run/command-gate.js +157 -0
  18. package/dist/run/command-gate.js.map +1 -0
  19. package/dist/run/drain.d.ts +194 -0
  20. package/dist/run/drain.d.ts.map +1 -0
  21. package/dist/run/drain.js +228 -0
  22. package/dist/run/drain.js.map +1 -0
  23. package/dist/run/index.d.ts +8 -0
  24. package/dist/run/index.d.ts.map +1 -1
  25. package/dist/run/index.js +4 -0
  26. package/dist/run/index.js.map +1 -1
  27. package/dist/run/memory-promoter.d.ts +70 -0
  28. package/dist/run/memory-promoter.d.ts.map +1 -0
  29. package/dist/run/memory-promoter.js +117 -0
  30. package/dist/run/memory-promoter.js.map +1 -0
  31. package/dist/run/workspace-fingerprint.d.ts +105 -0
  32. package/dist/run/workspace-fingerprint.d.ts.map +1 -0
  33. package/dist/run/workspace-fingerprint.js +147 -0
  34. package/dist/run/workspace-fingerprint.js.map +1 -0
  35. package/dist/runtime/query/events.d.ts +12 -0
  36. package/dist/runtime/query/events.d.ts.map +1 -1
  37. package/dist/runtime/query/events.js +61 -3
  38. package/dist/runtime/query/events.js.map +1 -1
  39. package/dist/runtime/query/index.d.ts +36 -0
  40. package/dist/runtime/query/index.d.ts.map +1 -1
  41. package/dist/runtime/query/index.js +32 -0
  42. package/dist/runtime/query/index.js.map +1 -1
  43. package/dist/runtime/query/resume-run.d.ts +25 -0
  44. package/dist/runtime/query/resume-run.d.ts.map +1 -1
  45. package/dist/runtime/query/resume-run.js +15 -3
  46. package/dist/runtime/query/resume-run.js.map +1 -1
  47. package/dist/store/index.d.ts +1 -1
  48. package/dist/store/index.d.ts.map +1 -1
  49. package/dist/store/index.js +1 -1
  50. package/dist/store/index.js.map +1 -1
  51. package/dist/store/run/conformance.d.ts +159 -0
  52. package/dist/store/run/conformance.d.ts.map +1 -0
  53. package/dist/store/run/conformance.js +451 -0
  54. package/dist/store/run/conformance.js.map +1 -0
  55. package/dist/store/run/disk.d.ts +30 -2
  56. package/dist/store/run/disk.d.ts.map +1 -1
  57. package/dist/store/run/disk.js +101 -0
  58. package/dist/store/run/disk.js.map +1 -1
  59. package/dist/store/run/memory.d.ts +5 -4
  60. package/dist/store/run/memory.d.ts.map +1 -1
  61. package/dist/store/run/memory.js +30 -1
  62. package/dist/store/run/memory.js.map +1 -1
  63. package/dist/types/doctor/check.d.ts +28 -2
  64. package/dist/types/doctor/check.d.ts.map +1 -1
  65. package/dist/types/run/event-cursor.d.ts +90 -0
  66. package/dist/types/run/event-cursor.d.ts.map +1 -0
  67. package/dist/types/run/event-cursor.js +47 -0
  68. package/dist/types/run/event-cursor.js.map +1 -0
  69. package/dist/types/run/events.d.ts +71 -1
  70. package/dist/types/run/events.d.ts.map +1 -1
  71. package/dist/types/run/events.js.map +1 -1
  72. package/dist/types/run/index.d.ts +1 -0
  73. package/dist/types/run/index.d.ts.map +1 -1
  74. package/dist/types/run/index.js +1 -0
  75. package/dist/types/run/index.js.map +1 -1
  76. package/dist/types/run/store.d.ts +41 -1
  77. package/dist/types/run/store.d.ts.map +1 -1
  78. package/package.json +6 -1
  79. package/src/bridge/sse/mapper.ts +28 -1
  80. package/src/manager/run/persistence.ts +43 -0
  81. package/src/public-runtime.ts +53 -0
  82. package/src/run/command-gate.ts +234 -0
  83. package/src/run/drain.ts +393 -0
  84. package/src/run/index.ts +20 -0
  85. package/src/run/memory-promoter.ts +155 -0
  86. package/src/run/workspace-fingerprint.ts +193 -0
  87. package/src/runtime/query/events.ts +68 -4
  88. package/src/runtime/query/index.ts +87 -0
  89. package/src/runtime/query/resume-run.ts +67 -12
  90. package/src/store/index.ts +1 -1
  91. package/src/store/run/conformance.ts +705 -0
  92. package/src/store/run/disk.ts +106 -2
  93. package/src/store/run/memory.ts +35 -5
  94. package/src/types/doctor/check.ts +28 -2
  95. package/src/types/run/event-cursor.ts +118 -0
  96. package/src/types/run/events.ts +80 -3
  97. package/src/types/run/index.ts +1 -0
  98. package/src/types/run/store.ts +43 -1
@@ -0,0 +1,393 @@
1
+ /**
2
+ * One pass over a queue of durable runs: list what nobody holds, take it,
3
+ * hand it to a worker, give it back.
4
+ *
5
+ * Every primitive this composes already shipped —
6
+ * {@link import('../store/run/listing.js').listDurableRuns} enumerates runs
7
+ * above a run id, `claimRun` arbitrates between processes, `releaseRun`
8
+ * returns a run to the queue, and `resumeRun` carries a fence into every
9
+ * durable write. Nothing composed them, so the two things the claim was
10
+ * built for — an approval inbox and a crash sweeper — still required a host
11
+ * to write the loop, and writing it correctly means getting the release
12
+ * into a `finally` and the `null` claim out of the error path. Both are the
13
+ * kind of thing a host gets wrong once, quietly.
14
+ *
15
+ * ## What this deliberately is NOT
16
+ *
17
+ * A supervisor, a daemon, or a scheduler. There is no timer here, no
18
+ * process spawn, no retry backoff and no `while (true)`. `drainRuns` makes
19
+ * ONE bounded pass and returns what happened; running it again is the
20
+ * caller's decision, made wherever that caller already has a scheduler. A
21
+ * per-platform supervisor is the same trade the deployment-adapter matrix
22
+ * was rejected for: one seam beats N adapters.
23
+ *
24
+ * The unit of work is a callback, so this module never needs a provider, a
25
+ * tool registry or a sandbox — the half of a run that cannot be serialized
26
+ * stays with the caller, exactly as `resumeRun` already splits it.
27
+ */
28
+
29
+ import { claimRun, listDurableRuns, releaseRun, summarizePark } from '../store/run/listing.js'
30
+ import type { NamzuErrorCode } from '../types/errors/index.js'
31
+ import { NamzuError } from '../types/errors/index.js'
32
+ import type { RunId } from '../types/ids/index.js'
33
+ import type {
34
+ CheckpointListingScope,
35
+ CheckpointStore,
36
+ DurableRunEntry,
37
+ ParkState,
38
+ RunClaim,
39
+ } from '../types/run/checkpoint-store.js'
40
+
41
+ /** Runs handled per pass when the caller names no page size. */
42
+ export const DEFAULT_DRAIN_PAGE_SIZE = 100
43
+
44
+ /**
45
+ * What a drainer does with one run it successfully took.
46
+ *
47
+ * Receives the claim, not just its fence, because the holder and expiry are
48
+ * what a worker needs to decide whether it still has time to start — and
49
+ * because a caller that only ever sees a number tends to forget the lease
50
+ * can lapse under it.
51
+ *
52
+ * The intended body is a resume:
53
+ *
54
+ * ```ts
55
+ * onRun: (entry, claim) =>
56
+ * resumeRun({
57
+ * ...yourQueryParams,
58
+ * scope: { ...entry, threadId },
59
+ * checkpointStore: store,
60
+ * claimFence: claim.fence,
61
+ * })
62
+ * ```
63
+ *
64
+ * `claimFence` is the whole reason the claim is handed over: a write that
65
+ * does not carry it is unfenced, so a worker stalled past its lease would
66
+ * still be able to overwrite the record of whoever took the run over.
67
+ *
68
+ * A throw is recorded against that run and the pass continues. A drainer
69
+ * that died on the first bad run would leave the rest of the queue
70
+ * untouched, which is the failure a queue exists to spread out.
71
+ */
72
+ export type DrainRun = (entry: DurableRunEntry, claim: RunClaim) => void | Promise<void>
73
+
74
+ export interface DrainRunsParams {
75
+ /** Backend to list, claim and release against. Must support all three. */
76
+ readonly store: CheckpointStore
77
+ /** Contiguous prefix — `tenantId` required. See {@link CheckpointListingScope}. */
78
+ readonly scope: CheckpointListingScope
79
+ /**
80
+ * Who is taking the runs. Per-PROCESS, never per-deployment: `holder` is
81
+ * the only thing that distinguishes a renewal from a theft, so two
82
+ * drainers sharing a string take live claims from each other instantly.
83
+ */
84
+ readonly holder: string
85
+ /** Lease length in ms. Long enough that the slowest run finishes inside it. */
86
+ readonly ttlMs: number
87
+ /** The work. See {@link DrainRun}. */
88
+ readonly onRun: DrainRun
89
+
90
+ /**
91
+ * Keep only runs whose park is in one of these states.
92
+ *
93
+ * **Absent means every run with durable state, parked or not**, and that
94
+ * is not a placeholder default — it is what a crash sweep wants, because
95
+ * a run that died mid-flight never parked and would be invisible under
96
+ * any park filter. An approval inbox passes `['outstanding']`; a
97
+ * reclamation sweep passes `['expired']`.
98
+ */
99
+ readonly park?: readonly ParkState[]
100
+
101
+ /**
102
+ * Stop taking new runs. Work already in flight is NOT interrupted — this
103
+ * module owns no run and cannot cancel one; a caller that needs to abort
104
+ * the work itself passes the same signal into whatever `onRun` starts.
105
+ */
106
+ readonly signal?: AbortSignal
107
+
108
+ /**
109
+ * How many runs may be in flight at once. Defaults to 1.
110
+ *
111
+ * Bounded on purpose. The obvious implementation — claim everything, then
112
+ * `Promise.all` — holds N leases while doing one run's worth of work, so
113
+ * the runs at the back of the batch expire before they are started and
114
+ * are taken by somebody else mid-flight.
115
+ */
116
+ readonly maxConcurrent?: number
117
+
118
+ /** Listing page size. See {@link DEFAULT_DRAIN_PAGE_SIZE}. */
119
+ readonly pageSize?: number
120
+
121
+ /**
122
+ * Clock for expiry, so one pass judges every claim against one instant
123
+ * and a test does not have to wait out a lease.
124
+ */
125
+ readonly now?: number
126
+ }
127
+
128
+ /** A run a pass could not finish, and why. */
129
+ export interface DrainFailure {
130
+ readonly runId: RunId
131
+ readonly error: string
132
+ }
133
+
134
+ /** What one pass did. */
135
+ export interface DrainRunsResult {
136
+ /** Rows the listing returned, before any of them were contended for. */
137
+ readonly listed: number
138
+ /** Runs whose `onRun` returned. */
139
+ readonly drained: readonly RunId[]
140
+ /**
141
+ * Runs another worker held. Not failures: "somebody got there first" is
142
+ * the ordinary outcome of a queue with more than one reader.
143
+ */
144
+ readonly skipped: readonly RunId[]
145
+ /**
146
+ * Runs that stopped matching {@link DrainRunsParams.park} between the
147
+ * listing and the claim, and were given straight back.
148
+ *
149
+ * Separate from {@link DrainRunsResult.skipped} because the cause is
150
+ * different and so is what an operator should do about a lot of them: a
151
+ * skip means another drainer is holding runs right now, a stale entry
152
+ * means another drainer already FINISHED one. Empty on a pass with no
153
+ * park filter, which has nothing to re-check against.
154
+ */
155
+ readonly stale: readonly RunId[]
156
+ /** Runs whose `onRun` threw. */
157
+ readonly failed: readonly DrainFailure[]
158
+ /**
159
+ * Runs that finished but whose lease could not be handed back.
160
+ *
161
+ * Separate from {@link DrainRunsResult.failed} because it is a different
162
+ * fact with a different consequence: the work is done and the record is
163
+ * written; the run is merely unavailable to the next reader until the
164
+ * lease lapses. Reported rather than swallowed — a release that quietly
165
+ * did nothing is how a queue silently loses throughput.
166
+ */
167
+ readonly unreleased: readonly DrainFailure[]
168
+ /** Whether the pass stopped early because the signal aborted. */
169
+ readonly stopped: boolean
170
+ }
171
+
172
+ function refuse(code: NamzuErrorCode, message: string, details: Record<string, unknown>): never {
173
+ throw new NamzuError({ code, message, details })
174
+ }
175
+
176
+ function toMessage(err: unknown): string {
177
+ return err instanceof Error ? err.message : String(err)
178
+ }
179
+
180
+ /**
181
+ * Refuse a store that cannot do the whole job, BEFORE anything is listed.
182
+ *
183
+ * Checked up front rather than at the first call that needs each method, so
184
+ * that a store missing only `releaseRun` cannot resume half a queue and then
185
+ * discover it has no way to give the runs back. The optional-capability rule
186
+ * on `CheckpointStore` says a caller refuses rather than degrades; a drainer
187
+ * that degraded would be the worst instance of it, because "claimed by
188
+ * default" here means every worker proceeds on every run.
189
+ */
190
+ function assertDrainable(store: CheckpointStore): void {
191
+ const missing = (['listDurableRuns', 'claimRun', 'releaseRun'] as const).filter(
192
+ (m) => typeof store[m] !== 'function',
193
+ )
194
+ if (missing.length === 0) return
195
+ refuse(
196
+ 'capability_unavailable',
197
+ `drainRuns: the injected checkpoint store does not implement ${missing.map((m) => `\`${m}\``).join(', ')}, so it cannot arbitrate a queue. Refusing before anything is claimed rather than draining what it can — a drainer that proceeded without a claim would let two workers restore one checkpoint, both execute its tools and both write under one run id. Supply a store that implements all three (the built-in disk and in-memory stores do), or run a single writer per run.`,
198
+ { missing },
199
+ )
200
+ }
201
+
202
+ /**
203
+ * Take every unclaimed run under a scope, one bounded pass, and give each
204
+ * one back when its work returns.
205
+ *
206
+ * The shape is: list parked-and-unclaimed → claim → work → release in a
207
+ * `finally`. The `finally` is the part a host writes wrong: a worker that
208
+ * returns without releasing leaves the run stuck until the lease lapses,
209
+ * and a worker that releases only on success leaves a FAILED run stuck for
210
+ * the same duration — so a queue quietly loses its throughput to the runs
211
+ * that need retrying most.
212
+ *
213
+ * `claimed: false` is not a parameter. A drainer never wants work somebody
214
+ * else holds; that is what makes it a drainer rather than a listing. An
215
+ * expired claim counts as unheld, which is what makes a dead worker's runs
216
+ * recoverable at all.
217
+ *
218
+ * ## What "exactly once" does and does not mean here
219
+ *
220
+ * Two drainers never hold one run at the same time — that is the claim, and
221
+ * it is absolute. **Exactly-once over a whole pass is a weaker promise, and
222
+ * where it holds it comes from the FILTER, not from the claim.** A listing
223
+ * is a snapshot; between paging a row and claiming it, another drainer can
224
+ * finish that run and release it, and the claim then succeeds on work
225
+ * already done. So a claimed row is re-read against
226
+ * {@link DrainRunsParams.park} before any work starts, and one that no
227
+ * longer matches is given straight back as {@link DrainRunsResult.stale}.
228
+ * An inbox drain (`park: ['outstanding']`) whose work answers the park is
229
+ * therefore exactly-once, because doing the work is what removes the run
230
+ * from the queue.
231
+ *
232
+ * With NO park filter there is nothing to re-check, and two drainers can
233
+ * both process one run. That is not an omission: a checkpoint store holds no
234
+ * run STATUS by design — nothing in it distinguishes a run that finished
235
+ * from one that died — so "already done" is a fact only the host's own run
236
+ * records carry. A crash sweep intersects with those records inside
237
+ * `onRun`, which is the shape {@link DurableRunEntry} already prescribes.
238
+ *
239
+ * @throws NamzuError `capability_unavailable` when the store cannot list,
240
+ * claim or release — before any run is touched.
241
+ * @throws NamzuError `invalid_config` on a lease or concurrency that cannot
242
+ * mean what it says.
243
+ */
244
+ export async function drainRuns(params: DrainRunsParams): Promise<DrainRunsResult> {
245
+ const { store, scope, holder, ttlMs, onRun, park, signal, now } = params
246
+
247
+ assertDrainable(store)
248
+
249
+ if (holder.trim().length === 0) {
250
+ refuse(
251
+ 'invalid_config',
252
+ 'drainRuns: `holder` is empty. It is the only thing that distinguishes a renewal from a theft, so two drainers sharing one string take live claims from each other instantly. Use something per-process — a worker id, a pod name plus a pid.',
253
+ { holder },
254
+ )
255
+ }
256
+ if (!Number.isFinite(ttlMs) || ttlMs <= 0) {
257
+ refuse(
258
+ 'invalid_config',
259
+ `drainRuns: ttlMs must be a positive number of milliseconds, got ${String(ttlMs)}. A lease that expires immediately is a lease every worker can take at once, which is the condition a claim exists to prevent.`,
260
+ { ttlMs },
261
+ )
262
+ }
263
+ const maxConcurrent = params.maxConcurrent ?? 1
264
+ if (!Number.isInteger(maxConcurrent) || maxConcurrent < 1) {
265
+ refuse(
266
+ 'invalid_config',
267
+ `drainRuns: maxConcurrent must be a positive integer, got ${String(params.maxConcurrent)}. Zero would drain nothing while reporting a successful pass.`,
268
+ { maxConcurrent: params.maxConcurrent },
269
+ )
270
+ }
271
+ const pageSize = params.pageSize ?? DEFAULT_DRAIN_PAGE_SIZE
272
+
273
+ const drained: RunId[] = []
274
+ const skipped: RunId[] = []
275
+ const stale: RunId[] = []
276
+ const failed: DrainFailure[] = []
277
+ const unreleased: DrainFailure[] = []
278
+ let listed = 0
279
+ let stopped = false
280
+
281
+ const giveBack = async (entry: DurableRunEntry, fence: number): Promise<void> => {
282
+ try {
283
+ await releaseRun(store, entry, fence)
284
+ } catch (err) {
285
+ // Never rethrown: on the work path this runs inside a `finally`
286
+ // unwinding the caller's error, and replacing it would send the
287
+ // operator to debug the disk instead of the run.
288
+ unreleased.push({ runId: entry.runId, error: toMessage(err) })
289
+ }
290
+ }
291
+
292
+ /**
293
+ * Is this row still the row the listing described?
294
+ *
295
+ * A listing is a SNAPSHOT, and a claim taken against a stale snapshot is
296
+ * a claim on work somebody already did. The window is real and small:
297
+ * drainer B pages the queue, drainer A takes a run, finishes it, answers
298
+ * its park and releases — and B's claim then succeeds on a run that is no
299
+ * longer outstanding. Mutual exclusion cannot close that; only re-reading
300
+ * after the claim can, which is why this is here and not in the store.
301
+ *
302
+ * Only the park is re-checked, because it is the only predicate this loop
303
+ * was given. **Two drainers with no park filter can both process one
304
+ * run**, and no amount of claiming prevents it: a checkpoint store holds
305
+ * no run STATUS by design — see the note on {@link DurableRunEntry} — so
306
+ * "already done" is a fact only the host's own run records carry. A crash
307
+ * sweep intersects with those records inside `onRun`.
308
+ */
309
+ const stillMatches = async (entry: DurableRunEntry): Promise<boolean> => {
310
+ if (!park) return true
311
+ const fresh = summarizePark(await store.listCheckpoints(entry), now ?? Date.now())
312
+ return fresh !== undefined && park.includes(fresh.state)
313
+ }
314
+
315
+ /**
316
+ * One run: take it, work it, give it back.
317
+ *
318
+ * **No cancellation check here, and its absence is deliberate.** One was
319
+ * written, and a mutation test found nothing could kill it: the batch
320
+ * below dispatches with `.map(handle)`, which calls every handler
321
+ * synchronously before any of them awaits, so a signal that aborts during
322
+ * a batch cannot be observed at the top of a handler that has already
323
+ * been entered — and a signal that aborts BETWEEN batches is caught by
324
+ * the check in the loop, which runs first. A branch nothing can reach is
325
+ * a declaration nothing drives, so it is gone rather than covered by a
326
+ * test that would have proved nothing
327
+ * (`docs/conventions/declared-but-undriven.md`).
328
+ */
329
+ const handle = async (entry: DurableRunEntry): Promise<void> => {
330
+ const claim = await claimRun(store, entry, {
331
+ holder,
332
+ ttlMs,
333
+ ...(now !== undefined ? { now } : {}),
334
+ })
335
+ // `null` is not an error. Another worker got there first, which is the
336
+ // ordinary outcome of two readers on one queue.
337
+ if (!claim) {
338
+ skipped.push(entry.runId)
339
+ return
340
+ }
341
+ // Checked with the claim in hand rather than before taking it: only
342
+ // under the claim is the answer stable, because nobody else can change
343
+ // it while this drainer holds the run.
344
+ if (!(await stillMatches(entry))) {
345
+ stale.push(entry.runId)
346
+ await giveBack(entry, claim.fence)
347
+ return
348
+ }
349
+ try {
350
+ await onRun(entry, claim)
351
+ drained.push(entry.runId)
352
+ } catch (err) {
353
+ failed.push({ runId: entry.runId, error: toMessage(err) })
354
+ } finally {
355
+ await giveBack(entry, claim.fence)
356
+ }
357
+ }
358
+
359
+ let cursor: string | undefined
360
+ do {
361
+ if (signal?.aborted) {
362
+ stopped = true
363
+ break
364
+ }
365
+ const page = await listDurableRuns(store, scope, {
366
+ // Not a parameter. See the note above.
367
+ claimed: false,
368
+ ...(park ? { park } : {}),
369
+ limit: pageSize,
370
+ ...(cursor !== undefined ? { cursor } : {}),
371
+ ...(now !== undefined ? { now } : {}),
372
+ })
373
+ listed += page.entries.length
374
+
375
+ // Windowed rather than `Promise.all` over the page: the leases are taken
376
+ // as the work starts, so a page bigger than the pass can finish inside
377
+ // one TTL does not hand the tail of it to somebody else mid-flight.
378
+ for (let i = 0; i < page.entries.length; i += maxConcurrent) {
379
+ if (signal?.aborted) {
380
+ stopped = true
381
+ break
382
+ }
383
+ await Promise.all(page.entries.slice(i, i + maxConcurrent).map(handle))
384
+ }
385
+
386
+ // A drained run is released, so it is unclaimed again — but the cursor
387
+ // is a position in a total order and has already passed it, so the pass
388
+ // cannot see it twice and cannot fail to terminate.
389
+ cursor = stopped ? undefined : page.cursor
390
+ } while (cursor !== undefined)
391
+
392
+ return { listed, drained, skipped, stale, failed, unreleased, stopped }
393
+ }
package/src/run/index.ts CHANGED
@@ -5,5 +5,25 @@ export { RunDiskStore } from '../store/run/disk.js'
5
5
  export { createRunReporter } from './reporter.js'
6
6
  export type { RunReporter } from './reporter.js'
7
7
 
8
+ export { DEFAULT_DRAIN_PAGE_SIZE, drainRuns } from './drain.js'
9
+ export type { DrainFailure, DrainRun, DrainRunsParams, DrainRunsResult } from './drain.js'
10
+ export {
11
+ DEFAULT_GATE_MAX_RETRIES,
12
+ DEFAULT_GATE_OUTPUT_CHARS,
13
+ DEFAULT_GATE_TIMEOUT_MS,
14
+ clipOutput,
15
+ createCommandGate,
16
+ } from './command-gate.js'
17
+ export type { CommandGateOptions, GateExec } from './command-gate.js'
18
+ export {
19
+ FINGERPRINT_MAX_BYTES,
20
+ FINGERPRINT_TIMEOUT_MS,
21
+ fingerprintWorkspace,
22
+ } from './workspace-fingerprint.js'
23
+ export type { FingerprintExec, WorkspaceFingerprintOptions } from './workspace-fingerprint.js'
24
+
8
25
  export { checkLimitsDetailed, buildLimitConfig } from './LimitChecker.js'
9
26
  export type { LimitCheckerState, LimitCheckResult } from './LimitChecker.js'
27
+
28
+ export { RUN_MEMORY_TAG, createMemoryPromoter } from './memory-promoter.js'
29
+ export type { MemoryPromoterOptions } from './memory-promoter.js'
@@ -0,0 +1,155 @@
1
+ /**
2
+ * The default {@link PromoteMemory}: write what a run learned into a
3
+ * {@link MemoryStore}, or write nothing at all.
4
+ *
5
+ * `promoteMemory` is called once at settle with the compaction extractor's
6
+ * already-structured output — decisions, discoveries, user requirements,
7
+ * failures, environment facts — and **nothing shipped supplied the hook**.
8
+ * So the structure the compaction pass had spent tokens producing was
9
+ * serialized into one system message and dropped on the floor when the run
10
+ * ended, exactly as its own module comment says. This is the supplier, and
11
+ * it is mostly a filter: the hard part — extracting facts from a transcript
12
+ * — already happened.
13
+ *
14
+ * ## The filter, which is the only decision here
15
+ *
16
+ * **A run that learned nothing must leave nothing.** Not an empty record,
17
+ * not a record whose body says "no decisions" — nothing. A promoter that
18
+ * wrote a row per run would fill the store with the runs least worth
19
+ * remembering, and `search_memory` would then return them: the model reads
20
+ * that store on later runs, so noise here is not merely wasted disk, it is
21
+ * context spent on a run that did nothing.
22
+ *
23
+ * What counts as having learned something is the five KNOWLEDGE categories —
24
+ * decisions, discoveries, user requirements, failures, environment. Not
25
+ * `task`, which every run has because it is the prompt restated. Not
26
+ * `files`, which every run that opened anything has, and which says what was
27
+ * touched rather than what was learned. A run whose only trace is "it read
28
+ * six files" is the exact record this filter exists to refuse.
29
+ *
30
+ * ## What it does NOT do
31
+ *
32
+ * Deduplicate against what is already stored, merge with a previous run's
33
+ * record, or expire anything. Each is a policy with real trade-offs and a
34
+ * host that wants one owns it — `promoteMemory` is a callback precisely so
35
+ * that the runtime does not decide this. This is the obvious default, not
36
+ * the only possible one.
37
+ */
38
+
39
+ import type { MemoryStore } from '../types/memory/index.js'
40
+ import type { PromoteMemory, RunMemoryCandidate } from '../types/run/memory-promotion.js'
41
+
42
+ /**
43
+ * The categories that make a run worth remembering.
44
+ *
45
+ * Ordered as they are rendered. `userRequirements` first because it is the
46
+ * most durable of the five — a constraint the user stated outlives the run
47
+ * that heard it, whereas a discovery about a codebase expires when the
48
+ * codebase moves.
49
+ */
50
+ const KNOWLEDGE = [
51
+ ['userRequirements', 'What the user requires'],
52
+ ['decisions', 'Decisions'],
53
+ ['discoveries', 'Discoveries'],
54
+ ['failures', 'What did not work'],
55
+ ['environment', 'Environment'],
56
+ ] as const satisfies readonly (readonly [keyof RunMemoryCandidate, string])[]
57
+
58
+ /** Tag every record this promoter writes, so a host can find or prune them. */
59
+ export const RUN_MEMORY_TAG = 'run-memory'
60
+
61
+ export interface MemoryPromoterOptions {
62
+ /** Where records go. The same store `save_memory` writes through. */
63
+ readonly store: MemoryStore
64
+ /**
65
+ * Extra tags on every record, beyond {@link RUN_MEMORY_TAG}.
66
+ *
67
+ * A host running several agents against one store uses this to tell whose
68
+ * memory is whose; without it a later search cannot.
69
+ */
70
+ readonly tags?: readonly string[]
71
+ /**
72
+ * Cap on entries rendered per category. Defaults to 20.
73
+ *
74
+ * The extractor already caps its lists, and this is the second cap for
75
+ * the same reason the first exists: a record nobody will read is a record
76
+ * that costs context every time it is retrieved.
77
+ */
78
+ readonly maxPerCategory?: number
79
+ }
80
+
81
+ /** Everything the candidate knows, as `[heading, items]`, empties dropped. */
82
+ function knowledge(
83
+ candidate: RunMemoryCandidate,
84
+ cap: number,
85
+ ): readonly (readonly [string, readonly string[]])[] {
86
+ const out: (readonly [string, readonly string[]])[] = []
87
+ for (const [key, heading] of KNOWLEDGE) {
88
+ const items = candidate[key] as readonly string[]
89
+ if (items.length > 0) out.push([heading, items.slice(0, cap)])
90
+ }
91
+ return out
92
+ }
93
+
94
+ /** A one-line summary naming what kind of knowledge the record holds. */
95
+ function summarize(sections: readonly (readonly [string, readonly string[]])[]): string {
96
+ return sections.map(([heading, items]) => `${heading.toLowerCase()} (${items.length})`).join(', ')
97
+ }
98
+
99
+ function render(
100
+ candidate: RunMemoryCandidate,
101
+ sections: readonly (readonly [string, readonly string[]])[],
102
+ ): string {
103
+ const body = sections.map(
104
+ ([heading, items]) => `## ${heading}\n\n${items.map((i) => `- ${i}`).join('\n')}`,
105
+ )
106
+ // The eviction counts, when there are any. Carried rather than hidden for
107
+ // the reason the candidate carries them: somebody reading this record
108
+ // should know they are reading a truncated account of the run, not a
109
+ // complete one.
110
+ const evicted = Object.entries(candidate.evicted).filter(([, n]) => n > 0)
111
+ if (evicted.length > 0) {
112
+ body.push(
113
+ `## Dropped during the run\n\n${evicted
114
+ .map(([category, n]) => `- ${category}: ${n} entr${n === 1 ? 'y' : 'ies'} evicted`)
115
+ .join('\n')}`,
116
+ )
117
+ }
118
+ if (candidate.files.length > 0) {
119
+ body.push(`## Files touched\n\n${candidate.files.map((f) => `- ${f}`).join('\n')}`)
120
+ }
121
+ return `# ${candidate.task}\n\n${body.join('\n\n')}\n`
122
+ }
123
+
124
+ /**
125
+ * Build a promoter that writes one record per run that learned something.
126
+ *
127
+ * Never throws out to the runtime — but it does not swallow either: the
128
+ * runtime already catches and logs a promoter's failure at settle, and
129
+ * catching here as well would hide a broken store from the one place that
130
+ * reports it.
131
+ */
132
+ export function createMemoryPromoter(options: MemoryPromoterOptions): PromoteMemory {
133
+ const cap = options.maxPerCategory ?? 20
134
+ const tags = [RUN_MEMORY_TAG, ...(options.tags ?? [])]
135
+
136
+ return async (candidate: RunMemoryCandidate): Promise<void> => {
137
+ const sections = knowledge(candidate, cap)
138
+ // Nothing learned, nothing written. Not an empty record: a store full
139
+ // of rows describing runs that discovered nothing is a store whose
140
+ // search results are mostly noise, and the model reads that store.
141
+ if (sections.length === 0) return
142
+
143
+ await options.store.create({
144
+ title: candidate.task.trim() || `Run ${candidate.runId}`,
145
+ summary: summarize(sections),
146
+ content: render(candidate, sections),
147
+ tags,
148
+ format: 'markdown',
149
+ // The run id, so a record can be traced back to the run that formed
150
+ // it. Evidence rather than decoration: without it a surprising
151
+ // memory cannot be checked against what actually happened.
152
+ metadata: { runId: candidate.runId, source: RUN_MEMORY_TAG },
153
+ })
154
+ }
155
+ }