Files
worklane/.opencode/tools/worklane.ts
T
Ansho ReiandClaude Opus 5 bbb1568a0f (eadaca9) Add check and uncheck for one acceptance criterion, and bump to 0.6.0
Criteria are stored as - [ ] lines and nothing could tick one, so marking
progress meant replacing the whole list through set, losing the state of every
other item.

check and uncheck are separate commands rather than one verb with a flag,
sharing CheckArgs and cmd_check. The criterion is an index first and a substring
second, so a criterion whose text is literally "2" is reachable only by
substring. A number out of range is reported as a bad index rather than as a
substring that missed.

Only the character between the brackets is spliced, so the text keeps whatever
indentation and spacing it had. Criteria are counted inside the Acceptance
Criteria section only, so a checkbox written into a description is not a
criterion and a handwritten line in the section takes no number.

With the criterion omitted, the criteria are listed and the number asked for
when stdin is a terminal. Where it is not, the same list comes back as an error
instead. Prompting regardless would leave the opencode wrapper blocked on a
stdin that never closes, and that is the choice resolve_ticket already makes for
an ambiguous match, for the same reason: the wrapper keeps stderr and throws on
the code, so a list printed to stdout would be discarded.

Any listing of a subset keeps the real numbers. Renumbering the matches from one
would contradict the advice to use the number and point at the wrong criterion.

show now numbers the criteria as "1. [x] text", so the index is visible where
the ticket is read. That also drops a manual prefix strip, so clippy is one
warning below where it started.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-21 10:46:07 +02:00

443 lines
15 KiB
TypeScript

import { tool, ToolContext } from "@opencode-ai/plugin";
import path from "path";
function resolveWorklaneDir(context: ToolContext): string {
return path.join(context.worktree || context.directory || ".");
}
/**
* Run worklane and return its stdout, throwing with its stderr on failure.
*
* Both streams have to be piped. Bun defaults stderr to inherit, so it went to
* this process and never reached the model, and Bun.$ throws a ShellError whose
* message is only "Failed with exit code 1". Either way the CLI explained itself
* and nothing relayed the explanation.
*
* stdout is the fallback, not the source: worklane writes errors to stderr.
*/
async function run(cmd: string[], context: ToolContext): Promise<string> {
const proc = Bun.spawn(["worklane", ...cmd], {
cwd: resolveWorklaneDir(context),
stdout: "pipe",
stderr: "pipe",
});
const [stdout, stderr, exitCode] = await Promise.all([
new Response(proc.stdout).text(),
new Response(proc.stderr).text(),
proc.exited,
]);
if (exitCode !== 0) {
// anyhow prefixes its own "Error: ", and every caller here adds a prefix of
// its own, so drop it rather than relaying "Error adding comment: Error: ...".
const reason = stderr.trim().replace(/^Error:\s*/, "");
throw new Error(reason || stdout.trim() || `worklane exited with code ${exitCode}`);
}
return stdout.trim();
}
/**
* Description lines as worklane wants them, one --description value per line,
* blank ones included.
*
* cmd_add joins the values with a single newline, so an empty value is how a
* paragraph break is spelled. Dropping the blanks here, which is what the old
* filter(Boolean) did, collapsed every multi paragraph description into a single
* paragraph, against this tool's own instruction to separate paragraphs with
* newlines.
*
* Only the ends are trimmed, and only trailing whitespace within a line. Leading
* whitespace is content: it is what makes a nested markdown list or an indented
* block survive the trip.
*/
function descriptionLines(text: string): string[] {
const lines = text.split("\n").map((line: string) => line.trimEnd());
let start = 0;
let end = lines.length;
while (start < end && lines[start] === "") start++;
while (end > start && lines[end - 1] === "") end--;
return lines.slice(start, end);
}
/** One value per non-empty line, for the arguments that hold a list of items. */
function itemLines(text: string): string[] {
return text
.split("\n")
.map((line: string) => line.trim())
.filter(Boolean);
}
export const init = tool({
description:
"Initialize worklane in the current project. Creates the .worklane/ directory with backlog, committed, reviewing, and done subdirectories.",
args: {},
async execute(_args: Record<string, any>, context: ToolContext) {
try {
return await run(["init"], context);
} catch (err: any) {
return `Error initializing worklane: ${err.message}`;
}
},
});
export const add = tool({
description:
"Add a new ticket to the worklane backlog. Requires a title. Description, acceptance criteria, and plan each support multiple lines (one item per line). Tags are comma-separated.",
// Title is the only required field. Every other flag is left off entirely when
// the field is omitted, so an unmarked schema only forced the model to invent a
// value for fields it had nothing to say about.
args: {
title: tool.schema
.string()
.describe("Ticket title (required)"),
description: tool.schema
.string()
.describe("Description text. Use newlines between paragraphs.")
.optional(),
acceptance: tool.schema
.string()
.describe("Acceptance criteria, one per line. Put each criterium on its own line.")
.optional(),
plan: tool.schema
.string()
.describe("Implementation plan steps, one per line. Put each step on its own line.")
.optional(),
tags: tool.schema
.string()
.describe("Comma-separated tags, e.g. 'bug,frontend,urgent'")
.optional(),
due: tool.schema
.string()
.describe("Due date in YYYY-MM-DD format")
.optional(),
owner: tool.schema
.string()
.describe("Ticket owner name. If omitted, defaults to the git user.")
.optional(),
priority: tool.schema
.string()
.describe("Priority level, 1 (most urgent) to 5 (least). Left unset if omitted.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.title) {
return "Error adding ticket: title is required";
}
const cmd: string[] = ["add", "--title", args.title];
if (args.description) {
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
}
// Blanks are dropped from these two on purpose: each value is one criterium or
// one step, so an empty line between them is spacing rather than content.
if (args.acceptance) {
itemLines(args.acceptance).forEach((line: string) =>
cmd.push("--acceptance", line),
);
}
if (args.plan) {
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
}
if (args.tags) cmd.push("--tags", args.tags);
if (args.due) cmd.push("--due", args.due);
if (args.owner) cmd.push("--owner", args.owner);
if (args.priority) cmd.push("--priority", String(args.priority));
try {
return await run(cmd, context);
} catch (err: any) {
return `Error adding ticket: ${err.message}`;
}
},
});
export const ls = tool({
description:
"List all worklane tickets, sorted by priority then title. Optionally filter by status and by priority.",
args: {
status: tool.schema
.enum(["backlog", "committed", "reviewing", "done"])
.describe("Filter by status")
.optional(),
priority: tool.schema
.string()
.describe("Only show tickets at this priority, 1 (most urgent) to 5 (least)")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
const cmd = args.status ? ["ls", args.status] : ["ls"];
if (args.priority) cmd.push("--priority", String(args.priority));
try {
return await run(cmd, context);
} catch (err: any) {
// The directory is worth naming here: the usual failure is that there is
// no .worklane above it.
return `Error listing tickets: ${err.message}, Dir: ${resolveWorklaneDir(context)}`;
}
},
});
export const show = tool({
description:
"Show a complete ticket by UUID or title. Displays title, description, acceptance criteria, implementation plan, metadata, and comments.",
args: {
id: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.id) {
return "Error showing ticket: id is required";
}
try {
return await run(["show", args.id], context);
} catch (err: any) {
return `Error showing ticket: ${err.message}`;
}
},
});
export const mv = tool({
description:
"Move a ticket to a different status in the workflow (backlog -> committed -> reviewing -> done).",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
status: tool.schema
.enum(["backlog", "committed", "reviewing", "done"])
.describe("Target status (required)"),
force: tool.schema
.boolean()
.describe("Force move (allows non-sequential moves like done -> backlog). Use with caution.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return "Error moving ticket: ticket is required";
}
if (!args.status) {
return "Error moving ticket: status is required. Must be one of: backlog, committed, reviewing, done";
}
const cmd: string[] = ["mv", args.ticket, "--status", args.status];
if (args.force) cmd.push("--force");
try {
return await run(cmd, context);
} catch (err: any) {
return `Error moving ticket: ${err.message}`;
}
},
});
export const comment = tool({
description: "Add a comment to an existing ticket. The comment body supports markdown and newlines. Use it to add review feedback, notes, or status updates.",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
body: tool.schema
.string()
.describe("Comment body text (required). Supports markdown formatting and multiple paragraphs separated by newlines."),
owner: tool.schema
.string()
.describe("Comment author. If omitted, defaults to the git user.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return "Error adding comment: ticket is required";
}
if (!args.body) {
return "Error adding comment: body is required";
}
const cmd: string[] = ["comment", args.ticket, args.body];
if (args.owner) cmd.push("--owner", args.owner);
try {
return await run(cmd, context);
} catch (err: any) {
return `Error adding comment: ${err.message}`;
}
},
});
export const set = tool({
description:
"Replace fields on an existing worklane ticket. Only the fields given are touched; everything else in the file, including ticked criteria and handwritten sections, is left alone. Owner is not settable here, use chown. Status is not settable here, use mv. To add to a section instead of replacing it, use append.",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
title: tool.schema
.string()
.describe("New title. The file is renamed to match, keeping the UUID.")
.optional(),
description: tool.schema
.string()
.describe("New description, replacing the whole section. Use newlines between paragraphs.")
.optional(),
acceptance: tool.schema
.string()
.describe("New acceptance criteria, one per line, replacing the whole list.")
.optional(),
plan: tool.schema
.string()
.describe("New implementation plan steps, one per line, replacing the whole list.")
.optional(),
tags: tool.schema
.string()
.describe("New comma-separated tags, replacing the existing ones.")
.optional(),
due: tool.schema
.string()
.describe("New due date in YYYY-MM-DD format")
.optional(),
priority: tool.schema
.string()
.describe("New priority level, 1 (most urgent) to 5 (least)")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return "Error setting fields: ticket is required";
}
const cmd: string[] = ["set", args.ticket];
if (args.title) cmd.push("--title", args.title);
if (args.description) {
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
}
if (args.acceptance) {
itemLines(args.acceptance).forEach((line: string) =>
cmd.push("--acceptance", line),
);
}
if (args.plan) {
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
}
if (args.tags) cmd.push("--tags", args.tags);
if (args.due) cmd.push("--due", args.due);
if (args.priority) cmd.push("--priority", String(args.priority));
if (cmd.length === 2) {
return "Error setting fields: give at least one field to change";
}
try {
return await run(cmd, context);
} catch (err: any) {
return `Error setting fields: ${err.message}`;
}
},
});
export const append = tool({
description:
"Add to a section of an existing worklane ticket without replacing what is there. The description gains a new paragraph; acceptance criteria and plan steps are added to the end of their lists, with steps numbered on from the last. Ticked criteria and handwritten content are left alone. To replace a section outright, use set.",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
description: tool.schema
.string()
.describe("Text to add as a new paragraph at the end of the description.")
.optional(),
acceptance: tool.schema
.string()
.describe("Acceptance criteria to add, one per line.")
.optional(),
plan: tool.schema
.string()
.describe("Implementation plan steps to add, one per line.")
.optional(),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return "Error appending: ticket is required";
}
const cmd: string[] = ["append", args.ticket];
if (args.description) {
descriptionLines(args.description).forEach((line: string) =>
cmd.push("--description", line),
);
}
if (args.acceptance) {
itemLines(args.acceptance).forEach((line: string) =>
cmd.push("--acceptance", line),
);
}
if (args.plan) {
itemLines(args.plan).forEach((line: string) => cmd.push("--plan", line));
}
if (cmd.length === 2) {
return "Error appending: give at least one section to add to";
}
try {
return await run(cmd, context);
} catch (err: any) {
return `Error appending: ${err.message}`;
}
},
});
/**
* check and uncheck differ only in the verb, so the tool is built once.
*
* The criterion is required here even though the CLI makes it optional: without it the
* CLI prompts, and there is no terminal on this side of the pipe. The CLI answers a
* missing criterion with the numbered list on stderr, which run() relays, so the model
* sees the options and can retry with a number.
*/
function checkboxTool(verb: "check" | "uncheck") {
const past = verb === "check" ? "Checked" : "Unchecked";
return tool({
description:
`${past === "Checked" ? "Tick" : "Untick"} one acceptance criterion on a worklane ticket. ` +
"Every other criterion keeps its state. Identify the criterion by its number as shown by show, " +
"or by a substring of its text; a substring matching more than one is an error listing them.",
args: {
ticket: tool.schema
.string()
.describe("Ticket UUID prefix (4+ chars) or title substring (required)"),
criterion: tool.schema
.string()
.describe(
"Criterion number as shown by show, or a substring of its text (required)",
),
},
async execute(args: Record<string, any>, context: ToolContext) {
if (!args.ticket) {
return `Error running ${verb}: ticket is required`;
}
if (!args.criterion) {
return `Error running ${verb}: criterion is required, give the number or a substring`;
}
try {
return await run([verb, args.ticket, String(args.criterion)], context);
} catch (err: any) {
return `Error running ${verb}: ${err.message}`;
}
},
});
}
export const check = checkboxTool("check");
export const uncheck = checkboxTool("uncheck");