From 646eb49676f1413a2cdbf5df720a48e07971718c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Tue, 24 Nov 2026 11:19:20 +0000 Subject: [PATCH 01/15] feat(provider): run a custom issue provider command and validate its answer (#357) Phase 1 of #357: the version-1 fetch request/answer schemas (strict zod) and fetchCustomIssue, which runs the configured argv with the request on stdin, bounds it at 15 s and 1 MiB, and maps the provider's errors. runCapturing gains stdin input and maxBuffer, and now reports a timed-out child as killed with a null code even when its SIGTERM handler exits with a code. Gate 1: all verify.md sections exit 0 (pnpm test 3898, docs:test 1655). Gate 2: reviewer subagent PASS after two loopbacks. --- context/notes.md | 20 + src/integrations/custom-provider.test.ts | 546 +++++++++++++++++++++++ src/integrations/custom-provider.ts | 246 ++++++++++ src/lib/cli.test.ts | 85 ++++ src/lib/cli.ts | 48 +- 5 files changed, 943 insertions(+), 2 deletions(-) create mode 100644 context/notes.md create mode 100644 src/integrations/custom-provider.test.ts create mode 100644 src/integrations/custom-provider.ts diff --git a/context/notes.md b/context/notes.md new file mode 100644 index 00000000..db65c82f --- /dev/null +++ b/context/notes.md @@ -0,0 +1,20 @@ +# Notes — custom issue providers (#357) + +Non-blocking observations from the gates. Branch-local; `/feature-close` deletes this file. + +## Phase 1 + +- **Signal death that is not a timeout is misreported** (`custom-provider.ts`, the fall-through after the + `killed` check): a provider killed by an outside signal reads "could not be run", and the text embeds Node's + `Command failed: …` with the start of stderr, not its last line. Branch-local; fix before the feature closes. +- **Defaults for omitted `type`, `labels`, `fields`, `kind`, `can`** (null / empty) are the coder's choice, not + the plan's — they become contract once released, so Phase 6's guide must state them. `can` is in the fetch + schema because §4.2's example carries it. +- **Errors rebuilt without `cause`** in `describeRunFailure`, and a type assertion on Node's error there; + `CommandResult` could replace `Awaited>`; the test file holds literal U+202E + and U+200B where `\u` escapes would read better. +- **`runCapturing`'s timeout message** (` was killed after ms`) does not match base-command's timeout + pattern; harmless while every caller builds its own message. +- **For Phase 4's printers:** the title may hold control characters (D6 allows it) and must be escaped + wherever printed; a `url` with `user:token@` passes the http(s) check and would reach `--json`; `not_found` + gives `--json` code `failed`, which `branch.mdx`'s table should say. diff --git a/src/integrations/custom-provider.test.ts b/src/integrations/custom-provider.test.ts new file mode 100644 index 00000000..5107d0a6 --- /dev/null +++ b/src/integrations/custom-provider.test.ts @@ -0,0 +1,546 @@ +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { isProcessRunning, KILL_GRACE_MS } from "../lib/cli.js"; +import { InvalidValueError } from "../lib/prompt.js"; +import { fetchCustomIssue } from "./custom-provider.js"; + +// src/test-setup.ts mocks ../lib/cli.js for every suite so command tests never +// execute anything. The runner is the subject here, so it opts back out and +// drives a real child process. +vi.unmock("../lib/cli.js"); + +const node = process.execPath; +const NAME = "verk"; + +// The stand-in provider is written into a temp directory, one script per case: +// it is a program the runner executes, not a module of this package, and none +// of it ships under src/. +let dir: string; +let scripts = 0; + +beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "worktree-provider-")); +}); + +afterAll(() => { + if (dir) { + rmSync(dir, { recursive: true, force: true }); + } +}); + +/** The argv of a stand-in provider whose whole program is `body`. */ +function provider(body: string): string[] { + scripts += 1; + const file = join(dir, `provider-${scripts}.mjs`); + writeFileSync(file, body); + return [node, file]; +} + +/** A provider that prints `document` as its answer. */ +function printing(document: unknown, { raw = false } = {}): string[] { + const text = raw ? String(document) : JSON.stringify(document); + return provider(`process.stdout.write(${JSON.stringify(text)});`); +} + +// The version-1 fetch answer of the contract (plan §4.2), field for field. +function issue(overrides: Record = {}) { + return { + key: "VERK-42", + title: "Fix login", + url: "https://verk.example/i/42", + type: "Bug", + labels: ["auth"], + fields: [], + kind: "bugfix", + can: ["assign", "start"], + ...overrides, + }; +} + +function answer(overrides: Record = {}) { + return { version: 1, issue: issue(overrides) }; +} + +function fetching(argv: string[], reference = "VERK-42", timeout?: number) { + return fetchCustomIssue(argv, reference, { + name: NAME, + cwd: dir, + ...(timeout === undefined ? {} : { timeoutMs: timeout }), + }); +} + +describe("a valid answer", () => { + it("is parsed into the issue the provider described", async () => { + // Expected values are the contract's own example (plan §4.2), not read + // back from the parser. + await expect(fetching(printing(answer()))).resolves.toEqual({ + key: "VERK-42", + title: "Fix login", + url: "https://verk.example/i/42", + type: "Bug", + labels: ["auth"], + fields: [], + kind: "bugfix", + can: ["assign", "start"], + }); + }); + + it("carries extra fields in the shape the rules engine compares (D7)", async () => { + const fields = [ + { id: "sev", name: "Severity", values: [{ id: "1", name: "High" }] }, + ]; + + const result = await fetching(printing(answer({ fields }))); + + expect(result.fields).toEqual(fields); + }); + + it("defaults what the provider leaves out: no url, type, labels, fields, kind or abilities", async () => { + const result = await fetching( + printing({ version: 1, issue: { key: "VERK-1", title: "T" } }), + ); + + expect(result).toEqual({ + key: "VERK-1", + title: "T", + url: null, + type: null, + labels: [], + fields: [], + kind: null, + can: [], + }); + }); + + it("accepts a null url and a null kind", async () => { + const result = await fetching( + printing(answer({ url: null, kind: null, type: null })), + ); + + expect(result).toMatchObject({ url: null, kind: null, type: null }); + }); + + it("accepts a title with control characters, which only reaches the slug", async () => { + const result = await fetching(printing(answer({ title: "a\u001b[31mb" }))); + + expect(result.title).toBe("a\u001b[31mb"); + }); + + it("runs the command in the directory it is given", async () => { + const argv = provider( + `process.stdout.write(JSON.stringify({version:1,issue:{key:"K-1",title:process.cwd()}}));`, + ); + + const result = await fetchCustomIssue(argv, "K-1", { + name: NAME, + cwd: dir, + }); + + // macOS reports the temp directory through a symlink; compare the tail. + expect(result.title.endsWith(dir.split("/").pop() ?? "")).toBe(true); + }); +}); + +describe("the request", () => { + // D2: one JSON document on stdin, argv exactly what was configured. A + // reference that starts with `-` would be read as an option by the provider's + // own parser had it been appended to argv. + it("reaches the provider as one JSON document on stdin, a leading dash intact", async () => { + const argv = provider(` + let stdin = ""; + process.stdin.on("data", (chunk) => (stdin += chunk)).on("end", () => { + const seen = JSON.stringify({ stdin, argv: process.argv.slice(2) }); + process.stdout.write(JSON.stringify({ version: 1, issue: { key: "K-1", title: seen } })); + }); + `); + + const result = await fetching(argv, "--output=/etc/passwd"); + const seen = JSON.parse(result.title); + + expect(JSON.parse(seen.stdin)).toEqual({ + version: 1, + operation: "fetch", + reference: "--output=/etc/passwd", + }); + expect(seen.argv).toEqual([]); + expect(argv).not.toContain("--output=/etc/passwd"); + }); +}); + +describe("what is refused at the boundary (D6)", () => { + async function refusal(argv: string[]) { + const error = await fetching(argv).catch((caught: unknown) => caught); + expect(error).toBeInstanceOf(Error); + return error as Error; + } + + it.each([ + ["a missing version", { issue: issue() }], + ["an unknown version", { version: 2, issue: issue() }], + ["a version that is a string", { version: "1", issue: issue() }], + ])("%s, naming the provider", async (_label, document) => { + const error = await refusal(printing(document)); + + expect(error.message).toMatch(/^verk: /); + expect(error.message).toContain("version"); + expect(error).not.toBeInstanceOf(InvalidValueError); + }); + + it.each([ + ["an empty key", "", /key/], + ["a key with a slash", "a/b", /key/], + ["a key with a dot", "a.b", /key/], + ["a key with a space", "a b", /key/], + ["a key starting with a dash", "-a", /key/], + ["a key ending with a dash", "a-", /key/], + ["a key with a double dash", "a--b", /key/], + ["a key with a control character", "A-1\u0007", /key/], + ["a key of 65 characters", "a".repeat(65), /key/], + ])("%s", async (_label, key, where) => { + const error = await refusal(printing(answer({ key }))); + + expect(error.message).toMatch(/^verk: /); + expect(error.message).toMatch(where); + }); + + it("accepts a key of exactly 64 characters, and underscores between segments", async () => { + const key = `${"a".repeat(31)}_${"b".repeat(32)}`; + expect(key).toHaveLength(64); + + const result = await fetching(printing(answer({ key }))); + + expect(result.key).toBe(key); + }); + + it.each([ + "javascript:alert(1)", + "file:///etc/passwd", + "ftp://verk.example/i/1", + "not a url", + "", + ])("a url that is not http or https: %j", async (url) => { + const error = await refusal(printing(answer({ url }))); + + expect(error.message).toMatch(/^verk: /); + expect(error.message).toContain("url"); + }); + + it.each([ + ["type", { type: "Bug\u001b[2J" }], + ["a label", { labels: ["ok", "bad‮"] }], + ["a field id", { fields: [{ id: "a\u0000", name: "n", values: [] }] }], + ["a field name", { fields: [{ id: "a", name: "n\r", values: [] }] }], + [ + "a field value", + { fields: [{ id: "a", name: "n", values: [{ name: "v​" }] }] }, + ], + ["the url", { url: "https://verk.example/\u0007" }], + ])("a control or formatting character in %s", async (_label, overrides) => { + const error = await refusal(printing(answer(overrides))); + + expect(error.message).toMatch(/^verk: /); + }); + + it("a kind outside feature, bugfix and chore", async () => { + const error = await refusal(printing(answer({ kind: "epic" }))); + + expect(error.message).toContain("kind"); + }); + + it("a key the contract does not name, because the schema is strict", async () => { + const error = await refusal(printing(answer({ assignee: "ada" }))); + + expect(error.message).toMatch(/^verk: /); + }); + + it("an unknown top-level key", async () => { + const error = await refusal(printing({ ...answer(), extra: true })); + + expect(error.message).toMatch(/^verk: /); + }); + + it("output that is not JSON", async () => { + const error = await refusal(printing("hello", { raw: true })); + + expect(error.message).toMatch(/^verk: .*JSON/); + }); + + it("JSON that is not an object", async () => { + const error = await refusal(printing("[1]", { raw: true })); + + expect(error.message).toMatch(/^verk: /); + }); + + it("stdout over 1 MiB, ending the provider", async () => { + const argv = provider( + `process.stdout.write("a".repeat(2 * 1024 * 1024)); setTimeout(() => {}, 600_000);`, + ); + + const error = await refusal(argv); + + expect(error.message).toMatch(/^verk: .*1 MiB/); + }); + + it("does not show the provider's own bytes in the refusal of a bad key", async () => { + const error = await refusal(printing(answer({ key: "x\u001b[2Jy/" }))); + + expect(error.message.includes("\u001b")).toBe(false); + }); +}); + +describe("an error the provider reports (D6)", () => { + function failing(code: string, message = "No issue VERK-42.") { + return printing({ version: 1, error: { code, message } }); + } + + it("maps invalid_reference to an invalid value, exit 2", async () => { + const error = await fetching( + failing("invalid_reference", "Not a Verk key."), + ).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(InvalidValueError); + expect((error as InvalidValueError).message).toBe("verk: Not a Verk key."); + expect((error as InvalidValueError).oclif).toEqual({ exit: 2 }); + }); + + it.each([ + "not_found", + "failed", + ])("maps %s to a plain failure, exit 1, with the provider's message", async (code) => { + const error = await fetching(failing(code)).catch( + (caught: unknown) => caught, + ); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(InvalidValueError); + expect((error as Error).message).toBe("verk: No issue VERK-42."); + expect((error as { oclif?: unknown }).oclif).toBeUndefined(); + }); + + it("honours the error document when the provider also exits non-zero", async () => { + const argv = provider( + `process.stdout.write(JSON.stringify({version:1,error:{code:"not_found",message:"gone"}})); process.exit(1);`, + ); + + await expect(fetching(argv)).rejects.toThrow("verk: gone"); + }); + + it("refuses an error code the contract does not name", async () => { + await expect(fetching(failing("exploded"))).rejects.toThrow(/^verk: /); + }); + + it("shows the provider's message visibly and without a secret", async () => { + const message = `bad\u001b[2J ghp_${"a".repeat(30)}`; + + const error = await fetching(failing("failed", message)).catch( + (caught: unknown) => caught as Error, + ); + + expect((error as Error).message).toBe("verk: bad\\x1b[2J ***"); + }); +}); + +describe("a provider that fails without a valid document", () => { + it("is a failure naming issueProvider.command, with the exit code", async () => { + const argv = provider("process.exit(3);"); + + const error = await fetching(argv).catch((caught: unknown) => caught); + + expect(error).toBeInstanceOf(Error); + expect(error).not.toBeInstanceOf(InvalidValueError); + expect((error as Error).message).toMatch( + /^verk: .*issueProvider\.command.*3/, + ); + }); + + it("is a failure even when stdout holds a valid answer", async () => { + const argv = provider( + `process.stdout.write(${JSON.stringify(JSON.stringify(answer()))}); process.exit(1);`, + ); + + await expect(fetching(argv)).rejects.toThrow(/^verk: .*exit/); + }); + + it("shows the last non-empty line of stderr, on failure only", async () => { + const argv = provider( + `process.stderr.write("noise\\nconnecting\\nHTTP 500 from upstream\\n\\n"); process.exit(1);`, + ); + + await expect(fetching(argv)).rejects.toThrow(/HTTP 500 from upstream/); + }); + + it("does not show earlier stderr lines", async () => { + const argv = provider( + `process.stderr.write("secret-looking first line\\nlast line\\n"); process.exit(1);`, + ); + + const error = await fetching(argv).catch((caught: unknown) => caught); + + expect((error as Error).message).not.toContain("first line"); + }); + + it("redacts a token-shaped string in stderr", async () => { + const token = `ghp_${"A1b2C3d4E5".repeat(3)}`; + const argv = provider( + `process.stderr.write("auth failed with ${token}\\n"); process.exit(1);`, + ); + + const error = (await fetching(argv).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toContain("auth failed with ***"); + expect(error.message).not.toContain(token); + }); + + it("escapes control characters in stderr", async () => { + const argv = provider( + `process.stderr.write("a\\u001b[2Jb\\n"); process.exit(1);`, + ); + + const error = (await fetching(argv).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toContain("a\\x1b[2Jb"); + expect(error.message.includes("\u001b")).toBe(false); + }); + + it("cuts stderr to 200 characters", async () => { + const argv = provider( + `process.stderr.write("e".repeat(500) + "\\n"); process.exit(1);`, + ); + + const error = (await fetching(argv).catch( + (caught: unknown) => caught, + )) as Error; + + expect(error.message).toContain("e".repeat(200)); + expect(error.message).not.toContain("e".repeat(201)); + }); + + it("shows stderr when the answer is malformed too", async () => { + const argv = provider( + `process.stderr.write("deprecated flag\\n"); process.stdout.write("oops");`, + ); + + await expect(fetching(argv)).rejects.toThrow(/deprecated flag/); + }); + + it("does not show stderr when the answer is good", async () => { + const argv = provider( + `process.stderr.write("just a warning\\n"); process.stdout.write(${JSON.stringify(JSON.stringify(answer()))});`, + ); + + await expect(fetching(argv)).resolves.toMatchObject({ key: "VERK-42" }); + }); + + it("is a failure naming issueProvider.command when the program cannot be run", async () => { + const error = await fetching([ + "northguild-worktree-no-such-provider", + ]).catch((caught: unknown) => caught); + + expect((error as Error).message).toMatch(/^verk: .*issueProvider\.command/); + expect(error).not.toBeInstanceOf(InvalidValueError); + }); + + it("is a failure naming issueProvider.command for an empty command", async () => { + await expect(fetching([])).rejects.toThrow(/issueProvider\.command/); + }); +}); + +describe("the time bound (D6)", () => { + afterEach(() => { + vi.doUnmock("../lib/cli.js"); + vi.resetModules(); + }); + + const ignoreTerm = (pidFile: string) => + `import { writeFileSync } from "node:fs"; + writeFileSync(${JSON.stringify(pidFile)}, String(process.pid)); + process.on("SIGTERM", () => {}); + setTimeout(() => {}, 600_000);`; + + it("rejects a provider that sleeps past the bound with the message base-command.ts maps to a timeout", async () => { + const argv = provider(`setTimeout(() => {}, 600_000);`); + + const error = (await fetching(argv, "K-1", 1_000).catch( + (caught: unknown) => caught, + )) as Error; + + // The pattern base-command.ts's TIMEOUT_MESSAGE uses, and the exact + // sentence D6 writes (here for a 1s bound, so `1s`, not `15s`). + expect(error.message).toBe( + "verk: the issue provider did not answer within 1s.", + ); + expect(error.message).toMatch(/did not (?:answer|finish) within \d+s/); + }); + + it("bounds every call at 15 s and 1 MiB when the caller names no timeout", async () => { + // The file-level unmock hands this suite the real runner; this case wants + // the global mock (src/test-setup.ts) so nothing runs and the call's + // options can be read. + vi.resetModules(); + vi.doMock("../lib/cli.js", () => ({ runCapturing: mockRunCapturing })); + const mockRunCapturing = vi.fn().mockResolvedValue({ + stdout: JSON.stringify(answer()), + stderr: "", + exitCode: 0, + }); + const { fetchCustomIssue: fetchWithMock } = await import( + "./custom-provider.js" + ); + + await fetchWithMock(["provider"], "K-1", { name: NAME }); + + expect(mockRunCapturing).toHaveBeenCalledWith( + "provider", + [], + expect.objectContaining({ timeout: 15_000, maxBuffer: 1_048_576 }), + ); + }); + + it("says 15s for a 15 000 ms bound", async () => { + vi.resetModules(); + const killed = Object.assign(new Error("killed"), { killed: true }); + vi.doMock("../lib/cli.js", () => ({ + runCapturing: vi.fn().mockRejectedValue(killed), + })); + const { fetchCustomIssue: fetchWithMock } = await import( + "./custom-provider.js" + ); + + await expect( + fetchWithMock(["provider"], "K-1", { name: NAME }), + ).rejects.toThrow("verk: the issue provider did not answer within 15s."); + }); + + it("reports a provider whose SIGTERM handler exits 1 as a timeout", async () => { + const argv = provider( + `process.on("SIGTERM", () => process.exit(1)); setTimeout(() => {}, 600_000);`, + ); + + await expect(fetching(argv, "K-1", 1_000)).rejects.toThrow( + "verk: the issue provider did not answer within 1s.", + ); + }); + + it( + "kills a provider that ignores SIGTERM, with SIGKILL after the grace period", + async () => { + const pidFile = join(dir, "sigterm-ignorer.pid"); + const argv = provider(ignoreTerm(pidFile)); + + await expect(fetching(argv, "K-1", 1_000)).rejects.toThrow( + /did not answer within 1s/, + ); + + const pid = Number(readFileSync(pidFile, "utf8")); + expect(pid).toBeGreaterThan(0); + // The rejection waits for the child's exit, so by now it is gone. + expect(isProcessRunning(pid)).toBe(false); + }, + 1_000 + KILL_GRACE_MS + 5_000, + ); +}); diff --git a/src/integrations/custom-provider.ts b/src/integrations/custom-provider.ts new file mode 100644 index 00000000..03311523 --- /dev/null +++ b/src/integrations/custom-provider.ts @@ -0,0 +1,246 @@ +import { z } from "zod"; +import { runCapturing } from "../lib/cli.js"; +import { showVisibly } from "../lib/config-keys.js"; +import { InvalidValueError } from "../lib/prompt.js"; +import { redactSecrets } from "../lib/redact.js"; + +// A custom issue provider is a configured command that prints JSON in the shape +// below (version 1). It runs through `runCapturing`, so it is bounded, killed on +// overrun and never sees a shell, and whatever it prints is untrusted input: +// validated here, at the boundary, before anything else reads it (D6). The zod +// schemas are the contract's source; the guide is its reference. +// +// This module imports no integration and no caller: it knows a command, a +// reference and a name, and nothing tracker-shaped. + +/** Per call (D6). A provider that has not answered by then is killed. */ +export const PROVIDER_TIMEOUT_MS = 15_000; + +/** Stdout cap, in bytes (D6); `maxBuffer` ends the child that passes it. */ +const MAX_STDOUT_BYTES = 1024 * 1024; + +/** The longest stretch of the provider's own words shown to a person. */ +const MAX_SHOWN_CHARS = 200; + +const PROTOCOL_VERSION = 1; + +// `key` becomes `{id}` in a ref and a directory name, so it can hold none of +// what git-check-ref-format refuses: no `/`, `.`, space, control character, or +// a leading, trailing or doubled separator. +const KEY_PATTERN = /^[A-Za-z0-9]+(?:[-_][A-Za-z0-9]+)*$/; +const MAX_KEY_LENGTH = 64; + +// The same rule as the approval prompt's `step` (config-keys.ts): a control or +// formatting character could redraw the terminal or reorder what is printed. +const CONTROL_OR_FORMAT = /[\p{Cc}\p{Cf}]/u; + +const plainText = z.string().refine((value) => !CONTROL_OR_FORMAT.test(value), { + message: "must not contain control or formatting characters", +}); + +const key = plainText + .max(MAX_KEY_LENGTH) + .regex(KEY_PATTERN, "must be letters and digits joined by - or _"); + +const url = plainText + .refine((value) => /^https?:$/.test(URL.parse(value)?.protocol ?? ""), { + message: "must be an http or https URL", + }) + .nullable() + .default(null); + +const fieldValue = z.strictObject({ + id: plainText.optional(), + name: plainText.optional(), +}); + +// `IssueField`-shaped (branch-type.ts), so the rules engine takes it unchanged. +const field = z.strictObject({ + id: plainText, + name: plainText, + values: z.array(fieldValue), +}); + +const issueSchema = z.strictObject({ + key, + // Only `slugifyBranchTitle` reads it, and that keeps `[a-z0-9_-]`; the rule + // above does not apply, so a title is not refused for what it cannot do. + title: z.string(), + url, + type: plainText.nullable().default(null), + labels: z.array(plainText).default([]), + fields: z.array(field).default([]), + kind: z.enum(["feature", "bugfix", "chore"]).nullable().default(null), + can: z.array(z.enum(["assign", "start"])).default([]), +}); + +const ERROR_CODES = ["invalid_reference", "not_found", "failed"] as const; + +const fetchAnswer = z.strictObject({ + version: z.literal(PROTOCOL_VERSION), + issue: issueSchema, +}); + +const errorAnswer = z.strictObject({ + version: z.literal(PROTOCOL_VERSION), + error: z.strictObject({ code: z.enum(ERROR_CODES), message: z.string() }), +}); + +export type CustomIssue = z.output; + +export interface FetchCustomIssueOptions { + /** The provider's display name; every message names it. */ + name: string; + /** The directory the command runs in (the repository's top level). */ + cwd?: string; + /** Overrides the 15 s bound; for tests. */ + timeoutMs?: number; +} + +/** Text the provider wrote, as it may be shown: no secret, no escape, cut. */ +function shown(text: string): string { + return showVisibly(redactSecrets(text)).slice(0, MAX_SHOWN_CHARS); +} + +function lastLine(stderr: string): string { + const lines = stderr.split("\n").filter((line) => line.trim() !== ""); + return lines.at(-1) ?? ""; +} + +/** A failure that is the provider's, with the tail of its stderr when it has one. */ +function failure(name: string, what: string, stderr = ""): Error { + const tail = lastLine(stderr); + return new Error( + tail + ? `${name}: ${what} Its stderr ended: ${shown(tail)}` + : `${name}: ${what}`, + ); +} + +function describeIssue(error: z.ZodError): string { + const first = error.issues[0]; + const path = first?.path.join(".") ?? ""; + return shown(`${path ? `${path}: ` : ""}${first?.message ?? "invalid"}`); +} + +function parseJson(text: string): unknown { + try { + return JSON.parse(text); + } catch { + return undefined; + } +} + +function isObject(value: unknown): value is Record { + return typeof value === "object" && value !== null && !Array.isArray(value); +} + +/** + * Runs `argv` (the configured command line, unchanged) with a `fetch` request + * for `reference` on its stdin (D2) and returns the validated answer. + * + * Throws `InvalidValueError` (exit 2) for the provider's `invalid_reference`, + * and a plain `Error` (exit 1) for everything else: `not_found`, `failed`, a + * non-zero exit, a program that cannot be run, a timeout, and an answer that + * breaks the contract. Every message starts with the provider's name. + */ +export async function fetchCustomIssue( + argv: string[], + reference: string, + { name, cwd, timeoutMs = PROVIDER_TIMEOUT_MS }: FetchCustomIssueOptions, +): Promise { + const [file, ...args] = argv; + if (file === undefined) { + throw new Error(`${name}: issueProvider.command is empty.`); + } + + const request = JSON.stringify({ + version: PROTOCOL_VERSION, + operation: "fetch", + reference, + }); + + let result: Awaited>; + try { + result = await runCapturing(file, args, { + cwd, + timeout: timeoutMs, + input: request, + maxBuffer: MAX_STDOUT_BYTES, + }); + } catch (error) { + throw describeRunFailure(name, error, timeoutMs); + } + + const document = parseJson(result.stdout); + + // The provider's own error report is honoured whatever it exited with. + if (isObject(document) && "error" in document) { + const parsed = errorAnswer.safeParse(document); + if (parsed.success) { + const { code, message } = parsed.data.error; + const text = `${name}: ${shown(message)}`; + throw code === "invalid_reference" + ? new InvalidValueError(text) + : new Error(text); + } + } + + // A non-zero exit is a failure even beside a well-formed answer: the exit is + // the provider's own statement that it did not succeed. + if (result.exitCode !== 0) { + throw failure( + name, + `issueProvider.command exited with code ${result.exitCode}.`, + result.stderr, + ); + } + + if (document === undefined) { + throw failure( + name, + "the issue provider did not print valid JSON.", + result.stderr, + ); + } + if (!isObject(document) || document.version !== PROTOCOL_VERSION) { + throw failure( + name, + `the issue provider's answer has a missing or unsupported "version" (this worktree speaks version ${PROTOCOL_VERSION}).`, + result.stderr, + ); + } + + const parsed = fetchAnswer.safeParse(document); + if (!parsed.success) { + throw failure( + name, + `the issue provider's answer is not valid (${describeIssue(parsed.error)}).`, + result.stderr, + ); + } + return parsed.data.issue; +} + +/** `runCapturing` rejects when no exit code exists: overrun, kill, or no program. */ +function describeRunFailure( + name: string, + error: unknown, + timeoutMs: number, +): Error { + const { code, killed } = error as { code?: unknown; killed?: unknown }; + if (code === "ERR_CHILD_PROCESS_STDIO_MAXBUFFER") { + return new Error( + `${name}: the issue provider printed more than ${MAX_STDOUT_BYTES / 1024 / 1024} MiB.`, + ); + } + if (killed === true) { + return new Error( + `${name}: the issue provider did not answer within ${Math.round(timeoutMs / 1000)}s.`, + ); + } + const reason = error instanceof Error ? error.message : String(error); + return new Error( + `${name}: issueProvider.command could not be run (${shown(reason)}).`, + ); +} diff --git a/src/lib/cli.test.ts b/src/lib/cli.test.ts index 1d68a30f..884fc54f 100644 --- a/src/lib/cli.test.ts +++ b/src/lib/cli.test.ts @@ -238,6 +238,23 @@ describe("runCapturing", () => { ).rejects.toMatchObject({ killed: true, signal: "SIGTERM" }); }); + // A wrapper script's `trap 'cleanup; exit 1' TERM` ends the child with a + // number, not a signal; the timeout still ended it, so it is a rejection. + it.each([ + 1, 0, + ])("rejects a child that exits %i from its SIGTERM handler, still a timeout", async (code) => { + await expect( + runCapturing( + node, + [ + "-e", + `process.on("SIGTERM", () => process.exit(${code})); ${sleepForever}`, + ], + { timeout: 1_000 }, + ), + ).rejects.toMatchObject({ killed: true, code: null }); + }); + it("leaves a child that answers within the timeout alone", async () => { const result = await runCapturing( node, @@ -259,6 +276,74 @@ describe("runCapturing", () => { expect(result).toEqual({ stdout: "slow", stderr: "", exitCode: 0 }); }); + + // A request document for a provider command: it goes to stdin, not argv, so + // a value starting with `-` is never read as an option by the child. + it("writes input to the child's stdin and closes it, so a reader of all of stdin finishes", async () => { + const result = await runCapturing( + node, + [ + "-e", + "let d='';process.stdin.on('data',c=>d+=c).on('end',()=>process.stdout.write('got:'+d))", + ], + { input: '{"reference":"-rf"}' }, + ); + + expect(result).toEqual({ + stdout: 'got:{"reference":"-rf"}', + stderr: "", + exitCode: 0, + }); + }); + + it("delivers input byte for byte, multi-byte characters included", async () => { + const input = "naïve ☃ \u{1F600}\n"; + + const result = await runCapturing( + node, + [ + "-e", + "const c=[];process.stdin.on('data',b=>c.push(b)).on('end',()=>process.stdout.write(Buffer.concat(c)))", + ], + { input, trim: false }, + ); + + expect(result.stdout).toBe(input); + }); + + it("does not fail when the child exits without reading its input", async () => { + // 4 MiB cannot sit in the pipe's buffer, so the write meets a closed pipe + // (EPIPE). That is the child's choice, not this call's failure. + const result = await runCapturing( + node, + ["-e", "process.stdout.write('ignored')"], + { input: "x".repeat(4 * 1024 * 1024) }, + ); + + expect(result).toEqual({ stdout: "ignored", stderr: "", exitCode: 0 }); + }); + + it("rejects, killing the child, once stdout exceeds maxBuffer", async () => { + // 200 bytes against a 100-byte cap: Node's documented maxBuffer behaviour + // (child_process.html) is to terminate the child and report the overrun. + await expect( + runCapturing( + node, + ["-e", `process.stdout.write("a".repeat(200)); ${sleepForever}`], + { maxBuffer: 100 }, + ), + ).rejects.toMatchObject({ code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }); + }); + + it("resolves output that fits within maxBuffer", async () => { + const result = await runCapturing( + node, + ["-e", `process.stdout.write("a".repeat(100))`], + { maxBuffer: 100 }, + ); + + expect(result.stdout).toBe("a".repeat(100)); + }); }); describe("runStreaming", () => { diff --git a/src/lib/cli.ts b/src/lib/cli.ts index 7407b748..0a3e4e26 100644 --- a/src/lib/cli.ts +++ b/src/lib/cli.ts @@ -43,6 +43,22 @@ interface RunOptions extends ExecOptions { trim?: boolean; } +interface CapturingOptions { + /** + * Written to the child's stdin, which is then closed, so a child that reads + * until end-of-input finishes. A request goes here rather than into argv so a + * value starting with `-` is never read as an option by the child's own + * argument parser. Unset, stdin is left as execFile has it. + */ + input?: string; + /** + * Bytes of stdout or stderr after which the child is terminated and the call + * rejects with `code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER"`. Left unset, Node's + * own default (1 MiB) applies. + */ + maxBuffer?: number; +} + interface SpawnDetachedOptions { cwd?: string; onError?: (error: Error) => void; @@ -128,13 +144,15 @@ export function runCapturing( timeout, env, trim = true, - }: ExecOptions & Pick = {}, + input, + maxBuffer, + }: ExecOptions & Pick & CapturingOptions = {}, ): Promise { return new Promise((resolve, reject) => { const child = execFile( file, args, - { cwd, timeout, env: mergeEnv(env) }, + { cwd, timeout, env: mergeEnv(env), maxBuffer }, (error, stdout, stderr) => { disarm(); const output = { @@ -142,6 +160,25 @@ export function runCapturing( stderr: stderr.trim(), }; + // A child that handles SIGTERM by exiting reports a number (or none at + // all, for exit 0), but it was stopped by the timeout and so did not + // finish: reject, as the doc above says, whatever it exited with. + // A signal or maxBuffer error (a string or null `code`) is already + // specific and falls through to the rejection below, unchanged. + if ( + child.killed && + timeout && + (!error || typeof error.code === "number") + ) { + reject( + Object.assign( + new Error(`${file} was killed after ${timeout}ms`), + error ?? {}, + { killed: true, code: null }, + ), + ); + return; + } if (!error) { resolve({ ...output, exitCode: 0 }); return; @@ -154,6 +191,13 @@ export function runCapturing( }, ); const disarm = killAfterGrace(child, timeout); + if (input !== undefined) { + // A child may exit without reading all of its input; the write then fails + // with EPIPE, which is the child's choice and not this call's failure — + // its exit decides the outcome. Without a listener the error is thrown. + child.stdin?.on("error", () => {}); + child.stdin?.end(input); + } }); } From e3d4900869c7d9cb53634a3f8937300e7d2b700a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Baldur=20P=C3=A1ll=20H=C3=B3lmgeirsson?= Date: Tue, 24 Nov 2026 11:29:02 +0000 Subject: [PATCH 02/15] feat(config): issueProvider.name and issueProvider.command team keys (#357) Phase 2 of #357: issueProvider.name and issueProvider.command as team keys (git config, .worktree.yml, user file), the issueProvider section with branchType in the project schema, resolveIssueProvider() taking the pair from the layer that sets the command, config --list / --project / summary support, the regenerated docs/public/schema/v1.json, and the docs for the keys. Gate 1: all verify.md sections exit 0 (pnpm test 3961, docs:test 1655). Gate 2: reviewer subagent PASS WITH NOTES after one loopback. --- README.md | 4 +- context/notes.md | 16 + docs/public/schema/v1.json | 93 +++++ docs/src/content/docs/commands/config.mdx | 4 +- docs/src/content/docs/configuration.mdx | 4 +- .../content/docs/project-configuration.mdx | 12 +- skills/worktree/SKILL.md | 6 +- src/commands/config.test.ts | 95 +++++ src/lib/config-keys.ts | 1 + src/lib/constants.ts | 6 + src/lib/project-config.test.ts | 335 ++++++++++++++++++ src/lib/project-config.ts | 95 ++++- src/lib/user-config.test.ts | 36 ++ src/lib/user-config.ts | 8 + src/lib/validators.test.ts | 44 +++ src/lib/validators.ts | 15 + 16 files changed, 764 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 5d6ef6cc..b13092a1 100644 --- a/README.md +++ b/README.md @@ -96,7 +96,7 @@ The setup flow can configure: - `linear.agentToken`, `linear.webhookSecret`, `linear.agentAllow` and `linear.agentContext` for a Linear agent that starts worktrees: the app's OAuth token and the webhook signing secret (both secret, shown as `***` by `worktree config --list`), the Linear user ids allowed to delegate an issue to it, and `true` to also hand the issue's text to the agent (off by default). `worktree linear-listen` reads them; the wizard never asks for any of them, and a `.worktree.yml` cannot set them A repository can also commit a `.worktree.yml` that supplies the team's `defaultSourceBranch`, `branchPrefix.*`, -`jira.host`, `jira.deployment`, `clickup.workspaceId`, `github.repository` and `github.host`, read from the default branch; your own git config overrides it. The +`jira.host`, `jira.deployment`, `clickup.workspaceId`, `github.repository`, `github.host`, `issueProvider.name` and `issueProvider.command`, read from the default branch; your own git config overrides it. The wizard skips what the file answers, `worktree config --list` marks each value `(.worktree.yml)` or `(overrides .worktree.yml: )`, and `worktree config --project` writes a `.worktree.yml` from the team keys in your git config (never a personal or secret one), uncommitted. See @@ -273,7 +273,7 @@ worktree help branch Configuration is stored in Git config under the `northguild.worktree.*` namespace. A committed `.worktree.yml` can supply the team keys (`defaultSourceBranch`, `branchPrefix.*`, `jira.host`, `jira.deployment`, -`clickup.workspaceId`, `github.repository`, `github.host`); your git config wins over it, and it wins over your user config file and the built-in default. A file's +`clickup.workspaceId`, `github.repository`, `github.host`, `issueProvider.name`, `issueProvider.command`); your git config wins over it, and it wins over your user config file and the built-in default. A file's `jira.host` receives every teammate's Jira credentials, so review a change to it like code. See [Project Configuration](https://northguild.dev/worktree/project-configuration/). diff --git a/context/notes.md b/context/notes.md index db65c82f..3518c986 100644 --- a/context/notes.md +++ b/context/notes.md @@ -18,3 +18,19 @@ Non-blocking observations from the gates. Branch-local; `/feature-close` deletes - **For Phase 4's printers:** the title may hold control characters (D6 allows it) and must be escaped wherever printed; a `url` with `user:token@` passes the http(s) check and would reach `--json`; `not_found` gives `--json` code `failed`, which `branch.mdx`'s table should say. + +## Phase 2 + +- **`config --list` and `config ` treat `issueProvider.name` per key, not as a pair** + (`src/commands/config.ts:287`, `:330`): a git-config name beside the file's command lists as overriding the + file, though the resolver ignores it; a file name beside a git-config command lists as set but resolves to + `null`. Contradicts `project-configuration.mdx`'s pair sentence. Branch-local and user-visible; fix by + Phase 4 at the latest. +- **`commands/config.mdx` has no key entries for `issueProvider.name`/`.command`** (every other key has one); + §7 assigned no row for it. +- **Docs say the command's "head must be a program that exists"** — true for `worktree config`, not for a + command in `.worktree.yml`, which only the `step` rule checks. +- **§5's process-list risk** is only implied by "a token never goes in this section"; Phase 6's guide should say it. +- **Smaller:** the git-config path's name lookup still reads (and can throw on) lower layers; an invalid + git-config name is dropped silently (documented); the test at `project-config.test.ts:2461` does not assert + `token` is absent; the name's error text is written three times. diff --git a/docs/public/schema/v1.json b/docs/public/schema/v1.json index 22b1ac89..33af3d59 100644 --- a/docs/public/schema/v1.json +++ b/docs/public/schema/v1.json @@ -291,6 +291,99 @@ } } }, + "issueProvider": { + "type": "object", + "properties": { + "branchType": { + "type": "array", + "items": { + "anyOf": [ + { + "type": "object", + "properties": { + "when": { + "type": "object", + "propertyNames": { + "type": "string" + }, + "additionalProperties": { + "anyOf": [ + { + "anyOf": [ + { + "type": ["string", "number"] + }, + { + "type": "object", + "properties": { + "id": { + "type": ["string", "number"] + } + }, + "required": ["id"], + "additionalProperties": false + } + ] + }, + { + "minItems": 1, + "type": "array", + "items": { + "anyOf": [ + { + "type": ["string", "number"] + }, + { + "type": "object", + "properties": { + "id": { + "type": ["string", "number"] + } + }, + "required": ["id"], + "additionalProperties": false + } + ] + } + } + ] + }, + "description": "Field name or id mapped to the value, id object or list of either that must match. Every field must match." + }, + "type": { + "type": "string", + "enum": ["feature", "bugfix", "chore"] + } + }, + "required": ["when", "type"], + "additionalProperties": false + }, + { + "type": "object", + "properties": { + "otherwise": { + "type": "string", + "enum": ["feature", "bugfix", "chore"] + } + }, + "required": ["otherwise"], + "additionalProperties": false + } + ] + }, + "description": "Ordered rules; the first match wins. `- otherwise: ` sets the kind for an issue no rule matched." + }, + "name": { + "type": "string", + "pattern": "^[a-z][a-z0-9-]{0,31}$", + "description": "A short name for the provider, shown in messages and reported by --json. Optional." + }, + "command": { + "type": "string", + "description": "The command line that runs the provider, split into arguments, never through a shell." + } + } + }, "clickup": { "type": "object", "properties": { diff --git a/docs/src/content/docs/commands/config.mdx b/docs/src/content/docs/commands/config.mdx index c86aea05..62ae7a1e 100644 --- a/docs/src/content/docs/commands/config.mdx +++ b/docs/src/content/docs/commands/config.mdx @@ -99,7 +99,7 @@ When the repository's `.worktree.yml` sets a team key, `worktree config` knows. [user config file](#user-config-file) are marked the same way with `(user config)` and `(overrides user config: )`; where `.worktree.yml` sets the key too, only it is named, since it outranks the user file. Keys only the file can set follow, one line - each: `jira.branchType: 4 rules`, `branchType: 2 rules` (the shared list), `branchName=