@markjaquith/agency 2.19.0 → 2.21.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.
@@ -23,6 +23,11 @@ import {
23
23
  resolveWorkbase,
24
24
  type PickWorkbase,
25
25
  } from "../workbase/workbase-choice"
26
+ import {
27
+ printableEnvironment,
28
+ resolveRunnerCommand,
29
+ runnerEnvironment,
30
+ } from "../workbase/runner-command"
26
31
 
27
32
  interface WorkOptions extends BaseCommandOptions {
28
33
  readonly directory?: string
@@ -31,10 +36,17 @@ interface WorkOptions extends BaseCommandOptions {
31
36
  readonly epicId?: string
32
37
  readonly opencode?: boolean
33
38
  readonly claude?: boolean
39
+ readonly runner?: string
40
+ readonly printCommand?: boolean
34
41
  readonly force?: boolean
35
42
  }
36
43
 
37
- type LaunchAgent = (cli: string, args: readonly string[], cwd: string) => void
44
+ type LaunchAgent = (
45
+ cli: string,
46
+ args: readonly string[],
47
+ cwd: string,
48
+ environment: Readonly<Record<string, string>>,
49
+ ) => void
38
50
 
39
51
  const formatCommand = (args: readonly string[]) =>
40
52
  args
@@ -68,13 +80,15 @@ export const work = (
68
80
  pickBase: PickWorkbase = pickWorkbase,
69
81
  ) =>
70
82
  Effect.gen(function* () {
71
- if (options.opencode && options.claude) {
83
+ if (
84
+ (options.opencode && options.claude) ||
85
+ (options.runner && (options.opencode || options.claude))
86
+ ) {
72
87
  return yield* Effect.fail(
73
- new Error("Cannot use both --opencode and --claude"),
88
+ new Error("Cannot combine --runner, --opencode, and --claude"),
74
89
  )
75
90
  }
76
- const previousSessionId = process.env.AGENCY_SESSION_ID
77
- const previousClaimRevision = process.env.AGENCY_CLAIM_REVISION
91
+ const previousEnvironment = { ...process.env }
78
92
  if (
79
93
  options.epicId &&
80
94
  (options.directory || options.taskId || options.phaseId)
@@ -104,6 +118,7 @@ export const work = (
104
118
  const inputAllowed = options.inputAllowed ?? true
105
119
  const root = yield* resolveWorkbase(startPath, pickBase, inputAllowed)
106
120
  if (!root) return
121
+ const { config } = yield* workbase.loadConfig(root)
107
122
 
108
123
  let target: WorkTarget | null = null
109
124
  if (options.epicId) {
@@ -199,7 +214,6 @@ export const work = (
199
214
  new Error("No ready work targets found in this workbase"),
200
215
  )
201
216
  }
202
- const { config } = yield* workbase.loadConfig(root)
203
217
  target = yield* pick(choices, config.chooserCommand)
204
218
  if (!target) return
205
219
  }
@@ -233,13 +247,49 @@ export const work = (
233
247
  launchPath = workspace.writablePath
234
248
  }
235
249
 
236
- const requested = options.claude ? "claude" : "opencode"
237
- let cli = requested
250
+ const explicitlyRequested = Boolean(
251
+ options.runner ||
252
+ options.opencode ||
253
+ options.claude ||
254
+ process.env.AGENCY_RUNNER,
255
+ )
256
+ let runner =
257
+ options.runner ??
258
+ process.env.AGENCY_RUNNER ??
259
+ (options.claude ? "claude" : "opencode")
260
+ const claimant = process.env.AGENCY_CLAIMANT ?? process.env.USER ?? "agency"
261
+ const sessionId =
262
+ process.env.AGENCY_SESSION_ID ?? `${process.pid}-${Date.now()}`
263
+ const resume = process.env.AGENCY_SESSION_ID !== undefined
264
+ let claimRevision = ""
265
+ let variables = {
266
+ prompt,
267
+ workbase: root,
268
+ target: targetNodeId(target),
269
+ task: target.kind === "epic" ? "" : target.taskId,
270
+ phase: target.kind === "phase" ? target.phaseId : "",
271
+ claimant,
272
+ sessionId,
273
+ claimRevision,
274
+ }
275
+ let resolved = resolveRunnerCommand(
276
+ runner,
277
+ config.runners,
278
+ variables,
279
+ resume,
280
+ )
281
+ let cli = resolved.argv[0]!
238
282
  let available = yield* fs.runCommand(["which", cli], {
239
283
  captureOutput: true,
240
284
  })
241
- if (available.exitCode !== 0 && !options.opencode && !options.claude) {
242
- cli = "claude"
285
+ if (
286
+ available.exitCode !== 0 &&
287
+ !explicitlyRequested &&
288
+ runner === "opencode"
289
+ ) {
290
+ runner = "claude"
291
+ resolved = resolveRunnerCommand(runner, config.runners, variables, resume)
292
+ cli = resolved.argv[0]!
243
293
  available = yield* fs.runCommand(["which", cli], { captureOutput: true })
244
294
  }
245
295
  if (available.exitCode !== 0) {
@@ -251,36 +301,55 @@ export const work = (
251
301
  ) {
252
302
  const phaseId = target.kind === "phase" ? target.phaseId : undefined
253
303
  const current = yield* claims.inspect(target.taskId, phaseId, root)
254
- const sessionId =
255
- process.env.AGENCY_SESSION_ID ?? `${process.pid}-${Date.now()}`
256
304
  const acquired = yield* claims.claim(
257
305
  {
258
306
  taskId: target.taskId,
259
307
  ...(phaseId ? { phaseId } : {}),
260
- claimant: process.env.AGENCY_CLAIMANT ?? process.env.USER ?? "agency",
261
- runner: process.env.AGENCY_RUNNER ?? cli,
308
+ claimant,
309
+ runner,
262
310
  sessionId,
263
311
  revision: current.revision,
264
312
  },
265
313
  root,
266
314
  )
267
- process.env.AGENCY_SESSION_ID = sessionId
268
- process.env.AGENCY_CLAIM_REVISION = acquired.revision
315
+ claimRevision = acquired.revision
269
316
  }
270
317
 
271
- const args =
272
- cli === "opencode" ? ["--continue", "--prompt", prompt] : [prompt]
318
+ variables = { ...variables, claimRevision }
319
+ resolved = resolveRunnerCommand(runner, config.runners, variables, resume)
320
+ cli = resolved.argv[0]!
321
+ const environment = {
322
+ ...resolved.environment,
323
+ ...runnerEnvironment(runner, variables),
324
+ }
325
+ if (options.printCommand) {
326
+ log(
327
+ JSON.stringify(
328
+ {
329
+ cwd: launchPath,
330
+ argv: resolved.argv,
331
+ environment: printableEnvironment(environment),
332
+ },
333
+ null,
334
+ 2,
335
+ ),
336
+ )
337
+ return
338
+ }
339
+ for (const [key, value] of Object.entries(environment)) {
340
+ process.env[key] = value
341
+ }
273
342
  verboseLog(
274
- `Launching command: ${formatCommand([cli, ...args])} (cwd: ${launchPath})`,
343
+ `Launching command: ${formatCommand(resolved.argv)} (cwd: ${launchPath})`,
275
344
  )
276
345
  try {
277
- launch(cli, [cli, ...args], launchPath)
346
+ launch(cli, resolved.argv, launchPath, environment)
278
347
  } finally {
279
- if (previousSessionId === undefined) delete process.env.AGENCY_SESSION_ID
280
- else process.env.AGENCY_SESSION_ID = previousSessionId
281
- if (previousClaimRevision === undefined)
282
- delete process.env.AGENCY_CLAIM_REVISION
283
- else process.env.AGENCY_CLAIM_REVISION = previousClaimRevision
348
+ for (const key of Object.keys(environment)) {
349
+ const previous = previousEnvironment[key]
350
+ if (previous === undefined) delete process.env[key]
351
+ else process.env[key] = previous
352
+ }
284
353
  }
285
354
  })
286
355
 
@@ -344,7 +413,7 @@ export const workPrepare = (options: WorkOptions = {}) =>
344
413
  })
345
414
 
346
415
  export const help = `
347
- Usage: agency work [<directory-or-task-id> | --epic <epic-id>]
416
+ Usage: agency work [<directory-or-task-id> | --epic <epic-id>] [--runner <name>]
348
417
  agency work prepare [target] [--dry-run] [--json]
349
418
 
350
419
  Launch an agent for an epic, task, or phase. With no directory, select one
@@ -362,8 +431,10 @@ Options:
362
431
  --phase <id> Work on a phase selected with --task
363
432
  --workbase <target> Select a workbase by ID, name, or path
364
433
  --cwd <path> Resolve context from a specific directory
365
- --opencode Require OpenCode
366
- --claude Require Claude Code
434
+ --runner <name> Select a configured runner or built-in preset
435
+ --print-command Print cwd, argv, and non-secret environment without launch
436
+ --opencode Require the OpenCode preset
437
+ --claude Require the Claude Code preset
367
438
  --force Override readiness and terminal-state guards
368
439
  --no-input Never open an interactive selector
369
440
 
@@ -0,0 +1,336 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test"
2
+ import { mkdir } from "node:fs/promises"
3
+ import { join } from "node:path"
4
+ import { Effect } from "effect"
5
+ import { cleanupTempDir, createTempDir, runTestEffect } from "../test-utils"
6
+ import { EpicService } from "./EpicService"
7
+ import { GraphMutationService } from "./GraphMutationService"
8
+ import { PhaseService } from "./PhaseService"
9
+ import { TaskService } from "./TaskService"
10
+ import {
11
+ formatMarkdownDocument,
12
+ parseFrontmatter,
13
+ } from "../workbase/frontmatter"
14
+
15
+ describe("GraphMutationService", () => {
16
+ let root: string
17
+
18
+ beforeEach(async () => {
19
+ root = await createTempDir()
20
+ await Bun.write(join(root, "agency.json"), '{"version":2}\n')
21
+ await mkdir(join(root, "repos/agency"), { recursive: true })
22
+ await mkdir(join(root, "repos/docs"), { recursive: true })
23
+ await runTestEffect(
24
+ Effect.gen(function* () {
25
+ const epics = yield* EpicService
26
+ const tasks = yield* TaskService
27
+ const phases = yield* PhaseService
28
+ yield* epics.create(
29
+ "first-epic",
30
+ "https://example.com/first",
31
+ [{ repo: "agency", ref: "main" }],
32
+ root,
33
+ )
34
+ yield* epics.create(
35
+ "second-epic",
36
+ "https://example.com/second",
37
+ [{ repo: "agency", ref: "main" }],
38
+ root,
39
+ )
40
+ for (const id of ["alpha", "beta", "gamma"]) {
41
+ yield* tasks.create(
42
+ {
43
+ id,
44
+ ticketUrl: null,
45
+ epic: "first-epic",
46
+ repo: "agency",
47
+ branch: `task/${id}`,
48
+ base: "main",
49
+ },
50
+ root,
51
+ )
52
+ }
53
+ yield* tasks.create(
54
+ {
55
+ id: "multi",
56
+ ticketUrl: "https://example.com/multi",
57
+ multiPhase: true,
58
+ },
59
+ root,
60
+ )
61
+ yield* phases.create(
62
+ {
63
+ taskId: "multi",
64
+ id: "build",
65
+ repo: "agency",
66
+ branch: "task/multi-build",
67
+ base: "main",
68
+ },
69
+ root,
70
+ )
71
+ yield* phases.create(
72
+ {
73
+ taskId: "multi",
74
+ id: "ship",
75
+ repo: "agency",
76
+ branch: "task/multi-ship",
77
+ base: "main",
78
+ },
79
+ root,
80
+ )
81
+ }),
82
+ )
83
+ })
84
+
85
+ afterEach(async () => cleanupTempDir(root))
86
+
87
+ test("updates descriptions, tickets, repositories, and execution metadata", async () => {
88
+ const output = await runTestEffect(
89
+ Effect.gen(function* () {
90
+ const mutations = yield* GraphMutationService
91
+ yield* mutations.updateEpic(
92
+ "first-epic",
93
+ {
94
+ description: "Updated epic",
95
+ ticketUrl: "https://example.com/revised",
96
+ repos: [{ repo: "docs", ref: "trunk" }],
97
+ },
98
+ root,
99
+ )
100
+ yield* mutations.updateTask(
101
+ "alpha",
102
+ {
103
+ description: "Updated task",
104
+ ticketUrl: "https://example.com/alpha",
105
+ repos: [{ repo: "docs", ref: "main" }],
106
+ branch: "feature/alpha",
107
+ base: "develop",
108
+ pr: "https://github.com/example/agency/pull/12",
109
+ },
110
+ root,
111
+ )
112
+ return yield* mutations.updatePhase(
113
+ "multi",
114
+ "build",
115
+ {
116
+ description: "Updated phase",
117
+ repo: "docs",
118
+ branch: "feature/build",
119
+ base: "develop",
120
+ },
121
+ root,
122
+ )
123
+ }),
124
+ )
125
+
126
+ expect(output).toMatchObject({
127
+ operation: "phase.update",
128
+ changed: true,
129
+ validation: { valid: true },
130
+ })
131
+ await runTestEffect(
132
+ Effect.gen(function* () {
133
+ const epics = yield* EpicService
134
+ const tasks = yield* TaskService
135
+ const phases = yield* PhaseService
136
+ expect((yield* epics.show("first-epic", root)).data).toMatchObject({
137
+ description: "Updated epic",
138
+ ticketUrl: "https://example.com/revised",
139
+ repos: [{ repo: "docs", ref: "trunk" }],
140
+ })
141
+ expect((yield* tasks.show("alpha", root)).data).toMatchObject({
142
+ description: "Updated task",
143
+ ticketUrl: "https://example.com/alpha",
144
+ repos: [{ repo: "docs", ref: "main" }],
145
+ branch: "feature/alpha",
146
+ base: "develop",
147
+ pr: "https://github.com/example/agency/pull/12",
148
+ })
149
+ expect((yield* phases.show("multi", "build", root)).data).toMatchObject(
150
+ {
151
+ description: "Updated phase",
152
+ repo: "docs",
153
+ branch: "feature/build",
154
+ base: "develop",
155
+ },
156
+ )
157
+ }),
158
+ )
159
+ })
160
+
161
+ test("preserves dependency order and rejects cycles", async () => {
162
+ await runTestEffect(
163
+ Effect.gen(function* () {
164
+ const mutations = yield* GraphMutationService
165
+ yield* mutations.mutateTaskDependency("add", "beta", "alpha", root)
166
+ yield* mutations.mutateTaskDependency("add", "beta", "gamma", root)
167
+ yield* mutations.mutateTaskDependency("remove", "beta", "alpha", root)
168
+ yield* mutations.mutatePhaseDependency(
169
+ "add",
170
+ "multi",
171
+ "ship",
172
+ "build",
173
+ root,
174
+ )
175
+ }),
176
+ )
177
+ await expect(
178
+ runTestEffect(
179
+ Effect.gen(function* () {
180
+ return yield* (yield* GraphMutationService).mutateTaskDependency(
181
+ "add",
182
+ "gamma",
183
+ "beta",
184
+ root,
185
+ )
186
+ }),
187
+ ),
188
+ ).rejects.toThrow("dependency cycle")
189
+
190
+ await expect(
191
+ runTestEffect(
192
+ Effect.gen(function* () {
193
+ return yield* (yield* GraphMutationService).mutateTaskDependency(
194
+ "add",
195
+ "beta",
196
+ "gamma",
197
+ root,
198
+ )
199
+ }),
200
+ ),
201
+ ).rejects.toThrow("already depends")
202
+
203
+ await runTestEffect(
204
+ Effect.gen(function* () {
205
+ const epics = yield* EpicService
206
+ const tasks = yield* TaskService
207
+ const declarations = (yield* epics.show("first-epic", root)).data.tasks
208
+ expect(
209
+ declarations.find((item) => item.id === "beta")?.dependsOn,
210
+ ).toEqual(["gamma"])
211
+ expect((yield* tasks.show("multi", root)).data).toMatchObject({
212
+ phases: [{ id: "build" }, { id: "ship", dependsOn: ["build"] }],
213
+ })
214
+ }),
215
+ )
216
+ })
217
+
218
+ test("renames entities and rewrites every structured reference", async () => {
219
+ await runTestEffect(
220
+ Effect.gen(function* () {
221
+ const mutations = yield* GraphMutationService
222
+ yield* mutations.mutateTaskDependency("add", "beta", "alpha", root)
223
+ yield* mutations.mutatePhaseDependency(
224
+ "add",
225
+ "multi",
226
+ "ship",
227
+ "build",
228
+ root,
229
+ )
230
+ yield* mutations.renameTask("alpha", "renamed-alpha", root)
231
+ yield* mutations.renamePhase("multi", "build", "compile", root)
232
+ yield* mutations.renameEpic("first-epic", "renamed-epic", root)
233
+ }),
234
+ )
235
+
236
+ await runTestEffect(
237
+ Effect.gen(function* () {
238
+ const epics = yield* EpicService
239
+ const tasks = yield* TaskService
240
+ const phases = yield* PhaseService
241
+ const epic = yield* epics.show("renamed-epic", root)
242
+ expect(
243
+ epic.data.tasks.find((item) => item.id === "beta")?.dependsOn,
244
+ ).toEqual(["renamed-alpha"])
245
+ expect((yield* tasks.show("renamed-alpha", root)).data.epic).toBe(
246
+ "renamed-epic",
247
+ )
248
+ expect((yield* tasks.show("multi", root)).data).toMatchObject({
249
+ phases: [{ id: "compile" }, { id: "ship", dependsOn: ["compile"] }],
250
+ })
251
+ expect((yield* phases.show("multi", "compile", root)).id).toBe(
252
+ "compile",
253
+ )
254
+ }),
255
+ )
256
+ })
257
+
258
+ test("moves task membership in both directions", async () => {
259
+ await runTestEffect(
260
+ Effect.gen(function* () {
261
+ yield* (yield* GraphMutationService).moveTask(
262
+ "alpha",
263
+ "second-epic",
264
+ root,
265
+ )
266
+ const epics = yield* EpicService
267
+ const tasks = yield* TaskService
268
+ expect(
269
+ (yield* epics.show("first-epic", root)).data.tasks.map(
270
+ (item) => item.id,
271
+ ),
272
+ ).not.toContain("alpha")
273
+ expect(
274
+ (yield* epics.show("second-epic", root)).data.tasks.map(
275
+ (item) => item.id,
276
+ ),
277
+ ).toEqual(["alpha"])
278
+ expect((yield* tasks.show("alpha", root)).data.epic).toBe("second-epic")
279
+ }),
280
+ )
281
+ })
282
+
283
+ test("refuses a rename that would invalidate a materialized worktree", async () => {
284
+ await mkdir(join(root, "tasks/alpha/code/agency"), { recursive: true })
285
+ await expect(
286
+ runTestEffect(
287
+ Effect.gen(function* () {
288
+ return yield* (yield* GraphMutationService).renameTask(
289
+ "alpha",
290
+ "renamed-alpha",
291
+ root,
292
+ )
293
+ }),
294
+ ),
295
+ ).rejects.toThrow("materialized worktree")
296
+ expect(await Bun.file(join(root, "tasks/alpha/TASK.md")).exists()).toBe(
297
+ true,
298
+ )
299
+ expect(
300
+ await Bun.file(join(root, "tasks/renamed-alpha/TASK.md")).exists(),
301
+ ).toBe(false)
302
+ })
303
+
304
+ test("refuses rename when the parent backlink is inconsistent", async () => {
305
+ await runTestEffect(
306
+ Effect.gen(function* () {
307
+ const epic = yield* (yield* EpicService).show("first-epic", root)
308
+ const parsed = yield* parseFrontmatter(epic.content, epic.path)
309
+ yield* Effect.promise(() =>
310
+ Bun.write(
311
+ epic.path,
312
+ formatMarkdownDocument(
313
+ {
314
+ ...epic.data,
315
+ tasks: epic.data.tasks.filter((item) => item.id !== "alpha"),
316
+ },
317
+ parsed.body,
318
+ ),
319
+ ),
320
+ )
321
+ }),
322
+ )
323
+
324
+ await expect(
325
+ runTestEffect(
326
+ Effect.gen(function* () {
327
+ return yield* (yield* GraphMutationService).renameTask(
328
+ "alpha",
329
+ "renamed-alpha",
330
+ root,
331
+ )
332
+ }),
333
+ ),
334
+ ).rejects.toThrow("parent epic 'first-epic' does not list it")
335
+ })
336
+ })