@markjaquith/agency 2.8.0 → 2.10.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,379 @@
1
+ import { afterEach, beforeEach, describe, expect, test } from "bun:test"
2
+ import { mkdir, rm } from "node:fs/promises"
3
+ import { dirname, join } from "node:path"
4
+ import {
5
+ captureLogs,
6
+ cleanupTempDir,
7
+ createTempDir,
8
+ runTestEffect,
9
+ } from "../test-utils"
10
+ import { context } from "./context"
11
+
12
+ const write = async (root: string, path: string, content: string) => {
13
+ const fullPath = join(root, path)
14
+ await mkdir(dirname(fullPath), { recursive: true })
15
+ await Bun.write(fullPath, content)
16
+ }
17
+
18
+ const run = async (cwd: string, args: string[]) => {
19
+ const process = Bun.spawn(args, { cwd, stdout: "pipe", stderr: "pipe" })
20
+ const [exitCode, stderr] = await Promise.all([
21
+ process.exited,
22
+ new Response(process.stderr).text(),
23
+ ])
24
+ if (exitCode !== 0) throw new Error(`${args.join(" ")}: ${stderr}`)
25
+ }
26
+
27
+ const readContext = async (
28
+ root: string,
29
+ target: string | undefined,
30
+ compact = false,
31
+ ) => {
32
+ const logs = await captureLogs(() =>
33
+ runTestEffect(context({ cwd: root, target, compact, json: true })),
34
+ )
35
+ expect(logs).toHaveLength(1)
36
+ return JSON.parse(logs[0]!)
37
+ }
38
+
39
+ describe("context", () => {
40
+ let root: string
41
+
42
+ beforeEach(async () => {
43
+ root = await createTempDir()
44
+ await write(root, "agency.json", '{"version":2}\n')
45
+ for (const repo of ["agency", "docs"]) {
46
+ const path = join(root, "repos", repo)
47
+ await mkdir(path, { recursive: true })
48
+ await run(root, ["git", "init", "--initial-branch=main", path])
49
+ await run(path, ["git", "config", "user.email", "test@example.com"])
50
+ await run(path, ["git", "config", "user.name", "Test"])
51
+ await Bun.write(join(path, "README.md"), `${repo}\n`)
52
+ await run(path, ["git", "add", "README.md"])
53
+ await run(path, ["git", "commit", "-m", "initial"])
54
+ }
55
+
56
+ await write(
57
+ root,
58
+ "epics/contract/EPIC.md",
59
+ `---
60
+ ticketUrl: https://example.com/contract
61
+ repos:
62
+ - repo: agency
63
+ ref: main
64
+ tasks:
65
+ - id: foundations
66
+ - id: agent-contract
67
+ dependsOn: [foundations]
68
+ ---
69
+
70
+ # Contract
71
+ `,
72
+ )
73
+ await write(
74
+ root,
75
+ "tasks/foundations/TASK.md",
76
+ `---
77
+ ticketUrl: null
78
+ epic: contract
79
+ repo: agency
80
+ branch: foundations
81
+ base: main
82
+ pr: https://github.com/example/agency/pull/1
83
+ status: done
84
+ ---
85
+
86
+ # Foundations
87
+ `,
88
+ )
89
+ await write(
90
+ root,
91
+ "tasks/agent-contract/TASK.md",
92
+ `---
93
+ ticketUrl: null
94
+ epic: contract
95
+ phases:
96
+ - id: schema
97
+ - id: context-command
98
+ dependsOn: [schema]
99
+ ---
100
+
101
+ # Agent contract
102
+ Task prose.
103
+ `,
104
+ )
105
+ await write(
106
+ root,
107
+ "tasks/agent-contract/phases/schema/PHASE.md",
108
+ `---
109
+ repo: agency
110
+ branch: schema
111
+ base: main
112
+ pr: https://github.com/example/agency/pull/2
113
+ status: done
114
+ ---
115
+
116
+ # Schema
117
+ `,
118
+ )
119
+ await write(
120
+ root,
121
+ "tasks/agent-contract/phases/context-command/PHASE.md",
122
+ `---
123
+ repo: agency
124
+ repos:
125
+ - repo: docs
126
+ ref: main
127
+ branch: feat/context
128
+ base: main
129
+ pr: null
130
+ status: open
131
+ ---
132
+
133
+ # Context command
134
+ Phase prose.
135
+ `,
136
+ )
137
+
138
+ const code = join(root, "tasks/agent-contract/phases/context-command/code")
139
+ await mkdir(code, { recursive: true })
140
+ await run(join(root, "repos/agency"), [
141
+ "git",
142
+ "worktree",
143
+ "add",
144
+ "-b",
145
+ "feat/context",
146
+ join(code, "agency"),
147
+ "main",
148
+ ])
149
+ await run(join(root, "repos/docs"), [
150
+ "git",
151
+ "worktree",
152
+ "add",
153
+ "--detach",
154
+ join(code, "docs"),
155
+ "main",
156
+ ])
157
+ })
158
+
159
+ afterEach(async () => {
160
+ await cleanupTempDir(root)
161
+ })
162
+
163
+ test("returns complete phase context with graph, authority, Git, and validation state", async () => {
164
+ const target = "tasks/agent-contract/phases/context-command"
165
+ const result = await readContext(root, target)
166
+
167
+ expect(result).toMatchObject({
168
+ projection: "complete",
169
+ workbase: { root, version: 2 },
170
+ target: {
171
+ kind: "phase",
172
+ taskId: "agent-contract",
173
+ phaseId: "context-command",
174
+ },
175
+ graph: {
176
+ parent: { kind: "task", id: "agent-contract" },
177
+ dependencies: ["schema"],
178
+ readiness: { ready: true, blocked: false, blockers: [] },
179
+ aggregate: { status: "open", total: 1, open: 1 },
180
+ },
181
+ authority: {
182
+ mode: "execution",
183
+ writable: { repo: "agency", branch: "feat/context", base: "main" },
184
+ references: [{ repo: "docs", ref: "main" }],
185
+ },
186
+ workspace: {
187
+ materialization: "complete",
188
+ writable: {
189
+ materialized: true,
190
+ registered: true,
191
+ checkoutBranch: "feat/context",
192
+ detached: false,
193
+ },
194
+ references: [
195
+ {
196
+ repo: "docs",
197
+ materialized: true,
198
+ registered: true,
199
+ detached: true,
200
+ },
201
+ ],
202
+ },
203
+ pr: { url: null, state: "none" },
204
+ validation: { valid: true, warnings: [] },
205
+ })
206
+ expect(result.documents.epic.body).toContain("# Contract")
207
+ expect(result.documents.task.body).toContain("Task prose.")
208
+ expect(result.documents.phase.body).toContain("Phase prose.")
209
+ expect(result.documents.phase.sha256).toMatch(/^[a-f0-9]{64}$/)
210
+ expect(result.workspace.writable.branchCommit).toMatch(/^[a-f0-9]{40}$/)
211
+ expect(result.workspace.writable.baseCommit).toMatch(/^[a-f0-9]{40}$/)
212
+ expect(result.workspace.references[0].resolvedCommit).toMatch(
213
+ /^[a-f0-9]{40}$/,
214
+ )
215
+ })
216
+
217
+ test("makes compact projection explicit without omitting essential identity", async () => {
218
+ const result = await readContext(
219
+ root,
220
+ "tasks/agent-contract/phases/context-command/code/agency",
221
+ true,
222
+ )
223
+
224
+ expect(result.projection).toBe("compact")
225
+ expect(result.target.kind).toBe("phase")
226
+ expect(result.documents.phase.body).toBeUndefined()
227
+ expect(result.documents.phase.data.branch).toBe("feat/context")
228
+ expect(result.documents.phase.sha256).toMatch(/^[a-f0-9]{64}$/)
229
+ expect(result.workspace.writable).toEqual({
230
+ materialized: true,
231
+ registered: true,
232
+ })
233
+ expect(result.authority.writable.checkoutPath).toContain("code/agency")
234
+ })
235
+
236
+ test("reports dependency and validation blockers deterministically", async () => {
237
+ await write(
238
+ root,
239
+ "tasks/agent-contract/phases/schema/PHASE.md",
240
+ `---
241
+ repo: missing
242
+ branch: schema
243
+ base: main
244
+ pr: null
245
+ status: dropped
246
+ ---
247
+
248
+ # Schema
249
+ `,
250
+ )
251
+ const result = await readContext(
252
+ root,
253
+ "tasks/agent-contract/phases/context-command",
254
+ )
255
+
256
+ expect(result.graph.readiness.ready).toBe(false)
257
+ expect(result.graph.readiness.blockers).toContainEqual({
258
+ kind: "dependency",
259
+ id: "schema",
260
+ status: "dropped",
261
+ reason: "Phase dependency is dropped",
262
+ })
263
+ expect(result.validation.valid).toBe(false)
264
+ expect(result.validation.warnings).toContainEqual({
265
+ path: "tasks/agent-contract/phases/schema/PHASE.md",
266
+ message: "Unknown repository alias 'missing'",
267
+ })
268
+ })
269
+
270
+ test("resolves a bare task ID and rejects a root target", async () => {
271
+ const task = await readContext(root, "agent-contract")
272
+ expect(task.target).toMatchObject({
273
+ kind: "task",
274
+ taskId: "agent-contract",
275
+ })
276
+ expect(task.graph.parent).toEqual({ kind: "epic", id: "contract" })
277
+
278
+ await expect(readContext(root, ".")).rejects.toThrow(
279
+ "Cannot infer an Agency target",
280
+ )
281
+ })
282
+
283
+ test("resolves bare task IDs from inside another target", async () => {
284
+ const cwd = join(
285
+ root,
286
+ "tasks/agent-contract/phases/context-command/code/agency",
287
+ )
288
+ const logs = await captureLogs(() =>
289
+ runTestEffect(context({ cwd, target: "foundations", json: true })),
290
+ )
291
+ const result = JSON.parse(logs[0]!)
292
+ expect(result.target).toMatchObject({ kind: "task", taskId: "foundations" })
293
+ expect(result.authority.writable.branch).toBe("foundations")
294
+ })
295
+
296
+ test("computes orchestration readiness from runnable descendants", async () => {
297
+ await write(
298
+ root,
299
+ "tasks/agent-contract/TASK.md",
300
+ `---
301
+ ticketUrl: null
302
+ epic: contract
303
+ phases:
304
+ - id: schema
305
+ - id: context-command
306
+ dependsOn: [schema]
307
+ - id: parallel
308
+ ---
309
+
310
+ # Agent contract
311
+ `,
312
+ )
313
+ await write(
314
+ root,
315
+ "tasks/agent-contract/phases/schema/PHASE.md",
316
+ `---
317
+ repo: agency
318
+ branch: schema
319
+ base: main
320
+ pr: null
321
+ status: working
322
+ ---
323
+
324
+ # Schema
325
+ `,
326
+ )
327
+ await write(
328
+ root,
329
+ "tasks/agent-contract/phases/parallel/PHASE.md",
330
+ `---
331
+ repo: docs
332
+ branch: parallel
333
+ base: main
334
+ pr: null
335
+ status: open
336
+ ---
337
+
338
+ # Parallel
339
+ `,
340
+ )
341
+
342
+ const task = await readContext(root, "agent-contract")
343
+ expect(task.graph.readiness).toMatchObject({ ready: true, blocked: false })
344
+ expect(task.graph.aggregate).toMatchObject({
345
+ status: "working",
346
+ total: 3,
347
+ open: 2,
348
+ working: 1,
349
+ })
350
+
351
+ const epic = await readContext(root, "epics/contract")
352
+ expect(epic.graph.readiness).toMatchObject({ ready: true, blocked: false })
353
+ expect(epic.graph.aggregate).toMatchObject({
354
+ status: "working",
355
+ total: 4,
356
+ done: 1,
357
+ open: 2,
358
+ working: 1,
359
+ })
360
+ })
361
+
362
+ test("reports stale worktree registration independently of materialization", async () => {
363
+ const checkout = join(
364
+ root,
365
+ "tasks/agent-contract/phases/context-command/code/agency",
366
+ )
367
+ await rm(checkout, { recursive: true, force: true })
368
+
369
+ const result = await readContext(
370
+ root,
371
+ "tasks/agent-contract/phases/context-command",
372
+ )
373
+ expect(result.workspace.writable).toMatchObject({
374
+ materialized: false,
375
+ registered: true,
376
+ })
377
+ expect(result.workspace.materialization).toBe("partial")
378
+ })
379
+ })
@@ -0,0 +1,29 @@
1
+ import { Effect } from "effect"
2
+ import type { BaseCommandOptions } from "../utils/command"
3
+ import { ContextService } from "../services/ContextService"
4
+ import { createLoggers } from "../utils/effect"
5
+
6
+ interface ContextOptions extends BaseCommandOptions {
7
+ readonly target?: string
8
+ readonly compact?: boolean
9
+ readonly json?: boolean
10
+ }
11
+
12
+ export const context = (options: ContextOptions = {}) =>
13
+ Effect.gen(function* () {
14
+ const service = yield* ContextService
15
+ const { log } = createLoggers(options)
16
+ const result = yield* service.get(options)
17
+ log(JSON.stringify(result, null, 2))
18
+ })
19
+
20
+ export const help = `
21
+ Usage: agency context [target] [options]
22
+
23
+ Return the complete, read-only context for an epic, task, or phase. The target
24
+ defaults to the current directory and may be an entity path or task ID.
25
+
26
+ Options:
27
+ --json Output a versioned machine result
28
+ --compact Omit prose bodies and low-level Git details
29
+ `
@@ -11,6 +11,7 @@ import { repo } from "./repo"
11
11
  import { status } from "./status"
12
12
  import { task } from "./task"
13
13
  import { validate } from "./validate"
14
+ import { context } from "./context"
14
15
 
15
16
  const write = async (root: string, path: string, content: string) => {
16
17
  const fullPath = join(root, path)
@@ -135,6 +136,13 @@ status: open
135
136
  )
136
137
  await runTestEffect(status({ cwd: root, silent: true }))
137
138
  await runTestEffect(validate({ path: root, silent: true }))
139
+ await runTestEffect(
140
+ context({
141
+ target: "tasks/example-task/phases/implementation",
142
+ cwd: root,
143
+ silent: true,
144
+ }),
145
+ )
138
146
 
139
147
  expect(await Bun.file(join(root, "AGENTS.md")).exists()).toBe(false)
140
148
  expect(
@@ -15,6 +15,11 @@ interface ValidateOptions extends BaseCommandOptions {
15
15
 
16
16
  class ValidationFailedError extends Data.TaggedError("ValidationFailedError")<{
17
17
  readonly message: string
18
+ readonly root: string
19
+ readonly issues: readonly {
20
+ readonly path: string
21
+ readonly message: string
22
+ }[]
18
23
  }> {}
19
24
 
20
25
  export const validate = (
@@ -46,6 +51,8 @@ export const validate = (
46
51
  .join("\n")
47
52
  return yield* new ValidationFailedError({
48
53
  message: `Workbase validation failed with ${report.issues.length} issue${report.issues.length === 1 ? "" : "s"}:\n${details}`,
54
+ root: report.root,
55
+ issues: report.issues,
49
56
  })
50
57
  }
51
58
 
@@ -6,7 +6,7 @@ import { EpicService } from "../services/EpicService"
6
6
  import { TaskService } from "../services/TaskService"
7
7
  import { PhaseService } from "../services/PhaseService"
8
8
  import { WorktreeService } from "../services/WorktreeService"
9
- import { captureLogs } from "../test-utils"
9
+ import { captureErrors, captureLogs } from "../test-utils"
10
10
  import { work } from "./work"
11
11
  import type { PickWorkTarget } from "../workbase/work-target"
12
12
  import type { PickWorkbase } from "../workbase/workbase-choice"
@@ -568,7 +568,7 @@ describe("work command", () => {
568
568
 
569
569
  test("respects silent and verbose logging options", async () => {
570
570
  const verboseHarness = createHarness()
571
- const verboseLogs = await captureLogs(() =>
571
+ const verboseLogs = await captureErrors(() =>
572
572
  verboseHarness.run({ taskId: "example", verbose: true }),
573
573
  )
574
574
  expect(verboseLogs).toEqual([
@@ -577,7 +577,7 @@ describe("work command", () => {
577
577
  expect(verboseHarness.materializeOptions[0]?.verbose).toBe(true)
578
578
 
579
579
  const silentHarness = createHarness()
580
- const silentLogs = await captureLogs(() =>
580
+ const silentLogs = await captureErrors(() =>
581
581
  silentHarness.run({
582
582
  taskId: "example",
583
583
  verbose: true,
@@ -0,0 +1,87 @@
1
+ import { describe, expect, test } from "bun:test"
2
+ import { Schema } from "@effect/schema"
3
+ import errorFixture from "../fixtures/protocol/error.json"
4
+ import successFixture from "../fixtures/protocol/success.json"
5
+ import jsonSchema from "../schemas/agency-envelope-v1.schema.json"
6
+ import {
7
+ AgencyEnvelope,
8
+ collectCommandResult,
9
+ emitCommandResult,
10
+ errorEnvelope,
11
+ successEnvelope,
12
+ } from "./protocol"
13
+
14
+ describe("machine protocol", () => {
15
+ test("accepts the representative success and error fixtures", () => {
16
+ for (const fixture of [successFixture, errorFixture]) {
17
+ const decoded = Schema.decodeUnknownSync(AgencyEnvelope, {
18
+ onExcessProperty: "error",
19
+ })(fixture)
20
+ expect(JSON.stringify(decoded)).toBe(JSON.stringify(fixture))
21
+ }
22
+ })
23
+
24
+ test("publishes the matching v1 JSON Schema", () => {
25
+ expect(jsonSchema).toMatchObject({
26
+ $schema: "https://json-schema.org/draft/2020-12/schema",
27
+ title: "Agency machine result envelope v1",
28
+ oneOf: [
29
+ { properties: { version: { const: 1 }, ok: { const: true } } },
30
+ { properties: { version: { const: 1 }, ok: { const: false } } },
31
+ ],
32
+ })
33
+ })
34
+
35
+ test("collects one command result without writing it", async () => {
36
+ const result = await collectCommandResult(async () => {
37
+ emitCommandResult('{"value":42}')
38
+ })
39
+ expect(successEnvelope(result)).toEqual({
40
+ version: 1,
41
+ ok: true,
42
+ result: { value: 42 },
43
+ })
44
+ expect(successEnvelope(undefined).result).toBeNull()
45
+ })
46
+
47
+ test("rejects commands that emit multiple machine results", async () => {
48
+ await expect(
49
+ collectCommandResult(async () => {
50
+ emitCommandResult("first")
51
+ emitCommandResult("second")
52
+ }),
53
+ ).rejects.toThrow("more than one result")
54
+ })
55
+
56
+ test("normalizes unknown failures into stable error details", () => {
57
+ expect(errorEnvelope(new Error("boom"))).toEqual({
58
+ version: 1,
59
+ ok: false,
60
+ error: {
61
+ code: "COMMAND_FAILED",
62
+ message: "boom",
63
+ fields: {},
64
+ retryable: false,
65
+ },
66
+ })
67
+ })
68
+
69
+ test("preserves relevant fields from classified errors", () => {
70
+ expect(
71
+ errorEnvelope({
72
+ _tag: "ValidationFailedError",
73
+ message: "invalid workbase",
74
+ root: "/work/agency",
75
+ issues: [{ path: "TASK.md", message: "invalid status" }],
76
+ }),
77
+ ).toMatchObject({
78
+ error: {
79
+ code: "VALIDATION_FAILED",
80
+ fields: {
81
+ root: "/work/agency",
82
+ issues: [{ path: "TASK.md", message: "invalid status" }],
83
+ },
84
+ },
85
+ })
86
+ })
87
+ })