@rhei-team/rhei 1.0.0-beta.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 (30) hide show
  1. package/README.md +1048 -0
  2. package/bin/rhei-mcp.js +3 -0
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +86366 -0
  5. package/dist/premium/contracts.d.ts +445 -0
  6. package/dist/premium/contracts.js +97 -0
  7. package/dist/vendor/rhei-core/briefs.js +1276 -0
  8. package/dist/vendor/rhei-core/codeAgent.js +615 -0
  9. package/dist/vendor/rhei-core/codeEditSession.js +293 -0
  10. package/dist/vendor/rhei-core/codeIntelligence.js +4287 -0
  11. package/dist/vendor/rhei-core/codeMarket.js +8946 -0
  12. package/dist/vendor/rhei-core/codeReviewIntelligence.js +5918 -0
  13. package/dist/vendor/rhei-core/codeSemantics.js +172427 -0
  14. package/dist/vendor/rhei-core/codeStory.js +667 -0
  15. package/dist/vendor/rhei-core/codeStrategyPlan.js +663 -0
  16. package/dist/vendor/rhei-core/codeTrail.js +2781 -0
  17. package/dist/vendor/rhei-core/codeWorkHandoff.js +281 -0
  18. package/dist/vendor/rhei-core/contextQuery.js +1119 -0
  19. package/dist/vendor/rhei-core/contextRouting.js +2052 -0
  20. package/dist/vendor/rhei-core/evidenceLedger.js +5336 -0
  21. package/dist/vendor/rhei-core/executionSafety.js +0 -0
  22. package/dist/vendor/rhei-core/goalIntelligence.js +2218 -0
  23. package/dist/vendor/rhei-core/model-lanes.js +75 -0
  24. package/dist/vendor/rhei-core/now.js +127 -0
  25. package/dist/vendor/rhei-core/package.json +29 -0
  26. package/dist/vendor/rhei-core/programPlan.js +3153 -0
  27. package/dist/vendor/rhei-core/search.js +196 -0
  28. package/dist/vendor/rhei-core/serviceIntelligence.js +1734 -0
  29. package/dist/vendor/rhei-core/workflowPlan.js +1660 -0
  30. package/package.json +41 -0
@@ -0,0 +1,1119 @@
1
+ // ../core/src/contextQuery/types.ts
2
+ var CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION = 1;
3
+ // ../core/src/contextQuery/builders.ts
4
+ function uniqueContextQueryStrings(values) {
5
+ return Array.from(new Set(values.filter((value) => typeof value === "string" && value.length > 0)));
6
+ }
7
+ function definedRecord(record) {
8
+ return Object.fromEntries(Object.entries(record).filter(([, value]) => value !== undefined));
9
+ }
10
+ function buildContextQueryAuthorityV1(reasonCodes = []) {
11
+ return {
12
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
13
+ kind: "context_query_authority",
14
+ noAuthority: true,
15
+ reportOnly: true,
16
+ advisoryOnly: true,
17
+ noApply: true,
18
+ noPromotion: true,
19
+ applyAvailable: false,
20
+ promotionAvailable: false,
21
+ writesAvailable: false,
22
+ providerWritesAvailable: false,
23
+ memoryPromotionAvailable: false,
24
+ grantsSourceWriteAuthority: false,
25
+ grantsProviderExecutionAuthority: false,
26
+ grantsTruthPromotionAuthority: false,
27
+ grantsMemoryPromotionAuthority: false,
28
+ grantsApplyAuthority: false,
29
+ authorityBoundary: [
30
+ "read_explain_only",
31
+ "context_handoff_only",
32
+ "review_evidence_only",
33
+ "impact_evidence_only",
34
+ "domain_read_model_only"
35
+ ],
36
+ domainReadModelsUnchanged: true,
37
+ reasonCodes: uniqueContextQueryStrings(["authority:no_authority", "authority:no_apply", "authority:no_promotion", ...reasonCodes])
38
+ };
39
+ }
40
+ function buildContextQueryFreshnessV1(args = {}) {
41
+ const state = args.stale ? "stale" : args.sourceFresh === true ? "fresh" : args.partial ? "partial" : args.readiness === "ready" || args.readiness === "context_ready" ? "likely_fresh" : args.sourceFresh === false ? "stale" : "unknown";
42
+ return definedRecord({
43
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
44
+ kind: "context_query_freshness",
45
+ state,
46
+ readiness: args.readiness,
47
+ generatedAt: args.generatedAt,
48
+ updatedAt: args.updatedAt,
49
+ watermark: args.watermark,
50
+ watermarks: args.watermarks && args.watermarks.length > 0 ? uniqueContextQueryStrings(args.watermarks) : undefined,
51
+ readinessRef: args.readinessRef,
52
+ contentHash: args.contentHash,
53
+ contentHashes: args.contentHashes && args.contentHashes.length > 0 ? uniqueContextQueryStrings(args.contentHashes) : undefined,
54
+ epoch: args.epoch,
55
+ sourceFresh: args.sourceFresh,
56
+ reasonCodes: uniqueContextQueryStrings([`freshness:${state}`, ...args.reasonCodes ?? []])
57
+ });
58
+ }
59
+ function buildContextQueryProvenanceV1(args) {
60
+ return definedRecord({
61
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
62
+ kind: "context_query_provenance",
63
+ providerId: args.providerId,
64
+ sources: uniqueContextQueryStrings(args.sources ?? []),
65
+ receiptRefs: args.receiptRefs && args.receiptRefs.length > 0 ? uniqueContextQueryStrings(args.receiptRefs) : undefined,
66
+ trailRefs: args.trailRefs && args.trailRefs.length > 0 ? uniqueContextQueryStrings(args.trailRefs) : undefined,
67
+ contentHashes: args.contentHashes && args.contentHashes.length > 0 ? uniqueContextQueryStrings(args.contentHashes) : undefined,
68
+ watermarks: args.watermarks && args.watermarks.length > 0 ? uniqueContextQueryStrings(args.watermarks) : undefined,
69
+ readinessRef: args.readinessRef,
70
+ receipts: args.receipts,
71
+ generatedAt: args.generatedAt,
72
+ reasonCodes: uniqueContextQueryStrings([`provider:${args.providerId}`, ...args.reasonCodes ?? []])
73
+ });
74
+ }
75
+ function buildContextQuerySourceScopeV1(args) {
76
+ return definedRecord({
77
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
78
+ kind: "context_query_source_scope",
79
+ source: args.source,
80
+ scopes: uniqueContextQueryStrings(args.scopes ?? []),
81
+ searchedFiles: args.searchedFiles,
82
+ matchedFiles: args.matchedFiles,
83
+ complete: args.complete,
84
+ truncated: args.truncated,
85
+ indexFresh: args.indexFresh,
86
+ reasonCodes: uniqueContextQueryStrings([`source:${args.source}`, ...args.reasonCodes ?? []])
87
+ });
88
+ }
89
+ function buildContextQueryResultRefV1(args) {
90
+ const refId = args.refId ?? (args.path ? `file:${args.path}` : args.label ?? "unknown");
91
+ return definedRecord({
92
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
93
+ kind: "context_query_result_ref",
94
+ refId,
95
+ path: args.path,
96
+ refKind: args.refKind,
97
+ label: args.label,
98
+ rank: args.rank,
99
+ score: args.score,
100
+ source: args.source,
101
+ reasonCodes: uniqueContextQueryStrings(args.reasonCodes ?? []),
102
+ evidenceRefs: args.evidenceRefs && args.evidenceRefs.length > 0 ? uniqueContextQueryStrings(args.evidenceRefs) : undefined,
103
+ suggestedReadSlices: args.suggestedReadSlices && args.suggestedReadSlices.length > 0 ? args.suggestedReadSlices : undefined,
104
+ metadata: args.metadata
105
+ });
106
+ }
107
+ function buildContextQueryTruncationV1(args) {
108
+ return definedRecord({
109
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
110
+ kind: "context_query_truncation",
111
+ sourceKey: args.sourceKey,
112
+ truncated: args.truncated,
113
+ limit: args.limit,
114
+ returned: args.returned,
115
+ omittedCount: args.omittedCount,
116
+ reason: args.reason,
117
+ reasonCodes: uniqueContextQueryStrings([args.truncated ? "truncation:truncated" : "truncation:complete", ...args.reasonCodes ?? []])
118
+ });
119
+ }
120
+ function buildContextQueryMissV1(args) {
121
+ return definedRecord({
122
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
123
+ kind: "context_query_miss",
124
+ ref: args.ref,
125
+ claim: args.claim,
126
+ query: args.query,
127
+ scope: args.scope,
128
+ reason: args.reason,
129
+ confidence: args.confidence,
130
+ reasonCodes: uniqueContextQueryStrings(args.reasonCodes ?? [])
131
+ });
132
+ }
133
+ function buildContextQueryRequestSummaryV1(args) {
134
+ return definedRecord({
135
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
136
+ kind: "context_query_request_summary",
137
+ surface: args.surface,
138
+ query: args.query,
139
+ goal: args.goal,
140
+ repoPath: args.repoPath,
141
+ repoId: args.repoId,
142
+ projectId: args.projectId,
143
+ filters: args.filters,
144
+ limit: args.limit,
145
+ requestedAt: args.requestedAt,
146
+ reasonCodes: uniqueContextQueryStrings([`surface:${args.surface}`, ...args.reasonCodes ?? []])
147
+ });
148
+ }
149
+ function buildContextQueryExplainV1(args = {}) {
150
+ return definedRecord({
151
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
152
+ kind: "context_query_explain",
153
+ summary: args.summary,
154
+ reasonCodes: uniqueContextQueryStrings(args.reasonCodes ?? []),
155
+ ranking: args.ranking,
156
+ candidateAccounting: args.candidateAccounting,
157
+ graphExpansionReceipt: args.graphExpansionReceipt,
158
+ coverageReceipt: args.coverageReceipt,
159
+ liveEvidence: args.liveEvidence,
160
+ noLive: args.noLive,
161
+ nextReadPlan: args.nextReadPlan,
162
+ warnings: args.warnings && args.warnings.length > 0 ? uniqueContextQueryStrings(args.warnings) : undefined
163
+ });
164
+ }
165
+ function buildContextQueryEnvelopeV1(args) {
166
+ const authority = args.authority ?? buildContextQueryAuthorityV1();
167
+ return {
168
+ schemaVersion: CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION,
169
+ kind: "rhei_context_query_envelope",
170
+ envelopeId: args.envelopeId,
171
+ surface: args.surface,
172
+ request: args.request,
173
+ authority,
174
+ freshness: args.freshness ?? buildContextQueryFreshnessV1(),
175
+ provenance: args.provenance,
176
+ sourceScopes: args.sourceScopes ?? [],
177
+ results: args.results ?? [],
178
+ explain: args.explain ?? buildContextQueryExplainV1(),
179
+ truncation: args.truncation ?? [],
180
+ misses: args.misses ?? [],
181
+ warnings: uniqueContextQueryStrings(args.warnings ?? []),
182
+ generatedAt: args.generatedAt ?? Date.now()
183
+ };
184
+ }
185
+ // ../core/src/contextQuery/runtime.ts
186
+ function isRecord(value) {
187
+ return value !== null && typeof value === "object" && !Array.isArray(value);
188
+ }
189
+ function isString(value) {
190
+ return typeof value === "string" && value.length > 0;
191
+ }
192
+ function isStringArray(value) {
193
+ return Array.isArray(value) && value.every((item) => typeof item === "string");
194
+ }
195
+ function isNumber(value) {
196
+ return typeof value === "number" && Number.isFinite(value);
197
+ }
198
+ function hasSchemaKind(record, kind) {
199
+ return record["schemaVersion"] === CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION && record["kind"] === kind;
200
+ }
201
+ function hasRequiredAuthorityBoundary(value) {
202
+ return isStringArray(value) && value.length > 0;
203
+ }
204
+ function isContextQueryAuthorityV1(value) {
205
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_authority"))
206
+ return false;
207
+ return value["noAuthority"] === true && value["reportOnly"] === true && value["advisoryOnly"] === true && value["noApply"] === true && value["noPromotion"] === true && value["applyAvailable"] === false && value["promotionAvailable"] === false && value["writesAvailable"] === false && value["providerWritesAvailable"] === false && value["memoryPromotionAvailable"] === false && value["grantsSourceWriteAuthority"] === false && value["grantsProviderExecutionAuthority"] === false && value["grantsTruthPromotionAuthority"] === false && value["grantsMemoryPromotionAuthority"] === false && value["grantsApplyAuthority"] === false && value["domainReadModelsUnchanged"] === true && hasRequiredAuthorityBoundary(value["authorityBoundary"]) && isStringArray(value["reasonCodes"]);
208
+ }
209
+ function isContextQueryRequestSummaryV1(value, surface) {
210
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_request_summary"))
211
+ return false;
212
+ return isString(value["surface"]) && value["surface"] === surface && isStringArray(value["reasonCodes"]);
213
+ }
214
+ function isContextQueryFreshnessV1(value) {
215
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_freshness"))
216
+ return false;
217
+ return isString(value["state"]) && isStringArray(value["reasonCodes"]);
218
+ }
219
+ function isContextQueryProvenanceV1(value) {
220
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_provenance"))
221
+ return false;
222
+ return isString(value["providerId"]) && isStringArray(value["sources"]) && (value["receiptRefs"] === undefined || isStringArray(value["receiptRefs"])) && (value["trailRefs"] === undefined || isStringArray(value["trailRefs"])) && (value["contentHashes"] === undefined || isStringArray(value["contentHashes"])) && (value["watermarks"] === undefined || isStringArray(value["watermarks"])) && isStringArray(value["reasonCodes"]);
223
+ }
224
+ function isContextQuerySourceScopeV1(value) {
225
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_source_scope"))
226
+ return false;
227
+ return isString(value["source"]) && isStringArray(value["scopes"]) && isStringArray(value["reasonCodes"]);
228
+ }
229
+ function isContextQueryResultRefV1(value) {
230
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_result_ref"))
231
+ return false;
232
+ return isString(value["refId"]) && (value["rank"] === undefined || isNumber(value["rank"])) && (value["score"] === undefined || isNumber(value["score"])) && isStringArray(value["reasonCodes"]) && (value["evidenceRefs"] === undefined || isStringArray(value["evidenceRefs"]));
233
+ }
234
+ function isContextQueryExplainV1(value) {
235
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_explain"))
236
+ return false;
237
+ return isStringArray(value["reasonCodes"]) && (value["warnings"] === undefined || isStringArray(value["warnings"]));
238
+ }
239
+ function isContextQueryTruncationV1(value) {
240
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_truncation"))
241
+ return false;
242
+ return typeof value["truncated"] === "boolean" && isStringArray(value["reasonCodes"]);
243
+ }
244
+ function isContextQueryMissV1(value) {
245
+ if (!isRecord(value) || !hasSchemaKind(value, "context_query_miss"))
246
+ return false;
247
+ return isStringArray(value["reasonCodes"]);
248
+ }
249
+ function isContextQueryEnvelopeV1(value) {
250
+ if (!isRecord(value) || !hasSchemaKind(value, "rhei_context_query_envelope"))
251
+ return false;
252
+ return isString(value["envelopeId"]) && isString(value["surface"]) && isContextQueryRequestSummaryV1(value["request"], value["surface"]) && isContextQueryAuthorityV1(value["authority"]) && isContextQueryFreshnessV1(value["freshness"]) && isContextQueryProvenanceV1(value["provenance"]) && Array.isArray(value["sourceScopes"]) && value["sourceScopes"].every(isContextQuerySourceScopeV1) && Array.isArray(value["results"]) && value["results"].every(isContextQueryResultRefV1) && isContextQueryExplainV1(value["explain"]) && Array.isArray(value["truncation"]) && value["truncation"].every(isContextQueryTruncationV1) && Array.isArray(value["misses"]) && value["misses"].every(isContextQueryMissV1) && isStringArray(value["warnings"]) && isNumber(value["generatedAt"]);
253
+ }
254
+ function assertContextQueryEnvelopeV1(value) {
255
+ if (isContextQueryEnvelopeV1(value))
256
+ return value;
257
+ throw new TypeError("Invalid ContextQueryEnvelopeV1 runtime payload");
258
+ }
259
+ // ../core/src/contextQuery/provenance.ts
260
+ function asRecord(value) {
261
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : undefined;
262
+ }
263
+ function directString(value) {
264
+ return typeof value === "string" && value.length > 0 ? [value] : [];
265
+ }
266
+ function stringList(value) {
267
+ if (!Array.isArray(value))
268
+ return directString(value);
269
+ return uniqueContextQueryStrings(value.flatMap((item) => directString(item)));
270
+ }
271
+ function refsFromRecord(record, keys) {
272
+ const allowedKeys = new Set(keys);
273
+ return Object.entries(record).flatMap(([key, value]) => {
274
+ if (!allowedKeys.has(key))
275
+ return [];
276
+ if (Array.isArray(value)) {
277
+ return value.flatMap((item) => {
278
+ if (typeof item === "string")
279
+ return [item];
280
+ const itemRecord = asRecord(item);
281
+ return itemRecord ? refsFromRecord(itemRecord, keys) : [];
282
+ });
283
+ }
284
+ return stringList(value);
285
+ });
286
+ }
287
+ function normalizeRefs(values, keys) {
288
+ return uniqueContextQueryStrings(values.flatMap((value) => {
289
+ if (Array.isArray(value))
290
+ return normalizeRefs(value, keys);
291
+ if (typeof value === "string")
292
+ return [value];
293
+ const record = asRecord(value);
294
+ return record ? refsFromRecord(record, keys) : [];
295
+ }));
296
+ }
297
+ function normalizeReceiptRefs(...values) {
298
+ return normalizeRefs(values, [
299
+ "receiptRefs",
300
+ "receipts",
301
+ "sourceReceipts",
302
+ "sourceReceiptRefs",
303
+ "receiptRef",
304
+ "receiptId",
305
+ "id",
306
+ "ref"
307
+ ]);
308
+ }
309
+ function normalizeEvidenceRefs(...values) {
310
+ return normalizeRefs(values, [
311
+ "evidenceRefs",
312
+ "evidenceRef",
313
+ "sourceEvidenceRefs",
314
+ "sourceReceipts",
315
+ "receiptRefs",
316
+ "receipts",
317
+ "receiptRef",
318
+ "receiptId",
319
+ "id",
320
+ "ref"
321
+ ]);
322
+ }
323
+ function normalizeTrailRefs(...values) {
324
+ return normalizeRefs(values, [
325
+ "trailRefs",
326
+ "trailRef",
327
+ "trailId",
328
+ "codeTrailRefs",
329
+ "codeTrailRef",
330
+ "refs",
331
+ "id",
332
+ "ref"
333
+ ]);
334
+ }
335
+ // ../core/src/contextQuery/adapters/shared.ts
336
+ function asRecord2(value) {
337
+ return value && typeof value === "object" && !Array.isArray(value) ? value : undefined;
338
+ }
339
+ function asRecords(value) {
340
+ return Array.isArray(value) ? value.filter((item) => Boolean(asRecord2(item))) : [];
341
+ }
342
+ function sourceForLocalIndex(coverageReceipt) {
343
+ return coverageReceipt?.indexFresh === false ? "local_mcp" : "local_mcp";
344
+ }
345
+ function coverageSourceScope(coverageReceipt, source) {
346
+ if (!coverageReceipt) {
347
+ return buildContextQuerySourceScopeV1({ source, reasonCodes: ["coverage:missing"] });
348
+ }
349
+ return buildContextQuerySourceScopeV1({
350
+ source,
351
+ scopes: coverageReceipt.searchedScopes,
352
+ searchedFiles: coverageReceipt.searchedFiles,
353
+ matchedFiles: coverageReceipt.matchedFiles,
354
+ complete: coverageReceipt.truncated === false,
355
+ truncated: coverageReceipt.truncated,
356
+ indexFresh: coverageReceipt.indexFresh,
357
+ reasonCodes: coverageReceipt.reasonCodes
358
+ });
359
+ }
360
+ function coverageTruncation(coverageReceipt) {
361
+ return [buildContextQueryTruncationV1({
362
+ sourceKey: "coverage_receipt",
363
+ truncated: coverageReceipt?.truncated === true,
364
+ omittedCount: coverageReceipt?.omittedCount,
365
+ reason: coverageReceipt?.truncated ? "coverage receipt reported truncation" : undefined,
366
+ reasonCodes: coverageReceipt?.reasonCodes
367
+ })];
368
+ }
369
+ function coverageMisses(coverageReceipt) {
370
+ return (coverageReceipt?.absenceClaims ?? []).map((claim) => buildContextQueryMissV1({
371
+ claim: claim.claim,
372
+ query: claim.query,
373
+ scope: claim.scope,
374
+ confidence: claim.confidence,
375
+ reason: "absence_claim",
376
+ reasonCodes: claim.reasonCodes
377
+ }));
378
+ }
379
+ function recordString(record, key) {
380
+ const value = record?.[key];
381
+ return typeof value === "string" && value.length > 0 ? value : undefined;
382
+ }
383
+ function recordNumber(record, key) {
384
+ const value = record?.[key];
385
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
386
+ }
387
+ function stringList2(value) {
388
+ if (!Array.isArray(value))
389
+ return [];
390
+ return uniqueContextQueryStrings(value.filter((item) => typeof item === "string" && item.length > 0));
391
+ }
392
+ function pathRefsFromRecords(records, keys) {
393
+ return uniqueContextQueryStrings(records.flatMap((record) => keys.flatMap((key) => {
394
+ const value = record[key];
395
+ if (typeof value === "string")
396
+ return [value];
397
+ if (Array.isArray(value))
398
+ return value.filter((item) => typeof item === "string");
399
+ return [];
400
+ })));
401
+ }
402
+ function receiptsFromUnknown(value) {
403
+ return normalizeReceiptRefs(value);
404
+ }
405
+
406
+ // ../core/src/contextQuery/adapters/mcpSearch.ts
407
+ function buildMcpSearchContextQueryEnvelopeV1(args) {
408
+ const generatedAt = args.generatedAt ?? Date.now();
409
+ const source = sourceForLocalIndex(args.coverageReceipt);
410
+ const results = (args.results ?? []).map((result, index) => buildContextQueryResultRefV1({
411
+ refId: result.refId,
412
+ path: result.path,
413
+ refKind: result.kind,
414
+ rank: index + 1,
415
+ score: result.score,
416
+ source,
417
+ reasonCodes: result.reasonCodes,
418
+ evidenceRefs: result.evidenceRefs,
419
+ suggestedReadSlices: result.suggestedReadSlices,
420
+ metadata: {
421
+ surfaceKind: result.surfaceKind,
422
+ matchMode: result.matchMode,
423
+ matchCount: result.matchCount,
424
+ matchCountBasis: result.matchCountBasis
425
+ }
426
+ }));
427
+ const warnings = uniqueContextQueryStrings(args.warnings ?? []);
428
+ return buildContextQueryEnvelopeV1({
429
+ envelopeId: `context-query:mcp-search:${args.searchId ?? args.sessionId ?? generatedAt}`,
430
+ surface: "mcp_search",
431
+ generatedAt,
432
+ request: buildContextQueryRequestSummaryV1({
433
+ surface: "mcp_search",
434
+ query: args.query,
435
+ repoPath: args.repoPath,
436
+ limit: args.searchLimit,
437
+ filters: {
438
+ purpose: args.purpose,
439
+ profile: args.profile,
440
+ searchMode: args.searchMode,
441
+ effectiveResultLimit: args.effectiveResultLimit
442
+ },
443
+ requestedAt: generatedAt
444
+ }),
445
+ freshness: buildContextQueryFreshnessV1({
446
+ generatedAt,
447
+ sourceFresh: args.coverageReceipt?.indexFresh,
448
+ partial: args.coverageReceipt?.truncated,
449
+ reasonCodes: args.coverageReceipt?.reasonCodes
450
+ }),
451
+ provenance: buildContextQueryProvenanceV1({
452
+ providerId: "rhei_code_search",
453
+ sources: [source],
454
+ generatedAt,
455
+ receipts: {
456
+ coverageReceipt: args.coverageReceipt,
457
+ candidateAccounting: args.candidateAccounting,
458
+ graphExpansionReceipt: args.graphExpansionReceipt,
459
+ rankingNoLive: args.rankingNoLive,
460
+ liveEvidence: args.liveEvidence
461
+ }
462
+ }),
463
+ sourceScopes: [coverageSourceScope(args.coverageReceipt, source)],
464
+ results,
465
+ explain: buildContextQueryExplainV1({
466
+ summary: `${args.returnedResultCount ?? results.length}/${args.resultCount ?? results.length} search results returned`,
467
+ reasonCodes: uniqueContextQueryStrings([...args.coverageReceipt?.reasonCodes ?? [], ...args.warnings ?? []]),
468
+ ranking: {
469
+ resultCount: args.resultCount,
470
+ returnedResultCount: args.returnedResultCount,
471
+ omittedResultCount: args.omittedResultCount,
472
+ totalMatchCount: args.totalMatchCount,
473
+ returnedMatchCount: args.returnedMatchCount,
474
+ rankingNoLive: args.rankingNoLive
475
+ },
476
+ candidateAccounting: args.candidateAccounting,
477
+ graphExpansionReceipt: args.graphExpansionReceipt,
478
+ coverageReceipt: args.coverageReceipt,
479
+ liveEvidence: args.liveEvidence,
480
+ noLive: args.rankingNoLive,
481
+ nextReadPlan: args.nextReadPlan,
482
+ warnings
483
+ }),
484
+ truncation: coverageTruncation(args.coverageReceipt),
485
+ misses: coverageMisses(args.coverageReceipt),
486
+ warnings
487
+ });
488
+ }
489
+ // ../core/src/contextQuery/adapters/contextForGoal.ts
490
+ function buildContextForGoalContextQueryEnvelopeV1(args) {
491
+ const coverageReceipt = args.coverageReceipt;
492
+ const generatedAt = args.generatedAt ?? coverageReceipt?.generatedAt ?? args.snapshot?.generatedAt ?? Date.now();
493
+ const source = sourceForLocalIndex(coverageReceipt);
494
+ const symbolResults = (args.selection?.importantSymbols ?? []).map((symbol, index) => buildContextQueryResultRefV1({
495
+ refId: symbol.refId,
496
+ path: symbol.path,
497
+ refKind: symbol.kind ?? "symbol",
498
+ label: symbol.name,
499
+ rank: index + 1,
500
+ source,
501
+ reasonCodes: ["selection:important_symbol"]
502
+ }));
503
+ const fileRefs = uniqueContextQueryStrings([
504
+ ...args.selectedRefIds ?? [],
505
+ ...args.selection?.exactFiles ?? [],
506
+ ...args.selection?.relatedTests ?? [],
507
+ ...args.selection?.docsEvidence ?? []
508
+ ]);
509
+ const fileResults = fileRefs.map((path, index) => buildContextQueryResultRefV1({
510
+ refId: path.startsWith("file:") ? path : `file:${path}`,
511
+ path: path.startsWith("file:") ? path.slice("file:".length) : path,
512
+ refKind: "file",
513
+ rank: symbolResults.length + index + 1,
514
+ source,
515
+ reasonCodes: ["selection:context_for_goal"]
516
+ }));
517
+ const warnings = uniqueContextQueryStrings(args.warnings ?? []);
518
+ return buildContextQueryEnvelopeV1({
519
+ envelopeId: `context-query:mcp-context-for-goal:${args.requestId ?? generatedAt}`,
520
+ surface: "mcp_context_for_goal",
521
+ generatedAt,
522
+ request: buildContextQueryRequestSummaryV1({
523
+ surface: "mcp_context_for_goal",
524
+ goal: args.goal,
525
+ repoPath: args.repoPath,
526
+ requestedAt: generatedAt
527
+ }),
528
+ freshness: buildContextQueryFreshnessV1({
529
+ generatedAt,
530
+ sourceFresh: coverageReceipt?.indexFresh,
531
+ partial: coverageReceipt?.truncated,
532
+ readiness: typeof args.observability?.["readinessStatus"] === "string" ? args.observability["readinessStatus"] : undefined,
533
+ reasonCodes: coverageReceipt?.reasonCodes
534
+ }),
535
+ provenance: buildContextQueryProvenanceV1({
536
+ providerId: "rhei_code_context_for_goal",
537
+ sources: [source, "code_insights"],
538
+ generatedAt,
539
+ receipts: {
540
+ coverageReceipt,
541
+ retrievalAccounting: args.retrievalAccounting,
542
+ graphExpansionReceipt: args.graphExpansionReceipt,
543
+ repoIntelligenceStatus: args.repoIntelligenceStatus,
544
+ editReadiness: args.editReadiness,
545
+ observability: args.observability
546
+ }
547
+ }),
548
+ sourceScopes: [coverageSourceScope(coverageReceipt, source)],
549
+ results: [...fileResults, ...symbolResults],
550
+ explain: buildContextQueryExplainV1({
551
+ summary: args.goal ? `Context-for-goal envelope for: ${args.goal}` : "Context-for-goal envelope",
552
+ reasonCodes: uniqueContextQueryStrings([...coverageReceipt?.reasonCodes ?? [], ...args.warnings ?? []]),
553
+ candidateAccounting: args.retrievalAccounting,
554
+ graphExpansionReceipt: args.graphExpansionReceipt,
555
+ coverageReceipt,
556
+ noLive: asRecord2(args.observability?.["noLive"]),
557
+ nextReadPlan: asRecords(args.relatedFiles?.["nextReadPlan"]),
558
+ warnings
559
+ }),
560
+ truncation: coverageTruncation(coverageReceipt),
561
+ misses: coverageMisses(coverageReceipt),
562
+ warnings
563
+ });
564
+ }
565
+ // ../core/src/contextQuery/adapters/codeMap.ts
566
+ function buildCodeMapContextQueryEnvelopeV1(snapshot) {
567
+ const sourceScopes = snapshot.sourceWatermarks.map((watermark) => buildContextQuerySourceScopeV1({
568
+ source: watermark.kind,
569
+ scopes: [watermark.sourceKey],
570
+ complete: watermark.complete,
571
+ truncated: !watermark.complete,
572
+ reasonCodes: ["code_map:source_watermark"]
573
+ }));
574
+ const results = snapshot.tiles.map((tile, index) => buildContextQueryResultRefV1({
575
+ refId: tile.primaryRef.id,
576
+ path: tile.primaryRef.path,
577
+ refKind: tile.primaryRef.kind,
578
+ label: tile.title,
579
+ rank: index + 1,
580
+ score: tile.controlWeight,
581
+ source: tile.primaryRef.authority,
582
+ reasonCodes: tile.reasonCodes,
583
+ metadata: {
584
+ tileId: tile.id,
585
+ tileKind: tile.kind,
586
+ state: tile.state,
587
+ confidence: tile.confidence
588
+ }
589
+ }));
590
+ const truncation = snapshot.truncation.map((item) => buildContextQueryTruncationV1({
591
+ sourceKey: item.sourceKey,
592
+ truncated: item.truncated,
593
+ limit: item.limit,
594
+ returned: item.returned,
595
+ reason: item.reason
596
+ }));
597
+ const firstWatermark = snapshot.sourceWatermarks[0];
598
+ const watermarks = uniqueContextQueryStrings(snapshot.sourceWatermarks.map((watermark) => watermark.cursor ?? watermark.sourceKey));
599
+ return buildContextQueryEnvelopeV1({
600
+ envelopeId: `context-query:code-map:${snapshot.projectId}:${snapshot.generatedAt}`,
601
+ surface: "code_map",
602
+ generatedAt: snapshot.generatedAt,
603
+ request: buildContextQueryRequestSummaryV1({
604
+ surface: "code_map",
605
+ projectId: snapshot.projectId,
606
+ repoId: snapshot.scope.repoId,
607
+ filters: {
608
+ surface: snapshot.scope.surface,
609
+ groupBy: snapshot.scope.groupBy,
610
+ pathPrefix: snapshot.scope.pathPrefix,
611
+ focusedModuleId: snapshot.scope.focusedModuleId,
612
+ selectedModuleIds: snapshot.scope.selectedModuleIds
613
+ },
614
+ requestedAt: snapshot.generatedAt,
615
+ reasonCodes: snapshot.readiness.reasonCodes
616
+ }),
617
+ freshness: buildContextQueryFreshnessV1({
618
+ readiness: snapshot.readiness.state,
619
+ generatedAt: snapshot.generatedAt,
620
+ updatedAt: firstWatermark?.updatedAt,
621
+ watermark: firstWatermark?.cursor ?? firstWatermark?.sourceKey,
622
+ watermarks,
623
+ sourceFresh: snapshot.readiness.state === "ready" ? true : undefined,
624
+ partial: snapshot.readiness.state === "partial" || snapshot.truncation.some((item) => item.truncated),
625
+ reasonCodes: snapshot.readiness.reasonCodes
626
+ }),
627
+ provenance: buildContextQueryProvenanceV1({
628
+ providerId: "code_map_adapter",
629
+ sources: uniqueContextQueryStrings(snapshot.sources.map((source) => source.kind)),
630
+ generatedAt: snapshot.generatedAt,
631
+ receipts: {
632
+ readiness: snapshot.readiness,
633
+ sourceWatermarks: snapshot.sourceWatermarks,
634
+ truncation: snapshot.truncation
635
+ },
636
+ watermarks,
637
+ reasonCodes: snapshot.readiness.reasonCodes
638
+ }),
639
+ sourceScopes,
640
+ results,
641
+ explain: buildContextQueryExplainV1({
642
+ summary: snapshot.readiness.title,
643
+ reasonCodes: snapshot.readiness.reasonCodes,
644
+ ranking: {
645
+ tileCount: snapshot.tiles.length,
646
+ relationshipCount: snapshot.relationships.length,
647
+ gapCount: snapshot.gaps.length
648
+ },
649
+ warnings: snapshot.gaps.map((gap) => gap.title)
650
+ }),
651
+ truncation,
652
+ misses: snapshot.gaps.map((gap) => buildContextQueryMissV1({
653
+ ref: gap.ref?.id,
654
+ claim: gap.title,
655
+ reason: gap.kind,
656
+ reasonCodes: [gap.severity]
657
+ })),
658
+ warnings: snapshot.gaps.map((gap) => gap.title)
659
+ });
660
+ }
661
+ // ../core/src/contextQuery/adapters/review.ts
662
+ function buildReviewIntelligenceContextQueryEnvelopeV1(args) {
663
+ const generatedAt = args.generatedAt ?? Date.now();
664
+ const reviewDiffs = asRecords(args.reviewDiffs);
665
+ const outcomes = asRecords(args.outcomes);
666
+ const ranking = asRecord2(args.ranking);
667
+ const ledger = asRecord2(args.ledger);
668
+ const memoryCandidateSet = asRecord2(args.memoryCandidateSet);
669
+ const reviewRoomSummary = asRecord2(args.reviewRoomSummary);
670
+ const editReadiness = asRecord2(args.editReadiness);
671
+ const refinementIntelligence = asRecord2(args.refinementIntelligence);
672
+ const pathSummaryResults = reviewDiffs.flatMap((diff, diffIndex) => {
673
+ const pathSummaries = asRecords(diff["pathSummaries"]);
674
+ if (pathSummaries.length === 0) {
675
+ const fallbackId = recordString(diff, "reviewDiffId") ?? recordString(diff, "diffId") ?? `review-diff:${diffIndex + 1}`;
676
+ return [buildContextQueryResultRefV1({
677
+ refId: fallbackId,
678
+ refKind: "review_diff",
679
+ label: recordString(diff, "title") ?? fallbackId,
680
+ rank: diffIndex + 1,
681
+ source: "pr_review_intelligence",
682
+ reasonCodes: ["review:diff"],
683
+ evidenceRefs: receiptsFromUnknown(diff["sourceReceipts"])
684
+ })];
685
+ }
686
+ return pathSummaries.map((summary, pathIndex) => buildContextQueryResultRefV1({
687
+ refId: recordString(summary, "refId") ?? recordString(summary, "path") ?? `review-diff:${diffIndex + 1}:path:${pathIndex + 1}`,
688
+ path: recordString(summary, "path"),
689
+ refKind: "review_path_summary",
690
+ label: recordString(summary, "title") ?? recordString(summary, "path"),
691
+ rank: pathIndex + 1,
692
+ score: recordNumber(summary, "riskScore"),
693
+ source: "pr_review_intelligence",
694
+ reasonCodes: uniqueContextQueryStrings(["review:path_summary", recordString(summary, "riskLevel")]),
695
+ evidenceRefs: normalizeEvidenceRefs(summary["receiptRefs"], summary["evidenceRefs"]),
696
+ metadata: {
697
+ reviewDiffId: recordString(diff, "reviewDiffId") ?? recordString(diff, "diffId"),
698
+ riskLevel: recordString(summary, "riskLevel"),
699
+ stale: summary["stale"]
700
+ }
701
+ }));
702
+ });
703
+ const rankedProposalResults = asRecords(ranking?.["rankedProposals"] ?? ranking?.["proposals"]).map((proposal, index) => buildContextQueryResultRefV1({
704
+ refId: recordString(proposal, "proposalId") ?? recordString(proposal, "id") ?? `ranked-proposal:${index + 1}`,
705
+ refKind: "review_ranked_proposal",
706
+ label: recordString(proposal, "title") ?? recordString(proposal, "recommendedAction") ?? "ranked proposal",
707
+ rank: recordNumber(proposal, "rank") ?? index + 1,
708
+ score: recordNumber(proposal, "score"),
709
+ source: "pr_review_intelligence",
710
+ reasonCodes: uniqueContextQueryStrings(["review:ranking", recordString(proposal, "recommendedAction")]),
711
+ evidenceRefs: normalizeEvidenceRefs(proposal["receiptRefs"], proposal["evidenceRefs"])
712
+ }));
713
+ const outcomeResults = outcomes.map((outcome, index) => buildContextQueryResultRefV1({
714
+ refId: recordString(outcome, "outcomeId") ?? recordString(outcome, "id") ?? `review-outcome:${index + 1}`,
715
+ refKind: "review_outcome",
716
+ label: recordString(outcome, "verdict") ?? recordString(outcome, "status") ?? "review outcome",
717
+ rank: index + 1,
718
+ source: "pr_review_intelligence",
719
+ reasonCodes: uniqueContextQueryStrings(["review:outcome", recordString(outcome, "verdict"), recordString(outcome, "status")]),
720
+ evidenceRefs: normalizeEvidenceRefs(outcome["receiptRefs"], outcome["evidenceRefs"])
721
+ }));
722
+ const resultPaths = uniqueContextQueryStrings(pathSummaryResults.map((result) => result.path));
723
+ const sourceReceiptRefs = normalizeReceiptRefs(...reviewDiffs.map((diff) => diff["sourceReceipts"]), ...reviewDiffs.map((diff) => diff["receiptRefs"]), ...reviewDiffs.map((diff) => diff["evidenceRefs"]), ...outcomes.map((outcome) => outcome["receiptRefs"]), ...outcomes.map((outcome) => outcome["evidenceRefs"]));
724
+ const warnings = args.warnings ?? [];
725
+ return buildContextQueryEnvelopeV1({
726
+ envelopeId: `context-query:review:${args.mode}:${generatedAt}`,
727
+ surface: "review_intelligence",
728
+ generatedAt,
729
+ request: buildContextQueryRequestSummaryV1({
730
+ surface: "review_intelligence",
731
+ filters: { mode: args.mode, reviewDiffCount: reviewDiffs.length, outcomeCount: outcomes.length },
732
+ requestedAt: generatedAt,
733
+ reasonCodes: ["review:bridge"]
734
+ }),
735
+ freshness: buildContextQueryFreshnessV1({
736
+ generatedAt,
737
+ sourceFresh: editReadiness?.["status"] === "ready" ? true : undefined,
738
+ partial: warnings.length > 0,
739
+ reasonCodes: uniqueContextQueryStrings(["review:freshness_from_payload", recordString(editReadiness, "status")])
740
+ }),
741
+ provenance: buildContextQueryProvenanceV1({
742
+ providerId: "review_intelligence_bridge",
743
+ sources: ["pr_review_intelligence"],
744
+ generatedAt,
745
+ receipts: {
746
+ reviewDiffs: reviewDiffs.length,
747
+ outcomes: outcomes.length,
748
+ sourceReceiptRefs,
749
+ ledger,
750
+ memoryCandidateSet,
751
+ reviewRoomSummary,
752
+ refinementIntelligence,
753
+ editReadiness
754
+ },
755
+ receiptRefs: sourceReceiptRefs,
756
+ reasonCodes: ["review:source_receipts"]
757
+ }),
758
+ sourceScopes: [buildContextQuerySourceScopeV1({
759
+ source: "pr_review_intelligence",
760
+ scopes: uniqueContextQueryStrings(["review", args.mode, ...resultPaths]),
761
+ matchedFiles: resultPaths.length || undefined,
762
+ complete: true,
763
+ truncated: false,
764
+ indexFresh: undefined,
765
+ reasonCodes: ["review:domain_payload"]
766
+ })],
767
+ results: [...pathSummaryResults, ...rankedProposalResults, ...outcomeResults],
768
+ explain: buildContextQueryExplainV1({
769
+ summary: `Review intelligence envelope for ${args.mode}`,
770
+ reasonCodes: uniqueContextQueryStrings(["review:explain", ...warnings]),
771
+ ranking: ranking ? { ...ranking, resultPathCount: resultPaths.length } : { resultPathCount: resultPaths.length },
772
+ candidateAccounting: ledger ? { ledger } : undefined,
773
+ coverageReceipt: sourceReceiptRefs.length > 0 ? { receiptRefs: sourceReceiptRefs } : undefined,
774
+ warnings
775
+ }),
776
+ truncation: [buildContextQueryTruncationV1({
777
+ sourceKey: "review_intelligence",
778
+ truncated: false,
779
+ returned: pathSummaryResults.length + rankedProposalResults.length + outcomeResults.length,
780
+ reasonCodes: ["review:not_truncated_by_envelope"]
781
+ })],
782
+ misses: [],
783
+ warnings
784
+ });
785
+ }
786
+ // ../core/src/contextQuery/adapters/impact.ts
787
+ function buildImpactPredictionContextQueryEnvelopeV1(args) {
788
+ const generatedAt = args.generatedAt ?? Date.now();
789
+ const expectedEditScope = asRecords(args.expectedEditScope);
790
+ const baselineRefs = asRecords(args.baselineRefs);
791
+ const advisoryEvidence = asRecord2(args.advisoryEvidence);
792
+ const predictedImpact = asRecord2(args.predictedImpact);
793
+ const historicalReceipts = asRecords(args.historicalReceipts);
794
+ const liveEvidence = asRecord2(args.liveEvidence);
795
+ const selectedRefs = args.selectedRefs ?? [];
796
+ const changedPaths = pathRefsFromRecords(expectedEditScope, ["path"]);
797
+ const impactPaths = uniqueContextQueryStrings([
798
+ ...changedPaths,
799
+ ...selectedRefs,
800
+ ...stringList2(predictedImpact?.["tests"]),
801
+ ...stringList2(predictedImpact?.["docs"]),
802
+ ...stringList2(predictedImpact?.["runtimeContracts"])
803
+ ]);
804
+ const receiptRefs = normalizeReceiptRefs(args.receipts, advisoryEvidence, historicalReceipts);
805
+ const graphRefs = uniqueContextQueryStrings([...stringList2(advisoryEvidence?.["graphRefs"]), ...stringList2(predictedImpact?.["graphRefs"])]);
806
+ const trailRefs = normalizeTrailRefs(args.trailRefs);
807
+ return buildContextQueryEnvelopeV1({
808
+ envelopeId: `context-query:impact:${args.predictionId}`,
809
+ surface: "impact_prediction",
810
+ generatedAt,
811
+ request: buildContextQueryRequestSummaryV1({
812
+ surface: "impact_prediction",
813
+ filters: { sessionId: args.sessionId, proposalId: args.proposalId, riskLevel: args.riskLevel },
814
+ requestedAt: generatedAt,
815
+ reasonCodes: ["impact:bridge"]
816
+ }),
817
+ freshness: buildContextQueryFreshnessV1({
818
+ generatedAt,
819
+ sourceFresh: liveEvidence?.["readOnly"] === true ? true : undefined,
820
+ partial: graphRefs.length === 0 && receiptRefs.length === 0,
821
+ reasonCodes: ["impact:freshness_from_live_evidence"]
822
+ }),
823
+ provenance: buildContextQueryProvenanceV1({
824
+ providerId: "impact_prediction_bridge",
825
+ sources: ["code_insights", "local_mcp"],
826
+ generatedAt,
827
+ receipts: {
828
+ baselineRefs,
829
+ receiptRefs,
830
+ trailRefs,
831
+ graphRefs,
832
+ liveEvidence
833
+ },
834
+ receiptRefs,
835
+ trailRefs,
836
+ reasonCodes: ["impact:receipts", "impact:trail_refs", "impact:graph_refs"]
837
+ }),
838
+ sourceScopes: [
839
+ buildContextQuerySourceScopeV1({
840
+ source: "code_insights",
841
+ scopes: uniqueContextQueryStrings(["impact", args.sessionId, ...args.proposalId ? [args.proposalId] : []]),
842
+ matchedFiles: changedPaths.length || undefined,
843
+ complete: true,
844
+ truncated: false,
845
+ reasonCodes: ["impact:domain_payload"]
846
+ }),
847
+ buildContextQuerySourceScopeV1({
848
+ source: "local_mcp",
849
+ scopes: impactPaths,
850
+ matchedFiles: impactPaths.length || undefined,
851
+ complete: true,
852
+ truncated: false,
853
+ reasonCodes: ["impact:selected_refs"]
854
+ })
855
+ ],
856
+ results: impactPaths.map((path, index) => buildContextQueryResultRefV1({
857
+ refId: `impact-ref:${path}`,
858
+ path,
859
+ refKind: changedPaths.includes(path) ? "impact_changed_path" : "impact_related_path",
860
+ label: path,
861
+ rank: index + 1,
862
+ score: changedPaths.includes(path) ? 1 : undefined,
863
+ source: changedPaths.includes(path) ? "code_insights" : "local_mcp",
864
+ reasonCodes: uniqueContextQueryStrings(["impact:ref", changedPaths.includes(path) ? "impact:changed" : "impact:related"]),
865
+ evidenceRefs: receiptRefs
866
+ })),
867
+ explain: buildContextQueryExplainV1({
868
+ summary: `Impact prediction envelope for ${args.predictionId}`,
869
+ reasonCodes: uniqueContextQueryStrings(["impact:explain", args.riskLevel, ...args.warnings ?? []]),
870
+ ranking: {
871
+ riskLevel: args.riskLevel,
872
+ confidence: args.confidence,
873
+ changedPathCount: changedPaths.length,
874
+ graphRefCount: graphRefs.length,
875
+ receiptCount: receiptRefs.length,
876
+ historicalReceiptCount: historicalReceipts.length
877
+ },
878
+ graphExpansionReceipt: graphRefs.length > 0 ? { graphRefs } : undefined,
879
+ coverageReceipt: receiptRefs.length > 0 ? { receiptRefs } : undefined,
880
+ liveEvidence,
881
+ warnings: args.warnings
882
+ }),
883
+ truncation: [buildContextQueryTruncationV1({
884
+ sourceKey: "impact_prediction",
885
+ truncated: false,
886
+ returned: impactPaths.length,
887
+ reasonCodes: ["impact:not_truncated_by_envelope"]
888
+ })],
889
+ misses: [],
890
+ warnings: args.warnings
891
+ });
892
+ }
893
+ // ../core/src/contextQuery/adapters/rheiShellCodeMap.ts
894
+ function buildRheiShellCodeMapContextQueryEnvelopeV1(args) {
895
+ const generatedAt = args.generatedAt ?? Date.now();
896
+ const selectedTileIds = args.selectedTileIds ?? args.tiles.map((tile) => tile.id);
897
+ const selected = args.tiles.filter((tile) => selectedTileIds.includes(tile.id));
898
+ const warnings = args.warnings ?? [];
899
+ return buildContextQueryEnvelopeV1({
900
+ envelopeId: args.envelopeId ?? `context-query:rhei-shell-code-map:${args.workspaceId ?? "all"}:${generatedAt}`,
901
+ surface: "rhei_shell_code_map",
902
+ generatedAt,
903
+ request: buildContextQueryRequestSummaryV1({
904
+ surface: "rhei_shell_code_map",
905
+ projectId: args.projectId,
906
+ filters: { workspaceId: args.workspaceId, window: args.window, selectedTileCount: selected.length },
907
+ requestedAt: generatedAt,
908
+ reasonCodes: ["rhei_shell_code_map:fixture"]
909
+ }),
910
+ freshness: buildContextQueryFreshnessV1({
911
+ generatedAt,
912
+ sourceFresh: true,
913
+ reasonCodes: ["rhei_shell_code_map:local_fixture"]
914
+ }),
915
+ provenance: buildContextQueryProvenanceV1({
916
+ providerId: "rhei_shell_code_map_fixture",
917
+ sources: ["local_mcp"],
918
+ generatedAt,
919
+ receipts: { tileCount: args.tiles.length, selectedTileIds, window: args.window },
920
+ reasonCodes: ["rhei_shell_code_map:domain_fixture"]
921
+ }),
922
+ sourceScopes: [buildContextQuerySourceScopeV1({
923
+ source: "local_mcp",
924
+ scopes: uniqueContextQueryStrings(["rhei-shell", "code-map", ...args.workspaceId ? [args.workspaceId] : [], ...args.window ? [args.window] : []]),
925
+ matchedFiles: selected.length,
926
+ complete: selected.length === selectedTileIds.length,
927
+ truncated: false,
928
+ indexFresh: true,
929
+ reasonCodes: ["rhei_shell_code_map:selected_tiles"]
930
+ })],
931
+ results: selected.map((tile, index) => buildContextQueryResultRefV1({
932
+ refId: tile.id,
933
+ path: tile.path,
934
+ refKind: "rhei_shell_code_map_tile",
935
+ label: tile.label,
936
+ rank: index + 1,
937
+ score: tile.weight,
938
+ source: "local_mcp",
939
+ reasonCodes: uniqueContextQueryStrings(["rhei_shell_code_map:tile", tile.group, tile.workspaceId]),
940
+ metadata: { group: tile.group, workspaceId: tile.workspaceId, weight: tile.weight }
941
+ })),
942
+ explain: buildContextQueryExplainV1({
943
+ summary: "rhei-shell Code Map explain envelope",
944
+ reasonCodes: uniqueContextQueryStrings(["rhei_shell_code_map:explain", ...warnings]),
945
+ ranking: { tileCount: args.tiles.length, selectedTileCount: selected.length, window: args.window },
946
+ warnings
947
+ }),
948
+ truncation: [buildContextQueryTruncationV1({
949
+ sourceKey: "rhei_shell_code_map_tiles",
950
+ truncated: false,
951
+ returned: selected.length,
952
+ reasonCodes: ["rhei_shell_code_map:not_truncated_by_envelope"]
953
+ })],
954
+ misses: selected.length === selectedTileIds.length ? [] : [buildContextQueryMissV1({
955
+ claim: "Some selected tile ids were not present in the rhei-shell map fixture.",
956
+ reason: "missing_tile_fixture",
957
+ reasonCodes: ["rhei_shell_code_map:missing_selected_tile"]
958
+ })],
959
+ warnings
960
+ });
961
+ }
962
+ // ../core/src/contextQuery/publicReadRegistry.ts
963
+ var CONTEXT_QUERY_PUBLIC_READ_REGISTRY_V1 = [
964
+ {
965
+ surface: "mcp_search",
966
+ producer: "rhei_code_search",
967
+ path: "packages/mcp-server/src/codeSessionTools.ts",
968
+ status: "envelope_required",
969
+ envelopeRequired: true,
970
+ authorityRequired: true,
971
+ notes: "First MCP producer: maps search results, coverage, graph expansion, no-live policy, and next reads."
972
+ },
973
+ {
974
+ surface: "mcp_context_for_goal",
975
+ producer: "rhei_code_context_for_goal",
976
+ path: "packages/mcp-server/src/localCodeContextForGoal.ts",
977
+ status: "envelope_required",
978
+ envelopeRequired: true,
979
+ authorityRequired: true,
980
+ notes: "Agent-facing context pack producer: maps Code Market context-for-goal output."
981
+ },
982
+ {
983
+ surface: "code_map",
984
+ producer: "code_map_adapter",
985
+ path: "apps/web/src/components/code-context/codeMapAdapter.ts",
986
+ status: "envelope_required",
987
+ envelopeRequired: true,
988
+ authorityRequired: true,
989
+ notes: "Web Code Map adapter proof point; domain snapshot remains authoritative."
990
+ },
991
+ {
992
+ surface: "rhei_shell_code_map",
993
+ producer: "rhei_shell_code_map_adapter",
994
+ path: "apps/expo/src/rhei-shell/map/mapContextQuery.ts",
995
+ status: "envelope_required",
996
+ envelopeRequired: true,
997
+ authorityRequired: true,
998
+ notes: "Current Code Map UI consumer in rhei-shell; local adapter can swap fixture/live data without UI changes."
999
+ },
1000
+ {
1001
+ surface: "review_intelligence",
1002
+ producer: "rhei_code_review",
1003
+ path: "packages/mcp-server/src/codeReviewIntelligenceTools.ts",
1004
+ status: "envelope_required",
1005
+ envelopeRequired: true,
1006
+ authorityRequired: true,
1007
+ notes: "Review provenance bridge only; review ranking/domain payloads remain authoritative."
1008
+ },
1009
+ {
1010
+ surface: "impact_prediction",
1011
+ producer: "code_session_impact_prediction",
1012
+ path: "packages/mcp-server/src/codeSessionTools.ts",
1013
+ status: "envelope_required",
1014
+ envelopeRequired: true,
1015
+ authorityRequired: true,
1016
+ notes: "Impact provenance bridge only; apply/proof/write gates remain separate."
1017
+ },
1018
+ {
1019
+ surface: "truth_candidate_read",
1020
+ producer: "truth_candidate_queries",
1021
+ path: "convex/truthCandidatesRuntime/queries.ts",
1022
+ status: "explicit_exemption",
1023
+ envelopeRequired: false,
1024
+ authorityRequired: true,
1025
+ exemptionReason: "Truth candidate queues are canonical domain read models; promotion/write paths remain separate and are not normalized in this rollout."
1026
+ },
1027
+ {
1028
+ surface: "workroom_state",
1029
+ producer: "workroom_state_reads",
1030
+ path: "apps/*/workroom",
1031
+ status: "deferred",
1032
+ envelopeRequired: false,
1033
+ authorityRequired: true,
1034
+ exemptionReason: "Deferred until a public consumer needs cross-surface explain metadata."
1035
+ },
1036
+ {
1037
+ surface: "pulse_read",
1038
+ producer: "pulse_reads",
1039
+ path: "apps/*/pulse",
1040
+ status: "deferred",
1041
+ envelopeRequired: false,
1042
+ authorityRequired: true,
1043
+ exemptionReason: "Deferred; Pulse governance and scheduling stay domain-local."
1044
+ },
1045
+ {
1046
+ surface: "context_lens",
1047
+ producer: "context_lens_reads",
1048
+ path: "packages/core/src/contextLens",
1049
+ status: "deferred",
1050
+ envelopeRequired: false,
1051
+ authorityRequired: true,
1052
+ exemptionReason: "Context Lens is semantically broader than Code Map; adapt after MCP and Code Map prove value."
1053
+ }
1054
+ ];
1055
+ function contextQueryRegistryEntryForSurface(surface) {
1056
+ return CONTEXT_QUERY_PUBLIC_READ_REGISTRY_V1.find((entry) => entry.surface === surface);
1057
+ }
1058
+ function contextQueryEnvelopeRequiredForSurface(surface) {
1059
+ return contextQueryRegistryEntryForSurface(surface)?.envelopeRequired === true;
1060
+ }
1061
+ function contextQueryAuthorityRequiredForSurface(surface) {
1062
+ const entry = contextQueryRegistryEntryForSurface(surface);
1063
+ return entry ? entry.authorityRequired : true;
1064
+ }
1065
+ function assertContextQueryPublicReadEnvelopeV1(args) {
1066
+ const entry = contextQueryRegistryEntryForSurface(args.surface);
1067
+ if (!entry) {
1068
+ return { ok: false, reason: "context_query_registry:unknown_surface", warnings: [`unknown public read surface: ${args.surface}`] };
1069
+ }
1070
+ if (!entry.envelopeRequired) {
1071
+ return { ok: true, warnings: entry.exemptionReason ? [entry.exemptionReason] : [] };
1072
+ }
1073
+ if (!args.envelope) {
1074
+ return { ok: false, reason: "context_query_registry:missing_envelope", warnings: [`${entry.producer} must include ContextQueryEnvelopeV1`] };
1075
+ }
1076
+ if (args.envelope.kind !== "rhei_context_query_envelope" || args.envelope.schemaVersion !== 1) {
1077
+ return { ok: false, reason: "context_query_registry:invalid_envelope", warnings: [`${entry.producer} returned an invalid context query envelope`] };
1078
+ }
1079
+ if (args.envelope.surface !== args.surface) {
1080
+ return { ok: false, reason: "context_query_registry:surface_mismatch", warnings: [`envelope surface ${args.envelope.surface} does not match registry surface ${args.surface}`] };
1081
+ }
1082
+ if (entry.authorityRequired) {
1083
+ const authority = args.envelope.authority;
1084
+ if (!authority?.noAuthority || !authority.noApply || !authority.noPromotion || authority.grantsApplyAuthority !== false || authority.grantsTruthPromotionAuthority !== false || authority.grantsMemoryPromotionAuthority !== false) {
1085
+ return { ok: false, reason: "context_query_registry:invalid_authority", warnings: [`${entry.producer} envelope must be explicit no-authority/no-apply/no-promotion`] };
1086
+ }
1087
+ }
1088
+ return { ok: true, warnings: [] };
1089
+ }
1090
+ export {
1091
+ uniqueContextQueryStrings,
1092
+ normalizeTrailRefs,
1093
+ normalizeReceiptRefs,
1094
+ normalizeEvidenceRefs,
1095
+ isContextQueryEnvelopeV1,
1096
+ contextQueryRegistryEntryForSurface,
1097
+ contextQueryEnvelopeRequiredForSurface,
1098
+ contextQueryAuthorityRequiredForSurface,
1099
+ buildRheiShellCodeMapContextQueryEnvelopeV1,
1100
+ buildReviewIntelligenceContextQueryEnvelopeV1,
1101
+ buildMcpSearchContextQueryEnvelopeV1,
1102
+ buildImpactPredictionContextQueryEnvelopeV1,
1103
+ buildContextQueryTruncationV1,
1104
+ buildContextQuerySourceScopeV1,
1105
+ buildContextQueryResultRefV1,
1106
+ buildContextQueryRequestSummaryV1,
1107
+ buildContextQueryProvenanceV1,
1108
+ buildContextQueryMissV1,
1109
+ buildContextQueryFreshnessV1,
1110
+ buildContextQueryExplainV1,
1111
+ buildContextQueryEnvelopeV1,
1112
+ buildContextQueryAuthorityV1,
1113
+ buildContextForGoalContextQueryEnvelopeV1,
1114
+ buildCodeMapContextQueryEnvelopeV1,
1115
+ assertContextQueryPublicReadEnvelopeV1,
1116
+ assertContextQueryEnvelopeV1,
1117
+ CONTEXT_QUERY_PUBLIC_READ_REGISTRY_V1,
1118
+ CONTEXT_QUERY_ENVELOPE_SCHEMA_VERSION
1119
+ };