@adhdev/daemon-core 1.0.18-rc.2 → 1.0.18-rc.20

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 (82) hide show
  1. package/dist/cli-adapters/cli-state-engine.d.ts +77 -0
  2. package/dist/cli-adapters/provider-cli-shared.d.ts +33 -0
  3. package/dist/cli-adapters/pty-transport.d.ts +2 -1
  4. package/dist/commands/cli-manager.d.ts +9 -0
  5. package/dist/commands/process-lifecycle.d.ts +43 -0
  6. package/dist/commands/upgrade-helper.d.ts +1 -0
  7. package/dist/commands/windows-atomic-upgrade.d.ts +17 -1
  8. package/dist/config/mesh-json-config.d.ts +62 -0
  9. package/dist/index.d.ts +4 -2
  10. package/dist/index.js +6674 -4237
  11. package/dist/index.js.map +1 -1
  12. package/dist/index.mjs +6361 -3927
  13. package/dist/index.mjs.map +1 -1
  14. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  15. package/dist/mesh/mesh-active-work.d.ts +1 -1
  16. package/dist/mesh/mesh-disk-retention.d.ts +105 -0
  17. package/dist/mesh/mesh-ledger.d.ts +28 -1
  18. package/dist/mesh/mesh-node-identity.d.ts +23 -0
  19. package/dist/mesh/mesh-refine-gates.d.ts +89 -0
  20. package/dist/mesh/mesh-remote-event-pull.d.ts +3 -0
  21. package/dist/mesh/mesh-runtime-store.d.ts +11 -0
  22. package/dist/mesh/mesh-work-queue.d.ts +24 -1
  23. package/dist/providers/auto-approve-modes.d.ts +14 -0
  24. package/dist/providers/chat-message-normalization.d.ts +22 -0
  25. package/dist/providers/cli-provider-instance-types.d.ts +4 -0
  26. package/dist/providers/cli-provider-instance.d.ts +78 -0
  27. package/dist/providers/contracts.d.ts +17 -0
  28. package/dist/providers/provider-schema.d.ts +1 -0
  29. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +14 -0
  30. package/dist/providers/types/interactive-prompt.d.ts +18 -0
  31. package/dist/repo-mesh-types.d.ts +38 -6
  32. package/dist/shared-types.d.ts +4 -2
  33. package/package.json +3 -3
  34. package/src/boot/daemon-lifecycle.ts +10 -0
  35. package/src/cli-adapters/cli-state-engine.ts +220 -3
  36. package/src/cli-adapters/provider-cli-adapter.ts +41 -11
  37. package/src/cli-adapters/provider-cli-shared.ts +48 -0
  38. package/src/cli-adapters/pty-transport.d.ts +2 -1
  39. package/src/cli-adapters/pty-transport.ts +1 -1
  40. package/src/cli-adapters/session-host-transport.ts +8 -3
  41. package/src/commands/cli-manager.ts +72 -8
  42. package/src/commands/high-family/mesh-coordinator-launch.ts +17 -2
  43. package/src/commands/high-family/mesh-events.ts +13 -2
  44. package/src/commands/med-family/mesh-crud.ts +155 -0
  45. package/src/commands/med-family/mesh-queue.ts +74 -1
  46. package/src/commands/process-lifecycle.ts +248 -0
  47. package/src/commands/router-refine.ts +71 -4
  48. package/src/commands/router.ts +8 -0
  49. package/src/commands/upgrade-helper.ts +106 -82
  50. package/src/commands/windows-atomic-upgrade.ts +281 -35
  51. package/src/config/mesh-json-config.ts +111 -0
  52. package/src/index.ts +21 -1
  53. package/src/mesh/coordinator-prompt.ts +258 -11
  54. package/src/mesh/mesh-active-work.ts +11 -1
  55. package/src/mesh/mesh-completion-synthesis.ts +12 -1
  56. package/src/mesh/mesh-disk-retention.ts +370 -0
  57. package/src/mesh/mesh-event-classify.ts +19 -0
  58. package/src/mesh/mesh-event-forwarding.ts +64 -6
  59. package/src/mesh/mesh-events-utils.ts +42 -0
  60. package/src/mesh/mesh-ledger.ts +77 -0
  61. package/src/mesh/mesh-node-identity.ts +49 -0
  62. package/src/mesh/mesh-queue-assignment.ts +210 -11
  63. package/src/mesh/mesh-reconcile-loop.ts +306 -3
  64. package/src/mesh/mesh-refine-gates.ts +300 -0
  65. package/src/mesh/mesh-remote-event-pull.ts +68 -47
  66. package/src/mesh/mesh-runtime-store.ts +21 -0
  67. package/src/mesh/mesh-work-queue.ts +85 -2
  68. package/src/providers/auto-approve-modes.ts +103 -0
  69. package/src/providers/chat-message-normalization.ts +53 -0
  70. package/src/providers/cli-provider-instance-types.ts +53 -0
  71. package/src/providers/cli-provider-instance.ts +497 -15
  72. package/src/providers/contracts.ts +25 -1
  73. package/src/providers/provider-schema.ts +83 -0
  74. package/src/providers/sdk/v1/builders/cli/detect-status.ts +23 -0
  75. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +20 -0
  76. package/src/providers/sdk/v1/schemas/cli/provider.schema.json +44 -0
  77. package/src/providers/types/interactive-prompt.ts +77 -0
  78. package/src/repo-mesh-types.ts +112 -12
  79. package/src/session-host/managed-host.ts +34 -0
  80. package/src/shared-types.ts +9 -1
  81. package/src/status/reporter.ts +1 -0
  82. package/src/status/snapshot.ts +2 -0
@@ -68,6 +68,41 @@ export interface CoordinatorOperatingNote {
68
68
  category?: 'provider_quirk' | 'pattern_to_avoid' | 'recovery_lesson';
69
69
  createdAt?: string;
70
70
  sourceCoordinator?: string;
71
+ /**
72
+ * Operating-notes lifecycle (minimal first cut). When true the note ALWAYS
73
+ * rides into the coordinator prompt — it is never dropped by TTL expiry and
74
+ * survives the injection cap ahead of unpinned notes. Legacy notes without
75
+ * this field default to false.
76
+ */
77
+ pinned?: boolean;
78
+ /**
79
+ * Optional explicit expiry ISO timestamp. When set and in the past, an
80
+ * UNPINNED note is dropped from the injected prompt (read-side only — the
81
+ * ledger entry is never pruned by age). When absent, the category→TTL map
82
+ * (see isNoteExpired) governs expiry; pinned notes never expire regardless.
83
+ */
84
+ expiresAt?: string;
85
+ /**
86
+ * Phase 2 — the ledger id of this note, when known. Threaded from the ledger
87
+ * entry id at launch so version-supersede can target a specific note and
88
+ * same-class folding can list the subsumed ids. Repo-declared notes may lack
89
+ * one; absent is fine (folding/supersede fall back to the subject key).
90
+ */
91
+ noteId?: string;
92
+ /**
93
+ * Phase 2 (b) version-supersede — an optional note-id or stable subject-key
94
+ * this note replaces. At injection, any earlier LIVE note whose `noteId` or
95
+ * `subjectKey` matches this value is hidden from the prompt (the ledger entry
96
+ * is retained for audit). Optional and lossless: absent = supersedes nothing.
97
+ */
98
+ supersedes?: string;
99
+ /**
100
+ * Phase 2 (b)/(c) — an optional stable subject-key grouping notes about the
101
+ * same subject. Drives version-supersede targeting and same-class folding.
102
+ * When absent, folding derives a key from a leading `[tag]` bracket instead,
103
+ * so legacy notes still collapse by their conventional tag prefix.
104
+ */
105
+ subjectKey?: string;
71
106
  }
72
107
  export interface CoordinatorPromptContext {
73
108
  mesh: LocalMeshEntry;
@@ -102,6 +137,46 @@ export interface CoordinatorPromptContext {
102
137
  magiKindPanels?: MagiKindPanelMap;
103
138
  }
104
139
  export declare function buildCoordinatorSystemPrompt(ctx: CoordinatorPromptContext): string;
140
+ /**
141
+ * Phase 2 (c) — deterministic same-class fold. Given ranked notes (already
142
+ * highest-priority first), collapse runs of UNPINNED notes that share the same
143
+ * category AND subject key into a single injected entry: keep the highest-ranked
144
+ * (first-seen) note and record the note-ids/count it subsumes so the rendered
145
+ * line can say "(+N earlier)". Pinned notes never fold — each pinned note is
146
+ * author-opted-in and shown verbatim. The store is untouched; this is a pure,
147
+ * model-free text fold at injection time.
148
+ *
149
+ * Returns the folded note list (order preserved) with per-entry subsumed info.
150
+ */
151
+ interface FoldedNote {
152
+ note: CoordinatorOperatingNote;
153
+ /** note-ids of same-class notes this entry subsumes (may be empty). */
154
+ subsumedIds: string[];
155
+ /** count of subsumed notes (== subsumedIds.length, but counts id-less ones too). */
156
+ subsumedCount: number;
157
+ }
158
+ /**
159
+ * Operating-notes lifecycle selection (read-side). Given the effective notes
160
+ * (oldest-first, ledger order) and the current time, produce the ordered list
161
+ * that rides into the prompt:
162
+ * (i) ALWAYS include pinned notes.
163
+ * (ii) drop expired UNPINNED notes (per category TTL / explicit expiresAt).
164
+ * (iii) Phase 2 (b) drop any note SUPERSEDED by a later live note (by noteId
165
+ * or subjectKey); pinned notes are never dropped by supersede.
166
+ * (iv) rank pinned-first, then durable-category, then recency (newest first).
167
+ * (v) Phase 2 (c) fold same-category/same-subject unpinned runs into one.
168
+ * (vi) Phase 2 (d) fill up to a byte budget AND a count cap; pinned always
169
+ * kept even if they alone exceed the byte budget.
170
+ * Pure + deterministic given `now`. Returns { shown, omittedCount } where `shown`
171
+ * carries per-entry fold info for the renderer.
172
+ *
173
+ * Ranking is stable on the original ledger index so, within a tier, newest notes
174
+ * lead. The caps keep the leading (highest-priority) entries.
175
+ */
176
+ export declare function selectOperatingNotesForPrompt(notes: CoordinatorOperatingNote[], now: number, cap?: number, byteBudget?: number): {
177
+ shown: FoldedNote[];
178
+ omittedCount: number;
179
+ };
105
180
  /**
106
181
  * Render the machine-local MAGI kind-panel bindings so the coordinator KNOWS
107
182
  * which cross-verification panels (rca / design / claim_audit / freeform) are
@@ -114,3 +189,4 @@ export declare function buildCoordinatorSystemPrompt(ctx: CoordinatorPromptConte
114
189
  * That keeps a MAGI-less mesh's prompt byte-identical to before.
115
190
  */
116
191
  export declare function buildMagiKindPanelsSection(panels: MagiKindPanelMap | undefined | null): string | null;
192
+ export {};
@@ -1,7 +1,7 @@
1
1
  import type { MeshLedgerEntry } from './mesh-ledger.js';
2
2
  import type { MeshWorkQueueEntry, DirectDispatchRecord } from './mesh-work-queue.js';
3
3
  export type MeshActiveWorkSource = 'queue' | 'direct';
4
- export type MeshActiveWorkStatus = 'pending' | 'assigned' | 'generating' | 'idle' | 'failed' | 'awaiting_approval';
4
+ export type MeshActiveWorkStatus = 'pending' | 'assigned' | 'generating' | 'idle' | 'failed' | 'awaiting_approval' | 'awaiting_choice';
5
5
  export interface MeshActiveWorkRecord {
6
6
  taskId: string;
7
7
  source: MeshActiveWorkSource;
@@ -0,0 +1,105 @@
1
+ import type { SessionHostSurfaceRecordLike } from '../session-host/runtime-surface.js';
2
+ import type { LocalMeshEntry } from '../repo-mesh-types.js';
3
+ export declare const DAY_MS: number;
4
+ /** JSONL ledger files are legacy after the SQLite ledger — 30-day lifetime. */
5
+ export declare const LEDGER_JSONL_MAX_AGE_MS: number;
6
+ /** Terminated session-host runtimes: conservative 14-day retention. */
7
+ export declare const SESSION_HOST_RUNTIME_MAX_AGE_MS: number;
8
+ /** mesh-runtime.db.bak-* backups: 7-day retention. */
9
+ export declare const DB_BAK_MAX_AGE_MS: number;
10
+ /** A file candidate for age-based pruning: absolute path + last-modified epoch ms. */
11
+ export interface AgedFile {
12
+ path: string;
13
+ mtimeMs: number;
14
+ }
15
+ /**
16
+ * PURE. Select the JSONL ledger files whose mtime is older than `maxAgeMs`
17
+ * relative to `now`. A file exactly at the threshold is KEPT (strict `>`), so a
18
+ * 30-day-old file survives its 30th day and is pruned on the 31st. Deterministic:
19
+ * no fs access, no clock read.
20
+ */
21
+ export declare function selectExpiredLedgerJsonl(files: AgedFile[], now: number, maxAgeMs?: number): AgedFile[];
22
+ /** A parsed session-host runtime file: its path, mtime, and the wrapped record. */
23
+ export interface SessionHostRuntimeFile {
24
+ path: string;
25
+ mtimeMs: number;
26
+ /** The `record` object from the on-disk `{ record, snapshot, updatedAt }` file. */
27
+ record: SessionHostSurfaceRecordLike | null;
28
+ }
29
+ /**
30
+ * PURE. Select the session-host runtime files safe to delete: ONLY those whose
31
+ * runtime is terminated/dead (NOT a live runtime — decided by the session-host-core
32
+ * SSOT `isSessionHostLiveRuntime`) AND older than `maxAgeMs`. A live runtime, or a
33
+ * dead-but-recent one, is always kept. A file whose record failed to parse is treated
34
+ * as NON-live but is still age-gated, so a corrupt-but-fresh file is never removed.
35
+ */
36
+ export declare function selectExpiredSessionHostRuntimes(files: SessionHostRuntimeFile[], now: number, maxAgeMs?: number): SessionHostRuntimeFile[];
37
+ /** True for a `mesh-runtime.db.bak-*` backup filename (basename only). */
38
+ export declare function isDbBackupFileName(name: string): boolean;
39
+ /** PURE. Select `.bak-*` backups older than `maxAgeMs`. Strict `>` (see ledger). */
40
+ export declare function selectExpiredDbBackups(files: AgedFile[], now: number, maxAgeMs?: number): AgedFile[];
41
+ /** Minimal shape needed to decide whether a worktree path is orphaned. */
42
+ export interface WorktreePathLike {
43
+ path: string;
44
+ bare?: boolean;
45
+ }
46
+ /** A live mesh node's known workspace paths (self workspace + repoRoot, normalized). */
47
+ export interface LiveNodeWorkspaceLike {
48
+ workspace?: string;
49
+ repoRoot?: string;
50
+ }
51
+ /**
52
+ * PURE. Given the worktrees git reports on disk and the set of live-node workspace
53
+ * paths, return the worktrees that have NO matching live node — the orphan
54
+ * cleanup_candidates.
55
+ *
56
+ * SAFETY:
57
+ * - `mainWorktreePath` (the primary repo checkout, i.e. worktree[0]) is NEVER an
58
+ * orphan — it is the base repo, not a mesh clone.
59
+ * - `bare` worktrees are skipped (git's internal bookkeeping, not a node checkout).
60
+ * - Matching is path-equality after trailing-separator normalization against the
61
+ * union of every live node's `workspace` and `repoRoot`.
62
+ * This is DETECTION ONLY — the caller signals a cleanup_candidate; it must not delete.
63
+ */
64
+ export declare function detectOrphanWorktrees(worktrees: WorktreePathLike[], liveNodes: LiveNodeWorkspaceLike[], mainWorktreePath: string): WorktreePathLike[];
65
+ /**
66
+ * Prune expired legacy JSONL ledger files under ~/.adhdev/mesh-ledger/.
67
+ * Matches only `*.jsonl` (never the SQLite .db / -wal / -shm files). Returns the
68
+ * count deleted. Best-effort: individual unlink failures are logged, not thrown.
69
+ */
70
+ export declare function pruneExpiredLedgerJsonl(now?: number): number;
71
+ /**
72
+ * Prune expired `mesh-runtime.db.bak-*` backups under ~/.adhdev/mesh-ledger/.
73
+ * Never touches the live DB (only names matching the .bak- prefix). Returns count.
74
+ */
75
+ export declare function pruneExpiredDbBackups(now?: number): number;
76
+ /**
77
+ * Prune terminated session-host runtime files older than 14 days across every
78
+ * ~/.adhdev/session-host/<app>/runtimes/ directory. A LIVE runtime is never deleted
79
+ * regardless of age (isSessionHostLiveRuntime SSOT). Returns count deleted.
80
+ */
81
+ export declare function pruneExpiredSessionHostRuntimes(now?: number): number;
82
+ /**
83
+ * Run the file-deleting retention passes (JSONL ledger, DB backups, session-host
84
+ * runtimes) once. Each pass is isolated so one failing pass never blocks the others.
85
+ * Orphan-worktree DETECTION is driven separately in the reconcile loop (it needs the
86
+ * live mesh config + git worktree list and emits a ledger signal rather than deleting).
87
+ */
88
+ export declare function runDiskRetentionSweep(now?: number): {
89
+ ledgerJsonl: number;
90
+ dbBackups: number;
91
+ sessionHostRuntimes: number;
92
+ };
93
+ /**
94
+ * Detect orphaned worktrees for ONE mesh and emit a `worktree_cleanup_candidate`
95
+ * ledger signal for each — DETECTION ONLY, never deletes. An orphan is a git worktree
96
+ * on disk with no matching live mesh node (compared by path). It:
97
+ * 1. picks a base (non-worktree) node owned by this mesh to anchor `git worktree list`;
98
+ * 2. diffs the reported worktrees against the union of every node's workspace/repoRoot;
99
+ * 3. skips the main worktree + bare entries (detectOrphanWorktrees safety);
100
+ * 4. suppresses a repeat for a worktreePath already signalled within the recent window
101
+ * (idempotent re-emit guard), so the hourly sweep doesn't spam the ledger.
102
+ * Returns the list of newly-signalled orphan paths. Best-effort: git/ledger failures are
103
+ * logged and yield an empty result, never thrown.
104
+ */
105
+ export declare function detectAndSignalOrphanWorktrees(mesh: LocalMeshEntry, now?: number): Promise<string[]>;
@@ -15,7 +15,7 @@
15
15
  import { EventEmitter } from 'events';
16
16
  import { MeshRuntimeStore } from './mesh-runtime-store.js';
17
17
  import { type MeshLedgerOriginatingCoordinatorV2 } from './contracts.js';
18
- export type MeshLedgerKind = 'task_dispatched' | 'task_completed' | 'task_failed' | 'task_stalled' | 'task_approval_needed' | 'p2p_dispatch_failed' | 'session_launched' | 'session_auto_launch' | 'session_stopped' | 'checkpoint_created' | 'node_cloned' | 'node_joined' | 'node_removed' | 'coordinator_started' | 'recovery_attempted' | 'ledger_replicated' | 'ledger_reconciled' | 'direct_fast_forward' | 'delivery_unroutable' | 'direct_dispatch_pruned' | 'event_held' | 'event_held_requeued' | 'task_reclaimed' | 'coordinator_operating_note' | 'coordinator_operating_note_tombstone' | 'mission_created' | 'mission_status_changed' | 'mission_goal_updated' | 'magi_dispatched' | 'magi_synthesis' | 'key_injection';
18
+ export type MeshLedgerKind = 'task_dispatched' | 'task_completed' | 'task_failed' | 'task_stalled' | 'task_approval_needed' | 'task_question_pending' | 'p2p_dispatch_failed' | 'session_launched' | 'session_auto_launch' | 'session_stopped' | 'checkpoint_created' | 'node_cloned' | 'node_joined' | 'node_removed' | 'coordinator_started' | 'recovery_attempted' | 'ledger_replicated' | 'ledger_reconciled' | 'direct_fast_forward' | 'delivery_unroutable' | 'direct_dispatch_pruned' | 'event_held' | 'event_held_requeued' | 'task_reclaimed' | 'coordinator_operating_note' | 'coordinator_operating_note_tombstone' | 'mission_created' | 'mission_status_changed' | 'mission_goal_updated' | 'magi_dispatched' | 'magi_synthesis' | 'key_injection' | 'worktree_cleanup_candidate';
19
19
  export interface MeshLedgerEntry {
20
20
  id: string;
21
21
  meshId: string;
@@ -162,6 +162,33 @@ export declare const OPERATING_NOTE_KIND: MeshLedgerKind;
162
162
  export declare const OPERATING_NOTE_TOMBSTONE_KIND: MeshLedgerKind;
163
163
  export declare const OPERATING_NOTE_DEDUPE_WINDOW = 40;
164
164
  export declare const OPERATING_NOTE_KEEP_LATEST = 100;
165
+ export declare const OPERATING_NOTE_CATEGORY_TTL_DAYS: Readonly<Record<string, number>>;
166
+ /**
167
+ * Shape isNoteExpired reads. Structural so mesh-ledger stays free of a
168
+ * coordinator-prompt import (CoordinatorOperatingNote satisfies this).
169
+ */
170
+ export interface OperatingNoteExpiryInput {
171
+ category?: string;
172
+ pinned?: boolean;
173
+ createdAt?: string;
174
+ /** Explicit expiry override; wins over the category TTL when parseable. */
175
+ expiresAt?: string;
176
+ /** Fallback creation time (ledger entry timestamp) when createdAt absent. */
177
+ timestamp?: string;
178
+ }
179
+ /**
180
+ * Pure helper: is this UNPINNED operating note expired as of `now` (epoch ms)?
181
+ *
182
+ * Rules:
183
+ * - pinned notes NEVER expire (always false).
184
+ * - an explicit, parseable `expiresAt` in the past → expired.
185
+ * - otherwise the category TTL applies; a durable category (provider_quirk,
186
+ * uncategorized, or any category not in the TTL map) never expires.
187
+ * - age is measured from createdAt, falling back to `timestamp` (ledger entry
188
+ * time). If neither is a valid date, the note is treated as NOT expired
189
+ * (never silently drop a note we cannot age).
190
+ */
191
+ export declare function isNoteExpired(note: OperatingNoteExpiryInput, now: number): boolean;
165
192
  export declare function getLedgerDir(): string;
166
193
  /**
167
194
  * Footer to append to worker task messages so workers output structured results
@@ -107,6 +107,29 @@ export declare function resolveEffectiveMeshNodeHealth(node: any): string;
107
107
  * replica that can never run.
108
108
  */
109
109
  export declare function isMeshNodeHealthLaunchable(node: any): boolean;
110
+ /**
111
+ * Launch FRESHNESS gate — distinct from the health gate above.
112
+ *
113
+ * `deriveMeshNodeHealthFromGit` reports a clean-tree node with `behind > 0` as
114
+ * 'online', so the health gate (isMeshNodeHealthLaunchable) happily lets a STALE
115
+ * node — one whose branch is N commits behind its upstream — win auto-launch fitness
116
+ * routing and run a fresh worker against out-of-date code. `behind` is deliberately
117
+ * NOT folded into deriveMeshNodeHealthFromGit because "behind" is not universally
118
+ * unhealthy (the MAGI planner and other callers share that resolver); it is only
119
+ * unhealthy for *spawning new work*. This gate encodes exactly that launch-time axis.
120
+ *
121
+ * Returns false (NOT fresh → skip / de-rank) only when git telemetry is PRESENT and
122
+ * proves staleness:
123
+ * - behind count exceeds `maxBehind` (default 0 — any behind blocks), OR
124
+ * - a submodule is out of sync (gitlink points off upstream — cannot be caught up
125
+ * by a simple worktree ff and would launch against a mismatched submodule).
126
+ *
127
+ * When telemetry is absent it returns true (fresh), preserving the online/unknown-pass
128
+ * philosophy: we never block on missing data, only on data that proves the node stale.
129
+ */
130
+ export declare function isMeshNodeFreshEnoughToLaunch(node: any, opts?: {
131
+ maxBehind?: number;
132
+ }): boolean;
110
133
  export declare function applyInlineMeshBranchConvergence(mesh: any, node: any, status: Record<string, unknown>): void;
111
134
  export declare function summarizeInlineMeshBranchConvergence(nodes: Array<Record<string, unknown>>): Record<string, unknown>;
112
135
  export declare function readCachedInlineMeshActiveSessions(node: any): string[];
@@ -504,6 +504,95 @@ type GitlinkTrivialFastForwardEvaluation = {
504
504
  * gate.
505
505
  */
506
506
  export declare function collectFastForwardGitlinkPaths(repoRoot: string, baseHead: string, branchHead: string): string[];
507
+ export type SubmoduleGitlinkConvergeResult = {
508
+ /** True when at least one diverged gitlink submodule was rebased onto its base-side commit. */
509
+ converged: boolean;
510
+ /**
511
+ * Set when convergence was declined/aborted (fail-safe → caller keeps the
512
+ * original defer→blocked_review path). One of:
513
+ * no_changed_gitlinks — no gitlink differs base↔branch
514
+ * not_diverged — the gitlink is ff/behind/equal (gate handles it)
515
+ * rebase_conflict — replaying branch-side onto base-side hit a real
516
+ * content conflict inside the submodule (aborted)
517
+ */
518
+ reason?: string;
519
+ /**
520
+ * Converged gitlinks: path → the rebased submodule commit (SUBNEW) that the
521
+ * root rebase must resolve the gitlink conflict to. Only populated for paths
522
+ * whose submodule was successfully rebased (base-side is now a strict ancestor).
523
+ */
524
+ resolutions: Array<{
525
+ path: string;
526
+ baseCommit: string;
527
+ branchCommit: string;
528
+ rebasedCommit: string;
529
+ }>;
530
+ /** Per-path outcome for observability/logging. */
531
+ gitlinks: Array<{
532
+ path: string;
533
+ baseCommit?: string;
534
+ branchCommit?: string;
535
+ rebasedCommit?: string;
536
+ action: 'rebased' | 'skipped_not_diverged' | 'rebase_conflict';
537
+ }>;
538
+ };
539
+ /**
540
+ * STEP 1 of auto-converging diverged oss-style submodule gitlinks: rebase the
541
+ * branch-side submodule commit(s) onto the base-side submodule commit INSIDE the
542
+ * worktree's submodule checkout (detached HEAD), so the base-side commit becomes a
543
+ * strict ancestor of the rebased tip. Returns the rebased commit per path so the
544
+ * caller's root rebase can resolve the gitlink conflict to it (STEP 2, see
545
+ * {@link rootRebaseResolvingGitlinks}). This automates the documented manual
546
+ * strict-fast-forward bypass and keeps the landed submodule history linear rather
547
+ * than masking a divergence.
548
+ *
549
+ * Fail-safe by construction: it only touches gitlinks that are a genuine sibling
550
+ * divergence (both commits local, neither an ancestor of the other, shared merge
551
+ * base). A submodule rebase content conflict aborts, restores the branch-side
552
+ * checkout, and returns `converged:false` (caller keeps defer→blocked_review). It
553
+ * never commits the root and NEVER pushes — remote publish is the merge/
554
+ * reachability stage's job; this stage is local reconciliation only.
555
+ *
556
+ * @param worktreeRoot the branch worktree root (its `<path>` submodule checkout is rebased)
557
+ * @param baseRepoRoot the source/base repo root (reads the base-side gitlink commit)
558
+ * @param baseHead the fetched base head (root ref) — source of base-side gitlink commits
559
+ * @param branchHead the worktree branch head (root ref) — source of branch-side gitlink commits
560
+ */
561
+ export declare function convergeDivergedSubmoduleGitlinks(worktreeRoot: string, baseRepoRoot: string, baseHead: string, branchHead: string): SubmoduleGitlinkConvergeResult;
562
+ export type RootRebaseGitlinkResolveResult = {
563
+ /** True when the root rebase completed (with gitlink conflicts resolved to the converged commits). */
564
+ ok: boolean;
565
+ /** New root HEAD after the rebase (only meaningful when ok). */
566
+ branchHead?: string;
567
+ /**
568
+ * Set when the rebase was aborted (fail-safe). One of:
569
+ * non_gitlink_conflict — a conflict on a non-submodule path (genuine content conflict)
570
+ * unexpected_gitlink — a gitlink conflicted that we have no converged commit for
571
+ * rebase_error — the rebase failed for a non-conflict reason
572
+ */
573
+ reason?: string;
574
+ /** The paths that conflicted at the point of abort (for diagnostics). */
575
+ conflictPaths?: string[];
576
+ };
577
+ /**
578
+ * STEP 2 of auto-converging diverged submodule gitlinks: rebase the worktree root
579
+ * branch onto `baseHead`, resolving each submodule-gitlink conflict to the
580
+ * pre-converged commit from {@link convergeDivergedSubmoduleGitlinks}. git's
581
+ * recursive merge refuses to auto-merge a diverged gitlink ("Recursive merging
582
+ * with submodules currently only supports trivial cases"), so we drive the rebase
583
+ * ourselves: on each stop, if the ONLY unmerged paths are gitlinks we have a
584
+ * converged commit for, we stage those to the converged commit and `--continue`.
585
+ * Any non-gitlink conflict (or a gitlink with no converged commit) aborts the
586
+ * rebase and returns `ok:false` → caller keeps the defer→blocked_review path.
587
+ *
588
+ * On success the base-side gitlink is a strict ancestor of the resolved branch-side
589
+ * commit, so the downstream patch-equivalence gate treats it as a trivial
590
+ * fast-forward and passes.
591
+ */
592
+ export declare function rootRebaseResolvingGitlinks(worktreeRoot: string, baseHead: string, resolutions: Array<{
593
+ path: string;
594
+ rebasedCommit: string;
595
+ }>): RootRebaseGitlinkResolveResult;
507
596
  /**
508
597
  * Decide whether a merge-tree submodule conflict between base and branch is a
509
598
  * trivial gitlink fast-forward (and nothing else).
@@ -1,6 +1,9 @@
1
1
  import type { DaemonComponents } from '../boot/daemon-lifecycle.js';
2
2
  import type { LocalMeshEntry } from '../repo-mesh-types.js';
3
3
  export declare function pullRemoteNodeQueues(components: DaemonComponents, mesh: LocalMeshEntry, localDaemonId: string | undefined, candidateDaemonIds: string[]): Promise<void>;
4
+ export declare function pullPendingEventsFromNode(components: DaemonComponents, meshId: string, node: {
5
+ daemonId?: string;
6
+ }, localDaemonId: string | undefined, candidateDaemonIds: string[], pulls: Array<Record<string, unknown>>): Promise<void>;
4
7
  export declare function unwrapReadChatPayload(raw: unknown): Record<string, unknown> | null;
5
8
  export declare function readChatPayloadStatus(payload: Record<string, unknown> | null): string;
6
9
  export declare function realTerminalEmitPendingForTask(meshId: string, taskId: string): boolean;
@@ -23,6 +23,17 @@ export declare class MeshRuntimeStore {
23
23
  private static loggedGetInstanceFailure;
24
24
  static getInstance(): MeshRuntimeStore;
25
25
  static resetForTests(): void;
26
+ /**
27
+ * VACUUM the SQLite database to reclaim on-disk space. Retention prunes rows
28
+ * with DELETE, which frees pages inside the file but does NOT shrink it — the
29
+ * mesh-runtime.db grew to hundreds of MB (mission 86def38d disk-accumulation
30
+ * bootstrap failure) precisely because the file was never compacted. This
31
+ * rewrites the DB into a minimal footprint. Best-effort: a VACUUM failure (e.g.
32
+ * insufficient temp space, a read lock) is logged and swallowed so it can never
33
+ * block daemon shutdown. Called once on shutdown (see daemon-lifecycle), never
34
+ * on the hot path — VACUUM takes an exclusive lock and rewrites the whole file.
35
+ */
36
+ vacuum(): void;
26
37
  close(): void;
27
38
  transaction<T>(fn: () => T): T;
28
39
  private migrate;
@@ -337,7 +337,15 @@ export type DependencyFailurePolicy = 'block' | 'cancel';
337
337
  * Update the status of a specific task.
338
338
  * Used when a session completes, fails, or stalls.
339
339
  */
340
- export declare function updateTaskStatus(meshId: string, taskId: string, status: MeshTaskStatus, opts?: MeshQueueMutationOptions): MeshWorkQueueEntry | null;
340
+ export declare function updateTaskStatus(meshId: string, taskId: string, status: MeshTaskStatus, opts?: {
341
+ /**
342
+ * CANCEL-STICKY-TERMINAL: operator/system override to permit a terminal→non-terminal
343
+ * transition (e.g. an explicit operator reopen). Without this, a write that would flip
344
+ * a `completed`/`failed`/`cancelled` row back to `pending`/`assigned` is refused as a
345
+ * no-op. Terminal→terminal and any transition FROM a non-terminal state are unaffected.
346
+ */
347
+ force?: boolean;
348
+ } & MeshQueueMutationOptions): MeshWorkQueueEntry | null;
341
349
  export declare function recordTaskAutoLaunch(meshId: string, taskId: string, autoLaunch: Omit<NonNullable<MeshWorkQueueEntry['autoLaunch']>, 'updatedAt'>): MeshWorkQueueEntry | null;
342
350
  /**
343
351
  * Mark a queue task as manually cancelled without deleting audit history.
@@ -345,6 +353,21 @@ export declare function recordTaskAutoLaunch(meshId: string, taskId: string, aut
345
353
  export declare function cancelTask(meshId: string, taskId: string, opts?: {
346
354
  reason?: string;
347
355
  } & MeshQueueMutationOptions): MeshWorkQueueEntry | null;
356
+ /**
357
+ * CANCEL-STICKY-TERMINAL: the assignment a task carried at cancel time, handed to the cancel
358
+ * command handler so it can stop the bound worker. cancelTask runs in the pure queue-store
359
+ * module (no DaemonComponents), so it records the binding here and the handler drains it.
360
+ */
361
+ export interface CancelledTaskAssignment {
362
+ sessionId: string;
363
+ nodeId?: string;
364
+ providerType?: string;
365
+ }
366
+ /**
367
+ * Read-and-clear the assignment a just-cancelled task was bound to. Returns undefined when the
368
+ * cancelled task had no live assignment (nothing to stop). One-shot: the entry is deleted on read.
369
+ */
370
+ export declare function takeCancelledTaskAssignment(meshId: string, taskId: string): CancelledTaskAssignment | undefined;
348
371
  /**
349
372
  * Return a queue task to pending for retry. By default, dead session targeting
350
373
  * and assigned ownership are cleared so stale assignments do not strand again.
@@ -0,0 +1,14 @@
1
+ import type { AutoApproveMode, AutoApproveModeRisk, AutoApproveModeStrategy, ProviderModule } from './contracts.js';
2
+ export interface ResolvedAutoApproveMode {
3
+ active: boolean;
4
+ strategy: AutoApproveModeStrategy;
5
+ modeId: string;
6
+ }
7
+ /** Runtime defense-in-depth for provider definitions that bypass schema validation. */
8
+ export declare function deriveAutoApproveModeRisk(mode: Pick<AutoApproveMode, 'risk' | 'launchArgs'>): AutoApproveModeRisk;
9
+ /**
10
+ * Resolve new mode settings before the legacy boolean. A stale/unknown explicit
11
+ * mode id fails closed instead of falling through to an enabled legacy setting.
12
+ */
13
+ export declare function resolveProviderAutoApproveMode(provider: ProviderModule | null | undefined, settings: Record<string, unknown> | undefined): ResolvedAutoApproveMode;
14
+ export declare function findProviderAutoApproveMode(provider: ProviderModule | undefined, modeId: string): AutoApproveMode | undefined;
@@ -58,6 +58,28 @@ export declare function extractFinalAssistantSummaryEvidence(messages: ChatMessa
58
58
  * grace gate) on top of this structural check.
59
59
  */
60
60
  export declare function selectFinalAssistantTurnEndMessage(messages: ChatMessage[] | null | undefined): ChatMessage | null;
61
+ /**
62
+ * EARLY-IDLE-COMPLETION-FALSE-POSITIVE — trailing tool/terminal activity detector.
63
+ *
64
+ * True when the transcript's LAST non-empty user-facing assistant bubble is followed
65
+ * by one or more TOOL / TERMINAL activity bubbles (a tool_use/command the assistant
66
+ * fired AFTER its text) — i.e. the assistant emitted a preamble ("Let me explore…"),
67
+ * then started running Read/Grep, so the turn is still executing and its answer has
68
+ * not landed. Callers that would otherwise promote that preamble to a turn-end summary
69
+ * off a momentary (startup-grace / inter-tool) idle read use this as a veto.
70
+ *
71
+ * Deliberately NARROW so the pure-PTY completion rescue is preserved:
72
+ * - Only TOOL/TERMINAL activity trailing the assistant vetoes. A trailing THOUGHT or
73
+ * status bubble does NOT (a finished turn can end on an internal thought), matching
74
+ * selectFinalAssistantTurnEndMessage's skip set minus the "still-working" signals.
75
+ * - A genuinely FINISHED worker (final assistant last, no trailing tool activity —
76
+ * the kimi pure-PTY continuous-idle shape) returns false, so its early completion
77
+ * is untouched.
78
+ *
79
+ * Returns false when there is no final assistant bubble at all (the caller's
80
+ * selectFinalAssistantTurnEndMessage already handles that as "not a turn end").
81
+ */
82
+ export declare function hasTrailingToolActivityAfterFinalAssistant(messages: ChatMessage[] | null | undefined): boolean;
61
83
  export declare const BUILTIN_CHAT_MESSAGE_KINDS: readonly ["standard", "thought", "tool", "terminal", "system"];
62
84
  export type BuiltinChatMessageKind = typeof BUILTIN_CHAT_MESSAGE_KINDS[number];
63
85
  export type ChatMessageKind = BuiltinChatMessageKind | (string & {});
@@ -19,6 +19,7 @@ export type CompletedFinalizationBlock = {
19
19
  terminal?: boolean;
20
20
  allowTimeout?: boolean;
21
21
  holdForTranscript?: boolean;
22
+ noExternalTranscriptSource?: boolean;
22
23
  };
23
24
  export type CompletionFinalAssistantEvidence = {
24
25
  present: boolean;
@@ -37,8 +38,11 @@ export type ExternalTranscriptProbe = {
37
38
  };
38
39
  export declare const COMPLETED_FINALIZATION_RETRY_MS = 1000;
39
40
  export declare const COMPLETED_FINALIZATION_MAX_WAIT_MS = 30000;
41
+ export declare const CANON_C_MISSING_ASSISTANT_MIN_ELAPSED_MS = 20000;
40
42
  export declare const NATIVE_HISTORY_MESH_IDLE_SETTLE_MS = 4000;
41
43
  export declare const PTY_PARSED_FINAL_ASSISTANT_QUIET_DWELL_MS = 1200;
44
+ export declare const ANTIGRAVITY_HOLD_QUIET_DWELL_MS = 3000;
45
+ export declare const ANTIGRAVITY_HOLD_HARD_CAP_MS: number;
42
46
  export declare const BACKGROUND_TASK_HOLD_MAX_MS: number;
43
47
  export declare const USER_INPUT_ACK_DEDUP_WINDOW_MS = 60000;
44
48
  export declare const STARTUP_GRACE_IDLE_COLLAPSE_WINDOW_MS = 12000;
@@ -192,6 +192,7 @@ export declare class CliProviderInstance implements ProviderInstance {
192
192
  private meshStallEmittedForAnchor;
193
193
  private meshStallTurnActiveLast;
194
194
  private meshStallLastFiredAt;
195
+ private meshStallNativeTranscriptSample;
195
196
  private busyEpoch;
196
197
  private fastCollapseSynthesizedTaskId;
197
198
  private startupGraceCollapseAt;
@@ -201,6 +202,7 @@ export declare class CliProviderInstance implements ProviderInstance {
201
202
  private generatingDebounceTimer;
202
203
  private generatingDebouncePending;
203
204
  private lastApprovalEventFingerprint;
205
+ private lastInteractivePromptEventKey;
204
206
  private autoApproveBusy;
205
207
  private autoApproveBusyTimer;
206
208
  private lastAutoApprovalSignature;
@@ -423,6 +425,7 @@ export declare class CliProviderInstance implements ProviderInstance {
423
425
  * once at completion). Reset on the next turn's start.
424
426
  */
425
427
  private lastCompletionSummary;
428
+ private lastEmittedCompletion;
426
429
  private enforceFreshSessionLaunchIfNeeded;
427
430
  /**
428
431
  * BRAIN-ROUTING (runtime-control thinking axis): for a provider that selects
@@ -473,6 +476,7 @@ export declare class CliProviderInstance implements ProviderInstance {
473
476
  private completionFinalSummary;
474
477
  private buildCompletedFinalizationDiagnostic;
475
478
  private hasAdapterPendingResponse;
479
+ private antigravityHoldPtyStillActive;
476
480
  private shouldSuppressStaleParsedBusyStatus;
477
481
  private getCompletedFinalizationBlock;
478
482
  private hasApprovalResolutionEvidence;
@@ -572,6 +576,76 @@ export declare class CliProviderInstance implements ProviderInstance {
572
576
  * starts with a clean slate (a restart is not throttled by a prior stall).
573
577
  */
574
578
  private resetMeshStallEpisode;
579
+ /**
580
+ * KIMI-MESH-COMPLETION-EMIT (axis 1). For a native-source provider
581
+ * (transcriptAuthority=provider — its authoritative history is an on-disk
582
+ * transcript file, e.g. kimi's wire.jsonl), sample the transcript's current
583
+ * progress fingerprint (record count + source-file mtime) WITHOUT parsing the
584
+ * PTY. Used by the stall watchdog to distinguish "PTY render is quiet but the
585
+ * worker is still doing long tool work (transcript growing)" from a genuine
586
+ * wedge. Returns null for a pure-PTY provider (no native source) or when the
587
+ * source cannot be resolved this tick — the caller then falls back to the
588
+ * unchanged lastOutputAt-only judgment.
589
+ *
590
+ * Generalized on the provider's native-source flag, NOT a hardcoded provider
591
+ * type, so every current and future pure-PTY long-tool native-source provider
592
+ * benefits. Cheap enough for the stall path: it runs only at the stall threshold
593
+ * (≥180s of PTY stasis), never on the routine 5s tick.
594
+ */
595
+ private sampleNativeTranscriptProgress;
596
+ /**
597
+ * KIMI-MESH-COMPLETION-EMIT (axis 2). Last-chance completion emit for a mesh
598
+ * DELEGATED worker whose PTY has already exited (e.g. killed by a false stall)
599
+ * and is about to be auto-cleaned (cli-manager.startCliExitMonitor →
600
+ * removeInstance closes the event-emit window forever). If the worker actually
601
+ * FINISHED its assigned turn — its authoritative native transcript holds a final
602
+ * assistant message for the injected task — but the completion event never fired
603
+ * (the stall-kill happened before the FSM's idle transition), emit it now so the
604
+ * coordinator learns the task completed instead of waiting ~180s for the reconcile
605
+ * transcript-poll to reclaim it.
606
+ *
607
+ * Scope & guards (must all hold to emit):
608
+ * • mesh worker session only — a normal standalone session's ordinary exit is
609
+ * never synthesized (isMeshWorkerSession()).
610
+ * • DOUBLE-EMIT guard — refuse if this turn's completion already fired
611
+ * (lastEmittedCompletion matches the current taskId). A worker that completed
612
+ * cleanly and is merely being cleaned up never double-emits.
613
+ * • evidence gate — reuse the same final-assistant/turn-scoped summary machinery
614
+ * as the normal completion path (completionFinalSummary over the native
615
+ * transcript). No in-turn assistant summary ⇒ no proof of completion ⇒ leave
616
+ * the reclaim path to handle a genuinely-unfinished worker.
617
+ *
618
+ * Returns true when a synthetic completion was emitted, false otherwise. Safe to
619
+ * call unconditionally from the cleanup path.
620
+ */
621
+ flushMeshCompletionBeforeCleanup(): boolean;
622
+ /**
623
+ * KIMI-PURE-PTY-COMPLETION-EMIT (Fix 3): stall-path completion reconcile for the
624
+ * PURE-PTY transcript class (kimi and kin — no native transcript, no provider
625
+ * authority; see isPurePtyTranscriptProvider). Such a worker whose
626
+ * generating_completed never emitted (the onTurnStarted idle→idle collapse Fix 1
627
+ * fixes at the source) sits at a STATIC idle prompt: its PTY output stops the
628
+ * instant the answer is rendered, so the status-agnostic no-progress watchdog
629
+ * (checkMeshWorkerStall) reads the finished-but-quiet session as a stall and would
630
+ * false-fire monitor:no_progress. The native-transcript reconcile
631
+ * (sampleNativeTranscriptProgress) does NOT cover this class (no native source →
632
+ * null sample), so the stall path needs its own guard.
633
+ *
634
+ * Called from checkMeshWorkerStall just before the fire. Returns true when the
635
+ * session is a finished pure-PTY turn — idle, no pending response, and a PTY-parsed
636
+ * in-turn final assistant summary — in which case it emits the missing
637
+ * generating_completed (idempotent: a real/late emit writes the terminal ledger and
638
+ * the coordinator's reconcile makes any duplicate a no-op) and the caller SUPPRESSES
639
+ * the stall. Returns false for every other class/state (native-source provider, a
640
+ * genuinely mid-turn or wedged worker with no final assistant), so a real stall still
641
+ * fires unchanged.
642
+ *
643
+ * Evidence bar is identical to flushMeshCompletionBeforeCleanup: injected task's turn
644
+ * genuinely started + an in-turn final assistant summary. Conservative by
645
+ * construction — no summary ⇒ no proof of completion ⇒ return false and let the real
646
+ * stall fire.
647
+ */
648
+ private tryReconcilePurePtyCompletionForStall;
575
649
  /**
576
650
  * AUTOAPPROVE-FLAP-RECUR (Fix A+B): how long a busy blip / modal scroll-out may
577
651
  * persist before the in-progress settle gate is torn down. For a delegated
@@ -736,7 +810,11 @@ export declare class CliProviderInstance implements ProviderInstance {
736
810
  getAdapter(): ProviderCliAdapter;
737
811
  get cliType(): string;
738
812
  get cliName(): string;
813
+ private resolveAutoApproveMode;
814
+ /** Legacy boolean view retained for internal/test compatibility. */
739
815
  private shouldAutoApprove;
816
+ private shouldUsePtyAutoApprove;
817
+ private resetPtyAutoApproveState;
740
818
  /** @see ProviderInstance.noteManualInteraction */
741
819
  noteManualInteraction(now?: number, opts?: {
742
820
  passive?: boolean;