agenr 3.2.0 → 2026.6.2

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 (39) hide show
  1. package/CHANGELOG.md +104 -3
  2. package/README.md +40 -42
  3. package/dist/adapters/skeln/index.d.ts +629 -51
  4. package/dist/adapters/skeln/index.js +782 -2039
  5. package/dist/build-before-turn-artifact-NPUHVWFE.js +71 -0
  6. package/dist/build-recall-artifact-F3LS3PZX.js +62 -0
  7. package/dist/chunk-5AYIXQRF.js +4452 -0
  8. package/dist/{chunk-FMQTRTWE.js → chunk-5TIP2EPP.js} +1453 -2563
  9. package/dist/{chunk-5LADPJ4C.js → chunk-GAERET5Q.js} +138 -504
  10. package/dist/chunk-GF3PX3VM.js +41 -0
  11. package/dist/chunk-GKZQ5AG5.js +44 -0
  12. package/dist/chunk-LDJN7CVU.js +3231 -0
  13. package/dist/{chunk-ZYADFKX3.js → chunk-MC3C2XM5.js} +34 -1
  14. package/dist/{chunk-KL6X2E3I.js → chunk-NBS62ES5.js} +1168 -816
  15. package/dist/chunk-NSLTJBUC.js +270 -0
  16. package/dist/chunk-OJSIZDZD.js +9 -0
  17. package/dist/chunk-OWGQWQUP.js +45 -0
  18. package/dist/{chunk-ZAX3YSTU.js → chunk-Q5UTJXHZ.js} +2 -140
  19. package/dist/{chunk-TMDNFBBC.js → chunk-SOQW7356.js} +271 -1935
  20. package/dist/chunk-VBPYU7GO.js +597 -0
  21. package/dist/chunk-VTHBPXDQ.js +1750 -0
  22. package/dist/{chunk-UEGURBBW.js → chunk-XFJ4S4G2.js} +844 -39
  23. package/dist/chunk-Y5NB3FTH.js +106 -0
  24. package/dist/{chunk-6HY5F5FE.js → chunk-ZX55JBV2.js} +1704 -314
  25. package/dist/cli.js +1125 -9537
  26. package/dist/core/recall/index.d.ts +64 -6
  27. package/dist/core/recall/index.js +8 -1
  28. package/dist/internal-eval-server.js +9 -6
  29. package/dist/internal-recall-eval-server.js +9 -6
  30. package/dist/lifecycle-checkpoint-IAC5FCQU.js +154 -0
  31. package/dist/{ports-CpzWESmZ.d.ts → ports-C4QkwDBS.d.ts} +114 -69
  32. package/dist/scan-6JKPOQHD.js +6 -0
  33. package/dist/service-EKFACEN6.js +15 -0
  34. package/dist/service-RHNB5AEQ.js +861 -0
  35. package/dist/sink-AUAAWC5O.js +8 -0
  36. package/package.json +7 -4
  37. package/dist/adapters/openclaw/index.d.ts +0 -32
  38. package/dist/adapters/openclaw/index.js +0 -3112
  39. /package/dist/{chunk-GELCEVFA.js → chunk-5AXMFBHR.js} +0 -0
@@ -1,7 +1,7 @@
1
1
  import { TSchema } from 'typebox';
2
2
  import { AgentToolResult, AgentMessage } from '@earendil-works/pi-agent-core';
3
3
  import { C as ClaimSlotPolicyConfig, a as ClaimSlotPolicy } from '../../claim-slot-policy-CdrW_1l4.js';
4
- import { E as EntryType, b as RecallPorts, r as ProcedureDatabasePort, t as Entry, u as DatabasePort, v as EpisodeDatabasePort, w as EmbeddingPort, L as LlmPort } from '../../ports-CpzWESmZ.js';
4
+ import { D as DurableKind, b as RecallPorts, v as ProcedureDatabasePort, a as Durable, w as DurableUpdateInput, x as DatabasePort, y as EpisodeDatabasePort, z as EmbeddingPort, L as LlmPort } from '../../ports-C4QkwDBS.js';
5
5
 
6
6
  /** Minimal branch-entry shape needed for before-turn visibility filtering. */
7
7
  interface SkelnBranchEntryLike {
@@ -76,9 +76,9 @@ type AgenrFeatureFlagKey = (typeof AGENR_FEATURE_FLAG_KEYS)[number];
76
76
  /**
77
77
  * Sparse persisted feature-flag overrides.
78
78
  *
79
- * Only `true` values are written to disk. Explicit `false` is accepted during
80
- * parse and reflected in resolved runtime flags, but canonicalization strips
81
- * false entries because every flag defaults to off.
79
+ * Most flags default to off and are persisted only when explicitly enabled.
80
+ * `sessionTreeCompaction` defaults to on and is persisted only when explicitly
81
+ * disabled.
82
82
  */
83
83
  type AgenrFeatureFlagConfig = Partial<Record<AgenrFeatureFlagKey, boolean>>;
84
84
  /**
@@ -92,7 +92,7 @@ type AgenrFeatureFlags = Record<AgenrFeatureFlagKey, boolean>;
92
92
  interface ClaimExtractionConfig {
93
93
  enabled: boolean;
94
94
  confidenceThreshold: number;
95
- eligibleTypes: EntryType[];
95
+ eligibleTypes: DurableKind[];
96
96
  /** Maximum preview workers used by cleanup flows that parallelize claim extraction. Defaults to `10`. */
97
97
  concurrency?: number;
98
98
  }
@@ -109,6 +109,451 @@ interface BeforeTurnDeps {
109
109
  embedQuery?: (text: string) => Promise<number[]>;
110
110
  /** Optional runtime claim-slot-policy overrides used during claim-aware shaping. */
111
111
  slotPolicyConfig?: ClaimSlotPolicyConfig;
112
+ /** Optional semantic clock used for recall validity and recency decisions. */
113
+ now?: Date;
114
+ /**
115
+ * Optional lookup for active user memory directives.
116
+ *
117
+ * When wired, the service drops directive rows from injection and suppresses
118
+ * any surfaced durable that mentions a directive's blocked topic. Callers that
119
+ * omit it skip directive abstention entirely.
120
+ */
121
+ listActiveAbstainDirectives?: () => Promise<Durable[]>;
122
+ /**
123
+ * Optional lookup for active proactive directives with `topic:` triggers.
124
+ *
125
+ * When wired, the service may inject matching directives during before-turn
126
+ * selection before the abstain filter runs.
127
+ */
128
+ listActiveTopicProactiveDirectives?: () => Promise<Durable[]>;
129
+ }
130
+
131
+ /**
132
+ * Supported dreaming action identifiers.
133
+ */
134
+ type DreamActionType = "stale" | "merge" | "log_conflict" | "resolve_conflict" | "update_durable" | "insert_durable" | "supersede_durable" | "flag_review" | "skip";
135
+ /**
136
+ * Audit log record for one action emitted during a dreaming run.
137
+ */
138
+ interface DreamRunAction {
139
+ id: string;
140
+ runId: string;
141
+ actionType: DreamActionType;
142
+ durableIds: string[];
143
+ reasoning: string;
144
+ details?: Record<string, unknown> | null;
145
+ createdAt: string;
146
+ }
147
+
148
+ /**
149
+ * Core dreaming domain types.
150
+ */
151
+
152
+ /** Ordered list of supported dreaming run tiers. */
153
+ declare const DREAM_TIERS: readonly ["light", "standard", "deep"];
154
+
155
+ /** Union of supported dreaming run tiers. */
156
+ type DreamTier = (typeof DREAM_TIERS)[number];
157
+ /** Ordered list of supported dreaming pipeline stages. */
158
+ declare const DREAM_STAGES: readonly ["scan", "extract", "reconcile", "temporalize", "project", "prune", "apply"];
159
+
160
+ /** Union of supported dreaming pipeline stages. */
161
+ type DreamStage = (typeof DREAM_STAGES)[number];
162
+ /**
163
+ * Structured claim-key health snapshot captured before or after one pass.
164
+ */
165
+ interface ClaimKeyHealthSnapshot {
166
+ totalDurables: number;
167
+ activeDurables: number;
168
+ coverageCount: number;
169
+ coveragePct: number;
170
+ missingCount: number;
171
+ eligibleMissingCount: number;
172
+ malformedOrNoncanonicalCount: number;
173
+ suspectCanonicalCount: number;
174
+ entityFamilyGroupCount: number;
175
+ suspiciousSingletonAliasCount: number;
176
+ mixedGroupCount: number;
177
+ exactKeyMultiActiveClusterCount: number;
178
+ }
179
+ /**
180
+ * Aggregate repair counts captured during one reconcile run.
181
+ */
182
+ interface ReconcileRepairCounts {
183
+ identifiedNormalizations: number;
184
+ appliedNormalizations: number;
185
+ identifiedBackfills: number;
186
+ appliedBackfills: number;
187
+ identifiedMetadataRewrites: number;
188
+ appliedMetadataRewrites: number;
189
+ identifiedEntityFamilyConvergences: number;
190
+ appliedEntityFamilyConvergences: number;
191
+ proposalsEmitted: number;
192
+ skippedNoClaim: number;
193
+ skippedLowConfidence: number;
194
+ skippedCollision: number;
195
+ flaggedAmbiguousProposals: number;
196
+ }
197
+ /** Threshold-only cohort bucket used by shadow sibling-slot-resonance reporting. */
198
+ type ReconcileShadowBucket = "high_density_grounded_family" | "large_grounding_diluted_grounded_family" | "thin_grounded_family_tail" | "relaxed_one_sibling_stable_slot" | "other_grounded_family_alignment";
199
+ /** Stable machine-readable circuit-breaker categories for reconcile runs. */
200
+ type ReconcileCircuitBreakerKind = "claim_key_concentration" | "entity_prefix_concentration" | "collision_spike";
201
+ /** Summary counts for one threshold-only shadow-evaluation bucket. */
202
+ interface ReconcileShadowBucketSummary {
203
+ bucket: ReconcileShadowBucket;
204
+ candidateCount: number;
205
+ resonanceApplicableCount: number;
206
+ resonanceFiredCount: number;
207
+ shadowQualifiedCount: number;
208
+ }
209
+ /** Shadow-only sibling-slot-resonance summary captured for threshold-only supported cases. */
210
+ interface ReconcileSiblingSlotResonanceShadowSummary {
211
+ rule: {
212
+ supportClass: "trusted_family_grounded_alignment";
213
+ minFamilyReuseCount: number;
214
+ minGroundedRatio: number;
215
+ minConfidence: number;
216
+ requiresSiblingSlotResonance: true;
217
+ };
218
+ thresholdOnlyCandidateCount: number;
219
+ resonanceApplicableCount: number;
220
+ resonanceFiredCount: number;
221
+ shadowQualifiedCount: number;
222
+ resonanceFiredClaimKeys: string[];
223
+ shadowQualifiedClaimKeys: string[];
224
+ buckets: ReconcileShadowBucketSummary[];
225
+ }
226
+ /** Structured reconcile pass summary persisted on the dreaming run. */
227
+ interface ReconcilePassSummary {
228
+ executionStyle: "autonomous" | "targeted";
229
+ workingSet: {
230
+ includeInactive: boolean;
231
+ project: string | null;
232
+ type: string | null;
233
+ claimKeyPrefix: string | null;
234
+ durableIds: string[];
235
+ };
236
+ before: ClaimKeyHealthSnapshot;
237
+ after: ClaimKeyHealthSnapshot;
238
+ projectedAfter?: ClaimKeyHealthSnapshot;
239
+ counts: ReconcileRepairCounts;
240
+ shadowSiblingSlotResonance?: ReconcileSiblingSlotResonanceShadowSummary | null;
241
+ circuitBreaker?: {
242
+ kind: ReconcileCircuitBreakerKind;
243
+ message: string;
244
+ } | null;
245
+ }
246
+ /** Machine-readable reason one dreaming pipeline stage was skipped. */
247
+ type DreamStageSkipReason = "light_tier";
248
+ /** Structured record for a pipeline stage skipped by tier policy. */
249
+ interface DreamStageSkipSummary {
250
+ /** Pipeline stage skipped during the run. */
251
+ stage: DreamStage;
252
+ /** Stable reason the stage did not run. */
253
+ reason: DreamStageSkipReason;
254
+ }
255
+ /** Structured unresolved claim-key proposal persisted for later adjudication. */
256
+ type DreamProposalReviewStatus = "open" | "applied" | "rejected";
257
+ /** Structured unresolved claim-key proposal persisted for later adjudication. */
258
+ interface DreamRunProposal {
259
+ id: string;
260
+ runId: string;
261
+ groupId: string;
262
+ issueKind: string;
263
+ scope: "single_durable" | "cluster";
264
+ durableIds: string[];
265
+ currentClaimKeys: string[];
266
+ proposedClaimKeys: string[];
267
+ rationale: string;
268
+ confidence: number;
269
+ source: string;
270
+ eligibleForApply: boolean;
271
+ createdAt: string;
272
+ reviewStatus: DreamProposalReviewStatus;
273
+ reviewedAt: string | null;
274
+ reviewReason: string | null;
275
+ appliedActionCount: number;
276
+ }
277
+ /** Lifecycle states for one dreaming run. */
278
+ type DreamRunStatus = "running" | "completed" | "failed" | "aborted" | "budget_exhausted" | "cost_capped" | "no_work" | "stalled";
279
+ /** Evidence locator referenced by dreaming mutations. */
280
+ interface DreamEvidenceRef {
281
+ kind: "episode" | "ingest_log" | "durable" | "transcript";
282
+ locator: string;
283
+ observedAt?: string;
284
+ }
285
+ /** Structured summary of one extract stage execution. */
286
+ interface DreamExtractSummary {
287
+ episodesScanned: number;
288
+ candidatesEmitted: number;
289
+ newCandidates: number;
290
+ refineCandidates: number;
291
+ knownCandidates: number;
292
+ durablesInserted: number;
293
+ }
294
+ /** Structured summary of one temporalize stage execution. */
295
+ interface DreamTemporalizeSummary {
296
+ revisionsIdentified: number;
297
+ revisionsApplied: number;
298
+ revisionsSkipped: number;
299
+ }
300
+ /** Structured summary of one profile projection stage execution. */
301
+ interface DreamProjectSummary {
302
+ profileDurableCount: number;
303
+ directiveCount: number;
304
+ snapshotId: string | null;
305
+ applied: boolean;
306
+ }
307
+ /** Structured summary of one deterministic prune stage execution. */
308
+ interface DreamPruneSummary {
309
+ durablesScanned: number;
310
+ candidatesIdentified: number;
311
+ candidatesProtected: number;
312
+ /**
313
+ * Count of unprotected candidates eligible to be staled this run. The field
314
+ * keeps the `candidatesRetirable` name for backward compatibility with the
315
+ * dreaming-efficiency eval wire contract consumed by `agenr-evals`; it counts
316
+ * stale-eligible candidates and does not imply a separate retirement concept.
317
+ */
318
+ candidatesRetirable: number;
319
+ durablesStaled: number;
320
+ dryRun: boolean;
321
+ }
322
+ /** Compute-efficiency counters emitted for eval scoreboard reporting. */
323
+ interface DreamEfficiencySummary {
324
+ evidenceItemsRead: number;
325
+ synthesizedDurableMutations: number;
326
+ costPerSynthesizedDurableUsd: number | null;
327
+ profileInjectionTokenEstimate: number;
328
+ recomputeRatio: number;
329
+ }
330
+ /** Scan delta describing unsynthesized evidence since the last successful run. */
331
+ interface DreamScanSummary {
332
+ episodesSinceLastRun: number;
333
+ ingestFilesSinceLastRun: number;
334
+ durablesCreatedSinceLastRun: number;
335
+ evidenceRefs: DreamEvidenceRef[];
336
+ unsynthesizedImportanceSum: number;
337
+ }
338
+ /** Minimal persisted completion summary for a dreaming run. */
339
+ interface DreamCompletionSummary {
340
+ actions_taken: number;
341
+ /** True when an apply run intentionally skipped the pre-apply database backup. */
342
+ backupSkipped?: boolean;
343
+ /** Pipeline stages intentionally skipped by tier policy. */
344
+ stages_skipped?: DreamStageSkipSummary[];
345
+ durables_skipped: Array<{
346
+ durable_id?: string;
347
+ reason: string;
348
+ }>;
349
+ observations: string[];
350
+ recommendations: string[];
351
+ scan?: DreamScanSummary;
352
+ extract?: DreamExtractSummary;
353
+ reconcile?: ReconcilePassSummary;
354
+ temporalize?: DreamTemporalizeSummary;
355
+ project?: DreamProjectSummary;
356
+ prune?: DreamPruneSummary;
357
+ efficiency?: DreamEfficiencySummary;
358
+ }
359
+
360
+ /**
361
+ * Narrative evidence row surfaced to the extract stage from one episode.
362
+ */
363
+ interface DreamEpisodeEvidence {
364
+ id: string;
365
+ summary: string;
366
+ startedAt: string;
367
+ endedAt: string | null;
368
+ sessionId: string | null;
369
+ project: string | null;
370
+ }
371
+ /**
372
+ * Persisted dreaming run metadata returned by history and status queries.
373
+ */
374
+ interface DreamRunRecord {
375
+ id: string;
376
+ tier: DreamTier;
377
+ project: string | null;
378
+ startedAt: string;
379
+ completedAt: string | null;
380
+ status: DreamRunStatus;
381
+ inputTokens: number;
382
+ outputTokens: number;
383
+ estimatedCostUsd: number;
384
+ model: string | null;
385
+ actionsTaken: number;
386
+ actionsSkipped: number;
387
+ durablesStaled: number;
388
+ summaryJson: DreamCompletionSummary | null;
389
+ error: string | null;
390
+ dryRun: boolean;
391
+ config: Record<string, unknown> | null;
392
+ }
393
+ /**
394
+ * Persisted profile snapshot generated by the dreaming project stage.
395
+ */
396
+ interface DreamProfileSnapshot {
397
+ id: string;
398
+ durableIds: string[];
399
+ directiveIds: string[];
400
+ asOf: string;
401
+ contentHash: string;
402
+ runId: string | null;
403
+ createdAt: string;
404
+ }
405
+ /**
406
+ * Aggregate corpus health summary used by dreaming status tools.
407
+ */
408
+ interface DreamHealthStats {
409
+ total: number;
410
+ byType: Record<string, number>;
411
+ claimKeyLifecycle: {
412
+ trusted: number;
413
+ tentative: number;
414
+ unresolved: number;
415
+ noKey: number;
416
+ };
417
+ /** Count of durable unresolved dreaming proposals awaiting review. */
418
+ proposalBacklogCount: number;
419
+ /** Open proposals that are already safe to apply. */
420
+ eligibleProposalBacklogCount: number;
421
+ /** Oldest still-open proposal creation timestamp, when one exists. */
422
+ oldestOpenProposalCreatedAt: string | null;
423
+ recency: {
424
+ last7: number;
425
+ last30: number;
426
+ d30To90: number;
427
+ d90Plus: number;
428
+ };
429
+ recall: {
430
+ never: number;
431
+ oneToFive: number;
432
+ fivePlus: number;
433
+ };
434
+ quality: {
435
+ high: number;
436
+ medium: number;
437
+ low: number;
438
+ average: number;
439
+ };
440
+ }
441
+ /**
442
+ * Query options for the global proposal backlog view.
443
+ */
444
+ interface DreamProposalBacklogQuery {
445
+ state?: DreamProposalReviewStatus | "all";
446
+ issueKind?: string;
447
+ eligibleOnly?: boolean;
448
+ durableId?: string;
449
+ limit?: number;
450
+ offset?: number;
451
+ }
452
+ /**
453
+ * Global backlog row that joins one proposal to its originating run metadata.
454
+ */
455
+ interface DreamProposalBacklogItem {
456
+ proposal: DreamRunProposal;
457
+ runPassType: DreamTier;
458
+ runStartedAt: string;
459
+ runStatus: DreamRunStatus;
460
+ runDryRun: boolean;
461
+ }
462
+ /**
463
+ * Milestone 1 dreaming persistence boundary.
464
+ */
465
+ interface DreamPort {
466
+ getDailyCost(now?: Date): Promise<number>;
467
+ createRun(run: {
468
+ tier: DreamTier;
469
+ project?: string;
470
+ model?: string | null;
471
+ dryRun: boolean;
472
+ config?: Record<string, unknown> | null;
473
+ startedAt?: string;
474
+ }): Promise<string>;
475
+ completeRun(runId: string, result: {
476
+ status: DreamRunStatus;
477
+ inputTokens: number;
478
+ outputTokens: number;
479
+ estimatedCostUsd: number;
480
+ actionsTaken: number;
481
+ actionsSkipped: number;
482
+ durablesStaled: number;
483
+ summaryJson?: DreamCompletionSummary | null;
484
+ error?: string | null;
485
+ completedAt?: string;
486
+ }): Promise<void>;
487
+ logRunAction(action: DreamRunAction): Promise<void>;
488
+ getLastRun(): Promise<DreamRunRecord | null>;
489
+ getRunHistory(limit?: number): Promise<DreamRunRecord[]>;
490
+ /** Returns the most recent applied (non-dry-run) `light` runs, newest first. */
491
+ getRecentAppliedLightRuns(limit: number): Promise<DreamRunRecord[]>;
492
+ getRunActions(runId: string): Promise<DreamRunAction[]>;
493
+ getRunProposals(runId: string): Promise<DreamRunProposal[]>;
494
+ getProposal(proposalId: string): Promise<DreamRunProposal | null>;
495
+ reviewProposal(input: {
496
+ proposalId: string;
497
+ status: Exclude<DreamProposalReviewStatus, "open">;
498
+ reason: string;
499
+ reviewedAt?: string;
500
+ appliedActionCount?: number;
501
+ }): Promise<boolean>;
502
+ listProposalBacklog(query?: DreamProposalBacklogQuery): Promise<DreamProposalBacklogItem[]>;
503
+ getHealthStats(now?: Date): Promise<DreamHealthStats>;
504
+ getDurable(durableId: string): Promise<Durable | null>;
505
+ getDurables(durableIds: string[]): Promise<Durable[]>;
506
+ closeDurableValidity(durableId: string, reason?: string): Promise<boolean>;
507
+ updateDurable(durableId: string, fields: DurableUpdateInput, options?: {
508
+ includeInactive?: boolean;
509
+ }): Promise<boolean>;
510
+ listReconcileDurables(query: {
511
+ project?: string;
512
+ type?: string;
513
+ claimKeyPrefix?: string;
514
+ durableIds?: string[];
515
+ includeInactive?: boolean;
516
+ }): Promise<Durable[]>;
517
+ /** Reads recent episode narrative evidence newer than one timestamp. */
518
+ listEpisodeEvidenceSince(since: string, options?: {
519
+ project?: string;
520
+ limit?: number;
521
+ }): Promise<DreamEpisodeEvidence[]>;
522
+ /** Lists live host-store durables written during one episode session window. */
523
+ listSessionHostStoreDurables(sessionId: string, startedAt: string, endedAt: string): Promise<Durable[]>;
524
+ /** Loads active durables that share one canonical claim key (context-lookup). */
525
+ findActiveDurablesByClaimKey(claimKey: string): Promise<Durable[]>;
526
+ /** Returns the subset of normalized content hashes that already exist among active durables. */
527
+ findExistingNormContentHashes(hashes: string[]): Promise<Set<string>>;
528
+ /** Inserts one new durable row written by the extract or temporalize stages. */
529
+ insertDurable(durable: Durable, embedding: number[], contentHash: string): Promise<string>;
530
+ /** Links one active durable to the newer durable that supersedes it. */
531
+ supersedeDurable(oldDurableId: string, newDurableId: string, kind?: string, reason?: string): Promise<boolean>;
532
+ logRunProposal(proposal: DreamRunProposal): Promise<void>;
533
+ countEpisodesSince(since: string, project?: string): Promise<number>;
534
+ countIngestFilesSince(since: string): Promise<number>;
535
+ countDurablesCreatedSince(since: string, project?: string): Promise<number>;
536
+ sumDurableImportanceCreatedSince(since: string, project?: string): Promise<number>;
537
+ createProfileSnapshot(snapshot: DreamProfileSnapshot): Promise<void>;
538
+ getActiveProfileSnapshot(): Promise<DreamProfileSnapshot | null>;
539
+ updateDreamState(input: {
540
+ lastSuccessfulRunAt?: string;
541
+ unsynthesizedImportanceSum?: number;
542
+ activeProfileSnapshotId?: string;
543
+ updatedAt: string;
544
+ }): Promise<void>;
545
+ /** Attempts to acquire the singleton dreaming run lock row. */
546
+ tryAcquireRunLock(holderToken: string): Promise<boolean>;
547
+ /** Refreshes the dreaming run lock heartbeat when the holder token still matches. */
548
+ heartbeatRunLock(holderToken: string): Promise<boolean>;
549
+ /** Releases the dreaming run lock when the holder token still matches. */
550
+ releaseRunLock(holderToken: string): Promise<void>;
551
+ /**
552
+ * Runs a callback inside a single write transaction so a group of related
553
+ * dreaming writes either all commit or all roll back. The callback receives a
554
+ * port bound to the transaction; nested executors fall back to running inline.
555
+ */
556
+ withTransaction<T>(fn: (tx: DreamPort) => Promise<T>): Promise<T>;
112
557
  }
113
558
 
114
559
  /**
@@ -119,6 +564,59 @@ interface EntryRecallEvent {
119
564
  sessionKey?: string;
120
565
  recalledAt: string;
121
566
  }
567
+ /**
568
+ * Recall summary returned by the trace read model.
569
+ */
570
+ interface EntryTraceRecallSummary {
571
+ /** Total persisted recall events for the durable. */
572
+ totalCount: number;
573
+ /** Most recent recall events, ordered newest first. */
574
+ recentEvents: EntryRecallEvent[];
575
+ }
576
+ /**
577
+ * Dreaming audit action linked to one traced durable.
578
+ */
579
+ interface EntryTraceDreamAction {
580
+ id: string;
581
+ runId: string;
582
+ actionType: string;
583
+ reasoning: string;
584
+ details?: Record<string, unknown> | null;
585
+ createdAt: string;
586
+ }
587
+ /**
588
+ * Profile snapshot that included one traced durable.
589
+ */
590
+ interface EntryTraceProfileSnapshot {
591
+ id: string;
592
+ asOf: string;
593
+ runId: string | null;
594
+ createdAt: string;
595
+ role: "profile" | "directive";
596
+ }
597
+ /**
598
+ * Provenance facts surfaced by the trace read model.
599
+ */
600
+ interface EntryTraceProvenance {
601
+ sourceFile?: string;
602
+ sourceContext?: string;
603
+ claimKeySource?: string;
604
+ claimSupportLocator?: string;
605
+ claimSupportObservedAt?: string;
606
+ project?: string;
607
+ userId?: string;
608
+ }
609
+ /**
610
+ * One chronological audit event in a durable trace timeline.
611
+ */
612
+ interface EntryTraceTimelineEvent {
613
+ at: string;
614
+ kind: "created" | "updated" | "dream" | "recall" | "profile";
615
+ label: string;
616
+ detail?: string;
617
+ runId?: string;
618
+ actionType?: string;
619
+ }
122
620
  /**
123
621
  * Narrow claim-family lineage view returned by trace surfaces.
124
622
  */
@@ -130,17 +628,21 @@ interface ClaimFamily {
130
628
  /** Human-readable explanation of how the slot policy was chosen. */
131
629
  slotPolicyReason?: string;
132
630
  /** Family rows ordered oldest-first for lineage inspection. */
133
- entries: Entry[];
631
+ entries: Durable[];
134
632
  }
135
633
  /**
136
- * Minimal provenance view available from the current v1 schema.
634
+ * Unified provenance and audit view for one durable.
137
635
  */
138
636
  interface EntryTrace {
139
- entry: Entry;
140
- supersededBy?: Entry;
141
- supersedes: Entry[];
637
+ entry: Durable;
638
+ supersededBy?: Durable;
639
+ supersedes: Durable[];
142
640
  claimFamily?: ClaimFamily;
143
- recallEvents: EntryRecallEvent[];
641
+ recall: EntryTraceRecallSummary;
642
+ provenance: EntryTraceProvenance;
643
+ dreamActions: EntryTraceDreamAction[];
644
+ profileSnapshots: EntryTraceProfileSnapshot[];
645
+ timeline: EntryTraceTimelineEvent[];
144
646
  }
145
647
  /**
146
648
  * Aggregate memory status facts used by host memory runtimes.
@@ -160,13 +662,13 @@ interface MemoryRepository {
160
662
  * @param subject - Free-form subject text to resolve.
161
663
  * @returns Matching entry, or `null` when no match exists.
162
664
  */
163
- findEntryBySubject(subject: string): Promise<Entry | null>;
665
+ findEntryBySubject(subject: string): Promise<Durable | null>;
164
666
  /**
165
667
  * Finds the most recently created entry from any state.
166
668
  *
167
669
  * @returns Newest entry, or `null` when none exist.
168
670
  */
169
- findMostRecentEntry(): Promise<Entry | null>;
671
+ findMostRecentEntry(): Promise<Durable | null>;
170
672
  /**
171
673
  * Loads the current trace view for one entry.
172
674
  *
@@ -632,7 +1134,7 @@ interface ResolvedWorkingScope extends WorkingScope {
632
1134
  /**
633
1135
  * Artifact kinds accepted by schema v12.
634
1136
  */
635
- declare const SESSION_ARTIFACT_KINDS: readonly ["continuity_summary", "recent_session", "compaction_checkpoint", "branch_abandonment", "session_episode"];
1137
+ declare const SESSION_ARTIFACT_KINDS: readonly ["compaction_checkpoint", "branch_abandonment", "session_episode"];
636
1138
  /**
637
1139
  * Host transition reasons that create session-lineage edges.
638
1140
  */
@@ -1365,6 +1867,15 @@ interface WorkingMemoryService {
1365
1867
  renderProjection(input: string | WorkingProjectionRequest): Promise<WorkingContextProjection>;
1366
1868
  }
1367
1869
 
1870
+ /** Active profile snapshot metadata used by session-start selection. */
1871
+ interface SessionStartProfileSnapshot {
1872
+ id: string;
1873
+ durableIds: string[];
1874
+ directiveIds: string[];
1875
+ asOf: string;
1876
+ runId: string | null;
1877
+ createdAt: string;
1878
+ }
1368
1879
  /**
1369
1880
  * Feature-scoped durable-memory lookup contract used by session-start selection.
1370
1881
  */
@@ -1375,7 +1886,21 @@ interface SessionStartRepository {
1375
1886
  * @param limit - Maximum number of core entries to return.
1376
1887
  * @returns Ordered active core entries.
1377
1888
  */
1378
- listCoreEntries(limit: number): Promise<Entry[]>;
1889
+ listCoreEntries(limit: number, now?: Date): Promise<Durable[]>;
1890
+ /**
1891
+ * Loads the active profile snapshot when it is fresh enough.
1892
+ *
1893
+ * @param maxAgeMs - Maximum snapshot age in milliseconds.
1894
+ * @returns Fresh active snapshot, or null.
1895
+ */
1896
+ getActiveProfileSnapshot(maxAgeMs: number, now?: Date): Promise<SessionStartProfileSnapshot | null>;
1897
+ /**
1898
+ * Hydrates active durables by id while preserving the caller's id order.
1899
+ *
1900
+ * @param ids - Ordered durable ids to hydrate.
1901
+ * @returns Hydrated active durables in requested order.
1902
+ */
1903
+ listEntriesByIds(ids: string[]): Promise<Durable[]>;
1379
1904
  }
1380
1905
  /**
1381
1906
  * Dependencies needed by the app-layer session-start service.
@@ -1387,6 +1912,20 @@ interface SessionStartDeps {
1387
1912
  recall: RecallPorts;
1388
1913
  /** Optional runtime claim-slot-policy overrides used during claim-aware shaping. */
1389
1914
  slotPolicyConfig?: ClaimSlotPolicyConfig;
1915
+ /** Optional semantic clock used for validity, freshness, and recall decisions. */
1916
+ now?: Date;
1917
+ /**
1918
+ * Optional lookup for active user memory directives.
1919
+ *
1920
+ * When wired, the service drops directive rows from injection and suppresses
1921
+ * any surfaced durable that mentions a directive's blocked topic. Callers that
1922
+ * omit it skip directive abstention entirely.
1923
+ */
1924
+ listActiveAbstainDirectives?: () => Promise<Durable[]>;
1925
+ /** Optional lookup for proactive session-start directives. */
1926
+ listActiveProactiveDirectives?: () => Promise<Durable[]>;
1927
+ /** Optional session-memory repository used for predecessor artifact recall. */
1928
+ sessionMemoryRepository?: SessionMemoryRepository;
1390
1929
  }
1391
1930
 
1392
1931
  /**
@@ -1438,6 +1977,13 @@ interface PluginWorkingContextMemoryPolicyConfig {
1438
1977
  /** Enables or disables automatic working-context injection. Defaults to true when working memory is enabled. */
1439
1978
  enabled?: boolean;
1440
1979
  }
1980
+ /**
1981
+ * Episode-write overrides for automatic OpenClaw episode capture.
1982
+ */
1983
+ interface PluginEpisodeMemoryPolicyConfig {
1984
+ /** Enables or disables automatic episode writes. Defaults to true. */
1985
+ enabled?: boolean;
1986
+ }
1441
1987
  /**
1442
1988
  * Memory-policy settings shared by host plugin adapters, including injection knobs.
1443
1989
  */
@@ -1448,6 +1994,8 @@ interface PluginInjectionMemoryPolicyConfig extends PluginMemoryPolicyConfig {
1448
1994
  beforeTurn?: PluginBeforeTurnMemoryPolicyConfig;
1449
1995
  /** Working-context overrides for transient per-turn WIP injection. */
1450
1996
  workingContext?: PluginWorkingContextMemoryPolicyConfig;
1997
+ /** Episode-write overrides for automatic OpenClaw/Skeln episode capture. */
1998
+ episodes?: PluginEpisodeMemoryPolicyConfig;
1451
1999
  }
1452
2000
  /**
1453
2001
  * Infrastructure path overrides shared by host plugin adapters.
@@ -1490,6 +2038,7 @@ interface PluginMemoryRuntimeServices {
1490
2038
  episodes: EpisodeDatabasePort;
1491
2039
  procedures: ProcedureDatabasePort;
1492
2040
  memory: MemoryRepository;
2041
+ dreaming: DreamPort;
1493
2042
  workingMemoryRepository?: WorkingMemoryRepository;
1494
2043
  sessionMemoryRepository?: SessionMemoryRepository;
1495
2044
  sessionStart: SessionStartDeps;
@@ -1588,33 +2137,51 @@ interface ModelConfig {
1588
2137
  model?: string;
1589
2138
  }
1590
2139
  /**
1591
- * Per-pass surgeon configuration.
2140
+ * Prune-stage protection configuration for dreaming runs.
1592
2141
  */
1593
- interface SurgeonPassConfig {
1594
- /** Protect entries recalled within this many days. */
2142
+ interface DreamingPruneConfig {
2143
+ /** Protect durables recalled within this many days. */
1595
2144
  protectRecalledDays?: number;
1596
- /** Protect entries at or above this importance. */
2145
+ /** Protect durables at or above this importance. */
1597
2146
  protectMinImportance?: number;
1598
- /** Skip entries evaluated by surgeon in the last N days. */
1599
- skipRecentlyEvaluatedDays?: number;
1600
2147
  }
1601
2148
  /**
1602
- * Surgeon module configuration persisted in `config.json`.
2149
+ * Dreaming module configuration persisted in `config.json`.
1603
2150
  */
1604
- interface SurgeonConfig {
1605
- /** Model override for surgeon runs. */
2151
+ interface DreamingConfig {
2152
+ /** Model override for dreaming runs. */
1606
2153
  model?: ModelConfig;
1607
- /** Maximum cost per run in USD. */
1608
- costCap?: number;
1609
- /** Maximum total surgeon cost in the last 24 hours. */
2154
+ /** Maximum total dreaming cost in the last 24 hours. */
1610
2155
  dailyCostCap?: number;
1611
- /** Context token limit override. */
1612
- contextLimit?: number;
1613
- /** Custom instructions appended to the surgeon system prompt. */
1614
- customInstructions?: string;
1615
- /** Per-pass configuration. */
1616
- passes?: {
1617
- retirement?: SurgeonPassConfig;
2156
+ tiers?: {
2157
+ light?: {
2158
+ enabled?: boolean;
2159
+ };
2160
+ standard?: {
2161
+ enabled?: boolean;
2162
+ };
2163
+ deep?: {
2164
+ enabled?: boolean;
2165
+ intervalHours?: number;
2166
+ };
2167
+ };
2168
+ stages?: {
2169
+ extract?: {
2170
+ maxSessionsPerRun?: number;
2171
+ lightMaxSessionsPerRun?: number;
2172
+ contextLookup?: {
2173
+ enabled?: boolean;
2174
+ };
2175
+ };
2176
+ project?: {
2177
+ maxProfileDurables?: number;
2178
+ };
2179
+ prune?: DreamingPruneConfig;
2180
+ };
2181
+ triggers?: {
2182
+ postSessionLightDream?: boolean;
2183
+ importanceThreshold?: number;
2184
+ minIntervalMinutes?: number;
1618
2185
  };
1619
2186
  }
1620
2187
  /**
@@ -1657,8 +2224,8 @@ interface AgenrConfigInput {
1657
2224
  crossEncoderModel?: ModelConfig;
1658
2225
  /** Best-effort claim-key extraction settings. */
1659
2226
  claimExtraction?: AgenrClaimExtractionConfig;
1660
- /** Surgeon module configuration. */
1661
- surgeon?: SurgeonConfig;
2227
+ /** Dreaming module configuration. */
2228
+ dreaming?: DreamingConfig;
1662
2229
  /** Staged rollout feature flags. All default to false. */
1663
2230
  features?: AgenrFeatureFlagConfig;
1664
2231
  /** Database file path. */
@@ -1907,6 +2474,18 @@ interface AgenrSkelnMemoryController {
1907
2474
  executeWorkCommand(context: ExtensionContext, params: AgenrSkelnWorkCommandParams): Promise<AgenrSkelnWorkCommandOutcome>;
1908
2475
  }
1909
2476
 
2477
+ /**
2478
+ * Tracks lifecycle intake writes that prompt injection depends on.
2479
+ */
2480
+ interface SessionLifecycleIntakeTracker {
2481
+ /** Records one pending lifecycle intake promise for the session identity. */
2482
+ track(sessionId: string | undefined, sessionKey: string | undefined, work: Promise<void>): Promise<void>;
2483
+ /** Waits for any pending lifecycle intake for the session identity. */
2484
+ wait(sessionId: string | undefined, sessionKey: string | undefined): Promise<void>;
2485
+ /** Waits for pending intake, then clears tracked state for the session identity. */
2486
+ clear(sessionId: string | undefined, sessionKey: string | undefined): Promise<void>;
2487
+ }
2488
+
1910
2489
  /**
1911
2490
  * Structured tracking facts returned by the session-start tracker.
1912
2491
  */
@@ -1932,21 +2511,18 @@ interface SessionStartTracker {
1932
2511
  * @returns Tracking facts for the attempted session-start event.
1933
2512
  */
1934
2513
  consume(sessionId?: string, sessionKey?: string): SessionStartConsumeResult;
1935
- /**
1936
- * Remembers a session-start transition emitted by the host.
1937
- *
1938
- * @param sessionId - New ephemeral host session identifier.
1939
- * @param sessionKey - Stable host session key for the active lane.
1940
- * @param resumedFrom - Previous session identifier when the host provides it.
1941
- */
1942
- rememberSessionStart(sessionId?: string, sessionKey?: string, resumedFrom?: string): void;
1943
- /**
1944
- * Returns the predecessor session identifier remembered for a new session.
1945
- *
1946
- * @param sessionId - New ephemeral host session identifier lookup.
1947
- * @returns Previous session identifier, or `undefined` when unavailable.
1948
- */
1949
- getResumedFrom(sessionId?: string): string | undefined;
2514
+ }
2515
+
2516
+ /**
2517
+ * Tracks which compaction artifacts were already injected into prompts.
2518
+ */
2519
+ interface CompactionPromptTracker {
2520
+ /** Returns whether one artifact should be injected for the active session. */
2521
+ shouldInject(sessionId: string | undefined, sessionKey: string | undefined, artifactSourceId: string): boolean;
2522
+ /** Records one injected compaction artifact for the active session. */
2523
+ markInjected(sessionId: string | undefined, sessionKey: string | undefined, artifactSourceId: string): void;
2524
+ /** Clears tracked compaction prompt state for one session identity. */
2525
+ clear(sessionId: string | undefined, sessionKey: string | undefined): void;
1950
2526
  }
1951
2527
 
1952
2528
  /** Describes one agenr memory surface observed during a prompt turn. */
@@ -1985,6 +2561,8 @@ interface AgenrSkelnBeforeAgentStartResult {
1985
2561
  interface AgenrSkelnBeforeAgentStartDeps {
1986
2562
  servicesPromise: Promise<AgenrSkelnServices>;
1987
2563
  sessionStartTracker: SessionStartTracker;
2564
+ compactionPromptTracker: CompactionPromptTracker;
2565
+ lifecycleIntakeTracker: SessionLifecycleIntakeTracker;
1988
2566
  resolveScope: (context: ExtensionContext) => Promise<AgenrSkelnSessionScope>;
1989
2567
  }
1990
2568
  /**