@yielded/agent-storage-memory 0.1.0-beta.189 → 0.1.0-beta.190

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.
@@ -1,4 +1,4 @@
1
- import { t as MemoryThreadStoreKernel } from "./MemoryThreadStoreKernel-Dy0PRmUy.mjs";
1
+ import { t as MemoryThreadStoreKernel } from "./MemoryThreadStoreKernel-a2vrXxZZ.mjs";
2
2
  import * as Layer from "effect/Layer";
3
3
  import { MessageDeliveryError, MessageDeliveryStore, MessageDeliveryStoreLimits } from "@yielded/agent/message-delivery";
4
4
  declare namespace MemoryMessageDeliveryStore_d_exports {
@@ -359,7 +359,7 @@ const memoryMessageDeliveryStoreLayer = (limits = defaultMessageDeliveryStoreLim
359
359
  ownerThreadId: threadId,
360
360
  messageId
361
361
  }));
362
- return text === void 0 ? Effect.succeed(void 0) : transferDecode(text);
362
+ return text === void 0 ? Effect.as(Effect.void, void 0) : transferDecode(text);
363
363
  },
364
364
  snapshot: (threadId) => {
365
365
  const counts = MutableRef.get(state.ref).counts.get(threadId);
@@ -379,7 +379,7 @@ const memoryMessageDeliveryStoreLayer = (limits = defaultMessageDeliveryStoreLim
379
379
  const messageId = keys[after === void 0 ? 0 : position(keys, after) + Number(keys[position(keys, after)] === after)];
380
380
  const record = messageId === void 0 ? void 0 : yield* transferDecode(current.records.get(messageDeliveryKeyString({
381
381
  ownerThreadId: threadId,
382
- messageId: Schema.decodeSync(MessageDeliveryKey.fields.messageId)(messageId)
382
+ messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(messageId).pipe(Effect.orDie)
383
383
  })) ?? "");
384
384
  return {
385
385
  facts: {
@@ -411,7 +411,7 @@ const memoryMessageDeliveryStoreLayer = (limits = defaultMessageDeliveryStoreLim
411
411
  ownerThreadId: threadId,
412
412
  messageId
413
413
  }));
414
- return text === void 0 ? Effect.succeed(void 0) : transferDecode(text);
414
+ return text === void 0 ? Effect.as(Effect.void, void 0) : transferDecode(text);
415
415
  },
416
416
  stage: Effect.fnUntraced(function* (page) {
417
417
  for (const record of page.archive.deliveries) {
@@ -436,7 +436,7 @@ const memoryMessageDeliveryStoreLayer = (limits = defaultMessageDeliveryStoreLim
436
436
  commitInto(staged, record, text, false);
437
437
  }
438
438
  }),
439
- prepareCommit: Effect.fnUntraced(function* () {
439
+ prepareCommit: Effect.gen(function* () {
440
440
  const reader = yield* ThreadDeliveryImportReader;
441
441
  const read = (messageId) => {
442
442
  const text = staged.records.get(messageDeliveryKeyString({
@@ -554,7 +554,7 @@ const memoryMessageDeliveryStoreLayer = (limits = defaultMessageDeliveryStoreLim
554
554
  while (at < keys.length && items.length < input.limit) {
555
555
  const text = current.records.get(messageDeliveryKeyString({
556
556
  ownerThreadId: input.ownerThreadId,
557
- messageId: Schema.decodeSync(MessageDeliveryKey.fields.messageId)(keys[at])
557
+ messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(keys[at]).pipe(Effect.orDie)
558
558
  }));
559
559
  if (text === void 0) return yield* MessageDeliveryError.make({
560
560
  reason: "corrupt",
@@ -1 +1 @@
1
- {"version":3,"file":"MemoryMessageDeliveryStore.mjs","names":[],"sources":["../src/MemoryMessageDeliveryStore.ts"],"sourcesContent":["import { ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n applyMessageDeliveryChange,\n defaultMessageDeliveryStoreLimits,\n MessageDeliveryChange,\n MessageDeliveryError,\n MessageDeliveryFailpoint,\n MessageDeliveryKey,\n MessageDeliveryPageRequest,\n MessageDeliveryRecord,\n MessageDeliveryStore,\n MessageDeliveryStoreLimits,\n messageDeliveryDeadline,\n messageDeliveryKeyString,\n messageDeliveryUsesCapacity,\n peerMessageRetentionDeadline,\n isWorkerUpdateDelivery,\n messageDeliveryCapacity,\n sameMessageDeliveryIdentity,\n validateMessageDelivery,\n} from \"@yielded/agent/message-delivery\";\nimport { PreparedInput } from \"@yielded/agent/prepared-input-admission\";\nimport { ScheduleInstant } from \"@yielded/agent/schedule\";\nimport { validateCanonicalSettlement } from \"@yielded/agent/settlement-publisher\";\nimport {\n Settlement,\n settlementFailureFromRecord,\n submissionSettlementRecordId,\n submissionSettlementId,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n ThreadDeliveryImportReader,\n ThreadImportRejected,\n invalidThreadArchive,\n} from \"@yielded/agent/thread-import\";\nimport { ThreadStoreError, makeTransferFactCheck } from \"@yielded/agent/thread-store\";\nimport { workId, type ThreadWorkEntry } from \"@yielded/agent/thread-work\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { MemoryThreadStoreKernel } from \"./internal/MemoryThreadStoreKernel.ts\";\nimport { boundedWorkSelection } from \"./internal/WorkSelection.ts\";\n\nconst codec = Schema.fromJsonString(MessageDeliveryRecord);\nconst deliveryFitsTransfer = makeTransferFactCheck(MessageDeliveryRecord);\n\nconst checkTransfer = (record: MessageDeliveryRecord) =>\n deliveryFitsTransfer(record.key.ownerThreadId, { ...record, leaseUntilMillis: null })\n ? Effect.void\n : Effect.fail(\n MessageDeliveryError.make({ reason: \"capacity\", operation: \"transfer-page-bytes\" }),\n );\n\nconst decode = (text: string) =>\n Schema.decodeEffect(codec)(text).pipe(\n Effect.mapError(() => MessageDeliveryError.make({ reason: \"corrupt\", operation: \"decode\" })),\n );\n\nconst Scan = Schema.Struct({\n nowMillis: ScheduleInstant,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ownerThreadId: Schema.optionalKey(ThreadId),\n});\n\nconst position = (keys: ReadonlyArray<string>, key: string) => {\n let low = 0;\n let high = keys.length;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n\n if (keys[mid] < key) low = mid + 1;\n else high = mid;\n }\n\n return low;\n};\n\nconst retainKey = (keys: Array<string>, key: string) => {\n const at = position(keys, key);\n\n if (keys[at] !== key) keys.splice(at, 0, key);\n};\n\nconst removeKey = (keys: Array<string>, key: string) => {\n const at = position(keys, key);\n\n if (keys[at] === key) keys.splice(at, 1);\n};\n\n/** First deadline after the request time; retained evidence also supports clock rollback. */\nconst deadlinePosition = (deadlines: ReadonlyArray<number>, nowMillis: number) => {\n let low = 0;\n let high = deadlines.length;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n\n if (deadlines[mid] <= nowMillis) low = mid + 1;\n else high = mid;\n }\n\n return low;\n};\n\nconst backend = () => ({\n records: new Map<string, string>(),\n work: new Map<string, ThreadWorkEntry>(),\n ordered: new Map<string, Array<string>>(),\n pending: new Map<ThreadId, Set<MessageDeliveryKey[\"messageId\"]>>(),\n retainedPeers: new Map<ThreadId, Array<number>>(),\n counts: new Map<ThreadId, { retained: number; ordinary: number; update: number; peer: number }>(),\n metadata: new Map<\n string,\n {\n update: boolean;\n pending: boolean;\n peer: boolean;\n peerRetentionDeadline: number | null;\n deadlineKey?: string;\n importVisit?: \"visiting\" | \"verified\";\n }\n >(),\n deadlines: new Map<string, { readonly key: MessageDeliveryKey; readonly deadline: number }>(),\n deadlineKeys: new Array<string>(),\n ownerDeadlineKeys: new Map<ThreadId, Array<string>>(),\n});\n\nconst ownerKey = (id: ThreadId) => JSON.stringify([id]);\n\ninterface PreparedDeliveryInsert {\n readonly record: MessageDeliveryRecord;\n readonly encoded: string;\n}\n\nconst keysFor = (current: ReturnType<typeof backend>, key: string) => {\n let keys = current.ordered.get(key);\n\n if (keys === undefined) current.ordered.set(key, (keys = []));\n\n return keys;\n};\n\nexport interface MemoryMessageDeliveryStoreOptions {\n /** UTF-8 bound on the complete stored record, including a processed Settlement. */\n readonly maxStoredValueBytes?: number;\n}\n\n/**\n * Pair with MemoryThreadStoreLive to publish canonical messages and their deliveries atomically.\n * Export/import preserves every retained delivery obligation.\n * Each retained value and live partition is bounded; completed deduplication evidence is never evicted.\n */\nexport const memoryMessageDeliveryStoreLayer = (\n limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,\n options: MemoryMessageDeliveryStoreOptions = {},\n): Layer.Layer<MessageDeliveryStore, MessageDeliveryError, MemoryThreadStoreKernel> =>\n Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const journal = yield* MemoryThreadStoreKernel;\n const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, \"limits\");\n\n const maxStoredValueBytes = yield* validateMessageDelivery(\n Schema.Int.check(Schema.isGreaterThan(0)),\n options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,\n \"stored-value-limit\",\n );\n\n const state = yield* Ref.make(backend());\n\n yield* journal.registerWorkOwner(\"deliveries\", {\n threads: (request) =>\n Ref.get(state).pipe(\n Effect.map((current) => {\n const candidates = boundedWorkSelection<ThreadId>(\n request.limit,\n (id) => id,\n request.afterThreadId,\n );\n\n for (const threadId of current.pending.keys()) candidates.add(threadId);\n const threadIds = candidates.values;\n\n const afterThreadId =\n threadIds.length === request.limit ? threadIds.at(-1) : undefined;\n\n return {\n threadIds,\n ...(afterThreadId === undefined ? {} : { afterThreadId }),\n };\n }),\n ),\n page: Effect.fnUntraced(function* (threadId, after, limit) {\n const current = yield* Ref.get(state);\n\n const candidates = boundedWorkSelection<MessageDeliveryKey[\"messageId\"]>(\n limit + 1,\n (id) => id,\n after,\n );\n\n for (const id of current.pending.get(threadId) ?? []) candidates.add(id);\n const ids = candidates.values;\n\n const entries: Array<ThreadWorkEntry> = [];\n\n for (const messageId of ids.slice(0, limit)) {\n const key = messageDeliveryKeyString({ ownerThreadId: threadId, messageId });\n const entry = current.work.get(key);\n\n if (entry === undefined || !current.records.has(key))\n return yield* ThreadStoreError.make({\n operation: \"delivery work\",\n message: \"Pending delivery index is incomplete or corrupt\",\n });\n entries.push(entry);\n }\n const next = ids.length > limit ? ids[limit - 1] : undefined;\n\n return { entries, ...(next === undefined ? {} : { after: next }) };\n }),\n });\n\n const commitInto = (\n current: ReturnType<typeof backend>,\n record: MessageDeliveryRecord,\n encoded: string,\n publish: boolean,\n ) => {\n const key = messageDeliveryKeyString(record.key);\n const owner = record.key.ownerThreadId;\n const old = current.metadata.get(key);\n const update = isWorkerUpdateDelivery(record);\n const pending = messageDeliveryUsesCapacity(record);\n\n const peer =\n record.envelope.messageAdmission !== undefined &&\n \"peerName\" in record.envelope.messageAdmission;\n\n let counts = current.counts.get(owner);\n\n if (counts === undefined)\n current.counts.set(owner, (counts = { retained: 0, ordinary: 0, update: 0, peer: 0 }));\n if (old === undefined) counts.retained++;\n if (old?.pending) {\n if (old.update) counts.update--;\n else counts.ordinary--;\n if (old.peer) counts.peer--;\n }\n if (pending) {\n if (update) counts.update++;\n else counts.ordinary++;\n if (peer) counts.peer++;\n }\n const retentionDeadline = peerMessageRetentionDeadline(record);\n const previousDeadline = old?.peerRetentionDeadline ?? null;\n\n if (previousDeadline !== retentionDeadline) {\n let retained = current.retainedPeers.get(owner);\n\n if (retained === undefined) current.retainedPeers.set(owner, (retained = []));\n if (previousDeadline !== null)\n retained.splice(deadlinePosition(retained, previousDeadline) - 1, 1);\n if (retentionDeadline !== null)\n retained.splice(deadlinePosition(retained, retentionDeadline), 0, retentionDeadline);\n if (retained.length === 0) current.retainedPeers.delete(owner);\n }\n let owned = current.pending.get(owner);\n\n if (owned === undefined) current.pending.set(owner, (owned = new Set()));\n if (pending) owned.add(record.key.messageId);\n else owned.delete(record.key.messageId);\n if (owned.size === 0) current.pending.delete(owner);\n retainKey(keysFor(current, ownerKey(owner)), record.key.messageId);\n const admission = record.envelope.workerAdmission;\n\n if (admission !== undefined) {\n const worker = admission.origin.worker;\n\n if (record.key.messageId === admission.origin.firstMessageId)\n retainKey(\n keysFor(current, JSON.stringify([owner, worker.delegationId, worker.targetAgentId])),\n record.key.messageId,\n );\n const inputs = keysFor(current, JSON.stringify([owner, worker.threadId]));\n\n if (\n (record.status === \"pending\" || record.status === \"parked\") &&\n record.receipt === null\n )\n retainKey(inputs, record.key.messageId);\n else removeKey(inputs, record.key.messageId);\n }\n const deadline = messageDeliveryDeadline(record);\n let ownerDeadlines = current.ownerDeadlineKeys.get(owner);\n\n if (ownerDeadlines === undefined)\n current.ownerDeadlineKeys.set(owner, (ownerDeadlines = []));\n if (old?.deadlineKey !== undefined) {\n current.deadlines.delete(old.deadlineKey);\n removeKey(current.deadlineKeys, old.deadlineKey);\n removeKey(ownerDeadlines, old.deadlineKey);\n }\n\n const deadlineKey =\n deadline === null ? undefined : `${String(deadline).padStart(16, \"0\")}:${key}`;\n\n if (deadlineKey !== undefined && deadline !== null) {\n current.deadlines.set(deadlineKey, { key: record.key, deadline });\n retainKey(current.deadlineKeys, deadlineKey);\n retainKey(ownerDeadlines, deadlineKey);\n }\n current.metadata.set(key, {\n update,\n pending,\n peer,\n peerRetentionDeadline: retentionDeadline,\n ...(deadlineKey === undefined ? {} : { deadlineKey }),\n });\n if (pending)\n current.work.set(key, {\n id: workId(\"delivery\", record.key.messageId),\n owner: { _tag: \"Delivery\", messageId: record.key.messageId },\n partition: update ? \"update\" : \"ordinary\",\n stateReference: {\n _tag: \"Delivery\",\n messageId: record.key.messageId,\n version: record.version,\n },\n state: record.status === \"pending\" ? \"ready\" : \"waiting\",\n ...(record.status === \"parked\"\n ? { wait: \"parked\" as const }\n : record.receipt !== null\n ? { wait: \"destination\" as const }\n : {}),\n ...(deadline === null ? {} : { notBeforeMillis: deadline }),\n ...(record.receipt === null\n ? {}\n : {\n receiptId: record.receipt.receiptId,\n queueSequence: record.receipt.queueSequence,\n }),\n });\n else current.work.delete(key);\n current.records.set(key, encoded);\n if (publish) journal.initializeWork(owner);\n };\n\n const commit = (record: MessageDeliveryRecord, encoded: string) =>\n Effect.sync(() => commitInto(MutableRef.get(state.ref), record, encoded, true));\n\n const failpoint = yield* MessageDeliveryFailpoint;\n\n const encode = Effect.fnUntraced(function* (record: MessageDeliveryRecord) {\n const text = yield* Schema.encodeEffect(codec)(record).pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"corrupt\", operation: \"encode\" }),\n ),\n );\n\n if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"stored-value-bytes\",\n });\n }\n\n return text;\n });\n\n const prepareInsert = Effect.fnUntraced(function* (record: MessageDeliveryRecord) {\n const encoded = yield* encode(record);\n const input = yield* decode(encoded);\n\n if (\n input.version !== 1 ||\n input.status !== \"pending\" ||\n input.leaseUntilMillis !== null ||\n input.retry.attempts !== 0 ||\n input.retry.generation !== 0 ||\n input.retry.automaticAttempts !== 0 ||\n input.retry.nextAttemptAtMillis !== input.createdAtMillis ||\n input.retry.lastAttemptAtMillis !== null ||\n input.retry.lastFailure !== null ||\n input.deadlineAtMillis !== input.initialDeadlineAtMillis\n )\n return yield* MessageDeliveryError.make({\n reason: \"validation\",\n operation: \"insert-state\",\n });\n if (\n new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >\n config.maxEnvelopeBytes\n )\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"envelope-bytes\",\n });\n\n return { record: input, encoded };\n });\n\n /** The caller holds the journal gate through staging and synchronous publication. */\n const stageInsert = Effect.fnUntraced(function* (\n inputs: ReadonlyArray<PreparedDeliveryInsert>,\n ) {\n const current = yield* Ref.get(state);\n const additions = new Map<string, PreparedDeliveryInsert>();\n const counts = new Map<ThreadId, { ordinary: number; update: number }>();\n const retained: Array<MessageDeliveryRecord> = [];\n\n for (const prepared of inputs) {\n const input = prepared.record;\n const owner = input.key.ownerThreadId;\n\n yield* journal\n .checkThreadCapacity(owner)\n .pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"capacity\", operation: \"Thread capacity\" }),\n ),\n );\n const key = messageDeliveryKeyString(input.key);\n const existingText = current.records.get(key);\n\n const existing =\n additions.get(key)?.record ??\n (existingText === undefined ? undefined : yield* decode(existingText));\n\n if (existing !== undefined) {\n if (!sameMessageDeliveryIdentity(existing, input))\n return yield* MessageDeliveryError.make({\n reason: \"conflict\",\n operation: \"insert\",\n });\n retained.push(existing);\n continue;\n }\n\n yield* checkTransfer(input);\n const update = isWorkerUpdateDelivery(input);\n const partition = update ? \"update\" : \"ordinary\";\n const capacity = messageDeliveryCapacity(config, update);\n let count = counts.get(owner);\n\n if (count === undefined) {\n const previous = current.counts.get(owner);\n\n count = { ordinary: previous?.ordinary ?? 0, update: previous?.update ?? 0 };\n counts.set(owner, count);\n }\n if (count[partition] >= capacity.pending)\n return yield* MessageDeliveryError.make({ reason: \"capacity\", operation: \"insert\" });\n count[partition]++;\n additions.set(key, prepared);\n retained.push(input);\n }\n\n return {\n records: retained,\n commit: () => {\n for (const { record, encoded } of additions.values())\n commitInto(current, record, encoded, true);\n },\n };\n });\n\n yield* journal.registerDeliveryWriter((records) =>\n Effect.forEach(records, prepareInsert).pipe(\n Effect.flatMap(stageInsert),\n Effect.map((staged) => staged.commit),\n ),\n );\n\n const insert: MessageDeliveryStore[\"Service\"][\"insert\"] = Effect.fnUntraced(\n function* (record) {\n const prepared = yield* prepareInsert(record);\n\n yield* failpoint.hit(\"message-delivery:insert:before\");\n\n const inserted = yield* journal.withMutation(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const staged = yield* stageInsert([prepared]);\n\n yield* Effect.sync(staged.commit);\n\n return staged.records[0];\n }),\n ),\n );\n\n yield* failpoint.hit(\"message-delivery:insert:after\");\n\n return yield* decode(yield* encode(inserted));\n },\n );\n\n const get: MessageDeliveryStore[\"Service\"][\"get\"] = Effect.fnUntraced(function* (key) {\n const input = yield* validateMessageDelivery(MessageDeliveryKey, key, \"get\");\n const text = (yield* Ref.get(state)).records.get(messageDeliveryKeyString(input));\n\n return text === undefined ? null : yield* decode(text);\n });\n\n const change: MessageDeliveryStore[\"Service\"][\"change\"] = Effect.fnUntraced(\n function* (key, change) {\n const input = yield* validateMessageDelivery(MessageDeliveryChange, change, \"change\");\n const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, \"change\");\n const point = `message-delivery:${input._tag.toLowerCase()}`;\n\n yield* failpoint.hit(`${point}:before`);\n\n const changed = yield* journal.withMutation(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const existing = yield* get(decodedKey);\n\n if (existing === null)\n return yield* MessageDeliveryError.make({\n reason: \"not-found\",\n operation: \"change\",\n });\n const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input));\n\n if (next === existing) return existing;\n yield* checkTransfer(next);\n const encoded = yield* encode(next);\n\n yield* commit(next, encoded);\n\n return next;\n }),\n ),\n );\n\n yield* failpoint.hit(`${point}:after`);\n\n return yield* decode(yield* encode(changed));\n },\n );\n\n const transferDecode = (text: string) =>\n decode(text).pipe(\n Effect.mapError(() =>\n ThreadStoreError.make({\n operation: \"delivery transfer\",\n message: \"Invalid retained delivery wire\",\n }),\n ),\n );\n\n yield* journal.registerDeliveryTransfer({\n record: (threadId, messageId) => {\n const text = MutableRef.get(state.ref).records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined ? Effect.succeed(undefined) : transferDecode(text);\n },\n snapshot: (threadId) => {\n const counts = MutableRef.get(state.ref).counts.get(threadId);\n\n return {\n idle: (MutableRef.get(state.ref).pending.get(threadId)?.size ?? 0) === 0,\n deliveries: counts?.retained ?? 0,\n };\n },\n peerCount: (threadId, nowMillis, limit) => {\n const current = MutableRef.get(state.ref);\n const retained = current.retainedPeers.get(threadId) ?? [];\n\n return Math.min(\n (current.counts.get(threadId)?.peer ?? 0) +\n retained.length -\n deadlinePosition(retained, nowMillis),\n limit,\n );\n },\n facts: Effect.fnUntraced(function* (threadId, after) {\n const current = MutableRef.get(state.ref);\n const keys = current.ordered.get(ownerKey(threadId)) ?? [];\n\n const at =\n after === undefined\n ? 0\n : position(keys, after) + Number(keys[position(keys, after)] === after);\n\n const messageId = keys[at];\n\n const record =\n messageId === undefined\n ? undefined\n : yield* transferDecode(\n current.records.get(\n messageDeliveryKeyString({\n ownerThreadId: threadId,\n messageId: Schema.decodeSync(MessageDeliveryKey.fields.messageId)(messageId),\n }),\n ) ?? \"\",\n );\n\n return {\n facts: {\n admissions: [],\n commands: { aborts: [], approvals: [], resolutions: [] },\n deliveries:\n record === undefined\n ? []\n : [MessageDeliveryRecord.make({ ...record, leaseUntilMillis: null })],\n },\n after: messageId ?? after ?? \"\",\n };\n }),\n startImport: Effect.fnUntraced(function* (threadId) {\n const current = MutableRef.get(state.ref);\n\n if ((current.counts.get(threadId)?.retained ?? 0) > 0)\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"target-not-empty\",\n message: \"Destination Thread owns retained deliveries\",\n });\n const staged = backend();\n\n return {\n record: (messageId) => {\n const text = staged.records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined ? Effect.succeed(undefined) : transferDecode(text);\n },\n stage: Effect.fnUntraced(function* (page) {\n for (const record of page.archive.deliveries) {\n const key = messageDeliveryKeyString(record.key);\n\n if (staged.records.has(key) || current.records.has(key))\n return yield* invalidThreadArchive(\"Duplicate retained delivery\", threadId);\n\n const text = yield* encode(record).pipe(\n Effect.mapError(() =>\n ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Delivery wire exceeds destination stored-value bound\",\n }),\n ),\n );\n\n if (\n new TextEncoder().encode(\n JSON.stringify(\n yield* Schema.encodeEffect(PreparedInput)(record.envelope).pipe(\n Effect.mapError(() =>\n invalidThreadArchive(\"Invalid delivery envelope\", threadId),\n ),\n ),\n ),\n ).byteLength > config.maxEnvelopeBytes\n )\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Delivery envelope exceeds destination bound\",\n });\n const counts = staged.counts.get(threadId);\n\n if (\n messageDeliveryUsesCapacity(record) &&\n (isWorkerUpdateDelivery(record)\n ? (counts?.update ?? 0)\n : (counts?.ordinary ?? 0)) >=\n messageDeliveryCapacity(config, isWorkerUpdateDelivery(record)).pending\n )\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Pending delivery capacity exceeded\",\n });\n commitInto(staged, record, text, false);\n }\n }),\n prepareCommit: Effect.fnUntraced(function* () {\n const reader = yield* ThreadDeliveryImportReader;\n\n const read = (messageId: MessageDeliveryKey[\"messageId\"]) => {\n const text = staged.records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined\n ? Effect.fail(invalidThreadArchive(\"Missing delivery predecessor\", threadId))\n : transferDecode(text);\n };\n\n const visit = (messageId: MessageDeliveryKey[\"messageId\"]) => {\n const metadata = staged.metadata.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return metadata === undefined\n ? Effect.fail(\n invalidThreadArchive(\"Missing delivery predecessor metadata\", threadId),\n )\n : Effect.succeed(metadata);\n };\n\n const verifyPredecessors = Effect.fnUntraced(function* (\n start: MessageDeliveryKey[\"messageId\"],\n ) {\n let cursor: MessageDeliveryKey[\"messageId\"] | undefined = start;\n\n while (cursor !== undefined) {\n const metadata = yield* visit(cursor);\n\n if (metadata.importVisit === \"verified\") break;\n if (metadata.importVisit === \"visiting\")\n return yield* invalidThreadArchive(\"Delivery predecessor cycle\", threadId);\n metadata.importVisit = \"visiting\";\n const record: MessageDeliveryRecord = yield* read(cursor);\n\n if (\n record.predecessor !== undefined &&\n (yield* read(record.predecessor)).createdAtMillis > record.createdAtMillis\n )\n return yield* invalidThreadArchive(\n \"Delivery predecessor has a later boundary\",\n threadId,\n );\n cursor = record.predecessor;\n }\n cursor = start;\n while (cursor !== undefined) {\n const metadata = yield* visit(cursor);\n\n if (metadata.importVisit === \"verified\") break;\n metadata.importVisit = \"verified\";\n cursor = (yield* read(cursor)).predecessor;\n }\n });\n\n for (const text of staged.records.values()) {\n const d = yield* transferDecode(text);\n\n yield* verifyPredecessors(d.key.messageId);\n if (d.receipt !== null) {\n if (\n d.settlement !== null &&\n d.settlement.settlementId !== submissionSettlementId(d.receipt.submissionId)\n )\n return yield* invalidThreadArchive(\n \"Delivery settlement identity is not canonical\",\n threadId,\n );\n const foreign = d.receipt.threadId !== threadId;\n\n if (foreign && d.status !== \"processed\")\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-obligations\",\n message: \"Live foreign delivery receipt cannot be restored\",\n });\n\n const destination = yield* reader.admission(\n d.receipt.threadId,\n d.receipt.submissionId,\n );\n\n // A closed foreign delivery retains frozen evidence, not the receiver's execution authority.\n if (destination === undefined) {\n if (foreign && d.status === \"processed\") continue;\n\n return yield* invalidThreadArchive(\n \"Destination delivery receipt evidence is missing\",\n threadId,\n );\n }\n\n const expected = PreparedInput.make({\n schemaVersion: 1,\n authorization: d.envelope.authorization,\n threadId: destination.threadId,\n deliveryPrincipal: destination.principal,\n admissionKey: destination.idempotencyKey,\n agentId: destination.agentId,\n definitions: destination.agentDigests,\n input: destination.inputPayload,\n inputDigest: destination.inputDigest,\n ...(destination.admissionGroup === undefined\n ? {}\n : { admissionGroup: destination.admissionGroup }),\n ...(destination.admissionFence === undefined\n ? {}\n : { admissionFence: destination.admissionFence }),\n ...(destination.workerAdmission === undefined\n ? {}\n : { workerAdmission: destination.workerAdmission }),\n ...(destination.messageAdmission === undefined\n ? {}\n : { messageAdmission: destination.messageAdmission }),\n });\n\n if (\n d.receipt.receiptId !== destination.receiptId ||\n d.receipt.queueSequence !== destination.queueSequence ||\n !Schema.toEquivalence(PreparedInput)(d.envelope, expected)\n )\n return yield* invalidThreadArchive(\n \"Delivery envelope differs from destination admission\",\n threadId,\n );\n if (d.settlement !== null) {\n const record = yield* reader.record(\n destination.threadId,\n submissionSettlementRecordId(destination.submissionId),\n );\n\n if (record === undefined) {\n if (foreign) continue;\n\n return yield* invalidThreadArchive(\n \"Processed delivery has no destination settlement\",\n threadId,\n );\n }\n\n const settled = yield* validateCanonicalSettlement(record, destination).pipe(\n Effect.mapError(() =>\n invalidThreadArchive(\"Invalid destination settlement\", threadId),\n ),\n );\n\n const failure = settlementFailureFromRecord(record);\n\n const expected = Settlement.make({\n submissionId: settled.submissionId,\n receiptId: settled.receiptId,\n settlementId: settled.settlementId,\n outcome: settled.outcome,\n settledAt: d.settlement.settledAt,\n ...(failure === undefined ? {} : { failure }),\n ...(d.settlement.runDisposition === undefined ||\n settled.runDisposition === undefined\n ? {}\n : { runDisposition: settled.runDisposition }),\n ...(d.settlement.usageSummary === undefined ||\n settled.usageSummary === undefined\n ? {}\n : { usageSummary: settled.usageSummary }),\n });\n\n if (!Schema.toEquivalence(Settlement)(d.settlement, expected))\n return yield* invalidThreadArchive(\n \"Delivery settlement differs from destination evidence\",\n threadId,\n );\n }\n }\n }\n\n return () => {\n for (const text of staged.records.values())\n commitInto(current, Schema.decodeSync(codec)(text), text, true);\n };\n }),\n };\n }),\n });\n\n return MessageDeliveryStore.of({\n limits: config,\n maxStoredValueBytes,\n insert,\n get,\n change,\n list: Effect.fnUntraced(function* (request) {\n const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, \"list\");\n\n const current = yield* Ref.get(state);\n\n const workerKey =\n input.workerStarts !== undefined\n ? JSON.stringify([\n input.ownerThreadId,\n input.workerStarts.delegationId,\n input.workerStarts.targetAgentId,\n ])\n : input.pendingWorker !== undefined\n ? JSON.stringify([input.ownerThreadId, input.pendingWorker])\n : undefined;\n\n const keys =\n workerKey === undefined\n ? input.pendingOnly\n ? Array.from(current.pending.get(input.ownerThreadId) ?? []).sort()\n : (current.ordered.get(ownerKey(input.ownerThreadId)) ?? [])\n : (current.ordered.get(workerKey) ?? []);\n\n const start =\n input.after === undefined\n ? 0\n : position(keys, input.after) +\n Number(keys[position(keys, input.after)] === input.after);\n\n const items: Array<MessageDeliveryRecord> = [];\n let bytes = 0;\n let at = start;\n\n while (at < keys.length && items.length < input.limit) {\n const text = current.records.get(\n messageDeliveryKeyString({\n ownerThreadId: input.ownerThreadId,\n messageId: Schema.decodeSync(MessageDeliveryKey.fields.messageId)(keys[at]),\n }),\n );\n\n if (text === undefined)\n return yield* MessageDeliveryError.make({\n reason: \"corrupt\",\n operation: \"list locator\",\n });\n const size = new TextEncoder().encode(text).byteLength;\n\n if (size > 32 * 1024 * 1024)\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"list byte bound\",\n });\n if (bytes + size > 32 * 1024 * 1024) break;\n items.push(yield* decode(text));\n bytes += size;\n at++;\n }\n\n return {\n items,\n next: at < keys.length ? (items.at(-1)?.key.messageId ?? null) : null,\n };\n }),\n due: Effect.fnUntraced(function* (nowMillis, limit, ownerThreadId) {\n const input = yield* validateMessageDelivery(\n Scan,\n { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },\n \"due\",\n );\n\n const current = MutableRef.get(state.ref);\n\n const keys =\n input.ownerThreadId === undefined\n ? current.deadlineKeys\n : (current.ownerDeadlineKeys.get(input.ownerThreadId) ?? []);\n\n const selected: Array<MessageDeliveryKey> = [];\n\n for (const key of keys) {\n const row = current.deadlines.get(key);\n\n if (row === undefined)\n return yield* MessageDeliveryError.make({\n reason: \"corrupt\",\n operation: \"deadline index\",\n });\n if (row.deadline > input.nowMillis || selected.length === input.limit) break;\n selected.push(row.key);\n }\n\n return selected;\n }),\n nextDeadline: Effect.fnUntraced(function* (ownerThreadId) {\n if (ownerThreadId !== undefined)\n yield* validateMessageDelivery(ThreadId, ownerThreadId, \"nextDeadline\");\n const current = MutableRef.get(state.ref);\n\n const first = (\n ownerThreadId === undefined\n ? current.deadlineKeys\n : current.ownerDeadlineKeys.get(ownerThreadId)\n )?.[0];\n\n return first === undefined ? null : (current.deadlines.get(first)?.deadline ?? null);\n }),\n });\n }),\n );\n\nexport const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,QAAQ,OAAO,eAAe,qBAAqB;AACzD,MAAM,uBAAuB,sBAAsB,qBAAqB;AAExE,MAAM,iBAAiB,WACrB,qBAAqB,OAAO,IAAI,eAAe;CAAE,GAAG;CAAQ,kBAAkB;AAAK,CAAC,IAChF,OAA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nE;EACF,CAAC;EACD,KAAK,OAAO,WAAW,WAAW,WAAW,OAAO,eAAe;GACjE,MAAM,QAAQ,OAAO,wBACnB,MACA;IAAE;IAAW;IAAO,GAAI,kBAAkB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc;GAAG,GAC9E,KACF;GAEA,MAAM,UAAU,WAAW,IAAI,MAAM,GAAG;GAExC,MAAM,OACJ,MAAM,kBAAkB,KAAA,IACpB,QAAQ,eACP,QAAQ,kBAAkB,IAAI,MAAM,aAAa,KAAK,CAAC;GAE9D,MAAM,WAAsC,CAAC;GAE7C,KAAK,MAAM,OAAO,MAAM;IACtB,MAAM,MAAM,QAAQ,UAAU,IAAI,GAAG;IAErC,IAAI,QAAQ,KAAA,GACV,OAAO,OAAO,qBAAqB,KAAK;KACtC,QAAQ;KACR,WAAW;IACb,CAAC;IACH,IAAI,IAAI,WAAW,MAAM,aAAa,SAAS,WAAW,MAAM,OAAO;IACvE,SAAS,KAAK,IAAI,GAAG;GACvB;GAEA,OAAO;EACT,CAAC;EACD,cAAc,OAAO,WAAW,WAAW,eAAe;GACxD,IAAI,kBAAkB,KAAA,GACpB,OAAO,wBAAwB,UAAU,eAAe,cAAc;GACxE,MAAM,UAAU,WAAW,IAAI,MAAM,GAAG;GAExC,MAAM,SACJ,kBAAkB,KAAA,IACd,QAAQ,eACR,QAAQ,kBAAkB,IAAI,aAAa,EAAA,GAC7C;GAEJ,OAAO,UAAU,KAAA,IAAY,OAAQ,QAAQ,UAAU,IAAI,KAAK,CAAC,EAAE,YAAY;EACjF,CAAC;CACH,CAAC;AACH,CAAC,CACH;AAEF,MAAa,iCAAiC,gCAAgC"}
1
+ {"version":3,"file":"MemoryMessageDeliveryStore.mjs","names":[],"sources":["../src/MemoryMessageDeliveryStore.ts"],"sourcesContent":["import { ThreadId } from \"@yielded/agent/identifiers\";\nimport {\n applyMessageDeliveryChange,\n defaultMessageDeliveryStoreLimits,\n MessageDeliveryChange,\n MessageDeliveryError,\n MessageDeliveryFailpoint,\n MessageDeliveryKey,\n MessageDeliveryPageRequest,\n MessageDeliveryRecord,\n MessageDeliveryStore,\n MessageDeliveryStoreLimits,\n messageDeliveryDeadline,\n messageDeliveryKeyString,\n messageDeliveryUsesCapacity,\n peerMessageRetentionDeadline,\n isWorkerUpdateDelivery,\n messageDeliveryCapacity,\n sameMessageDeliveryIdentity,\n validateMessageDelivery,\n} from \"@yielded/agent/message-delivery\";\nimport { PreparedInput } from \"@yielded/agent/prepared-input-admission\";\nimport { ScheduleInstant } from \"@yielded/agent/schedule\";\nimport { validateCanonicalSettlement } from \"@yielded/agent/settlement-publisher\";\nimport {\n Settlement,\n settlementFailureFromRecord,\n submissionSettlementRecordId,\n submissionSettlementId,\n} from \"@yielded/agent/submission-ledger\";\nimport {\n ThreadDeliveryImportReader,\n ThreadImportRejected,\n invalidThreadArchive,\n} from \"@yielded/agent/thread-import\";\nimport { ThreadStoreError, makeTransferFactCheck } from \"@yielded/agent/thread-store\";\nimport { workId, type ThreadWorkEntry } from \"@yielded/agent/thread-work\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as MutableRef from \"effect/MutableRef\";\nimport * as Ref from \"effect/Ref\";\nimport * as Schema from \"effect/Schema\";\n\nimport { MemoryThreadStoreKernel } from \"./internal/MemoryThreadStoreKernel.ts\";\nimport { boundedWorkSelection } from \"./internal/WorkSelection.ts\";\n\nconst codec = Schema.fromJsonString(MessageDeliveryRecord);\nconst deliveryFitsTransfer = makeTransferFactCheck(MessageDeliveryRecord);\n\nconst checkTransfer = (record: MessageDeliveryRecord) =>\n deliveryFitsTransfer(record.key.ownerThreadId, { ...record, leaseUntilMillis: null })\n ? Effect.void\n : Effect.fail(\n MessageDeliveryError.make({ reason: \"capacity\", operation: \"transfer-page-bytes\" }),\n );\n\nconst decode = (text: string) =>\n Schema.decodeEffect(codec)(text).pipe(\n Effect.mapError(() => MessageDeliveryError.make({ reason: \"corrupt\", operation: \"decode\" })),\n );\n\nconst Scan = Schema.Struct({\n nowMillis: ScheduleInstant,\n limit: Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(100)),\n ownerThreadId: Schema.optionalKey(ThreadId),\n});\n\nconst position = (keys: ReadonlyArray<string>, key: string) => {\n let low = 0;\n let high = keys.length;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n\n if (keys[mid] < key) low = mid + 1;\n else high = mid;\n }\n\n return low;\n};\n\nconst retainKey = (keys: Array<string>, key: string) => {\n const at = position(keys, key);\n\n if (keys[at] !== key) keys.splice(at, 0, key);\n};\n\nconst removeKey = (keys: Array<string>, key: string) => {\n const at = position(keys, key);\n\n if (keys[at] === key) keys.splice(at, 1);\n};\n\n/** First deadline after the request time; retained evidence also supports clock rollback. */\nconst deadlinePosition = (deadlines: ReadonlyArray<number>, nowMillis: number) => {\n let low = 0;\n let high = deadlines.length;\n\n while (low < high) {\n const mid = Math.floor((low + high) / 2);\n\n if (deadlines[mid] <= nowMillis) low = mid + 1;\n else high = mid;\n }\n\n return low;\n};\n\nconst backend = () => ({\n records: new Map<string, string>(),\n work: new Map<string, ThreadWorkEntry>(),\n ordered: new Map<string, Array<string>>(),\n pending: new Map<ThreadId, Set<MessageDeliveryKey[\"messageId\"]>>(),\n retainedPeers: new Map<ThreadId, Array<number>>(),\n counts: new Map<ThreadId, { retained: number; ordinary: number; update: number; peer: number }>(),\n metadata: new Map<\n string,\n {\n update: boolean;\n pending: boolean;\n peer: boolean;\n peerRetentionDeadline: number | null;\n deadlineKey?: string;\n importVisit?: \"visiting\" | \"verified\";\n }\n >(),\n deadlines: new Map<string, { readonly key: MessageDeliveryKey; readonly deadline: number }>(),\n deadlineKeys: new Array<string>(),\n ownerDeadlineKeys: new Map<ThreadId, Array<string>>(),\n});\n\nconst ownerKey = (id: ThreadId) => JSON.stringify([id]);\n\ninterface PreparedDeliveryInsert {\n readonly record: MessageDeliveryRecord;\n readonly encoded: string;\n}\n\nconst keysFor = (current: ReturnType<typeof backend>, key: string) => {\n let keys = current.ordered.get(key);\n\n if (keys === undefined) current.ordered.set(key, (keys = []));\n\n return keys;\n};\n\nexport interface MemoryMessageDeliveryStoreOptions {\n /** UTF-8 bound on the complete stored record, including a processed Settlement. */\n readonly maxStoredValueBytes?: number;\n}\n\n/**\n * Pair with MemoryThreadStoreLive to publish canonical messages and their deliveries atomically.\n * Export/import preserves every retained delivery obligation.\n * Each retained value and live partition is bounded; completed deduplication evidence is never evicted.\n */\nexport const memoryMessageDeliveryStoreLayer = (\n limits: MessageDeliveryStoreLimits = defaultMessageDeliveryStoreLimits,\n options: MemoryMessageDeliveryStoreOptions = {},\n): Layer.Layer<MessageDeliveryStore, MessageDeliveryError, MemoryThreadStoreKernel> =>\n Layer.effect(\n MessageDeliveryStore,\n Effect.gen(function* () {\n const journal = yield* MemoryThreadStoreKernel;\n const config = yield* validateMessageDelivery(MessageDeliveryStoreLimits, limits, \"limits\");\n\n const maxStoredValueBytes = yield* validateMessageDelivery(\n Schema.Int.check(Schema.isGreaterThan(0)),\n options.maxStoredValueBytes ?? 16 * 1_024 * 1_024,\n \"stored-value-limit\",\n );\n\n const state = yield* Ref.make(backend());\n\n yield* journal.registerWorkOwner(\"deliveries\", {\n threads: (request) =>\n Ref.get(state).pipe(\n Effect.map((current) => {\n const candidates = boundedWorkSelection<ThreadId>(\n request.limit,\n (id) => id,\n request.afterThreadId,\n );\n\n for (const threadId of current.pending.keys()) candidates.add(threadId);\n const threadIds = candidates.values;\n\n const afterThreadId =\n threadIds.length === request.limit ? threadIds.at(-1) : undefined;\n\n return {\n threadIds,\n ...(afterThreadId === undefined ? {} : { afterThreadId }),\n };\n }),\n ),\n page: Effect.fnUntraced(function* (threadId, after, limit) {\n const current = yield* Ref.get(state);\n\n const candidates = boundedWorkSelection<MessageDeliveryKey[\"messageId\"]>(\n limit + 1,\n (id) => id,\n after,\n );\n\n for (const id of current.pending.get(threadId) ?? []) candidates.add(id);\n const ids = candidates.values;\n\n const entries: Array<ThreadWorkEntry> = [];\n\n for (const messageId of ids.slice(0, limit)) {\n const key = messageDeliveryKeyString({ ownerThreadId: threadId, messageId });\n const entry = current.work.get(key);\n\n if (entry === undefined || !current.records.has(key))\n return yield* ThreadStoreError.make({\n operation: \"delivery work\",\n message: \"Pending delivery index is incomplete or corrupt\",\n });\n entries.push(entry);\n }\n const next = ids.length > limit ? ids[limit - 1] : undefined;\n\n return { entries, ...(next === undefined ? {} : { after: next }) };\n }),\n });\n\n const commitInto = (\n current: ReturnType<typeof backend>,\n record: MessageDeliveryRecord,\n encoded: string,\n publish: boolean,\n ) => {\n const key = messageDeliveryKeyString(record.key);\n const owner = record.key.ownerThreadId;\n const old = current.metadata.get(key);\n const update = isWorkerUpdateDelivery(record);\n const pending = messageDeliveryUsesCapacity(record);\n\n const peer =\n record.envelope.messageAdmission !== undefined &&\n \"peerName\" in record.envelope.messageAdmission;\n\n let counts = current.counts.get(owner);\n\n if (counts === undefined)\n current.counts.set(owner, (counts = { retained: 0, ordinary: 0, update: 0, peer: 0 }));\n if (old === undefined) counts.retained++;\n if (old?.pending) {\n if (old.update) counts.update--;\n else counts.ordinary--;\n if (old.peer) counts.peer--;\n }\n if (pending) {\n if (update) counts.update++;\n else counts.ordinary++;\n if (peer) counts.peer++;\n }\n const retentionDeadline = peerMessageRetentionDeadline(record);\n const previousDeadline = old?.peerRetentionDeadline ?? null;\n\n if (previousDeadline !== retentionDeadline) {\n let retained = current.retainedPeers.get(owner);\n\n if (retained === undefined) current.retainedPeers.set(owner, (retained = []));\n if (previousDeadline !== null)\n retained.splice(deadlinePosition(retained, previousDeadline) - 1, 1);\n if (retentionDeadline !== null)\n retained.splice(deadlinePosition(retained, retentionDeadline), 0, retentionDeadline);\n if (retained.length === 0) current.retainedPeers.delete(owner);\n }\n let owned = current.pending.get(owner);\n\n if (owned === undefined) current.pending.set(owner, (owned = new Set()));\n if (pending) owned.add(record.key.messageId);\n else owned.delete(record.key.messageId);\n if (owned.size === 0) current.pending.delete(owner);\n retainKey(keysFor(current, ownerKey(owner)), record.key.messageId);\n const admission = record.envelope.workerAdmission;\n\n if (admission !== undefined) {\n const worker = admission.origin.worker;\n\n if (record.key.messageId === admission.origin.firstMessageId)\n retainKey(\n keysFor(current, JSON.stringify([owner, worker.delegationId, worker.targetAgentId])),\n record.key.messageId,\n );\n const inputs = keysFor(current, JSON.stringify([owner, worker.threadId]));\n\n if (\n (record.status === \"pending\" || record.status === \"parked\") &&\n record.receipt === null\n )\n retainKey(inputs, record.key.messageId);\n else removeKey(inputs, record.key.messageId);\n }\n const deadline = messageDeliveryDeadline(record);\n let ownerDeadlines = current.ownerDeadlineKeys.get(owner);\n\n if (ownerDeadlines === undefined)\n current.ownerDeadlineKeys.set(owner, (ownerDeadlines = []));\n if (old?.deadlineKey !== undefined) {\n current.deadlines.delete(old.deadlineKey);\n removeKey(current.deadlineKeys, old.deadlineKey);\n removeKey(ownerDeadlines, old.deadlineKey);\n }\n\n const deadlineKey =\n deadline === null ? undefined : `${String(deadline).padStart(16, \"0\")}:${key}`;\n\n if (deadlineKey !== undefined && deadline !== null) {\n current.deadlines.set(deadlineKey, { key: record.key, deadline });\n retainKey(current.deadlineKeys, deadlineKey);\n retainKey(ownerDeadlines, deadlineKey);\n }\n current.metadata.set(key, {\n update,\n pending,\n peer,\n peerRetentionDeadline: retentionDeadline,\n ...(deadlineKey === undefined ? {} : { deadlineKey }),\n });\n if (pending)\n current.work.set(key, {\n id: workId(\"delivery\", record.key.messageId),\n owner: { _tag: \"Delivery\", messageId: record.key.messageId },\n partition: update ? \"update\" : \"ordinary\",\n stateReference: {\n _tag: \"Delivery\",\n messageId: record.key.messageId,\n version: record.version,\n },\n state: record.status === \"pending\" ? \"ready\" : \"waiting\",\n ...(record.status === \"parked\"\n ? { wait: \"parked\" as const }\n : record.receipt !== null\n ? { wait: \"destination\" as const }\n : {}),\n ...(deadline === null ? {} : { notBeforeMillis: deadline }),\n ...(record.receipt === null\n ? {}\n : {\n receiptId: record.receipt.receiptId,\n queueSequence: record.receipt.queueSequence,\n }),\n });\n else current.work.delete(key);\n current.records.set(key, encoded);\n if (publish) journal.initializeWork(owner);\n };\n\n const commit = (record: MessageDeliveryRecord, encoded: string) =>\n Effect.sync(() => commitInto(MutableRef.get(state.ref), record, encoded, true));\n\n const failpoint = yield* MessageDeliveryFailpoint;\n\n const encode = Effect.fnUntraced(function* (record: MessageDeliveryRecord) {\n const text = yield* Schema.encodeEffect(codec)(record).pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"corrupt\", operation: \"encode\" }),\n ),\n );\n\n if (new TextEncoder().encode(text).byteLength > maxStoredValueBytes) {\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"stored-value-bytes\",\n });\n }\n\n return text;\n });\n\n const prepareInsert = Effect.fnUntraced(function* (record: MessageDeliveryRecord) {\n const encoded = yield* encode(record);\n const input = yield* decode(encoded);\n\n if (\n input.version !== 1 ||\n input.status !== \"pending\" ||\n input.leaseUntilMillis !== null ||\n input.retry.attempts !== 0 ||\n input.retry.generation !== 0 ||\n input.retry.automaticAttempts !== 0 ||\n input.retry.nextAttemptAtMillis !== input.createdAtMillis ||\n input.retry.lastAttemptAtMillis !== null ||\n input.retry.lastFailure !== null ||\n input.deadlineAtMillis !== input.initialDeadlineAtMillis\n )\n return yield* MessageDeliveryError.make({\n reason: \"validation\",\n operation: \"insert-state\",\n });\n if (\n new TextEncoder().encode(JSON.stringify(input.envelope)).byteLength >\n config.maxEnvelopeBytes\n )\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"envelope-bytes\",\n });\n\n return { record: input, encoded };\n });\n\n /** The caller holds the journal gate through staging and synchronous publication. */\n const stageInsert = Effect.fnUntraced(function* (\n inputs: ReadonlyArray<PreparedDeliveryInsert>,\n ) {\n const current = yield* Ref.get(state);\n const additions = new Map<string, PreparedDeliveryInsert>();\n const counts = new Map<ThreadId, { ordinary: number; update: number }>();\n const retained: Array<MessageDeliveryRecord> = [];\n\n for (const prepared of inputs) {\n const input = prepared.record;\n const owner = input.key.ownerThreadId;\n\n yield* journal\n .checkThreadCapacity(owner)\n .pipe(\n Effect.mapError(() =>\n MessageDeliveryError.make({ reason: \"capacity\", operation: \"Thread capacity\" }),\n ),\n );\n const key = messageDeliveryKeyString(input.key);\n const existingText = current.records.get(key);\n\n const existing =\n additions.get(key)?.record ??\n (existingText === undefined ? undefined : yield* decode(existingText));\n\n if (existing !== undefined) {\n if (!sameMessageDeliveryIdentity(existing, input))\n return yield* MessageDeliveryError.make({\n reason: \"conflict\",\n operation: \"insert\",\n });\n retained.push(existing);\n continue;\n }\n\n yield* checkTransfer(input);\n const update = isWorkerUpdateDelivery(input);\n const partition = update ? \"update\" : \"ordinary\";\n const capacity = messageDeliveryCapacity(config, update);\n let count = counts.get(owner);\n\n if (count === undefined) {\n const previous = current.counts.get(owner);\n\n count = { ordinary: previous?.ordinary ?? 0, update: previous?.update ?? 0 };\n counts.set(owner, count);\n }\n if (count[partition] >= capacity.pending)\n return yield* MessageDeliveryError.make({ reason: \"capacity\", operation: \"insert\" });\n count[partition]++;\n additions.set(key, prepared);\n retained.push(input);\n }\n\n return {\n records: retained,\n commit: () => {\n for (const { record, encoded } of additions.values())\n commitInto(current, record, encoded, true);\n },\n };\n });\n\n yield* journal.registerDeliveryWriter((records) =>\n Effect.forEach(records, prepareInsert).pipe(\n Effect.flatMap(stageInsert),\n Effect.map((staged) => staged.commit),\n ),\n );\n\n const insert: MessageDeliveryStore[\"Service\"][\"insert\"] = Effect.fnUntraced(\n function* (record) {\n const prepared = yield* prepareInsert(record);\n\n yield* failpoint.hit(\"message-delivery:insert:before\");\n\n const inserted = yield* journal.withMutation(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const staged = yield* stageInsert([prepared]);\n\n yield* Effect.sync(staged.commit);\n\n return staged.records[0];\n }),\n ),\n );\n\n yield* failpoint.hit(\"message-delivery:insert:after\");\n\n return yield* decode(yield* encode(inserted));\n },\n );\n\n const get: MessageDeliveryStore[\"Service\"][\"get\"] = Effect.fnUntraced(function* (key) {\n const input = yield* validateMessageDelivery(MessageDeliveryKey, key, \"get\");\n const text = (yield* Ref.get(state)).records.get(messageDeliveryKeyString(input));\n\n return text === undefined ? null : yield* decode(text);\n });\n\n const change: MessageDeliveryStore[\"Service\"][\"change\"] = Effect.fnUntraced(\n function* (key, change) {\n const input = yield* validateMessageDelivery(MessageDeliveryChange, change, \"change\");\n const decodedKey = yield* validateMessageDelivery(MessageDeliveryKey, key, \"change\");\n const point = `message-delivery:${input._tag.toLowerCase()}`;\n\n yield* failpoint.hit(`${point}:before`);\n\n const changed = yield* journal.withMutation(\n Effect.uninterruptible(\n Effect.gen(function* () {\n const existing = yield* get(decodedKey);\n\n if (existing === null)\n return yield* MessageDeliveryError.make({\n reason: \"not-found\",\n operation: \"change\",\n });\n const next = yield* Effect.fromResult(applyMessageDeliveryChange(existing, input));\n\n if (next === existing) return existing;\n yield* checkTransfer(next);\n const encoded = yield* encode(next);\n\n yield* commit(next, encoded);\n\n return next;\n }),\n ),\n );\n\n yield* failpoint.hit(`${point}:after`);\n\n return yield* decode(yield* encode(changed));\n },\n );\n\n const transferDecode = (text: string) =>\n decode(text).pipe(\n Effect.mapError(() =>\n ThreadStoreError.make({\n operation: \"delivery transfer\",\n message: \"Invalid retained delivery wire\",\n }),\n ),\n );\n\n yield* journal.registerDeliveryTransfer({\n record: (threadId, messageId) => {\n const text = MutableRef.get(state.ref).records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined ? Effect.as(Effect.void, undefined) : transferDecode(text);\n },\n snapshot: (threadId) => {\n const counts = MutableRef.get(state.ref).counts.get(threadId);\n\n return {\n idle: (MutableRef.get(state.ref).pending.get(threadId)?.size ?? 0) === 0,\n deliveries: counts?.retained ?? 0,\n };\n },\n peerCount: (threadId, nowMillis, limit) => {\n const current = MutableRef.get(state.ref);\n const retained = current.retainedPeers.get(threadId) ?? [];\n\n return Math.min(\n (current.counts.get(threadId)?.peer ?? 0) +\n retained.length -\n deadlinePosition(retained, nowMillis),\n limit,\n );\n },\n facts: Effect.fnUntraced(function* (threadId, after) {\n const current = MutableRef.get(state.ref);\n const keys = current.ordered.get(ownerKey(threadId)) ?? [];\n\n const at =\n after === undefined\n ? 0\n : position(keys, after) + Number(keys[position(keys, after)] === after);\n\n const messageId = keys[at];\n\n const record =\n messageId === undefined\n ? undefined\n : yield* transferDecode(\n current.records.get(\n messageDeliveryKeyString({\n ownerThreadId: threadId,\n messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(\n messageId,\n ).pipe(Effect.orDie),\n }),\n ) ?? \"\",\n );\n\n return {\n facts: {\n admissions: [],\n commands: { aborts: [], approvals: [], resolutions: [] },\n deliveries:\n record === undefined\n ? []\n : [MessageDeliveryRecord.make({ ...record, leaseUntilMillis: null })],\n },\n after: messageId ?? after ?? \"\",\n };\n }),\n startImport: Effect.fnUntraced(function* (threadId) {\n const current = MutableRef.get(state.ref);\n\n if ((current.counts.get(threadId)?.retained ?? 0) > 0)\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"target-not-empty\",\n message: \"Destination Thread owns retained deliveries\",\n });\n const staged = backend();\n\n return {\n record: (messageId) => {\n const text = staged.records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined ? Effect.as(Effect.void, undefined) : transferDecode(text);\n },\n stage: Effect.fnUntraced(function* (page) {\n for (const record of page.archive.deliveries) {\n const key = messageDeliveryKeyString(record.key);\n\n if (staged.records.has(key) || current.records.has(key))\n return yield* invalidThreadArchive(\"Duplicate retained delivery\", threadId);\n\n const text = yield* encode(record).pipe(\n Effect.mapError(() =>\n ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Delivery wire exceeds destination stored-value bound\",\n }),\n ),\n );\n\n if (\n new TextEncoder().encode(\n JSON.stringify(\n yield* Schema.encodeEffect(PreparedInput)(record.envelope).pipe(\n Effect.mapError(() =>\n invalidThreadArchive(\"Invalid delivery envelope\", threadId),\n ),\n ),\n ),\n ).byteLength > config.maxEnvelopeBytes\n )\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Delivery envelope exceeds destination bound\",\n });\n const counts = staged.counts.get(threadId);\n\n if (\n messageDeliveryUsesCapacity(record) &&\n (isWorkerUpdateDelivery(record)\n ? (counts?.update ?? 0)\n : (counts?.ordinary ?? 0)) >=\n messageDeliveryCapacity(config, isWorkerUpdateDelivery(record)).pending\n )\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-capacity\",\n message: \"Pending delivery capacity exceeded\",\n });\n commitInto(staged, record, text, false);\n }\n }),\n prepareCommit: Effect.gen(function* () {\n const reader = yield* ThreadDeliveryImportReader;\n\n const read = (messageId: MessageDeliveryKey[\"messageId\"]) => {\n const text = staged.records.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return text === undefined\n ? Effect.fail(invalidThreadArchive(\"Missing delivery predecessor\", threadId))\n : transferDecode(text);\n };\n\n const visit = (messageId: MessageDeliveryKey[\"messageId\"]) => {\n const metadata = staged.metadata.get(\n messageDeliveryKeyString({ ownerThreadId: threadId, messageId }),\n );\n\n return metadata === undefined\n ? Effect.fail(\n invalidThreadArchive(\"Missing delivery predecessor metadata\", threadId),\n )\n : Effect.succeed(metadata);\n };\n\n const verifyPredecessors = Effect.fnUntraced(function* (\n start: MessageDeliveryKey[\"messageId\"],\n ) {\n let cursor: MessageDeliveryKey[\"messageId\"] | undefined = start;\n\n while (cursor !== undefined) {\n const metadata = yield* visit(cursor);\n\n if (metadata.importVisit === \"verified\") break;\n if (metadata.importVisit === \"visiting\")\n return yield* invalidThreadArchive(\"Delivery predecessor cycle\", threadId);\n metadata.importVisit = \"visiting\";\n const record: MessageDeliveryRecord = yield* read(cursor);\n\n if (\n record.predecessor !== undefined &&\n (yield* read(record.predecessor)).createdAtMillis > record.createdAtMillis\n )\n return yield* invalidThreadArchive(\n \"Delivery predecessor has a later boundary\",\n threadId,\n );\n cursor = record.predecessor;\n }\n cursor = start;\n while (cursor !== undefined) {\n const metadata = yield* visit(cursor);\n\n if (metadata.importVisit === \"verified\") break;\n metadata.importVisit = \"verified\";\n cursor = (yield* read(cursor)).predecessor;\n }\n });\n\n for (const text of staged.records.values()) {\n const d = yield* transferDecode(text);\n\n yield* verifyPredecessors(d.key.messageId);\n if (d.receipt !== null) {\n if (\n d.settlement !== null &&\n d.settlement.settlementId !== submissionSettlementId(d.receipt.submissionId)\n )\n return yield* invalidThreadArchive(\n \"Delivery settlement identity is not canonical\",\n threadId,\n );\n const foreign = d.receipt.threadId !== threadId;\n\n if (foreign && d.status !== \"processed\")\n return yield* ThreadImportRejected.make({\n threadId,\n reason: \"unsupported-obligations\",\n message: \"Live foreign delivery receipt cannot be restored\",\n });\n\n const destination = yield* reader.admission(\n d.receipt.threadId,\n d.receipt.submissionId,\n );\n\n // A closed foreign delivery retains frozen evidence, not the receiver's execution authority.\n if (destination === undefined) {\n if (foreign && d.status === \"processed\") continue;\n\n return yield* invalidThreadArchive(\n \"Destination delivery receipt evidence is missing\",\n threadId,\n );\n }\n\n const expected = PreparedInput.make({\n schemaVersion: 1,\n authorization: d.envelope.authorization,\n threadId: destination.threadId,\n deliveryPrincipal: destination.principal,\n admissionKey: destination.idempotencyKey,\n agentId: destination.agentId,\n definitions: destination.agentDigests,\n input: destination.inputPayload,\n inputDigest: destination.inputDigest,\n ...(destination.admissionGroup === undefined\n ? {}\n : { admissionGroup: destination.admissionGroup }),\n ...(destination.admissionFence === undefined\n ? {}\n : { admissionFence: destination.admissionFence }),\n ...(destination.workerAdmission === undefined\n ? {}\n : { workerAdmission: destination.workerAdmission }),\n ...(destination.messageAdmission === undefined\n ? {}\n : { messageAdmission: destination.messageAdmission }),\n });\n\n if (\n d.receipt.receiptId !== destination.receiptId ||\n d.receipt.queueSequence !== destination.queueSequence ||\n !Schema.toEquivalence(PreparedInput)(d.envelope, expected)\n )\n return yield* invalidThreadArchive(\n \"Delivery envelope differs from destination admission\",\n threadId,\n );\n if (d.settlement !== null) {\n const record = yield* reader.record(\n destination.threadId,\n submissionSettlementRecordId(destination.submissionId),\n );\n\n if (record === undefined) {\n if (foreign) continue;\n\n return yield* invalidThreadArchive(\n \"Processed delivery has no destination settlement\",\n threadId,\n );\n }\n\n const settled = yield* validateCanonicalSettlement(record, destination).pipe(\n Effect.mapError(() =>\n invalidThreadArchive(\"Invalid destination settlement\", threadId),\n ),\n );\n\n const failure = settlementFailureFromRecord(record);\n\n const expected = Settlement.make({\n submissionId: settled.submissionId,\n receiptId: settled.receiptId,\n settlementId: settled.settlementId,\n outcome: settled.outcome,\n settledAt: d.settlement.settledAt,\n ...(failure === undefined ? {} : { failure }),\n ...(d.settlement.runDisposition === undefined ||\n settled.runDisposition === undefined\n ? {}\n : { runDisposition: settled.runDisposition }),\n ...(d.settlement.usageSummary === undefined ||\n settled.usageSummary === undefined\n ? {}\n : { usageSummary: settled.usageSummary }),\n });\n\n if (!Schema.toEquivalence(Settlement)(d.settlement, expected))\n return yield* invalidThreadArchive(\n \"Delivery settlement differs from destination evidence\",\n threadId,\n );\n }\n }\n }\n\n return () => {\n for (const text of staged.records.values())\n commitInto(current, Schema.decodeSync(codec)(text), text, true);\n };\n }),\n };\n }),\n });\n\n return MessageDeliveryStore.of({\n limits: config,\n maxStoredValueBytes,\n insert,\n get,\n change,\n list: Effect.fnUntraced(function* (request) {\n const input = yield* validateMessageDelivery(MessageDeliveryPageRequest, request, \"list\");\n\n const current = yield* Ref.get(state);\n\n const workerKey =\n input.workerStarts !== undefined\n ? JSON.stringify([\n input.ownerThreadId,\n input.workerStarts.delegationId,\n input.workerStarts.targetAgentId,\n ])\n : input.pendingWorker !== undefined\n ? JSON.stringify([input.ownerThreadId, input.pendingWorker])\n : undefined;\n\n const keys =\n workerKey === undefined\n ? input.pendingOnly\n ? Array.from(current.pending.get(input.ownerThreadId) ?? []).sort()\n : (current.ordered.get(ownerKey(input.ownerThreadId)) ?? [])\n : (current.ordered.get(workerKey) ?? []);\n\n const start =\n input.after === undefined\n ? 0\n : position(keys, input.after) +\n Number(keys[position(keys, input.after)] === input.after);\n\n const items: Array<MessageDeliveryRecord> = [];\n let bytes = 0;\n let at = start;\n\n while (at < keys.length && items.length < input.limit) {\n const text = current.records.get(\n messageDeliveryKeyString({\n ownerThreadId: input.ownerThreadId,\n messageId: yield* Schema.decodeEffect(MessageDeliveryKey.fields.messageId)(\n keys[at],\n ).pipe(Effect.orDie),\n }),\n );\n\n if (text === undefined)\n return yield* MessageDeliveryError.make({\n reason: \"corrupt\",\n operation: \"list locator\",\n });\n const size = new TextEncoder().encode(text).byteLength;\n\n if (size > 32 * 1024 * 1024)\n return yield* MessageDeliveryError.make({\n reason: \"capacity\",\n operation: \"list byte bound\",\n });\n if (bytes + size > 32 * 1024 * 1024) break;\n items.push(yield* decode(text));\n bytes += size;\n at++;\n }\n\n return {\n items,\n next: at < keys.length ? (items.at(-1)?.key.messageId ?? null) : null,\n };\n }),\n due: Effect.fnUntraced(function* (nowMillis, limit, ownerThreadId) {\n const input = yield* validateMessageDelivery(\n Scan,\n { nowMillis, limit, ...(ownerThreadId === undefined ? {} : { ownerThreadId }) },\n \"due\",\n );\n\n const current = MutableRef.get(state.ref);\n\n const keys =\n input.ownerThreadId === undefined\n ? current.deadlineKeys\n : (current.ownerDeadlineKeys.get(input.ownerThreadId) ?? []);\n\n const selected: Array<MessageDeliveryKey> = [];\n\n for (const key of keys) {\n const row = current.deadlines.get(key);\n\n if (row === undefined)\n return yield* MessageDeliveryError.make({\n reason: \"corrupt\",\n operation: \"deadline index\",\n });\n if (row.deadline > input.nowMillis || selected.length === input.limit) break;\n selected.push(row.key);\n }\n\n return selected;\n }),\n nextDeadline: Effect.fnUntraced(function* (ownerThreadId) {\n if (ownerThreadId !== undefined)\n yield* validateMessageDelivery(ThreadId, ownerThreadId, \"nextDeadline\");\n const current = MutableRef.get(state.ref);\n\n const first = (\n ownerThreadId === undefined\n ? current.deadlineKeys\n : current.ownerDeadlineKeys.get(ownerThreadId)\n )?.[0];\n\n return first === undefined ? null : (current.deadlines.get(first)?.deadline ?? null);\n }),\n });\n }),\n );\n\nexport const MemoryMessageDeliveryStoreLive = memoryMessageDeliveryStoreLayer();\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA8CA,MAAM,QAAQ,OAAO,eAAe,qBAAqB;AACzD,MAAM,uBAAuB,sBAAsB,qBAAqB;AAExE,MAAM,iBAAiB,WACrB,qBAAqB,OAAO,IAAI,eAAe;CAAE,GAAG;CAAQ,kBAAkB;AAAK,CAAC,IAChF,OAAO,OACP,OAAO,KACL,qBAAqB,KAAK;CAAE,QAAQ;CAAY,WAAW;AAAsB,CAAC,CACpF;AAEN,MAAM,UAAU,SACd,OAAO,aAAa,KAAK,CAAC,CAAC,IAAI,CAAC,CAAC,KAC/B,OAAO,eAAe,qBAAqB,KAAK;CAAE,QAAQ;CAAW,WAAW;AAAS,CAAC,CAAC,CAC7F;AAEF,MAAM,OAAO,OAAO,OAAO;CACzB,WAAW;CACX,OAAO,OAAO,IAAI,MAAM,OAAO,cAAc,CAAC,GAAG,OAAO,oBAAoB,GAAG,CAAC;CAChF,eAAe,OAAO,YAAY,QAAQ;AAC5C,CAAC;AAED,MAAM,YAAY,MAA6B,QAAgB;CAC7D,IAAI,MAAM;CACV,IAAI,OAAO,KAAK;CAEhB,OAAO,MAAM,MAAM;EACjB,MAAM,MAAM,KAAK,OAAO,MAAM,QAAQ,CAAC;EAEvC,IAAI,KAAK,OAAO,KAAK,MAAM,MAAM;OAC5B,OAAO;CACd;CAEA,OAAO;AACT;AAEA,MAAM,aAAa,MAAqB,QAAgB;CACtD,MAAM,KAAK,SAAS,MAAM,GAAG;CAE7B,IAAI,KAAK,QAAQ,KAAK,KAAK,OAAO,IAAI,GAAG,GAAG;AAC9C;AAEA,MAAM,aAAa,MAAqB,QAAgB;CACtD,MAAM,KAAK,SAAS,MAAM,GAAG;CAE7B,IAA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,WAAW,IAAI,MAAM,GAAG;GAExC,MAAM,SACJ,kBAAkB,KAAA,IACd,QAAQ,eACR,QAAQ,kBAAkB,IAAI,aAAa,EAAA,GAC7C;GAEJ,OAAO,UAAU,KAAA,IAAY,OAAQ,QAAQ,UAAU,IAAI,KAAK,CAAC,EAAE,YAAY;EACjF,CAAC;CACH,CAAC;AACH,CAAC,CACH;AAEF,MAAa,iCAAiC,gCAAgC"}
@@ -3,7 +3,7 @@ import * as Layer from "effect/Layer";
3
3
  declare namespace MemoryScheduleStore_d_exports {
4
4
  export { MemoryScheduleStoreLive, memoryScheduleStoreLayer };
5
5
  }
6
- export declare const memoryScheduleStoreLayer: () => Layer.Layer<ScheduleStore>;
6
+ export declare const memoryScheduleStoreLayer: Layer.Layer<ScheduleStore>;
7
7
  export declare const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore>;
8
8
  //#endregion
9
9
  export { MemoryScheduleStore_d_exports as t };
@@ -15,18 +15,9 @@ const storageError = (operation, reason) => ScheduleStorageError.make({
15
15
  operation,
16
16
  reason
17
17
  });
18
- const encodeRecord = (operation, record) => Effect.try({
19
- try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(record),
20
- catch: () => storageError(operation, "corrupt")
21
- });
22
- const decodeRecord = (operation, encoded) => Effect.try({
23
- try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(encoded),
24
- catch: () => storageError(operation, "corrupt")
25
- });
26
- const decodeInput = (operation, schema, value) => Effect.try({
27
- try: () => Schema.decodeUnknownSync(schema)(value),
28
- catch: () => storageError(operation, "corrupt")
29
- });
18
+ const encodeRecord = (operation, record) => Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(Effect.mapError(() => storageError(operation, "corrupt")));
19
+ const decodeRecord = (operation, encoded) => Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(encoded).pipe(Effect.mapError(() => storageError(operation, "corrupt")));
20
+ const decodeInput = (operation, schema, value) => Schema.decodeUnknownEffect(schema)(value).pipe(Effect.mapError(() => storageError(operation, "corrupt")));
30
21
  const sameOwner = (record, owner) => scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);
31
22
  const makeScheduleStore = Effect.gen(function* () {
32
23
  const state = yield* Ref.make({ records: /* @__PURE__ */ new Map() });
@@ -165,8 +156,8 @@ const makeScheduleStore = Effect.gen(function* () {
165
156
  nextDeadline
166
157
  });
167
158
  });
168
- const memoryScheduleStoreLayer = () => Layer.effect(ScheduleStore, makeScheduleStore);
169
- const MemoryScheduleStoreLive = memoryScheduleStoreLayer();
159
+ const memoryScheduleStoreLayer = Layer.fresh(Layer.effect(ScheduleStore, makeScheduleStore));
160
+ const MemoryScheduleStoreLive = Layer.effect(ScheduleStore, makeScheduleStore);
170
161
  //#endregion
171
162
  export { MemoryScheduleStoreLive, memoryScheduleStoreLayer, MemoryScheduleStore_exports as t };
172
163
 
@@ -1 +1 @@
1
- {"version":3,"file":"MemoryScheduleStore.mjs","names":[],"sources":["../src/MemoryScheduleStore.ts"],"sourcesContent":["import {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n ScheduleKey,\n ScheduleNotFound,\n ScheduleOwner,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@yielded/agent/schedule\";\nimport {\n scheduleUsesCapacity,\n applyScheduleChange,\n compareScheduleKeys,\n compareScheduleNames,\n scheduleDeadline,\n scheduleKeyString,\n scheduleKeyOf,\n scheduleOwnerKey,\n} from \"@yielded/agent/schedule-transition\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\ninterface MemoryScheduleState {\n readonly records: ReadonlyMap<string, string>;\n}\n\nconst storageError = (operation: string, reason: \"unavailable\" | \"corrupt\") =>\n ScheduleStorageError.make({ operation, reason });\n\nconst encodeRecord = (operation: string, record: ScheduleRecord) =>\n Effect.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(record),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeRecord = (operation: string, encoded: string) =>\n Effect.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(encoded),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>\n Effect.try({\n try: () => Schema.decodeUnknownSync(schema)(value),\n catch: () => storageError(operation, \"corrupt\"),\n });\n\nconst sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>\n scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);\n\nconst makeScheduleStore = Effect.gen(function* () {\n const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() });\n const failpoint = yield* ScheduleFailpoint;\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fnUntraced(\n function* (record, ownerLimit) {\n const encoded = yield* encodeRecord(\"insert\", record);\n\n yield* failpoint.hit(\"schedule:insert:before\");\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleCapacityError | ScheduleStorageError\n >,\n MemoryScheduleState,\n ] => {\n const key = scheduleKeyString(record);\n const existingText = current.records.get(key);\n\n if (existingText !== undefined) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (decoded.success.creationFingerprint === record.creationFingerprint) {\n return [Result.succeed(decoded.success), current];\n }\n\n return [\n Result.fail(\n ScheduleConflict.make({ reason: \"creation\", key: scheduleKeyOf(record) }),\n ),\n current,\n ];\n }\n\n let ownerCount = 0;\n\n for (const text of current.records.values()) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (sameOwner(decoded.success, record.owner) && scheduleUsesCapacity(decoded.success))\n ownerCount += 1;\n }\n if (ownerCount >= ownerLimit) {\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n const records = new Map(current.records);\n\n records.set(key, encoded);\n const next = { records };\n\n return [Result.succeed(record), next];\n },\n ),\n );\n\n const inserted = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(\"schedule:insert:after\");\n\n return yield* decodeRecord(\"insert\", yield* encodeRecord(\"insert\", inserted));\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fnUntraced(function* (key) {\n const decodedKey = yield* decodeInput(\"get\", ScheduleKey, key);\n const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey));\n\n return text === undefined ? null : yield* decodeRecord(\"get\", text);\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fnUntraced(function* (request) {\n const decodedRequest = yield* decodeInput(\"list\", SchedulePageRequest, request);\n const records: Array<ScheduleRecord> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"list\", text);\n\n if (\n sameOwner(record, decodedRequest.owner) &&\n (decodedRequest.after === undefined ||\n compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)\n ) {\n records.push(record);\n }\n }\n records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId));\n const hasNext = records.length > decodedRequest.limit;\n const items = records.slice(0, decodedRequest.limit);\n\n return {\n items,\n next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,\n };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fnUntraced(function* (\n key,\n command,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const decodedKey = yield* decodeInput(\"change\", ScheduleKey, key);\n const decodedCommand = yield* decodeInput(\"change\", ScheduleChange, command);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`);\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError\n >,\n MemoryScheduleState,\n ] => {\n const storageKey = scheduleKeyString(decodedKey);\n const text = current.records.get(storageKey);\n\n if (text === undefined) {\n return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current];\n }\n\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n const applied = applyScheduleChange(decoded.success, decodedCommand);\n\n if (Result.isFailure(applied)) {\n return [Result.fail(applied.failure), current];\n }\n if (applied.success === decoded.success) {\n return [Result.succeed(decoded.success), current];\n }\n if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {\n let count = 0;\n\n for (const text of current.records.values()) {\n const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(text);\n\n if (Result.isFailure(candidate))\n return [Result.fail(storageError(\"change\", \"corrupt\")), current];\n if (\n sameOwner(candidate.success, decodedKey.owner) &&\n scheduleUsesCapacity(candidate.success)\n )\n count += 1;\n }\n if (count >= ownerLimit)\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n\n const encoded = Result.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(encoded)) {\n return [Result.fail(encoded.failure), current];\n }\n const records = new Map(current.records);\n\n records.set(storageKey, encoded.success);\n const next = { records };\n\n return [Result.succeed(applied.success), next];\n },\n ),\n );\n\n const changed = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`);\n\n return yield* decodeRecord(\"change\", yield* encodeRecord(\"change\", changed));\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fnUntraced(\n function* (nowMillis, limit, owner, after) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"due\", ScheduleOwner, owner);\n\n const cursor =\n after === undefined ? undefined : yield* decodeInput(\"due\", ScheduleDueCursor, after);\n\n const records: Array<ScheduleDueCursor> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"due\", text);\n const deadline = scheduleDeadline(record);\n\n if (\n deadline !== null &&\n deadline <= nowMillis &&\n (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&\n (cursor === undefined ||\n deadline > cursor.deadlineAtMillis ||\n (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))\n ) {\n records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline });\n }\n }\n records.sort((left, right) => {\n const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis;\n\n return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right);\n });\n\n return records.slice(0, limit);\n },\n );\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fnUntraced(\n function* (owner) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"nextDeadline\", ScheduleOwner, owner);\n\n let earliest: number | null = null;\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"nextDeadline\", text);\n\n if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue;\n const deadline = scheduleDeadline(record);\n\n if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline;\n }\n\n return earliest;\n },\n );\n\n return ScheduleStore.of({ insert, get, list, change, due, nextDeadline });\n});\n\nexport const memoryScheduleStoreLayer = (): Layer.Layer<ScheduleStore> =>\n Layer.effect(Sc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B,CACF;CAEA,MAAM,eAAyD,OAAO,WACpE,WAAW,OAAO;EAChB,MAAM,eACJ,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,YAAY,gBAAgB,eAAe,KAAK;EAE3F,IAAI,WAA0B;EAE9B,KAAK,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK,EAAA,CAAG,QAAQ,OAAO,GAAG;GAC3D,MAAM,SAAS,OAAO,aAAa,gBAAgB,IAAI;GAEvD,IAAI,iBAAiB,KAAA,KAAa,CAAC,UAAU,QAAQ,YAAY,GAAG;GACpE,MAAM,WAAW,iBAAiB,MAAM;GAExC,IAAI,aAAa,SAAS,aAAa,QAAQ,WAAW,WAAW,WAAW;EAClF;EAEA,OAAO;CACT,CACF;CAEA,OAAO,cAAc,GAAG;EAAE;EAAQ;EAAK;EAAM;EAAQ;EAAK;CAAa,CAAC;AAC1E,CAAC;AAED,MAAa,iCACX,MAAM,OAAO,eAAe,iBAAiB;AAE/C,MAAa,0BAAsD,yBAAyB"}
1
+ {"version":3,"file":"MemoryScheduleStore.mjs","names":[],"sources":["../src/MemoryScheduleStore.ts"],"sourcesContent":["import {\n ScheduleCapacityError,\n ScheduleDueCursor,\n defaultSchedulingLimits,\n ScheduleChange,\n ScheduleConflict,\n ScheduleFailpoint,\n ScheduleKey,\n ScheduleNotFound,\n ScheduleOwner,\n SchedulePageRequest,\n ScheduleRecord,\n ScheduleStorageError,\n ScheduleStore,\n} from \"@yielded/agent/schedule\";\nimport {\n scheduleUsesCapacity,\n applyScheduleChange,\n compareScheduleKeys,\n compareScheduleNames,\n scheduleDeadline,\n scheduleKeyString,\n scheduleKeyOf,\n scheduleOwnerKey,\n} from \"@yielded/agent/schedule-transition\";\nimport * as Effect from \"effect/Effect\";\nimport * as Layer from \"effect/Layer\";\nimport * as Ref from \"effect/Ref\";\nimport * as Result from \"effect/Result\";\nimport * as Schema from \"effect/Schema\";\n\ninterface MemoryScheduleState {\n readonly records: ReadonlyMap<string, string>;\n}\n\nconst storageError = (operation: string, reason: \"unavailable\" | \"corrupt\") =>\n ScheduleStorageError.make({ operation, reason });\n\nconst encodeRecord = (operation: string, record: ScheduleRecord) =>\n Schema.encodeEffect(Schema.fromJsonString(ScheduleRecord))(record).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst decodeRecord = (operation: string, encoded: string) =>\n Schema.decodeEffect(Schema.fromJsonString(ScheduleRecord))(encoded).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst decodeInput = <A, I>(operation: string, schema: Schema.Codec<A, I>, value: unknown) =>\n Schema.decodeUnknownEffect(schema)(value).pipe(\n Effect.mapError(() => storageError(operation, \"corrupt\")),\n );\n\nconst sameOwner = (record: ScheduleRecord, owner: ScheduleOwner): boolean =>\n scheduleOwnerKey(record.owner) === scheduleOwnerKey(owner);\n\nconst makeScheduleStore = Effect.gen(function* () {\n const state = yield* Ref.make<MemoryScheduleState>({ records: new Map() });\n const failpoint = yield* ScheduleFailpoint;\n\n const insert: ScheduleStore[\"Service\"][\"insert\"] = Effect.fnUntraced(\n function* (record, ownerLimit) {\n const encoded = yield* encodeRecord(\"insert\", record);\n\n yield* failpoint.hit(\"schedule:insert:before\");\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleCapacityError | ScheduleStorageError\n >,\n MemoryScheduleState,\n ] => {\n const key = scheduleKeyString(record);\n const existingText = current.records.get(key);\n\n if (existingText !== undefined) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(existingText),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (decoded.success.creationFingerprint === record.creationFingerprint) {\n return [Result.succeed(decoded.success), current];\n }\n\n return [\n Result.fail(\n ScheduleConflict.make({ reason: \"creation\", key: scheduleKeyOf(record) }),\n ),\n current,\n ];\n }\n\n let ownerCount = 0;\n\n for (const text of current.records.values()) {\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"insert\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n if (sameOwner(decoded.success, record.owner) && scheduleUsesCapacity(decoded.success))\n ownerCount += 1;\n }\n if (ownerCount >= ownerLimit) {\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n const records = new Map(current.records);\n\n records.set(key, encoded);\n const next = { records };\n\n return [Result.succeed(record), next];\n },\n ),\n );\n\n const inserted = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(\"schedule:insert:after\");\n\n return yield* decodeRecord(\"insert\", yield* encodeRecord(\"insert\", inserted));\n },\n );\n\n const get: ScheduleStore[\"Service\"][\"get\"] = Effect.fnUntraced(function* (key) {\n const decodedKey = yield* decodeInput(\"get\", ScheduleKey, key);\n const text = (yield* Ref.get(state)).records.get(scheduleKeyString(decodedKey));\n\n return text === undefined ? null : yield* decodeRecord(\"get\", text);\n });\n\n const list: ScheduleStore[\"Service\"][\"list\"] = Effect.fnUntraced(function* (request) {\n const decodedRequest = yield* decodeInput(\"list\", SchedulePageRequest, request);\n const records: Array<ScheduleRecord> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"list\", text);\n\n if (\n sameOwner(record, decodedRequest.owner) &&\n (decodedRequest.after === undefined ||\n compareScheduleNames(record.scheduleId, decodedRequest.after) > 0)\n ) {\n records.push(record);\n }\n }\n records.sort((left, right) => compareScheduleNames(left.scheduleId, right.scheduleId));\n const hasNext = records.length > decodedRequest.limit;\n const items = records.slice(0, decodedRequest.limit);\n\n return {\n items,\n next: hasNext ? (items.at(-1)?.scheduleId ?? null) : null,\n };\n });\n\n const change: ScheduleStore[\"Service\"][\"change\"] = Effect.fnUntraced(function* (\n key,\n command,\n ownerLimit = defaultSchedulingLimits.maxSchedulesPerOwner,\n ) {\n const decodedKey = yield* decodeInput(\"change\", ScheduleKey, key);\n const decodedCommand = yield* decodeInput(\"change\", ScheduleChange, command);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:before`);\n\n const decision = yield* Effect.uninterruptible(\n Ref.modify(\n state,\n (\n current,\n ): readonly [\n Result.Result<\n ScheduleRecord,\n ScheduleConflict | ScheduleStorageError | ScheduleNotFound | ScheduleCapacityError\n >,\n MemoryScheduleState,\n ] => {\n const storageKey = scheduleKeyString(decodedKey);\n const text = current.records.get(storageKey);\n\n if (text === undefined) {\n return [Result.fail(ScheduleNotFound.make({ key: decodedKey })), current];\n }\n\n const decoded = Result.try({\n try: () => Schema.decodeSync(Schema.fromJsonString(ScheduleRecord))(text),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(decoded)) {\n return [Result.fail(decoded.failure), current];\n }\n const applied = applyScheduleChange(decoded.success, decodedCommand);\n\n if (Result.isFailure(applied)) {\n return [Result.fail(applied.failure), current];\n }\n if (applied.success === decoded.success) {\n return [Result.succeed(decoded.success), current];\n }\n if (!scheduleUsesCapacity(decoded.success) && scheduleUsesCapacity(applied.success)) {\n let count = 0;\n\n for (const text of current.records.values()) {\n const candidate = Schema.decodeResult(Schema.fromJsonString(ScheduleRecord))(text);\n\n if (Result.isFailure(candidate))\n return [Result.fail(storageError(\"change\", \"corrupt\")), current];\n if (\n sameOwner(candidate.success, decodedKey.owner) &&\n scheduleUsesCapacity(candidate.success)\n )\n count += 1;\n }\n if (count >= ownerLimit)\n return [Result.fail(ScheduleCapacityError.make({ limit: ownerLimit })), current];\n }\n\n const encoded = Result.try({\n try: () => Schema.encodeSync(Schema.fromJsonString(ScheduleRecord))(applied.success),\n catch: () => storageError(\"change\", \"corrupt\"),\n });\n\n if (Result.isFailure(encoded)) {\n return [Result.fail(encoded.failure), current];\n }\n const records = new Map(current.records);\n\n records.set(storageKey, encoded.success);\n const next = { records };\n\n return [Result.succeed(applied.success), next];\n },\n ),\n );\n\n const changed = yield* Effect.fromResult(decision);\n\n yield* failpoint.hit(`schedule:${decodedCommand._tag.toLowerCase()}:after`);\n\n return yield* decodeRecord(\"change\", yield* encodeRecord(\"change\", changed));\n });\n\n const due: ScheduleStore[\"Service\"][\"due\"] = Effect.fnUntraced(\n function* (nowMillis, limit, owner, after) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"due\", ScheduleOwner, owner);\n\n const cursor =\n after === undefined ? undefined : yield* decodeInput(\"due\", ScheduleDueCursor, after);\n\n const records: Array<ScheduleDueCursor> = [];\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"due\", text);\n const deadline = scheduleDeadline(record);\n\n if (\n deadline !== null &&\n deadline <= nowMillis &&\n (decodedOwner === undefined || sameOwner(record, decodedOwner)) &&\n (cursor === undefined ||\n deadline > cursor.deadlineAtMillis ||\n (deadline === cursor.deadlineAtMillis && compareScheduleKeys(record, cursor) > 0))\n ) {\n records.push({ ...scheduleKeyOf(record), deadlineAtMillis: deadline });\n }\n }\n records.sort((left, right) => {\n const byDeadline = left.deadlineAtMillis - right.deadlineAtMillis;\n\n return byDeadline !== 0 ? byDeadline : compareScheduleKeys(left, right);\n });\n\n return records.slice(0, limit);\n },\n );\n\n const nextDeadline: ScheduleStore[\"Service\"][\"nextDeadline\"] = Effect.fnUntraced(\n function* (owner) {\n const decodedOwner =\n owner === undefined ? undefined : yield* decodeInput(\"nextDeadline\", ScheduleOwner, owner);\n\n let earliest: number | null = null;\n\n for (const text of (yield* Ref.get(state)).records.values()) {\n const record = yield* decodeRecord(\"nextDeadline\", text);\n\n if (decodedOwner !== undefined && !sameOwner(record, decodedOwner)) continue;\n const deadline = scheduleDeadline(record);\n\n if (deadline !== null && (earliest === null || deadline < earliest)) earliest = deadline;\n }\n\n return earliest;\n },\n );\n\n return ScheduleStore.of({ insert, get, list, change, due, nextDeadline });\n});\n\nexport const memoryScheduleStoreLayer: Layer.Layer<ScheduleStore> = Layer.fresh(\n Layer.effect(ScheduleStore, makeScheduleStore),\n);\n\nexport const MemoryScheduleStoreLive: Layer.Layer<ScheduleStore> = Layer.effect(\n ScheduleStore,\n makeScheduleStore,\n);\n"],"mappings":";;;;;;;;;;;;;AAmCA,MAAM,gBAAgB,WAAmB,WACvC,qBAAqB,KAAK;CAAE;CAAW;AAAO,CAAC;AAEjD,MAAM,gBAAgB,WAAmB,WACvC,OAAO,aAAa,OAAO,eAAe,cAAc,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,KACjE,OAAO,eAAe,aAAa,WAAW,SAAS,CAAC,CAC1D;AAEF,MAAM,gBAAgB,WAAmB,YACvC,OAAO,aAAa,OAAO,eAAe,cAAc,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,KAClE,OAAO,eAAe,aAAa,WAAW,SAAS,CAAC,CAC1D;AAEF,MAAM,eAAqB,WAAmB,QAA4B,UACxE,OAAO,oBAAoB,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,KACxC,OAAO,eAAe,aAAa,WAAW,SAAS,CAAC,CAC1D;AAEF,MAAM,aAAa,QAAwB,UACzC,iBAAiB,OAAO,KAAK,MAAM,iBAAiB,KAAK;AAE3D,MAAM,oBAAoB,OAAO,IAAI,aAAa;CAChD,MAAM,QAAQ,OAAO,IAAI,KAA0B,EAAE,yBAAS,IAAI,IAAI,EAAE,CAAC;CACzE,MAAM,YAAY,OAAO;CAEzB,MAAM,SAA6C,OAAO,WACxD,WAAW,QAAQ,YAAY;EAC7B,MAAM,UAAU,OAAO,aAAa,UAAU,MAAM;EAEpD,OAAO,UAAU,IAAI,wBAAwB;EAE7C,MAAM,WAAW,OAAO,OAAO,gBAC7B,IAAI,OACF,QAEE,YAOG;GACH,MAAM,MAAM,kBAAkB,MAAM;GACpC,MAAM,eAAe,QAAQ,QAAQ,IAAI,GAAG;GAE5C,IAAI,iBAAiB,KAAA,GAAW;IAC9B,MAAM,UAAU,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B,MAAM,KAAK;EACxE,CAAC;EAED,OAAO,QAAQ,MAAM,GAAG,KAAK;CAC/B,CACF;CAEA,MAAM,eAAyD,OAAO,WACpE,WAAW,OAAO;EAChB,MAAM,eACJ,UAAU,KAAA,IAAY,KAAA,IAAY,OAAO,YAAY,gBAAgB,eAAe,KAAK;EAE3F,IAAI,WAA0B;EAE9B,KAAK,MAAM,SAAS,OAAO,IAAI,IAAI,KAAK,EAAA,CAAG,QAAQ,OAAO,GAAG;GAC3D,MAAM,SAAS,OAAO,aAAa,gBAAgB,IAAI;GAEvD,IAAI,iBAAiB,KAAA,KAAa,CAAC,UAAU,QAAQ,YAAY,GAAG;GACpE,MAAM,WAAW,iBAAiB,MAAM;GAExC,IAAI,aAAa,SAAS,aAAa,QAAQ,WAAW,WAAW,WAAW;EAClF;EAEA,OAAO;CACT,CACF;CAEA,OAAO,cAAc,GAAG;EAAE;EAAQ;EAAK;EAAM;EAAQ;EAAK;CAAa,CAAC;AAC1E,CAAC;AAED,MAAa,2BAAuD,MAAM,MACxE,MAAM,OAAO,eAAe,iBAAiB,CAC/C;AAEA,MAAa,0BAAsD,MAAM,OACvE,eACA,iBACF"}
@@ -1,4 +1,4 @@
1
- import { t as MemoryThreadStoreKernel } from "./MemoryThreadStoreKernel-Dy0PRmUy.mjs";
1
+ import { t as MemoryThreadStoreKernel } from "./MemoryThreadStoreKernel-a2vrXxZZ.mjs";
2
2
  import * as Effect from "effect/Effect";
3
3
  import * as Layer from "effect/Layer";
4
4
  import { SettlementPublisher } from "@yielded/agent/settlement-publisher";
@@ -1464,9 +1464,9 @@ const makeSubmissionLedger = Effect.fnUntraced(
1464
1464
  const stored = staged.submissions.get(id);
1465
1465
  return stored === void 0 ? void 0 : toAdmission(stored.row, settledTimes.get(id));
1466
1466
  }),
1467
- runOwner: (runId) => Effect.sync(() => {
1467
+ runOwner: Effect.fnUntraced(function* (runId) {
1468
1468
  if (!runId.startsWith("run:")) return void 0;
1469
- const id = Schema.decodeSync(SubmissionId)(runId.slice(4));
1469
+ const id = yield* Schema.decodeEffect(SubmissionId)(runId.slice(4)).pipe(Effect.orDie);
1470
1470
  const stored = staged.submissions.get(id);
1471
1471
  return stored === void 0 ? void 0 : toAdmission(stored.row, settledTimes.get(id));
1472
1472
  }),