@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,1276 @@
1
+ // ../core/src/briefs/types.ts
2
+ var BRIEF_SCHEMA_VERSION = 1;
3
+ var TASK_BRIEF_READ_MODEL_VERSION = 1;
4
+ var CONTEXT_DEPTHS = ["light", "normal", "deep"];
5
+ var BRIEF_SURFACES_V1 = ["task", "daily", "agent_handoff", "impact"];
6
+ var TASK_BRIEF_STATES_V1 = ["empty", "warming", "ready"];
7
+ var BRIEF_ITEM_KINDS_V1 = [
8
+ "action",
9
+ "context",
10
+ "connection",
11
+ "receipt",
12
+ "gap",
13
+ "source",
14
+ "workroom",
15
+ "impact",
16
+ "handoff"
17
+ ];
18
+ var BRIEF_SECTION_KINDS_V1 = [
19
+ "resume",
20
+ "waiting",
21
+ "in_motion",
22
+ "review",
23
+ "changed",
24
+ "context",
25
+ "gaps"
26
+ ];
27
+ var FEEDBACK_COMMANDS_V1 = [
28
+ "open",
29
+ "ask_with_this",
30
+ "ask_with_brief",
31
+ "pin",
32
+ "hide_for_me",
33
+ "why_this_appears",
34
+ "not_useful_here",
35
+ "not_related",
36
+ "wrong",
37
+ "request_review"
38
+ ];
39
+ var SESSION_ACTIVITY_TYPES_V1 = [
40
+ "brief_viewed",
41
+ "item_opened",
42
+ "ask_with_this",
43
+ "ask_with_brief",
44
+ "why_viewed",
45
+ "pin_applied",
46
+ "hide_applied",
47
+ "feedback_submitted",
48
+ "review_requested"
49
+ ];
50
+ var BRIEF_COMMAND_DESCRIPTORS_V1 = {
51
+ open: {
52
+ command: "open",
53
+ label: "Open",
54
+ description: "Open this item as a reference.",
55
+ recordsPositiveEvidence: true
56
+ },
57
+ ask_with_this: {
58
+ command: "ask_with_this",
59
+ label: "Ask with this",
60
+ description: "Use this item as context for an Ask Rhei turn.",
61
+ recordsPositiveEvidence: true
62
+ },
63
+ ask_with_brief: {
64
+ command: "ask_with_brief",
65
+ label: "Ask with Brief",
66
+ description: "Use the full brief as context for an Ask Rhei turn.",
67
+ recordsPositiveEvidence: true
68
+ },
69
+ pin: {
70
+ command: "pin",
71
+ label: "Pin",
72
+ description: "Save this item for the current work without promoting it to canonical truth.",
73
+ defaultScope: "current_working_set",
74
+ correctionTool: true,
75
+ recordsPositiveEvidence: true
76
+ },
77
+ hide_for_me: {
78
+ command: "hide_for_me",
79
+ label: "Hide",
80
+ description: "Hide this item for your ranking only.",
81
+ defaultScope: "personal_ranking",
82
+ correctionTool: true
83
+ },
84
+ why_this_appears: {
85
+ command: "why_this_appears",
86
+ label: "Why this appears",
87
+ description: "Show evidence and reasoning for this item."
88
+ },
89
+ not_useful_here: {
90
+ command: "not_useful_here",
91
+ label: "Not useful here",
92
+ description: "Downrank this item for the current working context only.",
93
+ defaultScope: "current_working_set",
94
+ correctionTool: true
95
+ },
96
+ not_related: {
97
+ command: "not_related",
98
+ label: "Not related",
99
+ description: "Mark this soft connection as not related at the project level.",
100
+ defaultScope: "project_connection",
101
+ correctionTool: true,
102
+ requiresConnection: true
103
+ },
104
+ wrong: {
105
+ command: "wrong",
106
+ label: "Wrong",
107
+ description: "Flag this soft connection as wrong for review.",
108
+ defaultScope: "project_connection",
109
+ correctionTool: true,
110
+ requiresConnection: true
111
+ },
112
+ request_review: {
113
+ command: "request_review",
114
+ label: "Review relationship",
115
+ description: "Open a governed review request without mutating canonical truth.",
116
+ defaultScope: "project_connection",
117
+ governanceOnly: true,
118
+ requiresConnection: true
119
+ }
120
+ };
121
+ var BRIEF_COMMAND_LABELS_V1 = Object.fromEntries(Object.entries(BRIEF_COMMAND_DESCRIPTORS_V1).map(([command, descriptor]) => [command, descriptor.label]));
122
+ 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]));
123
+ var BRIEF_ITEM_READ_MODEL_VERSION_V2 = 2;
124
+ var DETERMINISTIC_WHY_SCHEMA_VERSION = 1;
125
+ var DETERMINISTIC_WHY_COPY_VERSION = "product-safe-v1";
126
+ var DETERMINISTIC_WHY_BULLET_KINDS_V1 = [
127
+ "status",
128
+ "evidence",
129
+ "recency",
130
+ "desk",
131
+ "policy",
132
+ "uncertainty"
133
+ ];
134
+ var BRIEF_ITEM_RELEVANCE_SOURCES_V1 = [
135
+ "signal",
136
+ "desk",
137
+ "feedback",
138
+ "resume",
139
+ "review",
140
+ "changed"
141
+ ];
142
+ function defaultFeedbackScopeForCommand(command) {
143
+ return BRIEF_COMMAND_DEFAULT_SCOPES_V1[command] ?? "personal_ranking";
144
+ }
145
+ function activityTypeForFeedbackCommand(command) {
146
+ if (command === "open")
147
+ return "item_opened";
148
+ if (command === "ask_with_this")
149
+ return "ask_with_this";
150
+ if (command === "ask_with_brief")
151
+ return "ask_with_brief";
152
+ if (command === "why_this_appears")
153
+ return "why_viewed";
154
+ if (command === "pin")
155
+ return "pin_applied";
156
+ if (command === "hide_for_me")
157
+ return "hide_applied";
158
+ if (command === "request_review")
159
+ return "review_requested";
160
+ return "feedback_submitted";
161
+ }
162
+ function isCorrectionFeedbackCommand(command) {
163
+ return BRIEF_COMMAND_DESCRIPTORS_V1[command].correctionTool === true;
164
+ }
165
+ function isGovernanceFeedbackCommand(command) {
166
+ return BRIEF_COMMAND_DESCRIPTORS_V1[command].governanceOnly === true;
167
+ }
168
+ function feedbackCommandRecordsPositiveEvidence(command) {
169
+ return BRIEF_COMMAND_DESCRIPTORS_V1[command].recordsPositiveEvidence === true;
170
+ }
171
+ function briefCommandsForItem(item) {
172
+ const base = [
173
+ "open",
174
+ "ask_with_this",
175
+ "pin",
176
+ "hide_for_me",
177
+ "why_this_appears",
178
+ "not_useful_here"
179
+ ];
180
+ const connectionCommands = item.connectionId ? ["not_related", "wrong", "request_review"] : [];
181
+ const commands = [...base, ...connectionCommands];
182
+ return commands.map((command) => BRIEF_COMMAND_DESCRIPTORS_V1[command]);
183
+ }
184
+ function buildTaskBriefV1FromActionItems(args) {
185
+ const briefItems = args.items.map(actionSurfaceItemToBriefItem);
186
+ const sections = groupBriefItems(briefItems);
187
+ const state = args.readiness.state;
188
+ return {
189
+ schemaVersion: BRIEF_SCHEMA_VERSION,
190
+ readModelVersion: TASK_BRIEF_READ_MODEL_VERSION,
191
+ surface: "task",
192
+ projectId: args.projectId,
193
+ generatedAt: args.generatedAt,
194
+ contextDepth: args.readiness.contextDepth,
195
+ state,
196
+ title: args.title ?? defaultTaskBriefTitle(state),
197
+ subtitle: args.subtitle ?? args.readiness.label,
198
+ primaryItem: briefItems[0],
199
+ sections,
200
+ items: briefItems,
201
+ primaryAction: args.primaryAction,
202
+ secondaryActions: args.secondaryActions ?? [],
203
+ commands: [BRIEF_COMMAND_DESCRIPTORS_V1.ask_with_brief],
204
+ readiness: args.readiness,
205
+ sourceModel: briefItems.length > 0 ? "before_work_brief" : "empty",
206
+ metadata: args.metadata
207
+ };
208
+ }
209
+ function actionSurfaceItemToBriefItem(item) {
210
+ const targetRef = item.primaryAction?.targetRef ?? item.allActions[0]?.targetRef ?? {
211
+ kind: "action",
212
+ id: item.signalItem.primaryAction.targetRef,
213
+ label: item.title
214
+ };
215
+ const connectionId = readConnectionId(item);
216
+ const briefItem = {
217
+ schemaVersion: BRIEF_SCHEMA_VERSION,
218
+ id: item.id,
219
+ kind: briefItemKindForActionItem(item),
220
+ title: item.title,
221
+ subtitle: item.subtitle,
222
+ summary: item.evidenceSummary,
223
+ statusLabel: item.statusLabel,
224
+ targetRef,
225
+ sourceRefs: item.sourceRefs.map((ref) => ({ kind: ref.kind, id: ref.id, label: ref.label })),
226
+ evidenceRefs: item.allActions.flatMap((action) => action.evidenceRefs),
227
+ receiptRefs: item.receiptRefs.map((ref) => ({ kind: ref.kind ?? "receipt", id: ref.id, label: ref.label })),
228
+ connectionId,
229
+ actionIds: item.allActions.map((action) => action.id),
230
+ commands: briefCommandsForItem({ connectionId }),
231
+ privacyLabel: item.privacyBoundary === "private_personal" ? "Private to you" : undefined,
232
+ reasonCodes: Array.from(new Set(item.allActions.flatMap((action) => action.reasonCodes))),
233
+ metadata: {
234
+ groupKey: item.groupKey,
235
+ sourceSignalIds: item.sourceSignalIds,
236
+ latestStatus: item.latestStatus
237
+ }
238
+ };
239
+ return briefItem;
240
+ }
241
+ function groupBriefItems(items) {
242
+ const groups = [
243
+ { id: "resume", title: "Resume", items: [] },
244
+ { id: "waiting", title: "Waiting", items: [] },
245
+ { id: "in_motion", title: "In motion", items: [] },
246
+ { id: "review", title: "For review", items: [] },
247
+ { id: "changed", title: "Changed", items: [] },
248
+ { id: "context", title: "Context", items: [] }
249
+ ];
250
+ const byId = new Map(groups.map((section) => [section.id, section]));
251
+ for (const item of items) {
252
+ const sectionId = sectionForBriefItem(item);
253
+ byId.get(sectionId)?.items.push(item);
254
+ }
255
+ return groups.filter((section) => section.items.length > 0);
256
+ }
257
+ function briefItemKindForActionItem(item) {
258
+ if (item.signalItem.primaryAction.targetRef.startsWith("connected_work:"))
259
+ return "connection";
260
+ if (item.signalItem.primaryAction.targetRef.includes("workroom"))
261
+ return "workroom";
262
+ if (item.receiptRefs.length > 0)
263
+ return "receipt";
264
+ if (item.allActions.some((action) => action.reasonCodes.some((code) => code.includes("context"))))
265
+ return "context";
266
+ return "action";
267
+ }
268
+ function sectionForBriefItem(item) {
269
+ const status = item.metadata?.["latestStatus"];
270
+ if (item.reasonCodes.includes("attention:resume"))
271
+ return "resume";
272
+ if (item.reasonCodes.some((code) => code.includes("review")))
273
+ return "review";
274
+ if (item.reasonCodes.some((code) => code.includes("changed")))
275
+ return "changed";
276
+ if (item.kind === "context")
277
+ return "context";
278
+ if (status === "queued" || status === "scheduled" || status === "awaiting_approval")
279
+ return "waiting";
280
+ if (status === "running")
281
+ return "in_motion";
282
+ return "waiting";
283
+ }
284
+ function readConnectionId(item) {
285
+ const candidates = [
286
+ item.primaryAction?.targetRef.id,
287
+ item.allActions.find((action) => action.targetRef.kind === "observed_connection")?.targetRef.id,
288
+ item.allActions.find((action) => action.targetRef.kind === "connected_work")?.targetRef.id,
289
+ item.signalItem.primaryAction.targetRef,
290
+ ...item.allActions.map((action) => action.targetRef.id)
291
+ ];
292
+ for (const candidate of candidates) {
293
+ if (typeof candidate !== "string" || candidate.length === 0)
294
+ continue;
295
+ if (candidate.startsWith("connected_work:"))
296
+ return candidate.slice("connected_work:".length);
297
+ if (candidate.startsWith("observed_connection:"))
298
+ return candidate.slice("observed_connection:".length);
299
+ }
300
+ const connectedWorkAction = item.allActions.find((action) => action.targetRef.kind === "observed_connection" || action.targetRef.kind === "connected_work");
301
+ return connectedWorkAction?.targetRef.id;
302
+ }
303
+ function defaultTaskBriefTitle(state) {
304
+ if (state === "empty")
305
+ return "No task brief yet";
306
+ if (state === "warming")
307
+ return "Rhei is preparing your Task Brief";
308
+ return "Task Brief";
309
+ }
310
+ // ../core/src/briefs/why.ts
311
+ var DEFAULT_WHY_HEADLINE = "Rhei found a task-relevant signal.";
312
+ var DEFAULT_WHY_BULLET = "No additional explanation was available, so this item is shown with conservative context only.";
313
+ function buildDeterministicWhyV1(args = {}) {
314
+ const bullets = normalizeWhyBullets(args.bullets);
315
+ if (bullets.length === 0) {
316
+ bullets.push({ kind: "uncertainty", text: cleanText(args.fallbackText) ?? DEFAULT_WHY_BULLET });
317
+ }
318
+ return {
319
+ schemaVersion: DETERMINISTIC_WHY_SCHEMA_VERSION,
320
+ headline: cleanText(args.headline) ?? DEFAULT_WHY_HEADLINE,
321
+ bullets,
322
+ confidenceLabel: confidenceLabelFor(args.confidence, args.confidenceLabel),
323
+ evidenceCount: safeEvidenceCount(args.evidenceCount, bullets),
324
+ copyVersion: DETERMINISTIC_WHY_COPY_VERSION
325
+ };
326
+ }
327
+ function buildDeterministicWhyForBriefItem(item) {
328
+ const bullets = [];
329
+ const refIds = refIdsForBriefRefs([...item.sourceRefs, ...item.evidenceRefs, ...item.receiptRefs]);
330
+ if (item.statusLabel) {
331
+ bullets.push({ kind: "status", text: `Status: ${item.statusLabel}.`, refIds });
332
+ }
333
+ if (item.summary) {
334
+ bullets.push({ kind: "evidence", text: item.summary, refIds });
335
+ }
336
+ if (item.sourceRefs.length > 0 || item.evidenceRefs.length > 0) {
337
+ bullets.push({
338
+ kind: "evidence",
339
+ text: `Backed by ${item.sourceRefs.length + item.evidenceRefs.length} source or evidence reference(s).`,
340
+ refIds
341
+ });
342
+ }
343
+ if (item.receiptRefs.length > 0) {
344
+ bullets.push({ kind: "recency", text: `Includes ${item.receiptRefs.length} recent receipt reference(s).`, refIds });
345
+ }
346
+ if (item.stale) {
347
+ bullets.push({ kind: "recency", text: "This item may be stale; inspect the source before acting.", refIds });
348
+ }
349
+ if (item.conflicted) {
350
+ bullets.push({ kind: "uncertainty", text: "Some signals conflict, so treat this as a prompt to inspect rather than a fact.", refIds });
351
+ }
352
+ if (item.reasonCodes.some((code) => code.startsWith("policy:"))) {
353
+ bullets.push({ kind: "policy", text: "Policy state comes from the action offer and does not grant new authority.", refIds });
354
+ }
355
+ return buildDeterministicWhyV1({
356
+ headline: item.title,
357
+ bullets,
358
+ confidence: item.confidence,
359
+ evidenceCount: item.sourceRefs.length + item.evidenceRefs.length + item.receiptRefs.length
360
+ });
361
+ }
362
+ function normalizeWhyBullets(bullets) {
363
+ if (!bullets)
364
+ return [];
365
+ return bullets.map((bullet) => ({
366
+ ...bullet,
367
+ text: cleanText(bullet.text) ?? DEFAULT_WHY_BULLET,
368
+ refIds: bullet.refIds ? Array.from(new Set(bullet.refIds.filter(Boolean))) : undefined
369
+ })).filter((bullet) => bullet.text.length > 0).slice(0, 6);
370
+ }
371
+ function confidenceLabelFor(confidence, fallback) {
372
+ if (fallback)
373
+ return fallback;
374
+ if (typeof confidence !== "number")
375
+ return;
376
+ if (confidence >= 0.75)
377
+ return "high";
378
+ if (confidence >= 0.45)
379
+ return "medium";
380
+ return "low";
381
+ }
382
+ function safeEvidenceCount(count, bullets) {
383
+ if (typeof count === "number" && Number.isFinite(count))
384
+ return Math.max(0, Math.floor(count));
385
+ return bullets.reduce((total, bullet) => total + (bullet.refIds?.length ?? 0), 0);
386
+ }
387
+ function refIdsForBriefRefs(refs) {
388
+ const ids = Array.from(new Set(refs.map((ref) => ref.id).filter(Boolean)));
389
+ return ids.length > 0 ? ids : undefined;
390
+ }
391
+ function cleanText(value) {
392
+ const text = value?.trim();
393
+ return text && text.length > 0 ? text : undefined;
394
+ }
395
+ // ../core/src/briefs/contextPlan.ts
396
+ var DEFAULT_MAX_CONTEXT_ITEMS = 8;
397
+ var DEFAULT_ASK_GOAL = "Use this Task Brief context to answer without broad project search.";
398
+ function buildContextPlanV1(args = {}) {
399
+ return {
400
+ schemaVersion: BRIEF_SCHEMA_VERSION,
401
+ planner: "task_brief_v1",
402
+ intent: args.intent ?? "explain_why",
403
+ scope: args.scope ?? "item",
404
+ allowProjectSearch: args.allowProjectSearch ?? false,
405
+ maxContextItems: positiveInteger(args.maxContextItems, DEFAULT_MAX_CONTEXT_ITEMS),
406
+ maxTokens: args.maxTokens,
407
+ exactRefs: dedupeRefs(args.exactRefs ?? []),
408
+ sourceRoles: dedupeSourceRoles(args.sourceRoles ?? []),
409
+ serviceConnectionIds: dedupeStrings(args.serviceConnectionIds ?? []),
410
+ constraints: {
411
+ privacyBoundary: args.constraints?.privacyBoundary ?? "project",
412
+ requireExplicitRefs: args.constraints?.requireExplicitRefs ?? true,
413
+ productSafeCopy: true,
414
+ workingSetGrantsAuthority: false
415
+ }
416
+ };
417
+ }
418
+ function buildContextPlanForBriefItem(item, command = "ask_with_this", args = {}) {
419
+ return buildContextPlanV1({
420
+ ...args,
421
+ intent: args.intent ?? contextPlanIntentForFeedbackCommand(command),
422
+ scope: args.scope ?? contextPlanScopeForFeedbackCommand(command),
423
+ allowProjectSearch: args.allowProjectSearch ?? false,
424
+ exactRefs: args.exactRefs ?? exactRefsForBriefItem(item),
425
+ sourceRoles: args.sourceRoles ?? sourceRolesForBriefItem(item),
426
+ constraints: {
427
+ ...args.constraints,
428
+ privacyBoundary: args.constraints?.privacyBoundary ?? privacyBoundaryForBriefItem(item),
429
+ requireExplicitRefs: args.constraints?.requireExplicitRefs ?? true,
430
+ productSafeCopy: true,
431
+ workingSetGrantsAuthority: false
432
+ }
433
+ });
434
+ }
435
+ function buildBriefItemRelevanceV1(item, args = {}) {
436
+ return {
437
+ source: args.source ?? relevanceSourceForReasonCodes(item.reasonCodes),
438
+ deskRole: args.deskRole,
439
+ pinned: args.pinned,
440
+ hiddenForViewer: args.hiddenForViewer,
441
+ downrankedForViewer: args.downrankedForViewer,
442
+ score: clampScore(args.score),
443
+ reasonCodes: dedupeStrings(args.reasonCodes ?? item.reasonCodes)
444
+ };
445
+ }
446
+ function buildBriefItemV2(args) {
447
+ const item = args.item;
448
+ const existing = isBriefItemV2(item) ? item : undefined;
449
+ const actionOffers = args.actionOffers ?? existing?.actionOffers ?? [];
450
+ const primaryOffer = args.primaryOffer ?? existing?.primaryOffer ?? actionOffers[0];
451
+ return {
452
+ ...item,
453
+ readModelVersion: BRIEF_ITEM_READ_MODEL_VERSION_V2,
454
+ why: args.why ?? existing?.why ?? buildDeterministicWhyForBriefItem(item),
455
+ actionOffers,
456
+ primaryOffer,
457
+ relevance: args.relevance ?? existing?.relevance ?? buildBriefItemRelevanceV1(item),
458
+ contextPlan: args.contextPlan ?? existing?.contextPlan ?? buildContextPlanForBriefItem(item)
459
+ };
460
+ }
461
+ function buildAgentWorkBriefV1(args) {
462
+ const selectedSourceItems = sourceItemsForAgentWorkBrief(args);
463
+ const selectedItems = selectedSourceItems.map(agentWorkBriefSelectedItemForBriefItem);
464
+ const selectedItem = selectedItems[0];
465
+ const contextPlan = args.contextPlan ?? contextPlanForAgentWorkBrief(args, selectedItems);
466
+ const primaryOffer = isBriefItemV2(args.item) ? args.item.primaryOffer : undefined;
467
+ return {
468
+ schemaVersion: BRIEF_SCHEMA_VERSION,
469
+ workBriefVersion: 1,
470
+ source: {
471
+ surface: "task",
472
+ briefId: briefIdForAgentWorkBrief(args),
473
+ itemId: args.item?.id,
474
+ command: args.command,
475
+ projectId: args.brief.projectId,
476
+ generatedAt: args.generatedAt ?? args.brief.generatedAt
477
+ },
478
+ userGoal: cleanText2(args.userGoal) ?? DEFAULT_ASK_GOAL,
479
+ briefTitle: args.brief.title,
480
+ selectedItem,
481
+ items: selectedItems,
482
+ selectedItems,
483
+ contextPlan,
484
+ actionIntent: {
485
+ command: args.command,
486
+ label: BRIEF_COMMAND_DESCRIPTORS_V1[args.command].label,
487
+ actionId: primaryOffer?.id,
488
+ actionVerb: primaryOffer?.verb,
489
+ executionPath: primaryOffer?.executionPath,
490
+ policyState: primaryOffer?.policyState,
491
+ targetRef: primaryOffer?.targetRef ?? args.item?.targetRef
492
+ },
493
+ evidenceRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.evidenceRefs)),
494
+ sourceRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.sourceRefs)),
495
+ receiptRefs: dedupeRefs(selectedSourceItems.flatMap((item) => item.receiptRefs)),
496
+ workingSetSnapshotHash: args.workingSetSnapshotHash,
497
+ plannerHandoffGraphAdvisory: args.plannerHandoffGraphAdvisory,
498
+ guardrails: {
499
+ actionLayerOffersOnly: true,
500
+ workingSetGrantsAuthority: false,
501
+ canonicalChangesRequireTruthGate: true,
502
+ memoryPromotionRequiresExplicitPath: true
503
+ }
504
+ };
505
+ }
506
+ function contextPlanIntentForFeedbackCommand(command) {
507
+ if (command === "ask_with_this")
508
+ return "ask_with_item";
509
+ if (command === "ask_with_brief")
510
+ return "ask_with_brief";
511
+ if (command === "open")
512
+ return "open_item";
513
+ if (command === "request_review")
514
+ return "review_relationship";
515
+ return "explain_why";
516
+ }
517
+ function contextPlanScopeForFeedbackCommand(command) {
518
+ if (command === "ask_with_brief")
519
+ return "brief";
520
+ return "item";
521
+ }
522
+ function sourceItemsForAgentWorkBrief(args) {
523
+ const sourceItems = args.item ? [args.item] : args.items ?? args.brief.items;
524
+ const limit = positiveInteger(args.contextPlan?.maxContextItems, DEFAULT_MAX_CONTEXT_ITEMS);
525
+ return sourceItems.slice(0, limit);
526
+ }
527
+ function agentWorkBriefSelectedItemForBriefItem(item) {
528
+ return {
529
+ id: item.id,
530
+ kind: item.kind,
531
+ title: item.title,
532
+ subtitle: item.subtitle,
533
+ summary: item.summary,
534
+ statusLabel: item.statusLabel,
535
+ targetRef: item.targetRef,
536
+ why: isBriefItemV2(item) ? item.why : buildDeterministicWhyForBriefItem(item),
537
+ relevance: isBriefItemV2(item) ? item.relevance : undefined,
538
+ reasonCodes: item.reasonCodes
539
+ };
540
+ }
541
+ function contextPlanForAgentWorkBrief(args, selectedItems) {
542
+ if (args.item)
543
+ return buildContextPlanForBriefItem(args.item, args.command);
544
+ return buildContextPlanV1({
545
+ intent: contextPlanIntentForFeedbackCommand(args.command),
546
+ scope: contextPlanScopeForFeedbackCommand(args.command),
547
+ allowProjectSearch: false,
548
+ maxContextItems: selectedItems.length || DEFAULT_MAX_CONTEXT_ITEMS,
549
+ exactRefs: dedupeRefs(selectedItems.map((item) => item.targetRef)),
550
+ sourceRoles: selectedItems.map((item, index) => ({
551
+ role: index === 0 ? "selected_item" : "brief_neighbor",
552
+ ref: item.targetRef
553
+ })),
554
+ constraints: {
555
+ privacyBoundary: "project",
556
+ requireExplicitRefs: true,
557
+ productSafeCopy: true,
558
+ workingSetGrantsAuthority: false
559
+ }
560
+ });
561
+ }
562
+ function exactRefsForBriefItem(item) {
563
+ return dedupeRefs([item.targetRef, ...item.sourceRefs, ...item.evidenceRefs, ...item.receiptRefs]);
564
+ }
565
+ function sourceRolesForBriefItem(item) {
566
+ return dedupeSourceRoles([
567
+ { role: "selected_item", ref: item.targetRef },
568
+ ...item.sourceRefs.map((ref) => ({ role: "evidence", ref })),
569
+ ...item.evidenceRefs.map((ref) => ({ role: "evidence", ref })),
570
+ ...item.receiptRefs.map((ref) => ({ role: "receipt", ref }))
571
+ ]);
572
+ }
573
+ function privacyBoundaryForBriefItem(item) {
574
+ return item.privacyLabel ? "private_personal" : "project";
575
+ }
576
+ function relevanceSourceForReasonCodes(reasonCodes) {
577
+ if (reasonCodes.some((code) => code.includes("resume")))
578
+ return "resume";
579
+ if (reasonCodes.some((code) => code.includes("review")))
580
+ return "review";
581
+ if (reasonCodes.some((code) => code.includes("changed")))
582
+ return "changed";
583
+ return "signal";
584
+ }
585
+ function isBriefItemV2(item) {
586
+ if (!item)
587
+ return false;
588
+ return item.readModelVersion === BRIEF_ITEM_READ_MODEL_VERSION_V2;
589
+ }
590
+ function briefIdForAgentWorkBrief(args) {
591
+ const value = args.brief.metadata?.["briefId"];
592
+ if (typeof value === "string" && value.length > 0)
593
+ return value;
594
+ return `task_brief:${args.brief.projectId}:${args.generatedAt ?? args.brief.generatedAt}`;
595
+ }
596
+ function dedupeRefs(refs) {
597
+ const seen = new Set;
598
+ const output = [];
599
+ for (const ref of refs) {
600
+ const key = `${ref.kind}:${ref.id}:${ref.versionId ?? ""}`;
601
+ if (seen.has(key))
602
+ continue;
603
+ seen.add(key);
604
+ output.push(ref);
605
+ }
606
+ return output;
607
+ }
608
+ function dedupeSourceRoles(sourceRoles) {
609
+ const seen = new Set;
610
+ const output = [];
611
+ for (const sourceRole of sourceRoles) {
612
+ const key = `${sourceRole.role}:${sourceRole.ref.kind}:${sourceRole.ref.id}:${sourceRole.ref.versionId ?? ""}`;
613
+ if (seen.has(key))
614
+ continue;
615
+ seen.add(key);
616
+ output.push(sourceRole);
617
+ }
618
+ return output;
619
+ }
620
+ function dedupeStrings(values) {
621
+ return Array.from(new Set(values.filter(Boolean)));
622
+ }
623
+ function positiveInteger(value, fallback) {
624
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 1)
625
+ return fallback;
626
+ return Math.floor(value);
627
+ }
628
+ function clampScore(value) {
629
+ if (typeof value !== "number" || !Number.isFinite(value))
630
+ return;
631
+ if (value < 0)
632
+ return 0;
633
+ if (value > 1)
634
+ return 1;
635
+ return value;
636
+ }
637
+ function cleanText2(value) {
638
+ const text = value?.trim();
639
+ return text && text.length > 0 ? text : undefined;
640
+ }
641
+ // ../core/src/actionRouting/display.ts
642
+ function renderActionRouteSummaryMarkdown(actionRoute) {
643
+ if (!actionRoute)
644
+ return ["- None supplied."];
645
+ return [
646
+ `- Action mode: ${formatRouteValue(actionRoute.actionMode)}`,
647
+ `- Primary lens: ${formatRouteValue(actionRoute.primaryLens)}`,
648
+ `- Supporting lenses: ${actionRoute.supportingLenses.length > 0 ? actionRoute.supportingLenses.map(formatRouteValue).join(", ") : "none"}`,
649
+ `- Surface scopes: ${actionRoute.surfaceScopes.length > 0 ? actionRoute.surfaceScopes.map(formatRouteValue).join(", ") : "none"}`,
650
+ `- Confidence band: ${formatRouteValue(actionRoute.confidenceBand)}`,
651
+ `- Route metadata is report-only, advisory-only, and grants no execution or canon authority: ${actionRoute.reportOnly && actionRoute.advisoryOnly && actionRoute.noAuthority}`
652
+ ];
653
+ }
654
+ function formatRouteValue(value) {
655
+ return value.replace(/\n/g, " ").trim();
656
+ }
657
+
658
+ // ../core/src/contextRouting/graphExecutionMode.ts
659
+ var GRAPH_EXECUTION_MODES = [
660
+ "convex_local",
661
+ "connected_work_shallow",
662
+ "memgraph_depth3",
663
+ "memgraph_depth5",
664
+ "memgraph_depth5_plus_lite_llm"
665
+ ];
666
+ // ../core/src/contextRouting/plannerHandoffGraphAdvisory.ts
667
+ var PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY = "Graph routing advisory explains context selection. It does not authorize graph mutation, provider synthesis, Memgraph execution, code writes, or Truth Gate promotion.";
668
+ var VALID_SOURCES = new Set([
669
+ "local_code_context",
670
+ "code_market",
671
+ "mcp_input",
672
+ "task_brief",
673
+ "workroom_context_receipt",
674
+ "connected_work_packet",
675
+ "plan_contract",
676
+ "external"
677
+ ]);
678
+ var VALID_BASES = new Set([
679
+ "graph_routing_policy_v1",
680
+ "explicit_metadata",
681
+ "default_no_live"
682
+ ]);
683
+ var VALID_EVIDENCE_QUALITY = new Set(["none", "weak", "usable", "strong"]);
684
+ var VALID_GRAPH_NOISE_RISK = new Set(["unknown", "low", "medium", "high"]);
685
+ var VALID_MODES = new Set(GRAPH_EXECUTION_MODES);
686
+ // ../core/src/contextRouting/surfacePolicies.ts
687
+ var CONNECTED_SURFACE_KINDS_V1 = [
688
+ "primary_code",
689
+ "targeted_tests",
690
+ "user_docs",
691
+ "config_policy",
692
+ "package_exports",
693
+ "runtime_enforcement",
694
+ "schema_persistence",
695
+ "ui_surface",
696
+ "design_system_or_shared_component",
697
+ "usage_sites",
698
+ "visual_snapshot_or_story",
699
+ "native_counterpart",
700
+ "receipt_audit",
701
+ "eval_report",
702
+ "migration_notes",
703
+ "provider_gateway",
704
+ "agent_handoff"
705
+ ];
706
+ var COMMON_CODE_EVIDENCE = [
707
+ "primary_edit_file",
708
+ "context_slice",
709
+ "source_ref",
710
+ "evidence_ref"
711
+ ];
712
+ var COMMON_SUPPORT_EVIDENCE = [
713
+ "context_slice",
714
+ "affected_test",
715
+ "affected_doc",
716
+ "config_file",
717
+ "source_ref",
718
+ "evidence_ref",
719
+ "receipt_ref"
720
+ ];
721
+ function required(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
722
+ return { surfaceKind, level: "required", minEvidenceCount, evidenceTypes, rationale };
723
+ }
724
+ function optional(surfaceKind, minEvidenceCount, evidenceTypes, rationale) {
725
+ return { surfaceKind, level: "optional", minEvidenceCount, evidenceTypes, rationale };
726
+ }
727
+ var CONNECTED_SURFACE_POLICIES_V1 = {
728
+ shared_abstraction: {
729
+ version: 1,
730
+ changeShape: "shared_abstraction",
731
+ label: "Shared abstraction",
732
+ description: "Reusable code contracts need implementation, public contract/docs, and regression tests in the same bounded packet.",
733
+ recommendedEscalation: "memgraph_depth3",
734
+ graphInput: {
735
+ intentConfidence: "strong",
736
+ graphComplexity: "medium",
737
+ connectedWorkAvailable: true,
738
+ noLiveMode: true,
739
+ networkAllowed: false,
740
+ providerCallsAllowed: false
741
+ },
742
+ rules: [
743
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
744
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Shared behavior changes need targeted regression tests."),
745
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Public behavior should stay aligned with user-facing docs."),
746
+ optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Export/type surfaces often carry shared abstraction contracts."),
747
+ optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Runtime guards and helpers can constrain shared behavior."),
748
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing receipts or reports help confirm prior behavior.")
749
+ ]
750
+ },
751
+ ui_behavior: {
752
+ version: 1,
753
+ changeShape: "ui_behavior",
754
+ label: "UI behavior",
755
+ description: "UI behavior packets need render code and visible surface context, with tests/docs when available.",
756
+ recommendedEscalation: "connected_work_shallow",
757
+ graphInput: {
758
+ intentConfidence: "strong",
759
+ graphComplexity: "shallow",
760
+ connectedWorkAvailable: true,
761
+ noLiveMode: true,
762
+ networkAllowed: false,
763
+ providerCallsAllowed: false
764
+ },
765
+ rules: [
766
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary render/state code must be represented."),
767
+ required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
768
+ optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
769
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "UI regression tests are useful when present."),
770
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Trail/receipt display surfaces should remain auditable."),
771
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-visible behavior may need docs or copy updates.")
772
+ ]
773
+ },
774
+ ui_reuse_or_design_system: {
775
+ version: 1,
776
+ changeShape: "ui_reuse_or_design_system",
777
+ label: "UI reuse or design system",
778
+ description: "Reusable UI/design-system opportunities need shared component context, usage sites, package exports, and visible UI surfaces in the same bounded packet.",
779
+ recommendedEscalation: "connected_work_shallow",
780
+ graphInput: {
781
+ intentConfidence: "strong",
782
+ graphComplexity: "shallow",
783
+ connectedWorkAvailable: true,
784
+ noLiveMode: true,
785
+ networkAllowed: false,
786
+ providerCallsAllowed: false
787
+ },
788
+ rules: [
789
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary implementation files must be represented."),
790
+ required("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "Visible UI surface files must be present."),
791
+ required("design_system_or_shared_component", 1, COMMON_SUPPORT_EVIDENCE, "The shared UI primitive or design-system component must be represented."),
792
+ required("usage_sites", 1, COMMON_SUPPORT_EVIDENCE, "Representative call sites must show how the reusable behavior is consumed."),
793
+ required("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Package export surfaces must expose or bound the reusable UI contract."),
794
+ optional("native_counterpart", 1, COMMON_SUPPORT_EVIDENCE, "Native or platform counterpart context prevents platform drift."),
795
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Reusable UI behavior should have targeted regression tests when available."),
796
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Shared UI behavior may need docs or usage guidance."),
797
+ optional("visual_snapshot_or_story", 1, COMMON_SUPPORT_EVIDENCE, "Visual snapshots or stories help validate reusable UI behavior."),
798
+ optional("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes can bound adoption across usage sites."),
799
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Existing reports or receipts help confirm prior UI behavior.")
800
+ ]
801
+ },
802
+ execution_safety: {
803
+ version: 1,
804
+ changeShape: "execution_safety",
805
+ label: "Execution safety",
806
+ description: "Safety-sensitive changes need implementation, enforcement, tests, and audit/receipt surfaces.",
807
+ recommendedEscalation: "memgraph_depth5",
808
+ graphInput: {
809
+ intentConfidence: "strong",
810
+ graphComplexity: "high",
811
+ connectedWorkAvailable: true,
812
+ noLiveMode: true,
813
+ networkAllowed: false,
814
+ providerCallsAllowed: false
815
+ },
816
+ rules: [
817
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Safety behavior must include the primary implementation."),
818
+ required("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Policy/enforcement code must be represented."),
819
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Safety changes require targeted regression tests."),
820
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Environment/config policy can change safety behavior."),
821
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipt and audit surfaces support post-run proof."),
822
+ optional("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Operator docs should reflect safety policy."),
823
+ optional("ui_surface", 1, COMMON_SUPPORT_EVIDENCE, "User-facing callbacks or flows can be affected by safety policy.")
824
+ ]
825
+ },
826
+ provider_integration: {
827
+ version: 1,
828
+ changeShape: "provider_integration",
829
+ label: "Provider integration",
830
+ description: "Provider-routing changes need gateway/provider code, call-path code, docs, and targeted tests.",
831
+ recommendedEscalation: "memgraph_depth3",
832
+ graphInput: {
833
+ intentConfidence: "strong",
834
+ graphComplexity: "medium",
835
+ connectedWorkAvailable: true,
836
+ noLiveMode: true,
837
+ networkAllowed: false,
838
+ providerCallsAllowed: false
839
+ },
840
+ rules: [
841
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Provider integration must include primary call-path code."),
842
+ required("provider_gateway", 1, COMMON_SUPPORT_EVIDENCE, "Gateway/provider routing surfaces must be present."),
843
+ required("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Provider fallback behavior needs targeted tests."),
844
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Provider integration contracts are user-facing."),
845
+ optional("package_exports", 1, COMMON_SUPPORT_EVIDENCE, "Exported provider contracts should be checked."),
846
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Provider options/config can control routing."),
847
+ optional("runtime_enforcement", 1, COMMON_SUPPORT_EVIDENCE, "Retry/error wrappers enforce provider behavior.")
848
+ ]
849
+ },
850
+ agent_handoff: {
851
+ version: 1,
852
+ changeShape: "agent_handoff",
853
+ label: "Agent handoff",
854
+ description: "Agent handoff work needs handoff contracts, docs/work packets, and preferably tests/eval reports.",
855
+ recommendedEscalation: "memgraph_depth3",
856
+ graphInput: {
857
+ intentConfidence: "strong",
858
+ graphComplexity: "medium",
859
+ connectedWorkAvailable: true,
860
+ noLiveMode: true,
861
+ networkAllowed: false,
862
+ providerCallsAllowed: false
863
+ },
864
+ rules: [
865
+ required("agent_handoff", 1, COMMON_SUPPORT_EVIDENCE, "The handoff contract or work packet must be represented."),
866
+ required("primary_code", 1, COMMON_CODE_EVIDENCE, "Primary handoff implementation/contract code must be present."),
867
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "Agent-facing docs or markdown guidance must be present."),
868
+ optional("eval_report", 1, COMMON_SUPPORT_EVIDENCE, "Eval reports help validate handoff usefulness."),
869
+ optional("receipt_audit", 1, COMMON_SUPPORT_EVIDENCE, "Receipts can prove agent handoff lineage."),
870
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Handoff contracts should have targeted tests when available.")
871
+ ]
872
+ },
873
+ docs_or_migration: {
874
+ version: 1,
875
+ changeShape: "docs_or_migration",
876
+ label: "Docs or migration",
877
+ description: "Documentation/migration work needs user docs and migration notes, with code/tests when applicable.",
878
+ recommendedEscalation: "connected_work_shallow",
879
+ graphInput: {
880
+ intentConfidence: "strong",
881
+ graphComplexity: "shallow",
882
+ connectedWorkAvailable: true,
883
+ noLiveMode: true,
884
+ networkAllowed: false,
885
+ providerCallsAllowed: false
886
+ },
887
+ rules: [
888
+ required("user_docs", 1, COMMON_SUPPORT_EVIDENCE, "User-facing docs must be represented."),
889
+ required("migration_notes", 1, COMMON_SUPPORT_EVIDENCE, "Migration notes or planning docs must be represented."),
890
+ optional("primary_code", 1, COMMON_CODE_EVIDENCE, "Related implementation code can anchor docs changes."),
891
+ optional("targeted_tests", 1, COMMON_SUPPORT_EVIDENCE, "Tests can validate migration guidance."),
892
+ optional("config_policy", 1, COMMON_SUPPORT_EVIDENCE, "Migration/config policy may be relevant.")
893
+ ]
894
+ }
895
+ };
896
+ // ../core/src/contextRouting/semanticSelectionSignals.ts
897
+ var CONNECTED_SURFACE_KIND_SET = new Set(CONNECTED_SURFACE_KINDS_V1);
898
+ // ../core/src/contextRouting/semanticGraphRouting.ts
899
+ var PUBLIC_SURFACES = new Set(["package_exports", "user_docs"]);
900
+ var CRITICAL_SURFACES = new Set([
901
+ "runtime_enforcement",
902
+ "config_policy",
903
+ "schema_persistence",
904
+ "receipt_audit"
905
+ ]);
906
+ var TOKEN_VALUE_NAMESPACES = new Set(["focus_lens", "audience", "intent", "tag", "feature_label", "risk", "context_packet"]);
907
+ // ../core/src/briefs/agentHandoffMarkdown.ts
908
+ var AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION = 1;
909
+ function buildAgentHandoffMarkdownV1(args) {
910
+ const generatedAt = args.generatedAt ?? 0;
911
+ const contextPlan = args.agentWorkBrief?.contextPlan ?? args.contextPacket?.links?.contextPlan;
912
+ const lines = [
913
+ `# ${formatInline(args.title ?? args.agentWorkBrief?.briefTitle ?? "Agent handoff")}`,
914
+ "",
915
+ "## Goal",
916
+ `- ${formatInline(args.agentWorkBrief?.userGoal ?? args.contextPacket?.objective ?? "No goal supplied.")}`,
917
+ "",
918
+ "## Scope",
919
+ ...renderScope(args.contextPacket, args.agentWorkBrief),
920
+ "",
921
+ "## Semantic summary",
922
+ ...renderSemanticSummary(args.contextPacket, args.agentWorkBrief),
923
+ "",
924
+ "## Action route",
925
+ ...renderActionRoute(contextPlan, args.contextPacket, args.agentWorkBrief),
926
+ "",
927
+ ...renderPlannerGraphAdvisory(args.agentWorkBrief?.plannerHandoffGraphAdvisory),
928
+ "## Exact context refs",
929
+ ...renderExactRefs(contextPlan, args.contextPacket, args.agentWorkBrief),
930
+ "",
931
+ "## Guardrails",
932
+ ...renderGuardrails(contextPlan, args.contextPacket, args.agentWorkBrief),
933
+ "",
934
+ "## Receipts",
935
+ ...renderReceipts(args.executionReceipts ?? []),
936
+ "",
937
+ "## Open questions",
938
+ ...renderOpenQuestions(args.contextPacket),
939
+ "",
940
+ "## Next agent instructions",
941
+ ...renderNextAgentInstructions()
942
+ ];
943
+ return {
944
+ schemaVersion: AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION,
945
+ kind: "agent_handoff_markdown",
946
+ markdown: `${lines.join(`
947
+ `)}
948
+ `,
949
+ source: {
950
+ contextPacketId: args.contextPacket?.packetId ?? args.agentWorkBrief?.contextPacketId,
951
+ agentWorkBriefId: args.agentWorkBrief?.source.briefId,
952
+ receiptIds: (args.executionReceipts ?? []).map((receipt) => receipt.receiptId)
953
+ },
954
+ generatedAt
955
+ };
956
+ }
957
+ function renderScope(contextPacket, agentWorkBrief) {
958
+ const lines = [
959
+ `- Repo: ${formatInline(contextPacket ? `${contextPacket.repo.name} (${contextPacket.repo.repoId})` : "Not supplied")}`,
960
+ `- Packet id: ${formatInline(contextPacket?.packetId ?? agentWorkBrief?.contextPacketId ?? "Not supplied")}`,
961
+ `- Brief id: ${formatInline(agentWorkBrief?.source.briefId ?? "Not supplied")}`
962
+ ];
963
+ lines.push(...renderPathList("Primary files", contextPacket?.primaryEditFiles.map((ref) => ref.path) ?? []));
964
+ lines.push(...renderSliceList(contextPacket));
965
+ lines.push(...renderPathList("Docs", contextPacket?.affectedDocs.map((ref) => ref.path) ?? []));
966
+ lines.push(...renderPathList("Tests", contextPacket?.affectedTests.map((ref) => ref.path) ?? []));
967
+ lines.push(...renderPathList("Config", contextPacket?.configFiles.map((ref) => ref.path) ?? []));
968
+ return lines;
969
+ }
970
+ function renderSemanticSummary(contextPacket, agentWorkBrief) {
971
+ const semanticSignals = semanticSelectionSignals2(contextPacket);
972
+ const parsedSignals = semanticSignals.map(parseSemanticSelectionSignal).filter(isDefined);
973
+ const coveredSurfaces = renderCoveredSurfaces(contextPacket, agentWorkBrief);
974
+ const semanticSurfaces = uniqueStrings(parsedSignals.filter((signal) => signal.kind === "connected_surface" && signal.value).map((signal) => `${signal.value} (${signal.authority === "parser_fact" ? "parser fact" : "advisory"})`));
975
+ const parserFacts = parsedSignals.filter((signal) => signal.authority === "parser_fact").map(formatParsedSemanticSignal);
976
+ const advisoryLabels = parsedSignals.filter((signal) => signal.authority !== "parser_fact").map(formatParsedSemanticSignal);
977
+ const advisoryConstraints = advisoryConstraintSummary(contextPacket);
978
+ const warnings = staleOrLowConfidenceWarnings(contextPacket);
979
+ return [
980
+ `- Covered surfaces: ${coveredSurfaces.length > 0 ? coveredSurfaces.join("; ") : "none supplied"}`,
981
+ `- Semantic connected surfaces: ${semanticSurfaces.length > 0 ? semanticSurfaces.map(formatInline).join(", ") : "none signaled"}`,
982
+ `- Parser facts from selection signals: ${parserFacts.length > 0 ? parserFacts.map(formatInline).join(", ") : "none supplied"}`,
983
+ `- Advisory signals/labels from selection signals (not authority): ${advisoryLabels.length > 0 ? advisoryLabels.map(formatInline).join(", ") : "none supplied"}`,
984
+ `- Advisory constraints (not authority): ${advisoryConstraints.length > 0 ? advisoryConstraints.map(formatInline).join("; ") : "none supplied"}`,
985
+ `- Stale/low-confidence warnings: ${warnings.length > 0 ? warnings.map(formatInline).join("; ") : "none supplied"}`,
986
+ `- Semantic selection signals used: ${semanticSignals.length}`,
987
+ ...semanticSignals.map((signal) => ` - ${formatInline(signal)}`)
988
+ ];
989
+ }
990
+ function renderActionRoute(contextPlan, contextPacket, agentWorkBrief) {
991
+ const actionRoute = agentWorkBrief?.actionRoute ?? contextPacket?.links?.actionRoute ?? contextPlan?.actionRoute;
992
+ return renderActionRouteSummaryMarkdown(actionRoute);
993
+ }
994
+ function renderPlannerGraphAdvisory(advisory) {
995
+ if (!advisory)
996
+ return [];
997
+ return [
998
+ "## Planner graph advisory",
999
+ `- ${PLANNER_HANDOFF_GRAPH_ADVISORY_REQUIRED_COPY}`,
1000
+ `- Source: ${formatInline(advisory.source)}; basis: ${formatInline(advisory.basis)}`,
1001
+ `- Recommended mode: ${formatInline(String(advisory.recommendedGraphMode ?? advisory.recommendedMode ?? "unspecified"))}`,
1002
+ `- Selected mode: ${formatInline(String(advisory.selectedGraphMode ?? advisory.selectedMode ?? "unspecified"))}`,
1003
+ `- Policy blockers: ${advisory.policyBlockers.length > 0 ? advisory.policyBlockers.map((blocker) => formatInline(String(blocker))).join(", ") : "none"}`,
1004
+ `- Memgraph allowed by this handoff: ${advisory.executionPolicy.memgraphAllowed}`,
1005
+ `- Depth5 default: ${advisory.depthPolicy.depth5Default}`,
1006
+ `- Depth5 allowed: ${advisory.depthPolicy.depth5Allowed}`,
1007
+ `- Synapse prediction input allowed: ${advisory.executionPolicy.synapsePredictionInputAllowed}`,
1008
+ `- Production defaults changed: ${advisory.executionPolicy.productionDefaultsChanged}`,
1009
+ ""
1010
+ ];
1011
+ }
1012
+ function renderExactRefs(contextPlan, contextPacket, agentWorkBrief) {
1013
+ const exactRefs = contextPlan?.exactRefs ?? [];
1014
+ const sourceRefs = uniqueStrings([...contextPacket?.sourceRefs ?? [], ...formatRefIds(agentWorkBrief?.sourceRefs ?? [])]);
1015
+ const evidenceRefs = uniqueStrings([
1016
+ ...contextPacket?.evidenceRefs ?? [],
1017
+ ...formatRefIds(agentWorkBrief?.evidenceRefs ?? [])
1018
+ ]);
1019
+ const receiptRefs = uniqueStrings([
1020
+ ...contextPacket?.receiptRefs ?? [],
1021
+ ...formatRefIds(agentWorkBrief?.receiptRefs ?? [])
1022
+ ]);
1023
+ const serviceConnectionIds = uniqueStrings([
1024
+ ...contextPlan?.serviceConnectionIds ?? [],
1025
+ ...contextPacket?.serviceConnectionIds ?? [],
1026
+ ...agentWorkBrief?.serviceConnectionIds ?? []
1027
+ ]);
1028
+ const serviceConnectionRefs = formatRefIds(agentWorkBrief?.serviceConnectionRefs ?? []);
1029
+ return [
1030
+ `- Exact refs: ${exactRefs.length}`,
1031
+ ...renderRefList(exactRefs),
1032
+ `- Source refs: ${sourceRefs.length}${sourceRefs.length > 0 ? ` (${sourceRefs.map(formatInline).join(", ")})` : ""}`,
1033
+ `- Evidence refs: ${evidenceRefs.length}${evidenceRefs.length > 0 ? ` (${evidenceRefs.map(formatInline).join(", ")})` : ""}`,
1034
+ `- Receipt refs: ${receiptRefs.length}${receiptRefs.length > 0 ? ` (${receiptRefs.map(formatInline).join(", ")})` : ""}`,
1035
+ `- Service connection ids: ${serviceConnectionIds.length}${serviceConnectionIds.length > 0 ? ` (${serviceConnectionIds.map(formatInline).join(", ")})` : ""}`,
1036
+ `- Service connection refs: ${serviceConnectionRefs.length}${serviceConnectionRefs.length > 0 ? ` (${serviceConnectionRefs.map(formatInline).join(", ")})` : ""}`,
1037
+ "- Service connection evidence is advisory and grants no authority unless separately promoted by governance."
1038
+ ];
1039
+ }
1040
+ function renderGuardrails(contextPlan, contextPacket, agentWorkBrief) {
1041
+ return [
1042
+ "- Context is advisory and grants no authority.",
1043
+ "- Do not mutate canon from this handoff alone; canonical changes require explicit approval and gates.",
1044
+ "- Do not perform hidden execution; execution requires an explicit path and receipt trail.",
1045
+ `- Explicit refs required: ${contextPlan?.constraints.requireExplicitRefs ?? true}`,
1046
+ `- Project search allowed by plan: ${contextPlan?.allowProjectSearch ?? false}`,
1047
+ `- Context packet write mode: ${contextPacket?.guardrails?.writeMode ?? "report_only_no_write"}`,
1048
+ `- Working set grants authority: ${agentWorkBrief?.guardrails.workingSetGrantsAuthority ?? false}`
1049
+ ];
1050
+ }
1051
+ function renderReceipts(receipts) {
1052
+ if (receipts.length === 0)
1053
+ return ["- None supplied."];
1054
+ return receipts.flatMap((receipt) => [
1055
+ `- ${formatInline(receipt.receiptId)}: ${receipt.status}; blast radius ${receipt.safetySummary.blastRadiusStatus}; changed files ${receipt.safetySummary.changedFileCount}; out of scope ${receipt.safetySummary.outOfScopeFileCount}; denied ${receipt.safetySummary.deniedFileCount}`,
1056
+ ` - Traceability flags: ${receipt.safetySummary.traceabilityFlags.length > 0 ? receipt.safetySummary.traceabilityFlags.map(formatInline).join(", ") : "none"}`,
1057
+ ` - Warnings: ${receipt.warnings.length > 0 ? receipt.warnings.map(formatInline).join("; ") : "none"}`,
1058
+ ` - Errors: ${receipt.errors.length > 0 ? receipt.errors.map(formatInline).join("; ") : "none"}`
1059
+ ]);
1060
+ }
1061
+ function renderOpenQuestions(contextPacket) {
1062
+ const questions = contextPacket?.openQuestions ?? [];
1063
+ if (questions.length === 0)
1064
+ return ["- None supplied."];
1065
+ return questions.map((question) => `- ${formatInline(question)}`);
1066
+ }
1067
+ function renderNextAgentInstructions() {
1068
+ return [
1069
+ "- Start by verifying the worktree state and preserving unrelated changes.",
1070
+ "- Use the refs and files above as the initial context, then ask before broadening scope.",
1071
+ "- Keep changes within the stated scope and leave a receipt trail for execution or canon changes."
1072
+ ];
1073
+ }
1074
+ function renderPathList(label, paths) {
1075
+ if (paths.length === 0)
1076
+ return [`- ${label}: none supplied`];
1077
+ return [`- ${label}: ${paths.length}`, ...uniqueStrings(paths).map((path) => ` - ${formatInline(path)}`)];
1078
+ }
1079
+ function renderSliceList(contextPacket) {
1080
+ const slices = contextPacket?.contextSlices ?? [];
1081
+ if (slices.length === 0)
1082
+ return ["- Slices: none supplied"];
1083
+ return [
1084
+ `- Slices: ${slices.length}`,
1085
+ ...slices.map((slice) => {
1086
+ const range = slice.startLine && slice.endLine ? `:${slice.startLine}-${slice.endLine}` : "";
1087
+ return ` - ${formatInline(`${slice.path}${range}`)} (${slice.role}, ${slice.contentMode ?? "path_only"})`;
1088
+ })
1089
+ ];
1090
+ }
1091
+ var LOW_CONFIDENCE_THRESHOLD = 0.7;
1092
+ var SEMANTIC_SIGNAL_PREFIX = "semantic_label:v1:";
1093
+ function semanticSelectionSignals2(contextPacket) {
1094
+ return uniqueStrings((contextPacket?.contextSlices ?? []).flatMap((slice) => slice.selectionSignals ?? []).filter((signal) => signal.startsWith(SEMANTIC_SIGNAL_PREFIX) && parseSemanticSelectionSignal(signal) !== undefined));
1095
+ }
1096
+ function parseSemanticSelectionSignal(signal) {
1097
+ const parts = signal.split(":");
1098
+ if (parts[0] !== "semantic_label" || parts[1] !== "v1" || parts.length < 5)
1099
+ return;
1100
+ const [, , source, authority, kind] = parts;
1101
+ if (!source || !authority || !kind)
1102
+ return;
1103
+ if (kind === "label") {
1104
+ return { source, authority, kind, namespace: parts[5], key: parts[6], value: parts.slice(7).join(":") };
1105
+ }
1106
+ return { source, authority, kind, value: parts.slice(5).join(":") };
1107
+ }
1108
+ function formatParsedSemanticSignal(signal) {
1109
+ if (signal.kind === "label") {
1110
+ const namespace = signal.namespace ?? "unknown";
1111
+ const key = signal.key ?? "unknown";
1112
+ const value2 = signal.value ?? "unknown";
1113
+ return `${namespace}.${key}=${value2} (${signal.source}, ${signal.authority})`;
1114
+ }
1115
+ const value = signal.value ? `:${signal.value}` : "";
1116
+ return `${signal.kind}${value} (${signal.source}, ${signal.authority})`;
1117
+ }
1118
+ function renderCoveredSurfaces(contextPacket, agentWorkBrief) {
1119
+ if (!contextPacket)
1120
+ return renderWorkBriefCoveredSurfaces(agentWorkBrief);
1121
+ const roleCounts = new Map;
1122
+ for (const slice of contextPacket.contextSlices) {
1123
+ const role = `slice:${slice.role}`;
1124
+ roleCounts.set(role, (roleCounts.get(role) ?? 0) + 1);
1125
+ }
1126
+ const contextSurfaces = [
1127
+ countSurface("primary_files", contextPacket.primaryEditFiles.length),
1128
+ ...Array.from(roleCounts.entries()).map(([role, count]) => `${role} ${count}`),
1129
+ countSurface("docs", contextPacket.affectedDocs.length),
1130
+ countSurface("tests", contextPacket.affectedTests.length),
1131
+ countSurface("config", contextPacket.configFiles.length)
1132
+ ].filter(isDefined);
1133
+ return contextSurfaces.length > 0 ? contextSurfaces : renderWorkBriefCoveredSurfaces(agentWorkBrief);
1134
+ }
1135
+ function countSurface(label, count) {
1136
+ return count > 0 ? `${label} ${count}` : undefined;
1137
+ }
1138
+ function renderWorkBriefCoveredSurfaces(agentWorkBrief) {
1139
+ const paths = uniqueStrings([
1140
+ ...(agentWorkBrief?.contextPlan.exactRefs ?? []).map(refPathFromActionRef).filter(isDefined),
1141
+ ...(agentWorkBrief?.sourceRefs ?? []).map(refPathFromActionRef).filter(isDefined),
1142
+ ...(agentWorkBrief?.evidenceRefs ?? []).map(refPathFromActionRef).filter(isDefined),
1143
+ ...(agentWorkBrief?.receiptRefs ?? []).map(refPathFromActionRef).filter(isDefined)
1144
+ ]);
1145
+ if (paths.length === 0)
1146
+ return [];
1147
+ return [
1148
+ countSurface("backend_code", paths.filter(isBackendCodePath).length),
1149
+ countSurface("ui_surface", paths.filter(isUiSurfacePath).length),
1150
+ countSurface("tests", paths.filter(isTestPath).length),
1151
+ countSurface("docs", paths.filter(isDocPath).length),
1152
+ countSurface("config", paths.filter(isConfigPath).length),
1153
+ countSurface("mcp_server", paths.filter((path) => path.includes("packages/mcp-server/")).length)
1154
+ ].filter(isDefined);
1155
+ }
1156
+ function refPathFromActionRef(ref) {
1157
+ const metadataPath = ref.metadata?.["path"];
1158
+ if (typeof metadataPath === "string" && metadataPath.length > 0)
1159
+ return metadataPath;
1160
+ if (looksLikePath(ref.id))
1161
+ return ref.id;
1162
+ if (ref.label && looksLikePath(ref.label))
1163
+ return ref.label;
1164
+ return;
1165
+ }
1166
+ function looksLikePath(value) {
1167
+ return value.includes("/") || value.endsWith(".ts") || value.endsWith(".tsx") || value.endsWith(".md") || value.endsWith(".json");
1168
+ }
1169
+ function isBackendCodePath(path) {
1170
+ return path.startsWith("convex/") || path.startsWith("packages/core/") || path.startsWith("packages/state/");
1171
+ }
1172
+ function isUiSurfacePath(path) {
1173
+ return path.startsWith("apps/") || path.startsWith("packages/ui/") || path.endsWith(".tsx");
1174
+ }
1175
+ function isTestPath(path) {
1176
+ return path.includes("convex-tests/") || path.includes(".test.") || path.includes(".spec.");
1177
+ }
1178
+ function isDocPath(path) {
1179
+ return path.startsWith("docs/") || path.endsWith(".md") || path.includes("/README.");
1180
+ }
1181
+ function isConfigPath(path) {
1182
+ return path.endsWith("package.json") || path.endsWith("tsconfig.json") || path.endsWith("vite.config.ts");
1183
+ }
1184
+ function advisoryConstraintSummary(contextPacket) {
1185
+ return uniqueStrings([
1186
+ ...contextPacket?.constraints ?? [],
1187
+ ...contextPacket?.guardrails?.reportOnly ? ["report_only"] : [],
1188
+ ...contextPacket?.guardrails?.sourceContextGrantsNoAuthority ? ["source_context_grants_no_authority"] : [],
1189
+ ...contextPacket?.guardrails?.contextDoesNotMutateCanon ? ["context_does_not_mutate_canon"] : []
1190
+ ]);
1191
+ }
1192
+ function staleOrLowConfidenceWarnings(contextPacket) {
1193
+ if (!contextPacket)
1194
+ return [];
1195
+ const warnings = [];
1196
+ for (const fileRef of fileRefsWithLabels(contextPacket)) {
1197
+ if (isLowConfidence(fileRef.ref.confidence)) {
1198
+ warnings.push(`${fileRef.label} ${fileRef.ref.path} confidence ${formatConfidence(fileRef.ref.confidence)}`);
1199
+ }
1200
+ }
1201
+ for (const slice of contextPacket.contextSlices) {
1202
+ if (!isLowConfidence(slice.confidence))
1203
+ continue;
1204
+ const range = slice.startLine && slice.endLine ? `:${slice.startLine}-${slice.endLine}` : "";
1205
+ warnings.push(`slice ${slice.path}${range} confidence ${formatConfidence(slice.confidence)}`);
1206
+ }
1207
+ return warnings;
1208
+ }
1209
+ function fileRefsWithLabels(contextPacket) {
1210
+ return [
1211
+ ...contextPacket.primaryEditFiles.map((ref) => ({ label: "primary_file", ref })),
1212
+ ...contextPacket.affectedDocs.map((ref) => ({ label: "doc", ref })),
1213
+ ...contextPacket.affectedTests.map((ref) => ({ label: "test", ref })),
1214
+ ...contextPacket.configFiles.map((ref) => ({ label: "config", ref }))
1215
+ ];
1216
+ }
1217
+ function isLowConfidence(confidence) {
1218
+ return typeof confidence === "number" && Number.isFinite(confidence) && confidence < LOW_CONFIDENCE_THRESHOLD;
1219
+ }
1220
+ function formatConfidence(confidence) {
1221
+ return typeof confidence === "number" && Number.isFinite(confidence) ? confidence.toFixed(2) : "unknown";
1222
+ }
1223
+ function renderRefList(refs) {
1224
+ if (refs.length === 0)
1225
+ return [];
1226
+ return refs.map((ref) => ` - ${formatInline(`${ref.kind}:${ref.id}${ref.label ? ` (${ref.label})` : ""}`)}`);
1227
+ }
1228
+ function formatRefIds(refs) {
1229
+ return refs.map((ref) => `${ref.kind}:${ref.id}`);
1230
+ }
1231
+ function isDefined(value) {
1232
+ return value !== undefined;
1233
+ }
1234
+ function uniqueStrings(values) {
1235
+ return Array.from(new Set(values.filter((value) => value.length > 0)));
1236
+ }
1237
+ function formatInline(value) {
1238
+ return value.replace(/\n/g, " ").trim();
1239
+ }
1240
+ export {
1241
+ isGovernanceFeedbackCommand,
1242
+ isCorrectionFeedbackCommand,
1243
+ isBriefItemV2,
1244
+ feedbackCommandRecordsPositiveEvidence,
1245
+ defaultFeedbackScopeForCommand,
1246
+ contextPlanIntentForFeedbackCommand,
1247
+ buildTaskBriefV1FromActionItems,
1248
+ buildDeterministicWhyV1,
1249
+ buildDeterministicWhyForBriefItem,
1250
+ buildContextPlanV1,
1251
+ buildContextPlanForBriefItem,
1252
+ buildBriefItemV2,
1253
+ buildBriefItemRelevanceV1,
1254
+ buildAgentWorkBriefV1,
1255
+ buildAgentHandoffMarkdownV1,
1256
+ briefCommandsForItem,
1257
+ activityTypeForFeedbackCommand,
1258
+ TASK_BRIEF_STATES_V1,
1259
+ TASK_BRIEF_READ_MODEL_VERSION,
1260
+ SESSION_ACTIVITY_TYPES_V1,
1261
+ FEEDBACK_COMMANDS_V1,
1262
+ DETERMINISTIC_WHY_SCHEMA_VERSION,
1263
+ DETERMINISTIC_WHY_COPY_VERSION,
1264
+ DETERMINISTIC_WHY_BULLET_KINDS_V1,
1265
+ CONTEXT_DEPTHS,
1266
+ BRIEF_SURFACES_V1,
1267
+ BRIEF_SECTION_KINDS_V1,
1268
+ BRIEF_SCHEMA_VERSION,
1269
+ BRIEF_ITEM_RELEVANCE_SOURCES_V1,
1270
+ BRIEF_ITEM_READ_MODEL_VERSION_V2,
1271
+ BRIEF_ITEM_KINDS_V1,
1272
+ BRIEF_COMMAND_LABELS_V1,
1273
+ BRIEF_COMMAND_DESCRIPTORS_V1,
1274
+ BRIEF_COMMAND_DEFAULT_SCOPES_V1,
1275
+ AGENT_HANDOFF_MARKDOWN_SCHEMA_VERSION
1276
+ };