@adhdev/daemon-core 1.0.18-rc.1 → 1.0.18-rc.11

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 (56) hide show
  1. package/dist/cli-adapters/cli-state-engine.d.ts +77 -0
  2. package/dist/cli-adapters/pty-transport.d.ts +2 -1
  3. package/dist/commands/process-lifecycle.d.ts +43 -0
  4. package/dist/commands/upgrade-helper.d.ts +7 -0
  5. package/dist/commands/windows-atomic-upgrade.d.ts +63 -0
  6. package/dist/index.js +6513 -4536
  7. package/dist/index.js.map +1 -1
  8. package/dist/index.mjs +6539 -4556
  9. package/dist/index.mjs.map +1 -1
  10. package/dist/mesh/coordinator-prompt.d.ts +76 -0
  11. package/dist/mesh/mesh-active-work.d.ts +1 -1
  12. package/dist/mesh/mesh-disk-retention.d.ts +105 -0
  13. package/dist/mesh/mesh-ledger.d.ts +28 -1
  14. package/dist/mesh/mesh-node-identity.d.ts +23 -0
  15. package/dist/mesh/mesh-refine-gates.d.ts +89 -0
  16. package/dist/mesh/mesh-runtime-store.d.ts +11 -0
  17. package/dist/mesh/mesh-work-queue.d.ts +24 -1
  18. package/dist/providers/cli-provider-instance-types.d.ts +4 -0
  19. package/dist/providers/cli-provider-instance.d.ts +2 -0
  20. package/dist/providers/sdk/v1/builders/cli/detect-status.d.ts +14 -0
  21. package/dist/providers/types/interactive-prompt.d.ts +18 -0
  22. package/package.json +3 -3
  23. package/src/boot/daemon-lifecycle.ts +10 -0
  24. package/src/cli-adapters/cli-state-engine.ts +204 -3
  25. package/src/cli-adapters/provider-cli-adapter.ts +39 -5
  26. package/src/cli-adapters/pty-transport.d.ts +2 -1
  27. package/src/cli-adapters/pty-transport.ts +1 -1
  28. package/src/cli-adapters/session-host-transport.ts +8 -3
  29. package/src/commands/high-family/mesh-coordinator-launch.ts +17 -2
  30. package/src/commands/high-family/mesh-events.ts +13 -2
  31. package/src/commands/med-family/mesh-queue.ts +74 -1
  32. package/src/commands/process-lifecycle.ts +248 -0
  33. package/src/commands/router-refine.ts +71 -4
  34. package/src/commands/router.ts +8 -0
  35. package/src/commands/upgrade-helper.ts +146 -79
  36. package/src/commands/windows-atomic-upgrade.ts +631 -0
  37. package/src/config/mesh-json-config.ts +8 -0
  38. package/src/mesh/coordinator-prompt.ts +258 -11
  39. package/src/mesh/mesh-active-work.ts +11 -1
  40. package/src/mesh/mesh-disk-retention.ts +370 -0
  41. package/src/mesh/mesh-event-classify.ts +19 -0
  42. package/src/mesh/mesh-event-forwarding.ts +46 -4
  43. package/src/mesh/mesh-events-utils.ts +42 -0
  44. package/src/mesh/mesh-ledger.ts +77 -0
  45. package/src/mesh/mesh-node-identity.ts +49 -0
  46. package/src/mesh/mesh-queue-assignment.ts +144 -2
  47. package/src/mesh/mesh-reconcile-loop.ts +55 -1
  48. package/src/mesh/mesh-refine-gates.ts +300 -0
  49. package/src/mesh/mesh-runtime-store.ts +21 -0
  50. package/src/mesh/mesh-work-queue.ts +85 -2
  51. package/src/providers/cli-provider-instance-types.ts +53 -0
  52. package/src/providers/cli-provider-instance.ts +193 -2
  53. package/src/providers/sdk/v1/builders/cli/detect-status.ts +23 -0
  54. package/src/providers/sdk/v1/builders/cli/parse-approval.ts +20 -0
  55. package/src/providers/types/interactive-prompt.ts +77 -0
  56. package/src/session-host/managed-host.ts +34 -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).
@@ -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.
@@ -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;
@@ -201,6 +201,7 @@ export declare class CliProviderInstance implements ProviderInstance {
201
201
  private generatingDebounceTimer;
202
202
  private generatingDebouncePending;
203
203
  private lastApprovalEventFingerprint;
204
+ private lastInteractivePromptEventKey;
204
205
  private autoApproveBusy;
205
206
  private autoApproveBusyTimer;
206
207
  private lastAutoApprovalSignature;
@@ -473,6 +474,7 @@ export declare class CliProviderInstance implements ProviderInstance {
473
474
  private completionFinalSummary;
474
475
  private buildCompletedFinalizationDiagnostic;
475
476
  private hasAdapterPendingResponse;
477
+ private antigravityHoldPtyStillActive;
476
478
  private shouldSuppressStaleParsedBusyStatus;
477
479
  private getCompletedFinalizationBlock;
478
480
  private hasApprovalResolutionEvidence;
@@ -75,6 +75,20 @@ export interface DetectStatusTuiSpec {
75
75
  declare function scopeText(input: CliStatusInput, scope: SpinnerSpec['scope'] | SettledPromptSpec['scope'], windowLines: number | undefined): string;
76
76
  declare function spinnerMatches(spec: SpinnerSpec, input: CliStatusInput): boolean;
77
77
  declare function settledPromptMatches(spec: SettledPromptSpec, input: CliStatusInput): boolean;
78
+ /**
79
+ * APPROVAL-PICKER-MISROUTE (mission f1d25e11) defense-in-depth: an
80
+ * AskUserQuestion multi-choice picker is NOT an approval modal. Its option rows
81
+ * ("❯ 1. label") can otherwise satisfy the approval button cue and get
82
+ * mis-classified as `waiting_approval`, so the worker's question is surfaced to
83
+ * the coordinator as a task_approval_needed (→ mesh_approve, which cannot answer
84
+ * it). The picker carries a distinctive signature the approval FSM never does:
85
+ * the claude TUI select footer ("Enter to select … Esc to cancel") together with
86
+ * the freeform escape hatch ("Type something" / "Chat about this"). When both are
87
+ * present the screen is a question picker — surfaced separately as
88
+ * waiting_choice — so the approval matchers must yield. Mirrors the legacy
89
+ * looksLikeSelectionPicker guard (cli-provider-instance.ts) ported to SDK-v1.
90
+ */
91
+ export declare function isAskUserQuestionPickerSignature(text: string): boolean;
78
92
  declare function modalMatches(spec: ModalSpec, input: CliStatusInput): boolean;
79
93
  export declare function buildDetectStatusFromTui(spec: DetectStatusTuiSpec): CliDetectStatusFn;
80
94
  export declare const __internal: {
@@ -28,6 +28,24 @@ export interface InteractiveAnswer {
28
28
  }
29
29
  export declare function normalizeInteractivePrompt(raw: unknown): InteractivePrompt | null;
30
30
  export declare function normalizeInteractivePromptResponse(raw: unknown): InteractivePromptResponse;
31
+ /**
32
+ * Resolve a coordinator-friendly answer form into the strict, questionId-keyed
33
+ * InteractivePromptResponse the TUI/answer machinery consumes (mission f1d25e11).
34
+ *
35
+ * mesh_answer_question lets the coordinator answer against the option LABELS or
36
+ * 1-based INDEXES it saw in the agent:waiting_choice event, without having to
37
+ * reconstruct the exact questionId → selectedLabels map. This resolves that
38
+ * ergonomic form against the AUTHORITATIVE active prompt (the daemon holds it),
39
+ * so index/label resolution and question ordering are correct by construction.
40
+ *
41
+ * Accepted `raw` shapes:
42
+ * - The strict form ({ promptId, answers: { [questionId]: { selectedLabels } } })
43
+ * — passed straight to normalizeInteractivePromptResponse (back-compat).
44
+ * - The friendly form ({ promptId, answers: [ { questionId?, select?, freeform? } ] })
45
+ * — entries map to questions by questionId, else by array position. `select`
46
+ * is a label (string) / 1-based index (number) / array of either.
47
+ */
48
+ export declare function resolveInteractivePromptResponse(prompt: InteractivePrompt, raw: unknown): InteractivePromptResponse;
31
49
  export declare function buildClaudeInteractiveToolResult(response: InteractivePromptResponse): string;
32
50
  export interface ClaudeInteractiveTuiPage {
33
51
  screenText: string;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@adhdev/daemon-core",
3
- "version": "1.0.18-rc.1",
3
+ "version": "1.0.18-rc.11",
4
4
  "description": "ADHDev daemon core — CDP, IDE detection, providers, command execution",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",
@@ -47,8 +47,8 @@
47
47
  "author": "vilmire",
48
48
  "license": "AGPL-3.0-or-later",
49
49
  "dependencies": {
50
- "@adhdev/mesh-shared": "1.0.18-rc.1",
51
- "@adhdev/session-host-core": "1.0.18-rc.1",
50
+ "@adhdev/mesh-shared": "1.0.18-rc.11",
51
+ "@adhdev/session-host-core": "1.0.18-rc.11",
52
52
  "@agentclientprotocol/sdk": "^0.16.1",
53
53
  "ajv": "^8.20.0",
54
54
  "ajv-formats": "^3.0.1",
@@ -39,6 +39,7 @@ import type { IdeProviderInstance } from '../providers/ide-provider-instance.js'
39
39
  import { createDefaultGitCommandServices } from '../git/git-commands.js';
40
40
  import { setupMeshEventForwarding } from '../mesh/mesh-events.js';
41
41
  import { setupMeshReconcileLoop } from '../mesh/mesh-reconcile-loop.js';
42
+ import { MeshRuntimeStore } from '../mesh/mesh-runtime-store.js';
42
43
  import { loadMeshCoordinatorRegistry } from '../mesh/coordinator-registry.js';
43
44
  import { applyProcessHardening } from './process-hardening.js';
44
45
  import { installProviderProcessShim } from '../providers/sdk/v1/sandbox/require-whitelist.js';
@@ -503,4 +504,13 @@ export async function shutdownDaemonComponents(components: DaemonComponents): Pr
503
504
  try { m.disconnect(); } catch { /* noop */ }
504
505
  }
505
506
  cdpManagers.clear();
507
+
508
+ // 7. VACUUM the mesh runtime DB. Retention prunes rows with DELETE (frees pages
509
+ // inside the file but never shrinks it); the mesh-runtime.db grew to hundreds of
510
+ // MB (mission 86def38d disk-accumulation bootstrap failure) because it was never
511
+ // compacted. Do this LAST, after all writers (reconcile loop, CLIs, instances)
512
+ // are stopped, so nothing contends for the exclusive VACUUM lock. Best-effort —
513
+ // vacuum() swallows its own errors; the try/catch guards the getInstance() throw
514
+ // when the store never opened (degraded JSONL-only mode).
515
+ try { MeshRuntimeStore.getInstance().vacuum(); } catch { /* store unavailable — nothing to vacuum */ }
506
516
  }