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

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 +2764 -17
  3. package/dist/index.js.map +1 -1
  4. package/dist/index.mjs +2441 -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 +407 -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 +562 -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,562 @@
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
+ // A genuine FSM end of a mesh turn whose worker holds a live worker-MCP bind:
126
+ // the structured report is the primary evidence (design §F2), so the idle edge
127
+ // only opens this hold (R9r) — a report commits (R17), a new busy edge cancels
128
+ // it as a false idle (R12r), expiry commits weak (R13r).
129
+ 'await_report',
130
+ ] as const
131
+ export type HoldReason = typeof HOLD_REASONS[number]
132
+
133
+ export const TURN_OUTCOMES = ['completed', 'failed', 'cancelled'] as const
134
+ export type TurnOutcome = typeof TURN_OUTCOMES[number]
135
+
136
+ export const COMMIT_STRENGTHS = ['genuine', 'weak', 'tool_report', 'operator'] as const
137
+ export type CommitStrength = typeof COMMIT_STRENGTHS[number]
138
+
139
+ /** Every terminal or reclaim reason the ledger writes. Closed: no free-text reasons. */
140
+ export const TURN_REASONS = [
141
+ // commits
142
+ 'turn_end', 'weak_end_confirmed', 'transcript_final', 'worker_reported',
143
+ 'finalization_timeout_no_response', 'session_error', 'provider_auth_failed', 'provider_billing_failed',
144
+ 'operator_cancel', 'intentional_cleanup', 'task_removed', 'mission_abandoned', 'superseded',
145
+ 'operator_update', 'refine_terminal', 'validation_terminal',
146
+ 'hard_ceiling', 'reclaim_budget_exhausted', 'hollow_max_retries', 'migration_orphan',
147
+ // reclaims (generation + 1)
148
+ 'dispatch_refused_session_exited', 'dispatch_refused_no_target', 'dispatch_refused_unsupported_input', 'dispatch_failed',
149
+ 'session_exit', 'session_exit_before_turn', 'session_dead', 'hollow_completion',
150
+ 'assigned_stranded_dispatch_unconfirmed', 'delivered_not_consumed_redrive', 'delivered_no_turn_deadline',
151
+ ] as const
152
+ export type TurnReason = typeof TURN_REASONS[number]
153
+
154
+ /**
155
+ * What a `turn.notify` entry tells a coordinator.
156
+ *
157
+ * `late_completion` (C1 R27, owner revision 2026-09-23): a superseded
158
+ * generation finished while the current one was already running; the
159
+ * coordinator decides whether to salvage it (the entry carries the g−1
160
+ * summary as its append `ref`). `mesh_event`: a non-turn coordinator notice
161
+ * (refine terminal, worktree bootstrap, …) whose text lives only in the
162
+ * owner's local `turn_events.payload_json` and is rendered at deliver time.
163
+ */
164
+ export const NOTIFY_KINDS = [
165
+ 'completed', 'failed', 'cancelled', 'stopped', 'approval', 'choice', 'approval_resolved',
166
+ 'candidate', 'no_progress', 'progress', 'late_completion', 'mesh_event',
167
+ ] as const
168
+ export type NotifyKind = typeof NOTIFY_KINDS[number]
169
+
170
+ // ─── shared shapes ───────────────────────────────────────────────────────
171
+
172
+ export interface TurnAttemptRef { attemptId: string; generation: number }
173
+
174
+ /**
175
+ * Pointer to text that lives in a content-class topic entry (`mesh.<id>.handoff`).
176
+ * Text never travels inside evidence; the deliver side renders it from the ref.
177
+ */
178
+ export interface SummaryRef { topic: string; writer: string; seq: number }
179
+
180
+ /** Live-state observations that make a transcript end premature (admission input). */
181
+ export interface LiveTurnPending { modal: boolean; adapterPending: boolean; trailingTool: boolean; newestActivityAt?: number }
182
+
183
+ /** Structural copy of daemon-core's `CoordinatorIdentity` (this package cannot import daemon-core). */
184
+ export interface EvidenceCoordinatorIdentity { daemonId: string; coordinatorRunId: string; sessionId?: string }
185
+
186
+ export interface NativeTurnMarkerRef { outcome: NativeTurnOutcome; turnId?: string }
187
+
188
+ export interface EvidenceEnvelope {
189
+ /** Stable id of this observation; dedupe key across republish/replication. */
190
+ eventId: string
191
+ /** Producer clock, epoch ms. */
192
+ at: number
193
+ source: EvidenceSourceId
194
+ /** The session that produced / is the subject of the observation. */
195
+ sessionId: string
196
+ attemptRef?: TurnAttemptRef
197
+ /** Only when attemptRef is absent (legacy relay / MCP probe). */
198
+ taskId?: string
199
+ /** Daemon id that observed it. */
200
+ observedBy: string
201
+ }
202
+
203
+ /** Kind-specific bodies. `TurnEvidence = EvidenceEnvelope & TurnEvidenceBody`. */
204
+ export type TurnEvidenceBody =
205
+ // ── dispatch / delivery ──
206
+ | { kind: 'dispatch_accepted'; scope: TurnScope; messageId: string; meshId?: string; nodeId?: string; providerType?: string
207
+ attemptNo?: number; dispatchNonce?: number; consumeProfile?: ConsumeProfile; maxTaskRetries?: number
208
+ coordinator?: EvidenceCoordinatorIdentity }
209
+ | { kind: 'delivered'; messageId: string; outcome: DeliveryOutcome; via: DeliveryVia }
210
+ | { kind: 'delivery_refused'; messageId: string; reason: SendRefusal }
211
+ | { kind: 'dispatch_failed'; workerAbsent: boolean; reason: DispatchFailureReason }
212
+ | { kind: 'duplicate_dispatch_refusal'; holderSessionId: string; holderAttemptId?: string }
213
+ | { kind: 'session_rebound'; toSessionId: string; reason: SessionReboundReason }
214
+ // ── worker turn lifecycle ──
215
+ | { kind: 'turn_started'; retro: boolean }
216
+ | { kind: 'suspension'; modal: SuspensionModal; modalKey?: string }
217
+ | { kind: 'suspension_resolved'; resolution: SuspensionResolution; via: SuspensionResolutionVia }
218
+ | { kind: 'turn_end'; strength: TurnEndStrength; afterFinalizationTimeout?: boolean; hollow?: boolean; summary?: SummaryRef
219
+ blockReason?: TurnEndBlockReason; releasedByHardCap?: boolean; nativeOutcome?: NativeTurnOutcome; live?: LiveTurnPending
220
+ /**
221
+ * Stamped (true only) by the WORKER's daemon when the session holds a live
222
+ * worker-MCP session bind, i.e. the worker can call report_completion. The
223
+ * owner then treats a genuine end as a report-awaiting candidate (R9r), not
224
+ * a commit. Absent = no reporting surface = today's genuine-end commit.
225
+ */
226
+ reportExpected?: boolean }
227
+ | { kind: 'transcript_final'; selfAttributing: boolean; nativeRead: boolean; nativeMarker?: NativeTurnMarkerRef
228
+ live: LiveTurnPending; summary?: SummaryRef; messageAt?: number }
229
+ | { kind: 'transcript_activity'; newestActivityAt: number }
230
+ | { kind: 'no_progress'; stalledMs: number; observedStatus: NoProgressObservedStatus; finalAssistantPresent: boolean }
231
+ | { kind: 'liveness'; result: LivenessResult }
232
+ | { kind: 'process_exit'; exitCode: number | null; providerFailure?: ProviderFailure }
233
+ | { kind: 'session_error'; reason: SessionErrorReason }
234
+ // ── worker MCP (F2) ──
235
+ | { kind: 'worker_report'; outcome: WorkerReportOutcome; summary: SummaryRef; hasHandoffNotes: boolean
236
+ branchState?: WorkerBranchState; touchedFileCount?: number }
237
+ | { kind: 'worker_progress'; note?: SummaryRef }
238
+ // ── coordinator / operator ──
239
+ | { kind: 'git_side_effect'; dirty: boolean; commitsSinceDispatch: number; attributable: boolean }
240
+ | { kind: 'cancel'; reason: CancelReason }
241
+ | { kind: 'operator_status'; status: OperatorStatus; reason: OperatorStatusReason }
242
+ | { kind: 'coordinator_ack'; notify: NotifyKind; outcome: CoordinatorAckOutcome }
243
+ // ── scheduler-generated ──
244
+ | { kind: 'hold_expired'; holdId: string; reason: HoldReason }
245
+
246
+ export type TurnEvidence = EvidenceEnvelope & TurnEvidenceBody
247
+ export type TurnEvidenceKind = TurnEvidenceBody['kind']
248
+ export type TurnEvidenceOf<K extends TurnEvidenceKind> = EvidenceEnvelope & Extract<TurnEvidenceBody, { kind: K }>
249
+
250
+ // ─── field-class registry (drives the guard and the content-free test) ────
251
+
252
+ /**
253
+ * The class of every declared field. There is deliberately NO free-text class:
254
+ * `id` strings are length-bounded and whitespace-free, so prose cannot be
255
+ * smuggled through an identifier slot either.
256
+ */
257
+ export type EvidenceFieldSpec =
258
+ | { t: 'id'; optional?: true }
259
+ | { t: 'enum'; values: readonly string[]; optional?: true }
260
+ | { t: 'bool'; optional?: true }
261
+ | { t: 'int'; optional?: true; nullable?: true }
262
+ | { t: 'ms'; optional?: true }
263
+ | { t: 'summary_ref'; optional?: true }
264
+ | { t: 'attempt_ref'; optional?: true }
265
+ | { t: 'live'; optional?: true }
266
+ | { t: 'native_marker'; optional?: true }
267
+ | { t: 'coordinator'; optional?: true }
268
+
269
+ type FieldsOf<K extends TurnEvidenceKind> = Exclude<keyof Extract<TurnEvidenceBody, { kind: K }>, 'kind'>
270
+ /** Exact per-kind registry: a missing or extra field fails to compile. */
271
+ export type TurnEvidenceFieldSpecs = { readonly [K in TurnEvidenceKind]: { readonly [F in FieldsOf<K>]-?: EvidenceFieldSpec } }
272
+
273
+ const id = { t: 'id' } as const
274
+ const idOpt = { t: 'id', optional: true } as const
275
+ const bool = { t: 'bool' } as const
276
+ const boolOpt = { t: 'bool', optional: true } as const
277
+ const ms = { t: 'ms' } as const
278
+ const msOpt = { t: 'ms', optional: true } as const
279
+ const intOpt = { t: 'int', optional: true } as const
280
+ const en = (values: readonly string[]) => ({ t: 'enum', values }) as const
281
+ const enOpt = (values: readonly string[]) => ({ t: 'enum', values, optional: true }) as const
282
+
283
+ export const EVIDENCE_ENVELOPE_FIELD_SPECS: { readonly [F in keyof EvidenceEnvelope]-?: EvidenceFieldSpec } = {
284
+ eventId: id,
285
+ at: ms,
286
+ source: en(EVIDENCE_SOURCE_IDS),
287
+ sessionId: id,
288
+ attemptRef: { t: 'attempt_ref', optional: true },
289
+ taskId: idOpt,
290
+ observedBy: id,
291
+ }
292
+
293
+ export const TURN_EVIDENCE_FIELD_SPECS: TurnEvidenceFieldSpecs = {
294
+ dispatch_accepted: {
295
+ scope: en(TURN_SCOPES), messageId: id, meshId: idOpt, nodeId: idOpt, providerType: idOpt,
296
+ attemptNo: intOpt, dispatchNonce: intOpt, consumeProfile: enOpt(CONSUME_PROFILES), maxTaskRetries: intOpt,
297
+ coordinator: { t: 'coordinator', optional: true },
298
+ },
299
+ delivered: { messageId: id, outcome: en(DELIVERY_OUTCOMES), via: en(DELIVERY_VIAS) },
300
+ delivery_refused: { messageId: id, reason: en(SEND_REFUSAL_REASONS) },
301
+ dispatch_failed: { workerAbsent: bool, reason: en(DISPATCH_FAILURE_REASONS) },
302
+ duplicate_dispatch_refusal: { holderSessionId: id, holderAttemptId: idOpt },
303
+ session_rebound: { toSessionId: id, reason: en(SESSION_REBOUND_REASONS) },
304
+ turn_started: { retro: bool },
305
+ suspension: { modal: en(SUSPENSION_MODALS), modalKey: idOpt },
306
+ suspension_resolved: { resolution: en(SUSPENSION_RESOLUTIONS), via: en(SUSPENSION_RESOLUTION_VIAS) },
307
+ turn_end: {
308
+ strength: en(TURN_END_STRENGTHS), afterFinalizationTimeout: boolOpt, hollow: boolOpt,
309
+ summary: { t: 'summary_ref', optional: true }, blockReason: enOpt(TURN_END_BLOCK_REASONS),
310
+ releasedByHardCap: boolOpt, nativeOutcome: enOpt(NATIVE_TURN_OUTCOMES), live: { t: 'live', optional: true },
311
+ reportExpected: boolOpt,
312
+ },
313
+ transcript_final: {
314
+ selfAttributing: bool, nativeRead: bool, nativeMarker: { t: 'native_marker', optional: true },
315
+ live: { t: 'live' }, summary: { t: 'summary_ref', optional: true }, messageAt: msOpt,
316
+ },
317
+ transcript_activity: { newestActivityAt: ms },
318
+ no_progress: { stalledMs: ms, observedStatus: en(NO_PROGRESS_OBSERVED_STATUSES), finalAssistantPresent: bool },
319
+ liveness: { result: en(LIVENESS_RESULTS) },
320
+ process_exit: { exitCode: { t: 'int', nullable: true }, providerFailure: enOpt(PROVIDER_FAILURES) },
321
+ session_error: { reason: en(SESSION_ERROR_REASONS) },
322
+ worker_report: {
323
+ outcome: en(WORKER_REPORT_OUTCOMES), summary: { t: 'summary_ref' }, hasHandoffNotes: bool,
324
+ branchState: enOpt(WORKER_BRANCH_STATES), touchedFileCount: intOpt,
325
+ },
326
+ worker_progress: { note: { t: 'summary_ref', optional: true } },
327
+ git_side_effect: { dirty: bool, commitsSinceDispatch: { t: 'int' }, attributable: bool },
328
+ cancel: { reason: en(CANCEL_REASONS) },
329
+ operator_status: { status: en(OPERATOR_STATUSES), reason: en(OPERATOR_STATUS_REASONS) },
330
+ coordinator_ack: { notify: en(NOTIFY_KINDS), outcome: en(COORDINATOR_ACK_OUTCOMES) },
331
+ hold_expired: { holdId: id, reason: en(HOLD_REASONS) },
332
+ }
333
+
334
+ export const TURN_EVIDENCE_KINDS = Object.keys(TURN_EVIDENCE_FIELD_SPECS) as readonly TurnEvidenceKind[]
335
+
336
+ /** Evidence kinds that, on their own, can end a turn (the ones R18/R19/R27 reason about). */
337
+ export const TERMINAL_CLASS_EVIDENCE_KINDS = [
338
+ 'turn_end', 'transcript_final', 'no_progress', 'worker_report', 'session_error', 'process_exit', 'cancel', 'operator_status',
339
+ ] as const satisfies readonly TurnEvidenceKind[]
340
+
341
+ // ─── guards ──────────────────────────────────────────────────────────────
342
+
343
+ /** Identifier shape: 1..256 chars, no whitespace or control characters. */
344
+ const IDENTIFIER_RE = /^[^\s\u0000-\u001f\u007f]{1,256}$/
345
+
346
+ function makeGuard<T extends readonly string[]>(values: T): (value: unknown) => value is T[number] {
347
+ const set: ReadonlySet<string> = new Set(values)
348
+ return (value: unknown): value is T[number] => typeof value === 'string' && set.has(value)
349
+ }
350
+
351
+ export const isEvidenceSourceId = makeGuard(EVIDENCE_SOURCE_IDS)
352
+ export const isTurnEvidenceKind = makeGuard(TURN_EVIDENCE_KINDS as readonly TurnEvidenceKind[])
353
+ export const isTurnReason = makeGuard(TURN_REASONS)
354
+ export const isNotifyKind = makeGuard(NOTIFY_KINDS)
355
+ export const isHoldReason = makeGuard(HOLD_REASONS)
356
+ export const isTurnOutcome = makeGuard(TURN_OUTCOMES)
357
+ export const isCommitStrength = makeGuard(COMMIT_STRENGTHS)
358
+
359
+ function isRecord(value: unknown): value is Record<string, unknown> {
360
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
361
+ }
362
+
363
+ export function isEvidenceIdentifier(value: unknown): value is string {
364
+ return typeof value === 'string' && IDENTIFIER_RE.test(value)
365
+ }
366
+
367
+ function isFiniteNumber(value: unknown): value is number {
368
+ return typeof value === 'number' && Number.isFinite(value)
369
+ }
370
+
371
+ export function isSummaryRef(value: unknown): value is SummaryRef {
372
+ return isRecord(value)
373
+ && hasOnlyKeys(value, ['topic', 'writer', 'seq'])
374
+ && isEvidenceIdentifier(value.topic)
375
+ && isEvidenceIdentifier(value.writer)
376
+ && Number.isSafeInteger(value.seq) && (value.seq as number) >= 0
377
+ }
378
+
379
+ export function isTurnAttemptRef(value: unknown): value is TurnAttemptRef {
380
+ return isRecord(value)
381
+ && hasOnlyKeys(value, ['attemptId', 'generation'])
382
+ && isEvidenceIdentifier(value.attemptId)
383
+ && Number.isSafeInteger(value.generation) && (value.generation as number) >= 0
384
+ }
385
+
386
+ function isLiveTurnPending(value: unknown): value is LiveTurnPending {
387
+ return isRecord(value)
388
+ && hasOnlyKeys(value, ['modal', 'adapterPending', 'trailingTool', 'newestActivityAt'])
389
+ && typeof value.modal === 'boolean'
390
+ && typeof value.adapterPending === 'boolean'
391
+ && typeof value.trailingTool === 'boolean'
392
+ && (value.newestActivityAt === undefined || isFiniteNumber(value.newestActivityAt))
393
+ }
394
+
395
+ function isNativeMarkerRef(value: unknown): value is NativeTurnMarkerRef {
396
+ return isRecord(value)
397
+ && hasOnlyKeys(value, ['outcome', 'turnId'])
398
+ && (NATIVE_TURN_OUTCOMES as readonly string[]).includes(value.outcome as string)
399
+ && (value.turnId === undefined || isEvidenceIdentifier(value.turnId))
400
+ }
401
+
402
+ function isCoordinatorIdentity(value: unknown): value is EvidenceCoordinatorIdentity {
403
+ return isRecord(value)
404
+ && hasOnlyKeys(value, ['daemonId', 'coordinatorRunId', 'sessionId'])
405
+ && isEvidenceIdentifier(value.daemonId)
406
+ && isEvidenceIdentifier(value.coordinatorRunId)
407
+ && (value.sessionId === undefined || isEvidenceIdentifier(value.sessionId))
408
+ }
409
+
410
+ function hasOnlyKeys(value: Record<string, unknown>, allowed: readonly string[]): boolean {
411
+ for (const key of Object.keys(value)) {
412
+ if (!allowed.includes(key)) return false
413
+ }
414
+ return true
415
+ }
416
+
417
+ function fieldMatches(spec: EvidenceFieldSpec, value: unknown): boolean {
418
+ if (value === undefined) return spec.optional === true
419
+ switch (spec.t) {
420
+ case 'id': return isEvidenceIdentifier(value)
421
+ case 'enum': return typeof value === 'string' && spec.values.includes(value)
422
+ case 'bool': return typeof value === 'boolean'
423
+ case 'int': return (value === null && spec.nullable === true) || Number.isSafeInteger(value)
424
+ case 'ms': return isFiniteNumber(value) && value >= 0
425
+ case 'summary_ref': return isSummaryRef(value)
426
+ case 'attempt_ref': return isTurnAttemptRef(value)
427
+ case 'live': return isLiveTurnPending(value)
428
+ case 'native_marker': return isNativeMarkerRef(value)
429
+ case 'coordinator': return isCoordinatorIdentity(value)
430
+ }
431
+ }
432
+
433
+ /**
434
+ * Strict structural guard: known kind, every declared field of the right class,
435
+ * and NO undeclared field (an unknown key is how free text would sneak in).
436
+ */
437
+ export function isTurnEvidence(value: unknown): value is TurnEvidence {
438
+ if (!isRecord(value) || !isTurnEvidenceKind(value.kind)) return false
439
+ const bodySpecs = TURN_EVIDENCE_FIELD_SPECS[value.kind] as Record<string, EvidenceFieldSpec>
440
+ const envelopeSpecs = EVIDENCE_ENVELOPE_FIELD_SPECS as Record<string, EvidenceFieldSpec>
441
+ for (const key of Object.keys(value)) {
442
+ if (key === 'kind') continue
443
+ if (!(key in bodySpecs) && !(key in envelopeSpecs)) return false
444
+ }
445
+ for (const [key, spec] of Object.entries(envelopeSpecs)) {
446
+ if (!fieldMatches(spec, value[key])) return false
447
+ }
448
+ for (const [key, spec] of Object.entries(bodySpecs)) {
449
+ if (!fieldMatches(spec, value[key])) return false
450
+ }
451
+ return true
452
+ }
453
+
454
+ export function isTerminalClassEvidenceKind(kind: TurnEvidenceKind): kind is typeof TERMINAL_CLASS_EVIDENCE_KINDS[number] {
455
+ return (TERMINAL_CLASS_EVIDENCE_KINDS as readonly string[]).includes(kind)
456
+ }
457
+
458
+ // ─── mesh.<id>.events topic entries (C2) ─────────────────────────────────
459
+
460
+ export const TURN_EVIDENCE_FLAGS = ['hollow', 'afterFinalizationTimeout', 'nativeMarker', 'selfAttributing'] as const
461
+ export type TurnEvidenceFlag = typeof TURN_EVIDENCE_FLAGS[number]
462
+
463
+ /** Scalar-only payload for `mesh.record` (the existing allow-list projection's output). */
464
+ export type ProjectedScalars = Readonly<Record<string, string | number | boolean | null>>
465
+
466
+ export const MESH_TOPIC_ENTRY_KINDS = ['turn.evidence', 'turn.committed', 'turn.notify', 'mesh.record'] as const
467
+ export type MeshTopicEntryKind = typeof MESH_TOPIC_ENTRY_KINDS[number]
468
+
469
+ export type MeshTopicEntry = { v: typeof MESH_TOPIC_PROTOCOL_VERSION; eventId: string; at: number } & (
470
+ | { k: 'turn.evidence'; attemptId: string; generation: number; ownerDaemonId: string; taskId?: string; sessionId: string
471
+ ev: TurnEvidenceKind; strength?: TurnEndStrength; flags?: Partial<Record<TurnEvidenceFlag, boolean>>
472
+ /** The full (content-free) evidence, so a foreign `turn.ingest` can re-observe it losslessly. */
473
+ evidence?: TurnEvidence }
474
+ | { k: 'turn.committed'; attemptId: string; generation: number; taskId?: string; outcome: TurnOutcome; strength: CommitStrength; reason: TurnReason }
475
+ | { k: 'turn.notify'; attemptId?: string; notify: NotifyKind; targetDaemonId: string; targetSessionId?: string; taskId?: string }
476
+ | { k: 'mesh.record'; ledgerKind: string; nodeId?: string; sessionId?: string; taskId?: string; payload: ProjectedScalars }
477
+ )
478
+
479
+ export const isMeshTopicEntryKind = makeGuard(MESH_TOPIC_ENTRY_KINDS)
480
+
481
+ function isOptionalId(value: unknown): boolean {
482
+ return value === undefined || isEvidenceIdentifier(value)
483
+ }
484
+
485
+ function isGeneration(value: unknown): boolean {
486
+ return Number.isSafeInteger(value) && (value as number) >= 0
487
+ }
488
+
489
+ function isProjectedScalars(value: unknown): value is ProjectedScalars {
490
+ if (!isRecord(value)) return false
491
+ for (const v of Object.values(value)) {
492
+ if (!(v === null || typeof v === 'number' || typeof v === 'boolean' || typeof v === 'string')) return false
493
+ }
494
+ return true
495
+ }
496
+
497
+ export function isMeshTopicEntry(value: unknown): value is MeshTopicEntry {
498
+ if (!isRecord(value)) return false
499
+ if (value.v !== MESH_TOPIC_PROTOCOL_VERSION || !isEvidenceIdentifier(value.eventId) || !isFiniteNumber(value.at)) return false
500
+ switch (value.k) {
501
+ case 'turn.evidence': {
502
+ if (!isEvidenceIdentifier(value.attemptId) || !isGeneration(value.generation)) return false
503
+ if (!isEvidenceIdentifier(value.ownerDaemonId) || !isEvidenceIdentifier(value.sessionId) || !isOptionalId(value.taskId)) return false
504
+ if (!isTurnEvidenceKind(value.ev)) return false
505
+ if (value.strength !== undefined && !(TURN_END_STRENGTHS as readonly string[]).includes(value.strength as string)) return false
506
+ if (value.flags !== undefined) {
507
+ if (!isRecord(value.flags)) return false
508
+ for (const [flag, on] of Object.entries(value.flags)) {
509
+ if (!(TURN_EVIDENCE_FLAGS as readonly string[]).includes(flag) || typeof on !== 'boolean') return false
510
+ }
511
+ }
512
+ if (value.evidence !== undefined && !(isTurnEvidence(value.evidence) && value.evidence.kind === value.ev)) return false
513
+ return true
514
+ }
515
+ case 'turn.committed':
516
+ return isEvidenceIdentifier(value.attemptId) && isGeneration(value.generation) && isOptionalId(value.taskId)
517
+ && isTurnOutcome(value.outcome) && isCommitStrength(value.strength) && isTurnReason(value.reason)
518
+ case 'turn.notify':
519
+ return isOptionalId(value.attemptId) && isNotifyKind(value.notify) && isEvidenceIdentifier(value.targetDaemonId)
520
+ && isOptionalId(value.targetSessionId) && isOptionalId(value.taskId)
521
+ case 'mesh.record':
522
+ return isEvidenceIdentifier(value.ledgerKind) && isOptionalId(value.nodeId) && isOptionalId(value.sessionId)
523
+ && isOptionalId(value.taskId) && isProjectedScalars(value.payload)
524
+ default:
525
+ return false
526
+ }
527
+ }
528
+
529
+ /**
530
+ * Project evidence onto its `turn.evidence` topic entry. Pure; the attempt
531
+ * identity comes from the resolved attempt (the evidence may lack attemptRef).
532
+ */
533
+ export function projectTurnEvidenceEntry(
534
+ evidence: TurnEvidence,
535
+ attempt: { attemptId: string; generation: number; ownerDaemonId: string },
536
+ ): Extract<MeshTopicEntry, { k: 'turn.evidence' }> {
537
+ const flags: Partial<Record<TurnEvidenceFlag, boolean>> = {}
538
+ if (evidence.kind === 'turn_end') {
539
+ if (evidence.hollow) flags.hollow = true
540
+ if (evidence.afterFinalizationTimeout) flags.afterFinalizationTimeout = true
541
+ }
542
+ if (evidence.kind === 'transcript_final') {
543
+ if (evidence.nativeMarker) flags.nativeMarker = true
544
+ if (evidence.selfAttributing) flags.selfAttributing = true
545
+ }
546
+ const taskId = evidence.taskId
547
+ return {
548
+ v: MESH_TOPIC_PROTOCOL_VERSION,
549
+ eventId: evidence.eventId,
550
+ at: evidence.at,
551
+ k: 'turn.evidence',
552
+ attemptId: attempt.attemptId,
553
+ generation: attempt.generation,
554
+ ownerDaemonId: attempt.ownerDaemonId,
555
+ ...(taskId ? { taskId } : {}),
556
+ sessionId: evidence.sessionId,
557
+ ev: evidence.kind,
558
+ ...(evidence.kind === 'turn_end' ? { strength: evidence.strength } : {}),
559
+ ...(Object.keys(flags).length > 0 ? { flags } : {}),
560
+ evidence,
561
+ }
562
+ }