@flyingrobots/graft 0.3.5 → 0.5.0

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 (111) hide show
  1. package/ARCHITECTURE.md +386 -0
  2. package/CHANGELOG.md +69 -0
  3. package/CODE_OF_CONDUCT.md +65 -0
  4. package/README.md +153 -17
  5. package/bin/graft.js +4 -11
  6. package/docs/ADVANCED_GUIDE.md +49 -0
  7. package/docs/CLI.md +43 -0
  8. package/docs/GUIDE.md +321 -32
  9. package/docs/MCP.md +44 -0
  10. package/package.json +17 -4
  11. package/src/adapters/node-fs.ts +4 -0
  12. package/src/adapters/node-git.ts +47 -0
  13. package/src/adapters/node-process-runner.ts +27 -0
  14. package/src/cli/index-cmd.ts +86 -0
  15. package/src/cli/init.ts +808 -57
  16. package/src/cli/main.ts +437 -0
  17. package/src/contracts/capabilities.ts +341 -0
  18. package/src/contracts/causal-ontology.ts +622 -0
  19. package/src/contracts/causal-surface-next-action.ts +18 -0
  20. package/src/contracts/output-schemas.ts +1169 -0
  21. package/src/git/diff.ts +25 -21
  22. package/src/git/target-git-hook-bootstrap.ts +56 -0
  23. package/src/hooks/posttooluse-read.ts +21 -74
  24. package/src/hooks/pretooluse-read.ts +20 -56
  25. package/src/hooks/read-governor.ts +95 -0
  26. package/src/hooks/read-messages.ts +53 -0
  27. package/src/mcp/burden.ts +123 -0
  28. package/src/mcp/cache.ts +51 -0
  29. package/src/mcp/cached-file.ts +10 -8
  30. package/src/mcp/context.ts +67 -2
  31. package/src/mcp/daemon-control-plane.ts +554 -0
  32. package/src/mcp/daemon-job-scheduler.ts +279 -0
  33. package/src/mcp/daemon-repos.ts +216 -0
  34. package/src/mcp/daemon-server.ts +396 -0
  35. package/src/mcp/daemon-worker-pool.ts +310 -0
  36. package/src/mcp/daemon-worker-process.ts +52 -0
  37. package/src/mcp/metrics.ts +108 -1
  38. package/src/mcp/monitor-tick-job.ts +99 -0
  39. package/src/mcp/persisted-local-history.ts +1246 -0
  40. package/src/mcp/persistent-monitor-runtime.ts +549 -0
  41. package/src/mcp/policy.ts +84 -0
  42. package/src/mcp/receipt.ts +82 -12
  43. package/src/mcp/repo-concurrency.ts +318 -0
  44. package/src/mcp/repo-state.ts +777 -0
  45. package/src/mcp/repo-tool-job.ts +302 -0
  46. package/src/mcp/run-capture-config.ts +33 -0
  47. package/src/mcp/runtime-causal-context.ts +72 -0
  48. package/src/mcp/runtime-observability.ts +219 -0
  49. package/src/mcp/runtime-staged-target.ts +161 -0
  50. package/src/mcp/runtime-workspace-overlay.ts +255 -0
  51. package/src/mcp/semantic-transition-guidance.ts +60 -0
  52. package/src/mcp/semantic-transition-summary.ts +130 -0
  53. package/src/mcp/server.ts +704 -45
  54. package/src/mcp/stdio-server.ts +12 -0
  55. package/src/mcp/stdio.ts +2 -5
  56. package/src/mcp/tools/activity-view.ts +325 -0
  57. package/src/mcp/tools/causal-attach.ts +67 -0
  58. package/src/mcp/tools/causal-status.ts +58 -0
  59. package/src/mcp/tools/changed-since.ts +13 -11
  60. package/src/mcp/tools/code-find.ts +164 -0
  61. package/src/mcp/tools/code-refs.ts +466 -0
  62. package/src/mcp/tools/code-show.ts +252 -0
  63. package/src/mcp/tools/daemon-monitors.ts +14 -0
  64. package/src/mcp/tools/daemon-repos.ts +22 -0
  65. package/src/mcp/tools/daemon-sessions.ts +14 -0
  66. package/src/mcp/tools/daemon-status.ts +12 -0
  67. package/src/mcp/tools/doctor.ts +45 -2
  68. package/src/mcp/tools/explain.ts +4 -0
  69. package/src/mcp/tools/file-outline.ts +7 -3
  70. package/src/mcp/tools/git-files.ts +73 -0
  71. package/src/mcp/tools/graft-diff.ts +12 -4
  72. package/src/mcp/tools/map.ts +136 -0
  73. package/src/mcp/tools/monitor-pause.ts +18 -0
  74. package/src/mcp/tools/monitor-resume.ts +18 -0
  75. package/src/mcp/tools/monitor-start.ts +20 -0
  76. package/src/mcp/tools/monitor-stop.ts +18 -0
  77. package/src/mcp/tools/precision-match.ts +51 -0
  78. package/src/mcp/tools/precision-query.ts +127 -0
  79. package/src/mcp/tools/precision.ts +312 -0
  80. package/src/mcp/tools/run-capture.ts +126 -44
  81. package/src/mcp/tools/safe-read.ts +14 -12
  82. package/src/mcp/tools/since.ts +49 -0
  83. package/src/mcp/tools/state.ts +11 -3
  84. package/src/mcp/tools/stats.ts +5 -1
  85. package/src/mcp/tools/workspace-authorizations.ts +14 -0
  86. package/src/mcp/tools/workspace-authorize.ts +20 -0
  87. package/src/mcp/tools/workspace-bind.ts +25 -0
  88. package/src/mcp/tools/workspace-rebind.ts +25 -0
  89. package/src/mcp/tools/workspace-revoke.ts +18 -0
  90. package/src/mcp/tools/workspace-status.ts +12 -0
  91. package/src/mcp/warp-pool.ts +36 -0
  92. package/src/mcp/workspace-router.ts +984 -0
  93. package/src/operations/file-outline.ts +12 -2
  94. package/src/operations/graft-diff.ts +56 -10
  95. package/src/operations/safe-read.ts +27 -4
  96. package/src/operations/state.ts +6 -9
  97. package/src/parser/lang.ts +19 -3
  98. package/src/parser/outline.ts +191 -2
  99. package/src/parser/types.ts +9 -1
  100. package/src/policy/types.ts +4 -3
  101. package/src/ports/filesystem.ts +1 -0
  102. package/src/ports/git.ts +16 -0
  103. package/src/ports/process-runner.ts +22 -0
  104. package/src/release/security-gate.ts +102 -0
  105. package/src/session/tracker.ts +31 -0
  106. package/src/version.ts +3 -0
  107. package/src/warp/indexer.ts +513 -0
  108. package/src/warp/observers.ts +105 -0
  109. package/src/warp/open.ts +31 -0
  110. package/src/warp/plumbing.d.ts +15 -0
  111. package/src/warp/writer-id.ts +30 -0
@@ -0,0 +1,279 @@
1
+ import * as crypto from "node:crypto";
2
+
3
+ export type DaemonJobKind = "repo_tool" | "persistent_monitor";
4
+ export type DaemonJobPriority = "interactive" | "background";
5
+ export type DaemonJobState = "queued" | "running";
6
+
7
+ export interface DaemonJobRequest {
8
+ readonly sessionId: string | null;
9
+ readonly sliceId: string | null;
10
+ readonly repoId: string;
11
+ readonly worktreeId: string | null;
12
+ readonly tool: string;
13
+ readonly kind: DaemonJobKind;
14
+ readonly priority: DaemonJobPriority;
15
+ readonly writerId: string;
16
+ }
17
+
18
+ export interface DaemonJobView extends DaemonJobRequest {
19
+ readonly jobId: string;
20
+ readonly state: DaemonJobState;
21
+ readonly enqueuedAt: string;
22
+ readonly startedAt: string | null;
23
+ readonly waitMs: number;
24
+ }
25
+
26
+ export interface DaemonSchedulerCounts {
27
+ readonly maxConcurrentJobs: number;
28
+ readonly activeJobs: number;
29
+ readonly queuedJobs: number;
30
+ readonly interactiveQueuedJobs: number;
31
+ readonly backgroundQueuedJobs: number;
32
+ readonly activeWriterLanes: number;
33
+ readonly queuedWriterLanes: number;
34
+ readonly completedJobs: number;
35
+ readonly failedJobs: number;
36
+ readonly longestQueuedWaitMs: number;
37
+ }
38
+
39
+ export interface DaemonJobSchedulerOptions {
40
+ readonly maxConcurrentJobs?: number | undefined;
41
+ }
42
+
43
+ interface ScheduledJob extends DaemonJobRequest {
44
+ readonly jobId: string;
45
+ readonly enqueuedAtMs: number;
46
+ readonly enqueuedAt: string;
47
+ startedAtMs: number | null;
48
+ startedAt: string | null;
49
+ readonly run: () => Promise<unknown>;
50
+ readonly resolve: (value: unknown) => void;
51
+ readonly reject: (reason?: unknown) => void;
52
+ }
53
+
54
+ const DEFAULT_MAX_CONCURRENT_JOBS = 2;
55
+
56
+ export const ZERO_SCHEDULER_COUNTS: DaemonSchedulerCounts = Object.freeze({
57
+ maxConcurrentJobs: DEFAULT_MAX_CONCURRENT_JOBS,
58
+ activeJobs: 0,
59
+ queuedJobs: 0,
60
+ interactiveQueuedJobs: 0,
61
+ backgroundQueuedJobs: 0,
62
+ activeWriterLanes: 0,
63
+ queuedWriterLanes: 0,
64
+ completedJobs: 0,
65
+ failedJobs: 0,
66
+ longestQueuedWaitMs: 0,
67
+ });
68
+
69
+ function normalizeMaxConcurrentJobs(value: number | undefined): number {
70
+ if (value === undefined) return DEFAULT_MAX_CONCURRENT_JOBS;
71
+ const normalized = Math.trunc(value);
72
+ if (!Number.isFinite(normalized) || normalized <= 0) {
73
+ throw new Error("maxConcurrentJobs must be a positive integer");
74
+ }
75
+ return normalized;
76
+ }
77
+
78
+ function toIso(ms: number): string {
79
+ return new Date(ms).toISOString();
80
+ }
81
+
82
+ function compareLaneKeys(left: string, right: string): number {
83
+ return left.localeCompare(right);
84
+ }
85
+
86
+ function buildWriterLaneKey(job: Pick<DaemonJobRequest, "repoId" | "writerId">): string {
87
+ return `${job.repoId}:${job.writerId}`;
88
+ }
89
+
90
+ function toJobView(job: ScheduledJob, nowMs: number, state: DaemonJobState): DaemonJobView {
91
+ return {
92
+ jobId: job.jobId,
93
+ sessionId: job.sessionId,
94
+ sliceId: job.sliceId,
95
+ repoId: job.repoId,
96
+ worktreeId: job.worktreeId,
97
+ tool: job.tool,
98
+ kind: job.kind,
99
+ priority: job.priority,
100
+ writerId: job.writerId,
101
+ state,
102
+ enqueuedAt: job.enqueuedAt,
103
+ startedAt: job.startedAt,
104
+ waitMs: (job.startedAtMs ?? nowMs) - job.enqueuedAtMs,
105
+ };
106
+ }
107
+
108
+ export class DaemonJobScheduler {
109
+ private readonly maxConcurrentJobs: number;
110
+ private readonly interactiveQueues = new Map<string, ScheduledJob[]>();
111
+ private readonly backgroundQueues = new Map<string, ScheduledJob[]>();
112
+ private readonly running = new Map<string, ScheduledJob>();
113
+ private completedJobs = 0;
114
+ private failedJobs = 0;
115
+ private lastInteractiveLaneKey: string | null = null;
116
+ private lastBackgroundLaneKey: string | null = null;
117
+
118
+ constructor(options: DaemonJobSchedulerOptions = {}) {
119
+ this.maxConcurrentJobs = normalizeMaxConcurrentJobs(options.maxConcurrentJobs);
120
+ }
121
+
122
+ enqueue<T>(request: DaemonJobRequest, run: () => Promise<T>): Promise<T> {
123
+ return new Promise<T>((resolve, reject) => {
124
+ const enqueuedAtMs = Date.now();
125
+ const job: ScheduledJob = {
126
+ ...request,
127
+ jobId: crypto.randomUUID(),
128
+ enqueuedAtMs,
129
+ enqueuedAt: toIso(enqueuedAtMs),
130
+ startedAtMs: null,
131
+ startedAt: null,
132
+ run: () => run(),
133
+ resolve: (value) => {
134
+ resolve(value as T);
135
+ },
136
+ reject,
137
+ };
138
+ this.enqueueJob(job);
139
+ this.dispatch();
140
+ });
141
+ }
142
+
143
+ getCounts(nowMs = Date.now()): DaemonSchedulerCounts {
144
+ const queuedJobs = this.listQueuedJobs();
145
+ const interactiveQueuedJobs = queuedJobs.filter((job) => job.priority === "interactive").length;
146
+ const backgroundQueuedJobs = queuedJobs.length - interactiveQueuedJobs;
147
+ const longestQueuedWaitMs = queuedJobs.reduce((maxWait, job) => {
148
+ return Math.max(maxWait, nowMs - job.enqueuedAtMs);
149
+ }, 0);
150
+
151
+ return {
152
+ maxConcurrentJobs: this.maxConcurrentJobs,
153
+ activeJobs: this.running.size,
154
+ queuedJobs: queuedJobs.length,
155
+ interactiveQueuedJobs,
156
+ backgroundQueuedJobs,
157
+ activeWriterLanes: new Set([...this.running.values()].map((job) => buildWriterLaneKey(job))).size,
158
+ queuedWriterLanes: new Set(queuedJobs.map((job) => buildWriterLaneKey(job))).size,
159
+ completedJobs: this.completedJobs,
160
+ failedJobs: this.failedJobs,
161
+ longestQueuedWaitMs,
162
+ };
163
+ }
164
+
165
+ listJobs(nowMs = Date.now()): readonly DaemonJobView[] {
166
+ const runningJobs = [...this.running.values()]
167
+ .map((job) => toJobView(job, nowMs, "running"))
168
+ .sort((left, right) => {
169
+ return (left.startedAt ?? left.enqueuedAt).localeCompare(right.startedAt ?? right.enqueuedAt);
170
+ });
171
+ const queuedJobs = this.listQueuedJobs()
172
+ .map((job) => toJobView(job, nowMs, "queued"))
173
+ .sort((left, right) => left.enqueuedAt.localeCompare(right.enqueuedAt));
174
+ return [...runningJobs, ...queuedJobs];
175
+ }
176
+
177
+ private enqueueJob(job: ScheduledJob): void {
178
+ const queues = this.getQueues(job.priority);
179
+ const laneKey = buildWriterLaneKey(job);
180
+ const queue = queues.get(laneKey) ?? [];
181
+ queue.push(job);
182
+ queues.set(laneKey, queue);
183
+ }
184
+
185
+ private dispatch(): void {
186
+ while (this.running.size < this.maxConcurrentJobs) {
187
+ const nextJob = this.takeNextJob();
188
+ if (nextJob === null) {
189
+ return;
190
+ }
191
+ this.startJob(nextJob);
192
+ }
193
+ }
194
+
195
+ private startJob(job: ScheduledJob): void {
196
+ const startedAtMs = Date.now();
197
+ job.startedAtMs = startedAtMs;
198
+ job.startedAt = toIso(startedAtMs);
199
+ this.running.set(job.jobId, job);
200
+
201
+ void Promise.resolve()
202
+ .then(() => job.run())
203
+ .then((value) => {
204
+ this.running.delete(job.jobId);
205
+ this.completedJobs++;
206
+ job.resolve(value);
207
+ this.dispatch();
208
+ })
209
+ .catch((error: unknown) => {
210
+ this.running.delete(job.jobId);
211
+ this.failedJobs++;
212
+ job.reject(error);
213
+ this.dispatch();
214
+ });
215
+ }
216
+
217
+ private takeNextJob(): ScheduledJob | null {
218
+ return this.takeNextJobForPriority("interactive") ?? this.takeNextJobForPriority("background");
219
+ }
220
+
221
+ private takeNextJobForPriority(priority: DaemonJobPriority): ScheduledJob | null {
222
+ const queues = this.getQueues(priority);
223
+ return this.takeNextJobFromQueues(queues, priority);
224
+ }
225
+
226
+ private takeNextJobFromQueues(
227
+ queues: Map<string, ScheduledJob[]>,
228
+ priority: DaemonJobPriority,
229
+ ): ScheduledJob | null {
230
+ const laneKeys = [...queues.entries()]
231
+ .filter(([laneKey, queue]) => {
232
+ return queue.length > 0 && !this.hasRunningLane(laneKey);
233
+ })
234
+ .map(([laneKey]) => laneKey)
235
+ .sort(compareLaneKeys);
236
+
237
+ if (laneKeys.length === 0) {
238
+ return null;
239
+ }
240
+
241
+ const lastLaneKey = priority === "interactive" ? this.lastInteractiveLaneKey : this.lastBackgroundLaneKey;
242
+ const lastIndex = lastLaneKey === null ? -1 : laneKeys.indexOf(lastLaneKey);
243
+ const startIndex = lastIndex >= 0 ? (lastIndex + 1) % laneKeys.length : 0;
244
+
245
+ for (let offset = 0; offset < laneKeys.length; offset++) {
246
+ const laneKey = laneKeys[(startIndex + offset) % laneKeys.length];
247
+ if (laneKey === undefined) continue;
248
+ const queue = queues.get(laneKey);
249
+ const job = queue?.shift();
250
+ if (job === undefined) continue;
251
+ if (queue?.length === 0) {
252
+ queues.delete(laneKey);
253
+ }
254
+ if (priority === "interactive") {
255
+ this.lastInteractiveLaneKey = laneKey;
256
+ } else {
257
+ this.lastBackgroundLaneKey = laneKey;
258
+ }
259
+ return job;
260
+ }
261
+
262
+ return null;
263
+ }
264
+
265
+ private listQueuedJobs(): ScheduledJob[] {
266
+ return [
267
+ ...this.interactiveQueues.values(),
268
+ ...this.backgroundQueues.values(),
269
+ ].flatMap((queue) => [...queue]);
270
+ }
271
+
272
+ private hasRunningLane(laneKey: string): boolean {
273
+ return [...this.running.values()].some((job) => buildWriterLaneKey(job) === laneKey);
274
+ }
275
+
276
+ private getQueues(priority: DaemonJobPriority): Map<string, ScheduledJob[]> {
277
+ return priority === "interactive" ? this.interactiveQueues : this.backgroundQueues;
278
+ }
279
+ }
@@ -0,0 +1,216 @@
1
+ import type {
2
+ AuthorizedWorkspaceRecord,
3
+ DaemonControlPlane,
4
+ DaemonSessionView,
5
+ } from "./daemon-control-plane.js";
6
+ import type {
7
+ MonitorHealth,
8
+ MonitorLifecycleState,
9
+ MonitorStatusView,
10
+ MonitorWorkerKind,
11
+ PersistentMonitorRuntime,
12
+ } from "./persistent-monitor-runtime.js";
13
+
14
+ export interface DaemonRepoFilter {
15
+ readonly repoId?: string | undefined;
16
+ readonly cwd?: string | undefined;
17
+ }
18
+
19
+ export interface DaemonRepoWorktreeView {
20
+ readonly worktreeId: string;
21
+ readonly worktreeRoot: string;
22
+ readonly activeSessions: number;
23
+ readonly lastBoundAt: string | null;
24
+ }
25
+
26
+ export interface DaemonRepoMonitorView {
27
+ readonly workerKind: MonitorWorkerKind;
28
+ readonly lifecycleState: MonitorLifecycleState;
29
+ readonly health: MonitorHealth;
30
+ readonly lastTickAt: string | null;
31
+ readonly lastSuccessAt: string | null;
32
+ readonly lastError: string | null;
33
+ }
34
+
35
+ export interface DaemonRepoView {
36
+ readonly repoId: string;
37
+ readonly gitCommonDir: string;
38
+ readonly authorizedWorkspaces: number;
39
+ readonly boundSessions: number;
40
+ readonly activeWorktrees: number;
41
+ readonly backlogCommits: number;
42
+ readonly lastBoundAt: string | null;
43
+ readonly lastActivityAt: string | null;
44
+ readonly monitor: DaemonRepoMonitorView | null;
45
+ readonly worktrees: readonly DaemonRepoWorktreeView[];
46
+ }
47
+
48
+ export interface DaemonRepoListView {
49
+ readonly repos: readonly DaemonRepoView[];
50
+ readonly filter?: DaemonRepoFilter | undefined;
51
+ }
52
+
53
+ export interface DaemonRepoOverviewOptions {
54
+ readonly controlPlane: DaemonControlPlane;
55
+ readonly monitorRuntime: PersistentMonitorRuntime;
56
+ }
57
+
58
+ function normalizeFilter(filter: DaemonRepoFilter): DaemonRepoFilter {
59
+ const next: { repoId?: string; cwd?: string } = {};
60
+ if (typeof filter.repoId === "string" && filter.repoId.trim().length > 0) {
61
+ next.repoId = filter.repoId.trim();
62
+ }
63
+ if (typeof filter.cwd === "string" && filter.cwd.trim().length > 0) {
64
+ next.cwd = filter.cwd.trim();
65
+ }
66
+ return next;
67
+ }
68
+
69
+ function maxIsoTimestamp(values: readonly (string | null | undefined)[]): string | null {
70
+ let latest: string | null = null;
71
+ for (const value of values) {
72
+ if (value === undefined || value === null || value.length === 0) continue;
73
+ if (latest === null || value.localeCompare(latest) > 0) {
74
+ latest = value;
75
+ }
76
+ }
77
+ return latest;
78
+ }
79
+
80
+ function sortAuthorizedWorkspaces(
81
+ records: readonly AuthorizedWorkspaceRecord[],
82
+ ): readonly AuthorizedWorkspaceRecord[] {
83
+ return [...records].sort((left, right) => left.worktreeRoot.localeCompare(right.worktreeRoot));
84
+ }
85
+
86
+ export class DaemonRepoOverview {
87
+ constructor(private readonly options: DaemonRepoOverviewOptions) {}
88
+
89
+ async list(filter: DaemonRepoFilter = {}): Promise<DaemonRepoListView> {
90
+ const normalizedFilter = normalizeFilter(filter);
91
+ const resolvedRepoId = await this.resolveRepoIdFilter(normalizedFilter);
92
+ if (normalizedFilter.cwd !== undefined && resolvedRepoId === null) {
93
+ return this.buildResult(normalizedFilter, []);
94
+ }
95
+
96
+ const repoIdFilter = resolvedRepoId ?? normalizedFilter.repoId;
97
+ const [authorizedWorkspaces, monitors] = await Promise.all([
98
+ this.options.controlPlane.listAuthorizedWorkspaceRecords(),
99
+ this.options.monitorRuntime.listStatuses(),
100
+ ]);
101
+ const sessions = this.options.controlPlane.listSessions();
102
+ const visibleWorkspaces = authorizedWorkspaces.filter((workspace) => {
103
+ return repoIdFilter === undefined || workspace.repoId === repoIdFilter;
104
+ });
105
+ if (visibleWorkspaces.length === 0) {
106
+ return this.buildResult(normalizedFilter, []);
107
+ }
108
+
109
+ const workspacesByRepo = new Map<string, AuthorizedWorkspaceRecord[]>();
110
+ for (const workspace of visibleWorkspaces) {
111
+ const bucket = workspacesByRepo.get(workspace.repoId) ?? [];
112
+ bucket.push(workspace);
113
+ workspacesByRepo.set(workspace.repoId, bucket);
114
+ }
115
+
116
+ const sessionsByRepo = new Map<string, DaemonSessionView[]>();
117
+ for (const session of sessions) {
118
+ if (session.repoId === null) continue;
119
+ if (repoIdFilter !== undefined && session.repoId !== repoIdFilter) continue;
120
+ const bucket = sessionsByRepo.get(session.repoId) ?? [];
121
+ bucket.push(session);
122
+ sessionsByRepo.set(session.repoId, bucket);
123
+ }
124
+
125
+ const monitorsByRepo = new Map<string, MonitorStatusView>();
126
+ for (const status of monitors) {
127
+ if (repoIdFilter !== undefined && status.repoId !== repoIdFilter) continue;
128
+ monitorsByRepo.set(status.repoId, status);
129
+ }
130
+
131
+ const repos = [...workspacesByRepo.entries()]
132
+ .map(([repoId, repoWorkspaces]) => {
133
+ const sortedWorkspaces = sortAuthorizedWorkspaces(repoWorkspaces);
134
+ const firstWorkspace = sortedWorkspaces[0];
135
+ if (firstWorkspace === undefined) {
136
+ throw new Error(`DaemonRepoOverview: missing workspace for repo ${repoId}`);
137
+ }
138
+ const repoSessions = sessionsByRepo.get(repoId) ?? [];
139
+ const monitor = monitorsByRepo.get(repoId) ?? null;
140
+ const worktrees = sortedWorkspaces.map((workspace) => {
141
+ return this.toWorktreeView(workspace, repoSessions);
142
+ });
143
+ const boundSessions = repoSessions.filter((session) => session.bindState === "bound").length;
144
+ const lastBoundAt = maxIsoTimestamp(sortedWorkspaces.map((workspace) => workspace.lastBoundAt));
145
+ const lastActivityAt = maxIsoTimestamp([
146
+ ...sortedWorkspaces.map((workspace) => workspace.authorizedAt),
147
+ ...sortedWorkspaces.map((workspace) => workspace.lastBoundAt),
148
+ ...repoSessions.map((session) => session.lastActivityAt),
149
+ ...(monitor === null
150
+ ? []
151
+ : [monitor.lastStartedAt, monitor.lastTickAt, monitor.lastSuccessAt]),
152
+ ]);
153
+ return {
154
+ repoId,
155
+ gitCommonDir: firstWorkspace.gitCommonDir,
156
+ authorizedWorkspaces: sortedWorkspaces.length,
157
+ boundSessions,
158
+ activeWorktrees: worktrees.filter((worktree) => worktree.activeSessions > 0).length,
159
+ backlogCommits: monitor?.backlogCommits ?? 0,
160
+ lastBoundAt,
161
+ lastActivityAt,
162
+ monitor: monitor === null
163
+ ? null
164
+ : {
165
+ workerKind: monitor.workerKind,
166
+ lifecycleState: monitor.lifecycleState,
167
+ health: monitor.health,
168
+ lastTickAt: monitor.lastTickAt,
169
+ lastSuccessAt: monitor.lastSuccessAt,
170
+ lastError: monitor.lastError,
171
+ },
172
+ worktrees,
173
+ } satisfies DaemonRepoView;
174
+ })
175
+ .sort((left, right) => left.gitCommonDir.localeCompare(right.gitCommonDir));
176
+
177
+ return this.buildResult(normalizedFilter, repos);
178
+ }
179
+
180
+ private async resolveRepoIdFilter(filter: DaemonRepoFilter): Promise<string | null | undefined> {
181
+ if (filter.cwd === undefined) return undefined;
182
+ const workspace = await this.options.controlPlane.getAuthorizedWorkspace({ cwd: filter.cwd });
183
+ if (workspace === null) return null;
184
+ if (filter.repoId !== undefined && workspace.repoId !== filter.repoId) {
185
+ return null;
186
+ }
187
+ return workspace.repoId;
188
+ }
189
+
190
+ private buildResult(
191
+ filter: DaemonRepoFilter,
192
+ repos: readonly DaemonRepoView[],
193
+ ): DaemonRepoListView {
194
+ if (Object.keys(filter).length === 0) {
195
+ return { repos };
196
+ }
197
+ return {
198
+ repos,
199
+ filter,
200
+ };
201
+ }
202
+
203
+ private toWorktreeView(
204
+ workspace: AuthorizedWorkspaceRecord,
205
+ repoSessions: readonly DaemonSessionView[],
206
+ ): DaemonRepoWorktreeView {
207
+ return {
208
+ worktreeId: workspace.worktreeId,
209
+ worktreeRoot: workspace.worktreeRoot,
210
+ activeSessions: repoSessions.filter((session) => {
211
+ return session.bindState === "bound" && session.worktreeId === workspace.worktreeId;
212
+ }).length,
213
+ lastBoundAt: workspace.lastBoundAt,
214
+ };
215
+ }
216
+ }