@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,228 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.getFreshAgentSituationPacket = getFreshAgentSituationPacket;
4
+ exports.insertAgentSituationPacket = insertAgentSituationPacket;
5
+ exports.acquireAgentSituationLease = acquireAgentSituationLease;
6
+ exports.releaseAgentSituationLease = releaseAgentSituationLease;
7
+ exports.getOrRefreshAgentSituationPacket = getOrRefreshAgentSituationPacket;
8
+ const inProcessRefreshesByAdapter = new WeakMap();
9
+ function parseJson(row, field) {
10
+ const value = row[field];
11
+ if (typeof value !== 'string') {
12
+ throw new Error(`Invalid agent situation packet JSON field ${field}: expected string`);
13
+ }
14
+ try {
15
+ return JSON.parse(value);
16
+ }
17
+ catch (error) {
18
+ const message = error instanceof Error ? error.message : String(error);
19
+ throw new Error(`Invalid agent situation packet JSON field ${field}: ${message}`);
20
+ }
21
+ }
22
+ function inProcessRefreshesForAdapter(adapter) {
23
+ const existing = inProcessRefreshesByAdapter.get(adapter);
24
+ if (existing) {
25
+ return existing;
26
+ }
27
+ const scoped = new Map();
28
+ inProcessRefreshesByAdapter.set(adapter, scoped);
29
+ return scoped;
30
+ }
31
+ function mapPacketRow(row) {
32
+ return {
33
+ packet_id: String(row.packet_id),
34
+ cache_key: String(row.cache_key),
35
+ scope_json: String(row.scope_json),
36
+ scope: parseJson(row, 'scope_json'),
37
+ scope_hash: String(row.scope_hash),
38
+ range_start_ms: Number(row.range_start_ms),
39
+ range_end_ms: Number(row.range_end_ms),
40
+ focus_json: String(row.focus_json),
41
+ focus: parseJson(row, 'focus_json'),
42
+ envelope_hash: String(row.envelope_hash),
43
+ envelope_effective_filters_json: String(row.envelope_effective_filters_json),
44
+ envelope_effective_filters: parseJson(row, 'envelope_effective_filters_json'),
45
+ envelope_effective_filters_hash: String(row.envelope_effective_filters_hash),
46
+ ranking_policy_version: String(row.ranking_policy_version),
47
+ generated_at: Number(row.generated_at),
48
+ expires_at: Number(row.expires_at),
49
+ ttl_seconds: Number(row.ttl_seconds),
50
+ freshness_json: String(row.freshness_json),
51
+ freshness: parseJson(row, 'freshness_json'),
52
+ source_coverage_json: String(row.source_coverage_json),
53
+ source_coverage: parseJson(row, 'source_coverage_json'),
54
+ briefing_json: String(row.briefing_json),
55
+ briefing: parseJson(row, 'briefing_json'),
56
+ ranked_items_json: String(row.ranked_items_json),
57
+ ranked_items: parseJson(row, 'ranked_items_json'),
58
+ top_memory_refs_json: String(row.top_memory_refs_json),
59
+ top_memory_refs: parseJson(row, 'top_memory_refs_json'),
60
+ pending_human_questions_json: String(row.pending_human_questions_json),
61
+ pending_human_questions: parseJson(row, 'pending_human_questions_json'),
62
+ entity_clusters_json: String(row.entity_clusters_json),
63
+ entity_clusters: parseJson(row, 'entity_clusters_json'),
64
+ recommended_next_tools_json: String(row.recommended_next_tools_json),
65
+ recommended_next_tools: parseJson(row, 'recommended_next_tools_json'),
66
+ generated_from_slice_ids_json: String(row.generated_from_slice_ids_json),
67
+ generated_from_slice_ids: parseJson(row, 'generated_from_slice_ids_json'),
68
+ caveats_json: String(row.caveats_json),
69
+ caveats: parseJson(row, 'caveats_json'),
70
+ agent_id: String(row.agent_id),
71
+ model_run_id: String(row.model_run_id),
72
+ input_snapshot_ref: String(row.input_snapshot_ref),
73
+ source_refs_json: String(row.source_refs_json),
74
+ source_refs: parseJson(row, 'source_refs_json'),
75
+ tenant_id: String(row.tenant_id),
76
+ project_id: String(row.project_id),
77
+ memory_scope_kind: String(row.memory_scope_kind),
78
+ memory_scope_id: String(row.memory_scope_id),
79
+ created_at: Number(row.created_at),
80
+ };
81
+ }
82
+ function isDuplicateLeaseError(error) {
83
+ if (!(error instanceof Error)) {
84
+ return false;
85
+ }
86
+ return /UNIQUE constraint failed: agent_situation_refresh_leases\.cache_key|PRIMARY KEY constraint failed|SQLITE_CONSTRAINT_(PRIMARYKEY|UNIQUE)/i.test(error.message);
87
+ }
88
+ function mapLeaseRow(row) {
89
+ return {
90
+ cache_key: String(row.cache_key),
91
+ ranking_policy_version: String(row.ranking_policy_version),
92
+ lease_owner: String(row.lease_owner),
93
+ lease_expires_at: Number(row.lease_expires_at),
94
+ created_at: Number(row.created_at),
95
+ };
96
+ }
97
+ function getFreshAgentSituationPacket(adapter, cacheKey, rankingPolicyVersion, nowMs) {
98
+ const row = adapter
99
+ .prepare(`
100
+ SELECT *
101
+ FROM agent_situation_packets
102
+ WHERE cache_key = ?
103
+ AND ranking_policy_version = ?
104
+ AND expires_at > ?
105
+ ORDER BY expires_at DESC, generated_at DESC
106
+ LIMIT 1
107
+ `)
108
+ .get(cacheKey, rankingPolicyVersion, nowMs);
109
+ return row ? mapPacketRow(row) : null;
110
+ }
111
+ function insertAgentSituationPacket(adapter, packet) {
112
+ adapter
113
+ .prepare(`
114
+ INSERT INTO agent_situation_packets (
115
+ packet_id, cache_key, scope_json, scope_hash, range_start_ms, range_end_ms,
116
+ focus_json, envelope_hash, envelope_effective_filters_json,
117
+ envelope_effective_filters_hash, ranking_policy_version, generated_at, expires_at,
118
+ ttl_seconds, freshness_json, source_coverage_json, briefing_json, ranked_items_json,
119
+ top_memory_refs_json, pending_human_questions_json, entity_clusters_json,
120
+ recommended_next_tools_json, generated_from_slice_ids_json, caveats_json,
121
+ agent_id, model_run_id, input_snapshot_ref, source_refs_json, tenant_id, project_id,
122
+ memory_scope_kind, memory_scope_id, created_at
123
+ )
124
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
125
+ `)
126
+ .run(packet.packet_id, packet.cache_key, packet.scope_json, packet.scope_hash, packet.range_start_ms, packet.range_end_ms, packet.focus_json, packet.envelope_hash, packet.envelope_effective_filters_json, packet.envelope_effective_filters_hash, packet.ranking_policy_version, packet.generated_at, packet.expires_at, packet.ttl_seconds, packet.freshness_json, packet.source_coverage_json, packet.briefing_json, packet.ranked_items_json, packet.top_memory_refs_json, packet.pending_human_questions_json, packet.entity_clusters_json, packet.recommended_next_tools_json, packet.generated_from_slice_ids_json, packet.caveats_json, packet.agent_id, packet.model_run_id, packet.input_snapshot_ref, packet.source_refs_json, packet.tenant_id, packet.project_id, packet.memory_scope_kind, packet.memory_scope_id, packet.created_at);
127
+ const inserted = adapter
128
+ .prepare('SELECT * FROM agent_situation_packets WHERE packet_id = ?')
129
+ .get(packet.packet_id);
130
+ if (!inserted) {
131
+ throw new Error(`Agent situation packet insert failed: ${packet.packet_id}`);
132
+ }
133
+ return mapPacketRow(inserted);
134
+ }
135
+ function acquireAgentSituationLease(adapter, input) {
136
+ adapter
137
+ .prepare('DELETE FROM agent_situation_refresh_leases WHERE lease_expires_at <= ?')
138
+ .run(input.nowMs);
139
+ try {
140
+ adapter
141
+ .prepare(`
142
+ INSERT INTO agent_situation_refresh_leases (
143
+ cache_key, ranking_policy_version, lease_owner, lease_expires_at, created_at
144
+ )
145
+ VALUES (?, ?, ?, ?, ?)
146
+ `)
147
+ .run(input.cacheKey, input.rankingPolicyVersion, input.leaseOwner, input.nowMs + input.leaseSeconds * 1000, input.nowMs);
148
+ }
149
+ catch (error) {
150
+ if (isDuplicateLeaseError(error)) {
151
+ return null;
152
+ }
153
+ throw error;
154
+ }
155
+ const row = adapter
156
+ .prepare('SELECT * FROM agent_situation_refresh_leases WHERE cache_key = ?')
157
+ .get(input.cacheKey);
158
+ return row ? mapLeaseRow(row) : null;
159
+ }
160
+ function releaseAgentSituationLease(adapter, cacheKey, leaseOwner) {
161
+ adapter
162
+ .prepare('DELETE FROM agent_situation_refresh_leases WHERE cache_key = ? AND lease_owner = ?')
163
+ .run(cacheKey, leaseOwner);
164
+ }
165
+ function delay(ms) {
166
+ return new Promise((resolve) => setTimeout(resolve, ms));
167
+ }
168
+ async function waitForFreshPacket(adapter, input) {
169
+ const pollIntervalMs = input.pollIntervalMs ?? 50;
170
+ const maxPollMs = input.maxPollMs ?? 30_000;
171
+ const started = Date.now();
172
+ while (Date.now() - started < maxPollMs) {
173
+ const fresh = getFreshAgentSituationPacket(adapter, input.cacheKey, input.rankingPolicyVersion, input.nowMs);
174
+ if (fresh) {
175
+ return fresh;
176
+ }
177
+ await delay(pollIntervalMs);
178
+ }
179
+ return null;
180
+ }
181
+ async function getOrRefreshAgentSituationPacket(adapter, input, builder) {
182
+ if (!input.refresh) {
183
+ const fresh = getFreshAgentSituationPacket(adapter, input.cacheKey, input.rankingPolicyVersion, input.nowMs);
184
+ if (fresh) {
185
+ return fresh;
186
+ }
187
+ }
188
+ const refreshes = inProcessRefreshesForAdapter(adapter);
189
+ const key = `${input.cacheKey}:${input.rankingPolicyVersion}`;
190
+ const existing = refreshes.get(key);
191
+ if (existing) {
192
+ return existing;
193
+ }
194
+ const task = (async () => {
195
+ const lease = acquireAgentSituationLease(adapter, {
196
+ cacheKey: input.cacheKey,
197
+ rankingPolicyVersion: input.rankingPolicyVersion,
198
+ leaseOwner: input.leaseOwner,
199
+ nowMs: input.nowMs,
200
+ leaseSeconds: input.leaseSeconds ?? 30,
201
+ });
202
+ if (!lease) {
203
+ const fresh = await waitForFreshPacket(adapter, input);
204
+ if (fresh) {
205
+ return fresh;
206
+ }
207
+ throw new Error(`Timed out waiting for agent situation refresh lease for cache key ${input.cacheKey} and ranking policy ${input.rankingPolicyVersion}`);
208
+ }
209
+ try {
210
+ const built = await builder();
211
+ return insertAgentSituationPacket(adapter, built);
212
+ }
213
+ finally {
214
+ releaseAgentSituationLease(adapter, input.cacheKey, input.leaseOwner);
215
+ }
216
+ })();
217
+ refreshes.set(key, task);
218
+ try {
219
+ return await task;
220
+ }
221
+ finally {
222
+ refreshes.delete(key);
223
+ if (refreshes.size === 0) {
224
+ inProcessRefreshesByAdapter.delete(adapter);
225
+ }
226
+ }
227
+ }
228
+ //# sourceMappingURL=packet-store.js.map
@@ -0,0 +1,18 @@
1
+ import type { AgentSituationCandidate, SituationScore } from './types.js';
2
+ export declare const AGENT_SITUATION_V0_POLICY_VERSION = "agent_situation.v0";
3
+ export declare const AGENT_SITUATION_V0_WEIGHTS: {
4
+ readonly urgency: 0.35;
5
+ readonly confidence_gap: 0.2;
6
+ readonly debate_edge: 0.2;
7
+ readonly source_freshness: 0.2;
8
+ readonly cross_channel_signal: 0.15;
9
+ readonly pending_human_question: 0.1;
10
+ readonly open_question_urgency_boost: 0.2;
11
+ };
12
+ export interface AgentSituationRankingPolicy {
13
+ version: string;
14
+ weights: typeof AGENT_SITUATION_V0_WEIGHTS;
15
+ }
16
+ export declare function getAgentSituationRankingPolicy(version?: string): AgentSituationRankingPolicy;
17
+ export declare function scoreAgentSituationCandidate(candidate: AgentSituationCandidate, policy: AgentSituationRankingPolicy): SituationScore;
18
+ //# sourceMappingURL=ranking-policy.d.ts.map
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.AGENT_SITUATION_V0_WEIGHTS = exports.AGENT_SITUATION_V0_POLICY_VERSION = void 0;
4
+ exports.getAgentSituationRankingPolicy = getAgentSituationRankingPolicy;
5
+ exports.scoreAgentSituationCandidate = scoreAgentSituationCandidate;
6
+ exports.AGENT_SITUATION_V0_POLICY_VERSION = 'agent_situation.v0';
7
+ exports.AGENT_SITUATION_V0_WEIGHTS = {
8
+ urgency: 0.35,
9
+ confidence_gap: 0.2,
10
+ debate_edge: 0.2,
11
+ source_freshness: 0.2,
12
+ cross_channel_signal: 0.15,
13
+ pending_human_question: 0.1,
14
+ open_question_urgency_boost: 0.2,
15
+ };
16
+ const V0_POLICY = {
17
+ version: exports.AGENT_SITUATION_V0_POLICY_VERSION,
18
+ weights: exports.AGENT_SITUATION_V0_WEIGHTS,
19
+ };
20
+ function textHasUrgency(candidate) {
21
+ const text = `${candidate.title} ${candidate.summary}`.toLowerCase();
22
+ return /\b(blocked|urgent|risk|deploy|release|needs?|review|failed|failing)\b/.test(text);
23
+ }
24
+ function freshnessScore(candidate) {
25
+ if (!Number.isFinite(candidate.timestamp_ms) || candidate.timestamp_ms <= 0) {
26
+ return 0;
27
+ }
28
+ const ageMs = Math.max(0, Date.now() - candidate.timestamp_ms);
29
+ const sevenDaysMs = 7 * 24 * 60 * 60 * 1000;
30
+ return Math.max(0, 1 - Math.min(ageMs, sevenDaysMs) / sevenDaysMs);
31
+ }
32
+ function getAgentSituationRankingPolicy(version = exports.AGENT_SITUATION_V0_POLICY_VERSION) {
33
+ if (version !== exports.AGENT_SITUATION_V0_POLICY_VERSION) {
34
+ throw new Error(`Unknown agent situation ranking policy: ${version}`);
35
+ }
36
+ return V0_POLICY;
37
+ }
38
+ function scoreAgentSituationCandidate(candidate, policy) {
39
+ const reasons = [];
40
+ const caveats = [];
41
+ let score = 0;
42
+ if (textHasUrgency(candidate)) {
43
+ score += policy.weights.urgency;
44
+ reasons.push('urgent_visible_signal');
45
+ }
46
+ const confidence = typeof candidate.confidence === 'number' ? candidate.confidence : 1;
47
+ if (confidence < 0.6) {
48
+ score += policy.weights.confidence_gap;
49
+ reasons.push('low_confidence_memory');
50
+ caveats.push('low_confidence_visible_memory');
51
+ }
52
+ if (candidate.has_debate_edge) {
53
+ score += policy.weights.debate_edge;
54
+ reasons.push('debated_visible_memory');
55
+ }
56
+ const freshness = freshnessScore(candidate);
57
+ if (freshness > 0) {
58
+ score += freshness * policy.weights.source_freshness;
59
+ reasons.push('recent_visible_source');
60
+ }
61
+ if (candidate.connector && candidate.channel_id) {
62
+ score += policy.weights.cross_channel_signal / 2;
63
+ reasons.push('visible_connector_context');
64
+ }
65
+ if (candidate.is_open_question) {
66
+ score += policy.weights.pending_human_question + policy.weights.open_question_urgency_boost;
67
+ reasons.push('pending_open_question');
68
+ }
69
+ return {
70
+ score: Number(score.toFixed(6)),
71
+ reasons: [...new Set(reasons)],
72
+ caveats: [...new Set(caveats)],
73
+ };
74
+ }
75
+ //# sourceMappingURL=ranking-policy.js.map
@@ -0,0 +1,52 @@
1
+ import type { DatabaseAdapter } from '../db-manager.js';
2
+ import type { AgentSituationCandidate, AgentSituationEffectiveFilters, SituationRef } from './types.js';
3
+ type SituationReaderAdapter = Pick<DatabaseAdapter, 'prepare'>;
4
+ export interface AgentSituationSourceReadInput {
5
+ effective_filters: AgentSituationEffectiveFilters;
6
+ range_start_ms: number;
7
+ range_end_ms: number;
8
+ limit: number;
9
+ }
10
+ export interface VisibleRawCandidate extends AgentSituationCandidate {
11
+ ref: {
12
+ kind: 'raw';
13
+ id: string;
14
+ };
15
+ connector: string;
16
+ channel_id: string | null;
17
+ content: string;
18
+ }
19
+ export interface VisibleMemoryCandidate extends AgentSituationCandidate {
20
+ ref: {
21
+ kind: 'memory';
22
+ id: string;
23
+ };
24
+ topic: string;
25
+ }
26
+ export interface VisibleCaseCandidate extends AgentSituationCandidate {
27
+ ref: {
28
+ kind: 'case';
29
+ id: string;
30
+ };
31
+ }
32
+ export interface VisibleEdgeCandidate extends AgentSituationCandidate {
33
+ ref: {
34
+ kind: 'edge';
35
+ id: string;
36
+ };
37
+ subject_ref: SituationRef;
38
+ object_ref: SituationRef;
39
+ }
40
+ export interface VisibleAgentSituationSources {
41
+ raw: VisibleRawCandidate[];
42
+ memories: VisibleMemoryCandidate[];
43
+ cases: VisibleCaseCandidate[];
44
+ edges: VisibleEdgeCandidate[];
45
+ }
46
+ export declare function listVisibleRawCandidates(adapter: SituationReaderAdapter, input: AgentSituationSourceReadInput): VisibleRawCandidate[];
47
+ export declare function listVisibleMemoryCandidates(adapter: SituationReaderAdapter, input: AgentSituationSourceReadInput): VisibleMemoryCandidate[];
48
+ export declare function listVisibleCaseCandidates(adapter: SituationReaderAdapter, input: AgentSituationSourceReadInput): VisibleCaseCandidate[];
49
+ export declare function listVisibleEdgeCandidates(adapter: SituationReaderAdapter, input: AgentSituationSourceReadInput, visibleRefs: SituationRef[]): VisibleEdgeCandidate[];
50
+ export declare function listVisibleAgentSituationSources(adapter: SituationReaderAdapter, input: AgentSituationSourceReadInput): VisibleAgentSituationSources;
51
+ export {};
52
+ //# sourceMappingURL=source-readers.d.ts.map
@@ -0,0 +1,300 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.listVisibleRawCandidates = listVisibleRawCandidates;
4
+ exports.listVisibleMemoryCandidates = listVisibleMemoryCandidates;
5
+ exports.listVisibleCaseCandidates = listVisibleCaseCandidates;
6
+ exports.listVisibleEdgeCandidates = listVisibleEdgeCandidates;
7
+ exports.listVisibleAgentSituationSources = listVisibleAgentSituationSources;
8
+ const types_js_1 = require("../memory/types.js");
9
+ function placeholders(values) {
10
+ return values.map(() => '?').join(', ');
11
+ }
12
+ function scopeKey(scope) {
13
+ return `${scope.kind}:${scope.id}`;
14
+ }
15
+ function refKey(ref) {
16
+ return `${ref.kind}:${ref.id}`;
17
+ }
18
+ function tableExists(adapter, table) {
19
+ const row = adapter
20
+ .prepare("SELECT name FROM sqlite_master WHERE type='table' AND name = ?")
21
+ .get(table);
22
+ return Boolean(row?.name);
23
+ }
24
+ function normalizeLimit(limit) {
25
+ return Math.max(0, Math.min(100, Math.floor(limit)));
26
+ }
27
+ function visibilityEndMs(input) {
28
+ const asOf = input.effective_filters.as_of;
29
+ if (!asOf) {
30
+ return input.range_end_ms;
31
+ }
32
+ const parsed = Date.parse(asOf);
33
+ if (!Number.isFinite(parsed)) {
34
+ throw new Error(`Invalid agent situation as_of: ${asOf}`);
35
+ }
36
+ return Math.min(input.range_end_ms, parsed);
37
+ }
38
+ function parseCaseScopeRefs(row) {
39
+ const caseId = String(row.case_id ?? '<unknown>');
40
+ if (typeof row.scope_refs !== 'string' || row.scope_refs.length === 0) {
41
+ throw new Error(`Invalid case_truth.scope_refs for case ${caseId}: expected a JSON array string.`);
42
+ }
43
+ let parsed;
44
+ try {
45
+ parsed = JSON.parse(row.scope_refs);
46
+ }
47
+ catch {
48
+ throw new Error(`Invalid case_truth.scope_refs for case ${caseId}: malformed JSON.`);
49
+ }
50
+ if (!Array.isArray(parsed)) {
51
+ throw new Error(`Invalid case_truth.scope_refs for case ${caseId}: expected a JSON array.`);
52
+ }
53
+ return parsed.map((scope, index) => {
54
+ if (!scope || typeof scope !== 'object') {
55
+ throw new Error(`Invalid case_truth.scope_refs for case ${caseId}: entry ${index} must be an object.`);
56
+ }
57
+ const record = scope;
58
+ if (typeof record.kind !== 'string' ||
59
+ typeof record.id !== 'string' ||
60
+ !types_js_1.MEMORY_SCOPE_KINDS.includes(record.kind)) {
61
+ throw new Error(`Invalid case_truth.scope_refs for case ${caseId}: entry ${index} must include a valid kind and id.`);
62
+ }
63
+ return { kind: record.kind, id: record.id };
64
+ });
65
+ }
66
+ function isScopeVisible(scope, effective) {
67
+ const visible = new Set(effective.scopes.map(scopeKey));
68
+ return visible.has(scopeKey(scope));
69
+ }
70
+ function caseTimestampMs(row) {
71
+ const caseId = String(row.case_id ?? 'unknown');
72
+ const timestampFields = [
73
+ ['last_activity_at', row.last_activity_at],
74
+ ['updated_at', row.updated_at],
75
+ ['created_at', row.created_at],
76
+ ];
77
+ for (const [field, value] of timestampFields) {
78
+ if (value === null || value === undefined || value === '') {
79
+ continue;
80
+ }
81
+ if (typeof value !== 'string') {
82
+ throw new Error(`Invalid case_truth timestamp for case ${caseId}: ${field} must be an ISO timestamp string.`);
83
+ }
84
+ if (typeof value === 'string') {
85
+ const parsed = Date.parse(value);
86
+ if (Number.isFinite(parsed)) {
87
+ return parsed;
88
+ }
89
+ }
90
+ }
91
+ throw new Error(`Invalid case_truth timestamp for case ${caseId}: expected last_activity_at, updated_at, or created_at to contain a valid ISO timestamp.`);
92
+ }
93
+ function isOpenQuestion(row) {
94
+ const text = `${String(row.topic ?? '')} ${String(row.decision ?? '')} ${String(row.summary ?? '')}`;
95
+ return row.kind === 'task' || text.includes('?') || /\b(question|decide|answer)\b/i.test(text);
96
+ }
97
+ function listVisibleRawCandidates(adapter, input) {
98
+ if (!tableExists(adapter, 'connector_event_index')) {
99
+ return [];
100
+ }
101
+ const connectors = input.effective_filters.connectors;
102
+ const scopes = input.effective_filters.scopes;
103
+ const projectIds = input.effective_filters.project_refs.map((project) => project.id);
104
+ if (connectors.length === 0 || scopes.length === 0 || projectIds.length === 0) {
105
+ return [];
106
+ }
107
+ const endMs = visibilityEndMs(input);
108
+ const scopeClauses = scopes
109
+ .map(() => '(memory_scope_kind = ? AND memory_scope_id = ?)')
110
+ .join(' OR ');
111
+ const params = [input.effective_filters.tenant_id, ...projectIds, ...connectors];
112
+ for (const scope of scopes) {
113
+ params.push(scope.kind, scope.id);
114
+ }
115
+ params.push(input.range_start_ms, endMs, normalizeLimit(input.limit));
116
+ const rows = adapter
117
+ .prepare(`
118
+ SELECT event_index_id, source_connector, channel, title, content, event_datetime,
119
+ memory_scope_kind, memory_scope_id
120
+ FROM connector_event_index
121
+ WHERE tenant_id = ?
122
+ AND project_id IN (${placeholders(projectIds)})
123
+ AND source_connector IN (${placeholders(connectors)})
124
+ AND (${scopeClauses})
125
+ AND event_datetime BETWEEN ? AND ?
126
+ ORDER BY event_datetime DESC, event_index_id ASC
127
+ LIMIT ?
128
+ `)
129
+ .all(...params);
130
+ return rows.map((row) => ({
131
+ ref: { kind: 'raw', id: String(row.event_index_id) },
132
+ kind: 'raw',
133
+ title: String(row.title ?? 'Untitled raw event'),
134
+ summary: String(row.content ?? '').slice(0, 240),
135
+ content: String(row.content ?? ''),
136
+ timestamp_ms: Number(row.event_datetime),
137
+ connector: String(row.source_connector),
138
+ channel_id: typeof row.channel === 'string' ? row.channel : null,
139
+ scope: typeof row.memory_scope_kind === 'string' && typeof row.memory_scope_id === 'string'
140
+ ? { kind: row.memory_scope_kind, id: row.memory_scope_id }
141
+ : null,
142
+ }));
143
+ }
144
+ function listVisibleMemoryCandidates(adapter, input) {
145
+ if (!tableExists(adapter, 'decisions')) {
146
+ return [];
147
+ }
148
+ const scopes = input.effective_filters.scopes;
149
+ if (scopes.length === 0) {
150
+ return [];
151
+ }
152
+ const endMs = visibilityEndMs(input);
153
+ const scopeClauses = scopes.map(() => '(ms.kind = ? AND ms.external_id = ?)').join(' OR ');
154
+ const params = [];
155
+ for (const scope of scopes) {
156
+ params.push(scope.kind, scope.id);
157
+ }
158
+ params.push(input.range_start_ms, endMs, normalizeLimit(input.limit));
159
+ const rows = adapter
160
+ .prepare(`
161
+ SELECT DISTINCT d.id, d.topic, d.decision, d.reasoning, d.kind, d.status, d.summary,
162
+ d.confidence, d.event_datetime, d.created_at, ms.kind AS scope_kind,
163
+ ms.external_id AS scope_id
164
+ FROM decisions d
165
+ JOIN memory_scope_bindings msb ON msb.memory_id = d.id
166
+ JOIN memory_scopes ms ON ms.id = msb.scope_id
167
+ WHERE (${scopeClauses})
168
+ AND COALESCE(d.event_datetime, d.created_at) BETWEEN ? AND ?
169
+ ORDER BY COALESCE(d.event_datetime, d.created_at) DESC, d.id ASC
170
+ LIMIT ?
171
+ `)
172
+ .all(...params);
173
+ return rows.map((row) => ({
174
+ ref: { kind: 'memory', id: String(row.id) },
175
+ kind: 'memory',
176
+ title: String(row.topic ?? row.decision ?? 'Memory'),
177
+ summary: String(row.summary ?? row.decision ?? row.reasoning ?? ''),
178
+ topic: String(row.topic ?? ''),
179
+ timestamp_ms: Number(row.event_datetime ?? row.created_at ?? 0),
180
+ confidence: typeof row.confidence === 'number' ? row.confidence : Number(row.confidence ?? 1),
181
+ status: typeof row.status === 'string' ? row.status : null,
182
+ is_open_question: isOpenQuestion(row),
183
+ has_debate_edge: false,
184
+ scope: typeof row.scope_kind === 'string' && typeof row.scope_id === 'string'
185
+ ? { kind: row.scope_kind, id: row.scope_id }
186
+ : null,
187
+ }));
188
+ }
189
+ function listVisibleCaseCandidates(adapter, input) {
190
+ if (!tableExists(adapter, 'case_truth')) {
191
+ return [];
192
+ }
193
+ const endMs = visibilityEndMs(input);
194
+ const rows = adapter
195
+ .prepare(`
196
+ SELECT case_id, title, status, confidence, scope_refs, last_activity_at, updated_at, created_at
197
+ FROM case_truth
198
+ ORDER BY COALESCE(last_activity_at, updated_at, created_at) DESC, case_id ASC
199
+ `)
200
+ .all();
201
+ return rows
202
+ .map((row) => {
203
+ const timestamp = caseTimestampMs(row);
204
+ if (timestamp < input.range_start_ms || timestamp > endMs) {
205
+ return null;
206
+ }
207
+ const visibleScope = parseCaseScopeRefs(row).find((scope) => isScopeVisible(scope, input.effective_filters));
208
+ if (!visibleScope) {
209
+ return null;
210
+ }
211
+ return {
212
+ ref: { kind: 'case', id: String(row.case_id) },
213
+ kind: 'case',
214
+ title: String(row.title ?? 'Case'),
215
+ summary: String(row.status ?? ''),
216
+ timestamp_ms: timestamp,
217
+ confidence: row.confidence === 'low' ? 0.4 : row.confidence === 'medium' ? 0.7 : 1,
218
+ status: typeof row.status === 'string' ? row.status : null,
219
+ scope: visibleScope,
220
+ };
221
+ })
222
+ .filter((row) => Boolean(row))
223
+ .slice(0, normalizeLimit(input.limit));
224
+ }
225
+ function listVisibleEdgeCandidates(adapter, input, visibleRefs) {
226
+ if (!tableExists(adapter, 'twin_edges')) {
227
+ return [];
228
+ }
229
+ const visible = new Set(visibleRefs.map(refKey));
230
+ if (visible.size === 0) {
231
+ return [];
232
+ }
233
+ const uniqueVisibleRefs = [...new Map(visibleRefs.map((ref) => [refKey(ref), ref])).values()];
234
+ const subjectClauses = uniqueVisibleRefs
235
+ .map(() => '(subject_kind = ? AND subject_id = ?)')
236
+ .join(' OR ');
237
+ const objectClauses = uniqueVisibleRefs
238
+ .map(() => '(object_kind = ? AND object_id = ?)')
239
+ .join(' OR ');
240
+ const params = [input.range_start_ms, visibilityEndMs(input)];
241
+ for (const ref of uniqueVisibleRefs) {
242
+ params.push(ref.kind, ref.id);
243
+ }
244
+ for (const ref of uniqueVisibleRefs) {
245
+ params.push(ref.kind, ref.id);
246
+ }
247
+ params.push(normalizeLimit(input.limit));
248
+ const rows = adapter
249
+ .prepare(`
250
+ SELECT edge_id, edge_type, subject_kind, subject_id, object_kind, object_id,
251
+ confidence, reason_text, created_at
252
+ FROM twin_edges
253
+ WHERE created_at BETWEEN ? AND ?
254
+ AND (${subjectClauses})
255
+ AND (${objectClauses})
256
+ ORDER BY created_at DESC, edge_id ASC
257
+ LIMIT ?
258
+ `)
259
+ .all(...params);
260
+ return rows
261
+ .map((row) => {
262
+ const subject = {
263
+ kind: String(row.subject_kind),
264
+ id: String(row.subject_id),
265
+ };
266
+ const object = {
267
+ kind: String(row.object_kind),
268
+ id: String(row.object_id),
269
+ };
270
+ if (!visible.has(refKey(subject)) || !visible.has(refKey(object))) {
271
+ return null;
272
+ }
273
+ return {
274
+ ref: { kind: 'edge', id: String(row.edge_id) },
275
+ kind: String(row.edge_type),
276
+ title: String(row.edge_type),
277
+ summary: String(row.reason_text ?? ''),
278
+ timestamp_ms: Number(row.created_at),
279
+ confidence: typeof row.confidence === 'number' ? row.confidence : Number(row.confidence ?? 1),
280
+ status: null,
281
+ subject_ref: subject,
282
+ object_ref: object,
283
+ };
284
+ })
285
+ .filter((row) => Boolean(row))
286
+ .slice(0, normalizeLimit(input.limit));
287
+ }
288
+ function listVisibleAgentSituationSources(adapter, input) {
289
+ const raw = listVisibleRawCandidates(adapter, input);
290
+ const memories = listVisibleMemoryCandidates(adapter, input);
291
+ const cases = listVisibleCaseCandidates(adapter, input);
292
+ const visibleRefs = [
293
+ ...raw.map((item) => item.ref),
294
+ ...memories.map((item) => item.ref),
295
+ ...cases.map((item) => item.ref),
296
+ ];
297
+ const edges = listVisibleEdgeCandidates(adapter, input, visibleRefs);
298
+ return { raw, memories, cases, edges };
299
+ }
300
+ //# sourceMappingURL=source-readers.js.map