@lucern/contracts 0.1.0 → 0.1.2-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (128) hide show
  1. package/CHANGELOG.md +3 -0
  2. package/README.md +3 -0
  3. package/dist/agents/v1.d.ts +2 -0
  4. package/dist/agents/v1.js +3 -0
  5. package/dist/agents/v1.js.map +1 -0
  6. package/dist/api-enums.contract.d.ts +30 -29
  7. package/dist/api-enums.contract.js +145 -133
  8. package/dist/api-enums.contract.js.map +1 -1
  9. package/dist/auth-context.contract.d.ts +2 -0
  10. package/dist/auth-context.contract.js +48 -0
  11. package/dist/auth-context.contract.js.map +1 -0
  12. package/dist/auth-session.contract.d.ts +2 -54
  13. package/dist/auth-session.contract.js +41 -43
  14. package/dist/auth-session.contract.js.map +1 -1
  15. package/dist/auth.contract.d.ts +92 -0
  16. package/dist/auth.contract.js +48 -0
  17. package/dist/auth.contract.js.map +1 -0
  18. package/dist/beliefs/v1.d.ts +2 -0
  19. package/dist/beliefs/v1.js +3 -0
  20. package/dist/beliefs/v1.js.map +1 -0
  21. package/dist/context-pack.contract.d.ts +55 -54
  22. package/dist/context-pack.contract.js +88 -160
  23. package/dist/context-pack.contract.js.map +1 -1
  24. package/dist/convex-admin.contract.d.ts +7 -0
  25. package/dist/convex-admin.contract.js +3 -0
  26. package/dist/convex-admin.contract.js.map +1 -0
  27. package/dist/events-types.contract.d.ts +1 -0
  28. package/dist/events-types.contract.js +136 -0
  29. package/dist/events-types.contract.js.map +1 -0
  30. package/dist/events.contract.d.ts +178 -0
  31. package/dist/events.contract.js +136 -0
  32. package/dist/events.contract.js.map +1 -0
  33. package/dist/evidence/v1.d.ts +2 -0
  34. package/dist/evidence/v1.js +3 -0
  35. package/dist/evidence/v1.js.map +1 -0
  36. package/dist/gateway.contract.d.ts +17 -12
  37. package/dist/gateway.contract.js +11 -11
  38. package/dist/gateway.contract.js.map +1 -1
  39. package/dist/graph/v1.d.ts +2 -0
  40. package/dist/graph/v1.js +3 -0
  41. package/dist/graph/v1.js.map +1 -0
  42. package/dist/ids.contract.d.ts +9 -0
  43. package/dist/ids.contract.js +29 -0
  44. package/dist/ids.contract.js.map +1 -0
  45. package/dist/index.d.ts +15 -22
  46. package/dist/index.js +5525 -21
  47. package/dist/index.js.map +1 -1
  48. package/dist/lens-filter.contract.d.ts +10 -9
  49. package/dist/lens-filter.contract.js +59 -84
  50. package/dist/lens-filter.contract.js.map +1 -1
  51. package/dist/lens-workflow.contract.d.ts +23 -21
  52. package/dist/lens-workflow.contract.js +116 -48
  53. package/dist/lens-workflow.contract.js.map +1 -1
  54. package/dist/mcp-tools.contract-D8kXcP6d.d.ts +254 -0
  55. package/dist/mcp-tools.contract.d.ts +1 -152
  56. package/dist/mcp-tools.contract.js +2984 -3280
  57. package/dist/mcp-tools.contract.js.map +1 -1
  58. package/dist/ontologies/v1.d.ts +2 -0
  59. package/dist/ontologies/v1.js +3 -0
  60. package/dist/ontologies/v1.js.map +1 -0
  61. package/dist/ontology-matching.contract.d.ts +1 -0
  62. package/dist/ontology-matching.contract.js +346 -0
  63. package/dist/ontology-matching.contract.js.map +1 -0
  64. package/dist/prompt.contract.d.ts +5 -4
  65. package/dist/prompt.contract.js +10 -23
  66. package/dist/prompt.contract.js.map +1 -1
  67. package/dist/questions/v1.d.ts +2 -0
  68. package/dist/questions/v1.js +3 -0
  69. package/dist/questions/v1.js.map +1 -0
  70. package/dist/sdk-methods.contract.d.ts +51 -45
  71. package/dist/sdk-methods.contract.js +2 -16
  72. package/dist/sdk-methods.contract.js.map +1 -1
  73. package/dist/sdk-tools.contract-BnV0hKLp.d.ts +150 -0
  74. package/dist/sdk-tools.contract.d.ts +2 -93
  75. package/dist/sdk-tools.contract.js +4220 -1397
  76. package/dist/sdk-tools.contract.js.map +1 -1
  77. package/dist/text-matching.contract.d.ts +55 -0
  78. package/dist/text-matching.contract.js +246 -0
  79. package/dist/text-matching.contract.js.map +1 -0
  80. package/dist/topic-scope.contract.d.ts +1 -0
  81. package/dist/topic-scope.contract.js +54 -0
  82. package/dist/topic-scope.contract.js.map +1 -0
  83. package/dist/topics/v1.d.ts +2 -0
  84. package/dist/topics/v1.js +3 -0
  85. package/dist/topics/v1.js.map +1 -0
  86. package/dist/v1/agents/v1.d.ts +2 -0
  87. package/dist/v1/agents/v1.js +3 -0
  88. package/dist/v1/agents/v1.js.map +1 -0
  89. package/dist/v1/beliefs/v1.d.ts +2 -0
  90. package/dist/v1/beliefs/v1.js +3 -0
  91. package/dist/v1/beliefs/v1.js.map +1 -0
  92. package/dist/v1/evidence/v1.d.ts +2 -0
  93. package/dist/v1/evidence/v1.js +3 -0
  94. package/dist/v1/evidence/v1.js.map +1 -0
  95. package/dist/v1/graph/v1.d.ts +2 -0
  96. package/dist/v1/graph/v1.js +3 -0
  97. package/dist/v1/graph/v1.js.map +1 -0
  98. package/dist/v1/ontologies/v1.d.ts +78 -0
  99. package/dist/v1/ontologies/v1.js +346 -0
  100. package/dist/v1/ontologies/v1.js.map +1 -0
  101. package/dist/v1/questions/v1.d.ts +2 -0
  102. package/dist/v1/questions/v1.js +3 -0
  103. package/dist/v1/questions/v1.js.map +1 -0
  104. package/dist/v1/topics/v1.d.ts +21 -0
  105. package/dist/v1/topics/v1.js +54 -0
  106. package/dist/v1/topics/v1.js.map +1 -0
  107. package/dist/v1/worktrees/v1.d.ts +2 -0
  108. package/dist/v1/worktrees/v1.js +3 -0
  109. package/dist/v1/worktrees/v1.js.map +1 -0
  110. package/dist/workflow-runtime.contract.d.ts +46 -45
  111. package/dist/workflow-runtime.contract.js +228 -241
  112. package/dist/workflow-runtime.contract.js.map +1 -1
  113. package/dist/worktrees/v1.d.ts +2 -0
  114. package/dist/worktrees/v1.js +3 -0
  115. package/dist/worktrees/v1.js.map +1 -0
  116. package/package.json +19 -13
  117. package/dist/api-enums.contract.d.ts.map +0 -1
  118. package/dist/auth-session.contract.d.ts.map +0 -1
  119. package/dist/context-pack.contract.d.ts.map +0 -1
  120. package/dist/gateway.contract.d.ts.map +0 -1
  121. package/dist/index.d.ts.map +0 -1
  122. package/dist/lens-filter.contract.d.ts.map +0 -1
  123. package/dist/lens-workflow.contract.d.ts.map +0 -1
  124. package/dist/mcp-tools.contract.d.ts.map +0 -1
  125. package/dist/prompt.contract.d.ts.map +0 -1
  126. package/dist/sdk-methods.contract.d.ts.map +0 -1
  127. package/dist/sdk-tools.contract.d.ts.map +0 -1
  128. package/dist/workflow-runtime.contract.d.ts.map +0 -1
@@ -1,170 +1,98 @@
1
- /**
2
- * Context-Pack Contract v1
3
- *
4
- * Canonical TypeScript types and constants for the context-pack output schema.
5
- * This is the external contract consumed by:
6
- * - MCP tool `compile_context` (canonical compiler read)
7
- * - SDK/HTTP consumers that read compiled context packs programmatically
8
- * - Benchmark harnesses (context-pack-ab)
9
- *
10
- * BREAKING CHANGE RULES:
11
- * - Adding optional fields to ContextPackV1 is NON-breaking
12
- * - Removing fields or changing types is BREAKING (bump CONTEXT_PACK_SCHEMA_VERSION)
13
- * - Changing section budget ratios or ranking weights is NON-breaking (tuning)
14
- * - Changing the version string is BREAKING (consumers check it)
15
- */
16
- // =============================================================================
17
- // SCHEMA VERSION
18
- // =============================================================================
19
- /** Canonical version string. Consumers MUST check this field for compatibility. */
20
- export const CONTEXT_PACK_SCHEMA_VERSION = "1.0.0";
21
- export const CONTEXT_RANKING_PROFILES = [
22
- "baseline_v1",
23
- "weighted_v1",
1
+ // src/context-pack.contract.ts
2
+ var CONTEXT_PACK_SCHEMA_VERSION = "1.0.0";
3
+ var CONTEXT_RANKING_PROFILES = [
4
+ "baseline_v1",
5
+ "weighted_v1"
24
6
  ];
25
- export const DEFAULT_RANKING_PROFILE = "weighted_v1";
26
- export const DEFAULT_COMPILATION_MODE = "standard";
27
- export const CONTEXT_PACK_SECTION_KEYS = [
28
- "invariants",
29
- "activeBeliefs",
30
- "openQuestions",
31
- "recentEvidence",
32
- "contradictions",
7
+ var DEFAULT_RANKING_PROFILE = "weighted_v1";
8
+ var DEFAULT_COMPILATION_MODE = "standard";
9
+ var CONTEXT_PACK_SECTION_KEYS = [
10
+ "invariants",
11
+ "activeBeliefs",
12
+ "openQuestions",
13
+ "recentEvidence",
14
+ "contradictions"
33
15
  ];
34
- // =============================================================================
35
- // SECTION BUDGET RATIOS
36
- // =============================================================================
37
- /**
38
- * Token budget allocation ratios per section.
39
- * These sum to 1.0 and determine how the total tokenBudget is divided.
40
- *
41
- * Rationale:
42
- * - invariants (0.28): Highest-priority constraints, injected first
43
- * - activeBeliefs (0.30): Largest section, carries domain knowledge
44
- * - openQuestions (0.17): Unresolved work items guide agent behavior
45
- * - recentEvidence (0.17): Implementation context for grounding
46
- * - contradictions (0.08): Tension signals, smallest section
47
- */
48
- export const SECTION_BUDGET_RATIOS = {
49
- invariants: 0.28,
50
- activeBeliefs: 0.3,
51
- openQuestions: 0.17,
52
- recentEvidence: 0.17,
53
- contradictions: 0.08,
16
+ var SECTION_BUDGET_RATIOS = {
17
+ invariants: 0.28,
18
+ activeBeliefs: 0.3,
19
+ openQuestions: 0.17,
20
+ recentEvidence: 0.17,
21
+ contradictions: 0.08
54
22
  };
55
- // =============================================================================
56
- // TOKEN BUDGET CONSTRAINTS
57
- // =============================================================================
58
- /** Minimum allowed token budget. Below this, context packs lose utility. */
59
- export const MIN_TOKEN_BUDGET = 400;
60
- /** Maximum allowed token budget. Above this, context packs bloat prompts. */
61
- export const MAX_TOKEN_BUDGET = 8000;
62
- /** Default token budget when caller does not specify. */
63
- export const DEFAULT_TOKEN_BUDGET = 1800;
64
- /** Default max items per section. */
65
- export const DEFAULT_SECTION_LIMIT = 8;
66
- /** Hard ceiling on items per section. */
67
- export const MAX_SECTION_LIMIT = 25;
68
- /** Minimum contradiction section budget floor (tokens). */
69
- export const MIN_CONTRADICTION_BUDGET = 40;
70
- export const RANKING_WEIGHTS = {
71
- invariants: {
72
- query: 0.35,
73
- recency: 0.1,
74
- confidence: 0.4,
75
- beliefType: 0.15,
76
- },
77
- activeBeliefs: {
78
- query: 0.5,
79
- recency: 0.2,
80
- confidence: 0.2,
81
- beliefType: 0.1,
82
- },
83
- openQuestions: {
84
- query: 0.55,
85
- recency: 0.2,
86
- priority: 0.25,
87
- },
88
- recentEvidence: {
89
- query: 0.6,
90
- recency: 0.4,
91
- },
92
- contradictions: {
93
- query: 0.4,
94
- recency: 0.2,
95
- severity: 0.4,
96
- },
97
- };
98
- /** Recency decay half-life in days. After 30 days, recency score = 0.5. */
99
- export const RECENCY_HALF_LIFE_DAYS = 30;
100
- /**
101
- * Ranking weight vector for the relatedEntities section.
102
- * Entities are ranked by query relevance and connectivity (bridge edge count).
103
- * Separate from RANKING_WEIGHTS because entities are not part of the
104
- * token-budgeted injection plan.
105
- */
106
- export const ENTITY_RANKING_WEIGHTS = {
23
+ var MIN_TOKEN_BUDGET = 400;
24
+ var MAX_TOKEN_BUDGET = 8e3;
25
+ var DEFAULT_TOKEN_BUDGET = 1800;
26
+ var DEFAULT_SECTION_LIMIT = 8;
27
+ var MAX_SECTION_LIMIT = 25;
28
+ var MIN_CONTRADICTION_BUDGET = 40;
29
+ var RANKING_WEIGHTS = {
30
+ invariants: {
31
+ query: 0.35,
32
+ recency: 0.1,
33
+ confidence: 0.4,
34
+ beliefType: 0.15
35
+ },
36
+ activeBeliefs: {
37
+ query: 0.5,
38
+ recency: 0.2,
39
+ confidence: 0.2,
40
+ beliefType: 0.1
41
+ },
42
+ openQuestions: {
43
+ query: 0.55,
44
+ recency: 0.2,
45
+ priority: 0.25
46
+ },
47
+ recentEvidence: {
48
+ query: 0.6,
49
+ recency: 0.4
50
+ },
51
+ contradictions: {
107
52
  query: 0.4,
108
- connectivity: 0.6,
53
+ recency: 0.2,
54
+ severity: 0.4
55
+ }
56
+ };
57
+ var RECENCY_HALF_LIFE_DAYS = 30;
58
+ var ENTITY_RANKING_WEIGHTS = {
59
+ query: 0.4,
60
+ connectivity: 0.6
109
61
  };
110
- /** Default max entities to include in the context pack. */
111
- export const DEFAULT_ENTITY_LIMIT = 10;
112
- /** Hard ceiling on entities per context pack. */
113
- export const MAX_ENTITY_LIMIT = 50;
114
- // =============================================================================
115
- // BELIEF TYPE BONUS MAP
116
- // =============================================================================
117
- /**
118
- * Bonus multiplier for belief types in ranking.
119
- * Invariants get 1.0, unknown types get 0.4.
120
- */
121
- export const BELIEF_TYPE_BONUS = {
122
- invariant: 1.0,
123
- tenet: 0.8,
124
- principle: 0.6,
62
+ var DEFAULT_ENTITY_LIMIT = 10;
63
+ var MAX_ENTITY_LIMIT = 50;
64
+ var BELIEF_TYPE_BONUS = {
65
+ invariant: 1,
66
+ tenet: 0.8,
67
+ principle: 0.6
125
68
  };
126
- export const DEFAULT_BELIEF_TYPE_BONUS = 0.4;
127
- // =============================================================================
128
- // PRIORITY / SEVERITY SCORE MAPS
129
- // =============================================================================
130
- export const PRIORITY_SCORES = {
131
- critical: 1.0,
132
- high: 0.85,
133
- medium: 0.55,
134
- low: 0.35,
69
+ var DEFAULT_BELIEF_TYPE_BONUS = 0.4;
70
+ var PRIORITY_SCORES = {
71
+ critical: 1,
72
+ high: 0.85,
73
+ medium: 0.55,
74
+ low: 0.35
135
75
  };
136
- export const DEFAULT_PRIORITY_SCORE = 0.5;
137
- export const SEVERITY_SCORES = {
138
- critical: 1.0,
139
- high: 0.85,
140
- medium: 0.6,
141
- low: 0.35,
76
+ var DEFAULT_PRIORITY_SCORE = 0.5;
77
+ var SEVERITY_SCORES = {
78
+ critical: 1,
79
+ high: 0.85,
80
+ medium: 0.6,
81
+ low: 0.35
142
82
  };
143
- export const DEFAULT_SEVERITY_SCORE = 0.5;
144
- // =============================================================================
145
- // RESOLVED QUESTION STATUSES
146
- // =============================================================================
147
- /**
148
- * Question statuses that are considered "resolved" (not open).
149
- * Used to filter which questions appear in the openQuestions section.
150
- */
151
- export const RESOLVED_QUESTION_STATUSES = [
152
- "answered",
153
- "archived",
154
- "closed",
155
- "resolved",
156
- "resolved_support",
157
- "resolved_contra",
158
- "belief_forked",
83
+ var DEFAULT_SEVERITY_SCORE = 0.5;
84
+ var RESOLVED_QUESTION_STATUSES = [
85
+ "answered",
86
+ "archived",
87
+ "closed",
88
+ "resolved",
89
+ "resolved_support",
90
+ "resolved_contra",
91
+ "belief_forked"
159
92
  ];
160
- // =============================================================================
161
- // TOKEN ESTIMATION
162
- // =============================================================================
163
- /**
164
- * Tokens-per-word multiplier for rough token estimation.
165
- * Conservative estimate: ~1.35 tokens per whitespace-delimited word.
166
- */
167
- export const TOKENS_PER_WORD = 1.35;
168
- /** Minimum token estimate for any non-empty string. */
169
- export const MIN_TOKEN_ESTIMATE = 8;
93
+ var TOKENS_PER_WORD = 1.35;
94
+ var MIN_TOKEN_ESTIMATE = 8;
95
+
96
+ export { BELIEF_TYPE_BONUS, CONTEXT_PACK_SCHEMA_VERSION, CONTEXT_PACK_SECTION_KEYS, CONTEXT_RANKING_PROFILES, DEFAULT_BELIEF_TYPE_BONUS, DEFAULT_COMPILATION_MODE, DEFAULT_ENTITY_LIMIT, DEFAULT_PRIORITY_SCORE, DEFAULT_RANKING_PROFILE, DEFAULT_SECTION_LIMIT, DEFAULT_SEVERITY_SCORE, DEFAULT_TOKEN_BUDGET, ENTITY_RANKING_WEIGHTS, MAX_ENTITY_LIMIT, MAX_SECTION_LIMIT, MAX_TOKEN_BUDGET, MIN_CONTRADICTION_BUDGET, MIN_TOKEN_BUDGET, MIN_TOKEN_ESTIMATE, PRIORITY_SCORES, RANKING_WEIGHTS, RECENCY_HALF_LIFE_DAYS, RESOLVED_QUESTION_STATUSES, SECTION_BUDGET_RATIOS, SEVERITY_SCORES, TOKENS_PER_WORD };
97
+ //# sourceMappingURL=context-pack.contract.js.map
170
98
  //# sourceMappingURL=context-pack.contract.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"context-pack.contract.js","sourceRoot":"","sources":["../src/context-pack.contract.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AAEH,gFAAgF;AAChF,iBAAiB;AACjB,gFAAgF;A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QAAA;AAAA,EACA,UAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA;AACF;AAUO,IAAM,eAAA,GAAkB;AAGxB,IAAM,kBAAA,GAAqB","file":"context-pack.contract.js","sourcesContent":["/**\n * Context-Pack Contract v1\n *\n * Canonical TypeScript types and constants for the context-pack output schema.\n * This is the external contract consumed by:\n * - MCP tool `compile_context` (canonical compiler read)\n * - SDK/HTTP consumers that read compiled context packs programmatically\n * - Benchmark harnesses (context-pack-ab)\n *\n * BREAKING CHANGE RULES:\n * - Adding optional fields to ContextPackV1 is NON-breaking\n * - Removing fields or changing types is BREAKING (bump CONTEXT_PACK_SCHEMA_VERSION)\n * - Changing section budget ratios or ranking weights is NON-breaking (tuning)\n * - Changing the version string is BREAKING (consumers check it)\n */\n\n// =============================================================================\n// SCHEMA VERSION\n// =============================================================================\n\n/** Canonical version string. Consumers MUST check this field for compatibility. */\nexport const CONTEXT_PACK_SCHEMA_VERSION = \"1.0.0\" as const;\n\n// =============================================================================\n// RANKING PROFILES\n// =============================================================================\n\n/**\n * Available ranking profiles for context-pack assembly.\n *\n * - `baseline_v1`: Simple token-hit counting. Items with zero query hits are excluded.\n * - `weighted_v1`: Multi-signal scoring combining query relevance, recency, confidence,\n * belief type, priority, and severity with section-specific weight vectors.\n */\nexport type ContextRankingProfile = \"baseline_v1\" | \"weighted_v1\";\n\nexport const CONTEXT_RANKING_PROFILES: readonly ContextRankingProfile[] = [\n \"baseline_v1\",\n \"weighted_v1\",\n] as const;\n\nexport const DEFAULT_RANKING_PROFILE: ContextRankingProfile = \"weighted_v1\";\n\n// =============================================================================\n// COMPILATION MODE (RS-2)\n// =============================================================================\n\n/**\n * Context compilation mode.\n *\n * - `standard`: Default — ranked beliefs, questions, evidence, contradictions.\n * - `delta`: Diff-aware — adds failure context, verification obligations,\n * and worktree ledger analysis to the standard context pack.\n */\nexport type ContextCompilationMode = \"standard\" | \"delta\";\n\nexport const DEFAULT_COMPILATION_MODE: ContextCompilationMode = \"standard\";\n\n// =============================================================================\n// SECTION KEYS\n// =============================================================================\n\n/**\n * The five canonical sections of a context pack.\n * Order matters: invariants are injected first, contradictions last.\n */\nexport type ContextPackSectionKey =\n | \"invariants\"\n | \"activeBeliefs\"\n | \"openQuestions\"\n | \"recentEvidence\"\n | \"contradictions\";\n\nexport const CONTEXT_PACK_SECTION_KEYS: readonly ContextPackSectionKey[] = [\n \"invariants\",\n \"activeBeliefs\",\n \"openQuestions\",\n \"recentEvidence\",\n \"contradictions\",\n] as const;\n\n// =============================================================================\n// SECTION BUDGET RATIOS\n// =============================================================================\n\n/**\n * Token budget allocation ratios per section.\n * These sum to 1.0 and determine how the total tokenBudget is divided.\n *\n * Rationale:\n * - invariants (0.28): Highest-priority constraints, injected first\n * - activeBeliefs (0.30): Largest section, carries domain knowledge\n * - openQuestions (0.17): Unresolved work items guide agent behavior\n * - recentEvidence (0.17): Implementation context for grounding\n * - contradictions (0.08): Tension signals, smallest section\n */\nexport const SECTION_BUDGET_RATIOS: Readonly<\n Record<ContextPackSectionKey, number>\n> = {\n invariants: 0.28,\n activeBeliefs: 0.3,\n openQuestions: 0.17,\n recentEvidence: 0.17,\n contradictions: 0.08,\n} as const;\n\n// =============================================================================\n// TOKEN BUDGET CONSTRAINTS\n// =============================================================================\n\n/** Minimum allowed token budget. Below this, context packs lose utility. */\nexport const MIN_TOKEN_BUDGET = 400;\n\n/** Maximum allowed token budget. Above this, context packs bloat prompts. */\nexport const MAX_TOKEN_BUDGET = 8000;\n\n/** Default token budget when caller does not specify. */\nexport const DEFAULT_TOKEN_BUDGET = 1800;\n\n/** Default max items per section. */\nexport const DEFAULT_SECTION_LIMIT = 8;\n\n/** Hard ceiling on items per section. */\nexport const MAX_SECTION_LIMIT = 25;\n\n/** Minimum contradiction section budget floor (tokens). */\nexport const MIN_CONTRADICTION_BUDGET = 40;\n\n// =============================================================================\n// RANKING WEIGHT VECTORS\n// =============================================================================\n\n/**\n * Weight vectors for the weighted_v1 ranking profile.\n * Each section has a different signal mix:\n *\n * - query: How many query tokens appear in the candidate text\n * - recency: Exponential decay from updatedAt (half-life = 30 days)\n * - confidence: Belief confidence score [0,1]\n * - beliefType: Bonus for invariant > tenet > principle > other\n * - priority: Question priority (critical > high > medium > low)\n * - severity: Contradiction severity (critical > high > medium > low)\n */\nexport type RankingWeightVector = {\n query: number;\n recency: number;\n confidence?: number;\n beliefType?: number;\n priority?: number;\n severity?: number;\n};\n\nexport const RANKING_WEIGHTS: Readonly<\n Record<ContextPackSectionKey, RankingWeightVector>\n> = {\n invariants: {\n query: 0.35,\n recency: 0.1,\n confidence: 0.4,\n beliefType: 0.15,\n },\n activeBeliefs: {\n query: 0.5,\n recency: 0.2,\n confidence: 0.2,\n beliefType: 0.1,\n },\n openQuestions: {\n query: 0.55,\n recency: 0.2,\n priority: 0.25,\n },\n recentEvidence: {\n query: 0.6,\n recency: 0.4,\n },\n contradictions: {\n query: 0.4,\n recency: 0.2,\n severity: 0.4,\n },\n} as const;\n\n/** Recency decay half-life in days. After 30 days, recency score = 0.5. */\nexport const RECENCY_HALF_LIFE_DAYS = 30;\n\n/**\n * Ranking weight vector for the relatedEntities section.\n * Entities are ranked by query relevance and connectivity (bridge edge count).\n * Separate from RANKING_WEIGHTS because entities are not part of the\n * token-budgeted injection plan.\n */\nexport const ENTITY_RANKING_WEIGHTS = {\n query: 0.4,\n connectivity: 0.6,\n} as const;\n\n/** Default max entities to include in the context pack. */\nexport const DEFAULT_ENTITY_LIMIT = 10;\n\n/** Hard ceiling on entities per context pack. */\nexport const MAX_ENTITY_LIMIT = 50;\n\n// =============================================================================\n// BELIEF TYPE BONUS MAP\n// =============================================================================\n\n/**\n * Bonus multiplier for belief types in ranking.\n * Invariants get 1.0, unknown types get 0.4.\n */\nexport const BELIEF_TYPE_BONUS: Readonly<Record<string, number>> = {\n invariant: 1.0,\n tenet: 0.8,\n principle: 0.6,\n} as const;\n\nexport const DEFAULT_BELIEF_TYPE_BONUS = 0.4;\n\n// =============================================================================\n// PRIORITY / SEVERITY SCORE MAPS\n// =============================================================================\n\nexport const PRIORITY_SCORES: Readonly<Record<string, number>> = {\n critical: 1.0,\n high: 0.85,\n medium: 0.55,\n low: 0.35,\n} as const;\n\nexport const DEFAULT_PRIORITY_SCORE = 0.5;\n\nexport const SEVERITY_SCORES: Readonly<Record<string, number>> = {\n critical: 1.0,\n high: 0.85,\n medium: 0.6,\n low: 0.35,\n} as const;\n\nexport const DEFAULT_SEVERITY_SCORE = 0.5;\n\n// =============================================================================\n// SECTION ITEM TYPES\n// =============================================================================\n\n/** A ranked belief in the invariants or activeBeliefs section. */\nexport type ContextPackBelief = {\n nodeId: string;\n canonicalText: string;\n confidence: number | null;\n beliefType: string | null;\n score: number;\n /** Present in activeBeliefs, absent in invariants */\n status?: string;\n updatedAt?: number | null;\n /** Human-readable explanation of why this item was ranked here (RS-2). */\n justification?: string;\n};\n\n/** A ranked question in the openQuestions section. */\nexport type ContextPackQuestion = {\n questionId: string;\n text: string;\n status: string;\n priority: string;\n updatedAt?: number | null;\n score: number;\n /** Human-readable explanation of why this item was ranked here (RS-2). */\n justification?: string;\n};\n\n/** A ranked evidence item in the recentEvidence section. */\nexport type ContextPackEvidence = {\n nodeId: string;\n canonicalText: string;\n sourceUrl: string | null;\n kind: string;\n createdAt: number | null;\n score: number;\n /** Human-readable explanation of why this item was ranked here (RS-2). */\n justification?: string;\n};\n\n/** A ranked contradiction in the contradictions section. */\nexport type ContextPackContradiction = {\n contradictionId: string;\n severity: string;\n status: string;\n description: string;\n score: number;\n /** Human-readable explanation of why this item was ranked here (RS-2). */\n justification?: string;\n};\n\n/**\n * An entity from the ontological layer surfaced in the context pack.\n * Entities are domain objects (companies, people, functions, etc.) connected\n * to beliefs via bridge edges. They provide the \"reality anchor\" that makes\n * the reasoning graph domain-aware.\n */\nexport type ContextPackEntity = {\n /** Convex document ID of the entity node. */\n nodeId: string;\n /** Entity type (e.g., \"company\", \"person\", \"function\"). */\n entityType: string;\n /** Human-readable title/name of the entity. */\n title: string;\n /** Number of beliefs connected to this entity via bridge edges. */\n connectedBeliefCount: number;\n /** Number of evidence items referencing this entity. */\n connectedEvidenceCount: number;\n /** Relevance score from ranking algorithm. */\n score: number;\n /** Entity metadata (structured per ontology schema). */\n metadata?: Record<string, unknown>;\n};\n\n/**\n * A lattice seed entry representing a belief that was auto-generated\n * to cover an ontology entity type within a topic scope.\n */\nexport type BeliefLatticeSeed = {\n /** The belief node ID that was created or already existed. */\n beliefNodeId: string;\n /** The entity type this seed belief covers. */\n entityType: string;\n /** Whether this seed was newly created or already existed. */\n created: boolean;\n /** The canonical text of the seed belief. */\n canonicalText: string;\n};\n\n// =============================================================================\n// SUMMARY\n// =============================================================================\n\n/** Counts and scoped health signals for the context pack. */\nexport type ContextPackSummary = {\n totalBeliefs: number;\n invariants: number;\n openQuestions: number;\n evidenceItems: number;\n contradictions: number;\n /** Number of ontological entities in scope (optional, present when entity graph is active). */\n relatedEntities?: number;\n scopedTopics: number;\n descendantDepth: number;\n query: string | null;\n};\n\n// =============================================================================\n// FAILURE CONTEXT (RS-2)\n// =============================================================================\n\n/** A failed approach surfaced from the failure log for anti-repetition. */\nexport type ContextPackFailure = {\n /** Lucern attempt/evidence node ID. */\n attemptId: string;\n /** What was tried. */\n approach: string;\n /** Why it failed. */\n outcome: string;\n /** When the attempt was recorded (ms since epoch). */\n recordedAt: number;\n /** Relevance score from ranking algorithm. */\n score: number;\n};\n\n/** Failure context section appended to context packs in delta mode. */\nexport type ContextPackFailureContext = {\n /** Ranked failed approaches relevant to the current query. */\n failures: ContextPackFailure[];\n /** IDs of items suppressed from other sections due to anti-repetition. */\n suppressedIds: string[];\n};\n\n// =============================================================================\n// DELTA REPORT (RS-2)\n// =============================================================================\n\n/** A verification obligation surfaced by delta compilation. */\nexport type VerificationObligation = {\n /** What must be verified. */\n description: string;\n /** Source of the obligation (e.g., \"belief:xyz confidence drop\"). */\n source: string;\n /** Severity: how important it is to verify. */\n severity: \"critical\" | \"high\" | \"medium\" | \"low\";\n};\n\n/** Delta report appended to context packs when mode = \"delta\". */\nexport type ContextPackDeltaReport = {\n /** Items that changed since the reference point (new, updated, removed). */\n changedItems: Array<{\n id: string;\n section: ContextPackSectionKey;\n changeType: \"added\" | \"updated\" | \"removed\" | \"confidence_changed\";\n summary: string;\n }>;\n /** Obligations the consuming session must verify. */\n verificationObligations: VerificationObligation[];\n /** Reference point for the delta (worktree ID, timestamp, or commit SHA). */\n referencePoint: string;\n};\n\n// =============================================================================\n// PACK WEIGHT OVERRIDES (RS-2)\n// =============================================================================\n\n/**\n * Per-section weight overrides that domain packs can apply.\n * Overrides merge with RANKING_WEIGHTS — only specified fields replace defaults.\n */\nexport type PackWeightOverride = {\n /** Which section to override weights for. */\n section: ContextPackSectionKey;\n /** Partial weight vector — only specified fields replace defaults. */\n weights: Partial<RankingWeightVector>;\n};\n\n// =============================================================================\n// INJECTION POLICY\n// =============================================================================\n\n/** Token-budgeted section selections for prompt injection. */\nexport type ContextPackInjectionPolicy = {\n /** Total token budget for the entire context pack. */\n tokenBudget: number;\n /** Estimated tokens consumed across all sections. */\n estimatedTokens: number;\n /** Per-section token budgets derived from SECTION_BUDGET_RATIOS. */\n sectionBudgets: Record<ContextPackSectionKey, number>;\n /** Actual token usage per section after greedy fill. */\n sectionUsage: Record<ContextPackSectionKey, number>;\n /** Node/question IDs selected for injection, per section. */\n selected: Record<ContextPackSectionKey, string[]>;\n /** Items that were scored but excluded from injection, with reason (RS-2). */\n excludedItems?: Array<{\n id: string;\n section: ContextPackSectionKey;\n reason: \"budget_exceeded\" | \"anti_repetition\" | \"below_threshold\";\n score: number;\n }>;\n};\n\n// =============================================================================\n// DIAGNOSTICS\n// =============================================================================\n\n/** Telemetry for context pack assembly. */\nexport type ContextPackDiagnostics = {\n /** Total candidates scored across all sections. */\n itemsScored: number;\n /** Ratio of estimatedTokens / tokenBudget. Range [0, 1+]. */\n tokenBudgetUtilization: number;\n};\n\n// =============================================================================\n// PUBLIC COMPILED CONTEXT TYPES\n// =============================================================================\n\n/**\n * Public context surface returned by the SDK-facing context client.\n *\n * This preserves the existing external shape while the canonical compiler\n * contract evolves in parallel as ContextPackV1.\n */\nexport type PublicContextBelief = {\n beliefId: string;\n text: string;\n confidence: number | null;\n beliefType?: string | null;\n status?: string;\n updatedAt?: number | null;\n score: number;\n justification?: string;\n};\n\nexport type PublicContextQuestion = {\n questionId: string;\n text: string;\n status: string;\n priority: string;\n updatedAt?: number | null;\n score: number;\n justification?: string;\n};\n\nexport type PublicContextEvidence = {\n evidenceId: string;\n text: string;\n sourceUrl?: string | null;\n kind: string;\n createdAt?: number | null;\n score: number;\n justification?: string;\n};\n\nexport type PublicContextContradiction = {\n contradictionId: string;\n severity: string;\n status: string;\n description: string;\n score: number;\n justification?: string;\n};\n\nexport type PublicContextEntity = {\n entityId: string;\n entityType: string;\n title: string;\n text?: string;\n connectedBeliefCount: number;\n connectedEvidenceCount: number;\n score: number;\n metadata?: Record<string, unknown>;\n};\n\nexport type PublicContextInjectionPolicy = {\n tokenBudget: number;\n estimatedTokens: number;\n sectionBudgets: Record<string, number>;\n sectionUsage: Record<string, number>;\n selected: Record<string, string[]>;\n excludedItems?: Array<{\n id: string;\n section: string;\n reason: \"budget_exceeded\" | \"anti_repetition\" | \"below_threshold\";\n score: number;\n }>;\n};\n\nexport type PublicCompiledContext = {\n schemaVersion: string;\n topicId: string;\n topicName: string;\n scopedTopicIds: string[];\n generatedAt: number;\n ranking: ContextRankingProfile;\n summary: Record<string, unknown>;\n invariants: PublicContextBelief[];\n activeBeliefs: PublicContextBelief[];\n openQuestions: PublicContextQuestion[];\n recentEvidence: PublicContextEvidence[];\n contradictions: PublicContextContradiction[];\n relatedEntities?: PublicContextEntity[];\n contextNarrative: string[];\n injectionPolicy: PublicContextInjectionPolicy;\n diagnostics: Record<string, unknown>;\n compilationMode?: string;\n failureContext?: {\n failures: Array<{\n attemptId: string;\n approach: string;\n outcome: string;\n recordedAt: number;\n score: number;\n }>;\n suppressedIds: string[];\n };\n deltaReport?: {\n changedItems: Array<{\n id: string;\n section: string;\n changeType: string;\n summary: string;\n }>;\n verificationObligations: Array<{\n description: string;\n source: string;\n severity: \"critical\" | \"high\" | \"medium\" | \"low\";\n }>;\n referencePoint: string;\n };\n appliedWeightOverrides?: unknown[];\n};\n\n// =============================================================================\n// CONTEXT PACK V1 (TOP-LEVEL OUTPUT)\n// =============================================================================\n\n/**\n * The canonical output schema for context compilation responses.\n *\n * This is the contract that consumers depend on. All fields are required\n * in the output. Adding optional fields is non-breaking; removing or\n * changing types is breaking (requires version bump).\n */\nexport type ContextPackV1 = {\n /** Schema version for compatibility checking. */\n schemaVersion: typeof CONTEXT_PACK_SCHEMA_VERSION;\n /** Deprecated compatibility alias for the requested scope ID. */\n projectId?: string;\n /** Resolved topic ID after scope resolution. */\n topicId: string;\n /** Human-readable topic name. */\n topicName: string;\n /** All topic IDs included in the neighborhood expansion. */\n scopedTopicIds: string[];\n /** Deterministic freshness watermark for this pack (ms since epoch). */\n generatedAt: number;\n /** Which ranking profile was used. */\n rankingProfile: ContextRankingProfile;\n /** Aggregate counts and health signals. */\n summary: ContextPackSummary;\n /** High-confidence invariant beliefs (beliefType = \"invariant\"). */\n invariants: ContextPackBelief[];\n /** Active beliefs ranked by query relevance. */\n activeBeliefs: ContextPackBelief[];\n /** Open questions ranked by relevance and priority. */\n openQuestions: ContextPackQuestion[];\n /** Recent evidence ranked by relevance and recency. */\n recentEvidence: ContextPackEvidence[];\n /** Active contradictions ranked by severity. */\n contradictions: ContextPackContradiction[];\n /**\n * Ontological entities connected to beliefs in scope, ranked by connectivity.\n * Optional — present when entity graph substrate is active for this topic.\n * NON-BREAKING addition per contract rules.\n */\n relatedEntities?: ContextPackEntity[];\n /** Concise instructions for agent context injection. */\n contextNarrative: string[];\n /** Token-budgeted injection selections. */\n injectionPolicy: ContextPackInjectionPolicy;\n /** Assembly telemetry. */\n diagnostics: ContextPackDiagnostics;\n /** Compilation mode used to generate this pack (RS-2). Default: \"standard\". */\n compilationMode?: ContextCompilationMode;\n /** Failure context for anti-repetition (RS-2). Present when failures are relevant. */\n failureContext?: ContextPackFailureContext;\n /** Delta report (RS-2). Present only when compilationMode = \"delta\". */\n deltaReport?: ContextPackDeltaReport;\n /** Pack weight overrides applied during ranking (RS-2). */\n appliedWeightOverrides?: PackWeightOverride[];\n};\n\n// =============================================================================\n// CONTEXT PACK REQUEST V1 (INPUT)\n// =============================================================================\n\n/**\n * The canonical input schema for `compile_context`.\n * `topicId` is canonical. `projectId` remains an optional compatibility alias.\n */\nexport type ContextPackRequestV1 = {\n /** Topic scope ID (required). */\n topicId: string;\n /** Deprecated compatibility alias for older callers. */\n projectId?: string;\n /** Focus query for relevance ranking. */\n query?: string;\n /** Max items per section. Default: DEFAULT_SECTION_LIMIT. */\n limit?: number;\n /** Ranking profile. Default: DEFAULT_RANKING_PROFILE. */\n rankingProfile?: ContextRankingProfile;\n /** Total token budget. Default: DEFAULT_TOKEN_BUDGET. */\n tokenBudget?: number;\n /** Descendant topic depth for neighborhood expansion. */\n maxDepth?: number;\n /** Include ontological entities connected to beliefs in scope. Default: true. */\n includeEntities?: boolean;\n /** Compilation mode (RS-2). Default: \"standard\". */\n mode?: ContextCompilationMode;\n /** Include failure log context for anti-repetition (RS-2). Default: false. */\n includeFailures?: boolean;\n /** Active worktree ID for delta mode reference point (RS-2). */\n worktreeId?: string;\n /** Session ID for anti-repetition dedup (RS-2). */\n sessionId?: string;\n /** Pack weight overrides from domain pack binding (RS-2). */\n packWeightOverrides?: PackWeightOverride[];\n};\n\n// =============================================================================\n// RESOLVED QUESTION STATUSES\n// =============================================================================\n\n/**\n * Question statuses that are considered \"resolved\" (not open).\n * Used to filter which questions appear in the openQuestions section.\n */\nexport const RESOLVED_QUESTION_STATUSES: readonly string[] = [\n \"answered\",\n \"archived\",\n \"closed\",\n \"resolved\",\n \"resolved_support\",\n \"resolved_contra\",\n \"belief_forked\",\n] as const;\n\n// =============================================================================\n// TOKEN ESTIMATION\n// =============================================================================\n\n/**\n * Tokens-per-word multiplier for rough token estimation.\n * Conservative estimate: ~1.35 tokens per whitespace-delimited word.\n */\nexport const TOKENS_PER_WORD = 1.35;\n\n/** Minimum token estimate for any non-empty string. */\nexport const MIN_TOKEN_ESTIMATE = 8;\n"]}
@@ -0,0 +1,7 @@
1
+ interface ConvexAdminClient {
2
+ query<T = unknown>(functionReference: unknown, args: Record<string, unknown>): Promise<T>;
3
+ mutation<T = unknown>(functionReference: unknown, args: Record<string, unknown>): Promise<T>;
4
+ action<T = unknown>(functionReference: unknown, args: Record<string, unknown>): Promise<T>;
5
+ }
6
+
7
+ export type { ConvexAdminClient };
@@ -0,0 +1,3 @@
1
+
2
+ //# sourceMappingURL=convex-admin.contract.js.map
3
+ //# sourceMappingURL=convex-admin.contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":[],"names":[],"mappings":"","file":"convex-admin.contract.js"}
@@ -0,0 +1 @@
1
+ export { CreateDomainEventInput, DOMAIN_EVENT_TYPES, DOMAIN_EVENT_VERSION, DomainActorType, DomainEvent, DomainEventData, DomainEventType, DomainResourceType, EVENT_RETENTION_DEFAULT_DAYS, EventCursor, EventListQuery, EventListResult, ReplayEventsInput, ReplayEventsResult, WEBHOOK_MAX_ATTEMPTS, WEBHOOK_RETRY_DELAYS_MS, WebhookCreateInput, WebhookDeliveriesResult, WebhookDeliveryAttemptRecord, WebhookDeliveryRecord, WebhookDeliveryStatus, WebhookHealthResult, WebhookRecord, WebhookSecretMode, WebhookTestResult, WebhookUpdateInput, buildDomainEvent, compareEventCursor, createEventId, decodeEventCursor, emitDomainEvent, encodeEventCursor, inferActorType, isAfterCursor, normalizeRetentionDays, sortEventsByCursor } from './events.contract.js';
@@ -0,0 +1,136 @@
1
+ // src/events.contract.ts
2
+ var DOMAIN_EVENT_VERSION = "1.0";
3
+ var EVENT_RETENTION_DEFAULT_DAYS = 30;
4
+ var WEBHOOK_MAX_ATTEMPTS = 5;
5
+ var WEBHOOK_RETRY_DELAYS_MS = [1e3, 5e3, 3e4, 3e5];
6
+ var DOMAIN_EVENT_TYPES = [
7
+ "belief.created",
8
+ "belief.forked",
9
+ "belief.confidence_updated",
10
+ "belief.archived",
11
+ "belief.refined",
12
+ "belief.contract_created",
13
+ "belief.contract_evaluated",
14
+ "belief.lineage_queried",
15
+ "evidence.created",
16
+ "evidence.linked",
17
+ "evidence.search_executed",
18
+ "question.created",
19
+ "question.answered",
20
+ "question.refined",
21
+ "question.status_updated",
22
+ "question.archived",
23
+ "edge.created",
24
+ "contradiction.flagged",
25
+ "worktree.created",
26
+ "worktree.activated",
27
+ "worktree.merged",
28
+ "worktree.targets_updated",
29
+ "worktree.metadata_updated",
30
+ "topic.created",
31
+ "topic.updated",
32
+ "topic.archived",
33
+ "task.created",
34
+ "task.completed",
35
+ "task.updated",
36
+ "ontology.bound",
37
+ "context.compiled",
38
+ "identity.key_created",
39
+ "identity.key_rotated",
40
+ "identity.key_revoked",
41
+ "webhook.test"
42
+ ];
43
+ function toBase64(value) {
44
+ if (typeof Buffer !== "undefined") {
45
+ return Buffer.from(value, "utf8").toString("base64url");
46
+ }
47
+ return btoa(unescape(encodeURIComponent(value))).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, "");
48
+ }
49
+ function fromBase64(value) {
50
+ if (typeof Buffer !== "undefined") {
51
+ return Buffer.from(value, "base64url").toString("utf8");
52
+ }
53
+ const normalized = value.replace(/-/g, "+").replace(/_/g, "/");
54
+ return decodeURIComponent(escape(atob(normalized)));
55
+ }
56
+ function createEventId() {
57
+ const random = crypto.randomUUID().replace(/-/g, "");
58
+ return `evt_${random}`;
59
+ }
60
+ function normalizeRetentionDays(value) {
61
+ if (!Number.isFinite(value) || typeof value !== "number" || value <= 0) {
62
+ return EVENT_RETENTION_DEFAULT_DAYS;
63
+ }
64
+ return Math.max(1, Math.trunc(value));
65
+ }
66
+ function buildDomainEvent(input) {
67
+ const timestamp = input.timestamp ?? Date.now();
68
+ const retentionDays = normalizeRetentionDays(input.retentionDays);
69
+ return {
70
+ eventId: input.eventId?.trim() || createEventId(),
71
+ type: input.type.trim(),
72
+ version: DOMAIN_EVENT_VERSION,
73
+ timestamp,
74
+ tenantId: input.tenantId?.trim() || void 0,
75
+ workspaceId: input.workspaceId?.trim() || void 0,
76
+ topicId: input.topicId.trim(),
77
+ resourceId: input.resourceId.trim(),
78
+ resourceType: input.resourceType.trim(),
79
+ actorId: input.actorId.trim(),
80
+ actorType: input.actorType,
81
+ data: input.data ?? {},
82
+ correlationId: input.correlationId?.trim() || void 0,
83
+ expiresAt: timestamp + retentionDays * 24 * 60 * 60 * 1e3
84
+ };
85
+ }
86
+ function compareEventCursor(left, right) {
87
+ if (left.timestamp !== right.timestamp) {
88
+ return left.timestamp - right.timestamp;
89
+ }
90
+ return left.eventId.localeCompare(right.eventId);
91
+ }
92
+ function encodeEventCursor(cursor) {
93
+ return toBase64(JSON.stringify(cursor));
94
+ }
95
+ function decodeEventCursor(cursor) {
96
+ if (!cursor || cursor.trim().length === 0) {
97
+ return null;
98
+ }
99
+ try {
100
+ const parsed = JSON.parse(fromBase64(cursor.trim()));
101
+ if (typeof parsed.timestamp !== "number" || !Number.isFinite(parsed.timestamp) || typeof parsed.eventId !== "string" || parsed.eventId.trim().length === 0) {
102
+ return null;
103
+ }
104
+ return {
105
+ timestamp: parsed.timestamp,
106
+ eventId: parsed.eventId.trim()
107
+ };
108
+ } catch {
109
+ return null;
110
+ }
111
+ }
112
+ function isAfterCursor(event, cursor) {
113
+ if (!cursor) {
114
+ return true;
115
+ }
116
+ return compareEventCursor(event, cursor) > 0;
117
+ }
118
+ function sortEventsByCursor(events) {
119
+ return [...events].sort((left, right) => compareEventCursor(left, right));
120
+ }
121
+ function inferActorType(args) {
122
+ if (args.sessionType === "agent") {
123
+ return "agent";
124
+ }
125
+ if (args.authMode === "service_principal" || args.authMode === "tenant_api_key" || args.principalType === "service") {
126
+ return "service";
127
+ }
128
+ return "human";
129
+ }
130
+ async function emitDomainEvent(invokeMutation, input) {
131
+ return await invokeMutation("events:recordEvent", input);
132
+ }
133
+
134
+ export { DOMAIN_EVENT_TYPES, DOMAIN_EVENT_VERSION, EVENT_RETENTION_DEFAULT_DAYS, WEBHOOK_MAX_ATTEMPTS, WEBHOOK_RETRY_DELAYS_MS, buildDomainEvent, compareEventCursor, createEventId, decodeEventCursor, emitDomainEvent, encodeEventCursor, inferActorType, isAfterCursor, normalizeRetentionDays, sortEventsByCursor };
135
+ //# sourceMappingURL=events-types.contract.js.map
136
+ //# sourceMappingURL=events-types.contract.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/events.contract.ts"],"names":[],"mappings":";AAiBO,IAAM,oBAAA,GAAuB;AAC7B,IAAM,4BAAA,GAA+B;AACrC,IAAM,oBAAA,GAAuB;AAC7B,IAAM,uBAAA,GAA0B,CAAC,GAAA,EAAO,GAAA,EAAO,KAAQ,GAAO;AAE9D,IAAM,kBAAA,GAAqB;AAAA,EAChC,gBAAA;AAAA,EACA,eAAA;AAAA,EACA,2BAAA;AAAA,EACA,iBAAA;AAAA,EACA,gBAAA;AAAA,EACA,yBAAA;AAAA,EACA,2BAAA;AAAA,EACA,wBAAA;AAAA,EACA,kBAAA;AAAA,EACA,iBAAA;AAAA,EACA,0BAAA;AAAA,EACA,kBAAA;AAAA,EACA,mBAAA;AAAA,EACA,kBAAA;AAAA,EACA,yBAAA;AAAA,EACA,mBAAA;AAAA,EACA,cAAA;AAAA,EACA,uBAAA;AAAA,EACA,kBAAA;AAAA,EACA,oBAAA;AAAA,EACA,iBAAA;AAAA,EACA,0BAAA;AAAA,EACA,2BAAA;AAAA,EACA,eAAA;AAAA,EACA,eAAA;AAAA,EACA,gBAAA;AAAA,EACA,cAAA;AAAA,EACA,gBAAA;AAAA,EACA,cAAA;AAAA,EACA,gBAAA;AAAA,EACA,kBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA,sBAAA;AAAA,EACA;AACF;AAiMA,SAAS,SAAS,K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,EACT;AACA,EAAA,IACE,IAAA,CAAK,aAAa,mBAAA,IAClB,IAAA,CAAK,aAAa,gBAAA,IAClB,IAAA,CAAK,kBAAkB,SAAA,EACvB;AACA,IAAA,OAAO,SAAA;AAAA,EACT;AACA,EAAA,OAAO,OAAA;AACT;AAEA,eAAsB,eAAA,CACpB,gBACA,KAAA,EACkB;AAClB,EAAA,OAAO,MAAM,cAAA,CAAe,oBAAA,EAA6B,KAAK,CAAA;AAChE","file":"events-types.contract.js","sourcesContent":["/**\n * @lucern/contracts — events (canonical support contract)\n *\n * Consolidated flat support surface for Lucern's domain event stream:\n * - Event type definitions, constants, and shared enums\n * - Event construction + cursor helpers\n *\n * Consolidated from the former split type-definition module\n * and the prior src/events.contract.ts (helpers) in EK-16 T1 PR 3b.\n * Compat shim remains at the old events-types path until Lucern 1.0.0 (D12).\n */\n\n// =============================================================================\n// EVENT TYPE DEFINITIONS & CONSTANTS\n// (Formerly the split events type-definition module)\n// =============================================================================\n\nexport const DOMAIN_EVENT_VERSION = \"1.0\" as const;\nexport const EVENT_RETENTION_DEFAULT_DAYS = 30;\nexport const WEBHOOK_MAX_ATTEMPTS = 5;\nexport const WEBHOOK_RETRY_DELAYS_MS = [1_000, 5_000, 30_000, 300_000] as const;\n\nexport const DOMAIN_EVENT_TYPES = [\n \"belief.created\",\n \"belief.forked\",\n \"belief.confidence_updated\",\n \"belief.archived\",\n \"belief.refined\",\n \"belief.contract_created\",\n \"belief.contract_evaluated\",\n \"belief.lineage_queried\",\n \"evidence.created\",\n \"evidence.linked\",\n \"evidence.search_executed\",\n \"question.created\",\n \"question.answered\",\n \"question.refined\",\n \"question.status_updated\",\n \"question.archived\",\n \"edge.created\",\n \"contradiction.flagged\",\n \"worktree.created\",\n \"worktree.activated\",\n \"worktree.merged\",\n \"worktree.targets_updated\",\n \"worktree.metadata_updated\",\n \"topic.created\",\n \"topic.updated\",\n \"topic.archived\",\n \"task.created\",\n \"task.completed\",\n \"task.updated\",\n \"ontology.bound\",\n \"context.compiled\",\n \"identity.key_created\",\n \"identity.key_rotated\",\n \"identity.key_revoked\",\n \"webhook.test\",\n] as const;\n\nexport type DomainEventType = (typeof DOMAIN_EVENT_TYPES)[number];\n\nexport type DomainResourceType =\n | \"belief\"\n | \"evidence\"\n | \"question\"\n | \"edge\"\n | \"contradiction\"\n | \"worktree\"\n | \"topic\"\n | \"task\"\n | \"ontology\"\n | \"context\"\n | \"identity\"\n | \"webhook\";\n\nexport type DomainActorType = \"human\" | \"agent\" | \"service\";\n\nexport type DomainEventData = Record<string, unknown>;\n\nexport type DomainEvent = {\n eventId: string;\n type: DomainEventType | string;\n version: typeof DOMAIN_EVENT_VERSION;\n timestamp: number;\n tenantId?: string;\n workspaceId?: string;\n topicId: string;\n resourceId: string;\n resourceType: DomainResourceType | string;\n actorId: string;\n actorType: DomainActorType;\n data: DomainEventData;\n correlationId?: string;\n expiresAt: number;\n};\n\nexport type CreateDomainEventInput = {\n eventId?: string;\n timestamp?: number;\n tenantId?: string;\n workspaceId?: string;\n topicId: string;\n type: DomainEventType | string;\n resourceId: string;\n resourceType: DomainResourceType | string;\n actorId: string;\n actorType: DomainActorType;\n data?: DomainEventData;\n correlationId?: string;\n retentionDays?: number;\n};\n\nexport type EventCursor = {\n timestamp: number;\n eventId: string;\n};\n\nexport type EventListQuery = {\n topicId?: string;\n after?: string;\n types?: string[];\n startTime?: number;\n endTime?: number;\n limit?: number;\n};\n\nexport type EventListResult = {\n events: DomainEvent[];\n nextCursor: string | null;\n};\n\nexport type WebhookSecretMode = \"configured\";\n\nexport type WebhookRecord = {\n id: string;\n webhookId: string;\n tenantId?: string;\n workspaceId?: string;\n topicId?: string;\n url: string;\n events: string[];\n active: boolean;\n secretConfigured: boolean;\n createdAt: number;\n updatedAt: number;\n createdBy: string;\n updatedBy: string;\n lastDeliveryAt?: number;\n lastSuccessfulDeliveryAt?: number;\n};\n\nexport type WebhookCreateInput = {\n url: string;\n events: string[];\n secret: string;\n topicId?: string;\n active?: boolean;\n};\n\nexport type WebhookUpdateInput = {\n url?: string;\n events?: string[];\n secret?: string;\n topicId?: string | null;\n active?: boolean;\n};\n\nexport type WebhookDeliveryStatus =\n | \"pending\"\n | \"delivering\"\n | \"succeeded\"\n | \"failed\"\n | \"dead_letter\";\n\nexport type WebhookDeliveryRecord = {\n id: string;\n deliveryId: string;\n webhookId: string;\n eventId: string;\n eventType: string;\n topicId: string;\n status: WebhookDeliveryStatus;\n attemptCount: number;\n maxAttempts: number;\n nextAttemptAt?: number;\n lastAttemptAt?: number;\n lastStatusCode?: number;\n lastError?: string;\n deliveredAt?: number;\n createdAt: number;\n updatedAt: number;\n};\n\nexport type WebhookDeliveryAttemptRecord = {\n id: string;\n attemptId: string;\n deliveryId: string;\n webhookId: string;\n eventId: string;\n eventType: string;\n attemptNumber: number;\n status: \"succeeded\" | \"failed\";\n statusCode?: number;\n error?: string;\n responseBody?: string;\n durationMs?: number;\n createdAt: number;\n};\n\nexport type WebhookDeliveriesResult = {\n deliveries: Array<\n WebhookDeliveryRecord & {\n attempts?: WebhookDeliveryAttemptRecord[];\n }\n >;\n};\n\nexport type WebhookHealthResult = {\n webhookId: string;\n totalAttempts: number;\n successfulAttempts: number;\n failedAttempts: number;\n successRate: number;\n pendingDeliveries: number;\n deadLetterDeliveries: number;\n lastDeliveryAt?: number;\n lastSuccessfulDeliveryAt?: number;\n};\n\nexport type WebhookTestResult = {\n webhookId: string;\n deliveryId: string;\n status: WebhookDeliveryStatus;\n attempts: number;\n};\n\nexport type ReplayEventsInput = EventListQuery & {\n webhookId?: string;\n};\n\nexport type ReplayEventsResult = EventListResult & {\n replayedDeliveries?: number;\n replayedWebhookId?: string;\n};\n\n// =============================================================================\n// EVENT HELPERS\n// (Formerly the body of src/events.contract.ts)\n// =============================================================================\n\nfunction toBase64(value: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(value, \"utf8\").toString(\"base64url\");\n }\n return btoa(unescape(encodeURIComponent(value)))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/g, \"\");\n}\n\nfunction fromBase64(value: string): string {\n if (typeof Buffer !== \"undefined\") {\n return Buffer.from(value, \"base64url\").toString(\"utf8\");\n }\n const normalized = value.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return decodeURIComponent(escape(atob(normalized)));\n}\n\nexport function createEventId(): string {\n const random = crypto.randomUUID().replace(/-/g, \"\");\n return `evt_${random}`;\n}\n\nexport function normalizeRetentionDays(value: number | undefined): number {\n if (!Number.isFinite(value) || typeof value !== \"number\" || value <= 0) {\n return EVENT_RETENTION_DEFAULT_DAYS;\n }\n return Math.max(1, Math.trunc(value));\n}\n\nexport function buildDomainEvent(input: CreateDomainEventInput): DomainEvent {\n const timestamp = input.timestamp ?? Date.now();\n const retentionDays = normalizeRetentionDays(input.retentionDays);\n return {\n eventId: input.eventId?.trim() || createEventId(),\n type: input.type.trim(),\n version: DOMAIN_EVENT_VERSION,\n timestamp,\n tenantId: input.tenantId?.trim() || undefined,\n workspaceId: input.workspaceId?.trim() || undefined,\n topicId: input.topicId.trim(),\n resourceId: input.resourceId.trim(),\n resourceType: input.resourceType.trim(),\n actorId: input.actorId.trim(),\n actorType: input.actorType,\n data: input.data ?? {},\n correlationId: input.correlationId?.trim() || undefined,\n expiresAt: timestamp + retentionDays * 24 * 60 * 60 * 1000,\n };\n}\n\nexport function compareEventCursor(left: EventCursor, right: EventCursor): number {\n if (left.timestamp !== right.timestamp) {\n return left.timestamp - right.timestamp;\n }\n return left.eventId.localeCompare(right.eventId);\n}\n\nexport function encodeEventCursor(cursor: EventCursor): string {\n return toBase64(JSON.stringify(cursor));\n}\n\nexport function decodeEventCursor(cursor: string | undefined): EventCursor | null {\n if (!cursor || cursor.trim().length === 0) {\n return null;\n }\n try {\n const parsed = JSON.parse(fromBase64(cursor.trim())) as Partial<EventCursor>;\n if (\n typeof parsed.timestamp !== \"number\" ||\n !Number.isFinite(parsed.timestamp) ||\n typeof parsed.eventId !== \"string\" ||\n parsed.eventId.trim().length === 0\n ) {\n return null;\n }\n return {\n timestamp: parsed.timestamp,\n eventId: parsed.eventId.trim(),\n };\n } catch {\n return null;\n }\n}\n\nexport function isAfterCursor(\n event: Pick<DomainEvent, \"timestamp\" | \"eventId\">,\n cursor: EventCursor | null\n): boolean {\n if (!cursor) {\n return true;\n }\n return compareEventCursor(event, cursor) > 0;\n}\n\nexport function sortEventsByCursor<T extends Pick<DomainEvent, \"timestamp\" | \"eventId\">>(\n events: readonly T[]\n): T[] {\n return [...events].sort((left, right) => compareEventCursor(left, right));\n}\n\nexport function inferActorType(args: {\n sessionType?: \"agent\" | \"user\";\n authMode?: string;\n principalType?: string;\n}): DomainActorType {\n if (args.sessionType === \"agent\") {\n return \"agent\";\n }\n if (\n args.authMode === \"service_principal\" ||\n args.authMode === \"tenant_api_key\" ||\n args.principalType === \"service\"\n ) {\n return \"service\";\n }\n return \"human\";\n}\n\nexport async function emitDomainEvent(\n invokeMutation: (reference: any, args: CreateDomainEventInput) => Promise<unknown>,\n input: CreateDomainEventInput\n): Promise<unknown> {\n return await invokeMutation(\"events:recordEvent\" as any, input);\n}\n"]}