@adhdev/mesh-shared 1.0.60-rc.4 → 1.0.60-rc.40

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 (39) hide show
  1. package/dist/index.d.ts +10 -0
  2. package/dist/index.js +2758 -17
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +2435 -17
  5. package/dist/index.mjs.map +1 -1
  6. package/dist/mesh-tool-names.d.ts +2 -2
  7. package/dist/mesh-vocabulary.d.ts +70 -0
  8. package/dist/mission-brief.d.ts +62 -0
  9. package/dist/outbound-message.d.ts +202 -0
  10. package/dist/path-ownership.d.ts +101 -0
  11. package/dist/protocol/daemon-server.d.ts +388 -0
  12. package/dist/protocol/dashboard-daemon-p2p.d.ts +212 -0
  13. package/dist/protocol/dashboard-server.d.ts +240 -0
  14. package/dist/protocol/envelope.d.ts +55 -0
  15. package/dist/protocol/index.d.ts +15 -0
  16. package/dist/session-launch.d.ts +113 -0
  17. package/dist/session-status.d.ts +61 -0
  18. package/dist/turn-evidence.d.ts +400 -0
  19. package/dist/turn-ipc.d.ts +974 -0
  20. package/dist/worker-protocol.d.ts +69 -0
  21. package/dist/ws-protocol.d.ts +71 -41
  22. package/package.json +1 -1
  23. package/src/index.ts +10 -0
  24. package/src/mesh-tool-names.ts +0 -1
  25. package/src/mesh-vocabulary.ts +98 -0
  26. package/src/mission-brief.ts +153 -0
  27. package/src/outbound-message.ts +320 -0
  28. package/src/path-ownership.ts +271 -0
  29. package/src/protocol/daemon-server.ts +552 -0
  30. package/src/protocol/dashboard-daemon-p2p.ts +272 -0
  31. package/src/protocol/dashboard-server.ts +340 -0
  32. package/src/protocol/envelope.ts +75 -0
  33. package/src/protocol/index.ts +16 -0
  34. package/src/session-launch.ts +247 -0
  35. package/src/session-status.ts +140 -0
  36. package/src/turn-evidence.ts +549 -0
  37. package/src/turn-ipc.ts +2231 -0
  38. package/src/worker-protocol.ts +142 -0
  39. package/src/ws-protocol.ts +102 -93
@@ -0,0 +1,549 @@
1
+ /**
2
+ * turn-evidence — the ONE vocabulary for "what happened to a turn".
3
+ *
4
+ * Wiring-unification Phase C1 (docs/design/2026-09-23-wiring-unification.md §5).
5
+ *
6
+ * Every producer that today decides "done" on its own (completion flush, stall
7
+ * rescue, reconcile synthesis, MCP probes, worker report tools, …) instead
8
+ * submits one of these evidence records to the turn ledger, whose pure reducer
9
+ * is the only authority for a turn's state. Worker daemons and the MCP server
10
+ * build them, so the types live here (a dependency-free leaf).
11
+ *
12
+ * CONTENT-FREE BY CONSTRUCTION
13
+ * ----------------------------
14
+ * Evidence crosses machines (seqscribe `mesh.<id>.events` replication) and must
15
+ * never carry anything a user or an agent wrote. Every field is one of: an
16
+ * identifier, a closed enum, a boolean, a number, or a `SummaryRef` — a pointer
17
+ * `{topic, writer, seq}` to a content-class topic entry (`mesh.<id>.handoff`)
18
+ * where the text actually lives. `TURN_EVIDENCE_FIELD_SPECS` declares the class
19
+ * of every field of every member (the compiler forces it to stay total and
20
+ * exact), the runtime guard validates against it, and a test walks it to prove
21
+ * no free-text field exists.
22
+ */
23
+
24
+ import { WORKER_BRANCH_STATES, WORKER_REPORT_OUTCOMES, type WorkerBranchState, type WorkerReportOutcome } from './mesh-vocabulary'
25
+ import { SESSION_STATUSES, type SessionStatus } from './session-status'
26
+ import { SEND_REFUSAL_REASONS, type SendRefusal } from './outbound-message'
27
+
28
+ // ─── closed vocabularies ─────────────────────────────────────────────────
29
+
30
+ /** Protocol version stamped on every `mesh.<id>.events` entry written by the turn ledger. */
31
+ export const MESH_TOPIC_PROTOCOL_VERSION = 2 as const
32
+
33
+ export const EVIDENCE_SOURCE_IDS = [
34
+ 'fsm_edge', 'short_gen_inline', 'completion_flush_genuine', 'completion_flush_weak',
35
+ 'monitor_final_summary', 'pre_cleanup_transcript', 'stall_transcript', 'startup_grace_collapse',
36
+ 'acp_prompt_response', 'cdp_state', 'approval_gate', 'modal_button',
37
+ 'mesh_stall_watchdog', 'status_monitor', 'pty_exit', 'provider_error',
38
+ 'coordinator_probe', 'mcp_probe', 'worker_tool', 'dispatch', 'input_service',
39
+ 'operator', 'intentional_cleanup', 'scheduler', 'git_probe', 'session_registry',
40
+ ] as const
41
+ export type EvidenceSourceId = typeof EVIDENCE_SOURCE_IDS[number]
42
+
43
+ export const TURN_SCOPES = ['mesh_queue', 'mesh_direct', 'plain'] as const
44
+ export type TurnScope = typeof TURN_SCOPES[number]
45
+
46
+ /**
47
+ * Refusals (D1 `SendRefusal`, owned by ./outbound-message) that mean the target
48
+ * can never take this dispatch, so the attempt is reclaimed (R3). Every other
49
+ * refusal is retried by the sender and only recorded.
50
+ */
51
+ export const RECLAIMING_SEND_REFUSALS = ['session_exited', 'no_target', 'unsupported_input'] as const satisfies readonly SendRefusal[]
52
+ export type ReclaimingSendRefusal = typeof RECLAIMING_SEND_REFUSALS[number]
53
+
54
+ export const DELIVERY_OUTCOMES = ['delivered', 'queued'] as const
55
+ export type DeliveryOutcome = typeof DELIVERY_OUTCOMES[number]
56
+ export const DELIVERY_VIAS = ['local', 'p2p'] as const
57
+ export type DeliveryVia = typeof DELIVERY_VIAS[number]
58
+
59
+ export const DISPATCH_FAILURE_REASONS = ['worker_absent', 'transport_error', 'spawn_failed', 'rejected_by_worker', 'timeout'] as const
60
+ export type DispatchFailureReason = typeof DISPATCH_FAILURE_REASONS[number]
61
+
62
+ export const CONSUME_PROFILES = ['default', 'native_source'] as const
63
+ export type ConsumeProfile = typeof CONSUME_PROFILES[number]
64
+
65
+ export const SESSION_REBOUND_REASONS = ['restart', 'live_holder'] as const
66
+ export type SessionReboundReason = typeof SESSION_REBOUND_REASONS[number]
67
+
68
+ export const SUSPENSION_MODALS = ['approval', 'choice'] as const
69
+ export type SuspensionModal = typeof SUSPENSION_MODALS[number]
70
+ export const SUSPENSION_RESOLUTIONS = ['approved', 'rejected', 'answered'] as const
71
+ export type SuspensionResolution = typeof SUSPENSION_RESOLUTIONS[number]
72
+ export const SUSPENSION_RESOLUTION_VIAS = ['modal_button', 'auto_approve', 'prompt_answer'] as const
73
+ export type SuspensionResolutionVia = typeof SUSPENSION_RESOLUTION_VIAS[number]
74
+
75
+ export const TURN_END_STRENGTHS = ['genuine', 'weak'] as const
76
+ export type TurnEndStrength = typeof TURN_END_STRENGTHS[number]
77
+
78
+ /** Why a provider-side weak end was released (was free text `blockReason`). */
79
+ export const TURN_END_BLOCK_REASONS = [
80
+ 'missing_final_assistant', 'finalization_timeout', 'terminal_block_hard_cap', 'decoupled_completion',
81
+ ] as const
82
+ export type TurnEndBlockReason = typeof TURN_END_BLOCK_REASONS[number]
83
+
84
+ export const NATIVE_TURN_OUTCOMES = ['completed', 'aborted'] as const
85
+ export type NativeTurnOutcome = typeof NATIVE_TURN_OUTCOMES[number]
86
+
87
+ export const LIVENESS_RESULTS = ['alive', 'unknown', 'read_failed', 'dead'] as const
88
+ export type LivenessResult = typeof LIVENESS_RESULTS[number]
89
+
90
+ export const PROVIDER_FAILURES = ['auth_failed', 'billing_failed'] as const
91
+ export type ProviderFailure = typeof PROVIDER_FAILURES[number]
92
+
93
+ /**
94
+ * `daemon_restart` (wiring-unification follow-up, design §5): a boot-time
95
+ * reconciliation observes this for a plain attempt whose session is gone
96
+ * after a restart — the daemon never saw the session's own exit, so it is
97
+ * not `provider_error`/`adapter_error`/etc.; it is the daemon itself
98
+ * reporting "this session no longer exists".
99
+ */
100
+ export const SESSION_ERROR_REASONS = ['provider_error', 'adapter_error', 'spawn_failed', 'auth_failed', 'billing_failed', 'unknown', 'daemon_restart'] as const
101
+ export type SessionErrorReason = typeof SESSION_ERROR_REASONS[number]
102
+
103
+ export const CANCEL_REASONS = ['operator_cancel', 'intentional_cleanup', 'task_removed', 'mission_abandoned', 'superseded'] as const
104
+ export type CancelReason = typeof CANCEL_REASONS[number]
105
+
106
+ export const OPERATOR_STATUSES = ['completed', 'failed'] as const
107
+ export type OperatorStatus = typeof OPERATOR_STATUSES[number]
108
+ export const OPERATOR_STATUS_REASONS = ['operator_update', 'refine_terminal', 'validation_terminal'] as const
109
+ export type OperatorStatusReason = typeof OPERATOR_STATUS_REASONS[number]
110
+
111
+ export const COORDINATOR_ACK_OUTCOMES = ['delivered', 'queued', 'duplicate'] as const
112
+ export type CoordinatorAckOutcome = typeof COORDINATOR_ACK_OUTCOMES[number]
113
+
114
+ /** Observed status as a no-progress monitor saw it (canonical session status or `unknown`). */
115
+ export const NO_PROGRESS_OBSERVED_STATUSES = [...SESSION_STATUSES, 'unknown'] as const
116
+ export type NoProgressObservedStatus = SessionStatus | 'unknown'
117
+
118
+ /**
119
+ * Reasons a turn hold exists. Holds are attempt-scoped only (C2: delivery-side
120
+ * waits are consumer deferral on the `turn.deliver` cursor, not hold rows).
121
+ */
122
+ export const HOLD_REASONS = [
123
+ 'await_delivery', 'await_consume', 'await_turn', 'liveness', 'hard_ceiling',
124
+ 'live_pending', 'transcript_quiet', 'weak_candidate', 'suspension_before_consumed',
125
+ ] as const
126
+ export type HoldReason = typeof HOLD_REASONS[number]
127
+
128
+ export const TURN_OUTCOMES = ['completed', 'failed', 'cancelled'] as const
129
+ export type TurnOutcome = typeof TURN_OUTCOMES[number]
130
+
131
+ export const COMMIT_STRENGTHS = ['genuine', 'weak', 'tool_report', 'operator'] as const
132
+ export type CommitStrength = typeof COMMIT_STRENGTHS[number]
133
+
134
+ /** Every terminal or reclaim reason the ledger writes. Closed: no free-text reasons. */
135
+ export const TURN_REASONS = [
136
+ // commits
137
+ 'turn_end', 'weak_end_confirmed', 'transcript_final', 'worker_reported',
138
+ 'finalization_timeout_no_response', 'session_error', 'provider_auth_failed', 'provider_billing_failed',
139
+ 'operator_cancel', 'intentional_cleanup', 'task_removed', 'mission_abandoned', 'superseded',
140
+ 'operator_update', 'refine_terminal', 'validation_terminal',
141
+ 'hard_ceiling', 'reclaim_budget_exhausted', 'hollow_max_retries', 'migration_orphan',
142
+ // reclaims (generation + 1)
143
+ 'dispatch_refused_session_exited', 'dispatch_refused_no_target', 'dispatch_refused_unsupported_input', 'dispatch_failed',
144
+ 'session_exit', 'session_exit_before_turn', 'session_dead', 'hollow_completion',
145
+ 'assigned_stranded_dispatch_unconfirmed', 'delivered_not_consumed_redrive', 'delivered_no_turn_deadline',
146
+ ] as const
147
+ export type TurnReason = typeof TURN_REASONS[number]
148
+
149
+ /**
150
+ * What a `turn.notify` entry tells a coordinator.
151
+ *
152
+ * `late_completion` (C1 R27, owner revision 2026-09-23): a superseded
153
+ * generation finished while the current one was already running; the
154
+ * coordinator decides whether to salvage it (the entry carries the g−1
155
+ * summary as its append `ref`). `mesh_event`: a non-turn coordinator notice
156
+ * (refine terminal, worktree bootstrap, …) whose text lives only in the
157
+ * owner's local `turn_events.payload_json` and is rendered at deliver time.
158
+ */
159
+ export const NOTIFY_KINDS = [
160
+ 'completed', 'failed', 'cancelled', 'stopped', 'approval', 'choice', 'approval_resolved',
161
+ 'candidate', 'no_progress', 'progress', 'late_completion', 'mesh_event',
162
+ ] as const
163
+ export type NotifyKind = typeof NOTIFY_KINDS[number]
164
+
165
+ // ─── shared shapes ───────────────────────────────────────────────────────
166
+
167
+ export interface TurnAttemptRef { attemptId: string; generation: number }
168
+
169
+ /**
170
+ * Pointer to text that lives in a content-class topic entry (`mesh.<id>.handoff`).
171
+ * Text never travels inside evidence; the deliver side renders it from the ref.
172
+ */
173
+ export interface SummaryRef { topic: string; writer: string; seq: number }
174
+
175
+ /** Live-state observations that make a transcript end premature (admission input). */
176
+ export interface LiveTurnPending { modal: boolean; adapterPending: boolean; trailingTool: boolean; newestActivityAt?: number }
177
+
178
+ /** Structural copy of daemon-core's `CoordinatorIdentity` (this package cannot import daemon-core). */
179
+ export interface EvidenceCoordinatorIdentity { daemonId: string; coordinatorRunId: string; sessionId?: string }
180
+
181
+ export interface NativeTurnMarkerRef { outcome: NativeTurnOutcome; turnId?: string }
182
+
183
+ export interface EvidenceEnvelope {
184
+ /** Stable id of this observation; dedupe key across republish/replication. */
185
+ eventId: string
186
+ /** Producer clock, epoch ms. */
187
+ at: number
188
+ source: EvidenceSourceId
189
+ /** The session that produced / is the subject of the observation. */
190
+ sessionId: string
191
+ attemptRef?: TurnAttemptRef
192
+ /** Only when attemptRef is absent (legacy relay / MCP probe). */
193
+ taskId?: string
194
+ /** Daemon id that observed it. */
195
+ observedBy: string
196
+ }
197
+
198
+ /** Kind-specific bodies. `TurnEvidence = EvidenceEnvelope & TurnEvidenceBody`. */
199
+ export type TurnEvidenceBody =
200
+ // ── dispatch / delivery ──
201
+ | { kind: 'dispatch_accepted'; scope: TurnScope; messageId: string; meshId?: string; nodeId?: string; providerType?: string
202
+ attemptNo?: number; dispatchNonce?: number; consumeProfile?: ConsumeProfile; maxTaskRetries?: number
203
+ coordinator?: EvidenceCoordinatorIdentity }
204
+ | { kind: 'delivered'; messageId: string; outcome: DeliveryOutcome; via: DeliveryVia }
205
+ | { kind: 'delivery_refused'; messageId: string; reason: SendRefusal }
206
+ | { kind: 'dispatch_failed'; workerAbsent: boolean; reason: DispatchFailureReason }
207
+ | { kind: 'duplicate_dispatch_refusal'; holderSessionId: string; holderAttemptId?: string }
208
+ | { kind: 'session_rebound'; toSessionId: string; reason: SessionReboundReason }
209
+ // ── worker turn lifecycle ──
210
+ | { kind: 'turn_started'; retro: boolean }
211
+ | { kind: 'suspension'; modal: SuspensionModal; modalKey?: string }
212
+ | { kind: 'suspension_resolved'; resolution: SuspensionResolution; via: SuspensionResolutionVia }
213
+ | { kind: 'turn_end'; strength: TurnEndStrength; afterFinalizationTimeout?: boolean; hollow?: boolean; summary?: SummaryRef
214
+ blockReason?: TurnEndBlockReason; releasedByHardCap?: boolean; nativeOutcome?: NativeTurnOutcome; live?: LiveTurnPending }
215
+ | { kind: 'transcript_final'; selfAttributing: boolean; nativeRead: boolean; nativeMarker?: NativeTurnMarkerRef
216
+ live: LiveTurnPending; summary?: SummaryRef; messageAt?: number }
217
+ | { kind: 'transcript_activity'; newestActivityAt: number }
218
+ | { kind: 'no_progress'; stalledMs: number; observedStatus: NoProgressObservedStatus; finalAssistantPresent: boolean }
219
+ | { kind: 'liveness'; result: LivenessResult }
220
+ | { kind: 'process_exit'; exitCode: number | null; providerFailure?: ProviderFailure }
221
+ | { kind: 'session_error'; reason: SessionErrorReason }
222
+ // ── worker MCP (F2) ──
223
+ | { kind: 'worker_report'; outcome: WorkerReportOutcome; summary: SummaryRef; hasHandoffNotes: boolean
224
+ branchState?: WorkerBranchState; touchedFileCount?: number }
225
+ | { kind: 'worker_progress'; note?: SummaryRef }
226
+ // ── coordinator / operator ──
227
+ | { kind: 'git_side_effect'; dirty: boolean; commitsSinceDispatch: number; attributable: boolean }
228
+ | { kind: 'cancel'; reason: CancelReason }
229
+ | { kind: 'operator_status'; status: OperatorStatus; reason: OperatorStatusReason }
230
+ | { kind: 'coordinator_ack'; notify: NotifyKind; outcome: CoordinatorAckOutcome }
231
+ // ── scheduler-generated ──
232
+ | { kind: 'hold_expired'; holdId: string; reason: HoldReason }
233
+
234
+ export type TurnEvidence = EvidenceEnvelope & TurnEvidenceBody
235
+ export type TurnEvidenceKind = TurnEvidenceBody['kind']
236
+ export type TurnEvidenceOf<K extends TurnEvidenceKind> = EvidenceEnvelope & Extract<TurnEvidenceBody, { kind: K }>
237
+
238
+ // ─── field-class registry (drives the guard and the content-free test) ────
239
+
240
+ /**
241
+ * The class of every declared field. There is deliberately NO free-text class:
242
+ * `id` strings are length-bounded and whitespace-free, so prose cannot be
243
+ * smuggled through an identifier slot either.
244
+ */
245
+ export type EvidenceFieldSpec =
246
+ | { t: 'id'; optional?: true }
247
+ | { t: 'enum'; values: readonly string[]; optional?: true }
248
+ | { t: 'bool'; optional?: true }
249
+ | { t: 'int'; optional?: true; nullable?: true }
250
+ | { t: 'ms'; optional?: true }
251
+ | { t: 'summary_ref'; optional?: true }
252
+ | { t: 'attempt_ref'; optional?: true }
253
+ | { t: 'live'; optional?: true }
254
+ | { t: 'native_marker'; optional?: true }
255
+ | { t: 'coordinator'; optional?: true }
256
+
257
+ type FieldsOf<K extends TurnEvidenceKind> = Exclude<keyof Extract<TurnEvidenceBody, { kind: K }>, 'kind'>
258
+ /** Exact per-kind registry: a missing or extra field fails to compile. */
259
+ export type TurnEvidenceFieldSpecs = { readonly [K in TurnEvidenceKind]: { readonly [F in FieldsOf<K>]-?: EvidenceFieldSpec } }
260
+
261
+ const id = { t: 'id' } as const
262
+ const idOpt = { t: 'id', optional: true } as const
263
+ const bool = { t: 'bool' } as const
264
+ const boolOpt = { t: 'bool', optional: true } as const
265
+ const ms = { t: 'ms' } as const
266
+ const msOpt = { t: 'ms', optional: true } as const
267
+ const intOpt = { t: 'int', optional: true } as const
268
+ const en = (values: readonly string[]) => ({ t: 'enum', values }) as const
269
+ const enOpt = (values: readonly string[]) => ({ t: 'enum', values, optional: true }) as const
270
+
271
+ export const EVIDENCE_ENVELOPE_FIELD_SPECS: { readonly [F in keyof EvidenceEnvelope]-?: EvidenceFieldSpec } = {
272
+ eventId: id,
273
+ at: ms,
274
+ source: en(EVIDENCE_SOURCE_IDS),
275
+ sessionId: id,
276
+ attemptRef: { t: 'attempt_ref', optional: true },
277
+ taskId: idOpt,
278
+ observedBy: id,
279
+ }
280
+
281
+ export const TURN_EVIDENCE_FIELD_SPECS: TurnEvidenceFieldSpecs = {
282
+ dispatch_accepted: {
283
+ scope: en(TURN_SCOPES), messageId: id, meshId: idOpt, nodeId: idOpt, providerType: idOpt,
284
+ attemptNo: intOpt, dispatchNonce: intOpt, consumeProfile: enOpt(CONSUME_PROFILES), maxTaskRetries: intOpt,
285
+ coordinator: { t: 'coordinator', optional: true },
286
+ },
287
+ delivered: { messageId: id, outcome: en(DELIVERY_OUTCOMES), via: en(DELIVERY_VIAS) },
288
+ delivery_refused: { messageId: id, reason: en(SEND_REFUSAL_REASONS) },
289
+ dispatch_failed: { workerAbsent: bool, reason: en(DISPATCH_FAILURE_REASONS) },
290
+ duplicate_dispatch_refusal: { holderSessionId: id, holderAttemptId: idOpt },
291
+ session_rebound: { toSessionId: id, reason: en(SESSION_REBOUND_REASONS) },
292
+ turn_started: { retro: bool },
293
+ suspension: { modal: en(SUSPENSION_MODALS), modalKey: idOpt },
294
+ suspension_resolved: { resolution: en(SUSPENSION_RESOLUTIONS), via: en(SUSPENSION_RESOLUTION_VIAS) },
295
+ turn_end: {
296
+ strength: en(TURN_END_STRENGTHS), afterFinalizationTimeout: boolOpt, hollow: boolOpt,
297
+ summary: { t: 'summary_ref', optional: true }, blockReason: enOpt(TURN_END_BLOCK_REASONS),
298
+ releasedByHardCap: boolOpt, nativeOutcome: enOpt(NATIVE_TURN_OUTCOMES), live: { t: 'live', optional: true },
299
+ },
300
+ transcript_final: {
301
+ selfAttributing: bool, nativeRead: bool, nativeMarker: { t: 'native_marker', optional: true },
302
+ live: { t: 'live' }, summary: { t: 'summary_ref', optional: true }, messageAt: msOpt,
303
+ },
304
+ transcript_activity: { newestActivityAt: ms },
305
+ no_progress: { stalledMs: ms, observedStatus: en(NO_PROGRESS_OBSERVED_STATUSES), finalAssistantPresent: bool },
306
+ liveness: { result: en(LIVENESS_RESULTS) },
307
+ process_exit: { exitCode: { t: 'int', nullable: true }, providerFailure: enOpt(PROVIDER_FAILURES) },
308
+ session_error: { reason: en(SESSION_ERROR_REASONS) },
309
+ worker_report: {
310
+ outcome: en(WORKER_REPORT_OUTCOMES), summary: { t: 'summary_ref' }, hasHandoffNotes: bool,
311
+ branchState: enOpt(WORKER_BRANCH_STATES), touchedFileCount: intOpt,
312
+ },
313
+ worker_progress: { note: { t: 'summary_ref', optional: true } },
314
+ git_side_effect: { dirty: bool, commitsSinceDispatch: { t: 'int' }, attributable: bool },
315
+ cancel: { reason: en(CANCEL_REASONS) },
316
+ operator_status: { status: en(OPERATOR_STATUSES), reason: en(OPERATOR_STATUS_REASONS) },
317
+ coordinator_ack: { notify: en(NOTIFY_KINDS), outcome: en(COORDINATOR_ACK_OUTCOMES) },
318
+ hold_expired: { holdId: id, reason: en(HOLD_REASONS) },
319
+ }
320
+
321
+ export const TURN_EVIDENCE_KINDS = Object.keys(TURN_EVIDENCE_FIELD_SPECS) as readonly TurnEvidenceKind[]
322
+
323
+ /** Evidence kinds that, on their own, can end a turn (the ones R18/R19/R27 reason about). */
324
+ export const TERMINAL_CLASS_EVIDENCE_KINDS = [
325
+ 'turn_end', 'transcript_final', 'no_progress', 'worker_report', 'session_error', 'process_exit', 'cancel', 'operator_status',
326
+ ] as const satisfies readonly TurnEvidenceKind[]
327
+
328
+ // ─── guards ──────────────────────────────────────────────────────────────
329
+
330
+ /** Identifier shape: 1..256 chars, no whitespace or control characters. */
331
+ const IDENTIFIER_RE = /^[^\s\u0000-\u001f\u007f]{1,256}$/
332
+
333
+ function makeGuard<T extends readonly string[]>(values: T): (value: unknown) => value is T[number] {
334
+ const set: ReadonlySet<string> = new Set(values)
335
+ return (value: unknown): value is T[number] => typeof value === 'string' && set.has(value)
336
+ }
337
+
338
+ export const isEvidenceSourceId = makeGuard(EVIDENCE_SOURCE_IDS)
339
+ export const isTurnEvidenceKind = makeGuard(TURN_EVIDENCE_KINDS as readonly TurnEvidenceKind[])
340
+ export const isTurnReason = makeGuard(TURN_REASONS)
341
+ export const isNotifyKind = makeGuard(NOTIFY_KINDS)
342
+ export const isHoldReason = makeGuard(HOLD_REASONS)
343
+ export const isTurnOutcome = makeGuard(TURN_OUTCOMES)
344
+ export const isCommitStrength = makeGuard(COMMIT_STRENGTHS)
345
+
346
+ function isRecord(value: unknown): value is Record<string, unknown> {
347
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
348
+ }
349
+
350
+ export function isEvidenceIdentifier(value: unknown): value is string {
351
+ return typeof value === 'string' && IDENTIFIER_RE.test(value)
352
+ }
353
+
354
+ function isFiniteNumber(value: unknown): value is number {
355
+ return typeof value === 'number' && Number.isFinite(value)
356
+ }
357
+
358
+ export function isSummaryRef(value: unknown): value is SummaryRef {
359
+ return isRecord(value)
360
+ && hasOnlyKeys(value, ['topic', 'writer', 'seq'])
361
+ && isEvidenceIdentifier(value.topic)
362
+ && isEvidenceIdentifier(value.writer)
363
+ && Number.isSafeInteger(value.seq) && (value.seq as number) >= 0
364
+ }
365
+
366
+ export function isTurnAttemptRef(value: unknown): value is TurnAttemptRef {
367
+ return isRecord(value)
368
+ && hasOnlyKeys(value, ['attemptId', 'generation'])
369
+ && isEvidenceIdentifier(value.attemptId)
370
+ && Number.isSafeInteger(value.generation) && (value.generation as number) >= 0
371
+ }
372
+
373
+ function isLiveTurnPending(value: unknown): value is LiveTurnPending {
374
+ return isRecord(value)
375
+ && hasOnlyKeys(value, ['modal', 'adapterPending', 'trailingTool', 'newestActivityAt'])
376
+ && typeof value.modal === 'boolean'
377
+ && typeof value.adapterPending === 'boolean'
378
+ && typeof value.trailingTool === 'boolean'
379
+ && (value.newestActivityAt === undefined || isFiniteNumber(value.newestActivityAt))
380
+ }
381
+
382
+ function isNativeMarkerRef(value: unknown): value is NativeTurnMarkerRef {
383
+ return isRecord(value)
384
+ && hasOnlyKeys(value, ['outcome', 'turnId'])
385
+ && (NATIVE_TURN_OUTCOMES as readonly string[]).includes(value.outcome as string)
386
+ && (value.turnId === undefined || isEvidenceIdentifier(value.turnId))
387
+ }
388
+
389
+ function isCoordinatorIdentity(value: unknown): value is EvidenceCoordinatorIdentity {
390
+ return isRecord(value)
391
+ && hasOnlyKeys(value, ['daemonId', 'coordinatorRunId', 'sessionId'])
392
+ && isEvidenceIdentifier(value.daemonId)
393
+ && isEvidenceIdentifier(value.coordinatorRunId)
394
+ && (value.sessionId === undefined || isEvidenceIdentifier(value.sessionId))
395
+ }
396
+
397
+ function hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {
398
+ for (const key of Object.keys(value)) {
399
+ if (!allowed.includes(key)) return false
400
+ }
401
+ return true
402
+ }
403
+
404
+ function fieldMatches(spec: EvidenceFieldSpec, value: unknown): boolean {
405
+ if (value === undefined) return spec.optional === true
406
+ switch (spec.t) {
407
+ case 'id': return isEvidenceIdentifier(value)
408
+ case 'enum': return typeof value === 'string' && spec.values.includes(value)
409
+ case 'bool': return typeof value === 'boolean'
410
+ case 'int': return (value === null && spec.nullable === true) || Number.isSafeInteger(value)
411
+ case 'ms': return isFiniteNumber(value) && value >= 0
412
+ case 'summary_ref': return isSummaryRef(value)
413
+ case 'attempt_ref': return isTurnAttemptRef(value)
414
+ case 'live': return isLiveTurnPending(value)
415
+ case 'native_marker': return isNativeMarkerRef(value)
416
+ case 'coordinator': return isCoordinatorIdentity(value)
417
+ }
418
+ }
419
+
420
+ /**
421
+ * Strict structural guard: known kind, every declared field of the right class,
422
+ * and NO undeclared field (an unknown key is how free text would sneak in).
423
+ */
424
+ export function isTurnEvidence(value: unknown): value is TurnEvidence {
425
+ if (!isRecord(value) || !isTurnEvidenceKind(value.kind)) return false
426
+ const bodySpecs = TURN_EVIDENCE_FIELD_SPECS[value.kind] as Record<string, EvidenceFieldSpec>
427
+ const envelopeSpecs = EVIDENCE_ENVELOPE_FIELD_SPECS as Record<string, EvidenceFieldSpec>
428
+ for (const key of Object.keys(value)) {
429
+ if (key === 'kind') continue
430
+ if (!(key in bodySpecs) && !(key in envelopeSpecs)) return false
431
+ }
432
+ for (const [key, spec] of Object.entries(envelopeSpecs)) {
433
+ if (!fieldMatches(spec, value[key])) return false
434
+ }
435
+ for (const [key, spec] of Object.entries(bodySpecs)) {
436
+ if (!fieldMatches(spec, value[key])) return false
437
+ }
438
+ return true
439
+ }
440
+
441
+ export function isTerminalClassEvidenceKind(kind: TurnEvidenceKind): kind is typeof TERMINAL_CLASS_EVIDENCE_KINDS[number] {
442
+ return (TERMINAL_CLASS_EVIDENCE_KINDS as readonly string[]).includes(kind)
443
+ }
444
+
445
+ // ─── mesh.<id>.events topic entries (C2) ─────────────────────────────────
446
+
447
+ export const TURN_EVIDENCE_FLAGS = ['hollow', 'afterFinalizationTimeout', 'nativeMarker', 'selfAttributing'] as const
448
+ export type TurnEvidenceFlag = typeof TURN_EVIDENCE_FLAGS[number]
449
+
450
+ /** Scalar-only payload for `mesh.record` (the existing allow-list projection's output). */
451
+ export type ProjectedScalars = Readonly<Record<string, string | number | boolean | null>>
452
+
453
+ export const MESH_TOPIC_ENTRY_KINDS = ['turn.evidence', 'turn.committed', 'turn.notify', 'mesh.record'] as const
454
+ export type MeshTopicEntryKind = typeof MESH_TOPIC_ENTRY_KINDS[number]
455
+
456
+ export type MeshTopicEntry = { v: typeof MESH_TOPIC_PROTOCOL_VERSION; eventId: string; at: number } & (
457
+ | { k: 'turn.evidence'; attemptId: string; generation: number; ownerDaemonId: string; taskId?: string; sessionId: string
458
+ ev: TurnEvidenceKind; strength?: TurnEndStrength; flags?: Partial<Record<TurnEvidenceFlag, boolean>>
459
+ /** The full (content-free) evidence, so a foreign `turn.ingest` can re-observe it losslessly. */
460
+ evidence?: TurnEvidence }
461
+ | { k: 'turn.committed'; attemptId: string; generation: number; taskId?: string; outcome: TurnOutcome; strength: CommitStrength; reason: TurnReason }
462
+ | { k: 'turn.notify'; attemptId?: string; notify: NotifyKind; targetDaemonId: string; targetSessionId?: string; taskId?: string }
463
+ | { k: 'mesh.record'; ledgerKind: string; nodeId?: string; sessionId?: string; taskId?: string; payload: ProjectedScalars }
464
+ )
465
+
466
+ export const isMeshTopicEntryKind = makeGuard(MESH_TOPIC_ENTRY_KINDS)
467
+
468
+ function isOptionalId(value: unknown): boolean {
469
+ return value === undefined || isEvidenceIdentifier(value)
470
+ }
471
+
472
+ function isGeneration(value: unknown): boolean {
473
+ return Number.isSafeInteger(value) && (value as number) >= 0
474
+ }
475
+
476
+ function isProjectedScalars(value: unknown): value is ProjectedScalars {
477
+ if (!isRecord(value)) return false
478
+ for (const v of Object.values(value)) {
479
+ if (!(v === null || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'string')) return false
480
+ }
481
+ return true
482
+ }
483
+
484
+ export function isMeshTopicEntry(value: unknown): value is MeshTopicEntry {
485
+ if (!isRecord(value)) return false
486
+ if (value.v !== MESH_TOPIC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.eventId) || !isFiniteNumber(value.at)) return false
487
+ switch (value.k) {
488
+ case 'turn.evidence': {
489
+ if (!isEvidenceIdentifier(value.attemptId) || !isGeneration(value.generation)) return false
490
+ if (!isEvidenceIdentifier(value.ownerDaemonId) || !isEvidenceIdentifier(value.sessionId) || !isOptionalId(value.taskId)) return false
491
+ if (!isTurnEvidenceKind(value.ev)) return false
492
+ if (value.strength !== undefined && !(TURN_END_STRENGTHS as readonly string[]).includes(value.strength as string)) return false
493
+ if (value.flags !== undefined) {
494
+ if (!isRecord(value.flags)) return false
495
+ for (const [flag, on] of Object.entries(value.flags)) {
496
+ if (!(TURN_EVIDENCE_FLAGS as readonly string[]).includes(flag) || typeof on !== 'boolean') return false
497
+ }
498
+ }
499
+ if (value.evidence !== undefined && !(isTurnEvidence(value.evidence) && value.evidence.kind === value.ev)) return false
500
+ return true
501
+ }
502
+ case 'turn.committed':
503
+ return isEvidenceIdentifier(value.attemptId) && isGeneration(value.generation) && isOptionalId(value.taskId)
504
+ && isTurnOutcome(value.outcome) && isCommitStrength(value.strength) && isTurnReason(value.reason)
505
+ case 'turn.notify':
506
+ return isOptionalId(value.attemptId) && isNotifyKind(value.notify) && isEvidenceIdentifier(value.targetDaemonId)
507
+ && isOptionalId(value.targetSessionId) && isOptionalId(value.taskId)
508
+ case 'mesh.record':
509
+ return isEvidenceIdentifier(value.ledgerKind) && isOptionalId(value.nodeId) && isOptionalId(value.sessionId)
510
+ && isOptionalId(value.taskId) && isProjectedScalars(value.payload)
511
+ default:
512
+ return false
513
+ }
514
+ }
515
+
516
+ /**
517
+ * Project evidence onto its `turn.evidence` topic entry. Pure; the attempt
518
+ * identity comes from the resolved attempt (the evidence may lack attemptRef).
519
+ */
520
+ export function projectTurnEvidenceEntry(
521
+ evidence: TurnEvidence,
522
+ attempt: { attemptId: string; generation: number; ownerDaemonId: string },
523
+ ): Extract<MeshTopicEntry, { k: 'turn.evidence' }> {
524
+ const flags: Partial<Record<TurnEvidenceFlag, boolean>> = {}
525
+ if (evidence.kind === 'turn_end') {
526
+ if (evidence.hollow) flags.hollow = true
527
+ if (evidence.afterFinalizationTimeout) flags.afterFinalizationTimeout = true
528
+ }
529
+ if (evidence.kind === 'transcript_final') {
530
+ if (evidence.nativeMarker) flags.nativeMarker = true
531
+ if (evidence.selfAttributing) flags.selfAttributing = true
532
+ }
533
+ const taskId = evidence.taskId
534
+ return {
535
+ v: MESH_TOPIC_PROTOCOL_VERSION,
536
+ eventId: evidence.eventId,
537
+ at: evidence.at,
538
+ k: 'turn.evidence',
539
+ attemptId: attempt.attemptId,
540
+ generation: attempt.generation,
541
+ ownerDaemonId: attempt.ownerDaemonId,
542
+ ...(taskId ? { taskId } : {}),
543
+ sessionId: evidence.sessionId,
544
+ ev: evidence.kind,
545
+ ...(evidence.kind === 'turn_end' ? { strength: evidence.strength } : {}),
546
+ ...(Object.keys(flags).length > 0 ? { flags } : {}),
547
+ evidence,
548
+ }
549
+ }