@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,2781 @@
1
+ // ../core/src/codeTrail/types.ts
2
+ var CODE_TRAIL_SCHEMA_VERSION = 1;
3
+ var CODE_TRAIL_READ_MODEL_VERSION = 1;
4
+ var CODE_TRAIL_MODEL_VERSION = "code-trail-v1";
5
+ // ../core/src/codeTrail/selectors.ts
6
+ var CODE_TRAIL_NO_AUTHORITY_BOUNDARY = Object.freeze({
7
+ reportOnly: true,
8
+ noAuthority: true,
9
+ grantsApplyAuthority: false,
10
+ grantsCanonAuthority: false,
11
+ grantsProviderAuthority: false,
12
+ grantsNetworkAuthority: false,
13
+ grantsFilesystemEditAuthority: false,
14
+ grantsExecutionAuthority: false
15
+ });
16
+ var PHASE_SORT_ORDER = {
17
+ context: 0,
18
+ planning: 1,
19
+ execution: 2,
20
+ review: 3,
21
+ evidence: 4,
22
+ truth: 5,
23
+ import: 6,
24
+ observation: 7
25
+ };
26
+ var SAFE_METADATA_KEYS = new Set([
27
+ "artifactRefs",
28
+ "cursor",
29
+ "branch",
30
+ "cloudConsentStatus",
31
+ "cloudIndexStatus",
32
+ "cloudWorkspaceStatus",
33
+ "commit",
34
+ "consentTier",
35
+ "diagnosticCount",
36
+ "dirtyState",
37
+ "durationMs",
38
+ "duplicateDiagnosticsCount",
39
+ "errorCode",
40
+ "errorCodes",
41
+ "fileCount",
42
+ "generatedAt",
43
+ "graphId",
44
+ "hasErrors",
45
+ "importId",
46
+ "kind",
47
+ "nodeId",
48
+ "readinessStatus",
49
+ "reasonCode",
50
+ "reasonCodes",
51
+ "receiptRefs",
52
+ "receiptKind",
53
+ "requestId",
54
+ "resultState",
55
+ "revision",
56
+ "revisionCounter",
57
+ "runId",
58
+ "selectedRefCount",
59
+ "selectedRefs",
60
+ "sourceKind",
61
+ "sourceWatermark",
62
+ "status",
63
+ "patchStatus",
64
+ "proofStatus",
65
+ "tags",
66
+ "tokenCount",
67
+ "tokenEstimate",
68
+ "trailHash",
69
+ "warningCount",
70
+ "warnings",
71
+ "watermark"
72
+ ]);
73
+ var SAFE_METADATA_KEY_PATTERNS = [/Count$/, /Counts$/, /Hash$/, /Id$/, /Ids$/, /Ms$/, /Ref$/, /Refs$/];
74
+ var MAX_METADATA_STRING_LENGTH = 512;
75
+ var MAX_METADATA_ARRAY_LENGTH = 50;
76
+ function clamp(value, min, max) {
77
+ if (Number.isNaN(value))
78
+ return min;
79
+ return Math.min(max, Math.max(min, value));
80
+ }
81
+ function codeTrailNoAuthorityBoundary() {
82
+ return { ...CODE_TRAIL_NO_AUTHORITY_BOUNDARY };
83
+ }
84
+ function uniqueCodeTrailStrings(values) {
85
+ const seen = new Set;
86
+ const result = [];
87
+ for (const value of values) {
88
+ const trimmed = value?.trim();
89
+ if (!trimmed || seen.has(trimmed))
90
+ continue;
91
+ seen.add(trimmed);
92
+ result.push(trimmed);
93
+ }
94
+ return result;
95
+ }
96
+ function buildCodeTrailRefStableKey(args) {
97
+ return args.repoId ? `${args.kind}:${args.repoId}:${args.id}` : `${args.kind}:${args.id}`;
98
+ }
99
+ function buildCodeTrailSourceKey(args) {
100
+ return `source:${args.sourceKind}:${args.stableKey}`;
101
+ }
102
+ function isDeterministicCodeTrailRef(ref) {
103
+ if (!ref)
104
+ return false;
105
+ return Boolean(ref.id.trim() && ref.stableKey.trim() && ref.sourceKey.trim());
106
+ }
107
+ function sanitizeCodeTrailMetadata(metadata) {
108
+ if (!metadata)
109
+ return;
110
+ const output = {};
111
+ for (const [key, value] of Object.entries(metadata)) {
112
+ const trimmedKey = key.trim();
113
+ if (!trimmedKey || !isSafeMetadataKey(trimmedKey))
114
+ continue;
115
+ if (isSafeMetadataPrimitive(value)) {
116
+ output[trimmedKey] = value;
117
+ continue;
118
+ }
119
+ if (Array.isArray(value) && value.length <= MAX_METADATA_ARRAY_LENGTH && value.every(isSafeMetadataPrimitive)) {
120
+ output[trimmedKey] = value;
121
+ }
122
+ }
123
+ return Object.keys(output).length > 0 ? output : undefined;
124
+ }
125
+ function admitSource(candidate) {
126
+ const key = candidate.key?.trim();
127
+ const kind = candidate.kind;
128
+ if (!key || !kind)
129
+ return null;
130
+ return {
131
+ key,
132
+ kind,
133
+ ref: isDeterministicCodeTrailRef(candidate.ref) ? sanitizeRef(candidate.ref) : undefined,
134
+ label: candidate.label,
135
+ observedAt: candidate.observedAt,
136
+ confidence: candidate.confidence === undefined ? undefined : clamp(candidate.confidence, 0, 1),
137
+ watermark: candidate.watermark
138
+ };
139
+ }
140
+ function admitCodeTrailGap(candidate) {
141
+ const sourceKey = candidate.sourceKey?.trim();
142
+ if (!sourceKey)
143
+ return null;
144
+ const stableKey = candidate.stableKey?.trim() || `gap:${sourceKey}:${candidate.kind ?? "source_unavailable"}`;
145
+ return {
146
+ schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
147
+ id: candidate.id?.trim() || stableKey,
148
+ stableKey,
149
+ kind: candidate.kind ?? "source_unavailable",
150
+ severity: candidate.severity ?? "info",
151
+ title: candidate.title?.trim() || "Trail source gap",
152
+ detail: candidate.detail,
153
+ sourceKey,
154
+ ref: isDeterministicCodeTrailRef(candidate.ref) ? sanitizeRef(candidate.ref) : undefined
155
+ };
156
+ }
157
+ function admitEntry(candidate) {
158
+ if (!isDeterministicCodeTrailRef(candidate.primaryRef))
159
+ return null;
160
+ const primaryRef = sanitizeRef(candidate.primaryRef);
161
+ const sourceKey = candidate.sourceKey?.trim() || primaryRef.sourceKey;
162
+ if (!sourceKey)
163
+ return null;
164
+ const sourceRefs = uniqueRefs([primaryRef, ...candidate.sourceRefs ?? []]);
165
+ const inputRefs = uniqueRefs(candidate.inputRefs ?? []);
166
+ const outputRefs = uniqueRefs(candidate.outputRefs ?? []);
167
+ const evidenceRefs = uniqueRefs(candidate.evidenceRefs ?? []);
168
+ const receiptRefs = uniqueRefs(candidate.receiptRefs ?? []);
169
+ const relatedRefs = uniqueRefs(candidate.relatedRefs ?? []);
170
+ const stableKey = candidate.stableKey?.trim() || `entry:${candidate.entryKind ?? "observation"}:${primaryRef.stableKey}`;
171
+ const metadata = sanitizeCodeTrailMetadata(candidate.metadata);
172
+ return {
173
+ schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
174
+ id: candidate.id?.trim() || stableKey,
175
+ stableKey,
176
+ sourceKey,
177
+ sourceKeys: uniqueCodeTrailStrings([
178
+ sourceKey,
179
+ ...candidate.sourceKeys ?? [],
180
+ primaryRef.sourceKey,
181
+ ...sourceRefs.map((ref) => ref.sourceKey),
182
+ ...inputRefs.map((ref) => ref.sourceKey),
183
+ ...outputRefs.map((ref) => ref.sourceKey),
184
+ ...evidenceRefs.map((ref) => ref.sourceKey),
185
+ ...receiptRefs.map((ref) => ref.sourceKey),
186
+ ...relatedRefs.map((ref) => ref.sourceKey)
187
+ ]),
188
+ entryKind: candidate.entryKind ?? "observation",
189
+ phase: candidate.phase ?? "observation",
190
+ status: candidate.status ?? "observed",
191
+ sourceStatus: candidate.sourceStatus,
192
+ title: candidate.title,
193
+ summary: candidate.summary,
194
+ primaryRef,
195
+ sourceRefs,
196
+ inputRefs,
197
+ outputRefs,
198
+ evidenceRefs,
199
+ receiptRefs,
200
+ relatedRefs,
201
+ reasonCodes: uniqueCodeTrailStrings(candidate.reasonCodes ?? []),
202
+ createdAt: candidate.createdAt,
203
+ updatedAt: candidate.updatedAt,
204
+ startedAt: candidate.startedAt,
205
+ completedAt: candidate.completedAt,
206
+ metadata,
207
+ authorityBoundary: codeTrailNoAuthorityBoundary()
208
+ };
209
+ }
210
+ function admitLink(candidate) {
211
+ if (!isDeterministicCodeTrailRef(candidate.sourceRef))
212
+ return null;
213
+ if (!isDeterministicCodeTrailRef(candidate.targetRef))
214
+ return null;
215
+ const sourceRef = sanitizeRef(candidate.sourceRef);
216
+ const targetRef = sanitizeRef(candidate.targetRef);
217
+ const sourceKeys = uniqueCodeTrailStrings([
218
+ ...candidate.sourceKeys ?? [],
219
+ sourceRef.sourceKey,
220
+ targetRef.sourceKey
221
+ ]);
222
+ if (sourceKeys.length === 0)
223
+ return null;
224
+ const stableKey = candidate.stableKey?.trim() || `link:${candidate.kind ?? "references"}:${sourceRef.stableKey}:${targetRef.stableKey}`;
225
+ const metadata = sanitizeCodeTrailMetadata(candidate.metadata);
226
+ return {
227
+ schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
228
+ id: candidate.id?.trim() || stableKey,
229
+ stableKey,
230
+ kind: candidate.kind ?? "references",
231
+ sourceRef,
232
+ targetRef,
233
+ sourceKeys,
234
+ reasonCodes: uniqueCodeTrailStrings(candidate.reasonCodes ?? []),
235
+ metadata
236
+ };
237
+ }
238
+ function normalizeCodeTrailProjection(candidate) {
239
+ const entries = dedupeCodeTrailEntries(sortCodeTrailEntries((candidate.entries ?? []).map(admitEntry).filter(isPresent)));
240
+ const links = dedupeCodeTrailLinks(sortCodeTrailLinks((candidate.links ?? []).map(admitLink).filter(isPresent)));
241
+ const sources = dedupeSources((candidate.sources ?? []).map(admitSource).filter(isPresent));
242
+ const gaps = dedupeGaps((candidate.gaps ?? []).map(admitCodeTrailGap).filter(isPresent));
243
+ const reasonCodes = uniqueCodeTrailStrings([
244
+ ...candidate.summary?.reasonCodes ?? [],
245
+ ...entries.flatMap((entry) => entry.reasonCodes)
246
+ ]);
247
+ return {
248
+ schemaVersion: CODE_TRAIL_SCHEMA_VERSION,
249
+ readModelVersion: CODE_TRAIL_READ_MODEL_VERSION,
250
+ modelVersion: CODE_TRAIL_MODEL_VERSION,
251
+ projectId: candidate.projectId,
252
+ generatedAt: candidate.generatedAt ?? 0,
253
+ scope: {
254
+ projectId: candidate.scope?.projectId ?? candidate.projectId,
255
+ repoId: candidate.scope?.repoId,
256
+ repoName: candidate.scope?.repoName,
257
+ sessionId: candidate.scope?.sessionId,
258
+ workroomRunId: candidate.scope?.workroomRunId,
259
+ patchRunId: candidate.scope?.patchRunId,
260
+ editSessionId: candidate.scope?.editSessionId,
261
+ editSessionRowId: candidate.scope?.editSessionRowId,
262
+ truthCandidateId: candidate.scope?.truthCandidateId,
263
+ capabilityRunId: candidate.scope?.capabilityRunId,
264
+ importId: candidate.scope?.importId,
265
+ trailHash: candidate.scope?.trailHash,
266
+ sourceMcpRequestId: candidate.scope?.sourceMcpRequestId,
267
+ sourceMcpRunId: candidate.scope?.sourceMcpRunId,
268
+ sourceRunId: candidate.scope?.sourceRunId,
269
+ receiptId: candidate.scope?.receiptId,
270
+ artifactId: candidate.scope?.artifactId,
271
+ codeMarketSnapshotId: candidate.scope?.codeMarketSnapshotId,
272
+ mcpContextRunId: candidate.scope?.mcpContextRunId,
273
+ prSnapshotId: candidate.scope?.prSnapshotId,
274
+ reviewRoomId: candidate.scope?.reviewRoomId,
275
+ storyId: candidate.scope?.storyId,
276
+ filePath: candidate.scope?.filePath,
277
+ surface: candidate.scope?.surface,
278
+ sourceMode: candidate.scope?.sourceMode
279
+ },
280
+ summary: {
281
+ title: candidate.summary?.title?.trim() || "Code Trail",
282
+ detail: candidate.summary?.detail,
283
+ entryCount: entries.length,
284
+ linkCount: links.length,
285
+ statusCounts: countStatuses(entries),
286
+ reasonCodes
287
+ },
288
+ entries,
289
+ links,
290
+ sources,
291
+ gaps,
292
+ sourceWatermarks: dedupeBySourceKey(candidate.sourceWatermarks ?? []),
293
+ truncation: dedupeBySourceKey(candidate.truncation ?? []),
294
+ authorityBoundary: codeTrailNoAuthorityBoundary()
295
+ };
296
+ }
297
+ function sortCodeTrailEntries(entries) {
298
+ return [...entries].sort((a, b) => {
299
+ const timeDelta = entrySortTime(b) - entrySortTime(a);
300
+ if (timeDelta !== 0)
301
+ return timeDelta;
302
+ const phaseDelta = PHASE_SORT_ORDER[a.phase] - PHASE_SORT_ORDER[b.phase];
303
+ if (phaseDelta !== 0)
304
+ return phaseDelta;
305
+ return a.stableKey.localeCompare(b.stableKey);
306
+ });
307
+ }
308
+ function sortCodeTrailLinks(links) {
309
+ return [...links].sort((a, b) => {
310
+ const sourceDelta = a.sourceRef.stableKey.localeCompare(b.sourceRef.stableKey);
311
+ if (sourceDelta !== 0)
312
+ return sourceDelta;
313
+ const targetDelta = a.targetRef.stableKey.localeCompare(b.targetRef.stableKey);
314
+ if (targetDelta !== 0)
315
+ return targetDelta;
316
+ return a.stableKey.localeCompare(b.stableKey);
317
+ });
318
+ }
319
+ function dedupeCodeTrailEntries(entries) {
320
+ const byStableKey = new Map;
321
+ for (const entry of entries) {
322
+ const existing = byStableKey.get(entry.stableKey);
323
+ if (!existing || entrySortTime(entry) >= entrySortTime(existing)) {
324
+ byStableKey.set(entry.stableKey, entry);
325
+ }
326
+ }
327
+ return sortCodeTrailEntries([...byStableKey.values()]);
328
+ }
329
+ function dedupeCodeTrailLinks(links) {
330
+ const seen = new Set;
331
+ const output = [];
332
+ for (const link of links) {
333
+ const key = link.stableKey;
334
+ if (seen.has(key))
335
+ continue;
336
+ seen.add(key);
337
+ output.push(link);
338
+ }
339
+ return sortCodeTrailLinks(output);
340
+ }
341
+ function getCodeTrailEntryById(trail, id) {
342
+ return (trail.entries ?? []).find((entry) => entry.id === id || entry.stableKey === id);
343
+ }
344
+ function getCodeTrailEntriesForRef(trail, refStableKey) {
345
+ return (trail.entries ?? []).filter((entry) => [
346
+ entry.primaryRef,
347
+ ...entry.sourceRefs,
348
+ ...entry.inputRefs,
349
+ ...entry.outputRefs,
350
+ ...entry.evidenceRefs,
351
+ ...entry.receiptRefs,
352
+ ...entry.relatedRefs
353
+ ].some((ref) => ref.stableKey === refStableKey || ref.id === refStableKey));
354
+ }
355
+ function sanitizeRef(ref) {
356
+ return {
357
+ ...ref,
358
+ id: ref.id.trim(),
359
+ stableKey: ref.stableKey.trim(),
360
+ sourceKey: ref.sourceKey.trim(),
361
+ metadata: sanitizeCodeTrailMetadata(ref.metadata)
362
+ };
363
+ }
364
+ function uniqueRefs(refs) {
365
+ const seen = new Set;
366
+ const output = [];
367
+ for (const ref of refs) {
368
+ if (!isDeterministicCodeTrailRef(ref))
369
+ continue;
370
+ const sanitized = sanitizeRef(ref);
371
+ const key = `${sanitized.kind}:${sanitized.stableKey}:${sanitized.sourceKey}`;
372
+ if (seen.has(key))
373
+ continue;
374
+ seen.add(key);
375
+ output.push(sanitized);
376
+ }
377
+ return output;
378
+ }
379
+ function isSafeMetadataPrimitive(value) {
380
+ if (value === null || typeof value === "boolean")
381
+ return true;
382
+ if (typeof value === "number")
383
+ return Number.isFinite(value);
384
+ if (typeof value === "string")
385
+ return value.length <= MAX_METADATA_STRING_LENGTH;
386
+ return false;
387
+ }
388
+ function isSafeMetadataKey(key) {
389
+ return SAFE_METADATA_KEYS.has(key) || SAFE_METADATA_KEY_PATTERNS.some((pattern) => pattern.test(key));
390
+ }
391
+ function entrySortTime(entry) {
392
+ return entry.updatedAt ?? entry.completedAt ?? entry.startedAt ?? entry.createdAt ?? 0;
393
+ }
394
+ function countStatuses(entries) {
395
+ const counts = {};
396
+ for (const entry of entries) {
397
+ counts[entry.status] = (counts[entry.status] ?? 0) + 1;
398
+ }
399
+ return counts;
400
+ }
401
+ function dedupeSources(sources) {
402
+ const seen = new Set;
403
+ const output = [];
404
+ for (const source of sources) {
405
+ if (seen.has(source.key))
406
+ continue;
407
+ seen.add(source.key);
408
+ output.push(source);
409
+ }
410
+ return output.sort((a, b) => a.key.localeCompare(b.key));
411
+ }
412
+ function dedupeGaps(gaps) {
413
+ const seen = new Set;
414
+ const output = [];
415
+ for (const gap of gaps) {
416
+ if (seen.has(gap.stableKey))
417
+ continue;
418
+ seen.add(gap.stableKey);
419
+ output.push(gap);
420
+ }
421
+ return output.sort((a, b) => a.stableKey.localeCompare(b.stableKey));
422
+ }
423
+ function dedupeBySourceKey(items) {
424
+ const seen = new Set;
425
+ const output = [];
426
+ for (const item of items) {
427
+ const sourceKey = item.sourceKey.trim();
428
+ if (!sourceKey || seen.has(sourceKey))
429
+ continue;
430
+ seen.add(sourceKey);
431
+ output.push({ ...item, sourceKey });
432
+ }
433
+ return output.sort((a, b) => a.sourceKey.localeCompare(b.sourceKey));
434
+ }
435
+ function isPresent(value) {
436
+ return value !== null && value !== undefined;
437
+ }
438
+ // ../core/src/codeMarket/types.ts
439
+ var CODE_MARKET_SCHEMA_VERSION = 1;
440
+ var CODE_MARKET_READ_MODEL_VERSION = 1;
441
+ var CODE_MARKET_MODEL_VERSION = "code-market-v1";
442
+ // ../core/src/codeMarket/selectors.ts
443
+ var NON_ADMITTING_AUTHORITIES = new Set(["llm_label", "ready_code_insight", "title"]);
444
+ var NON_ADMITTING_REF_KINDS = new Set(["llm_label", "title"]);
445
+ function clamp2(value, min, max) {
446
+ if (Number.isNaN(value))
447
+ return min;
448
+ return Math.min(max, Math.max(min, value));
449
+ }
450
+ function unique(values) {
451
+ const seen = new Set;
452
+ const result = [];
453
+ for (const value of values) {
454
+ const trimmed = value?.trim();
455
+ if (!trimmed || seen.has(trimmed))
456
+ continue;
457
+ seen.add(trimmed);
458
+ result.push(trimmed);
459
+ }
460
+ return result;
461
+ }
462
+ function isDeterministicCodeMarketRef(ref) {
463
+ if (!ref)
464
+ return false;
465
+ if (!ref.id.trim() || !ref.stableKey.trim() || !ref.sourceKey.trim())
466
+ return false;
467
+ if (NON_ADMITTING_AUTHORITIES.has(ref.authority))
468
+ return false;
469
+ if (NON_ADMITTING_REF_KINDS.has(ref.kind))
470
+ return false;
471
+ return true;
472
+ }
473
+ function normalizeSelection(candidate) {
474
+ const filePaths = unique(candidate?.filePaths ?? []);
475
+ const nodeIds = unique(candidate?.nodeIds ?? []);
476
+ const moduleIds = unique(candidate?.moduleIds ?? []);
477
+ const entityIds = unique(candidate?.entityIds ?? []);
478
+ return {
479
+ source: candidate?.source ?? "code_market",
480
+ repoId: candidate?.repoId,
481
+ filePaths,
482
+ nodeIds,
483
+ moduleIds,
484
+ entityIds,
485
+ selectedItems: candidate?.selectedItems ?? [],
486
+ previewFilePaths: candidate?.previewFilePaths ?? filePaths.slice(0, 12),
487
+ label: candidate?.label ?? "Code Context selection",
488
+ warnings: candidate?.warnings ?? [],
489
+ workingSetItem: candidate?.workingSetItem
490
+ };
491
+ }
492
+ function admitGap(candidate) {
493
+ const sourceKey = candidate.sourceKey?.trim();
494
+ if (!sourceKey)
495
+ return null;
496
+ const stableKey = candidate.stableKey?.trim() || `gap:${sourceKey}:${candidate.kind ?? "source_unavailable"}`;
497
+ return {
498
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
499
+ id: candidate.id?.trim() || stableKey,
500
+ stableKey,
501
+ kind: candidate.kind ?? "source_unavailable",
502
+ severity: candidate.severity ?? "info",
503
+ title: candidate.title?.trim() || "Source gap",
504
+ detail: candidate.detail,
505
+ sourceKey,
506
+ ref: candidate.ref
507
+ };
508
+ }
509
+ function admitRelationship(candidate) {
510
+ if (!isDeterministicCodeMarketRef(candidate.sourceRef))
511
+ return null;
512
+ if (!isDeterministicCodeMarketRef(candidate.targetRef))
513
+ return null;
514
+ const sourceKeys = unique([
515
+ ...candidate.sourceKeys ?? [],
516
+ candidate.sourceRef.sourceKey,
517
+ candidate.targetRef.sourceKey
518
+ ]);
519
+ if (sourceKeys.length === 0)
520
+ return null;
521
+ const stableKey = candidate.stableKey?.trim() || `relationship:${candidate.kind ?? "relates_to"}:${candidate.sourceRef.stableKey}:${candidate.targetRef.stableKey}`;
522
+ return {
523
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
524
+ id: candidate.id?.trim() || stableKey,
525
+ stableKey,
526
+ kind: candidate.kind ?? "relates_to",
527
+ sourceRef: candidate.sourceRef,
528
+ targetRef: candidate.targetRef,
529
+ sourceKeys,
530
+ label: candidate.label,
531
+ strength: clamp2(candidate.strength ?? 0.5, 0, 1),
532
+ reasonCodes: unique(candidate.reasonCodes ?? [])
533
+ };
534
+ }
535
+ function admitAction(candidate) {
536
+ const mode = candidate.mode;
537
+ const state = candidate.state ?? "enabled";
538
+ const refs = candidate.refs ?? [];
539
+ const reasonCodes = unique(candidate.reasonCodes ?? []);
540
+ const sourceKeys = unique([...candidate.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]);
541
+ const stableKey = candidate.stableKey?.trim() || candidate.id?.trim();
542
+ const id = candidate.id?.trim() || stableKey;
543
+ const label = candidate.label?.trim();
544
+ if (!stableKey || !id || !label)
545
+ return null;
546
+ const base = {
547
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
548
+ id,
549
+ stableKey,
550
+ label,
551
+ shortLabel: candidate.shortLabel,
552
+ description: candidate.description,
553
+ sourceKeys,
554
+ refs,
555
+ reasonCodes,
556
+ sortPriority: candidate.sortPriority ?? 0
557
+ };
558
+ if (state === "disabled") {
559
+ if (mode !== "disabled")
560
+ return null;
561
+ const disabledReason = candidate.disabledReason?.trim();
562
+ if (!disabledReason || reasonCodes.length === 0)
563
+ return null;
564
+ return { ...base, state: "disabled", mode: "disabled", disabledReason };
565
+ }
566
+ if (sourceKeys.length === 0)
567
+ return null;
568
+ if (mode === "rheiAction" && candidate.rheiAction) {
569
+ return { ...base, state: "enabled", mode: "rheiAction", rheiAction: candidate.rheiAction };
570
+ }
571
+ if (mode === "localOnly" && candidate.localOnly) {
572
+ return { ...base, state: "enabled", mode: "localOnly", localOnly: candidate.localOnly };
573
+ }
574
+ return null;
575
+ }
576
+ function admitWorkCluster(candidate) {
577
+ const sourceKey = candidate.sourceKey?.trim();
578
+ if (!sourceKey)
579
+ return null;
580
+ const changedRefs = (candidate.changedRefs ?? []).filter(isDeterministicCodeMarketRef);
581
+ const relatedRefs = (candidate.relatedRefs ?? []).filter(isDeterministicCodeMarketRef);
582
+ const sourceRefs = (candidate.sourceRefs ?? []).filter(isDeterministicCodeMarketRef);
583
+ const evidenceRefs = (candidate.evidenceRefs ?? []).filter(isDeterministicCodeMarketRef);
584
+ const receiptRefs = (candidate.receiptRefs ?? []).filter(isDeterministicCodeMarketRef);
585
+ const identityRefs = uniqueRefs2([
586
+ ...changedRefs,
587
+ ...sourceRefs,
588
+ ...evidenceRefs,
589
+ ...receiptRefs,
590
+ ...relatedRefs
591
+ ]);
592
+ if (identityRefs.length === 0)
593
+ return null;
594
+ const sourceKeys = unique([
595
+ sourceKey,
596
+ ...candidate.sourceKeys ?? [],
597
+ ...identityRefs.map((ref) => ref.sourceKey)
598
+ ]);
599
+ const stableKey = candidate.stableKey?.trim() || `work-cluster:${sourceKey}`;
600
+ const title = candidate.title?.trim() || identityRefs[0]?.label || "Code Context work cluster";
601
+ return {
602
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
603
+ id: candidate.id?.trim() || stableKey,
604
+ stableKey,
605
+ sourceKey,
606
+ sourceKeys,
607
+ title,
608
+ summary: candidate.summary,
609
+ status: candidate.status ?? "observed",
610
+ completion: candidate.completion ?? "unknown",
611
+ changedRefs,
612
+ relatedRefs,
613
+ sourceRefs,
614
+ evidenceRefs,
615
+ receiptRefs,
616
+ tileIds: unique(candidate.tileIds ?? []),
617
+ relationshipIds: unique(candidate.relationshipIds ?? []),
618
+ reasonCodes: unique(candidate.reasonCodes ?? []),
619
+ confidence: clamp2(candidate.confidence ?? 0.5, 0, 1),
620
+ updatedAt: candidate.updatedAt ?? 0,
621
+ selection: candidate.selection ? normalizeSelection(candidate.selection) : undefined,
622
+ metadata: candidate.metadata
623
+ };
624
+ }
625
+ function admitTile(candidate) {
626
+ const refs = candidate.refs ?? [];
627
+ const primaryRef = refs.find(isDeterministicCodeMarketRef);
628
+ if (!primaryRef)
629
+ return null;
630
+ const title = candidate.title?.trim();
631
+ if (!title)
632
+ return null;
633
+ const sourceKeys = unique([...candidate.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]);
634
+ if (sourceKeys.length === 0)
635
+ return null;
636
+ const stableKey = candidate.stableKey?.trim() || `tile:${primaryRef.stableKey}`;
637
+ return {
638
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
639
+ id: candidate.id?.trim() || stableKey,
640
+ stableKey,
641
+ kind: candidate.kind ?? "module",
642
+ title,
643
+ subtitle: candidate.subtitle,
644
+ state: candidate.state ?? "unknown",
645
+ confidence: clamp2(candidate.confidence ?? 0.5, 0, 1),
646
+ controlWeight: candidate.controlWeight ?? 0,
647
+ primaryRef,
648
+ refs,
649
+ sourceKeys,
650
+ reasonCodes: unique(candidate.reasonCodes ?? []),
651
+ selection: normalizeSelection(candidate.selection),
652
+ gaps: candidate.gaps ?? [],
653
+ actions: candidate.actions ?? [],
654
+ metadata: candidate.metadata
655
+ };
656
+ }
657
+ function admitSector(candidate) {
658
+ const stableKey = candidate.stableKey?.trim() || candidate.id?.trim();
659
+ const title = candidate.title?.trim();
660
+ const sourceKeys = unique(candidate.sourceKeys ?? []);
661
+ if (!stableKey || !title || sourceKeys.length === 0)
662
+ return null;
663
+ return {
664
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
665
+ id: candidate.id?.trim() || stableKey,
666
+ stableKey,
667
+ title,
668
+ sourceKeys,
669
+ tileIds: unique(candidate.tileIds ?? []),
670
+ sortOrder: candidate.sortOrder ?? 0
671
+ };
672
+ }
673
+ function uniqueRefs2(refs) {
674
+ const seen = new Set;
675
+ const output = [];
676
+ for (const ref of refs) {
677
+ const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
678
+ if (seen.has(key))
679
+ continue;
680
+ seen.add(key);
681
+ output.push(ref);
682
+ }
683
+ return output;
684
+ }
685
+ // ../core/src/agentFactoryRouting.ts
686
+ var AGENT_FACTORY_TEMPLATE_IDS = [
687
+ "habit_coach",
688
+ "wellness_coach",
689
+ "learning_coach",
690
+ "hobby_project_agent",
691
+ "creative_partner",
692
+ "personal_ops_agent",
693
+ "project_agent",
694
+ "codebase_agent",
695
+ "project_review_agent"
696
+ ];
697
+ var AGENT_FACTORY_SOURCES = [
698
+ "natural_language",
699
+ "template",
700
+ "pulse_signal",
701
+ "widget_promotion",
702
+ "context_lens",
703
+ "canvas_cli",
704
+ "slash_command"
705
+ ];
706
+ var TEMPLATE_ID_SET = new Set(AGENT_FACTORY_TEMPLATE_IDS);
707
+ var SOURCE_SET = new Set(AGENT_FACTORY_SOURCES);
708
+ // ../core/src/briefs/types.ts
709
+ var BRIEF_COMMAND_DESCRIPTORS_V1 = {
710
+ open: {
711
+ command: "open",
712
+ label: "Open",
713
+ description: "Open this item as a reference.",
714
+ recordsPositiveEvidence: true
715
+ },
716
+ ask_with_this: {
717
+ command: "ask_with_this",
718
+ label: "Ask with this",
719
+ description: "Use this item as context for an Ask Rhei turn.",
720
+ recordsPositiveEvidence: true
721
+ },
722
+ ask_with_brief: {
723
+ command: "ask_with_brief",
724
+ label: "Ask with Brief",
725
+ description: "Use the full brief as context for an Ask Rhei turn.",
726
+ recordsPositiveEvidence: true
727
+ },
728
+ pin: {
729
+ command: "pin",
730
+ label: "Pin",
731
+ description: "Save this item for the current work without promoting it to canonical truth.",
732
+ defaultScope: "current_working_set",
733
+ correctionTool: true,
734
+ recordsPositiveEvidence: true
735
+ },
736
+ hide_for_me: {
737
+ command: "hide_for_me",
738
+ label: "Hide",
739
+ description: "Hide this item for your ranking only.",
740
+ defaultScope: "personal_ranking",
741
+ correctionTool: true
742
+ },
743
+ why_this_appears: {
744
+ command: "why_this_appears",
745
+ label: "Why this appears",
746
+ description: "Show evidence and reasoning for this item."
747
+ },
748
+ not_useful_here: {
749
+ command: "not_useful_here",
750
+ label: "Not useful here",
751
+ description: "Downrank this item for the current working context only.",
752
+ defaultScope: "current_working_set",
753
+ correctionTool: true
754
+ },
755
+ not_related: {
756
+ command: "not_related",
757
+ label: "Not related",
758
+ description: "Mark this soft connection as not related at the project level.",
759
+ defaultScope: "project_connection",
760
+ correctionTool: true,
761
+ requiresConnection: true
762
+ },
763
+ wrong: {
764
+ command: "wrong",
765
+ label: "Wrong",
766
+ description: "Flag this soft connection as wrong for review.",
767
+ defaultScope: "project_connection",
768
+ correctionTool: true,
769
+ requiresConnection: true
770
+ },
771
+ request_review: {
772
+ command: "request_review",
773
+ label: "Review relationship",
774
+ description: "Open a governed review request without mutating canonical truth.",
775
+ defaultScope: "project_connection",
776
+ governanceOnly: true,
777
+ requiresConnection: true
778
+ }
779
+ };
780
+ var BRIEF_COMMAND_LABELS_V1 = Object.fromEntries(Object.entries(BRIEF_COMMAND_DESCRIPTORS_V1).map(([command, descriptor]) => [command, descriptor.label]));
781
+ var BRIEF_COMMAND_DEFAULT_SCOPES_V1 = Object.fromEntries(Object.entries(BRIEF_COMMAND_DESCRIPTORS_V1).filter(([, descriptor]) => Boolean(descriptor.defaultScope)).map(([command, descriptor]) => [command, descriptor.defaultScope]));
782
+
783
+ // ../core/src/contextRouting/graphExecutionMode.ts
784
+ var GRAPH_EXECUTION_MODES = [
785
+ "convex_local",
786
+ "connected_work_shallow",
787
+ "memgraph_depth3",
788
+ "memgraph_depth5",
789
+ "memgraph_depth5_plus_lite_llm"
790
+ ];
791
+ // ../core/src/contextRouting/plannerHandoffGraphAdvisory.ts
792
+ var VALID_SOURCES = new Set([
793
+ "local_code_context",
794
+ "code_market",
795
+ "mcp_input",
796
+ "task_brief",
797
+ "workroom_context_receipt",
798
+ "connected_work_packet",
799
+ "plan_contract",
800
+ "external"
801
+ ]);
802
+ var VALID_BASES = new Set([
803
+ "graph_routing_policy_v1",
804
+ "explicit_metadata",
805
+ "default_no_live"
806
+ ]);
807
+ var VALID_EVIDENCE_QUALITY = new Set(["none", "weak", "usable", "strong"]);
808
+ var VALID_GRAPH_NOISE_RISK = new Set(["unknown", "low", "medium", "high"]);
809
+ var VALID_MODES = new Set(GRAPH_EXECUTION_MODES);
810
+ // ../core/src/contextRouting/surfacePolicies.ts
811
+ var CONNECTED_SURFACE_KINDS_V1 = [
812
+ "primary_code",
813
+ "targeted_tests",
814
+ "user_docs",
815
+ "config_policy",
816
+ "package_exports",
817
+ "runtime_enforcement",
818
+ "schema_persistence",
819
+ "ui_surface",
820
+ "design_system_or_shared_component",
821
+ "usage_sites",
822
+ "visual_snapshot_or_story",
823
+ "native_counterpart",
824
+ "receipt_audit",
825
+ "eval_report",
826
+ "migration_notes",
827
+ "provider_gateway",
828
+ "agent_handoff"
829
+ ];
830
+ var COMMON_CODE_EVIDENCE = [
831
+ "primary_edit_file",
832
+ "context_slice",
833
+ "source_ref",
834
+ "evidence_ref"
835
+ ];
836
+ var COMMON_SUPPORT_EVIDENCE = [
837
+ "context_slice",
838
+ "affected_test",
839
+ "affected_doc",
840
+ "config_file",
841
+ "source_ref",
842
+ "evidence_ref",
843
+ "receipt_ref"
844
+ ];
845
+ function required(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
846
+ return { surfaceKind, level: "required", minEvidenceCount, evidenceTypes, rationale };
847
+ }
848
+ function optional(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
849
+ return { surfaceKind, level: "optional", minEvidenceCount, evidenceTypes, rationale };
850
+ }
851
+ var CONNECTED_SURFACE_POLICIES_V1 = {
852
+ shared_abstraction: {
853
+ version: 1,
854
+ changeShape: "shared_abstraction",
855
+ label: "Shared abstraction",
856
+ description: "Reusable code contracts need implementation, public contract/docs, and regression tests in the same bounded packet.",
857
+ recommendedEscalation: "memgraph_depth3",
858
+ graphInput: {
859
+ intentConfidence: "strong",
860
+ graphComplexity: "medium",
861
+ connectedWorkAvailable: true,
862
+ noLiveMode: true,
863
+ networkAllowed: false,
864
+ providerCallsAllowed: false
865
+ },
866
+ rules: [
867
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
868
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Shared behavior changes need targeted regression tests."),
869
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Public behavior should stay aligned with user-facing docs."),
870
+ optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Export/type surfaces often carry shared abstraction contracts."),
871
+ optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Runtime guards and helpers can constrain shared behavior."),
872
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing receipts or reports help confirm prior behavior.")
873
+ ]
874
+ },
875
+ ui_behavior: {
876
+ version: 1,
877
+ changeShape: "ui_behavior",
878
+ label: "UI behavior",
879
+ description: "UI behavior packets need render code and visible surface context, with tests/docs when available.",
880
+ recommendedEscalation: "connected_work_shallow",
881
+ graphInput: {
882
+ intentConfidence: "strong",
883
+ graphComplexity: "shallow",
884
+ connectedWorkAvailable: true,
885
+ noLiveMode: true,
886
+ networkAllowed: false,
887
+ providerCallsAllowed: false
888
+ },
889
+ rules: [
890
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary render/state code must be represented."),
891
+ required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
892
+ optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
893
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "UI regression tests are useful when present."),
894
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Trail/receipt display surfaces should remain auditable."),
895
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-visible behavior may need docs or copy updates.")
896
+ ]
897
+ },
898
+ ui_reuse_or_design_system: {
899
+ version: 1,
900
+ changeShape: "ui_reuse_or_design_system",
901
+ label: "UI reuse or design system",
902
+ description: "Reusable UI/design-system opportunities need shared component context, usage sites, package exports, and visible UI surfaces in the same bounded packet.",
903
+ recommendedEscalation: "connected_work_shallow",
904
+ graphInput: {
905
+ intentConfidence: "strong",
906
+ graphComplexity: "shallow",
907
+ connectedWorkAvailable: true,
908
+ noLiveMode: true,
909
+ networkAllowed: false,
910
+ providerCallsAllowed: false
911
+ },
912
+ rules: [
913
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
914
+ required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
915
+ required("design_system_or_shared_component", 1, COMMON_SUPPORT_EVIDENCE, "The shared UI primitive or design-system component must be represented."),
916
+ required("usage_sites", 1, COMMON_SUPPORT_EVIDENCE, "Representative call sites must show how the reusable behavior is consumed."),
917
+ required("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Package export surfaces must expose or bound the reusable UI contract."),
918
+ optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
919
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Reusable UI behavior should have targeted regression tests when available."),
920
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Shared UI behavior may need docs or usage guidance."),
921
+ optional("visual_snapshot_or_story", 1, COMMON_SUPPORT_EVIDENCE, "Visual snapshots or stories help validate reusable UI behavior."),
922
+ optional("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes can bound adoption across usage sites."),
923
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing reports or receipts help confirm prior UI behavior.")
924
+ ]
925
+ },
926
+ execution_safety: {
927
+ version: 1,
928
+ changeShape: "execution_safety",
929
+ label: "Execution safety",
930
+ description: "Safety-sensitive changes need implementation, enforcement, tests, and audit/receipt surfaces.",
931
+ recommendedEscalation: "memgraph_depth5",
932
+ graphInput: {
933
+ intentConfidence: "strong",
934
+ graphComplexity: "high",
935
+ connectedWorkAvailable: true,
936
+ noLiveMode: true,
937
+ networkAllowed: false,
938
+ providerCallsAllowed: false
939
+ },
940
+ rules: [
941
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Safety behavior must include the primary implementation."),
942
+ required("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Policy/enforcement code must be represented."),
943
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Safety changes require targeted regression tests."),
944
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Environment/config policy can change safety behavior."),
945
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipt and audit surfaces support post-run proof."),
946
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Operator docs should reflect safety policy."),
947
+ optional("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "User-facing callbacks or flows can be affected by safety policy.")
948
+ ]
949
+ },
950
+ provider_integration: {
951
+ version: 1,
952
+ changeShape: "provider_integration",
953
+ label: "Provider integration",
954
+ description: "Provider-routing changes need gateway/provider code, call-path code, docs, and targeted tests.",
955
+ recommendedEscalation: "memgraph_depth3",
956
+ graphInput: {
957
+ intentConfidence: "strong",
958
+ graphComplexity: "medium",
959
+ connectedWorkAvailable: true,
960
+ noLiveMode: true,
961
+ networkAllowed: false,
962
+ providerCallsAllowed: false
963
+ },
964
+ rules: [
965
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Provider integration must include primary call-path code."),
966
+ required("provider_gateway", 1, COMMON_SUPPORT_EVIDENCE, "Gateway/provider routing surfaces must be present."),
967
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Provider fallback behavior needs targeted tests."),
968
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Provider integration contracts are user-facing."),
969
+ optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Exported provider contracts should be checked."),
970
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Provider options/config can control routing."),
971
+ optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Retry/error wrappers enforce provider behavior.")
972
+ ]
973
+ },
974
+ agent_handoff: {
975
+ version: 1,
976
+ changeShape: "agent_handoff",
977
+ label: "Agent handoff",
978
+ description: "Agent handoff work needs handoff contracts, docs/work packets, and preferably tests/eval reports.",
979
+ recommendedEscalation: "memgraph_depth3",
980
+ graphInput: {
981
+ intentConfidence: "strong",
982
+ graphComplexity: "medium",
983
+ connectedWorkAvailable: true,
984
+ noLiveMode: true,
985
+ networkAllowed: false,
986
+ providerCallsAllowed: false
987
+ },
988
+ rules: [
989
+ required("agent_handoff", 1, COMMON_SUPPORT_EVIDENCE, "The handoff contract or work packet must be represented."),
990
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary handoff implementation/contract code must be present."),
991
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Agent-facing docs or markdown guidance must be present."),
992
+ optional("eval_report", 1, COMMON_SUPPORT_EVIDENCE, "Eval reports help validate handoff usefulness."),
993
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipts can prove agent handoff lineage."),
994
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Handoff contracts should have targeted tests when available.")
995
+ ]
996
+ },
997
+ docs_or_migration: {
998
+ version: 1,
999
+ changeShape: "docs_or_migration",
1000
+ label: "Docs or migration",
1001
+ description: "Documentation/migration work needs user docs and migration notes, with code/tests when applicable.",
1002
+ recommendedEscalation: "connected_work_shallow",
1003
+ graphInput: {
1004
+ intentConfidence: "strong",
1005
+ graphComplexity: "shallow",
1006
+ connectedWorkAvailable: true,
1007
+ noLiveMode: true,
1008
+ networkAllowed: false,
1009
+ providerCallsAllowed: false
1010
+ },
1011
+ rules: [
1012
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-facing docs must be represented."),
1013
+ required("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes or planning docs must be represented."),
1014
+ optional("primary_code", 1, COMMON_CODE_EVIDENCE, "Related implementation code can anchor docs changes."),
1015
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Tests can validate migration guidance."),
1016
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Migration/config policy may be relevant.")
1017
+ ]
1018
+ }
1019
+ };
1020
+ // ../core/src/contextRouting/semanticSelectionSignals.ts
1021
+ var CONNECTED_SURFACE_KIND_SET = new Set(CONNECTED_SURFACE_KINDS_V1);
1022
+ // ../core/src/contextRouting/semanticGraphRouting.ts
1023
+ var PUBLIC_SURFACES = new Set(["package_exports", "user_docs"]);
1024
+ var CRITICAL_SURFACES = new Set([
1025
+ "runtime_enforcement",
1026
+ "config_policy",
1027
+ "schema_persistence",
1028
+ "receipt_audit"
1029
+ ]);
1030
+ var TOKEN_VALUE_NAMESPACES = new Set(["focus_lens", "audience", "intent", "tag", "feature_label", "risk", "context_packet"]);
1031
+ // ../core/src/codeMarket/evidenceRefinement.ts
1032
+ var SUPPORTED_KINDS = new Set([
1033
+ "command_diagnostic",
1034
+ "validation_result",
1035
+ "diff_packet",
1036
+ "pr_review_comment",
1037
+ "session_trace",
1038
+ "service_intelligence",
1039
+ "impact_prediction",
1040
+ "proof_plan",
1041
+ "stream_diagnostics",
1042
+ "ci_log",
1043
+ "review_diff",
1044
+ "session_validation",
1045
+ "agent_result",
1046
+ "run_summary"
1047
+ ]);
1048
+ // ../core/src/contextLens/relationshipTaxonomy.ts
1049
+ var CONNECTION_RELATIONSHIP_TYPE_REGISTRY = {
1050
+ related_to: { direction: "symmetric", riskLevel: "low" },
1051
+ knows: { direction: "symmetric", riskLevel: "low" },
1052
+ mentions: { direction: "symmetric", riskLevel: "low" },
1053
+ references: { direction: "symmetric", riskLevel: "low" },
1054
+ contradicts: { direction: "symmetric", riskLevel: "high" },
1055
+ owns: { direction: "directed", riskLevel: "medium" },
1056
+ owned_by: { direction: "directed", riskLevel: "medium" },
1057
+ depends_on: { direction: "directed", riskLevel: "medium" },
1058
+ implements: { direction: "directed", riskLevel: "medium" },
1059
+ documents: { direction: "directed", riskLevel: "medium" },
1060
+ calls: { direction: "directed", riskLevel: "medium" },
1061
+ imports: { direction: "directed", riskLevel: "medium" },
1062
+ affects: { direction: "directed", riskLevel: "medium" },
1063
+ affected_by: { direction: "directed", riskLevel: "medium" },
1064
+ uses: { direction: "directed", riskLevel: "medium" },
1065
+ uses_context: { direction: "directed", riskLevel: "medium" },
1066
+ supports: { direction: "directed", riskLevel: "medium" },
1067
+ tested_by: { direction: "directed", riskLevel: "medium" },
1068
+ covers: { direction: "directed", riskLevel: "medium" },
1069
+ verifies: { direction: "directed", riskLevel: "medium" },
1070
+ deploys: { direction: "directed", riskLevel: "medium" },
1071
+ configures: { direction: "directed", riskLevel: "medium" },
1072
+ publishes_to: { direction: "directed", riskLevel: "medium" },
1073
+ subscribes_to: { direction: "directed", riskLevel: "medium" },
1074
+ reads_from: { direction: "directed", riskLevel: "medium" },
1075
+ observes: { direction: "directed", riskLevel: "medium" },
1076
+ authenticates: { direction: "directed", riskLevel: "high" },
1077
+ authorizes: { direction: "directed", riskLevel: "high" },
1078
+ supersedes: { direction: "directed", riskLevel: "high" },
1079
+ source_of_truth_for: { direction: "directed", riskLevel: "high" },
1080
+ replaces: { direction: "directed", riskLevel: "high" },
1081
+ blocks: { direction: "directed", riskLevel: "high" },
1082
+ blocked_by: { direction: "directed", riskLevel: "high" },
1083
+ writes_to: { direction: "directed", riskLevel: "medium" },
1084
+ stores_in: { direction: "directed", riskLevel: "medium" },
1085
+ policy_for: { direction: "directed", riskLevel: "high" }
1086
+ };
1087
+ var CONNECTION_RELATIONSHIP_TYPES = Object.keys(CONNECTION_RELATIONSHIP_TYPE_REGISTRY);
1088
+
1089
+ // ../core/src/contextLens/serviceConnections.ts
1090
+ var SERVICE_CONNECTION_IDENTITY_SCOPES = ["logical_service", "deployment_environment"];
1091
+ var SERVICE_CONNECTION_LIFECYCLE_STATES = [
1092
+ "hint",
1093
+ "candidate",
1094
+ "verified",
1095
+ "stale",
1096
+ "rejected",
1097
+ "retracted"
1098
+ ];
1099
+ var SERVICE_CONNECTION_OBSERVATION_STATUSES = [
1100
+ "present",
1101
+ "absent_in_latest_scan",
1102
+ "changed",
1103
+ "unknown"
1104
+ ];
1105
+ var SERVICE_CONNECTION_SENSITIVITY_LEVELS = ["public", "internal", "sensitive", "secret"];
1106
+ var SERVICE_CONNECTION_RELATIONSHIP_TYPES = [
1107
+ "publishes_to",
1108
+ "subscribes_to",
1109
+ "writes_to",
1110
+ "stores_in",
1111
+ "reads_from",
1112
+ "observes",
1113
+ "blocked_by"
1114
+ ];
1115
+ var SERVICE_CONNECTION_ENDPOINT_KINDS = ["service", "resource"];
1116
+ var SERVICE_CONNECTION_SURFACE_KINDS = [
1117
+ "api",
1118
+ "queue",
1119
+ "topic",
1120
+ "stream",
1121
+ "datastore",
1122
+ "cache",
1123
+ "object_store",
1124
+ "observability_sink",
1125
+ "config",
1126
+ "secret",
1127
+ "feature_flag",
1128
+ "runtime",
1129
+ "external_service",
1130
+ "unknown"
1131
+ ];
1132
+ var SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS = [
1133
+ "code_static",
1134
+ "config_static",
1135
+ "runtime_receipt",
1136
+ "manual_report",
1137
+ "semantic_advisory"
1138
+ ];
1139
+ var SERVICE_CONNECTION_EVIDENCE_TIERS = [
1140
+ "explicit_user_action",
1141
+ "accepted_truth_candidate",
1142
+ "deterministic_code_edge",
1143
+ "receipt_backed",
1144
+ "explicit_source_language",
1145
+ "repeated_reference",
1146
+ "llm_classification",
1147
+ "co_mention",
1148
+ "vector_similarity"
1149
+ ];
1150
+ var SERVICE_CONNECTION_CANDIDATE_KINDS = [
1151
+ "http_api",
1152
+ "database",
1153
+ "auth_provider",
1154
+ "provider_client",
1155
+ "object_store",
1156
+ "queue_topic",
1157
+ "cache",
1158
+ "secret_config",
1159
+ "observability_sink",
1160
+ "runtime_owner",
1161
+ "test_proof",
1162
+ "doc_proof",
1163
+ "unknown_service_surface"
1164
+ ];
1165
+ var SERVICE_CONNECTION_DIRECTION_HINTS = [
1166
+ "inbound_api",
1167
+ "outbound_provider",
1168
+ "reads_secret",
1169
+ "reads_datastore",
1170
+ "writes_datastore",
1171
+ "publishes_queue",
1172
+ "consumes_queue",
1173
+ "reads_cache",
1174
+ "writes_cache",
1175
+ "emits_telemetry",
1176
+ "owns_runtime",
1177
+ "proves_with_test",
1178
+ "documents",
1179
+ "unknown"
1180
+ ];
1181
+ var SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS = [
1182
+ "path_only",
1183
+ "import_backed",
1184
+ "call_backed",
1185
+ "env_backed",
1186
+ "schema_backed",
1187
+ "test_backed",
1188
+ "doc_backed",
1189
+ "mixed_backed"
1190
+ ];
1191
+ var SERVICE_CONNECTION_RELATIONSHIP_TYPE_SET = new Set(SERVICE_CONNECTION_RELATIONSHIP_TYPES);
1192
+ var SERVICE_CONNECTION_ENDPOINT_KIND_SET = new Set(SERVICE_CONNECTION_ENDPOINT_KINDS);
1193
+ var SERVICE_CONNECTION_SURFACE_KIND_SET = new Set(SERVICE_CONNECTION_SURFACE_KINDS);
1194
+ var SERVICE_CONNECTION_EVIDENCE_SOURCE_KIND_SET = new Set(SERVICE_CONNECTION_EVIDENCE_SOURCE_KINDS);
1195
+ var SERVICE_CONNECTION_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_EVIDENCE_TIERS);
1196
+ var SERVICE_CONNECTION_CANDIDATE_KIND_SET = new Set(SERVICE_CONNECTION_CANDIDATE_KINDS);
1197
+ var SERVICE_CONNECTION_DIRECTION_HINT_SET = new Set(SERVICE_CONNECTION_DIRECTION_HINTS);
1198
+ var SERVICE_CONNECTION_STATIC_EVIDENCE_TIER_SET = new Set(SERVICE_CONNECTION_STATIC_EVIDENCE_TIERS);
1199
+ var SERVICE_CONNECTION_IDENTITY_SCOPE_SET = new Set(SERVICE_CONNECTION_IDENTITY_SCOPES);
1200
+ var SERVICE_CONNECTION_LIFECYCLE_STATE_SET = new Set(SERVICE_CONNECTION_LIFECYCLE_STATES);
1201
+ var SERVICE_CONNECTION_CONNECTED_WORK_STATE_SET = new Set([
1202
+ "observed",
1203
+ "usable_hint",
1204
+ "high_confidence_hint",
1205
+ "review_candidate",
1206
+ "canonical",
1207
+ "dismissed",
1208
+ "stale",
1209
+ "conflicted",
1210
+ "invalidated"
1211
+ ]);
1212
+ var SERVICE_CONNECTION_OBSERVATION_STATUS_SET = new Set(SERVICE_CONNECTION_OBSERVATION_STATUSES);
1213
+ var SERVICE_CONNECTION_SENSITIVITY_LEVEL_SET = new Set(SERVICE_CONNECTION_SENSITIVITY_LEVELS);
1214
+
1215
+ // ../core/src/codeMarket/localContextForGoal/contracts.ts
1216
+ var ROUTE_SLOT_GENERIC_TERMS = new Set(["route", "routing", "slot", "rerank", "retrieval", "graph", "memgraph", "seed", "confidence", "exact", "evidence", "implementation"]);
1217
+ var TOOL_COMPARISON_TERMS = new Set([
1218
+ "actionability",
1219
+ "absence",
1220
+ "compare",
1221
+ "comparison",
1222
+ "criterion",
1223
+ "criteria",
1224
+ "deepness",
1225
+ "evaluate",
1226
+ "exactness",
1227
+ "mcp",
1228
+ "oracle",
1229
+ "output",
1230
+ "outputs",
1231
+ "product",
1232
+ "proof",
1233
+ "repoprompt",
1234
+ "safety",
1235
+ "score",
1236
+ "scores",
1237
+ "selection",
1238
+ "selector",
1239
+ "speed",
1240
+ "tokens",
1241
+ "usefulness"
1242
+ ]);
1243
+ var TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES = [
1244
+ "apps/web/src/components/code-workroom/useCodeWorkroomState.ts",
1245
+ "apps/web/src/components/code-workroom/types.ts",
1246
+ "apps/web/src/components/code-workroom/CodeWorkroomView.tsx"
1247
+ ];
1248
+ var TEAM_BRIDGE_RELATED_UI_SURFACE_FILES = [
1249
+ "apps/web/src/components/canvas/Canvas.tsx",
1250
+ "apps/web/src/components/code-workroom/index.ts",
1251
+ "apps/web/src/components/canvas/ExpoCanvas.tsx",
1252
+ "packages/canvas/src/Canvas.tsx"
1253
+ ];
1254
+ var TEAM_BRIDGE_NEXT_SLICE_FILES = [
1255
+ ...TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES,
1256
+ "apps/web/src/components/canvas/Canvas.tsx"
1257
+ ];
1258
+ var TEAM_BRIDGE_UI_PATH_HINTS = [
1259
+ ...TEAM_BRIDGE_PRIMARY_UI_SLICE_FILES,
1260
+ ...TEAM_BRIDGE_RELATED_UI_SURFACE_FILES
1261
+ ].map((path) => path.toLowerCase());
1262
+ var TEAM_BRIDGE_PRODUCT_EXACT_PATHS = [
1263
+ "convex/code_layer/teambridge.ts",
1264
+ ...TEAM_BRIDGE_UI_PATH_HINTS
1265
+ ];
1266
+ var TEAM_BRIDGE_BACKEND_SYMBOL_HINTS = new Set([
1267
+ "buildTeamBridgeSessionState",
1268
+ "getTeamBridgeSessionState",
1269
+ "getTeamBridgeSessionStateInternal",
1270
+ "startTeamBridgeFromHandoffInternal",
1271
+ "runCodeAgentChildBridgeInternal",
1272
+ "recordToolTelemetryInternal"
1273
+ ]);
1274
+ var DOC_EXTENSIONS = new Set([".md", ".mdx"]);
1275
+ var CODE_EXTENSIONS = new Set([
1276
+ ".cjs",
1277
+ ".css",
1278
+ ".cts",
1279
+ ".dart",
1280
+ ".go",
1281
+ ".java",
1282
+ ".js",
1283
+ ".jsx",
1284
+ ".json",
1285
+ ".kt",
1286
+ ".md",
1287
+ ".mdx",
1288
+ ".mjs",
1289
+ ".mts",
1290
+ ".php",
1291
+ ".py",
1292
+ ".pyi",
1293
+ ".rb",
1294
+ ".rs",
1295
+ ".sh",
1296
+ ".sql",
1297
+ ".swift",
1298
+ ".toml",
1299
+ ".ts",
1300
+ ".tsx",
1301
+ ".yaml",
1302
+ ".yml"
1303
+ ]);
1304
+ var STOP_WORDS = new Set([
1305
+ "about",
1306
+ "after",
1307
+ "add",
1308
+ "adding",
1309
+ "advisory",
1310
+ "agent",
1311
+ "and",
1312
+ "build",
1313
+ "building",
1314
+ "can",
1315
+ "code",
1316
+ "context",
1317
+ "debugging",
1318
+ "files",
1319
+ "for",
1320
+ "from",
1321
+ "get",
1322
+ "goal",
1323
+ "have",
1324
+ "how",
1325
+ "improve",
1326
+ "into",
1327
+ "local",
1328
+ "make",
1329
+ "next",
1330
+ "only",
1331
+ "path",
1332
+ "paths",
1333
+ "plan",
1334
+ "report",
1335
+ "repo",
1336
+ "rhei",
1337
+ "safe",
1338
+ "then",
1339
+ "that",
1340
+ "the",
1341
+ "this",
1342
+ "tool",
1343
+ "use",
1344
+ "while",
1345
+ "with"
1346
+ ]);
1347
+ // ../core/src/codeMarket/workImpactOverlay.ts
1348
+ function codeMarketWorkClusterToWorkImpactOverlayV1(args) {
1349
+ const cluster = args.cluster;
1350
+ const generatedAt = args.generatedAt ?? cluster.updatedAt;
1351
+ const sourceKind = args.sourceKind ?? sourceKindFromCluster(cluster);
1352
+ const sourceRefs = uniqueRefs3(cluster.sourceRefs.length > 0 ? cluster.sourceRefs : cluster.receiptRefs);
1353
+ const sourceKey = cluster.sourceKey;
1354
+ const nodes = [];
1355
+ const edges = [];
1356
+ const sourceNode = overlayNode({
1357
+ role: "source",
1358
+ kind: "source",
1359
+ id: cluster.sourceKey,
1360
+ label: cluster.title,
1361
+ refs: sourceRefs,
1362
+ sourceKeys: cluster.sourceKeys,
1363
+ reasonCodes: unique(["source:work_cluster", ...cluster.reasonCodes]),
1364
+ metadata: cluster.metadata
1365
+ });
1366
+ nodes.push(sourceNode);
1367
+ for (const ref of cluster.changedRefs) {
1368
+ const node = overlayNode({ role: "scope", kind: "changed_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["scope:changed_ref"] });
1369
+ nodes.push(node);
1370
+ edges.push(overlayEdge({ kind: "touches", fromNodeId: sourceNode.nodeId, toNodeId: node.nodeId, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["source:touches_changed_ref"] }));
1371
+ }
1372
+ for (const ref of cluster.relatedRefs) {
1373
+ nodes.push(overlayNode({ role: "impact", kind: "impacted_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["impact:related_ref"] }));
1374
+ }
1375
+ for (const ref of cluster.evidenceRefs) {
1376
+ const node = overlayNode({ role: "evidence", kind: "evidence_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], evidenceRefs: [ref], reasonCodes: ["evidence:work_cluster_ref"] });
1377
+ nodes.push(node);
1378
+ evidencePush(nodes, edges, node, cluster.changedRefs, sourceKey);
1379
+ }
1380
+ for (const ref of cluster.receiptRefs) {
1381
+ const node = overlayNode({ role: "evidence", kind: "receipt_ref", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, ref, refs: [ref], filePaths: ref.path ? [ref.path] : [], sourceKeys: [sourceKey, ref.sourceKey], receiptRefs: [ref], reasonCodes: ["evidence:receipt_ref"] });
1382
+ nodes.push(node);
1383
+ evidencePush(nodes, edges, node, cluster.changedRefs, sourceKey);
1384
+ }
1385
+ const overlayId = stableId("work-impact-overlay", [sourceKind, cluster.stableKey]);
1386
+ return {
1387
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
1388
+ kind: "code_market_work_impact_overlay",
1389
+ overlayId,
1390
+ stableKey: overlayId,
1391
+ source: {
1392
+ kind: sourceKind,
1393
+ sourceId: cluster.sourceKey,
1394
+ label: cluster.title,
1395
+ generatedFrom: "CodeMarketWorkClusterV1",
1396
+ refs: sourceRefs,
1397
+ sourceKeys: cluster.sourceKeys
1398
+ },
1399
+ scope: {
1400
+ repoId: stringValue(cluster.selection?.repoId),
1401
+ surface: surfaceFromSourceKind(sourceKind),
1402
+ filePaths: unique(cluster.changedRefs.map((ref) => ref.path)),
1403
+ changedRefs: cluster.changedRefs,
1404
+ impactedRefs: cluster.relatedRefs,
1405
+ relatedRefs: cluster.relatedRefs,
1406
+ sourceRefs,
1407
+ evidenceRefs: cluster.evidenceRefs,
1408
+ receiptRefs: cluster.receiptRefs
1409
+ },
1410
+ status: {
1411
+ state: overlayStatusFromClusterStatus(cluster.status),
1412
+ clusterStatus: cluster.status,
1413
+ completion: cluster.completion,
1414
+ updatedAt: generatedAt,
1415
+ reasonCodes: unique([`cluster_status:${cluster.status}`, `completion:${cluster.completion}`])
1416
+ },
1417
+ nodes: dedupeNodes(nodes),
1418
+ edges: dedupeEdges(edges),
1419
+ evidence: dedupeEvidence([
1420
+ ...cluster.evidenceRefs.map((ref) => overlayEvidence({ kind: "evidence_ref", status: "used", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["evidence:work_cluster_ref"], observedAt: generatedAt })),
1421
+ ...cluster.receiptRefs.map((ref) => overlayEvidence({ kind: "receipt_ref", status: "used", id: ref.stableKey, label: ref.label ?? ref.path ?? ref.id, refs: [ref], sourceKeys: [sourceKey, ref.sourceKey], reasonCodes: ["evidence:receipt_ref"], observedAt: generatedAt }))
1422
+ ]),
1423
+ blockerNodeIds: [],
1424
+ proofNodeIds: [],
1425
+ impactNodeIds: unique(nodes.filter((node) => node.role === "impact").map((node) => node.nodeId)),
1426
+ workClusterIds: [cluster.id],
1427
+ reasonCodes: unique(["work_impact_overlay", `source:${sourceKind}`, ...cluster.reasonCodes]),
1428
+ generatedAt,
1429
+ reportOnly: true,
1430
+ advisoryOnly: true,
1431
+ noAuthority: true,
1432
+ metadata: {
1433
+ ...cluster.metadata ?? {},
1434
+ sourceClusterId: cluster.id,
1435
+ sourceClusterStableKey: cluster.stableKey,
1436
+ sourceTileIds: cluster.tileIds,
1437
+ sourceRelationshipIds: cluster.relationshipIds,
1438
+ sourceSelection: cluster.selection,
1439
+ sourceSummary: cluster.summary,
1440
+ sourceConfidence: cluster.confidence
1441
+ }
1442
+ };
1443
+ }
1444
+ function overlayNode(args) {
1445
+ const refs = uniqueRefs3([...args.ref ? [args.ref] : [], ...args.refs ?? []]);
1446
+ const stableKey = `work-impact-node:${args.kind}:${stableHash(args.id)}`;
1447
+ return {
1448
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
1449
+ nodeId: stableKey,
1450
+ stableKey,
1451
+ role: args.role,
1452
+ kind: args.kind,
1453
+ label: args.label,
1454
+ status: args.status,
1455
+ ref: args.ref,
1456
+ refs,
1457
+ filePaths: unique([...args.filePaths ?? [], ...refs.map((ref) => ref.path)]),
1458
+ sourceKeys: unique([...args.sourceKeys ?? [], ...refs.map((ref) => ref.sourceKey)]),
1459
+ evidenceRefs: uniqueRefs3(args.evidenceRefs ?? []),
1460
+ receiptRefs: uniqueRefs3(args.receiptRefs ?? []),
1461
+ reasonCodes: unique(args.reasonCodes ?? []),
1462
+ metadata: args.metadata
1463
+ };
1464
+ }
1465
+ function overlayEdge(args) {
1466
+ const stableKey = `work-impact-edge:${args.kind}:${stableHash(`${args.fromNodeId}->${args.toNodeId}`)}`;
1467
+ return {
1468
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
1469
+ edgeId: stableKey,
1470
+ stableKey,
1471
+ kind: args.kind,
1472
+ fromNodeId: args.fromNodeId,
1473
+ toNodeId: args.toNodeId,
1474
+ refs: uniqueRefs3(args.refs ?? []),
1475
+ sourceKeys: unique([...args.sourceKeys ?? [], ...(args.refs ?? []).map((ref) => ref.sourceKey)]),
1476
+ reasonCodes: unique(args.reasonCodes ?? []),
1477
+ label: args.label,
1478
+ metadata: args.metadata
1479
+ };
1480
+ }
1481
+ function overlayEvidence(args) {
1482
+ const stableKey = `work-impact-evidence:${args.kind}:${stableHash(args.id)}`;
1483
+ return {
1484
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
1485
+ evidenceId: stableKey,
1486
+ stableKey,
1487
+ kind: args.kind,
1488
+ status: args.status,
1489
+ label: args.label,
1490
+ refs: uniqueRefs3(args.refs ?? []),
1491
+ sourceKeys: unique([...args.sourceKeys ?? [], ...(args.refs ?? []).map((ref) => ref.sourceKey)]),
1492
+ reasonCodes: unique(args.reasonCodes ?? []),
1493
+ observedAt: args.observedAt,
1494
+ metadata: args.metadata
1495
+ };
1496
+ }
1497
+ function evidencePush(_nodes, edges, evidenceNode, changedRefs, sourceKey) {
1498
+ for (const changedRef of changedRefs) {
1499
+ const changedNodeId = `work-impact-node:changed_ref:${stableHash(changedRef.stableKey)}`;
1500
+ edges.push(overlayEdge({ kind: "evidences", fromNodeId: evidenceNode.nodeId, toNodeId: changedNodeId, refs: [changedRef, ...evidenceNode.refs], sourceKeys: [sourceKey, changedRef.sourceKey], reasonCodes: ["evidence:work_cluster_ref"] }));
1501
+ }
1502
+ }
1503
+ function sourceKindFromCluster(cluster) {
1504
+ const source = stringValue((cluster.metadata ?? {})["source"]);
1505
+ if (isWorkImpactSourceKind(source))
1506
+ return source;
1507
+ return "code_market";
1508
+ }
1509
+ function isWorkImpactSourceKind(value) {
1510
+ return value === "pr_review" || value === "agent_edit_session" || value === "trail_story" || value === "mcp_context" || value === "repo_intelligence" || value === "code_trail" || value === "code_market";
1511
+ }
1512
+ function surfaceFromSourceKind(sourceKind) {
1513
+ if (sourceKind === "pr_review")
1514
+ return "pr_review";
1515
+ if (sourceKind === "agent_edit_session")
1516
+ return "agent_edit_session";
1517
+ if (sourceKind === "mcp_context")
1518
+ return "mcp_context";
1519
+ if (sourceKind === "repo_intelligence")
1520
+ return "repo_intelligence";
1521
+ if (sourceKind === "trail_story" || sourceKind === "code_trail")
1522
+ return "trail_story";
1523
+ return "code_map";
1524
+ }
1525
+ function overlayStatusFromClusterStatus(status) {
1526
+ if (status === "in_progress" || status === "forming")
1527
+ return "in_progress";
1528
+ if (status === "ready_review")
1529
+ return "needs_review";
1530
+ if (status === "applied")
1531
+ return "applied";
1532
+ if (status === "stale")
1533
+ return "stale";
1534
+ return "observed";
1535
+ }
1536
+ function uniqueRefs3(refs) {
1537
+ const seen = new Set;
1538
+ const output = [];
1539
+ for (const ref of refs) {
1540
+ if (!ref?.id?.trim())
1541
+ continue;
1542
+ const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
1543
+ if (seen.has(key))
1544
+ continue;
1545
+ seen.add(key);
1546
+ output.push(ref);
1547
+ }
1548
+ return output;
1549
+ }
1550
+ function dedupeNodes(nodes) {
1551
+ const seen = new Set;
1552
+ const output = [];
1553
+ for (const node of nodes) {
1554
+ if (seen.has(node.stableKey))
1555
+ continue;
1556
+ seen.add(node.stableKey);
1557
+ output.push(node);
1558
+ }
1559
+ return output;
1560
+ }
1561
+ function dedupeEdges(edges) {
1562
+ const seen = new Set;
1563
+ const output = [];
1564
+ for (const edge of edges) {
1565
+ if (seen.has(edge.stableKey))
1566
+ continue;
1567
+ seen.add(edge.stableKey);
1568
+ output.push(edge);
1569
+ }
1570
+ return output;
1571
+ }
1572
+ function dedupeEvidence(evidence) {
1573
+ const seen = new Set;
1574
+ const output = [];
1575
+ for (const item of evidence) {
1576
+ if (seen.has(item.stableKey))
1577
+ continue;
1578
+ seen.add(item.stableKey);
1579
+ output.push(item);
1580
+ }
1581
+ return output;
1582
+ }
1583
+ function isString(value) {
1584
+ return typeof value === "string" && value.trim().length > 0;
1585
+ }
1586
+ function stringValue(value) {
1587
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
1588
+ }
1589
+ function stableId(prefix, parts) {
1590
+ return `${prefix}:${stableHash(parts.filter(isString).join("|"))}`;
1591
+ }
1592
+ function stableHash(input) {
1593
+ let hash = 2166136261;
1594
+ for (let index = 0;index < input.length; index += 1) {
1595
+ hash ^= input.charCodeAt(index);
1596
+ hash = Math.imul(hash, 16777619);
1597
+ }
1598
+ return (hash >>> 0).toString(16).padStart(8, "0");
1599
+ }
1600
+ // ../core/src/codeMarket/fixtures.ts
1601
+ var CODE_MARKET_FIXTURE_GENERATED_AT = 1779000000000;
1602
+ var CODE_MARKET_FIXTURE_PROJECT_ID = "project_code_market_fixture";
1603
+ var CODE_MARKET_FIXTURE_REPO_ID = "repo_rhei_fixture";
1604
+ var CODE_MARKET_FIXTURE_MODULE_ID = "module:packages/core/src/codeMarket";
1605
+ var codeMarketFixtureScope = {
1606
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
1607
+ repoId: CODE_MARKET_FIXTURE_REPO_ID,
1608
+ repoName: "rhei",
1609
+ surface: "pulse",
1610
+ groupBy: "directory",
1611
+ moduleDepth: 2,
1612
+ pathPrefix: "packages/core/src/codeMarket",
1613
+ focusedModuleId: CODE_MARKET_FIXTURE_MODULE_ID,
1614
+ selectedModuleIds: [CODE_MARKET_FIXTURE_MODULE_ID],
1615
+ codeScopeId: "code_scope_code_market_fixture",
1616
+ workingSetSnapshotHash: "working-set:fixture:v1",
1617
+ canvasSurfaceId: "canvas-surface:code-market-fixture",
1618
+ chatThreadId: "thread:code-market-fixture"
1619
+ };
1620
+ var codeMarketFixtureRepoRef = {
1621
+ kind: "repository",
1622
+ id: CODE_MARKET_FIXTURE_REPO_ID,
1623
+ stableKey: `repo:${CODE_MARKET_FIXTURE_REPO_ID}`,
1624
+ sourceKey: "source:code-index:repo:rhei",
1625
+ authority: "code_index",
1626
+ label: "rhei"
1627
+ };
1628
+ var codeMarketFixtureModuleRef = {
1629
+ kind: "module",
1630
+ id: CODE_MARKET_FIXTURE_MODULE_ID,
1631
+ stableKey: `module:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket`,
1632
+ sourceKey: "source:code-index:module:packages/core/src/codeMarket",
1633
+ authority: "code_index",
1634
+ label: "Code Context core",
1635
+ path: "packages/core/src/codeMarket"
1636
+ };
1637
+ var codeMarketFixtureFileRef = {
1638
+ kind: "file",
1639
+ id: "file:packages/core/src/codeMarket/selectors.ts",
1640
+ stableKey: `file:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket/selectors.ts`,
1641
+ sourceKey: "source:code-index:file:packages/core/src/codeMarket/selectors.ts",
1642
+ authority: "code_index",
1643
+ label: "selectors.ts",
1644
+ path: "packages/core/src/codeMarket/selectors.ts"
1645
+ };
1646
+ var codeMarketFixtureNodeRef = {
1647
+ kind: "code_node",
1648
+ id: "node:packages/core/src/codeMarket/selectors.ts#admitTile",
1649
+ stableKey: `node:${CODE_MARKET_FIXTURE_REPO_ID}:packages/core/src/codeMarket/selectors.ts#admitTile`,
1650
+ sourceKey: "source:code-index:node:admitTile",
1651
+ authority: "code_index",
1652
+ label: "admitTile",
1653
+ path: "packages/core/src/codeMarket/selectors.ts"
1654
+ };
1655
+ var codeMarketFixtureEdgeRef = {
1656
+ kind: "code_edge",
1657
+ id: "edge:fixtures-to-selectors",
1658
+ stableKey: `edge:${CODE_MARKET_FIXTURE_REPO_ID}:fixtures.ts->selectors.ts`,
1659
+ sourceKey: "source:code-edge:fixtures-to-selectors",
1660
+ authority: "code_edge",
1661
+ label: "fixtures imports selectors"
1662
+ };
1663
+ var codeMarketFixturePulseSignalRef = {
1664
+ kind: "pulse_signal",
1665
+ id: "pulse_signal:code-market-contract-change",
1666
+ stableKey: "pulse_signal:code-market-contract-change",
1667
+ sourceKey: "source:pulse-signal:code-market-contract-change",
1668
+ authority: "pulse_signal",
1669
+ label: "Code Context contract changed",
1670
+ metadata: { groupKey: "code-market-contract-change" }
1671
+ };
1672
+ var codeMarketFixtureReceiptRef = {
1673
+ kind: "receipt",
1674
+ id: "receipt:code-market-contract-context",
1675
+ stableKey: "receipt:code-market-contract-context",
1676
+ sourceKey: "source:receipt:code-market-contract-context",
1677
+ authority: "receipt",
1678
+ label: "Context receipt ready"
1679
+ };
1680
+ var codeMarketFixtureSources = [
1681
+ {
1682
+ key: codeMarketFixtureRepoRef.sourceKey,
1683
+ kind: "code_index",
1684
+ ref: codeMarketFixtureRepoRef,
1685
+ label: "Repository index",
1686
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 3000,
1687
+ confidence: 0.98,
1688
+ watermark: "repo-index:v1"
1689
+ },
1690
+ {
1691
+ key: codeMarketFixtureModuleRef.sourceKey,
1692
+ kind: "code_index",
1693
+ ref: codeMarketFixtureModuleRef,
1694
+ label: "Module index",
1695
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 2000,
1696
+ confidence: 0.96,
1697
+ watermark: "module-index:v1"
1698
+ },
1699
+ {
1700
+ key: codeMarketFixtureFileRef.sourceKey,
1701
+ kind: "code_index",
1702
+ ref: codeMarketFixtureFileRef,
1703
+ label: "File index",
1704
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 1500,
1705
+ confidence: 0.95,
1706
+ watermark: "file-index:v1"
1707
+ },
1708
+ {
1709
+ key: codeMarketFixtureEdgeRef.sourceKey,
1710
+ kind: "code_edge",
1711
+ ref: codeMarketFixtureEdgeRef,
1712
+ label: "Code edge index",
1713
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 1000,
1714
+ confidence: 0.9,
1715
+ watermark: "edge-index:v1"
1716
+ },
1717
+ {
1718
+ key: codeMarketFixturePulseSignalRef.sourceKey,
1719
+ kind: "pulse_signal",
1720
+ ref: codeMarketFixturePulseSignalRef,
1721
+ label: "Pulse changed-work signal",
1722
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 750,
1723
+ confidence: 0.88,
1724
+ watermark: "pulse-signal:v1"
1725
+ },
1726
+ {
1727
+ key: codeMarketFixtureReceiptRef.sourceKey,
1728
+ kind: "receipt",
1729
+ ref: codeMarketFixtureReceiptRef,
1730
+ label: "Context receipt",
1731
+ observedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 500,
1732
+ confidence: 0.84,
1733
+ watermark: "receipt:v1"
1734
+ }
1735
+ ];
1736
+ var codeMarketFixtureSelection = {
1737
+ source: "code_market",
1738
+ repoId: CODE_MARKET_FIXTURE_REPO_ID,
1739
+ filePaths: [
1740
+ "packages/core/src/codeMarket/types.ts",
1741
+ "packages/core/src/codeMarket/selectors.ts",
1742
+ "packages/core/src/codeMarket/fixtures.ts"
1743
+ ],
1744
+ nodeIds: [codeMarketFixtureNodeRef.id],
1745
+ moduleIds: [CODE_MARKET_FIXTURE_MODULE_ID],
1746
+ entityIds: ["entity:code-market-contract"],
1747
+ selectedItems: [
1748
+ {
1749
+ kind: "module",
1750
+ moduleId: CODE_MARKET_FIXTURE_MODULE_ID,
1751
+ path: "packages/core/src/codeMarket",
1752
+ label: "Code Context core",
1753
+ fileCount: 3,
1754
+ nodeCount: 1
1755
+ }
1756
+ ],
1757
+ previewFilePaths: ["packages/core/src/codeMarket/types.ts", "packages/core/src/codeMarket/selectors.ts"],
1758
+ label: "Code Context: core contract",
1759
+ warnings: []
1760
+ };
1761
+ var codeMarketFixtureRheiAction = {
1762
+ schemaVersion: 1,
1763
+ actionModelVersion: 1,
1764
+ id: "rhei-action:code-market:start-workroom",
1765
+ dedupeKey: "rhei-action:code-market:start-workroom",
1766
+ label: "Open in Workroom",
1767
+ shortLabel: "Workroom",
1768
+ description: "Open this Code Context selection in the code workroom.",
1769
+ verb: "start_workroom",
1770
+ sourceSurface: "pulse",
1771
+ targetRef: {
1772
+ kind: "code_node",
1773
+ id: codeMarketFixtureNodeRef.id,
1774
+ label: codeMarketFixtureNodeRef.label,
1775
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
1776
+ metadata: { repoId: CODE_MARKET_FIXTURE_REPO_ID }
1777
+ },
1778
+ executionPath: "workroom",
1779
+ requiredAuthority: "code_workroom",
1780
+ policyState: "enabled",
1781
+ reasonCodes: ["code_market_fixture_action"],
1782
+ evidenceRefs: [
1783
+ {
1784
+ kind: "code_file",
1785
+ id: codeMarketFixtureFileRef.id,
1786
+ label: codeMarketFixtureFileRef.label
1787
+ }
1788
+ ],
1789
+ sourceRefs: [{ kind: "code_index", id: codeMarketFixtureModuleRef.id, label: codeMarketFixtureModuleRef.label }],
1790
+ receiptRefs: [],
1791
+ privacyBoundary: "project",
1792
+ visibility: "shared_project",
1793
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
1794
+ authority: {
1795
+ required: "code_workroom",
1796
+ executionPath: "workroom",
1797
+ authorityRef: {
1798
+ kind: "repository",
1799
+ id: CODE_MARKET_FIXTURE_REPO_ID,
1800
+ label: "rhei",
1801
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID
1802
+ }
1803
+ },
1804
+ policy: {
1805
+ state: "enabled",
1806
+ requiresConfirmation: false,
1807
+ requiresTruthGate: false,
1808
+ reasonCodes: ["code_market_fixture_action"]
1809
+ },
1810
+ refs: {
1811
+ target: {
1812
+ kind: "code_node",
1813
+ id: codeMarketFixtureNodeRef.id,
1814
+ label: codeMarketFixtureNodeRef.label,
1815
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
1816
+ metadata: { repoId: CODE_MARKET_FIXTURE_REPO_ID }
1817
+ },
1818
+ evidenceRefs: [
1819
+ {
1820
+ kind: "code_file",
1821
+ id: codeMarketFixtureFileRef.id,
1822
+ label: codeMarketFixtureFileRef.label
1823
+ }
1824
+ ],
1825
+ sourceRefs: [{ kind: "code_index", id: codeMarketFixtureModuleRef.id, label: codeMarketFixtureModuleRef.label }],
1826
+ receiptRefs: [],
1827
+ sourceSignalIds: []
1828
+ },
1829
+ audit: {
1830
+ resolverVersion: "agentos-actions-v1",
1831
+ schemaVersion: 1,
1832
+ actionModelVersion: 1,
1833
+ sourceSurface: "pulse",
1834
+ groupKey: "code-market-fixture",
1835
+ generatedAt: CODE_MARKET_FIXTURE_GENERATED_AT
1836
+ },
1837
+ deterministic: {
1838
+ id: "rhei-action:code-market:start-workroom",
1839
+ dedupeKey: "rhei-action:code-market:start-workroom"
1840
+ },
1841
+ metadata: { codeMarketTileId: "tile:code-market-core" },
1842
+ sortPriority: 10
1843
+ };
1844
+ function required2(value, name) {
1845
+ if (!value)
1846
+ throw new Error(`Invalid Code Context fixture ${name}`);
1847
+ return value;
1848
+ }
1849
+ function createCodeMarketFixtureSnapshot() {
1850
+ const gap = required2(admitGap({
1851
+ id: "gap:readiness:partial-receipts",
1852
+ stableKey: "gap:readiness:partial-receipts",
1853
+ kind: "index_warming",
1854
+ severity: "info",
1855
+ title: "Receipt overlay is warming",
1856
+ detail: "The core contract can render before optional receipt overlays finish.",
1857
+ sourceKey: codeMarketFixtureRepoRef.sourceKey,
1858
+ ref: codeMarketFixtureRepoRef
1859
+ }), "gap");
1860
+ const actions = [
1861
+ required2(admitAction({
1862
+ id: "action:code-market:open-workroom",
1863
+ stableKey: "action:code-market:open-workroom",
1864
+ label: "Open in Workroom",
1865
+ shortLabel: "Workroom",
1866
+ state: "enabled",
1867
+ mode: "rheiAction",
1868
+ rheiAction: codeMarketFixtureRheiAction,
1869
+ sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
1870
+ refs: [codeMarketFixtureModuleRef, codeMarketFixtureNodeRef],
1871
+ reasonCodes: ["selection_has_code_scope"],
1872
+ sortPriority: 10
1873
+ }), "rhei action"),
1874
+ required2(admitAction({
1875
+ id: "action:code-market:pin-layout",
1876
+ stableKey: "action:code-market:pin-layout",
1877
+ label: "Pin layout",
1878
+ shortLabel: "Pin",
1879
+ state: "enabled",
1880
+ mode: "localOnly",
1881
+ localOnly: { kind: "pin_layout", targetTileId: "tile:code-market-core" },
1882
+ sourceKeys: ["source:local-state:code-market-controls"],
1883
+ refs: [codeMarketFixtureModuleRef],
1884
+ reasonCodes: ["client_local_surface_control"],
1885
+ sortPriority: 20
1886
+ }), "local action"),
1887
+ required2(admitAction({
1888
+ id: "action:code-market:assign-agent",
1889
+ stableKey: "action:code-market:assign-agent",
1890
+ label: "Assign agent",
1891
+ shortLabel: "Assign",
1892
+ state: "disabled",
1893
+ mode: "disabled",
1894
+ disabledReason: "Agent assignment authority is not available in the core contract slice.",
1895
+ sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
1896
+ refs: [codeMarketFixtureModuleRef],
1897
+ reasonCodes: ["missing_assignment_authority"],
1898
+ sortPriority: 30
1899
+ }), "disabled action")
1900
+ ];
1901
+ const tile = required2(admitTile({
1902
+ id: "tile:code-market-core",
1903
+ stableKey: "tile:repo_rhei_fixture:packages/core/src/codeMarket",
1904
+ kind: "module",
1905
+ title: "Code Context core contract",
1906
+ subtitle: "Shared DTOs, selectors, fixture, and action invariants",
1907
+ state: "review_needed",
1908
+ confidence: 0.92,
1909
+ controlWeight: 7.25,
1910
+ refs: [codeMarketFixtureModuleRef, codeMarketFixtureFileRef, codeMarketFixtureNodeRef],
1911
+ sourceKeys: [codeMarketFixtureRepoRef.sourceKey],
1912
+ reasonCodes: ["deterministic_module_ref", "selection_has_file_and_node_payload"],
1913
+ selection: codeMarketFixtureSelection,
1914
+ gaps: [gap],
1915
+ actions,
1916
+ metadata: { fixture: true }
1917
+ }), "tile");
1918
+ const relationship = required2(admitRelationship({
1919
+ id: "relationship:fixtures-import-selectors",
1920
+ stableKey: codeMarketFixtureEdgeRef.stableKey,
1921
+ kind: "imports",
1922
+ sourceRef: codeMarketFixtureFileRef,
1923
+ targetRef: codeMarketFixtureNodeRef,
1924
+ sourceKeys: [codeMarketFixtureEdgeRef.sourceKey],
1925
+ label: "Fixture exercises selector admission",
1926
+ strength: 0.86,
1927
+ reasonCodes: ["source_backed_code_edge"]
1928
+ }), "relationship");
1929
+ const workCluster = required2(admitWorkCluster({
1930
+ id: "work-cluster:code-market-contract-change",
1931
+ stableKey: "work-cluster:repo_rhei_fixture:code-market-contract-change",
1932
+ sourceKey: codeMarketFixturePulseSignalRef.sourceKey,
1933
+ sourceKeys: [codeMarketFixtureModuleRef.sourceKey, codeMarketFixtureReceiptRef.sourceKey],
1934
+ title: "Code Context contract work cluster",
1935
+ summary: "Changed core Code Context contract files are grouped for review and handoff.",
1936
+ status: "ready_review",
1937
+ completion: "partial",
1938
+ changedRefs: [codeMarketFixtureFileRef],
1939
+ relatedRefs: [codeMarketFixtureModuleRef, codeMarketFixtureNodeRef],
1940
+ sourceRefs: [codeMarketFixturePulseSignalRef, codeMarketFixtureModuleRef],
1941
+ evidenceRefs: [codeMarketFixtureFileRef, codeMarketFixtureNodeRef],
1942
+ receiptRefs: [codeMarketFixtureReceiptRef],
1943
+ tileIds: [tile.id],
1944
+ relationshipIds: [relationship.id],
1945
+ reasonCodes: ["source_backed_changed_work", "selection_has_file_and_node_payload"],
1946
+ confidence: 0.88,
1947
+ updatedAt: CODE_MARKET_FIXTURE_GENERATED_AT - 250,
1948
+ selection: codeMarketFixtureSelection,
1949
+ metadata: { fixture: true }
1950
+ }), "work cluster");
1951
+ const sector = required2(admitSector({
1952
+ id: "sector:code-market-contract",
1953
+ stableKey: "sector:code-market-contract",
1954
+ title: "Contract surface",
1955
+ sourceKeys: [codeMarketFixtureModuleRef.sourceKey],
1956
+ tileIds: [tile.id],
1957
+ sortOrder: 1
1958
+ }), "sector");
1959
+ const gaps = [gap];
1960
+ const tiles = [tile];
1961
+ const workClusters = [workCluster];
1962
+ return {
1963
+ schemaVersion: CODE_MARKET_SCHEMA_VERSION,
1964
+ readModelVersion: CODE_MARKET_READ_MODEL_VERSION,
1965
+ modelVersion: CODE_MARKET_MODEL_VERSION,
1966
+ projectId: CODE_MARKET_FIXTURE_PROJECT_ID,
1967
+ generatedAt: CODE_MARKET_FIXTURE_GENERATED_AT,
1968
+ scope: codeMarketFixtureScope,
1969
+ readiness: {
1970
+ state: "partial",
1971
+ title: "Code Context fixture is source-backed",
1972
+ detail: "Core contract is ready; optional overlays are represented as gaps.",
1973
+ reasonCodes: ["fixture_partial_overlay"]
1974
+ },
1975
+ sectors: [sector],
1976
+ tiles,
1977
+ workClusters,
1978
+ relationships: [relationship],
1979
+ gaps,
1980
+ sources: codeMarketFixtureSources,
1981
+ selections: [codeMarketFixtureSelection],
1982
+ sourceWatermarks: codeMarketFixtureSources.map((source) => ({
1983
+ sourceKey: source.key,
1984
+ kind: source.kind,
1985
+ complete: true,
1986
+ updatedAt: source.observedAt,
1987
+ cursor: source.watermark
1988
+ })),
1989
+ truncation: [
1990
+ {
1991
+ sourceKey: codeMarketFixtureModuleRef.sourceKey,
1992
+ limit: 50,
1993
+ returned: 1,
1994
+ truncated: false
1995
+ }
1996
+ ]
1997
+ };
1998
+ }
1999
+ var codeMarketFixtureSnapshot = createCodeMarketFixtureSnapshot();
2000
+ // ../core/src/codeTrail/codeMarketAdapter.ts
2001
+ var REF_KIND_MAP = {
2002
+ repository: "repository",
2003
+ file: "file",
2004
+ code_node: "code_node",
2005
+ context_receipt: "receipt",
2006
+ sync_receipt: "receipt",
2007
+ plan_contract: "plan_contract",
2008
+ session: "code_session",
2009
+ code_workroom_run: "code_workroom_run",
2010
+ code_patch_run: "code_patch_run",
2011
+ agent_edit_session: "agent_edit_session",
2012
+ code_write_proposal: "local_state",
2013
+ evidence_job: "evidence_job",
2014
+ truth_candidate: "truth_candidate",
2015
+ mcp_context_run: "local_state",
2016
+ mcp_run_graph: "local_state",
2017
+ trail_import: "local_state",
2018
+ code_change_story: "code_change_story",
2019
+ pr_snapshot: "pr_snapshot",
2020
+ review_room: "review_room",
2021
+ capability_run: "local_state"
2022
+ };
2023
+ var REF_AUTHORITY_MAP = {
2024
+ repository: "code_index",
2025
+ file: "code_index",
2026
+ code_node: "code_index",
2027
+ receipt: "receipt",
2028
+ plan_contract: "plan_contract",
2029
+ code_session: "code_session",
2030
+ code_workroom_run: "code_workroom_run",
2031
+ code_patch_run: "code_patch_run",
2032
+ agent_edit_session: "agent_edit_session",
2033
+ evidence_job: "evidence_job",
2034
+ truth_candidate: "truth_candidate",
2035
+ pr_snapshot: "pr_review",
2036
+ review_room: "pr_review",
2037
+ code_change_story: "trail_story",
2038
+ local_state: "local_only"
2039
+ };
2040
+ var SOURCE_KIND_MAP = {
2041
+ workroom_ledger: "code_session",
2042
+ code_context_receipt: "receipt",
2043
+ sync_receipt: "receipt",
2044
+ plan_contract: "plan_contract",
2045
+ workroom_run: "code_workroom_run",
2046
+ workroom_event: "code_workroom_run",
2047
+ patch_run: "code_patch_run",
2048
+ patch_file_diff: "code_patch_run",
2049
+ evidence_job: "evidence_job",
2050
+ truth_candidate: "truth_candidate",
2051
+ agent_edit_session: "agent_edit_session",
2052
+ code_write_proposal: "agent_edit_session",
2053
+ capability_run: "capability_run",
2054
+ trail_import: "local_state",
2055
+ local_mcp_context_run: "local_state",
2056
+ local_mcp_run_graph: "local_state",
2057
+ code_story: "trail_story",
2058
+ pr_review: "pr_review",
2059
+ code_market: "local_state"
2060
+ };
2061
+ var GAP_KIND_MAP = {
2062
+ source_unavailable: "source_unavailable",
2063
+ missing_source_row: "source_unavailable",
2064
+ permission_filtered: "permission_filtered",
2065
+ truncated_source: "truncated_source",
2066
+ unresolved_reference: "source_unavailable",
2067
+ local_history_unavailable: "source_unavailable",
2068
+ diff_unavailable: "source_unavailable"
2069
+ };
2070
+ var WORKROOM_LEDGER_ENTRY_KINDS = new Set([
2071
+ "workroom_run",
2072
+ "context_receipt",
2073
+ "plan_contract",
2074
+ "patch_run",
2075
+ "evidence_job",
2076
+ "truth_candidate"
2077
+ ]);
2078
+ var LIFECYCLE_WORK_ENTRY_KINDS = new Set([
2079
+ "context_receipt",
2080
+ "validation_receipt",
2081
+ "diagnostic_edit_trace",
2082
+ "agent_edit_session",
2083
+ "observation"
2084
+ ]);
2085
+ function codeTrailStatusToCodeMarketWorkClusterStatus(status) {
2086
+ if (["queued", "running", "waiting"].includes(status))
2087
+ return "in_progress";
2088
+ if (["ready", "review_needed", "blocked", "failed"].includes(status))
2089
+ return "ready_review";
2090
+ if (["succeeded", "completed", "approved", "canonical"].includes(status))
2091
+ return "applied";
2092
+ if (["aborted", "superseded", "rejected"].includes(status))
2093
+ return "stale";
2094
+ return "observed";
2095
+ }
2096
+ function codeTrailEntryToCodeMarketCompletion(entry) {
2097
+ if (entry.entryKind === "truth_candidate" && ["approved", "canonical"].includes(entry.status)) {
2098
+ return "done_by_review";
2099
+ }
2100
+ if (["context_receipt", "workroom_run"].includes(entry.entryKind) && ["ready", "succeeded", "completed"].includes(entry.status)) {
2101
+ return "done_by_receipt";
2102
+ }
2103
+ if (entry.entryKind === "patch_run" && ["succeeded", "completed", "approved"].includes(entry.status)) {
2104
+ return "likely_done";
2105
+ }
2106
+ if (["queued", "running", "waiting", "ready", "review_needed"].includes(entry.status)) {
2107
+ return "partial";
2108
+ }
2109
+ return "unknown";
2110
+ }
2111
+ function codeTrailRefToCodeMarketRef(ref) {
2112
+ const kind = REF_KIND_MAP[ref.kind] ?? "local_state";
2113
+ return {
2114
+ kind,
2115
+ id: ref.id,
2116
+ stableKey: ref.stableKey,
2117
+ sourceKey: ref.sourceKey,
2118
+ authority: REF_AUTHORITY_MAP[kind] ?? "local_only",
2119
+ label: ref.label,
2120
+ path: ref.path,
2121
+ href: ref.href,
2122
+ metadata: ref.metadata
2123
+ };
2124
+ }
2125
+ function codeTrailSourceToCodeMarketSource(source) {
2126
+ return {
2127
+ key: source.key,
2128
+ kind: SOURCE_KIND_MAP[source.kind] ?? "local_state",
2129
+ ref: source.ref ? codeTrailRefToCodeMarketRef(source.ref) : undefined,
2130
+ label: source.label,
2131
+ observedAt: source.observedAt,
2132
+ confidence: source.confidence,
2133
+ watermark: source.watermark
2134
+ };
2135
+ }
2136
+ function codeTrailGapToCodeMarketGap(gap) {
2137
+ return admitGap({
2138
+ id: `gap:code-trail:${gap.id}`,
2139
+ stableKey: `gap:code-trail:${gap.stableKey}`,
2140
+ kind: GAP_KIND_MAP[gap.kind] ?? "source_unavailable",
2141
+ severity: gap.severity,
2142
+ title: gap.title,
2143
+ detail: gap.detail,
2144
+ sourceKey: gap.sourceKey,
2145
+ ref: gap.ref ? codeTrailRefToCodeMarketRef(gap.ref) : undefined
2146
+ });
2147
+ }
2148
+ function codeTrailEntriesToCodeMarketWorkImpactOverlays(entries) {
2149
+ return codeTrailEntriesToCodeMarketWorkClusters(entries).map((cluster) => codeMarketWorkClusterToWorkImpactOverlayV1({
2150
+ cluster,
2151
+ sourceKind: cluster.reasonCodes.some((code) => code.includes("pr_review")) ? "pr_review" : "code_trail",
2152
+ generatedAt: cluster.updatedAt
2153
+ }));
2154
+ }
2155
+ function codeTrailEntriesToCodeMarketWorkClusters(entries) {
2156
+ const groups = buildWorkroomGroupMaps(entries);
2157
+ const drafts = new Map;
2158
+ for (const entry of entries) {
2159
+ if (!WORKROOM_LEDGER_ENTRY_KINDS.has(entry.entryKind) && !isLifecycleWorkEntry(entry))
2160
+ continue;
2161
+ const sourceKey = codeTrailEntryClusterSourceKey(entry, groups);
2162
+ upsertDraft(drafts, entryToDraft(entry, sourceKey));
2163
+ }
2164
+ return Array.from(drafts.values()).map((draft) => admitWorkCluster({
2165
+ id: `work-cluster:${draft.sourceKey}`,
2166
+ stableKey: `work-cluster:${draft.sourceKey}`,
2167
+ sourceKey: draft.sourceKey,
2168
+ sourceKeys: draft.sourceKeys,
2169
+ title: draft.title,
2170
+ summary: draft.summary,
2171
+ status: draft.status,
2172
+ completion: draft.completion,
2173
+ changedRefs: draft.changedRefs,
2174
+ relatedRefs: draft.relatedRefs,
2175
+ sourceRefs: draft.sourceRefs,
2176
+ evidenceRefs: draft.evidenceRefs,
2177
+ receiptRefs: draft.receiptRefs,
2178
+ reasonCodes: draft.reasonCodes,
2179
+ confidence: draft.confidence,
2180
+ updatedAt: draft.updatedAt,
2181
+ metadata: draft.metadata
2182
+ })).filter((cluster) => cluster !== null);
2183
+ }
2184
+ function isLifecycleWorkEntry(entry) {
2185
+ return LIFECYCLE_WORK_ENTRY_KINDS.has(entry.entryKind) && entry.reasonCodes.some((code) => code.startsWith("goal_lifecycle:"));
2186
+ }
2187
+ function buildWorkroomGroupMaps(entries) {
2188
+ const receiptToGroup = new Map;
2189
+ const planToGroup = new Map;
2190
+ const patchToGroup = new Map;
2191
+ const truthToGroup = new Map;
2192
+ const workroomRunToGroup = new Map;
2193
+ for (const entry of entries) {
2194
+ if (entry.primaryRef.kind === "session") {
2195
+ workroomRunToGroup.set(entry.primaryRef.id, codeSessionClusterSourceKey(entry.primaryRef.id));
2196
+ }
2197
+ if (entry.primaryRef.kind === "code_workroom_run") {
2198
+ const sessionRef = entry.inputRefs.find((ref) => ref.kind === "session");
2199
+ workroomRunToGroup.set(entry.primaryRef.id, sessionRef ? codeSessionClusterSourceKey(sessionRef.id) : codeWorkroomRunClusterSourceKey(entry.primaryRef.id));
2200
+ }
2201
+ }
2202
+ for (const entry of entries) {
2203
+ if (entry.entryKind !== "context_receipt")
2204
+ continue;
2205
+ const sessionRef = entry.inputRefs.find((ref) => ref.kind === "session");
2206
+ if (sessionRef)
2207
+ receiptToGroup.set(entry.primaryRef.id, codeSessionClusterSourceKey(sessionRef.id));
2208
+ }
2209
+ for (const entry of entries) {
2210
+ if (entry.entryKind !== "plan_contract")
2211
+ continue;
2212
+ const receiptRef = entry.inputRefs.find((ref) => ref.kind === "context_receipt") ?? entry.receiptRefs.find((ref) => ref.kind === "context_receipt");
2213
+ if (receiptRef && receiptToGroup.has(receiptRef.id))
2214
+ planToGroup.set(entry.primaryRef.id, receiptToGroup.get(receiptRef.id));
2215
+ }
2216
+ for (const entry of entries) {
2217
+ if (entry.entryKind !== "patch_run")
2218
+ continue;
2219
+ const sessionId = metadataString(entry.metadata, "workroomSessionId");
2220
+ const workroomRunRef = entry.inputRefs.find((ref) => ref.kind === "code_workroom_run");
2221
+ const planRef = entry.inputRefs.find((ref) => ref.kind === "plan_contract");
2222
+ const group = sessionId ? codeSessionClusterSourceKey(sessionId) : workroomRunRef && workroomRunToGroup.has(workroomRunRef.id) ? workroomRunToGroup.get(workroomRunRef.id) : planRef && planToGroup.has(planRef.id) ? planToGroup.get(planRef.id) : codePatchRunClusterSourceKey(entry.primaryRef.id);
2223
+ if (group)
2224
+ patchToGroup.set(entry.primaryRef.id, group);
2225
+ }
2226
+ for (const entry of entries) {
2227
+ if (entry.entryKind !== "truth_candidate")
2228
+ continue;
2229
+ const patchRef = entry.inputRefs.find((ref) => ref.kind === "code_patch_run") ?? entry.relatedRefs.find((ref) => ref.kind === "code_patch_run");
2230
+ if (patchRef && patchToGroup.has(patchRef.id))
2231
+ truthToGroup.set(entry.primaryRef.id, patchToGroup.get(patchRef.id));
2232
+ }
2233
+ return { receiptToGroup, planToGroup, patchToGroup, truthToGroup, workroomRunToGroup };
2234
+ }
2235
+ function codeTrailEntryClusterSourceKey(entry, groups) {
2236
+ if (entry.primaryRef.kind === "session")
2237
+ return codeSessionClusterSourceKey(entry.primaryRef.id);
2238
+ if (entry.primaryRef.kind === "code_workroom_run")
2239
+ return groups.workroomRunToGroup.get(entry.primaryRef.id) ?? codeWorkroomRunClusterSourceKey(entry.primaryRef.id);
2240
+ if (entry.entryKind === "context_receipt")
2241
+ return groups.receiptToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
2242
+ if (entry.entryKind === "plan_contract")
2243
+ return groups.planToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
2244
+ if (entry.entryKind === "patch_run")
2245
+ return groups.patchToGroup.get(entry.primaryRef.id) ?? codePatchRunClusterSourceKey(entry.primaryRef.id);
2246
+ if (entry.entryKind === "truth_candidate")
2247
+ return groups.truthToGroup.get(entry.primaryRef.id) ?? entry.sourceKey;
2248
+ if (entry.entryKind === "evidence_job") {
2249
+ const patchRef = entry.inputRefs.find((ref) => ref.kind === "code_patch_run");
2250
+ if (patchRef && groups.patchToGroup.has(patchRef.id))
2251
+ return groups.patchToGroup.get(patchRef.id);
2252
+ const truthRef = entry.inputRefs.find((ref) => ref.kind === "truth_candidate");
2253
+ if (truthRef && groups.truthToGroup.has(truthRef.id))
2254
+ return groups.truthToGroup.get(truthRef.id);
2255
+ const workroomRunRef = entry.inputRefs.find((ref) => ref.kind === "code_workroom_run");
2256
+ if (workroomRunRef && groups.workroomRunToGroup.has(workroomRunRef.id))
2257
+ return groups.workroomRunToGroup.get(workroomRunRef.id);
2258
+ }
2259
+ return entry.sourceKey;
2260
+ }
2261
+ function entryToDraft(entry, sourceKey) {
2262
+ const sourceRefs = uniqueRefs5([entry.primaryRef, ...entry.sourceRefs].map(codeTrailRefToCodeMarketRef));
2263
+ const changedRefs = uniqueRefs5(entry.outputRefs.map(codeTrailRefToCodeMarketRef));
2264
+ const relatedRefs = uniqueRefs5([...entry.relatedRefs, ...entry.inputRefs].map(codeTrailRefToCodeMarketRef));
2265
+ const evidenceRefs = uniqueRefs5([
2266
+ ...entry.entryKind === "truth_candidate" || entry.entryKind === "evidence_job" ? [entry.primaryRef] : [],
2267
+ ...entry.evidenceRefs
2268
+ ].map(codeTrailRefToCodeMarketRef));
2269
+ const receiptRefs = uniqueRefs5([
2270
+ ...entry.entryKind === "context_receipt" ? [entry.primaryRef] : [],
2271
+ ...entry.receiptRefs
2272
+ ].map(codeTrailRefToCodeMarketRef));
2273
+ return {
2274
+ sourceKey,
2275
+ title: entry.title ?? entry.primaryRef.label ?? "Code Trail entry",
2276
+ summary: entry.summary,
2277
+ status: codeTrailStatusToCodeMarketWorkClusterStatus(entry.status),
2278
+ completion: codeTrailEntryToCodeMarketCompletion(entry),
2279
+ changedRefs,
2280
+ relatedRefs,
2281
+ sourceRefs,
2282
+ evidenceRefs,
2283
+ receiptRefs,
2284
+ sourceKeys: unique([sourceKey, ...entry.sourceKeys, ...sourceRefs.map((ref) => ref.sourceKey), ...changedRefs.map((ref) => ref.sourceKey), ...evidenceRefs.map((ref) => ref.sourceKey), ...receiptRefs.map((ref) => ref.sourceKey)]),
2285
+ reasonCodes: unique(["code_trail_work_cluster", ...entry.reasonCodes]),
2286
+ confidence: 0.8,
2287
+ updatedAt: entry.updatedAt ?? entry.completedAt ?? entry.startedAt ?? entry.createdAt ?? 0,
2288
+ metadata: {
2289
+ source: "code_trail",
2290
+ trailEntryIds: [entry.id],
2291
+ trailStableKeys: [entry.stableKey],
2292
+ trailPhases: [entry.phase]
2293
+ }
2294
+ };
2295
+ }
2296
+ function upsertDraft(drafts, next) {
2297
+ const current = drafts.get(next.sourceKey);
2298
+ if (!current) {
2299
+ drafts.set(next.sourceKey, next);
2300
+ return;
2301
+ }
2302
+ drafts.set(next.sourceKey, {
2303
+ ...current,
2304
+ title: preferredTitle(current, next),
2305
+ summary: current.summary ?? next.summary,
2306
+ status: strongerStatus(current.status, next.status),
2307
+ completion: strongerCompletion(current.completion, next.completion),
2308
+ changedRefs: uniqueRefs5([...current.changedRefs, ...next.changedRefs]),
2309
+ relatedRefs: uniqueRefs5([...current.relatedRefs, ...next.relatedRefs]),
2310
+ sourceRefs: uniqueRefs5([...current.sourceRefs, ...next.sourceRefs]),
2311
+ evidenceRefs: uniqueRefs5([...current.evidenceRefs, ...next.evidenceRefs]),
2312
+ receiptRefs: uniqueRefs5([...current.receiptRefs, ...next.receiptRefs]),
2313
+ sourceKeys: unique([...current.sourceKeys, ...next.sourceKeys]),
2314
+ reasonCodes: unique([...current.reasonCodes, ...next.reasonCodes]),
2315
+ confidence: Math.max(current.confidence, next.confidence),
2316
+ updatedAt: Math.max(current.updatedAt, next.updatedAt),
2317
+ metadata: {
2318
+ ...current.metadata,
2319
+ ...next.metadata,
2320
+ trailEntryIds: unique([...asStringArray(current.metadata["trailEntryIds"]), ...asStringArray(next.metadata["trailEntryIds"])]),
2321
+ trailStableKeys: unique([...asStringArray(current.metadata["trailStableKeys"]), ...asStringArray(next.metadata["trailStableKeys"])]),
2322
+ trailPhases: unique([...asStringArray(current.metadata["trailPhases"]), ...asStringArray(next.metadata["trailPhases"])])
2323
+ }
2324
+ });
2325
+ }
2326
+ function preferredTitle(current, next) {
2327
+ if (next.reasonCodes.some((code) => code.includes("patch_run")) && !current.reasonCodes.some((code) => code.includes("patch_run")))
2328
+ return next.title;
2329
+ return current.title || next.title;
2330
+ }
2331
+ function strongerStatus(a, b) {
2332
+ const order = ["observed", "forming", "in_progress", "ready_review", "applied", "stale"];
2333
+ return order.indexOf(b) > order.indexOf(a) ? b : a;
2334
+ }
2335
+ function strongerCompletion(a, b) {
2336
+ const order = ["unknown", "partial", "likely_done", "done_by_receipt", "done_by_review"];
2337
+ return order.indexOf(b) > order.indexOf(a) ? b : a;
2338
+ }
2339
+ function uniqueRefs5(refs) {
2340
+ const seen = new Set;
2341
+ const output = [];
2342
+ for (const ref of refs) {
2343
+ const key = `${ref.kind}:${ref.stableKey}:${ref.sourceKey}`;
2344
+ if (seen.has(key))
2345
+ continue;
2346
+ seen.add(key);
2347
+ output.push(ref);
2348
+ }
2349
+ return output;
2350
+ }
2351
+ function metadataString(metadata, key) {
2352
+ const value = metadata?.[key];
2353
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
2354
+ }
2355
+ function asStringArray(value) {
2356
+ return Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
2357
+ }
2358
+ function codeSessionClusterSourceKey(sessionId) {
2359
+ return `source:code_session:${cleanPart(sessionId)}`;
2360
+ }
2361
+ function codeWorkroomRunClusterSourceKey(runId) {
2362
+ return `source:code_workroom_run:${cleanPart(runId)}`;
2363
+ }
2364
+ function codePatchRunClusterSourceKey(patchRunId) {
2365
+ return `source:code_patch_run:${cleanPart(patchRunId)}`;
2366
+ }
2367
+ function cleanPart(value) {
2368
+ return String(value ?? "").trim().replace(/\s+/g, "-").replace(/[^a-zA-Z0-9._:/#-]/g, "_");
2369
+ }
2370
+ // ../core/src/codeTrail/receiptTargets.ts
2371
+ function buildCodeTrailReceiptTargetV1(args) {
2372
+ const refs = normalizeRefs([
2373
+ ...args.refs ?? [],
2374
+ args.sourceKind && args.sourceId ? { kind: args.sourceKind, id: args.sourceId } : undefined
2375
+ ]);
2376
+ const explicitHref = firstSafeTrailHref([
2377
+ args.href,
2378
+ ...refs.map((ref) => ref.href),
2379
+ stringFromMetadata(args.metadata, "href"),
2380
+ stringFromMetadata(args.metadata, "route"),
2381
+ stringFromMetadata(args.metadata, "deepLink")
2382
+ ]);
2383
+ const params = explicitHref ? paramsFromHref(explicitHref) : new URLSearchParams;
2384
+ const projectId = cleanString2(args.projectId) ?? params.get("projectId") ?? projectIdFromRefs(refs);
2385
+ if (!projectId)
2386
+ return null;
2387
+ setParam(params, "projectId", projectId, true);
2388
+ setParam(params, "repoId", cleanString2(args.repoId));
2389
+ for (const ref of refs) {
2390
+ mapRefToTrailParams(params, ref);
2391
+ }
2392
+ const targetKind = args.targetKind ?? inferTargetKind(refs, explicitHref);
2393
+ const scope = buildScopeFromParams(params, targetKind);
2394
+ return {
2395
+ schemaVersion: 1,
2396
+ kind: "code_trail_receipt_target",
2397
+ targetKind,
2398
+ href: `/trail?${params.toString()}`,
2399
+ scope,
2400
+ params: Object.fromEntries(params.entries()),
2401
+ refs,
2402
+ fanout: buildFanout(params, targetKind),
2403
+ reasonCodes: uniqueStrings2([
2404
+ "trail_target:safe_internal_scope",
2405
+ explicitHref ? "trail_target:explicit_href_sanitized" : undefined,
2406
+ refs.length > 0 ? "trail_target:refs_mapped" : "trail_target:project_scope_only",
2407
+ `trail_target:fanout_${fanoutLaneForTargetKind(targetKind)}`,
2408
+ "authority:no_navigation_side_effects"
2409
+ ]),
2410
+ reportOnly: true,
2411
+ advisoryOnly: true,
2412
+ noAuthority: true
2413
+ };
2414
+ }
2415
+ function normalizeRefs(refs) {
2416
+ const output = [];
2417
+ const seen = new Set;
2418
+ for (const ref of refs) {
2419
+ const kind = cleanString2(ref?.kind);
2420
+ const id = cleanString2(ref?.id);
2421
+ const href = cleanString2(ref?.href);
2422
+ if (!kind && !id && !href)
2423
+ continue;
2424
+ const normalized = {
2425
+ kind,
2426
+ id,
2427
+ label: cleanString2(ref?.label),
2428
+ path: cleanString2(ref?.path),
2429
+ href,
2430
+ metadata: ref?.metadata
2431
+ };
2432
+ const key = `${normalized.kind ?? "ref"}:${normalized.id ?? normalized.href ?? ""}:${normalized.path ?? ""}`;
2433
+ if (seen.has(key))
2434
+ continue;
2435
+ seen.add(key);
2436
+ output.push(normalized);
2437
+ }
2438
+ return output;
2439
+ }
2440
+ function mapRefToTrailParams(params, ref) {
2441
+ const kind = normalizeKind(ref.kind);
2442
+ const id = cleanString2(ref.id);
2443
+ if (!id)
2444
+ return;
2445
+ switch (kind) {
2446
+ case "code_session":
2447
+ case "code_task_session":
2448
+ case "session":
2449
+ setParam(params, "sessionId", id);
2450
+ return;
2451
+ case "code_workroom_run":
2452
+ case "workroom_run":
2453
+ setParam(params, "workroomRunId", id);
2454
+ return;
2455
+ case "agent_run":
2456
+ setParam(params, "agentRunId", id);
2457
+ return;
2458
+ case "agent_run_node":
2459
+ setParam(params, "agentRunNodeId", id);
2460
+ return;
2461
+ case "code_patch_run":
2462
+ case "patch_run":
2463
+ setParam(params, "patchRunId", id);
2464
+ return;
2465
+ case "agent_edit_session":
2466
+ case "edit_session":
2467
+ setParam(params, "editSessionId", id);
2468
+ return;
2469
+ case "agent_edit_session_row":
2470
+ case "edit_session_row":
2471
+ setParam(params, "editSessionRowId", id);
2472
+ return;
2473
+ case "truth_candidate":
2474
+ setParam(params, "truthCandidateId", id);
2475
+ return;
2476
+ case "capability_run":
2477
+ setParam(params, "capabilityRunId", id);
2478
+ return;
2479
+ case "receipt":
2480
+ case "code_context_receipt":
2481
+ case "context_receipt":
2482
+ setParam(params, "receiptId", id);
2483
+ return;
2484
+ case "artifact":
2485
+ setParam(params, "artifactId", id);
2486
+ return;
2487
+ case "evidence_job":
2488
+ case "connection_evidence":
2489
+ setParam(params, "evidenceJobId", id);
2490
+ return;
2491
+ case "code_node":
2492
+ setParam(params, "codeNodeId", id);
2493
+ if (ref.path)
2494
+ setParam(params, "filePath", ref.path);
2495
+ return;
2496
+ case "pulse_signal":
2497
+ case "pulse_evidence":
2498
+ setParam(params, "pulseSignalId", id);
2499
+ return;
2500
+ case "code_market":
2501
+ case "code_market_snapshot":
2502
+ setParam(params, "codeMarketSnapshotId", id);
2503
+ return;
2504
+ case "mcp_run":
2505
+ case "mcp_context_run":
2506
+ case "local_mcp_context_run":
2507
+ setParam(params, "mcpContextRunId", id);
2508
+ return;
2509
+ case "mcp_run_graph":
2510
+ case "local_mcp_run_graph":
2511
+ setParam(params, "sourceMcpRunId", id);
2512
+ return;
2513
+ case "pr_report":
2514
+ case "pr_review":
2515
+ case "pr_snapshot":
2516
+ setParam(params, "prSnapshotId", id);
2517
+ return;
2518
+ case "pr_review_story":
2519
+ case "code_change_story":
2520
+ case "story":
2521
+ setParam(params, "storyId", id);
2522
+ return;
2523
+ case "review_room":
2524
+ setParam(params, "reviewRoomId", id);
2525
+ return;
2526
+ case "trail_import":
2527
+ setParam(params, "importId", id);
2528
+ return;
2529
+ case "file":
2530
+ setParam(params, "filePath", ref.path ?? id);
2531
+ return;
2532
+ default:
2533
+ if (kind.endsWith("_receipt"))
2534
+ setParam(params, "receiptId", id);
2535
+ return;
2536
+ }
2537
+ }
2538
+ function buildScopeFromParams(params, targetKind) {
2539
+ return {
2540
+ projectId: params.get("projectId") ?? "",
2541
+ repoId: params.get("repoId") ?? undefined,
2542
+ sessionId: params.get("sessionId") ?? undefined,
2543
+ workroomRunId: params.get("workroomRunId") ?? undefined,
2544
+ patchRunId: params.get("patchRunId") ?? undefined,
2545
+ editSessionId: params.get("editSessionId") ?? undefined,
2546
+ editSessionRowId: params.get("editSessionRowId") ?? undefined,
2547
+ truthCandidateId: params.get("truthCandidateId") ?? undefined,
2548
+ capabilityRunId: params.get("capabilityRunId") ?? undefined,
2549
+ importId: params.get("importId") ?? undefined,
2550
+ trailHash: params.get("trailHash") ?? undefined,
2551
+ receiptId: params.get("receiptId") ?? undefined,
2552
+ artifactId: params.get("artifactId") ?? undefined,
2553
+ codeMarketSnapshotId: params.get("codeMarketSnapshotId") ?? undefined,
2554
+ mcpContextRunId: params.get("mcpContextRunId") ?? undefined,
2555
+ sourceMcpRequestId: params.get("sourceMcpRequestId") ?? undefined,
2556
+ sourceMcpRunId: params.get("sourceMcpRunId") ?? undefined,
2557
+ agentRunId: params.get("agentRunId") ?? undefined,
2558
+ agentRunNodeId: params.get("agentRunNodeId") ?? undefined,
2559
+ evidenceJobId: params.get("evidenceJobId") ?? undefined,
2560
+ codeNodeId: params.get("codeNodeId") ?? undefined,
2561
+ pulseSignalId: params.get("pulseSignalId") ?? undefined,
2562
+ prSnapshotId: params.get("prSnapshotId") ?? undefined,
2563
+ reviewRoomId: params.get("reviewRoomId") ?? undefined,
2564
+ storyId: params.get("storyId") ?? undefined,
2565
+ filePath: params.get("filePath") ?? undefined,
2566
+ surface: surfaceForTargetKind(targetKind),
2567
+ sourceMode: "derived"
2568
+ };
2569
+ }
2570
+ function firstSafeTrailHref(values) {
2571
+ for (const value of values) {
2572
+ const href = cleanString2(value);
2573
+ if (!href || href.startsWith("//"))
2574
+ continue;
2575
+ try {
2576
+ const parsed = new URL(href, "https://rhei.local");
2577
+ if (parsed.origin !== "https://rhei.local")
2578
+ continue;
2579
+ if (parsed.pathname !== "/trail")
2580
+ continue;
2581
+ return `${parsed.pathname}${parsed.search}`;
2582
+ } catch {
2583
+ continue;
2584
+ }
2585
+ }
2586
+ return null;
2587
+ }
2588
+ function paramsFromHref(href) {
2589
+ try {
2590
+ return new URL(href, "https://rhei.local").searchParams;
2591
+ } catch {
2592
+ return new URLSearchParams;
2593
+ }
2594
+ }
2595
+ function setParam(params, key, value, force = false) {
2596
+ const cleaned = cleanString2(value);
2597
+ if (!cleaned)
2598
+ return;
2599
+ if (!force && params.has(key))
2600
+ return;
2601
+ params.set(key, cleaned);
2602
+ }
2603
+ function inferTargetKind(refs, href) {
2604
+ const kinds = refs.map((ref) => normalizeKind(ref.kind));
2605
+ if (kinds.some((kind) => kind.includes("market")))
2606
+ return "code_market";
2607
+ if (kinds.some((kind) => kind === "code_node"))
2608
+ return "code_node";
2609
+ if (kinds.some((kind) => kind.includes("map")))
2610
+ return "code_map";
2611
+ if (kinds.some((kind) => kind.includes("pr_impact")))
2612
+ return "pr_impact";
2613
+ if (kinds.some((kind) => kind.includes("pr_") || kind === "review_room"))
2614
+ return "pr_report";
2615
+ if (kinds.some((kind) => kind.includes("pulse")))
2616
+ return "pulse_evidence";
2617
+ if (kinds.some((kind) => kind.includes("backend_readiness") || kind.includes("repo_intelligence")))
2618
+ return "backend_readiness";
2619
+ if (kinds.some((kind) => kind.includes("mcp")))
2620
+ return "mcp_run";
2621
+ if (kinds.some((kind) => kind === "agent_run" || kind === "agent_run_node"))
2622
+ return "agent_run";
2623
+ if (kinds.some((kind) => kind.includes("workroom")))
2624
+ return "workroom";
2625
+ if (kinds.some((kind) => kind.includes("patch")))
2626
+ return "patch_run";
2627
+ if (kinds.some((kind) => kind.includes("edit_session")))
2628
+ return "edit_session";
2629
+ if (kinds.some((kind) => kind === "code_node"))
2630
+ return "code_node";
2631
+ if (kinds.some((kind) => kind === "artifact"))
2632
+ return "artifact";
2633
+ if (kinds.some((kind) => kind.includes("receipt")))
2634
+ return "receipt";
2635
+ return href ? "code_trail" : "receipt";
2636
+ }
2637
+ function surfaceForTargetKind(targetKind) {
2638
+ switch (targetKind) {
2639
+ case "code_market":
2640
+ return "code_market";
2641
+ case "code_map":
2642
+ case "code_node":
2643
+ return "code_map";
2644
+ case "pulse_evidence":
2645
+ return "pulse";
2646
+ case "pr_report":
2647
+ case "pr_impact":
2648
+ return "pr_review";
2649
+ case "edit_session":
2650
+ case "patch_run":
2651
+ case "workroom":
2652
+ return "workroom";
2653
+ case "mcp_run":
2654
+ case "agent_run":
2655
+ return "local_mcp";
2656
+ default:
2657
+ return "web";
2658
+ }
2659
+ }
2660
+ function buildFanout(params, targetKind) {
2661
+ const surfaces = uniqueSurfaceStrings([surfaceForTargetKind(targetKind), ...additionalSurfacesForParams(params)]);
2662
+ return {
2663
+ lane: fanoutLaneForTargetKind(targetKind),
2664
+ surfaces,
2665
+ sourceMode: "derived",
2666
+ params: Array.from(params.keys()).sort()
2667
+ };
2668
+ }
2669
+ function additionalSurfacesForParams(params) {
2670
+ const surfaces = [];
2671
+ if (params.has("prSnapshotId") || params.has("reviewRoomId") || params.has("storyId"))
2672
+ surfaces.push("pr_review");
2673
+ if (params.has("codeMarketSnapshotId"))
2674
+ surfaces.push("code_market");
2675
+ if (params.has("codeNodeId") || params.has("filePath"))
2676
+ surfaces.push("code_map");
2677
+ if (params.has("pulseSignalId") || params.has("evidenceJobId"))
2678
+ surfaces.push("pulse");
2679
+ if (params.has("workroomRunId") || params.has("patchRunId") || params.has("editSessionId") || params.has("editSessionRowId"))
2680
+ surfaces.push("workroom");
2681
+ if (params.has("mcpContextRunId") || params.has("sourceMcpRunId") || params.has("agentRunId") || params.has("agentRunNodeId"))
2682
+ surfaces.push("local_mcp");
2683
+ return surfaces;
2684
+ }
2685
+ function fanoutLaneForTargetKind(targetKind) {
2686
+ switch (targetKind) {
2687
+ case "code_market":
2688
+ return "code_market";
2689
+ case "code_map":
2690
+ case "code_node":
2691
+ return "code_map";
2692
+ case "pr_report":
2693
+ case "pr_impact":
2694
+ return "pr_review";
2695
+ case "pulse_evidence":
2696
+ return "pulse";
2697
+ case "workroom":
2698
+ case "patch_run":
2699
+ case "edit_session":
2700
+ return "workroom";
2701
+ case "mcp_run":
2702
+ return "local_mcp";
2703
+ case "agent_run":
2704
+ return "agent_run";
2705
+ case "backend_readiness":
2706
+ return "backend_readiness";
2707
+ default:
2708
+ return "trail";
2709
+ }
2710
+ }
2711
+ function uniqueSurfaceStrings(values) {
2712
+ const seen = new Set;
2713
+ const output = [];
2714
+ for (const value of values) {
2715
+ if (seen.has(value))
2716
+ continue;
2717
+ seen.add(value);
2718
+ output.push(value);
2719
+ }
2720
+ return output;
2721
+ }
2722
+ function projectIdFromRefs(refs) {
2723
+ for (const ref of refs) {
2724
+ const projectId = cleanString2(ref.metadata?.["projectId"]);
2725
+ if (projectId)
2726
+ return projectId;
2727
+ }
2728
+ return;
2729
+ }
2730
+ function stringFromMetadata(metadata, key) {
2731
+ return cleanString2(metadata?.[key]);
2732
+ }
2733
+ function normalizeKind(value) {
2734
+ return (value ?? "").trim().toLowerCase();
2735
+ }
2736
+ function cleanString2(value) {
2737
+ return typeof value === "string" && value.trim().length > 0 ? value.trim() : undefined;
2738
+ }
2739
+ function uniqueStrings2(values) {
2740
+ const seen = new Set;
2741
+ const output = [];
2742
+ for (const value of values) {
2743
+ const trimmed = value?.trim();
2744
+ if (!trimmed || seen.has(trimmed))
2745
+ continue;
2746
+ seen.add(trimmed);
2747
+ output.push(trimmed);
2748
+ }
2749
+ return output;
2750
+ }
2751
+ export {
2752
+ uniqueCodeTrailStrings,
2753
+ sortCodeTrailLinks,
2754
+ sortCodeTrailEntries,
2755
+ sanitizeCodeTrailMetadata,
2756
+ normalizeCodeTrailProjection,
2757
+ isDeterministicCodeTrailRef,
2758
+ getCodeTrailEntryById,
2759
+ getCodeTrailEntriesForRef,
2760
+ dedupeCodeTrailLinks,
2761
+ dedupeCodeTrailEntries,
2762
+ codeTrailStatusToCodeMarketWorkClusterStatus,
2763
+ codeTrailSourceToCodeMarketSource,
2764
+ codeTrailRefToCodeMarketRef,
2765
+ codeTrailNoAuthorityBoundary,
2766
+ codeTrailGapToCodeMarketGap,
2767
+ codeTrailEntryToCodeMarketCompletion,
2768
+ codeTrailEntriesToCodeMarketWorkImpactOverlays,
2769
+ codeTrailEntriesToCodeMarketWorkClusters,
2770
+ buildCodeTrailSourceKey,
2771
+ buildCodeTrailRefStableKey,
2772
+ buildCodeTrailReceiptTargetV1,
2773
+ admitSource,
2774
+ admitLink,
2775
+ admitEntry,
2776
+ admitCodeTrailGap,
2777
+ CODE_TRAIL_SCHEMA_VERSION,
2778
+ CODE_TRAIL_READ_MODEL_VERSION,
2779
+ CODE_TRAIL_NO_AUTHORITY_BOUNDARY,
2780
+ CODE_TRAIL_MODEL_VERSION
2781
+ };