@namzu/sdk 38.1.0 → 38.2.1

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 (90) hide show
  1. package/CHANGELOG.md +58 -0
  2. package/dist/manager/resident/agenda.d.ts +125 -0
  3. package/dist/manager/resident/agenda.d.ts.map +1 -0
  4. package/dist/manager/resident/agenda.js +551 -0
  5. package/dist/manager/resident/agenda.js.map +1 -0
  6. package/dist/manager/resident/delivery-window.d.ts +22 -0
  7. package/dist/manager/resident/delivery-window.d.ts.map +1 -0
  8. package/dist/manager/resident/delivery-window.js +78 -0
  9. package/dist/manager/resident/delivery-window.js.map +1 -0
  10. package/dist/manager/resident/host.d.ts +78 -0
  11. package/dist/manager/resident/host.d.ts.map +1 -0
  12. package/dist/manager/resident/host.js +252 -0
  13. package/dist/manager/resident/host.js.map +1 -0
  14. package/dist/manager/resident/initiative.d.ts +111 -0
  15. package/dist/manager/resident/initiative.d.ts.map +1 -0
  16. package/dist/manager/resident/initiative.js +121 -0
  17. package/dist/manager/resident/initiative.js.map +1 -0
  18. package/dist/manager/resident/learning.d.ts +483 -0
  19. package/dist/manager/resident/learning.d.ts.map +1 -0
  20. package/dist/manager/resident/learning.js +263 -0
  21. package/dist/manager/resident/learning.js.map +1 -0
  22. package/dist/manager/resident/loop.d.ts +31 -0
  23. package/dist/manager/resident/loop.d.ts.map +1 -0
  24. package/dist/manager/resident/loop.js +69 -0
  25. package/dist/manager/resident/loop.js.map +1 -0
  26. package/dist/manager/resident/outbox.d.ts +180 -0
  27. package/dist/manager/resident/outbox.d.ts.map +1 -0
  28. package/dist/manager/resident/outbox.js +214 -0
  29. package/dist/manager/resident/outbox.js.map +1 -0
  30. package/dist/manager/resident/proposal.d.ts +91 -0
  31. package/dist/manager/resident/proposal.d.ts.map +1 -0
  32. package/dist/manager/resident/proposal.js +75 -0
  33. package/dist/manager/resident/proposal.js.map +1 -0
  34. package/dist/manager/resident/store.d.ts +149 -0
  35. package/dist/manager/resident/store.d.ts.map +1 -0
  36. package/dist/manager/resident/store.js +175 -0
  37. package/dist/manager/resident/store.js.map +1 -0
  38. package/dist/prompt/contributions.d.ts +5 -2
  39. package/dist/prompt/contributions.d.ts.map +1 -1
  40. package/dist/prompt/contributions.js.map +1 -1
  41. package/dist/prompt/index.d.ts +2 -0
  42. package/dist/prompt/index.d.ts.map +1 -1
  43. package/dist/prompt/index.js +1 -0
  44. package/dist/prompt/index.js.map +1 -1
  45. package/dist/prompt/resident-step.d.ts +29 -0
  46. package/dist/prompt/resident-step.d.ts.map +1 -0
  47. package/dist/prompt/resident-step.js +74 -0
  48. package/dist/prompt/resident-step.js.map +1 -0
  49. package/dist/public-runtime.d.ts +10 -1
  50. package/dist/public-runtime.d.ts.map +1 -1
  51. package/dist/public-runtime.js +10 -1
  52. package/dist/public-runtime.js.map +1 -1
  53. package/dist/public-types.d.ts +16 -2
  54. package/dist/public-types.d.ts.map +1 -1
  55. package/dist/registry/index.d.ts +1 -1
  56. package/dist/registry/index.d.ts.map +1 -1
  57. package/dist/registry/tool/execute.d.ts +18 -0
  58. package/dist/registry/tool/execute.d.ts.map +1 -1
  59. package/dist/registry/tool/execute.js +43 -6
  60. package/dist/registry/tool/execute.js.map +1 -1
  61. package/dist/runtime/query/events.d.ts +6 -1
  62. package/dist/runtime/query/events.d.ts.map +1 -1
  63. package/dist/runtime/query/events.js +21 -12
  64. package/dist/runtime/query/events.js.map +1 -1
  65. package/dist/runtime/query/index.d.ts.map +1 -1
  66. package/dist/runtime/query/index.js +1 -1
  67. package/dist/runtime/query/index.js.map +1 -1
  68. package/dist/runtime/query/prompt-cache.d.ts.map +1 -1
  69. package/dist/runtime/query/prompt-cache.js +21 -42
  70. package/dist/runtime/query/prompt-cache.js.map +1 -1
  71. package/package.json +1 -1
  72. package/src/manager/resident/agenda.ts +853 -0
  73. package/src/manager/resident/delivery-window.ts +93 -0
  74. package/src/manager/resident/host.ts +356 -0
  75. package/src/manager/resident/initiative.ts +195 -0
  76. package/src/manager/resident/learning.ts +369 -0
  77. package/src/manager/resident/loop.ts +101 -0
  78. package/src/manager/resident/outbox.ts +307 -0
  79. package/src/manager/resident/proposal.ts +105 -0
  80. package/src/manager/resident/store.ts +229 -0
  81. package/src/prompt/contributions.ts +5 -2
  82. package/src/prompt/index.ts +2 -0
  83. package/src/prompt/resident-step.ts +96 -0
  84. package/src/public-runtime.ts +14 -0
  85. package/src/public-types.ts +67 -0
  86. package/src/registry/index.ts +1 -1
  87. package/src/registry/tool/execute.ts +56 -9
  88. package/src/runtime/query/events.ts +24 -14
  89. package/src/runtime/query/index.ts +1 -2
  90. package/src/runtime/query/prompt-cache.ts +24 -47
@@ -0,0 +1,853 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { join } from 'node:path'
3
+ import { isDeepStrictEqual } from 'node:util'
4
+ import { z } from 'zod'
5
+ import { DiskRecordStore } from '../../store/kv/record-store.js'
6
+ import { DiskRevisionRecordStore } from '../../store/kv/revision-record-store.js'
7
+ import { defineSchema } from '../../store/schema.js'
8
+ import type { TenantId } from '../../types/ids/index.js'
9
+ import { asTenantId } from '../../utils/id.js'
10
+ import {
11
+ ResidentConflictError,
12
+ type ResidentDecision,
13
+ type ResidentExecutionStore,
14
+ type ResidentState,
15
+ claimResidentState,
16
+ residentDecisionSchema,
17
+ residentKeySegment,
18
+ residentStateSchema,
19
+ settleResidentState,
20
+ wakeResidentState,
21
+ } from './store.js'
22
+
23
+ import {
24
+ type ResidentFeedback,
25
+ type ResidentObservation,
26
+ freezeResidentFeedback,
27
+ observeResidentStep,
28
+ residentFeedbackSchema,
29
+ residentObservationSchema,
30
+ } from './initiative.js'
31
+ import {
32
+ type ResidentLearningEvidence,
33
+ type ResidentLearningState,
34
+ type ResidentProfileUpdate,
35
+ type ResidentSkillCandidate,
36
+ type ResidentSkillEvaluation,
37
+ freezeResidentLearning,
38
+ promoteResidentSkill,
39
+ residentLearningEvidenceSchema,
40
+ residentLearningSchema,
41
+ restoreResidentSkill,
42
+ reviseResidentProfile,
43
+ } from './learning.js'
44
+ import {
45
+ type ResidentDeliveryOutcome,
46
+ type ResidentMessageInput,
47
+ type ResidentOutboxMessage,
48
+ appendResidentMessage,
49
+ claimResidentOutboxMessage,
50
+ residentDeliveryOutcomeSchema,
51
+ residentMessageInputSchema,
52
+ residentOutboxMessageSchema,
53
+ settleResidentOutboxMessage,
54
+ } from './outbox.js'
55
+ import {
56
+ type ResidentProposal,
57
+ type ResidentProposalLimits,
58
+ type ResidentProposalOrigin,
59
+ residentProposalLimitsSchema,
60
+ residentProposalOriginSchema,
61
+ residentProposalSchema,
62
+ validateResidentProposal,
63
+ } from './proposal.js'
64
+
65
+ const agendaSchema = z
66
+ .object({
67
+ tenantId: z.string().uuid(),
68
+ agentKey: z.string().min(1).max(200),
69
+ identity: z.string().trim().min(1).max(8_000),
70
+ revision: z.number().int().positive().safe(),
71
+ paused: z.boolean(),
72
+ pauseGeneration: z.number().int().nonnegative().safe().optional(),
73
+ archiveHead: z.number().int().min(2).safe().optional(),
74
+ learning: residentLearningSchema.optional(),
75
+ outbox: z.array(residentOutboxMessageSchema).max(128).optional(),
76
+ pursuits: z
77
+ .array(
78
+ z.object({
79
+ id: z.string().uuid(),
80
+ state: residentStateSchema,
81
+ feedback: residentFeedbackSchema.optional(),
82
+ origin: residentProposalOriginSchema.optional(),
83
+ retiredChildren: z.number().int().min(0).max(8).optional(),
84
+ }),
85
+ )
86
+ .max(32),
87
+ })
88
+ .superRefine((agenda, context) => {
89
+ const origins = agenda.pursuits.flatMap((p) => (p.origin ? [p.origin] : []))
90
+ const outbox = agenda.outbox ?? []
91
+ const invalid =
92
+ (agenda.archiveHead !== undefined && agenda.archiveHead > agenda.revision) ||
93
+ new Set(outbox.map((message) => message.id)).size !== outbox.length ||
94
+ outbox.filter((message) => message.phase === 'sending').length > 1 ||
95
+ outbox.some(
96
+ (message) =>
97
+ message.tenantId !== agenda.tenantId ||
98
+ message.agentKey !== agenda.agentKey ||
99
+ !agenda.pursuits.some((pursuit) => pursuit.id === message.pursuitId),
100
+ ) ||
101
+ new Set(agenda.pursuits.map((p) => p.id)).size !== agenda.pursuits.length ||
102
+ new Set(origins.map((origin) => origin.proposalId)).size !== origins.length ||
103
+ agenda.pursuits.filter((p) => p.state.phase === 'running').length > 1 ||
104
+ agenda.pursuits.some((p) => {
105
+ if (!p.origin) return false
106
+ const parent = agenda.pursuits.find((candidate) => candidate.id === p.origin?.parentId)
107
+ return (
108
+ !parent ||
109
+ parent.id === p.id ||
110
+ p.origin.parentRevision > parent.state.revision ||
111
+ p.origin.depth !== (parent.origin?.depth ?? 0) + 1
112
+ )
113
+ }) ||
114
+ agenda.pursuits.some((p) =>
115
+ p.feedback?.observations.some(
116
+ (item, index, all) =>
117
+ item.step > p.state.stepsAdmitted ||
118
+ (index > 0 && item.step <= (all[index - 1]?.step ?? 0)),
119
+ ),
120
+ ) ||
121
+ agenda.pursuits.some(
122
+ ({ id, state }) =>
123
+ state.pursuitId !== id ||
124
+ state.tenantId !== agenda.tenantId ||
125
+ state.agentKey !== agenda.agentKey ||
126
+ state.identity !== agenda.identity,
127
+ )
128
+ if (invalid)
129
+ context.addIssue({
130
+ code: z.ZodIssueCode.custom,
131
+ message:
132
+ 'Invalid agenda identity, pursuit ancestry, observation order, outbox or overlapping claims.',
133
+ })
134
+ })
135
+
136
+ /** @experimental One pursuit shares its agent's identity, but has its own lifecycle. */
137
+ export interface ResidentPursuit {
138
+ readonly id: string
139
+ readonly state: ResidentState
140
+ readonly feedback?: ResidentFeedback
141
+ readonly origin?: ResidentProposalOrigin
142
+ /** Archived direct children still consume the parent's lifetime admission bound. */
143
+ readonly retiredChildren?: number
144
+ }
145
+
146
+ /** @experimental Bounded shared admission record; at most one pursuit may be running. */
147
+ export interface ResidentAgendaState {
148
+ readonly tenantId: string
149
+ readonly agentKey: string
150
+ readonly identity: string
151
+ readonly revision: number
152
+ readonly paused: boolean
153
+ /** Durable pause requests; absent means zero. Resuming never resets this generation. */
154
+ readonly pauseGeneration?: number
155
+ readonly pursuits: readonly ResidentPursuit[]
156
+ readonly outbox?: readonly ResidentOutboxMessage[]
157
+ readonly archiveHead?: number
158
+ readonly learning?: ResidentLearningState
159
+ }
160
+
161
+ /** @experimental Explicit terminal entries to retire from active capacity together. */
162
+ export interface ResidentArchiveRequest {
163
+ readonly pursuitIds?: readonly string[]
164
+ readonly messageIds?: readonly string[]
165
+ }
166
+
167
+ /** @experimental A committed removal, whose immutable predecessor preserves the full records. */
168
+ export interface ResidentArchiveEntry {
169
+ readonly revision: number
170
+ readonly pursuits: readonly ResidentPursuit[]
171
+ readonly messages: readonly ResidentOutboxMessage[]
172
+ }
173
+
174
+ /** @experimental Pages count archive events; each event contains at most 32 pursuits and 128 messages. */
175
+ export interface ResidentArchivePage {
176
+ readonly entries: readonly ResidentArchiveEntry[]
177
+ readonly nextBeforeRevision: number | null
178
+ }
179
+
180
+ /** @experimental The cursor is the next archive-event revision returned by a previous page. */
181
+ export interface ResidentArchiveListOptions {
182
+ readonly beforeRevision?: number
183
+ /** Number of archive events to inspect; defaults to 8 and cannot exceed 32. */
184
+ readonly limit?: number
185
+ }
186
+
187
+ const agendaRecordSchema = defineSchema({
188
+ kind: 'resident-agenda',
189
+ current: 5,
190
+ migrations: {
191
+ 1: (record) => record,
192
+ 2: (record) => record,
193
+ 3: (record) => record,
194
+ 4: (record) => record,
195
+ },
196
+ })
197
+
198
+ const archiveRequestSchema = z.object({
199
+ pursuitIds: z.array(z.string().uuid()).max(32).default([]),
200
+ messageIds: z.array(z.string().uuid()).max(128).default([]),
201
+ })
202
+
203
+ /** @experimental Atomic whole-agent admission plus independently addressable pursuits. */
204
+ export interface ResidentAgendaStore {
205
+ read(): Promise<ResidentAgendaState | null>
206
+ create(identity: string): Promise<ResidentAgendaState>
207
+ add(expected: ResidentAgendaState, objective: string): Promise<ResidentPursuit>
208
+ /** Each committed true request advances pauseGeneration, even when already paused. */
209
+ setPaused(expected: ResidentAgendaState, paused: boolean): Promise<ResidentAgendaState>
210
+ wake(id: string, expected: ResidentState, reason: string, now: number): Promise<ResidentState>
211
+ execution(id: string): ResidentExecutionStore
212
+ /** Optional atomic extensions required by a configured resident initiative host. */
213
+ executionAt?(id: string, expected: ResidentAgendaState): ResidentExecutionStore
214
+ settleObserved?(
215
+ id: string,
216
+ expected: ResidentState,
217
+ decision: ResidentDecision,
218
+ observation: ResidentObservation,
219
+ now: number,
220
+ ): Promise<ResidentState>
221
+ /** Optional atomic settlement and outbound intent; no transport runs during persistence. */
222
+ settleWithMessage?(
223
+ id: string,
224
+ expected: ResidentState,
225
+ decision: ResidentDecision,
226
+ message: ResidentMessageInput,
227
+ now: number,
228
+ observation?: ResidentObservation,
229
+ ): Promise<ResidentState>
230
+ enqueueMessage?(
231
+ expected: ResidentAgendaState,
232
+ input: ResidentMessageInput,
233
+ ): Promise<ResidentOutboxMessage>
234
+ claimMessage?(
235
+ expected: ResidentAgendaState,
236
+ id: string,
237
+ now: number,
238
+ ): Promise<ResidentOutboxMessage>
239
+ settleMessage?(
240
+ expected: ResidentOutboxMessage,
241
+ outcome: ResidentDeliveryOutcome,
242
+ now: number,
243
+ ): Promise<ResidentOutboxMessage>
244
+ }
245
+
246
+ /**
247
+ * @experimental One immutable revision contains identity, pause state and all
248
+ * pursuits. Admission therefore serializes this agent even across processes
249
+ * choosing different pursuits. Trusted local filesystems only; no lease expiry.
250
+ */
251
+ export class DiskResidentAgenda implements ResidentAgendaStore {
252
+ private readonly records = new DiskRevisionRecordStore<ResidentAgendaState>(
253
+ agendaRecordSchema,
254
+ 'resident agenda',
255
+ (record) => record.revision,
256
+ )
257
+ private readonly history = new DiskRecordStore<ResidentAgendaState>(agendaRecordSchema)
258
+ private readonly location
259
+ private readonly tenantId: TenantId
260
+ private readonly agentKey: string
261
+
262
+ constructor(root: string, scope: { tenantId: TenantId; agentKey: string }) {
263
+ this.tenantId = asTenantId(scope.tenantId)
264
+ this.agentKey = z.string().min(1).max(200).parse(scope.agentKey)
265
+ const directory = join(root, this.tenantId, residentKeySegment(this.agentKey), 'agenda')
266
+ this.location = {
267
+ legacyPath: join(directory, 'state.json'),
268
+ revisionsDir: join(directory, 'revisions'),
269
+ publishLegacyProjection: false,
270
+ }
271
+ }
272
+
273
+ private checked(record: ResidentAgendaState): ResidentAgendaState {
274
+ const agenda = agendaSchema.parse(record)
275
+ if (agenda.tenantId !== this.tenantId || agenda.agentKey !== this.agentKey)
276
+ throw new Error('Agenda does not match the bound tenant and agent.')
277
+ return Object.freeze({
278
+ ...agenda,
279
+ ...(agenda.learning ? { learning: freezeResidentLearning(agenda.learning) } : {}),
280
+ ...(agenda.outbox
281
+ ? { outbox: Object.freeze(agenda.outbox.map((message) => Object.freeze(message))) }
282
+ : {}),
283
+ pursuits: Object.freeze(
284
+ agenda.pursuits.map((p) =>
285
+ Object.freeze({
286
+ ...p,
287
+ state: Object.freeze(p.state),
288
+ ...(p.feedback ? { feedback: freezeResidentFeedback(p.feedback) } : {}),
289
+ ...(p.origin ? { origin: Object.freeze(p.origin) } : {}),
290
+ }),
291
+ ),
292
+ ),
293
+ })
294
+ }
295
+
296
+ async read(): Promise<ResidentAgendaState | null> {
297
+ const record = await this.records.read(this.location)
298
+ return record === null ? null : this.checked(record)
299
+ }
300
+
301
+ /** Read one authoritative immutable commit, never the compatibility projection. */
302
+ async readRevision(revision: number): Promise<ResidentAgendaState | null> {
303
+ z.number().int().positive().safe().parse(revision)
304
+ const record = await this.history.read(join(this.location.revisionsDir, `${revision}.json`))
305
+ if (record === null) return null
306
+ const state = this.checked(record)
307
+ if (state.revision !== revision) throw new Error('Agenda revision filename and body disagree.')
308
+ return state
309
+ }
310
+
311
+ private retire(state: ResidentAgendaState, input: ResidentArchiveRequest): ResidentAgendaState {
312
+ const request = archiveRequestSchema.parse(input)
313
+ const pursuits = new Set(request.pursuitIds)
314
+ const messages = new Set(request.messageIds)
315
+ if (
316
+ pursuits.size + messages.size === 0 ||
317
+ pursuits.size !== request.pursuitIds.length ||
318
+ messages.size !== request.messageIds.length
319
+ )
320
+ throw new Error('Archive requires a nonempty set of unique entry IDs.')
321
+ const removed = state.pursuits.filter((pursuit) => pursuits.has(pursuit.id))
322
+ const removedMessages = (state.outbox ?? []).filter((message) => messages.has(message.id))
323
+ if (removed.length !== pursuits.size || removedMessages.length !== messages.size)
324
+ throw new Error('Unknown active entry in resident archive request.')
325
+ if (removed.some((p) => p.state.phase !== 'complete' && p.state.phase !== 'blocked'))
326
+ throw new Error('Only terminal pursuits can be archived.')
327
+ if (removedMessages.some((m) => m.phase !== 'acknowledged' && m.phase !== 'cancelled'))
328
+ throw new Error('Only terminal messages can be archived.')
329
+ const remaining = state.pursuits.filter((pursuit) => !pursuits.has(pursuit.id))
330
+ const remainingMessages = state.outbox?.filter((message) => !messages.has(message.id))
331
+ if (remaining.some((p) => p.origin && pursuits.has(p.origin.parentId)))
332
+ throw new Error('Archive must retain the parents of remaining pursuits.')
333
+ if (remainingMessages?.some((message) => pursuits.has(message.pursuitId)))
334
+ throw new Error('Archive must retain pursuits referenced by remaining messages.')
335
+ return {
336
+ ...state,
337
+ archiveHead: state.revision + 1,
338
+ pursuits: remaining.map((pursuit) => {
339
+ const retired = removed.filter((child) => child.origin?.parentId === pursuit.id).length
340
+ return retired
341
+ ? { ...pursuit, retiredChildren: (pursuit.retiredChildren ?? 0) + retired }
342
+ : pursuit
343
+ }),
344
+ ...(remainingMessages ? { outbox: remainingMessages } : {}),
345
+ }
346
+ }
347
+
348
+ /** Free active slots while preserving full records in the immutable predecessor commit. */
349
+ async archive(
350
+ expected: ResidentAgendaState,
351
+ input: ResidentArchiveRequest,
352
+ ): Promise<ResidentAgendaState> {
353
+ const request = archiveRequestSchema.parse(input)
354
+ return this.change(expected, (state) => this.retire(state, request))
355
+ }
356
+
357
+ private async archiveEntry(revision: number): Promise<{
358
+ entry: ResidentArchiveEntry
359
+ previous: number | null
360
+ }> {
361
+ const after = await this.readRevision(revision)
362
+ const before = await this.readRevision(revision - 1)
363
+ if (
364
+ !before ||
365
+ !after ||
366
+ after.archiveHead !== revision ||
367
+ (before.archiveHead !== undefined && before.archiveHead >= revision)
368
+ )
369
+ throw new Error('Resident archive history is missing or its chain is invalid.')
370
+ const activePursuits = new Set(after.pursuits.map((p) => p.id))
371
+ const activeMessages = new Set((after.outbox ?? []).map((m) => m.id))
372
+ const pursuits = before.pursuits.filter((p) => !activePursuits.has(p.id))
373
+ const messages = (before.outbox ?? []).filter((m) => !activeMessages.has(m.id))
374
+ const derived = this.checked({
375
+ ...this.retire(before, {
376
+ pursuitIds: pursuits.map((p) => p.id),
377
+ messageIds: messages.map((m) => m.id),
378
+ }),
379
+ revision,
380
+ })
381
+ if (!isDeepStrictEqual(derived, after))
382
+ throw new Error('Resident archive commit does not match its immutable predecessor.')
383
+ return {
384
+ entry: Object.freeze({
385
+ revision,
386
+ pursuits: Object.freeze(pursuits),
387
+ messages: Object.freeze(messages),
388
+ }),
389
+ previous: before.archiveHead ?? null,
390
+ }
391
+ }
392
+
393
+ /** Bounded archive-event pages; exact-ID deduplication may inspect the complete chain. */
394
+ async listArchived(options: ResidentArchiveListOptions = {}): Promise<ResidentArchivePage> {
395
+ const request = z
396
+ .object({
397
+ beforeRevision: z.number().int().min(2).safe().optional(),
398
+ limit: z.number().int().min(1).max(32).default(8),
399
+ })
400
+ .parse(options)
401
+ const state = await this.read()
402
+ if (!state) throw new Error('Create the resident agenda first.')
403
+ let revision = request.beforeRevision ?? state.archiveHead ?? null
404
+ if (revision !== null && (state.archiveHead === undefined || revision > state.archiveHead))
405
+ throw new Error('Archive cursor is ahead of committed archive history.')
406
+ const entries: ResidentArchiveEntry[] = []
407
+ while (revision !== null && entries.length < request.limit) {
408
+ const archived = await this.archiveEntry(revision)
409
+ entries.push(archived.entry)
410
+ revision = archived.previous
411
+ }
412
+ return Object.freeze({ entries: Object.freeze(entries), nextBeforeRevision: revision })
413
+ }
414
+
415
+ private async archivedMatch<T>(
416
+ state: ResidentAgendaState,
417
+ match: (entry: ResidentArchiveEntry) => T | undefined,
418
+ ): Promise<T | undefined> {
419
+ let revision = state.archiveHead ?? null
420
+ while (revision !== null) {
421
+ const archived = await this.archiveEntry(revision)
422
+ const found = match(archived.entry)
423
+ if (found !== undefined) return found
424
+ revision = archived.previous
425
+ }
426
+ return undefined
427
+ }
428
+
429
+ private assertArchivedIntent(
430
+ message: ResidentOutboxMessage,
431
+ input: ResidentMessageInput,
432
+ sourceClaimId: string | null,
433
+ ): void {
434
+ if (
435
+ message.pursuitId !== input.pursuitId ||
436
+ message.destination !== input.destination ||
437
+ message.body !== input.body ||
438
+ message.notBefore !== input.notBefore ||
439
+ message.sourceClaimId !== sourceClaimId
440
+ )
441
+ throw new Error('Outbox message ID already names a different immutable archived intent.')
442
+ }
443
+
444
+ async create(identity: string): Promise<ResidentAgendaState> {
445
+ const record = this.checked({
446
+ tenantId: this.tenantId,
447
+ agentKey: this.agentKey,
448
+ identity,
449
+ revision: 1,
450
+ paused: false,
451
+ pursuits: [],
452
+ })
453
+ return this.records.transact(this.location, (current) => {
454
+ if (current !== null) throw new ResidentConflictError()
455
+ return { record, result: record }
456
+ })
457
+ }
458
+
459
+ private async change(
460
+ expected: ResidentAgendaState,
461
+ update: (state: ResidentAgendaState) => ResidentAgendaState,
462
+ ): Promise<ResidentAgendaState> {
463
+ const snapshot = this.checked(expected)
464
+ return this.records.transact(this.location, (record) => {
465
+ if (record === null) throw new ResidentConflictError()
466
+ const current = this.checked(record)
467
+ if (current.revision !== snapshot.revision) throw new ResidentConflictError()
468
+ const next = this.checked({ ...update(current), revision: current.revision + 1 })
469
+ return { record: next, result: next }
470
+ })
471
+ }
472
+
473
+ private pursuit(identity: string, objective: string): ResidentPursuit {
474
+ const id = randomUUID()
475
+ const pursuit = Object.freeze({
476
+ id,
477
+ state: Object.freeze(
478
+ residentStateSchema.parse({
479
+ tenantId: this.tenantId,
480
+ agentKey: this.agentKey,
481
+ pursuitId: id,
482
+ identity,
483
+ objective,
484
+ revision: 1,
485
+ stepsAdmitted: 0,
486
+ phase: 'waiting',
487
+ wakeAt: 0,
488
+ reason: 'Initial pursuit',
489
+ summary: null,
490
+ claimId: null,
491
+ }),
492
+ ),
493
+ })
494
+ return pursuit
495
+ }
496
+
497
+ async add(expected: ResidentAgendaState, objective: string): Promise<ResidentPursuit> {
498
+ const pursuit = this.pursuit(expected.identity, objective)
499
+ await this.change(expected, (state) => ({ ...state, pursuits: [...state.pursuits, pursuit] }))
500
+ return pursuit
501
+ }
502
+
503
+ /** Host-approved proposal admission is atomic and inert until a future invocation. */
504
+ async admitProposal(
505
+ expected: ResidentAgendaState,
506
+ input: ResidentProposal,
507
+ limits: ResidentProposalLimits,
508
+ ): Promise<ResidentPursuit> {
509
+ const snapshot = this.checked(expected)
510
+ const proposal = residentProposalSchema.parse(input)
511
+ const policy = residentProposalLimitsSchema.parse(limits)
512
+ const current = await this.read()
513
+ if (!current || current.revision !== snapshot.revision) throw new ResidentConflictError()
514
+ validateResidentProposal(current, proposal, policy)
515
+ if (
516
+ await this.archivedMatch(current, (entry) =>
517
+ entry.pursuits.find((p) => p.origin?.proposalId === proposal.id),
518
+ )
519
+ )
520
+ throw new Error('Resident proposal has already been admitted and archived.')
521
+ let admitted: ResidentPursuit | undefined
522
+ await this.change(snapshot, (state) => {
523
+ const origin = validateResidentProposal(state, proposal, policy)
524
+ admitted = Object.freeze({
525
+ ...this.pursuit(state.identity, proposal.objective),
526
+ origin: Object.freeze(origin),
527
+ })
528
+ return { ...state, pursuits: [...state.pursuits, admitted] }
529
+ })
530
+ if (!admitted) throw new Error('Resident proposal was not admitted.')
531
+ return admitted
532
+ }
533
+
534
+ async setPaused(expected: ResidentAgendaState, paused: boolean): Promise<ResidentAgendaState> {
535
+ z.boolean().parse(paused)
536
+ return this.change(expected, (state) => ({
537
+ ...state,
538
+ paused,
539
+ ...(paused ? { pauseGeneration: (state.pauseGeneration ?? 0) + 1 } : {}),
540
+ }))
541
+ }
542
+
543
+ private async learn(
544
+ expected: ResidentAgendaState,
545
+ learning: ResidentLearningState,
546
+ ): Promise<ResidentAgendaState> {
547
+ return this.change(expected, (state) => {
548
+ if (state.pursuits.some((pursuit) => pursuit.state.phase === 'running'))
549
+ throw new Error('Resident learning cannot change while a pursuit is running.')
550
+ if (!isDeepStrictEqual(state.learning, expected.learning)) throw new ResidentConflictError()
551
+ return { ...state, learning }
552
+ })
553
+ }
554
+
555
+ /** Append a host-evidenced correction only while pursuit admission is idle. */
556
+ async updateProfile(
557
+ expected: ResidentAgendaState,
558
+ input: ResidentProfileUpdate,
559
+ ): Promise<ResidentAgendaState> {
560
+ const snapshot = this.checked(expected)
561
+ const learning = reviseResidentProfile(snapshot.learning, input)
562
+ return this.learn(snapshot, learning)
563
+ }
564
+
565
+ /** Bind evaluated guidance to the current learning version and an idle agenda. */
566
+ async promoteSkill(
567
+ expected: ResidentAgendaState,
568
+ candidate: ResidentSkillCandidate,
569
+ evaluation: ResidentSkillEvaluation,
570
+ evidence: ResidentLearningEvidence,
571
+ ): Promise<ResidentAgendaState> {
572
+ const snapshot = this.checked(expected)
573
+ const learning = promoteResidentSkill(snapshot.learning, candidate, evaluation, evidence)
574
+ return this.learn(snapshot, learning)
575
+ }
576
+
577
+ /** Restore one skill from an immutable agenda revision while retaining the current profile. */
578
+ async rollbackSkill(
579
+ expected: ResidentAgendaState,
580
+ name: string,
581
+ fromRevision: number,
582
+ evidence: ResidentLearningEvidence,
583
+ ): Promise<ResidentAgendaState> {
584
+ const snapshot = this.checked(expected)
585
+ const checkedEvidence = residentLearningEvidenceSchema.parse(evidence)
586
+ z.number().int().positive().safe().max(snapshot.revision).parse(fromRevision)
587
+ z.string()
588
+ .regex(/^[a-z0-9][a-z0-9_-]{0,63}$/)
589
+ .parse(name)
590
+ const historical = await this.readRevision(fromRevision)
591
+ if (!historical) throw new Error('Resident skill rollback revision is missing.')
592
+ const learning = restoreResidentSkill(
593
+ snapshot.learning,
594
+ historical.learning,
595
+ name,
596
+ checkedEvidence,
597
+ )
598
+ return this.learn(snapshot, learning)
599
+ }
600
+
601
+ private async updatePursuit(
602
+ id: string,
603
+ expected: ResidentState,
604
+ update: (state: ResidentState) => ResidentState,
605
+ admission = false,
606
+ expectedAgendaRevision?: number,
607
+ observation?: ResidentObservation,
608
+ message?: ResidentMessageInput,
609
+ ): Promise<ResidentState> {
610
+ const validate = (state: ResidentAgendaState): ResidentState => {
611
+ const pursuit = state.pursuits.find((p) => p.id === id)
612
+ if (!pursuit) throw new Error('Unknown resident pursuit.')
613
+ const current = pursuit.state
614
+ if (
615
+ expected.pursuitId !== id ||
616
+ expected.tenantId !== state.tenantId ||
617
+ expected.agentKey !== state.agentKey ||
618
+ current.revision !== expected.revision ||
619
+ current.claimId !== expected.claimId
620
+ )
621
+ throw new ResidentConflictError()
622
+ if (admission && (state.paused || state.pursuits.some((p) => p.state.phase === 'running')))
623
+ throw new ResidentConflictError()
624
+ return current
625
+ }
626
+ // Retry persistence contention only. The caller's exact pursuit revision
627
+ // and claim must survive every retry; a callback is never re-executed here.
628
+ for (let attempt = 0; attempt < 8; attempt++) {
629
+ const agenda = await this.read()
630
+ if (agenda === null) throw new Error('Create the resident agenda first.')
631
+ if (expectedAgendaRevision !== undefined && agenda.revision !== expectedAgendaRevision)
632
+ throw new ResidentConflictError()
633
+ const current = validate(agenda)
634
+ const archived =
635
+ message && !agenda.outbox?.some((item) => item.id === message.id)
636
+ ? await this.archivedMatch(agenda, (entry) =>
637
+ entry.messages.find((item) => item.id === message.id),
638
+ )
639
+ : undefined
640
+ if (message && archived) this.assertArchivedIntent(archived, message, current.claimId)
641
+ try {
642
+ const next = await this.change(agenda, (state) => {
643
+ const current = validate(state)
644
+ const updated = residentStateSchema.parse({
645
+ ...update(current),
646
+ revision: current.revision + 1,
647
+ })
648
+ return {
649
+ ...state,
650
+ ...(message && !archived
651
+ ? { outbox: appendResidentMessage(state, message, current.claimId) }
652
+ : {}),
653
+ pursuits: state.pursuits.map((p) =>
654
+ p.id === id
655
+ ? {
656
+ ...p,
657
+ state: updated,
658
+ ...(observation
659
+ ? {
660
+ feedback: observeResidentStep(
661
+ p.feedback,
662
+ observation,
663
+ current.stepsAdmitted,
664
+ ),
665
+ }
666
+ : {}),
667
+ }
668
+ : p,
669
+ ),
670
+ }
671
+ })
672
+ const result = next.pursuits.find((p) => p.id === id)
673
+ if (!result) throw new Error('Committed pursuit is missing.')
674
+ return result.state
675
+ } catch (error) {
676
+ if (!(error instanceof ResidentConflictError) || attempt === 7) throw error
677
+ }
678
+ }
679
+ throw new ResidentConflictError()
680
+ }
681
+
682
+ async wake(
683
+ id: string,
684
+ expected: ResidentState,
685
+ reason: string,
686
+ now: number,
687
+ ): Promise<ResidentState> {
688
+ return this.updatePursuit(id, expected, (state) => wakeResidentState(state, reason, now))
689
+ }
690
+
691
+ async settleObserved(
692
+ id: string,
693
+ expected: ResidentState,
694
+ decision: ResidentDecision,
695
+ observation: ResidentObservation,
696
+ now: number,
697
+ ): Promise<ResidentState> {
698
+ const checked = residentObservationSchema.parse(observation)
699
+ return this.updatePursuit(
700
+ id,
701
+ expected,
702
+ (state) => settleResidentState(state, decision, now),
703
+ false,
704
+ undefined,
705
+ checked,
706
+ )
707
+ }
708
+
709
+ /** Commit the step, observation and message intent together; delivery is separate. */
710
+ async settleWithMessage(
711
+ id: string,
712
+ expected: ResidentState,
713
+ decision: ResidentDecision,
714
+ message: ResidentMessageInput,
715
+ now: number,
716
+ observation?: ResidentObservation,
717
+ ): Promise<ResidentState> {
718
+ const input = residentMessageInputSchema.parse(message)
719
+ const disposition = residentDecisionSchema.parse(decision)
720
+ if (input.pursuitId !== id) throw new Error('Message must belong to the settling pursuit.')
721
+ const current = residentStateSchema.parse(expected)
722
+ const checked =
723
+ observation === undefined ? undefined : residentObservationSchema.parse(observation)
724
+ return this.updatePursuit(
725
+ id,
726
+ current,
727
+ (state) => settleResidentState(state, disposition, now),
728
+ false,
729
+ undefined,
730
+ checked,
731
+ input,
732
+ )
733
+ }
734
+
735
+ /** Enqueue host-authorized intent without invoking a transport or changing pursuit state. */
736
+ async enqueueMessage(
737
+ expected: ResidentAgendaState,
738
+ input: ResidentMessageInput,
739
+ ): Promise<ResidentOutboxMessage> {
740
+ const snapshot = this.checked(expected)
741
+ const message = residentMessageInputSchema.parse(input)
742
+ const current = await this.read()
743
+ if (!current || current.revision !== snapshot.revision) throw new ResidentConflictError()
744
+ const archived = current.outbox?.some((item) => item.id === message.id)
745
+ ? undefined
746
+ : await this.archivedMatch(current, (entry) =>
747
+ entry.messages.find((item) => item.id === message.id),
748
+ )
749
+ if (archived) this.assertArchivedIntent(archived, message, null)
750
+ const next = await this.change(snapshot, (state) => ({
751
+ ...state,
752
+ ...(!archived ? { outbox: appendResidentMessage(state, message) } : {}),
753
+ }))
754
+ const saved = archived ?? next.outbox?.find((candidate) => candidate.id === message.id)
755
+ if (!saved) throw new Error('Committed resident message is missing.')
756
+ return saved
757
+ }
758
+
759
+ /** Admit one delivery against the same agenda snapshot used by the host's gate. */
760
+ async claimMessage(
761
+ expected: ResidentAgendaState,
762
+ id: string,
763
+ now: number,
764
+ ): Promise<ResidentOutboxMessage> {
765
+ z.string().uuid().parse(id)
766
+ const next = await this.change(expected, (state) => {
767
+ const outbox = state.outbox ?? []
768
+ if (state.paused || outbox.some((message) => message.phase === 'sending'))
769
+ throw new ResidentConflictError()
770
+ const message = outbox.find((candidate) => candidate.id === id)
771
+ if (!message) throw new Error('Unknown resident message.')
772
+ const admitted = claimResidentOutboxMessage(message, now)
773
+ return {
774
+ ...state,
775
+ outbox: outbox.map((candidate) => (candidate.id === id ? admitted : candidate)),
776
+ }
777
+ })
778
+ const claim = next.outbox?.find((message) => message.id === id)
779
+ if (!claim) throw new Error('Claimed resident message is missing.')
780
+ return claim
781
+ }
782
+
783
+ /** Settle the exact delivery claim; unrelated agenda writes never repeat the transport. */
784
+ async settleMessage(
785
+ expected: ResidentOutboxMessage,
786
+ outcome: ResidentDeliveryOutcome,
787
+ now: number,
788
+ ): Promise<ResidentOutboxMessage> {
789
+ const claim = residentOutboxMessageSchema.parse(expected)
790
+ const checked = residentDeliveryOutcomeSchema.parse(outcome)
791
+ if (claim.tenantId !== this.tenantId || claim.agentKey !== this.agentKey)
792
+ throw new ResidentConflictError()
793
+ const validate = (state: ResidentAgendaState): ResidentOutboxMessage => {
794
+ const message = state.outbox?.find((candidate) => candidate.id === claim.id)
795
+ if (!message || message.revision !== claim.revision || message.claimId !== claim.claimId)
796
+ throw new ResidentConflictError()
797
+ return message
798
+ }
799
+ for (let attempt = 0; attempt < 8; attempt++) {
800
+ const agenda = await this.read()
801
+ if (agenda === null) throw new Error('Create the resident agenda first.')
802
+ validate(agenda)
803
+ try {
804
+ const next = await this.change(agenda, (state) => {
805
+ const current = validate(state)
806
+ const settled = settleResidentOutboxMessage(current, checked, now)
807
+ return {
808
+ ...state,
809
+ outbox: (state.outbox ?? []).map((message) =>
810
+ message.id === claim.id ? settled : message,
811
+ ),
812
+ }
813
+ })
814
+ const settled = next.outbox?.find((message) => message.id === claim.id)
815
+ if (!settled) throw new Error('Settled resident message is missing.')
816
+ return settled
817
+ } catch (error) {
818
+ if (!(error instanceof ResidentConflictError) || attempt === 7) throw error
819
+ }
820
+ }
821
+ throw new ResidentConflictError()
822
+ }
823
+
824
+ executionAt(id: string, expected: ResidentAgendaState): ResidentExecutionStore {
825
+ const state = this.checked(expected)
826
+ const pursuit = state.pursuits.find((p) => p.id === id)
827
+ if (!pursuit) throw new Error('Unknown resident pursuit.')
828
+ const execution = this.execution(id)
829
+ return {
830
+ read: async () => pursuit.state,
831
+ settle: (...args) => execution.settle(...args),
832
+ claim: (current, now) =>
833
+ this.updatePursuit(
834
+ id,
835
+ current,
836
+ (saved) => claimResidentState(saved, now),
837
+ true,
838
+ state.revision,
839
+ ),
840
+ }
841
+ }
842
+
843
+ execution(id: string): ResidentExecutionStore {
844
+ z.string().uuid().parse(id)
845
+ return {
846
+ read: async () => (await this.read())?.pursuits.find((p) => p.id === id)?.state ?? null,
847
+ claim: (expected, now) =>
848
+ this.updatePursuit(id, expected, (state) => claimResidentState(state, now), true),
849
+ settle: (expected, decision: ResidentDecision, now) =>
850
+ this.updatePursuit(id, expected, (state) => settleResidentState(state, decision, now)),
851
+ }
852
+ }
853
+ }