Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/opencode/src/automation/fixtures.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export const automationDefinitionFixture = Automation.Definition.parse({
revision: 2,
paused: false,
context: "fresh",
where: { projectID: "project-fixture" },
where: { projectID: "project-fixture", worktree: "daily-brief" },
createdAt: 1_800_000_000_000,
updatedAt: 1_800_000_030_000,
timezone: "UTC",
Expand Down
46 changes: 43 additions & 3 deletions packages/opencode/src/automation/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,36 @@ export namespace Automation {
details.push({ field, message })
}

export function normalizeWorktreePlacement(input: string) {
const slug = input
.trim()
.toLowerCase()
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+/, "")
.replace(/-+$/, "")
return slug.length > 0 && slug.length <= 40 ? slug : undefined
}

function normalizeWhere<T extends { projectID: ProjectID; worktree?: string }>(where: T): T {
if (!where.worktree) return where
const worktree = normalizeWorktreePlacement(where.worktree)
if (!worktree) return where
return { ...where, worktree }
}

function normalizeDefinitionInput<T extends CreateInput | Definition>(input: T): T {
return { ...input, where: normalizeWhere(input.where) } as T
}

function normalizeUpdateInput(input: UpdateInput): UpdateInput {
if (!input.where) return input
return { ...input, where: normalizeWhere(input.where) }
}

export function getWriterKey(definition: Definition) {
return definition.where.worktree ?? definition.where.projectID
}

function rejectUnknownFields(
input: Record<string, unknown>,
allowed: Set<string>,
Expand Down Expand Up @@ -404,7 +434,15 @@ export namespace Automation {
if (input.where.projectID !== projectID) {
addDetail(details, "where.projectID", "Automation must target the current project.")
}
if (input.where.worktree) addDetail(details, "where.worktree", "unsupported_where_worktree")
if (input.where.worktree && !normalizeWorktreePlacement(input.where.worktree)) {
addDetail(details, "where.worktree", "invalid_worktree_placement")
}
if (input.where.worktree && input.context === "continue") {
addDetail(details, "context", "unsupported_continue_with_worktree")
}
if (input.where.worktree && Instance.project.vcs !== "git") {
addDetail(details, "where.worktree", "unsupported_where_worktree_not_git")
}
details.push(...validateScheduleFields(input))
return details
}
Expand Down Expand Up @@ -433,6 +471,7 @@ export namespace Automation {
}

export function create(input: CreateInput, options?: { now?: number; sourceSessionID?: SessionID }): Definition {
input = normalizeDefinitionInput(input)
const now = options?.now ?? Date.now()
const details = validateCreateInput(input, Instance.project.id, now)
if (details.length) throw new ValidationError(details)
Expand Down Expand Up @@ -601,6 +640,7 @@ export namespace Automation {

export function update(id: string, patch: UpdateInput, options?: { now?: number }): Definition {
const previous = get(id)
patch = normalizeUpdateInput(patch)
const now = options?.now ?? Date.now()
const updateDetails = validateUpdateInput(previous, patch, now)
if (updateDetails.length) throw new ValidationError(updateDetails)
Expand Down Expand Up @@ -873,7 +913,7 @@ export namespace Automation {
const writerKeys = new Map(
definitions.map((row) => {
const item = Definition.parse(row.data)
return [item.id, item.where.worktree ?? item.where.projectID]
return [item.id, getWriterKey(item)]
}),
)
return rows.some((row) => {
Expand Down Expand Up @@ -1017,7 +1057,7 @@ export namespace Automation {
let current = initial
try {
const definition = get(initial.automationID)
writerKey = definition.where.worktree ?? definition.where.projectID
writerKey = getWriterKey(definition)
for (const run of await reconcileInterruptedRuns()) await publishRunUpdated(run)
if (data.activeWriters.has(writerKey) || hasDurableActiveWriter(initial, writerKey)) {
const stopped = reviseRun(initial, {
Expand Down
34 changes: 34 additions & 0 deletions packages/opencode/src/automation/runner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,47 @@ import { Automation } from "."
import { Session } from "@/session"
import { SessionPrompt } from "@/session/prompt"
import { AutomationRunContext, type AutomationRunBlocker } from "./run-context"
import { Worktree } from "@/worktree"

async function releaseAutomationWorktreeBindings(directory: string) {
for (let attempt = 0; attempt < 20; attempt++) {
const binding = await Session.findActiveWorktreeBinding(directory)
if (!binding) return
if (!binding.title.startsWith("Automation: ")) return
await Session.updateExecutionContext({ sessionID: binding.id, activeWorktree: null })
}
}

async function prepareWorktreePlacement(definition: Automation.Definition) {
const placement = definition.where.worktree
if (!placement) return undefined
const existing = await Worktree.lookupBySlug(placement)
if (existing) {
await releaseAutomationWorktreeBindings(existing.directory)
await Worktree.reset({ directory: existing.directory })
return existing
}
return Worktree.createReady({ name: placement })
}
Comment thread
Astro-Han marked this conversation as resolved.
Resolved

export const sessionPromptExecutor: Automation.RunExecutor = async ({ definition, run, attendance, signal }) => {
signal.throwIfAborted()
const sessionID =
definition.context === "continue" && definition.automationSessionID
? definition.automationSessionID
: (await Session.create({ title: `Automation: ${definition.title}` })).id
const worktree = await prepareWorktreePlacement(definition)
if (worktree) {
await Session.updateExecutionContext({
sessionID,
activeWorktree: {
directory: worktree.directory,
name: worktree.name,
branch: worktree.branch,
source: worktree.source,
},
})
}
const cancelPrompt = () => {
void SessionPrompt.cancel(sessionID, { source: "automation.cancel" }).catch(() => undefined)
}
Expand Down
13 changes: 13 additions & 0 deletions packages/opencode/src/worktree/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -162,6 +162,7 @@ export namespace Worktree {
readonly makeWorktreeInfo: (name?: string) => Effect.Effect<Info>
readonly createFromInfo: (info: Info, startCommand?: string) => Effect.Effect<void>
readonly create: (input?: CreateInput) => Effect.Effect<Info>
readonly createReady: (input?: CreateInput) => Effect.Effect<Info>
readonly list: () => Effect.Effect<Info[]>
readonly lookupByDirectory: (directory: string) => Effect.Effect<Info | undefined>
readonly lookupBySlug: (slug: string) => Effect.Effect<Info | undefined>
Expand Down Expand Up @@ -459,6 +460,13 @@ export namespace Worktree {
return info
})

const createReady = Effect.fn("Worktree.createReady")(function* (input?: CreateInput) {
const info = yield* makeWorktreeInfo(input?.name)
yield* setup(info)
yield* boot(info, input?.startCommand)
return info
})
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

const canonical = Effect.fnUntraced(function* (input: string) {
const abs = pathSvc.resolve(input)
const real = yield* fs.realPath(abs).pipe(Effect.catch(() => Effect.succeed(abs)))
Expand Down Expand Up @@ -751,6 +759,7 @@ export namespace Worktree {
makeWorktreeInfo,
createFromInfo,
create,
createReady,
list,
lookupByDirectory,
lookupBySlug,
Expand Down Expand Up @@ -782,6 +791,10 @@ export namespace Worktree {
return runPromise((svc) => svc.create(input))
}

export async function createReady(input?: CreateInput) {
return runPromise((svc) => svc.createReady(input))
}

export async function list() {
return runPromise((svc) => svc.list())
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { Automation } from "../../src/automation"
describe("automation event fixtures", () => {
test("match the frozen automation event schemas", () => {
expect(() => Automation.Event.DefinitionUpdated.properties.parse(automationEventFixtures[0].properties)).not.toThrow()
expect(automationEventFixtures[0].properties.where.worktree).toBe("daily-brief")
expect(() => Automation.Event.DefinitionDeleted.properties.parse(automationEventFixtures[1].properties)).not.toThrow()
expect(() => Automation.Event.RunUpdated.properties.parse(automationEventFixtures[2].properties)).not.toThrow()
})
Expand Down
72 changes: 65 additions & 7 deletions packages/opencode/test/server/automation-routes.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,11 @@
await Instance.disposeAll()
})

async function withAutomationApp<T>(fn: (input: { app: Hono; projectID: ProjectID }) => Promise<T>) {
await using tmp = await tmpdir({ git: true })
async function withAutomationApp<T>(
fn: (input: { app: Hono; projectID: ProjectID }) => Promise<T>,
options: { git?: boolean } = { git: true },
) {
await using tmp = await tmpdir({ git: options.git ?? true })
return Instance.provide({
directory: tmp.path,
fn: async () => {
Expand Down Expand Up @@ -420,22 +423,77 @@
})
})

test("rejects worktree placement until the PR5 location slice", async () => {
test("accepts fresh worktree placement for git projects", async () => {
await withAutomationApp(async ({ app, projectID }) => {
const body = await json(app, "/automation", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(recurringInput(projectID, { where: { projectID, worktree: "daily-brief" } })),
})

expect(body.where).toEqual({ projectID, worktree: "daily-brief" })

Check failure on line 434 in packages/opencode/test/server/automation-routes.test.ts

View workflow job for this annotation

GitHub Actions / unit-opencode

error: expect(received).toEqual(expected)

- { - "projectID": "global", - "worktree": "daily-brief", - } + undefined - Expected - 4 + Received + 1 at <anonymous> (/home/runner/work/pawwork/pawwork/packages/opencode/test/server/automation-routes.test.ts:434:26)
})
})

test("normalizes worktree placement before echoing the definition", async () => {
await withAutomationApp(async ({ app, projectID }) => {
const body = await json(app, "/automation", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(recurringInput(projectID, { where: { projectID, worktree: "Daily Brief!" } })),
})

expect(body.where).toEqual({ projectID, worktree: "daily-brief" })

Check failure on line 446 in packages/opencode/test/server/automation-routes.test.ts

View workflow job for this annotation

GitHub Actions / unit-opencode

error: expect(received).toEqual(expected)

- { - "projectID": "global", - "worktree": "daily-brief", - } + undefined - Expected - 4 + Received + 1 at <anonymous> (/home/runner/work/pawwork/pawwork/packages/opencode/test/server/automation-routes.test.ts:446:26)
})
})

test("rejects worktree placement that cannot be normalized to a slug", async () => {
await withAutomationApp(async ({ app, projectID }) => {
const response = await app.request("/automation", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(recurringInput(projectID, { where: { projectID, worktree: "/repo/.worktrees/run" } })),
body: JSON.stringify(recurringInput(projectID, { where: { projectID, worktree: "!!!" } })),
})
const body = await response.json()

expect(response.status).toBe(422)
expect(body.details).toEqual([
{ field: "where.worktree", message: "unsupported_where_worktree" },
])
expect(body.details).toEqual([{ field: "where.worktree", message: "invalid_worktree_placement" }])

Check failure on line 460 in packages/opencode/test/server/automation-routes.test.ts

View workflow job for this annotation

GitHub Actions / unit-opencode

error: expect(received).toEqual(expected)

[ { "field": "where.worktree", "message": "invalid_worktree_placement", }, + { + "field": "where.worktree", + "message": "unsupported_where_worktree_not_git", + }, ] - Expected - 0 + Received + 4 at <anonymous> (/home/runner/work/pawwork/pawwork/packages/opencode/test/server/automation-routes.test.ts:460:28)
})
})

test("rejects continue worktree placement", async () => {
await withAutomationApp(async ({ app, projectID }) => {
const response = await app.request("/automation", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(
recurringInput(projectID, { context: "continue", where: { projectID, worktree: "daily-brief" } }),
),
})
const body = await response.json()

expect(response.status).toBe(422)
expect(body.details).toEqual([{ field: "context", message: "unsupported_continue_with_worktree" }])

Check failure on line 476 in packages/opencode/test/server/automation-routes.test.ts

View workflow job for this annotation

GitHub Actions / unit-opencode

error: expect(received).toEqual(expected)

[ { "field": "context", "message": "unsupported_continue_with_worktree", }, + { + "field": "where.worktree", + "message": "unsupported_where_worktree_not_git", + }, ] - Expected - 0 + Received + 4 at <anonymous> (/home/runner/work/pawwork/pawwork/packages/opencode/test/server/automation-routes.test.ts:476:28)
})
})

test("rejects worktree placement for non-git projects", async () => {
await withAutomationApp(
async ({ app, projectID }) => {
const response = await app.request("/automation", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify(recurringInput(projectID, { where: { projectID, worktree: "daily-brief" } })),
})
const body = await response.json()

expect(response.status).toBe(422)
expect(body.details).toEqual([{ field: "where.worktree", message: "unsupported_where_worktree_not_git" }])
},
{ git: false },
)
})

test("rejects invalid semantic fields with the automation validation error shape", async () => {
await withAutomationApp(async ({ app, projectID }) => {
const cases = [
Expand Down
Loading
Loading