@markjaquith/agency 2.26.0 → 2.28.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.
@@ -0,0 +1,419 @@
1
+ import { Effect, Either } from "effect"
2
+ import { constants } from "node:fs"
3
+ import { access } from "node:fs/promises"
4
+ import { isAbsolute, join, resolve } from "node:path"
5
+ import { EpicService } from "./EpicService"
6
+ import { FileSystemService } from "./FileSystemService"
7
+ import { IntegrationService } from "./IntegrationService"
8
+ import { PhaseService } from "./PhaseService"
9
+ import { RepositoryService } from "./RepositoryService"
10
+ import { TaskService } from "./TaskService"
11
+ import { WorkbaseService } from "./WorkbaseService"
12
+ import { WorktreeService } from "./WorktreeService"
13
+
14
+ type DoctorCheckLevel = "error" | "warning" | "optional"
15
+
16
+ interface DoctorCheck {
17
+ readonly id: string
18
+ readonly category:
19
+ | "tool"
20
+ | "integration"
21
+ | "workbase"
22
+ | "repository"
23
+ | "ref"
24
+ | "worktree"
25
+ | "permission"
26
+ readonly level: DoctorCheckLevel
27
+ readonly status: "pass" | "fail"
28
+ readonly message: string
29
+ readonly remediation: string | null
30
+ }
31
+
32
+ interface DoctorReport {
33
+ readonly version: 1
34
+ readonly root: string
35
+ readonly healthy: boolean
36
+ readonly summary: {
37
+ readonly passed: number
38
+ readonly errors: number
39
+ readonly warnings: number
40
+ readonly optional: number
41
+ }
42
+ readonly checks: readonly DoctorCheck[]
43
+ }
44
+
45
+ const executableAvailable = (executable: string, root: string) =>
46
+ Effect.tryPromise({
47
+ try: async () => {
48
+ if (executable.includes("/")) {
49
+ const path = isAbsolute(executable)
50
+ ? executable
51
+ : resolve(root, executable)
52
+ await access(path, constants.X_OK)
53
+ return true
54
+ }
55
+ return Bun.which(executable) !== null
56
+ },
57
+ catch: () => false,
58
+ }).pipe(Effect.catchAll(() => Effect.succeed(false)))
59
+
60
+ const permissionAvailable = (path: string, mode: number) =>
61
+ Effect.tryPromise({
62
+ try: () => access(path, mode).then(() => true),
63
+ catch: () => false,
64
+ }).pipe(Effect.catchAll(() => Effect.succeed(false)))
65
+
66
+ const messageOf = (error: unknown) =>
67
+ error instanceof Error
68
+ ? error.message
69
+ : typeof error === "object" &&
70
+ error !== null &&
71
+ "message" in error &&
72
+ typeof error.message === "string"
73
+ ? error.message
74
+ : String(error)
75
+
76
+ export class DoctorService extends Effect.Service<DoctorService>()(
77
+ "DoctorService",
78
+ {
79
+ sync: () => ({
80
+ inspect: (startPath: string = process.cwd()) =>
81
+ Effect.gen(function* () {
82
+ const epics = yield* EpicService
83
+ const fs = yield* FileSystemService
84
+ const integrations = yield* IntegrationService
85
+ const phases = yield* PhaseService
86
+ const repositories = yield* RepositoryService
87
+ const tasks = yield* TaskService
88
+ const workbases = yield* WorkbaseService
89
+ const worktrees = yield* WorktreeService
90
+ const { root, config } = yield* workbases.loadConfig(startPath)
91
+ const checks: DoctorCheck[] = []
92
+ const add = (
93
+ check: Omit<DoctorCheck, "remediation"> & {
94
+ readonly remediation?: string
95
+ },
96
+ ) =>
97
+ checks.push({
98
+ ...check,
99
+ remediation:
100
+ check.status === "fail"
101
+ ? (check.remediation ?? "Remediation is unknown.")
102
+ : null,
103
+ })
104
+
105
+ const tool = function* (
106
+ id: string,
107
+ executable: string,
108
+ level: DoctorCheckLevel,
109
+ label: string,
110
+ ) {
111
+ const available = yield* executableAvailable(executable, root)
112
+ add({
113
+ id,
114
+ category: id.startsWith("tool.") ? "tool" : "integration",
115
+ level,
116
+ status: available ? "pass" : "fail",
117
+ message: available
118
+ ? `${label} executable '${executable}' is available`
119
+ : `${label} executable '${executable}' is unavailable`,
120
+ remediation:
121
+ level === "optional"
122
+ ? `Install '${executable}' to enable ${label.toLowerCase()}, or leave it unavailable if unused.`
123
+ : `Install '${executable}' and ensure it is executable on PATH.`,
124
+ })
125
+ return available
126
+ }
127
+
128
+ const gitAvailable = yield* tool("tool.git", "git", "error", "Git")
129
+ yield* tool(
130
+ "capability.runner.opencode",
131
+ "opencode",
132
+ "optional",
133
+ "OpenCode runner",
134
+ )
135
+ yield* tool(
136
+ "capability.runner.claude",
137
+ "claude",
138
+ "optional",
139
+ "Claude runner",
140
+ )
141
+
142
+ const configuredCommands: readonly (readonly [
143
+ string,
144
+ readonly string[],
145
+ string,
146
+ ])[] = [
147
+ ...(config.chooserCommand
148
+ ? [
149
+ [
150
+ "integration.chooser",
151
+ config.chooserCommand,
152
+ "Chooser",
153
+ ] as const,
154
+ ]
155
+ : []),
156
+ ...(config.worktreeCreateCommand
157
+ ? [
158
+ [
159
+ "integration.worktree-create",
160
+ config.worktreeCreateCommand,
161
+ "Worktree creator",
162
+ ] as const,
163
+ ]
164
+ : []),
165
+ ...Object.entries(config.runners ?? {}).map(
166
+ ([name, runner]) =>
167
+ [
168
+ `integration.runner.${name}`,
169
+ runner.command,
170
+ `Configured runner '${name}'`,
171
+ ] as const,
172
+ ),
173
+ ...Object.entries(config.runners ?? {}).flatMap(([name, runner]) =>
174
+ runner.resumeCommand
175
+ ? [
176
+ [
177
+ `integration.runner.${name}.resume`,
178
+ runner.resumeCommand,
179
+ `Configured runner '${name}' resume`,
180
+ ] as const,
181
+ ]
182
+ : [],
183
+ ),
184
+ ...(config.delivery
185
+ ? [
186
+ [
187
+ `integration.delivery.${config.delivery.provider}`,
188
+ config.delivery.createCommand,
189
+ `Delivery provider '${config.delivery.provider}'`,
190
+ ] as const,
191
+ [
192
+ `integration.delivery.${config.delivery.provider}.query`,
193
+ config.delivery.queryCommand,
194
+ `Delivery provider '${config.delivery.provider}' query`,
195
+ ] as const,
196
+ ]
197
+ : []),
198
+ ]
199
+ for (const [id, command, label] of configuredCommands) {
200
+ yield* tool(id, command[0]!, "error", label)
201
+ }
202
+
203
+ const validation = yield* workbases.validate(root)
204
+ add({
205
+ id: "workbase.validation",
206
+ category: "workbase",
207
+ level: "error",
208
+ status: validation.valid ? "pass" : "fail",
209
+ message: validation.valid
210
+ ? "Workbase documents and relationships are valid"
211
+ : `Workbase validation found ${validation.issues.length} issue(s): ${validation.issues.map((issue) => `${issue.path}: ${issue.message}`).join("; ")}`,
212
+ remediation:
213
+ "Run 'agency validate' and correct every reported issue.",
214
+ })
215
+
216
+ for (const [id, mode, level, label, remediation] of [
217
+ [
218
+ "permission.workbase.read",
219
+ constants.R_OK,
220
+ "error",
221
+ "readable",
222
+ `Grant the current user read access to ${root}.`,
223
+ ],
224
+ [
225
+ "permission.workbase.write",
226
+ constants.W_OK,
227
+ "warning",
228
+ "writable",
229
+ `Grant the current user write access to ${root} before running mutation commands.`,
230
+ ],
231
+ ] as const) {
232
+ const available = yield* permissionAvailable(root, mode)
233
+ add({
234
+ id,
235
+ category: "permission",
236
+ level,
237
+ status: available ? "pass" : "fail",
238
+ message: `Workbase root is ${available ? "" : "not "}${label}`,
239
+ remediation,
240
+ })
241
+ }
242
+
243
+ const integrationStatus = yield* integrations.status(root)
244
+ for (const file of integrationStatus.files) {
245
+ const failed = file.state === "missing" || file.state === "drifted"
246
+ add({
247
+ id: `integration.file.${file.name}`,
248
+ category: "integration",
249
+ level: file.state === "customized" ? "optional" : "warning",
250
+ status: failed ? "fail" : "pass",
251
+ message: `${file.name} integration file is ${file.state}: ${file.path}`,
252
+ remediation:
253
+ "Run 'agency integration sync' to restore managed content.",
254
+ })
255
+ }
256
+
257
+ const refs = new Map<string, Set<string>>()
258
+ const declareRef = (repo: string, ref: string) => {
259
+ const values = refs.get(repo) ?? new Set<string>()
260
+ values.add(ref)
261
+ refs.set(repo, values)
262
+ }
263
+ if (validation.valid) {
264
+ for (const epic of yield* epics.list(root)) {
265
+ for (const reference of epic.data.repos)
266
+ declareRef(reference.repo, reference.ref)
267
+ }
268
+ for (const task of yield* tasks.list(root)) {
269
+ if ("repo" in task.data) {
270
+ declareRef(task.data.repo, task.data.base)
271
+ for (const reference of task.data.repos ?? [])
272
+ declareRef(reference.repo, reference.ref)
273
+ } else {
274
+ for (const phase of yield* phases.list(task.id, root)) {
275
+ declareRef(phase.data.repo, phase.data.base)
276
+ for (const reference of phase.data.repos ?? [])
277
+ declareRef(reference.repo, reference.ref)
278
+ }
279
+ }
280
+ }
281
+ }
282
+
283
+ const repositoryList = gitAvailable
284
+ ? yield* repositories.list(root)
285
+ : []
286
+ if (!gitAvailable) {
287
+ add({
288
+ id: "repository.inspection",
289
+ category: "repository",
290
+ level: "warning",
291
+ status: "fail",
292
+ message:
293
+ "Repository, ref, remote, and worktree checks were skipped because Git is unavailable",
294
+ remediation: "Install 'git' and rerun 'agency doctor'.",
295
+ })
296
+ }
297
+ for (const repository of repositoryList) {
298
+ const verified = yield* fs.runCommand(
299
+ ["git", "-C", repository.path, "rev-parse", "--git-dir"],
300
+ { captureOutput: true },
301
+ )
302
+ const repositoryValid = verified.exitCode === 0
303
+ add({
304
+ id: `repository.${repository.alias}.valid`,
305
+ category: "repository",
306
+ level: "error",
307
+ status: repositoryValid ? "pass" : "fail",
308
+ message: repositoryValid
309
+ ? `Repository '${repository.alias}' is a valid Git repository`
310
+ : `Repository '${repository.alias}' is not a valid Git repository`,
311
+ remediation: `Run 'agency repo verify ${repository.alias}', then repair or relink the repository.`,
312
+ })
313
+ add({
314
+ id: `repository.${repository.alias}.remote`,
315
+ category: "repository",
316
+ level: "warning",
317
+ status: repository.remote ? "pass" : "fail",
318
+ message: repository.remote
319
+ ? `Repository '${repository.alias}' origin is ${repository.remote}`
320
+ : `Repository '${repository.alias}' has no origin remote`,
321
+ remediation: `Run 'agency repo remote ${repository.alias} <url>' to configure origin.`,
322
+ })
323
+
324
+ for (const ref of [...(refs.get(repository.alias) ?? [])].sort()) {
325
+ const local = yield* fs.runCommand(
326
+ [
327
+ "git",
328
+ "-C",
329
+ repository.path,
330
+ "rev-parse",
331
+ "--verify",
332
+ `${ref}^{commit}`,
333
+ ],
334
+ { captureOutput: true },
335
+ )
336
+ const remote =
337
+ local.exitCode === 0
338
+ ? local
339
+ : yield* fs.runCommand(
340
+ [
341
+ "git",
342
+ "-C",
343
+ repository.path,
344
+ "rev-parse",
345
+ "--verify",
346
+ `origin/${ref}^{commit}`,
347
+ ],
348
+ { captureOutput: true },
349
+ )
350
+ const found = local.exitCode === 0 || remote.exitCode === 0
351
+ add({
352
+ id: `ref.${repository.alias}.${ref}`,
353
+ category: "ref",
354
+ level: "error",
355
+ status: found ? "pass" : "fail",
356
+ message: `Declared ref '${ref}' for '${repository.alias}' is ${found ? "available" : "missing"}`,
357
+ remediation: `Run 'agency repo fetch ${repository.alias}' and verify that ref '${ref}' exists on origin.`,
358
+ })
359
+ }
360
+ }
361
+
362
+ if (validation.valid && gitAvailable) {
363
+ const inspected = yield* Effect.either(worktrees.list(root))
364
+ if (Either.isLeft(inspected)) {
365
+ add({
366
+ id: "worktree.inspection",
367
+ category: "worktree",
368
+ level: "warning",
369
+ status: "fail",
370
+ message: `Worktree inspection failed: ${messageOf(inspected.left)}`,
371
+ remediation:
372
+ "Remediation is unknown; inspect repositories with 'agency worktree list --json'.",
373
+ })
374
+ } else {
375
+ for (const inspection of inspected.right) {
376
+ const target =
377
+ inspection.owner.kind === "phase"
378
+ ? `${inspection.owner.taskId}.${inspection.owner.phaseId}`
379
+ : inspection.owner.taskId
380
+ add({
381
+ id: `worktree.${inspection.owner.kind}.${target}`,
382
+ category: "worktree",
383
+ level: "error",
384
+ status: inspection.conflicts.length === 0 ? "pass" : "fail",
385
+ message:
386
+ inspection.conflicts.length === 0
387
+ ? `Worktree registrations for '${target}' are consistent`
388
+ : inspection.conflicts
389
+ .map((conflict) => conflict.message)
390
+ .join("; "),
391
+ remediation: `Run 'agency worktree inspect ${inspection.owner.taskId}${inspection.owner.phaseId ? ` ${inspection.owner.phaseId}` : ""}', then use 'agency worktree repair' if appropriate.`,
392
+ })
393
+ }
394
+ }
395
+ }
396
+
397
+ const summary = {
398
+ passed: checks.filter((check) => check.status === "pass").length,
399
+ errors: checks.filter(
400
+ (check) => check.status === "fail" && check.level === "error",
401
+ ).length,
402
+ warnings: checks.filter(
403
+ (check) => check.status === "fail" && check.level === "warning",
404
+ ).length,
405
+ optional: checks.filter(
406
+ (check) => check.status === "fail" && check.level === "optional",
407
+ ).length,
408
+ }
409
+ return {
410
+ version: 1,
411
+ root,
412
+ healthy: summary.errors === 0,
413
+ summary,
414
+ checks,
415
+ } satisfies DoctorReport
416
+ }),
417
+ }),
418
+ },
419
+ ) {}
@@ -6,6 +6,7 @@ import {
6
6
  readdir,
7
7
  realpath,
8
8
  rename,
9
+ rmdir,
9
10
  stat,
10
11
  symlink,
11
12
  } from "node:fs/promises"
@@ -175,6 +176,31 @@ export class FileSystemService extends Effect.Service<FileSystemService>()(
175
176
  ),
176
177
  ),
177
178
 
179
+ deleteDirectoryIfEmpty: (path: string) =>
180
+ Effect.tryPromise({
181
+ try: async () => {
182
+ try {
183
+ await rmdir(path)
184
+ return true
185
+ } catch (error) {
186
+ if (
187
+ typeof error === "object" &&
188
+ error !== null &&
189
+ "code" in error &&
190
+ ["ENOENT", "ENOTEMPTY", "EEXIST"].includes(String(error.code))
191
+ ) {
192
+ return false
193
+ }
194
+ throw error
195
+ }
196
+ },
197
+ catch: (error) =>
198
+ new FileSystemError({
199
+ message: `Failed to delete empty directory: ${path}`,
200
+ cause: error,
201
+ }),
202
+ }),
203
+
178
204
  runCommand: (
179
205
  args: readonly string[],
180
206
  options?: {