@jungjaehoon/mama-core 1.5.0 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/README.md +48 -10
  2. package/db/migrations/032-add-memory-provenance-columns.sql +21 -0
  3. package/db/migrations/033-create-model-runs-and-tool-traces.sql +53 -0
  4. package/db/migrations/034-add-connector-event-scope-columns.sql +14 -0
  5. package/db/migrations/035-create-twin-edges.sql +63 -0
  6. package/db/migrations/036-create-agent-situation-packets.sql +61 -0
  7. package/db/migrations/037-create-context-packets.sql +32 -0
  8. package/dist/agent-graph/alias-write.d.ts +3 -0
  9. package/dist/agent-graph/alias-write.js +231 -0
  10. package/dist/agent-graph/entity-resolve.d.ts +3 -0
  11. package/dist/agent-graph/entity-resolve.js +275 -0
  12. package/dist/agent-graph/errors.d.ts +4 -0
  13. package/dist/agent-graph/errors.js +11 -0
  14. package/dist/agent-graph/graph-query.d.ts +5 -0
  15. package/dist/agent-graph/graph-query.js +359 -0
  16. package/dist/agent-graph/index.d.ts +6 -0
  17. package/dist/agent-graph/index.js +22 -0
  18. package/dist/agent-graph/types.d.ts +162 -0
  19. package/dist/agent-graph/types.js +3 -0
  20. package/dist/agent-situation/builder.d.ts +8 -0
  21. package/dist/agent-situation/builder.js +239 -0
  22. package/dist/agent-situation/cache-key.d.ts +4 -0
  23. package/dist/agent-situation/cache-key.js +64 -0
  24. package/dist/agent-situation/index.d.ts +7 -0
  25. package/dist/agent-situation/index.js +28 -0
  26. package/dist/agent-situation/packet-store.d.ts +27 -0
  27. package/dist/agent-situation/packet-store.js +228 -0
  28. package/dist/agent-situation/ranking-policy.d.ts +18 -0
  29. package/dist/agent-situation/ranking-policy.js +75 -0
  30. package/dist/agent-situation/source-readers.d.ts +52 -0
  31. package/dist/agent-situation/source-readers.js +300 -0
  32. package/dist/agent-situation/types.d.ts +195 -0
  33. package/dist/agent-situation/types.js +3 -0
  34. package/dist/cases/search-rollup.d.ts +4 -0
  35. package/dist/cases/search-rollup.js +84 -0
  36. package/dist/cases/wiki-page-index.js +6 -2
  37. package/dist/connectors/event-index.d.ts +1 -0
  38. package/dist/connectors/event-index.js +19 -4
  39. package/dist/connectors/raw-query.d.ts +18 -0
  40. package/dist/connectors/raw-query.js +305 -0
  41. package/dist/connectors/types.d.ts +40 -0
  42. package/dist/context-compile/boundary-defaults.d.ts +12 -0
  43. package/dist/context-compile/boundary-defaults.js +105 -0
  44. package/dist/context-compile/compiler-policy.d.ts +39 -0
  45. package/dist/context-compile/compiler-policy.js +147 -0
  46. package/dist/context-compile/compiler.d.ts +18 -0
  47. package/dist/context-compile/compiler.js +401 -0
  48. package/dist/context-compile/index.d.ts +9 -0
  49. package/dist/context-compile/index.js +25 -0
  50. package/dist/context-compile/packet-store.d.ts +9 -0
  51. package/dist/context-compile/packet-store.js +255 -0
  52. package/dist/context-compile/ref.d.ts +7 -0
  53. package/dist/context-compile/ref.js +102 -0
  54. package/dist/context-compile/source-readers.d.ts +69 -0
  55. package/dist/context-compile/source-readers.js +707 -0
  56. package/dist/context-compile/types.d.ts +138 -0
  57. package/dist/context-compile/types.js +11 -0
  58. package/dist/context-compile/visibility.d.ts +21 -0
  59. package/dist/context-compile/visibility.js +200 -0
  60. package/dist/db-adapter/node-sqlite-adapter.d.ts +9 -0
  61. package/dist/db-adapter/node-sqlite-adapter.js +207 -0
  62. package/dist/db-manager.d.ts +8 -1
  63. package/dist/db-manager.js +53 -5
  64. package/dist/edges/ref-validation.d.ts +8 -0
  65. package/dist/edges/ref-validation.js +301 -0
  66. package/dist/edges/store.d.ts +10 -0
  67. package/dist/edges/store.js +343 -0
  68. package/dist/edges/types.d.ts +88 -0
  69. package/dist/edges/types.js +18 -0
  70. package/dist/embeddings.d.ts +3 -0
  71. package/dist/embeddings.js +49 -9
  72. package/dist/entities/store.d.ts +4 -1
  73. package/dist/entities/store.js +206 -78
  74. package/dist/entities/types.d.ts +5 -1
  75. package/dist/entities/types.js +1 -1
  76. package/dist/index.d.ts +18 -3
  77. package/dist/index.js +54 -4
  78. package/dist/mama-api.d.ts +32 -35
  79. package/dist/mama-api.js +173 -22
  80. package/dist/memory/api.d.ts +17 -56
  81. package/dist/memory/api.js +494 -52
  82. package/dist/memory/event-store.d.ts +3 -0
  83. package/dist/memory/event-store.js +21 -2
  84. package/dist/memory/provenance-audit.d.ts +22 -0
  85. package/dist/memory/provenance-audit.js +112 -0
  86. package/dist/memory/provenance-query.d.ts +11 -0
  87. package/dist/memory/provenance-query.js +193 -0
  88. package/dist/memory/provenance.d.ts +29 -0
  89. package/dist/memory/provenance.js +137 -0
  90. package/dist/memory/scope-backfill.d.ts +17 -0
  91. package/dist/memory/scope-backfill.js +77 -0
  92. package/dist/memory/types.d.ts +87 -14
  93. package/dist/model-runs/store.d.ts +13 -0
  94. package/dist/model-runs/store.js +457 -0
  95. package/dist/model-runs/tool-trace-store.d.ts +4 -0
  96. package/dist/model-runs/tool-trace-store.js +114 -0
  97. package/dist/model-runs/types.d.ts +69 -0
  98. package/dist/model-runs/types.js +5 -0
  99. package/dist/runtime/trusted-provenance.d.ts +3 -0
  100. package/dist/runtime/trusted-provenance.js +6 -0
  101. package/dist/search/search-quality.d.ts +36 -0
  102. package/dist/search/search-quality.js +29 -0
  103. package/package.json +11 -3
@@ -0,0 +1,162 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
2
+ import type { EntityAlias, EntityAliasLabelType, EntityNode } from '../entities/types.js';
3
+ import type { TwinEdgeRecord, TwinEdgeType, TwinProjectRef, TwinRef, TwinScopeRef } from '../edges/types.js';
4
+ export type AgentGraphAdapter = Pick<DatabaseAdapter, 'prepare' | 'transaction'>;
5
+ export interface AgentGraphEdgeFilters {
6
+ edge_types?: TwinEdgeType[];
7
+ }
8
+ export interface ResolveEntityInput {
9
+ label: string;
10
+ scopes?: TwinScopeRef[];
11
+ connectors?: string[];
12
+ project_refs?: TwinProjectRef[];
13
+ tenant_id?: string | null;
14
+ context_refs?: TwinRef[];
15
+ limit?: number;
16
+ as_of_ms?: number | null;
17
+ }
18
+ export interface ResolvedEntityCandidate {
19
+ entity: EntityNode;
20
+ matched_label: string;
21
+ match_source: 'preferred_label' | 'alias' | 'observation';
22
+ score: number;
23
+ }
24
+ export interface ResolveEntityResult {
25
+ entity: EntityNode | null;
26
+ candidates: ResolvedEntityCandidate[];
27
+ }
28
+ export interface GraphNeighborhoodInput {
29
+ ref: TwinRef;
30
+ depth?: number;
31
+ scopes?: TwinScopeRef[];
32
+ connectors?: string[];
33
+ project_refs?: TwinProjectRef[];
34
+ tenant_id?: string | null;
35
+ edge_filters?: AgentGraphEdgeFilters;
36
+ as_of_ms?: number | null;
37
+ limit?: number;
38
+ }
39
+ export interface AgentGraphResult {
40
+ nodes: TwinRef[];
41
+ edges: TwinEdgeRecord[];
42
+ }
43
+ export interface GraphPathsInput {
44
+ from_ref: TwinRef;
45
+ to_ref: TwinRef;
46
+ max_depth?: number;
47
+ scopes?: TwinScopeRef[];
48
+ connectors?: string[];
49
+ project_refs?: TwinProjectRef[];
50
+ tenant_id?: string | null;
51
+ edge_filters?: AgentGraphEdgeFilters;
52
+ as_of_ms?: number | null;
53
+ limit?: number;
54
+ }
55
+ export interface AgentGraphPath {
56
+ refs: TwinRef[];
57
+ edges: TwinEdgeRecord[];
58
+ }
59
+ export interface GraphPathsResult {
60
+ paths: AgentGraphPath[];
61
+ }
62
+ export interface GraphTimelineInput {
63
+ ref: TwinRef;
64
+ scopes?: TwinScopeRef[];
65
+ connectors?: string[];
66
+ project_refs?: TwinProjectRef[];
67
+ tenant_id?: string | null;
68
+ edge_filters?: AgentGraphEdgeFilters;
69
+ from_ms?: number;
70
+ to_ms?: number;
71
+ as_of_ms?: number | null;
72
+ limit?: number;
73
+ }
74
+ export interface AgentGraphTimelineMemoryEvent {
75
+ kind: 'memory';
76
+ at_ms: number;
77
+ ref: Extract<TwinRef, {
78
+ kind: 'memory';
79
+ }>;
80
+ memory: {
81
+ id: string;
82
+ topic: string | null;
83
+ decision: string | null;
84
+ created_at: number;
85
+ event_datetime: number | null;
86
+ };
87
+ }
88
+ export interface AgentGraphTimelineCaseEvent {
89
+ kind: 'case';
90
+ at_ms: number;
91
+ ref: Extract<TwinRef, {
92
+ kind: 'case';
93
+ }>;
94
+ case: {
95
+ case_id: string;
96
+ title: string;
97
+ status: string;
98
+ created_at: string | number;
99
+ updated_at: string | number;
100
+ last_activity_at: string | null;
101
+ };
102
+ }
103
+ export interface AgentGraphTimelineEntityEvent {
104
+ kind: 'entity';
105
+ at_ms: number;
106
+ ref: Extract<TwinRef, {
107
+ kind: 'entity';
108
+ }>;
109
+ entity: EntityNode;
110
+ }
111
+ export interface AgentGraphTimelineRawEvent {
112
+ kind: 'raw';
113
+ at_ms: number;
114
+ ref: Extract<TwinRef, {
115
+ kind: 'raw';
116
+ }>;
117
+ raw: {
118
+ event_index_id: string;
119
+ source_connector: string;
120
+ source_type: string;
121
+ source_id: string;
122
+ source_locator: string | null;
123
+ title: string | null;
124
+ event_datetime: number | null;
125
+ source_timestamp_ms: number;
126
+ };
127
+ }
128
+ export interface AgentGraphTimelineEdgeEvent {
129
+ kind: 'edge';
130
+ at_ms: number;
131
+ edge: TwinEdgeRecord;
132
+ }
133
+ export type AgentGraphTimelineEvent = AgentGraphTimelineMemoryEvent | AgentGraphTimelineCaseEvent | AgentGraphTimelineEntityEvent | AgentGraphTimelineRawEvent | AgentGraphTimelineEdgeEvent;
134
+ export interface GraphTimelineResult {
135
+ ref: TwinRef;
136
+ events: AgentGraphTimelineEvent[];
137
+ }
138
+ export interface AttachEntityAliasWithEdgeInput {
139
+ entity_id: string;
140
+ label: string;
141
+ label_type?: EntityAliasLabelType;
142
+ lang?: string | null;
143
+ script?: string | null;
144
+ confidence?: number | null;
145
+ source_type: string;
146
+ source_ref?: string | null;
147
+ source_refs?: TwinRef[];
148
+ agent_id: string;
149
+ model_run_id: string;
150
+ envelope_hash: string;
151
+ request_idempotency_key?: string;
152
+ edge_idempotency_key?: string;
153
+ scopes?: TwinScopeRef[];
154
+ connectors?: string[];
155
+ project_refs?: TwinProjectRef[];
156
+ tenant_id?: string | null;
157
+ }
158
+ export interface AttachEntityAliasWithEdgeResult {
159
+ alias: EntityAlias;
160
+ edge: TwinEdgeRecord;
161
+ }
162
+ //# sourceMappingURL=types.d.ts.map
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1,8 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
2
+ import { type AgentSituationSourceReadInput, type VisibleAgentSituationSources } from './source-readers.js';
3
+ import type { AgentSituationInput, AgentSituationPacketRecord } from './types.js';
4
+ type SituationBuilderAdapter = Pick<DatabaseAdapter, 'prepare'>;
5
+ export declare function listVisibleAgentSituationSources(adapter: SituationBuilderAdapter, input: AgentSituationSourceReadInput): VisibleAgentSituationSources;
6
+ export declare function buildAgentSituationPacketRecord(adapter: SituationBuilderAdapter, input: AgentSituationInput): AgentSituationPacketRecord;
7
+ export {};
8
+ //# sourceMappingURL=builder.d.ts.map
@@ -0,0 +1,239 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listVisibleAgentSituationSources = listVisibleAgentSituationSources;
4
+ exports.buildAgentSituationPacketRecord = buildAgentSituationPacketRecord;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const canonicalize_js_1 = require("../canonicalize.js");
7
+ const cache_key_js_1 = require("./cache-key.js");
8
+ const ranking_policy_js_1 = require("./ranking-policy.js");
9
+ const source_readers_js_1 = require("./source-readers.js");
10
+ function iso(ms) {
11
+ return new Date(ms).toISOString();
12
+ }
13
+ function ttlForRange(rangeStartMs, rangeEndMs) {
14
+ const rangeMs = Math.max(0, rangeEndMs - rangeStartMs);
15
+ const dayMs = 24 * 60 * 60 * 1000;
16
+ if (rangeMs <= 7 * dayMs) {
17
+ return 120;
18
+ }
19
+ if (rangeMs <= 30 * dayMs) {
20
+ return 300;
21
+ }
22
+ return 900;
23
+ }
24
+ function topStrings(values, limit = 3) {
25
+ return values
26
+ .map((value) => value.trim())
27
+ .filter(Boolean)
28
+ .slice(0, limit);
29
+ }
30
+ function refKey(ref) {
31
+ return `${ref.kind}:${ref.id}`;
32
+ }
33
+ function buildBriefing(sources) {
34
+ const memories = sources.memories;
35
+ const openQuestions = memories.filter((memory) => memory.is_open_question);
36
+ const lowConfidence = [...memories, ...sources.cases, ...sources.edges].filter((candidate) => typeof candidate.confidence === 'number' && candidate.confidence < 0.6);
37
+ return {
38
+ decisions: topStrings(memories.map((memory) => memory.summary || memory.title)),
39
+ facts: topStrings(sources.raw.map((raw) => raw.summary)),
40
+ open_questions: topStrings(openQuestions.map((memory) => memory.summary || memory.title)),
41
+ risks: topStrings([
42
+ ...lowConfidence.map((candidate) => candidate.summary || candidate.title),
43
+ ...sources.cases
44
+ .filter((item) => item.status === 'blocked')
45
+ .map((item) => `${item.title}: ${item.status}`),
46
+ ]),
47
+ };
48
+ }
49
+ function buildCoverage(sources, input) {
50
+ const coverage = [];
51
+ for (const connector of input.effective_filters.connectors) {
52
+ for (const scope of input.effective_filters.scopes) {
53
+ const raw = sources.raw.filter((item) => item.connector === connector &&
54
+ item.scope?.kind === scope.kind &&
55
+ item.scope.id === scope.id);
56
+ const memories = sources.memories.filter((item) => item.scope?.kind === scope.kind && item.scope.id === scope.id);
57
+ const cases = sources.cases.filter((item) => item.scope?.kind === scope.kind && item.scope.id === scope.id);
58
+ const rowRefs = new Set([...raw, ...memories, ...cases].map((item) => refKey(item.ref)));
59
+ const edges = sources.edges.filter((item) => rowRefs.has(refKey(item.subject_ref)) && rowRefs.has(refKey(item.object_ref)));
60
+ const lastSeenMs = Math.max(0, ...raw.map((item) => item.timestamp_ms), ...memories.map((item) => item.timestamp_ms), ...cases.map((item) => item.timestamp_ms), ...edges.map((item) => item.timestamp_ms));
61
+ coverage.push({
62
+ connector,
63
+ channel_id: raw[0]?.channel_id ?? null,
64
+ memory_scope: scope,
65
+ raw_count: raw.length,
66
+ memory_count: memories.length,
67
+ case_count: cases.length,
68
+ edge_count: edges.length,
69
+ last_seen: lastSeenMs > 0 ? iso(lastSeenMs) : null,
70
+ stale: lastSeenMs > 0
71
+ ? (input.now_ms ?? Date.now()) - lastSeenMs > 30 * 24 * 60 * 60 * 1000
72
+ : true,
73
+ });
74
+ }
75
+ }
76
+ return coverage;
77
+ }
78
+ function buildRankedItems(sources, limit) {
79
+ const policy = (0, ranking_policy_js_1.getAgentSituationRankingPolicy)();
80
+ const candidates = [...sources.raw, ...sources.memories, ...sources.cases, ...sources.edges];
81
+ return candidates
82
+ .map((candidate) => {
83
+ const score = (0, ranking_policy_js_1.scoreAgentSituationCandidate)(candidate, policy);
84
+ return {
85
+ ref: candidate.ref,
86
+ kind: candidate.kind,
87
+ score: score.score,
88
+ reasons: score.reasons,
89
+ caveats: score.caveats,
90
+ };
91
+ })
92
+ .sort((left, right) => right.score - left.score || left.ref.id.localeCompare(right.ref.id))
93
+ .slice(0, limit);
94
+ }
95
+ function buildRecommendations(sources, rankedItems) {
96
+ const recommendations = [];
97
+ const expectedRefs = rankedItems.map((item) => item.ref);
98
+ if (sources.memories.some((memory) => memory.is_open_question) || sources.raw.length > 0) {
99
+ recommendations.push({
100
+ tool: 'raw.searchAll',
101
+ args: {
102
+ query: sources.memories.find((memory) => memory.is_open_question)?.title ?? 'recent work',
103
+ },
104
+ reason: 'visible_open_question_needs_evidence',
105
+ expected_refs: expectedRefs.filter((ref) => ref.kind === 'raw' || ref.kind === 'memory'),
106
+ });
107
+ }
108
+ const topRaw = sources.raw[0];
109
+ if (topRaw) {
110
+ recommendations.push({
111
+ tool: 'raw.window',
112
+ args: { raw_id: topRaw.ref.id },
113
+ reason: 'inspect_visible_raw_context',
114
+ expected_refs: [topRaw.ref],
115
+ });
116
+ }
117
+ return recommendations;
118
+ }
119
+ function sourceRefs(sources) {
120
+ return [
121
+ ...sources.raw.map((item) => item.ref),
122
+ ...sources.memories.map((item) => item.ref),
123
+ ...sources.cases.map((item) => item.ref),
124
+ ...sources.edges.map((item) => item.ref),
125
+ ];
126
+ }
127
+ function primaryScope(input) {
128
+ const scope = input.scope[0] ?? input.effective_filters.scopes[0];
129
+ if (!scope) {
130
+ throw new Error('agent.situation requires at least one effective memory scope');
131
+ }
132
+ return scope;
133
+ }
134
+ function primaryProjectId(input) {
135
+ const project = input.effective_filters.project_refs[0];
136
+ if (!project) {
137
+ throw new Error('agent.situation requires at least one effective project ref');
138
+ }
139
+ return project.id;
140
+ }
141
+ function json(value) {
142
+ return (0, canonicalize_js_1.canonicalizeJSON)(value);
143
+ }
144
+ function listVisibleAgentSituationSources(adapter, input) {
145
+ return (0, source_readers_js_1.listVisibleAgentSituationSources)(adapter, input);
146
+ }
147
+ function buildAgentSituationPacketRecord(adapter, input) {
148
+ const rankingPolicyVersion = input.ranking_policy_version ?? ranking_policy_js_1.AGENT_SITUATION_V0_POLICY_VERSION;
149
+ const nowMs = Math.floor(input.now_ms ?? Date.now());
150
+ const limit = Math.floor(input.limit);
151
+ const effectiveFilters = (0, cache_key_js_1.normalizeAgentSituationEffectiveFilters)(input.effective_filters);
152
+ const normalizedInput = { ...input, effective_filters: effectiveFilters };
153
+ const sources = (0, source_readers_js_1.listVisibleAgentSituationSources)(adapter, {
154
+ effective_filters: effectiveFilters,
155
+ range_start_ms: input.range_start_ms,
156
+ range_end_ms: input.range_end_ms,
157
+ limit,
158
+ });
159
+ const key = (0, cache_key_js_1.buildAgentSituationCacheKey)({
160
+ ...effectiveFilters,
161
+ range_start_ms: input.range_start_ms,
162
+ range_end_ms: input.range_end_ms,
163
+ focus: input.focus,
164
+ limit,
165
+ ranking_policy_version: rankingPolicyVersion,
166
+ });
167
+ const ttlSeconds = ttlForRange(input.range_start_ms, input.range_end_ms);
168
+ const expiresAt = nowMs + ttlSeconds * 1000;
169
+ const scope = primaryScope(input);
170
+ const rankedItems = buildRankedItems(sources, limit);
171
+ const briefing = buildBriefing(sources);
172
+ const coverage = buildCoverage(sources, normalizedInput);
173
+ const visibleSourceRefs = sourceRefs(sources);
174
+ const pendingHumanQuestions = sources.memories
175
+ .filter((memory) => memory.is_open_question)
176
+ .slice(0, 3)
177
+ .map((memory) => ({
178
+ memory_id: memory.ref.id,
179
+ title: memory.title,
180
+ summary: memory.summary,
181
+ }));
182
+ const caveats = visibleSourceRefs.length === 0 ? ['no_visible_sources'] : [];
183
+ const recommendedNextTools = buildRecommendations(sources, rankedItems);
184
+ const topMemoryRefs = sources.memories.map((memory) => memory.ref.id).slice(0, limit);
185
+ const freshness = {
186
+ generated_at_ms: nowMs,
187
+ visible_source_count: visibleSourceRefs.length,
188
+ };
189
+ return {
190
+ packet_id: `situ_${(0, node_crypto_1.randomUUID)().replace(/-/g, '')}`,
191
+ cache_key: key.cacheKey,
192
+ scope_json: json(input.scope),
193
+ scope: input.scope,
194
+ scope_hash: key.scopeHash,
195
+ range_start_ms: Math.floor(input.range_start_ms),
196
+ range_end_ms: Math.floor(input.range_end_ms),
197
+ focus_json: json(input.focus),
198
+ focus: input.focus,
199
+ envelope_hash: input.envelope_hash,
200
+ envelope_effective_filters_json: json(effectiveFilters),
201
+ envelope_effective_filters: effectiveFilters,
202
+ envelope_effective_filters_hash: key.filtersHash,
203
+ ranking_policy_version: rankingPolicyVersion,
204
+ generated_at: nowMs,
205
+ expires_at: expiresAt,
206
+ ttl_seconds: ttlSeconds,
207
+ freshness_json: json(freshness),
208
+ freshness,
209
+ source_coverage_json: json(coverage),
210
+ source_coverage: coverage,
211
+ briefing_json: json(briefing),
212
+ briefing,
213
+ ranked_items_json: json(rankedItems),
214
+ ranked_items: rankedItems,
215
+ top_memory_refs_json: json(topMemoryRefs),
216
+ top_memory_refs: topMemoryRefs,
217
+ pending_human_questions_json: json(pendingHumanQuestions),
218
+ pending_human_questions: pendingHumanQuestions,
219
+ entity_clusters_json: '[]',
220
+ entity_clusters: [],
221
+ recommended_next_tools_json: json(recommendedNextTools),
222
+ recommended_next_tools: recommendedNextTools,
223
+ generated_from_slice_ids_json: '[]',
224
+ generated_from_slice_ids: [],
225
+ caveats_json: json(caveats),
226
+ caveats,
227
+ agent_id: input.agent_id,
228
+ model_run_id: input.model_run_id,
229
+ input_snapshot_ref: `situation:${key.cacheKey}`,
230
+ source_refs_json: json(visibleSourceRefs),
231
+ source_refs: visibleSourceRefs,
232
+ tenant_id: effectiveFilters.tenant_id,
233
+ project_id: primaryProjectId(normalizedInput),
234
+ memory_scope_kind: scope.kind,
235
+ memory_scope_id: scope.id,
236
+ created_at: nowMs,
237
+ };
238
+ }
239
+ //# sourceMappingURL=builder.js.map
@@ -0,0 +1,4 @@
1
+ import type { AgentSituationCacheKeyInput, AgentSituationCacheKeyResult, AgentSituationEffectiveFilters } from './types.js';
2
+ export declare function normalizeAgentSituationEffectiveFilters(input: AgentSituationEffectiveFilters): AgentSituationEffectiveFilters;
3
+ export declare function buildAgentSituationCacheKey(input: AgentSituationCacheKeyInput): AgentSituationCacheKeyResult;
4
+ //# sourceMappingURL=cache-key.d.ts.map
@@ -0,0 +1,64 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.normalizeAgentSituationEffectiveFilters = normalizeAgentSituationEffectiveFilters;
4
+ exports.buildAgentSituationCacheKey = buildAgentSituationCacheKey;
5
+ const node_crypto_1 = require("node:crypto");
6
+ const canonicalize_js_1 = require("../canonicalize.js");
7
+ function sha256Hex(value) {
8
+ return (0, node_crypto_1.createHash)('sha256').update((0, canonicalize_js_1.canonicalizeJSON)(value), 'utf8').digest('hex');
9
+ }
10
+ function uniqueSorted(values) {
11
+ return [...new Set(values.map((value) => value.trim()).filter(Boolean))].sort();
12
+ }
13
+ function normalizeScopes(scopes) {
14
+ const byKey = new Map();
15
+ for (const scope of scopes) {
16
+ const normalized = { kind: scope.kind, id: scope.id.trim() };
17
+ if (normalized.id.length > 0) {
18
+ byKey.set(`${normalized.kind}:${normalized.id}`, normalized);
19
+ }
20
+ }
21
+ return [...byKey.values()].sort((left, right) => `${left.kind}:${left.id}`.localeCompare(`${right.kind}:${right.id}`));
22
+ }
23
+ function normalizeProjectRefs(projectRefs) {
24
+ const byId = new Map();
25
+ for (const project of projectRefs) {
26
+ const normalized = { kind: 'project', id: project.id.trim() };
27
+ if (normalized.id.length > 0) {
28
+ byId.set(normalized.id, normalized);
29
+ }
30
+ }
31
+ return [...byId.values()].sort((left, right) => left.id.localeCompare(right.id));
32
+ }
33
+ function normalizeFocus(focus) {
34
+ return [...new Set(focus)].sort();
35
+ }
36
+ function normalizeAgentSituationEffectiveFilters(input) {
37
+ return {
38
+ scopes: normalizeScopes(input.scopes),
39
+ connectors: uniqueSorted(input.connectors),
40
+ project_refs: normalizeProjectRefs(input.project_refs),
41
+ tenant_id: input.tenant_id.trim() || 'default',
42
+ as_of: input.as_of ?? null,
43
+ };
44
+ }
45
+ function buildAgentSituationCacheKey(input) {
46
+ const effective = normalizeAgentSituationEffectiveFilters(input);
47
+ const canonicalInput = {
48
+ ...effective,
49
+ range_start_ms: Math.floor(input.range_start_ms),
50
+ range_end_ms: Math.floor(input.range_end_ms),
51
+ focus: normalizeFocus(input.focus),
52
+ limit: Math.floor(input.limit),
53
+ ranking_policy_version: input.ranking_policy_version,
54
+ };
55
+ const canonicalJson = (0, canonicalize_js_1.canonicalizeJSON)(canonicalInput);
56
+ return {
57
+ cacheKey: (0, node_crypto_1.createHash)('sha256').update(canonicalJson, 'utf8').digest('hex'),
58
+ canonicalInput,
59
+ canonicalJson,
60
+ filtersHash: sha256Hex(effective),
61
+ scopeHash: sha256Hex(effective.scopes),
62
+ };
63
+ }
64
+ //# sourceMappingURL=cache-key.js.map
@@ -0,0 +1,7 @@
1
+ export * from './types.js';
2
+ export * from './cache-key.js';
3
+ export * from './ranking-policy.js';
4
+ export { listVisibleRawCandidates, listVisibleMemoryCandidates, listVisibleCaseCandidates, listVisibleEdgeCandidates, type AgentSituationSourceReadInput, type VisibleAgentSituationSources, type VisibleRawCandidate, type VisibleMemoryCandidate, type VisibleCaseCandidate, type VisibleEdgeCandidate, } from './source-readers.js';
5
+ export * from './builder.js';
6
+ export * from './packet-store.js';
7
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,28 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.listVisibleEdgeCandidates = exports.listVisibleCaseCandidates = exports.listVisibleMemoryCandidates = exports.listVisibleRawCandidates = void 0;
18
+ __exportStar(require("./types.js"), exports);
19
+ __exportStar(require("./cache-key.js"), exports);
20
+ __exportStar(require("./ranking-policy.js"), exports);
21
+ var source_readers_js_1 = require("./source-readers.js");
22
+ Object.defineProperty(exports, "listVisibleRawCandidates", { enumerable: true, get: function () { return source_readers_js_1.listVisibleRawCandidates; } });
23
+ Object.defineProperty(exports, "listVisibleMemoryCandidates", { enumerable: true, get: function () { return source_readers_js_1.listVisibleMemoryCandidates; } });
24
+ Object.defineProperty(exports, "listVisibleCaseCandidates", { enumerable: true, get: function () { return source_readers_js_1.listVisibleCaseCandidates; } });
25
+ Object.defineProperty(exports, "listVisibleEdgeCandidates", { enumerable: true, get: function () { return source_readers_js_1.listVisibleEdgeCandidates; } });
26
+ __exportStar(require("./builder.js"), exports);
27
+ __exportStar(require("./packet-store.js"), exports);
28
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,27 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
2
+ import type { AgentSituationLease, AgentSituationPacketRecord } from './types.js';
3
+ type PacketStoreAdapter = Pick<DatabaseAdapter, 'prepare' | 'transaction'>;
4
+ export interface AcquireAgentSituationLeaseInput {
5
+ cacheKey: string;
6
+ rankingPolicyVersion: string;
7
+ leaseOwner: string;
8
+ nowMs: number;
9
+ leaseSeconds: number;
10
+ }
11
+ export interface AgentSituationRefreshInput {
12
+ cacheKey: string;
13
+ rankingPolicyVersion: string;
14
+ nowMs: number;
15
+ leaseOwner: string;
16
+ leaseSeconds?: number;
17
+ pollIntervalMs?: number;
18
+ maxPollMs?: number;
19
+ refresh?: boolean;
20
+ }
21
+ export declare function getFreshAgentSituationPacket(adapter: PacketStoreAdapter, cacheKey: string, rankingPolicyVersion: string, nowMs: number): AgentSituationPacketRecord | null;
22
+ export declare function insertAgentSituationPacket(adapter: PacketStoreAdapter, packet: AgentSituationPacketRecord): AgentSituationPacketRecord;
23
+ export declare function acquireAgentSituationLease(adapter: PacketStoreAdapter, input: AcquireAgentSituationLeaseInput): AgentSituationLease | null;
24
+ export declare function releaseAgentSituationLease(adapter: PacketStoreAdapter, cacheKey: string, leaseOwner: string): void;
25
+ export declare function getOrRefreshAgentSituationPacket(adapter: PacketStoreAdapter, input: AgentSituationRefreshInput, builder: () => Promise<AgentSituationPacketRecord> | AgentSituationPacketRecord): Promise<AgentSituationPacketRecord>;
26
+ export {};
27
+ //# sourceMappingURL=packet-store.d.ts.map