@adhdev/mesh-shared 1.0.82-rc.7 → 1.0.82-rc.70

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 (69) hide show
  1. package/dist/assistant-protocol.d.ts +163 -6
  2. package/dist/decision-push-relay.d.ts +20 -0
  3. package/dist/index.d.ts +12 -0
  4. package/dist/index.js +1637 -124
  5. package/dist/index.js.map +1 -1
  6. package/dist/index.mjs +1499 -124
  7. package/dist/index.mjs.map +1 -1
  8. package/dist/launch-defaults.d.ts +196 -0
  9. package/dist/light-task.d.ts +96 -0
  10. package/dist/mesh-tool-names.d.ts +2 -2
  11. package/dist/mesh-vocabulary.d.ts +13 -4
  12. package/dist/mission-git-state.d.ts +83 -0
  13. package/dist/mission-items.d.ts +202 -0
  14. package/dist/node-facts.d.ts +61 -1
  15. package/dist/outbound-message.d.ts +9 -2
  16. package/dist/path-ownership.d.ts +1 -1
  17. package/dist/protocol/daemon-server.d.ts +42 -2
  18. package/dist/protocol/dashboard-daemon-p2p.d.ts +1 -1
  19. package/dist/protocol/dashboard-server.d.ts +20 -2
  20. package/dist/provider-approval.d.ts +36 -0
  21. package/dist/provider-question.d.ts +19 -0
  22. package/dist/quota-freshness.d.ts +4 -4
  23. package/dist/relay-reprobe.d.ts +52 -0
  24. package/dist/release.d.ts +90 -0
  25. package/dist/role-launch.d.ts +11 -0
  26. package/dist/session-launch.d.ts +10 -22
  27. package/dist/slot-proposal.d.ts +14 -0
  28. package/dist/task-source-phase.d.ts +83 -0
  29. package/dist/task-stages.d.ts +206 -0
  30. package/dist/turn-evidence.d.ts +43 -13
  31. package/dist/turn-ipc-mission.d.ts +72 -1
  32. package/dist/turn-ipc-queue.d.ts +30 -0
  33. package/dist/turn-ipc.d.ts +2 -2
  34. package/dist/types.d.ts +1 -0
  35. package/dist/worker-protocol.d.ts +33 -1
  36. package/package.json +1 -1
  37. package/src/assistant-protocol.ts +306 -6
  38. package/src/daemon-normalize.ts +7 -5
  39. package/src/decision-push-relay.ts +23 -0
  40. package/src/index.ts +13 -0
  41. package/src/keyed-doc-delta.ts +9 -1
  42. package/src/launch-defaults.ts +170 -0
  43. package/src/light-task.ts +116 -0
  44. package/src/mesh-tool-names.ts +22 -0
  45. package/src/mesh-vocabulary.ts +12 -2
  46. package/src/mission-git-state.ts +112 -0
  47. package/src/mission-items.ts +421 -0
  48. package/src/node-facts.ts +56 -1
  49. package/src/outbound-message.ts +19 -0
  50. package/src/path-ownership.ts +4 -6
  51. package/src/protocol/daemon-server.ts +37 -2
  52. package/src/protocol/dashboard-server.ts +13 -2
  53. package/src/provider-approval.ts +59 -0
  54. package/src/provider-question.ts +31 -0
  55. package/src/quota-freshness.ts +29 -13
  56. package/src/relay-reprobe.ts +117 -0
  57. package/src/release.ts +121 -0
  58. package/src/role-launch.ts +51 -0
  59. package/src/session-launch.ts +17 -1
  60. package/src/slot-proposal.ts +61 -2
  61. package/src/task-source-phase.ts +70 -0
  62. package/src/task-stages.ts +455 -0
  63. package/src/turn-evidence.ts +56 -20
  64. package/src/turn-ipc-mission.ts +127 -11
  65. package/src/turn-ipc-queue.ts +43 -2
  66. package/src/turn-ipc-turn.ts +1 -1
  67. package/src/turn-ipc.ts +1 -0
  68. package/src/types.ts +1 -0
  69. package/src/worker-protocol.ts +79 -0
@@ -0,0 +1,170 @@
1
+ /** Daemon-local launch intent and command wire contract. P2P/local only;
2
+ * never include this document or its history in cloud status_report.
3
+ * Publication through mesh-shared's barrel is a later integration step. */
4
+ export const LAUNCH_DEFAULT_ROLES = ['assistant', 'coordinator'] as const;
5
+ export type LaunchDefaultRole = typeof LAUNCH_DEFAULT_ROLES[number];
6
+ export const LAUNCH_DEFAULT_SOURCES = ['user', 'stored_default', 'project_default', 'provider_default'] as const;
7
+ export type LaunchDefaultSource = typeof LAUNCH_DEFAULT_SOURCES[number];
8
+ export const LAUNCH_DEFAULTS_NEXT_LAUNCH_NOTE = 'Applies to the next launch; running sessions are unchanged.';
9
+ export function isLaunchDefaultRole(value: unknown): value is LaunchDefaultRole {
10
+ return typeof value === 'string' && (LAUNCH_DEFAULT_ROLES as readonly string[]).includes(value);
11
+ }
12
+ export function isLaunchDefaultSource(value: unknown): value is LaunchDefaultSource {
13
+ return typeof value === 'string' && (LAUNCH_DEFAULT_SOURCES as readonly string[]).includes(value);
14
+ }
15
+ export interface LaunchDefaultSelection {
16
+ provider: string;
17
+ /** Omission means pass no model/thinking argument, not inherit another provider. */
18
+ model?: string;
19
+ thinkingLevel?: string;
20
+ }
21
+ export type LaunchDefaultToolRestriction = 'enforced' | 'prompt_only';
22
+ export type LaunchDefaultOrigin = 'owner' | 'human' | 'relay' | 'review' | 'review_tainted';
23
+ export interface LaunchDefaultEntry extends LaunchDefaultSelection {
24
+ revision: number;
25
+ setBy: 'owner' | 'assistant';
26
+ setAt: number;
27
+ /** Ordered quota-failover alternatives (<= 3, distinct providers). Absent = none. */
28
+ fallback?: LaunchDefaultSelection[];
29
+ }
30
+ export interface LaunchDefaultChange {
31
+ at: number;
32
+ role: LaunchDefaultRole;
33
+ by: 'owner' | 'assistant';
34
+ origin: LaunchDefaultOrigin;
35
+ from: LaunchDefaultEntry | null;
36
+ to: LaunchDefaultEntry | null;
37
+ }
38
+ export interface LaunchDefaultsDocument {
39
+ version: 1;
40
+ /** Global document token, including clears; distinct from entry revisions. */
41
+ revision: number;
42
+ assistant?: LaunchDefaultEntry;
43
+ coordinator?: LaunchDefaultEntry;
44
+ history: LaunchDefaultChange[];
45
+ }
46
+ export interface LaunchDefaultRef {
47
+ role: LaunchDefaultRole;
48
+ scope: 'global' | 'project';
49
+ /** Entry revision for global defaults; host project token for project defaults. */
50
+ revision: number;
51
+ projectId?: string;
52
+ }
53
+ export type LaunchDefaultField = keyof LaunchDefaultSelection;
54
+ export interface LaunchDefaultAxis {
55
+ value: string | null;
56
+ source: LaunchDefaultSource;
57
+ defaultRef?: LaunchDefaultRef;
58
+ }
59
+ export type LaunchDefaultWarning = 'catalog_unverified' | 'manual_mcp_setup_required';
60
+ export type LaunchDefaultValidationReason =
61
+ | 'invalid_schema' | 'provider_unknown' | 'provider_not_cli' | 'provider_disabled'
62
+ | 'provider_not_detected' | 'provider_not_eligible' | 'provider_quota_gated' | 'model_unsupported'
63
+ | 'model_provider_mismatch' | 'model_not_offered' | 'thinking_unsupported'
64
+ | 'thinking_not_offered' | 'catalog_unavailable';
65
+ export type LaunchDefaultResolution =
66
+ | { ok: true; selection: LaunchDefaultSelection; applied: Record<LaunchDefaultField, LaunchDefaultAxis>;
67
+ defaultRef?: LaunchDefaultRef; documentRevision: number; warnings: LaunchDefaultWarning[];
68
+ toolRestriction: LaunchDefaultToolRestriction }
69
+ | { ok: false; code: 'launch_default_required' | 'launch_default_unavailable' | 'launch_selection_invalid';
70
+ role: LaunchDefaultRole; field: LaunchDefaultField; reason: string; source?: LaunchDefaultSource;
71
+ value?: string | null; defaultRef?: LaunchDefaultRef; candidates?: readonly string[]; hint: string };
72
+ export interface LaunchDefaultsRoleView {
73
+ stored: LaunchDefaultEntry | null;
74
+ /** The existing daemon resolver's result, including loud failures. */
75
+ effective: LaunchDefaultResolution;
76
+ }
77
+ type Target = { role: 'assistant'; project?: never } | { role: 'coordinator'; project?: string };
78
+ export type LaunchDefaultsReadRequest =
79
+ | ({ action?: 'get' } & (Target | { role?: never; project?: never }))
80
+ | ({ action: 'check' } & Target & LaunchDefaultSelection);
81
+ /** Mandatory CAS: global document token, or host project token for project writes.
82
+ * 0 is explicit first setup; clears advance the token and never restore fallback. */
83
+ export type LaunchDefaultsSetRequest = Target & { expectedRevision: number } & (
84
+ | ({ action: 'set' } & LaunchDefaultSelection)
85
+ | { action: 'clear'; provider?: never; model?: never; thinkingLevel?: never }
86
+ );
87
+ /** Existing assistant routing envelope; session identity never supplies origin. */
88
+ export type AssistantLaunchDefaultsReadRequest = LaunchDefaultsReadRequest & { assistantSessionId?: string };
89
+ export type AssistantLaunchDefaultsSetRequest = LaunchDefaultsSetRequest & { assistantSessionId?: string };
90
+ export const LAUNCH_DEFAULT_ERROR_CODES = [
91
+ 'invalid_args', 'launch_default_required', 'launch_default_unavailable', 'launch_selection_invalid',
92
+ 'launch_default_invalid', 'revision_conflict', 'store_unavailable', 'store_busy', 'persistence_failed',
93
+ 'project_not_found', 'project_ambiguous', 'project_not_hosted', 'project_storage_unavailable',
94
+ 'staging_unavailable', 'staging_failed', 'review_turn_tool_denied',
95
+ ] as const;
96
+ export type LaunchDefaultsErrorCode = typeof LAUNCH_DEFAULT_ERROR_CODES[number];
97
+ export interface LaunchDefaultsError {
98
+ success: false;
99
+ code: LaunchDefaultsErrorCode;
100
+ error: string;
101
+ reason?: string;
102
+ role?: LaunchDefaultRole;
103
+ field?: LaunchDefaultField;
104
+ source?: LaunchDefaultSource;
105
+ value?: string | null;
106
+ defaultRef?: LaunchDefaultRef;
107
+ candidates?: readonly string[];
108
+ actualRevision?: number;
109
+ /** 0 for an absent global document; absent when it cannot be read. */
110
+ documentRevision?: number;
111
+ /** A persistence failure can replace intent without confirming durability.
112
+ * Re-read before retrying; never report applied on committed:true alone. */
113
+ committed?: boolean;
114
+ }
115
+ export interface LaunchDefaultsReadSuccess {
116
+ success: true;
117
+ result: 'get';
118
+ documentRevision: number;
119
+ roles: Partial<Record<LaunchDefaultRole, LaunchDefaultsRoleView>>;
120
+ project?: { projectId: string; revision: number; entry: LaunchDefaultEntry | null };
121
+ }
122
+ export interface LaunchDefaultsCheckSuccess {
123
+ success: true;
124
+ result: 'check';
125
+ role: LaunchDefaultRole;
126
+ selection: LaunchDefaultSelection;
127
+ warnings: LaunchDefaultWarning[];
128
+ toolRestriction: LaunchDefaultToolRestriction;
129
+ lowersToolLock: boolean;
130
+ }
131
+ export interface LaunchDefaultsApplied {
132
+ success: true;
133
+ result: 'applied';
134
+ role: LaunchDefaultRole;
135
+ scope: 'global' | 'project';
136
+ projectId?: string;
137
+ entry: LaunchDefaultEntry | null;
138
+ previous: LaunchDefaultEntry | null;
139
+ /** CAS token returned by the authority that performed the write. */
140
+ revision: number;
141
+ warnings: LaunchDefaultWarning[];
142
+ durable: true;
143
+ note: string;
144
+ }
145
+ export interface LaunchDefaultsStaged {
146
+ success: true;
147
+ result: 'staged';
148
+ role: LaunchDefaultRole;
149
+ stagedId: string;
150
+ previous: LaunchDefaultEntry | null;
151
+ selection: LaunchDefaultSelection | null;
152
+ expectedRevision: number;
153
+ warnings: LaunchDefaultWarning[];
154
+ note: string;
155
+ }
156
+ /** Existing owner Inbox adapter stores this proposal; it is not another default.
157
+ * Applying it must revalidate on the host and CAS via the same set handler. */
158
+ export interface LaunchDefaultsProposal {
159
+ kind: 'launch_defaults';
160
+ role: LaunchDefaultRole;
161
+ project?: string;
162
+ selection: LaunchDefaultSelection | null;
163
+ previous: LaunchDefaultEntry | null;
164
+ expectedRevision: number;
165
+ origin: LaunchDefaultOrigin;
166
+ callerSessionId?: string;
167
+ }
168
+ export type LaunchDefaultsReadResponse = LaunchDefaultsReadSuccess | LaunchDefaultsCheckSuccess | LaunchDefaultsError;
169
+ export type LaunchDefaultsSetResponse = LaunchDefaultsApplied | LaunchDefaultsStaged | LaunchDefaultsError;
170
+ export type LaunchDefaultsResponse = LaunchDefaultsReadResponse | LaunchDefaultsSetResponse;
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Same-machine light task — shared vocabulary and wire shapes (design
3
+ * docs/design/2026-11-01-same-machine-light-task.md).
4
+ *
5
+ * A light task is a `code_change` queue row that runs in a per-task scratch checkout
6
+ * (light workspace) on the coordinator's machine, based on the coordinator checkout's
7
+ * commit. Dependency-free leaf: daemon-core, mcp-server and web-core all import this.
8
+ */
9
+
10
+ /** Enqueue refusals (thrown as `<code>: <message>`). */
11
+ export const LIGHT_REJECT = {
12
+ REQUIRES_LOCAL_BASE: 'light_requires_local_base',
13
+ NOT_CONFIGURED: 'light_workspace_not_configured',
14
+ REQUIRES_OWNED_PATHS: 'light_requires_owned_paths',
15
+ MODE_CONFLICT: 'light_mode_conflict',
16
+ } as const
17
+ export type LightRejectCode = typeof LIGHT_REJECT[keyof typeof LIGHT_REJECT]
18
+
19
+ /** Pending-row hold reasons set by the light dispatcher. */
20
+ export const LIGHT_HOLD = {
21
+ PREPARE_FAILED: 'light_workspace_prepare_failed',
22
+ LIMIT: 'light_workspace_limit',
23
+ DISK_LOW: 'light_workspace_disk_low',
24
+ CAP: 'max_light_parallel_tasks_reached',
25
+ } as const
26
+
27
+ /** Reasons a finished light result is not landable (`landing: 'blocked'`). */
28
+ export const LIGHT_BLOCK_REASONS = [
29
+ 'light_uncommitted_changes',
30
+ 'light_dependency_change',
31
+ 'light_lineage_unproven',
32
+ 'shared_checkout_mutated',
33
+ ] as const
34
+ export type LightBlockReason = typeof LIGHT_BLOCK_REASONS[number]
35
+
36
+ /** Non-blocking observations recorded on the result. */
37
+ export const LIGHT_WARNINGS = ['shared_checkout_changed_during_task', 'light_base_dirty_overlap'] as const
38
+ export type LightWarning = typeof LIGHT_WARNINGS[number]
39
+
40
+ export const LIGHT_LAND_MODES = ['refine', 'apply_to_checkout'] as const
41
+ export type LightLandMode = typeof LIGHT_LAND_MODES[number]
42
+
43
+ export type LightLandingState = 'ready' | 'conflict' | 'blocked' | 'landed' | 'discarded'
44
+
45
+ export interface LightApplyCheckSide {
46
+ /** Commit the result was checked against. */
47
+ against: string
48
+ status: 'clean' | 'conflict' | 'base_unavailable'
49
+ conflictPaths?: string[]
50
+ }
51
+
52
+ /** merge-tree apply-check of the root (`.`) and each submodule, vs the base HEAD and `origin/<base>`. */
53
+ export interface LightApplyCheck {
54
+ head: LightApplyCheckSide
55
+ remote?: LightApplyCheckSide
56
+ }
57
+
58
+ /** Worker-reported test run (`report_completion.testsRun`). Self-reported, never trusted as evidence. */
59
+ export interface LightTestRun {
60
+ command: string
61
+ exit: number
62
+ passed?: number
63
+ failed?: number
64
+ note?: string
65
+ }
66
+
67
+ export const LIGHT_TESTS_RUN_MAX = 20
68
+
69
+ export interface LightTaskResult {
70
+ workspaceId: string
71
+ /** root branch (`mesh/light/<taskId8>`) */
72
+ branch: string
73
+ /** submodule path -> branch */
74
+ submoduleBranches?: Record<string, string>
75
+ rootBaseSha: string
76
+ rootHeadSha?: string
77
+ submoduleHeads?: Record<string, { base: string; head: string }>
78
+ touchedPaths: string[]
79
+ ownedPathsMismatch?: string[]
80
+ applyCheck?: LightApplyCheck
81
+ patchArtifactIds: string[]
82
+ testsRun?: LightTestRun[]
83
+ landing: LightLandingState
84
+ blockedReason?: LightBlockReason
85
+ blockedDetail?: string
86
+ warnings?: LightWarning[]
87
+ landedAt?: string
88
+ landedVia?: LightLandMode
89
+ /** The verified source packet (`MeshSourceCandidate`) for this result; tests carry no log hashes. */
90
+ sourceCandidate?: import('./task-source-phase').MeshSourceCandidate
91
+ capturedAt: string
92
+ }
93
+
94
+ export interface LightLandRequest {
95
+ taskIds: string[]
96
+ mode?: LightLandMode
97
+ dryRun?: boolean
98
+ /** Required when a result touched paths outside its `owned_paths`. */
99
+ acceptPathsOutsideOwned?: boolean
100
+ /** Land the leading non-conflicting tasks when a later one conflicts. */
101
+ partial?: boolean
102
+ approvedPublishShas?: string[]
103
+ }
104
+
105
+ /**
106
+ * True when a session record/state (or a bare settings object) belongs to a light-task worker, i.e.
107
+ * it was launched with `settings.lightWorkspaceId`. A light session is bound to ONE task's scratch
108
+ * workspace and, by the central claim rule, can never claim any other row — so it is never "the
109
+ * node's worker" for duplicate-launch guards, auto-launch gating or concurrency counts.
110
+ */
111
+ export function isLightWorkerSession(session: unknown): boolean {
112
+ const s = session as any
113
+ if (!s || typeof s !== 'object') return false
114
+ const has = (o: any): boolean => !!o && typeof o === 'object' && typeof o.lightWorkspaceId === 'string' && o.lightWorkspaceId.trim() !== ''
115
+ return has(s.settings) || has(s.launchRecord?.settings) || has(s)
116
+ }
@@ -27,7 +27,12 @@ export const CANONICAL_MESH_TOOL_NAMES = [
27
27
  'mesh_enqueue_task',
28
28
  'mesh_view_queue',
29
29
  'mesh_queue_cancel',
30
+ 'mesh_task_stage_decide',
31
+ 'mesh_direct_cancel',
30
32
  'mesh_queue_requeue',
33
+ 'mesh_queue_revise',
34
+ 'mesh_light_land',
35
+ 'mesh_light_discard',
31
36
  'mesh_send_task',
32
37
  'mesh_read_chat',
33
38
  'mesh_read_debug',
@@ -44,8 +49,13 @@ export const CANONICAL_MESH_TOOL_NAMES = [
44
49
  'mesh_list_pending_approvals',
45
50
  'mesh_create',
46
51
  'mesh_add_node',
52
+ 'mesh_reattach_source_parent',
53
+ 'mesh_attach_remote',
54
+ 'mesh_host_pairing',
47
55
  'mesh_clone_node',
48
56
  'mesh_remove_node',
57
+ 'mesh_retry_node_bootstrap',
58
+ 'mesh_recover_node_identity',
49
59
  'mesh_cleanup_worktree_nodes',
50
60
  'mesh_refine_node',
51
61
  'mesh_refine_batch',
@@ -62,8 +72,20 @@ export const CANONICAL_MESH_TOOL_NAMES = [
62
72
  'mesh_reconcile_ledger',
63
73
  'mesh_mission_upsert',
64
74
  'mesh_mission_list',
75
+ 'mesh_mission_git_eval',
76
+ 'mesh_release_upsert',
77
+ 'mesh_release_scope',
78
+ 'mesh_release_list',
79
+ 'mesh_release_record_deploy',
80
+ 'mesh_release_changelog_draft',
81
+ 'mesh_file_transfer',
65
82
  'mesh_review_inbox',
66
83
  'mesh_node_slots',
84
+ 'driver_list',
85
+ 'driver_describe',
86
+ 'artifact_list',
87
+ 'artifact_read',
88
+ 'artifact_register',
67
89
  ] as const;
68
90
 
69
91
  export type CanonicalMeshToolName = typeof CANONICAL_MESH_TOOL_NAMES[number];
@@ -17,10 +17,12 @@
17
17
 
18
18
  export { MESH_TASK_DIFFICULTIES, type MeshTaskDifficulty } from './brain-routing'
19
19
 
20
- export const MESH_TASK_STATUSES = ['pending', 'assigned', 'completed', 'failed', 'cancelled'] as const
20
+ /** `blocked` ends a worker attempt pending external follow-up; only completed satisfies dependencies.
21
+ * Branch convergence (including blocked_review) remains an independent axis. */
22
+ export const MESH_TASK_STATUSES = ['pending', 'assigned', 'completed', 'blocked', 'failed', 'cancelled'] as const
21
23
  export type MeshTaskStatus = typeof MESH_TASK_STATUSES[number]
22
24
 
23
- export const MESH_TERMINAL_TASK_STATUSES = ['completed', 'failed', 'cancelled'] as const
25
+ export const MESH_TERMINAL_TASK_STATUSES = ['completed', 'blocked', 'failed', 'cancelled'] as const
24
26
  export type MeshTerminalTaskStatus = typeof MESH_TERMINAL_TASK_STATUSES[number]
25
27
 
26
28
  export const MESH_TASK_MODES = ['code_change', 'validation', 'live_debug_readonly', 'launch_app', 'convergence'] as const
@@ -56,6 +58,14 @@ export type MeshSessionCleanupMode = typeof MESH_SESSION_CLEANUP_MODES[number]
56
58
  export const WORKER_REPORT_OUTCOMES = ['completed', 'blocked', 'failed'] as const
57
59
  export type WorkerReportOutcome = typeof WORKER_REPORT_OUTCOMES[number]
58
60
 
61
+ /**
62
+ * Hard cap on a `report_completion` summary (characters, after trim). Over-limit
63
+ * summaries are REJECTED, never truncated. Declared once so the daemon validator
64
+ * and the mcp-server's pre-send check (which keeps an over-limit report out of the
65
+ * durable outbox) cannot drift apart.
66
+ */
67
+ export const WORKER_REPORT_SUMMARY_MAX_CHARS = 8_000
68
+
59
69
  /** Final branch state a worker reports (see coordinator convergence rules). */
60
70
  export const WORKER_BRANCH_STATES = [
61
71
  'merged_to_main',
@@ -0,0 +1,112 @@
1
+ /**
2
+ * mission-git-state — types and the pure aggregation for "did this mission's
3
+ * referenced commits/branches land on the default branch?"
4
+ * (docs/design/2026-11-01-mission-git-refs.md §3).
5
+ *
6
+ * The facts come from the daemon opening git objects itself (never from
7
+ * commit-message text, branch-name similarity or worker prose). `landed` means
8
+ * ONLY "the referenced changes are on the base"; it never implies live
9
+ * acceptance, mission completion or that remaining items are done, and it is
10
+ * never used to change a mission's status.
11
+ *
12
+ * Dependency-free leaf: plain data in, plain data out.
13
+ */
14
+
15
+ /** Per-ref verdict. `unknown` is never folded into `not_contained` nor promoted to `contained_*`. */
16
+ export const MISSION_REF_GIT_STATUSES = ['contained_ancestor', 'contained_patch_equivalent', 'not_contained', 'unknown'] as const
17
+ export type MissionRefGitStatus = typeof MISSION_REF_GIT_STATUSES[number]
18
+
19
+ /** How a contained verdict was reached. */
20
+ export const MISSION_REF_GIT_METHODS = ['ancestry', 'cherry', 'residual_patch'] as const
21
+ export type MissionRefGitMethod = typeof MISSION_REF_GIT_METHODS[number]
22
+
23
+ /** Mission-level projection. */
24
+ export const MISSION_GIT_STATES = ['no_refs', 'landed', 'partial', 'not_landed', 'unknown'] as const
25
+ export type MissionGitStateValue = typeof MISSION_GIT_STATES[number]
26
+
27
+ export function isMissionRefContained(status: MissionRefGitStatus): boolean {
28
+ return status === 'contained_ancestor' || status === 'contained_patch_equivalent'
29
+ }
30
+
31
+ /** Why a ref is `unknown` (detail.unknownReason). Free-form strings are tolerated on read. */
32
+ export type MissionRefUnknownReason =
33
+ | 'object_missing'
34
+ | 'shallow'
35
+ | 'undeterminable'
36
+ | 'base_missing'
37
+ | 'branch_not_found'
38
+ | 'base_branch_ref'
39
+ | 'gitlink_undeterminable'
40
+ | 'merge_tree_failed'
41
+ | 'node_offline'
42
+ | 'no_repo'
43
+ | 'budget'
44
+ | 'not_a_git_ref'
45
+
46
+ export interface MissionRefGitDetail {
47
+ reasonCode?: string
48
+ unknownReason?: MissionRefUnknownReason | string
49
+ /** `modified_since_landing_possible`: main later touched the same lines — shown as a hint, not a verdict. */
50
+ note?: string
51
+ nodeId?: string
52
+ residualPatchId?: string
53
+ ahead?: number
54
+ behind?: number
55
+ }
56
+
57
+ /** One stored per-ref evaluation (a row of `mesh_mission_ref_evals`). */
58
+ export interface MissionRefGitEval {
59
+ itemId: string
60
+ /** `kind:repo:value` (normalized, lower-case SHA). */
61
+ refKey: string
62
+ kind: 'commit' | 'branch'
63
+ value: string
64
+ repo?: string
65
+ /** Branch refs: the SHA the name resolved to at first evaluation (re-evaluation keeps using it). */
66
+ pinnedSha?: string
67
+ baseRef: string
68
+ baseSha?: string
69
+ status: MissionRefGitStatus
70
+ method?: MissionRefGitMethod
71
+ detail?: MissionRefGitDetail
72
+ evaluatedAt: string
73
+ }
74
+
75
+ export interface MissionGitState {
76
+ missionId: string
77
+ state: MissionGitStateValue
78
+ /** `partial` only: some refs were `unknown` (not just `not_contained`). */
79
+ partialUnknown: boolean
80
+ counts: { total: number; contained: number; notContained: number; unknown: number }
81
+ /** Base the newest evaluation compared against. */
82
+ baseRef?: string
83
+ baseSha?: string
84
+ /** Oldest `evaluatedAt` among the refs (the freshness floor). */
85
+ evaluatedAt?: string
86
+ /** True when no row exists yet / the rows are older than the TTL — a refresh was (or can be) triggered. */
87
+ stale: boolean
88
+ refs: MissionRefGitEval[]
89
+ }
90
+
91
+ /**
92
+ * Aggregate per-ref statuses (design §3.3):
93
+ * - none → `no_refs`; all contained → `landed`; some contained → `partial`
94
+ * (`partialUnknown` when any of the rest is `unknown`);
95
+ * - none contained: all `not_contained` → `not_landed`, otherwise `unknown`.
96
+ */
97
+ export function aggregateMissionGitState(statuses: readonly MissionRefGitStatus[]): {
98
+ state: MissionGitStateValue
99
+ partialUnknown: boolean
100
+ counts: MissionGitState['counts']
101
+ } {
102
+ const total = statuses.length
103
+ const contained = statuses.filter(isMissionRefContained).length
104
+ const notContained = statuses.filter(s => s === 'not_contained').length
105
+ const unknown = statuses.filter(s => s === 'unknown').length
106
+ const counts = { total, contained, notContained, unknown }
107
+ if (total === 0) return { state: 'no_refs', partialUnknown: false, counts }
108
+ if (contained === total) return { state: 'landed', partialUnknown: false, counts }
109
+ if (contained > 0) return { state: 'partial', partialUnknown: unknown > 0, counts }
110
+ if (notContained === total) return { state: 'not_landed', partialUnknown: false, counts }
111
+ return { state: 'unknown', partialUnknown: false, counts }
112
+ }