ticket-runner 0.6.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.
Files changed (55) hide show
  1. package/LICENSE +21 -0
  2. package/README.ko.md +97 -0
  3. package/README.md +98 -0
  4. package/bin/ticket-runner.js +6 -0
  5. package/docs/templates/operator-skill.md +87 -0
  6. package/package.json +42 -0
  7. package/src/acceptance-criteria.ts +44 -0
  8. package/src/adapters/claude-agent-runner.ts +389 -0
  9. package/src/adapters/exec.ts +169 -0
  10. package/src/adapters/gh-tracker.ts +955 -0
  11. package/src/adapters/git-workspace.ts +951 -0
  12. package/src/adapters/repo-root.ts +20 -0
  13. package/src/adapters/version.ts +118 -0
  14. package/src/base-branch.ts +21 -0
  15. package/src/branch.ts +33 -0
  16. package/src/cli.ts +135 -0
  17. package/src/command-line.ts +190 -0
  18. package/src/config.ts +277 -0
  19. package/src/conventions.ts +118 -0
  20. package/src/criteria.ts +106 -0
  21. package/src/frontier.ts +36 -0
  22. package/src/guards.ts +143 -0
  23. package/src/handoff.ts +82 -0
  24. package/src/host.ts +116 -0
  25. package/src/init.ts +405 -0
  26. package/src/labels.ts +42 -0
  27. package/src/landing.ts +75 -0
  28. package/src/lifecycle.ts +34 -0
  29. package/src/lock.ts +215 -0
  30. package/src/note-schema.ts +58 -0
  31. package/src/notes.ts +433 -0
  32. package/src/operator-skill.ts +24 -0
  33. package/src/orchestrator.ts +1816 -0
  34. package/src/ports/agent-runner.ts +105 -0
  35. package/src/ports/tracker.ts +334 -0
  36. package/src/ports/workspace.ts +422 -0
  37. package/src/progress.ts +231 -0
  38. package/src/prompts.ts +288 -0
  39. package/src/readiness.ts +256 -0
  40. package/src/remove.ts +732 -0
  41. package/src/resume.ts +145 -0
  42. package/src/run-log.ts +85 -0
  43. package/src/run.ts +331 -0
  44. package/src/self-hosting.ts +33 -0
  45. package/src/stage-guard.ts +32 -0
  46. package/src/staleness.ts +101 -0
  47. package/src/start.ts +284 -0
  48. package/src/startup.ts +34 -0
  49. package/src/stop.ts +178 -0
  50. package/src/stranded.ts +136 -0
  51. package/src/templates.ts +596 -0
  52. package/src/title.ts +97 -0
  53. package/src/verdict.ts +88 -0
  54. package/src/version-number.ts +67 -0
  55. package/src/version-pr.ts +103 -0
package/src/config.ts ADDED
@@ -0,0 +1,277 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { z } from "zod";
4
+ import {
5
+ EFFORT_LEVELS,
6
+ type Effort,
7
+ PERMISSION_MODES,
8
+ type PermissionMode,
9
+ } from "./ports/agent-runner.js";
10
+
11
+ export const CONFIG_FILENAME = "ticket-runner.json";
12
+
13
+ /** The default model for every Stage: Opus 5.5, what a bare `claude -p` picks. */
14
+ const DEFAULT_MODEL = "claude-opus-5-5";
15
+
16
+ /**
17
+ * The default effort for every Stage: `high`, the level Opus 5 ran at before
18
+ * Opus 5.5 lowered its own default to `medium`. One number for all four Stages
19
+ * — tuning a Stage against its Ticket is the Target's job, not the pipeline's.
20
+ */
21
+ const DEFAULT_EFFORT: Effort = "high";
22
+
23
+ /** Thrown when the config file exists but cannot be used. */
24
+ export class ConfigError extends Error {}
25
+
26
+ const stageSchema = z
27
+ .object({
28
+ model: z.string().min(1).optional(),
29
+ effort: z.enum(EFFORT_LEVELS).optional(),
30
+ maxTurns: z.number().int().positive().optional(),
31
+ maxMinutes: z.number().positive().optional(),
32
+ extraPrompt: z.string().optional(),
33
+ })
34
+ .strict();
35
+
36
+ const configSchema = z
37
+ .object({
38
+ baseBranch: z.string().min(1).optional(),
39
+ lanes: z.number().int().positive().optional(),
40
+ checks: z.array(z.string().min(1)).optional(),
41
+ gates: z
42
+ .object({ checks: z.boolean().optional(), ci: z.boolean().optional() })
43
+ .strict()
44
+ .optional(),
45
+ stages: z
46
+ .object({
47
+ implement: stageSchema.optional(),
48
+ verify: stageSchema.optional(),
49
+ fix: stageSchema.optional(),
50
+ conflict: stageSchema.optional(),
51
+ })
52
+ .strict()
53
+ .optional(),
54
+ permissionMode: z.enum(PERMISSION_MODES).optional(),
55
+ ciTimeoutMinutes: z.number().positive().optional(),
56
+ ciGraceMinutes: z.number().positive().optional(),
57
+ checkTimeoutMinutes: z.number().positive().optional(),
58
+ labels: z
59
+ .object({
60
+ needsTriage: z.string().min(1).optional(),
61
+ needsInfo: z.string().min(1).optional(),
62
+ readyForAgent: z.string().min(1).optional(),
63
+ readyForHuman: z.string().min(1).optional(),
64
+ wontfix: z.string().min(1).optional(),
65
+ inProgress: z.string().min(1).optional(),
66
+ })
67
+ .strict()
68
+ .optional(),
69
+ })
70
+ .strict();
71
+
72
+ export interface StageConfig {
73
+ model: string;
74
+ effort: Effort;
75
+ maxTurns: number;
76
+ maxMinutes: number;
77
+ extraPrompt: string;
78
+ }
79
+
80
+ export interface Labels {
81
+ needsTriage: string;
82
+ needsInfo: string;
83
+ readyForAgent: string;
84
+ readyForHuman: string;
85
+ wontfix: string;
86
+ inProgress: string;
87
+ }
88
+
89
+ export interface Config {
90
+ /**
91
+ * The branch a Run branches from, rebases onto, merges into and pulls, where
92
+ * the config names one. Absent means the Target's default branch on GitHub,
93
+ * which is what {@link import("./base-branch.js").resolveBaseBranch} asks for.
94
+ */
95
+ baseBranch?: string;
96
+ /**
97
+ * How many Tickets a Run may hold at once, one Lane per Ticket. The Checks of
98
+ * different Lanes run in different worktrees at the same time, so a Target
99
+ * whose Checks share a port or a database stays at the default of one.
100
+ */
101
+ lanes: number;
102
+ checks: string[];
103
+ gates: { checks: boolean; ci: boolean };
104
+ stages: {
105
+ implement: StageConfig;
106
+ verify: StageConfig;
107
+ fix: StageConfig;
108
+ conflict: StageConfig;
109
+ };
110
+ permissionMode: PermissionMode;
111
+ ciTimeoutMinutes: number;
112
+ /**
113
+ * How long a pull request GitHub has registered no check run for still counts
114
+ * as pending. A Target whose Actions queue slowly raises it; a Target with no
115
+ * CI workflow pays it once per Landing, so it is not the CI timeout.
116
+ */
117
+ ciGraceMinutes: number;
118
+ /**
119
+ * How long any one Check command may run before it is killed. One number for
120
+ * the whole pipeline, and every command gets the whole of it.
121
+ */
122
+ checkTimeoutMinutes: number;
123
+ labels: Labels;
124
+ }
125
+
126
+ const STAGE_DEFAULTS = {
127
+ implement: { maxTurns: 300, maxMinutes: 60 },
128
+ verify: { maxTurns: 80, maxMinutes: 20 },
129
+ fix: { maxTurns: 150, maxMinutes: 40 },
130
+ // Resolving one rebase is narrower work than mending a defect, and the skill
131
+ // has the Checks to run before it finishes.
132
+ conflict: { maxTurns: 120, maxMinutes: 30 },
133
+ } as const;
134
+
135
+ /**
136
+ * The wall-clock limit a Check runs under when the config names none. Longer
137
+ * than any suite a Ticket-sized change should have, so reaching it means the
138
+ * command hung rather than that it was slow.
139
+ */
140
+ const DEFAULT_CHECK_TIMEOUT_MINUTES = 15;
141
+
142
+ /**
143
+ * How long "no checks yet" is given when the config names nothing. GitHub has
144
+ * taken over three minutes to register a check run (#119), and the Landing is
145
+ * serialized, so this is long enough to cover that and short enough that a
146
+ * Target with no CI workflow does not hold the other Lanes up for a CI timeout.
147
+ *
148
+ * Exported because the tracker falls back to it too, for a caller that hands it
149
+ * no grace: one number, so the documented default cannot drift from the real one.
150
+ */
151
+ export const DEFAULT_CI_GRACE_MINUTES = 5;
152
+
153
+ /**
154
+ * The Lane count a Target that says nothing gets: one, which is a Run that takes
155
+ * its Tickets one after another. Sharing a machine is opt-in, because only the
156
+ * Target knows whether its Checks can.
157
+ */
158
+ const DEFAULT_LANES = 1;
159
+
160
+ const LABEL_DEFAULTS: Labels = {
161
+ needsTriage: "needs-triage",
162
+ needsInfo: "needs-info",
163
+ readyForAgent: "ready-for-agent",
164
+ readyForHuman: "ready-for-human",
165
+ wontfix: "wontfix",
166
+ inProgress: "in-progress",
167
+ };
168
+
169
+ /**
170
+ * Read the config file, fill in every default, and infer the Check commands
171
+ * from package.json when the config does not name them.
172
+ *
173
+ * Throws {@link ConfigError} naming the offending field when the file is
174
+ * unusable; a missing file is not an error. `version` is the Version doing the
175
+ * refusing, which the message for an unknown key carries.
176
+ */
177
+ export function loadConfig(repoRoot: string, version: string): Config {
178
+ const raw = readJson(join(repoRoot, CONFIG_FILENAME));
179
+ const parsed = configSchema.safeParse(raw ?? {});
180
+ if (!parsed.success) {
181
+ throw new ConfigError(refusal(parsed.error, version));
182
+ }
183
+
184
+ const file = parsed.data;
185
+ return {
186
+ // Spread, not `baseBranch: file.baseBranch`: the field is absent rather
187
+ // than undefined when the config file names none.
188
+ ...(file.baseBranch === undefined ? {} : { baseBranch: file.baseBranch }),
189
+ lanes: file.lanes ?? DEFAULT_LANES,
190
+ checks: file.checks ?? inferChecks(repoRoot),
191
+ gates: {
192
+ checks: file.gates?.checks ?? true,
193
+ ci: file.gates?.ci ?? true,
194
+ },
195
+ stages: {
196
+ implement: stage(STAGE_DEFAULTS.implement, file.stages?.implement),
197
+ verify: stage(STAGE_DEFAULTS.verify, file.stages?.verify),
198
+ fix: stage(STAGE_DEFAULTS.fix, file.stages?.fix),
199
+ conflict: stage(STAGE_DEFAULTS.conflict, file.stages?.conflict),
200
+ },
201
+ permissionMode: file.permissionMode ?? "auto",
202
+ ciTimeoutMinutes: file.ciTimeoutMinutes ?? 30,
203
+ ciGraceMinutes: file.ciGraceMinutes ?? DEFAULT_CI_GRACE_MINUTES,
204
+ checkTimeoutMinutes: file.checkTimeoutMinutes ?? DEFAULT_CHECK_TIMEOUT_MINUTES,
205
+ labels: labels(file.labels),
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Why the file was refused, and — for an unknown key — which Version refused it.
211
+ *
212
+ * The schema is strict, so a key this install has never heard of is refused by
213
+ * name. That is the right answer to a typo and a confusing one to a key a newer
214
+ * Version added, and on a machine running a stale install the two look exactly
215
+ * the same. So the Version is said out loud, and the config file itself is left
216
+ * without one to carry (ADR-0007).
217
+ */
218
+ function refusal(error: z.ZodError, version: string): string {
219
+ const detail = error.issues
220
+ .map((issue) => `${issue.path.join(".") || "(root)"}: ${issue.message}`)
221
+ .join("; ");
222
+ const said = `Invalid ${CONFIG_FILENAME}: ${detail}`;
223
+ if (!error.issues.some((issue) => issue.code === "unrecognized_keys")) return said;
224
+ return `${said}. Refused by ticket-runner ${version}, so the key may be newer than this install.`;
225
+ }
226
+
227
+ /** Config label overrides win, but only where the file actually names one. */
228
+ function labels(
229
+ configured: { [K in keyof Labels]?: string | undefined } | undefined,
230
+ ): Labels {
231
+ const merged = { ...LABEL_DEFAULTS };
232
+ for (const key of Object.keys(LABEL_DEFAULTS) as (keyof Labels)[]) {
233
+ const override = configured?.[key];
234
+ if (override !== undefined) merged[key] = override;
235
+ }
236
+ return merged;
237
+ }
238
+
239
+ function stage(
240
+ defaults: { maxTurns: number; maxMinutes: number },
241
+ configured: z.infer<typeof stageSchema> | undefined,
242
+ ): StageConfig {
243
+ return {
244
+ model: configured?.model ?? DEFAULT_MODEL,
245
+ effort: configured?.effort ?? DEFAULT_EFFORT,
246
+ maxTurns: configured?.maxTurns ?? defaults.maxTurns,
247
+ maxMinutes: configured?.maxMinutes ?? defaults.maxMinutes,
248
+ extraPrompt: configured?.extraPrompt ?? "",
249
+ };
250
+ }
251
+
252
+ /** `npm test` and `npm run typecheck`, whichever package.json actually defines. */
253
+ function inferChecks(repoRoot: string): string[] {
254
+ const pkg = readJson(join(repoRoot, "package.json"));
255
+ const scripts =
256
+ pkg && typeof pkg === "object" && "scripts" in pkg ? pkg.scripts : undefined;
257
+ if (!scripts || typeof scripts !== "object") return [];
258
+
259
+ const checks: string[] = [];
260
+ if ("test" in scripts) checks.push("npm test");
261
+ if ("typecheck" in scripts) checks.push("npm run typecheck");
262
+ return checks;
263
+ }
264
+
265
+ function readJson(path: string): Record<string, unknown> | undefined {
266
+ let contents: string;
267
+ try {
268
+ contents = readFileSync(path, "utf8");
269
+ } catch {
270
+ return undefined;
271
+ }
272
+ try {
273
+ return JSON.parse(contents) as Record<string, unknown>;
274
+ } catch (error) {
275
+ throw new ConfigError(`Invalid JSON in ${path}: ${(error as Error).message}`);
276
+ }
277
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * The conventions document a Target must carry, and the pointer to it that
3
+ * every agent session in that Target reads first.
4
+ *
5
+ * This module is the source of the text; the copy in a Target is output.
6
+ * `ticket-runner init` writes it when it is missing and rewrites it when it says
7
+ * something else, so a requirement changed here reaches every Target on its
8
+ * next `init` rather than being merged into whatever the Target had.
9
+ *
10
+ * It states what the pipeline requires and nothing more: the type and scope
11
+ * vocabulary, the review rules, the test policy are the Target's business, and a
12
+ * document that took them over would be rewritten out from under it.
13
+ *
14
+ * The one thing it says about Versions is the mark it bears: which pipeline
15
+ * wrote the copy a Target carries, hidden on the first line so no reader of the
16
+ * document meets it. That is a direction comparing text never gives — `init`
17
+ * leaves a document a newer pipeline wrote alone, and a Run behind one warns
18
+ * and names the upgrade rather than rewriting anything (ADR-0007).
19
+ */
20
+
21
+ import { versionNumber } from "./version-number.js";
22
+
23
+ /** Where the document goes in a Target, relative to the Target's root. */
24
+ export const CONVENTIONS_PATH = "docs/agents/pipeline-conventions.md";
25
+
26
+ /**
27
+ * The section `init` adds to the Target's `CLAUDE.md`.
28
+ *
29
+ * Added only when the file names {@link CONVENTIONS_PATH} nowhere: a human who
30
+ * reworded the section still owns a pointer, and a second one would only be
31
+ * noise. Appended as a top-level section, so it reads the same in a `CLAUDE.md`
32
+ * this wrote and in one that already had a shape of its own.
33
+ */
34
+ export const CLAUDE_SECTION = `## Pipeline conventions
35
+
36
+ \`ticket-runner\` runs unattended sessions in this repository. What it requires of a commit, a branch, a Stage and a Ticket: \`docs/agents/pipeline-conventions.md\`. Read it before committing, opening a pull request or creating an issue.
37
+ `;
38
+
39
+ /**
40
+ * The marker carrying the Version, as the first line of the document ends.
41
+ *
42
+ * An HTML comment, like every other marker the pipeline finds its own writing
43
+ * by, so it is on the line a reader sees and in none of the text they read.
44
+ */
45
+ const MARKER = /<!-- ticket-runner:version ([^\s>]+) -->/;
46
+
47
+ /**
48
+ * The document itself, as {@link CONVENTIONS_PATH} must contain it, marked with
49
+ * the Version writing it.
50
+ *
51
+ * The number alone, never the commit a development checkout adds: two checkouts
52
+ * of one Version write one document, and a Target whose copy was rewritten by
53
+ * every commit would say nothing by having been.
54
+ *
55
+ * A copy with no number to stamp carries no marker rather than a marker saying
56
+ * so. A mark nothing can read is a mark that is not there, and writing one
57
+ * would leave `init` rewriting the same document every time it ran.
58
+ */
59
+ export function conventionsDoc(version: string): string {
60
+ const number = versionNumber(version);
61
+ const marker = number === undefined ? "" : ` <!-- ticket-runner:version ${number} -->`;
62
+ return `# ticket-runner conventions${marker}\n${BODY}`;
63
+ }
64
+
65
+ /**
66
+ * The Version number a Target's copy was written by, and undefined for a copy
67
+ * carrying no mark at all — every copy an older pipeline wrote, which is read
68
+ * as being behind rather than as being wrong.
69
+ */
70
+ export function conventionsMark(document: string | undefined): string | undefined {
71
+ const [first = ""] = (document ?? "").split("\n");
72
+ const marked = MARKER.exec(first)?.[1];
73
+ return marked === undefined ? undefined : versionNumber(marked);
74
+ }
75
+
76
+ /** Everything under the marked first line, which no Version changes. */
77
+ const BODY = `
78
+ What \`ticket-runner\` requires of this repository, and nothing else. \`ticket-runner init\` writes this file and rewrites it whenever those requirements change, so an edit made here does not survive the next \`init\`. Everything the pipeline leaves to this repository — which commit types and scopes it uses, how it reviews, what it tests — belongs in the repository's own contributing guide.
79
+
80
+ ## Commits
81
+
82
+ - Subject: \`<type>(<scope>): <summary> (#<n>)\`, where \`<n>\` is the Ticket number. Every commit carries the number, so no commit has to be traced back to the work it was part of.
83
+ - The type and scope vocabulary is this repository's own. The pipeline reads the shape and the number, never the words.
84
+ - A commit subject describes its own commit. The whole branch is summarised by the \`title\` the implement and fix Stages each answer beside their Notes: one line in the same shape without the \`(#<n>)\`. The latest one becomes the pull request title, and the pull request title becomes the subject of the squash commit that lands.
85
+
86
+ ## Branches
87
+
88
+ - \`agent/<n>-<slug>\` belongs to the pipeline. A Run creates one per Ticket, works in a worktree of it, and pushes it after every Stage that commits. The repository deletes it when the pull request merges, a setting \`ticket-runner init\` switches on. Nothing else branches there.
89
+ - \`ticket-runner/lock\` and \`ticket-runner/state\` belong to the pipeline too. The first says which Run holds this repository, and the second keeps the State of every Ticket a Run can resume, and the transcripts of a handed-off Ticket's Stages. Nothing else commits to either, except a human, or an Operator a human asked, releasing a lock a vanished Host left behind.
90
+ - A Stage commits only to the branch already checked out in the worktree it was started in. It creates no branch and switches to none.
91
+
92
+ ## What a Stage does not do
93
+
94
+ - A Stage opens no pull request and closes no issue. The pipeline opens the pull request when the Stage finishes, waits for CI, merges it, and lets the merge close the Ticket.
95
+
96
+ ## What a Ticket needs
97
+
98
+ A Ticket is one issue the pipeline can implement in a single session. It is refused unless it carries all three:
99
+
100
+ - **Acceptance Criteria** — unticked task list items, a \`- [ ]\` at the head of a line, in the issue body or in one of its comments. They are the only thing the verify Stage grades, so a promise written as prose is not one.
101
+ - **Blockers as native dependencies** — GitHub's own \`blocked by\` edges, as \`gh issue create --blocked-by <n>\` records them. A \`Blocked by\` section in the body is a human-readable copy and nothing the pipeline reads.
102
+ - **The \`ready-for-agent\` label** — how a Run finds the Ticket. A Run labels it \`in-progress\` for as long as it holds it.
103
+
104
+ ## Checks
105
+
106
+ - The Checks of different Tickets may run at the same time, each in its own worktree, because a Run has as many Lanes as \`lanes\` says. A Target whose Checks need a port, a database or anything else they would have to share keeps \`lanes\` at one, or makes them independent of each other.
107
+
108
+ ## The Operator's skill
109
+
110
+ - \`.claude/skills/ticket-runner/\` belongs to the pipeline. It tells an Operator, the Claude session a human opens on this repository from the Claude app, how to start a Run, report on it and stop it. \`ticket-runner init\` writes it and rewrites it like this file, so an edit made there does not survive the next \`init\` either.
111
+
112
+ ## Local directories
113
+
114
+ Both are \`ticket-runner\`'s own, both are gitignored by \`ticket-runner init\`, and neither is ever committed.
115
+
116
+ - \`.worktrees/ticket-<n>/\` — one git worktree per claimed Ticket, where its Stages run.
117
+ - \`.ticket-runner/\` — the Run's logs and Stage transcripts. The Run lock and the State a Ticket keeps while its branch has work worth resuming are not here but on the Target's remote, so that a Run on any Host sees which Run holds the Target, and carries on from where a killed Run, or a handed-off Ticket relabelled \`ready-for-agent\`, stopped.
118
+ `;
@@ -0,0 +1,106 @@
1
+ /**
2
+ * Ticking the Acceptance Criteria a Verdict proved.
3
+ *
4
+ * A merged Ticket whose checkboxes are all still empty reads as unfinished
5
+ * work, so the criteria verify marked `met` are ticked where they live — the
6
+ * body, or the comment triage posted its brief in. Only `met` ones: an
7
+ * `unverifiable` criterion is one nobody has evidence for, and a tick would
8
+ * claim otherwise.
9
+ *
10
+ * Nothing else in the text is touched. The pipeline is editing a human's
11
+ * writing, so it rewrites three characters of a line it recognises and leaves
12
+ * the line, and the document around it, as it found them.
13
+ */
14
+
15
+ import { TICKED_BOX, UNCHECKED_BOX } from "./acceptance-criteria.js";
16
+ import type { Tracker } from "./ports/tracker.js";
17
+ import type { Verdict } from "./verdict.js";
18
+
19
+ /** {@link UNCHECKED_BOX}, extended to capture the criterion text after the box. */
20
+ const CHECKBOX_LINE = new RegExp(`${UNCHECKED_BOX}( .*)$`, "gm");
21
+
22
+ /** {@link TICKED_BOX}, over every line of a text rather than the first. */
23
+ const TICKED_LINE = new RegExp(TICKED_BOX, "gm");
24
+
25
+ /**
26
+ * The same criterion as the verify Stage reported it.
27
+ *
28
+ * The Stage is asked for the criterion verbatim and mostly obliges, but it
29
+ * reflows and recases often enough that an exact match would leave half a
30
+ * Ticket unticked. Whitespace and case are the differences worth forgiving;
31
+ * anything more and the risk is ticking a box nobody graded.
32
+ */
33
+ function normalise(text: string): string {
34
+ return text.trim().replaceAll(/\s+/g, " ").toLowerCase();
35
+ }
36
+
37
+ /**
38
+ * `text` with every unticked box whose criterion is in `met` ticked.
39
+ *
40
+ * Returns the text unchanged when nothing matched, which is how the caller
41
+ * knows there is nothing to write back.
42
+ */
43
+ export function tickCriteria(text: string, met: string[]): string {
44
+ const wanted = new Set(met.map(normalise));
45
+ if (wanted.size === 0) return text;
46
+
47
+ return text.replaceAll(CHECKBOX_LINE, (line, bullet: string, rest: string) =>
48
+ wanted.has(normalise(rest)) ? `${bullet}[x]${rest}` : line,
49
+ );
50
+ }
51
+
52
+ /**
53
+ * Tick every criterion the Verdict proved, wherever the Ticket writes it.
54
+ *
55
+ * The issue is read again rather than reusing the copy it was claimed with: a
56
+ * whole Run has happened since, and both the body and any comment are written
57
+ * back whole. Triage posts its brief as a comment, and nothing says all the
58
+ * criteria are in one place, so every comment is offered the same edit.
59
+ *
60
+ * A criterion the Stage reworded past {@link normalise} matches nothing and is
61
+ * left as it was, which is said out loud rather than passed over in silence: a
62
+ * merged Ticket with an unticked criterion is otherwise a mystery.
63
+ */
64
+ export async function tickMetCriteria(
65
+ tracker: Tracker,
66
+ ticket: number,
67
+ verdict: Verdict,
68
+ log?: (line: string) => void,
69
+ ): Promise<void> {
70
+ const met = verdict.criteria
71
+ .filter((criterion) => criterion.status === "met")
72
+ .map((criterion) => criterion.text);
73
+ if (met.length === 0) return;
74
+
75
+ const issue = await tracker.getIssue(ticket);
76
+ let ticked = 0;
77
+
78
+ const body = tickCriteria(issue.body, met);
79
+ if (body !== issue.body) {
80
+ await tracker.updateIssueBody(ticket, body);
81
+ ticked += ticks(issue.body, body);
82
+ }
83
+
84
+ for (const comment of issue.comments) {
85
+ const edited = tickCriteria(comment.body, met);
86
+ if (edited === comment.body || comment.id === undefined) continue;
87
+ await tracker.updateComment(comment.id, edited);
88
+ ticked += ticks(comment.body, edited);
89
+ }
90
+
91
+ if (ticked < met.length) {
92
+ log?.(
93
+ `#${ticket} ticked ${ticked} of ${met.length} met criteria; ` +
94
+ "the rest match no checkbox on the Ticket",
95
+ );
96
+ }
97
+ }
98
+
99
+ /** How many boxes an edit ticked, so a criterion that matched nothing shows up. */
100
+ function ticks(before: string, after: string): number {
101
+ return countTicked(after) - countTicked(before);
102
+ }
103
+
104
+ function countTicked(text: string): number {
105
+ return [...text.matchAll(TICKED_LINE)].length;
106
+ }
@@ -0,0 +1,36 @@
1
+ import type { Candidate } from "./ports/tracker.js";
2
+
3
+ /**
4
+ * Splitting the open `ready-for-agent` issues into the ones a Run may pick and
5
+ * the ones an open blocker holds back.
6
+ *
7
+ * Nothing here talks to GitHub: the Frontier is a filter over what the
8
+ * {@link import("./ports/tracker.js").Tracker} already reported, so the
9
+ * selection rules are readable in one place and testable without a tracker.
10
+ */
11
+
12
+ export interface FrontierSelection {
13
+ /** The Frontier: unclaimed candidates whose blockers are all closed. */
14
+ frontier: Candidate[];
15
+ /** Unclaimed candidates an open blocker keeps off the Frontier. */
16
+ blocked: Candidate[];
17
+ }
18
+
19
+ /**
20
+ * Split the candidates into the Frontier and what is held back.
21
+ *
22
+ * Both sides come out in ascending Ticket order, so a Run always takes the
23
+ * oldest Ticket first. A candidate somebody has claimed — this Run or another —
24
+ * lands on neither side: it is not ours to pick and not ours to report.
25
+ */
26
+ export function selectFrontier(candidates: Candidate[]): FrontierSelection {
27
+ const frontier: Candidate[] = [];
28
+ const blocked: Candidate[] = [];
29
+
30
+ for (const candidate of [...candidates].sort((a, b) => a.number - b.number)) {
31
+ if (candidate.assignees.length > 0) continue;
32
+ (candidate.openBlockers === 0 ? frontier : blocked).push(candidate);
33
+ }
34
+
35
+ return { frontier, blocked };
36
+ }
package/src/guards.ts ADDED
@@ -0,0 +1,143 @@
1
+ import { UNCHECKED_BOX } from "./acceptance-criteria.js";
2
+ import type { Issue } from "./ports/tracker.js";
3
+
4
+ /**
5
+ * The guards a candidate passes before a Run claims it.
6
+ *
7
+ * Planning is human work and goes wrong in known ways: a Spec offered as a
8
+ * Ticket, a Ticket with nothing for verify to grade, blockers written into the
9
+ * body that GitHub knows nothing about (ADR-0003). Each of those produces a
10
+ * Ticket the pipeline would take and then fail on, so the cheaper answer is to
11
+ * pass it over and say why.
12
+ *
13
+ * Nothing here talks to GitHub: the guards read the issue the
14
+ * {@link import("./ports/tracker.js").Tracker} already reported, so what counts
15
+ * as a usable Ticket is readable in one place.
16
+ */
17
+
18
+ /** Why a candidate was passed over instead of claimed. */
19
+ export type SkipReason = Refusal | GuardReason;
20
+
21
+ /**
22
+ * A number that is nobody's to take: an issue already claimed or never
23
+ * offered, or a number with no issue behind it at all — nothing GitHub has, or
24
+ * a pull request. A Run's Frontier holds none of them, so they are what a Run
25
+ * narrowed to Tickets a human named reports about the ones it never met.
26
+ */
27
+ export type Refusal = "claimed" | "not-ready" | "no-issue" | "pull-request";
28
+
29
+ /** A Planning defect, which is worth exactly one warning comment. */
30
+ export type GuardReason = "spec" | "no-criteria" | "body-only-blockers";
31
+
32
+ /** Keyed rather than listed, so a new reason cannot be left out of it silently. */
33
+ const GUARD_REASONS: Record<GuardReason, true> = {
34
+ spec: true,
35
+ "no-criteria": true,
36
+ "body-only-blockers": true,
37
+ };
38
+
39
+ /** Whether the skip is something to warn the humans about on the issue. */
40
+ export function isGuardReason(reason: SkipReason): reason is GuardReason {
41
+ return reason in GUARD_REASONS;
42
+ }
43
+
44
+ /**
45
+ * The first reason this issue may not be claimed, or `undefined` to take it.
46
+ *
47
+ * Order matters: an issue nobody offered the pipeline is never commented on,
48
+ * and a Spec is named a Spec rather than whatever else is unlike a Ticket
49
+ * about it.
50
+ */
51
+ export function skipReason(
52
+ issue: Issue,
53
+ readyForAgent: string,
54
+ /**
55
+ * Whether this is a **Stranded Ticket**: one this checkout already holds, left
56
+ * claimed by a Run that never came back (CONTEXT.md). Both refusals read the
57
+ * Claim as somebody else's work, and a stranded Ticket wears it itself — the
58
+ * assignee is this very user and `ready-for-agent` came off when the Claim was
59
+ * made — so it passes them and is resumed rather than refused. The Planning
60
+ * guards below still grade it: they are about the issue, not about who has it.
61
+ *
62
+ * Required rather than defaulted, so no caller can forget to answer it and
63
+ * quietly have a stranded Ticket refused as somebody else's.
64
+ */
65
+ stranded: boolean,
66
+ ): SkipReason | undefined {
67
+ if (!stranded) {
68
+ if (issue.assignees.length > 0) return "claimed";
69
+ if (!issue.labels.includes(readyForAgent)) return "not-ready";
70
+ }
71
+ if (issue.subIssues > 0) return "spec";
72
+ if (!hasCriteria(issue)) return "no-criteria";
73
+ if (bodyOnlyBlockers(issue).length > 0) return "body-only-blockers";
74
+ return undefined;
75
+ }
76
+
77
+ /** {@link UNCHECKED_BOX}, asking only whether one line of a text is a criterion. */
78
+ const CRITERION_LINE = new RegExp(UNCHECKED_BOX, "m");
79
+
80
+ /** Triage posts its brief as a comment, so criteria are not always in the body. */
81
+ function hasCriteria(issue: Issue): boolean {
82
+ return [issue.body, ...issue.comments.map((comment) => comment.body)].some((text) =>
83
+ CRITERION_LINE.test(text),
84
+ );
85
+ }
86
+
87
+ /**
88
+ * The issues the body claims block this one that GitHub does not agree block
89
+ * it. The answer is only ever used to reject the Ticket: an edge the body
90
+ * alone knows about is not an edge (ADR-0003).
91
+ */
92
+ function bodyOnlyBlockers(issue: Issue): number[] {
93
+ return bodyBlockerReferences(issue.body).filter(
94
+ (number) => !issue.blockedBy.includes(number),
95
+ );
96
+ }
97
+
98
+ /** `#12`, but not the `other/repo#12` this repo cannot compare numbers with. */
99
+ const ISSUE_REFERENCE = /(?<![\w/])#(\d+)\b/g;
100
+ const LIST_ITEM = /^\s*[-*+]\s/;
101
+ /** Whatever a heading, a list item or bold text puts in front of the words. */
102
+ const DECORATION = /^[\s>#*_-]+/;
103
+
104
+ /**
105
+ * Every `#<n>` a body's `Blocked by` section names.
106
+ *
107
+ * A body says it one of two ways, and the section ends where that way ends: an
108
+ * inline `Blocked by: #3` is over at the end of its own line, and a `## Blocked
109
+ * by` heading is over at the end of the one list under it. Reading any further
110
+ * would take the Acceptance Criteria — a list of `#<n>`-quoting checkboxes, two
111
+ * blank lines below — for blockers and reject a Ticket Planning got right.
112
+ * Issue references elsewhere in the body are prose: a Parent, a follow-up, a
113
+ * duplicate.
114
+ */
115
+ function bodyBlockerReferences(body: string): number[] {
116
+ const lines = body.split("\n");
117
+ const announcement = lines.findIndex(announcesBlockers);
118
+ if (announcement === -1) return [];
119
+
120
+ const inline = issueReferences(lines[announcement] as string);
121
+ if (inline.length > 0) return inline;
122
+
123
+ const references: number[] = [];
124
+ let listStarted = false;
125
+ for (const line of lines.slice(announcement + 1)) {
126
+ if (!listStarted && line.trim() === "") continue;
127
+ if (!LIST_ITEM.test(line)) break;
128
+ listStarted = true;
129
+ references.push(...issueReferences(line));
130
+ }
131
+
132
+ return references;
133
+ }
134
+
135
+ function announcesBlockers(line: string): boolean {
136
+ return /^blocked[ -]by\b/i.test(line.replace(DECORATION, ""));
137
+ }
138
+
139
+ function issueReferences(line: string): number[] {
140
+ return [...line.matchAll(ISSUE_REFERENCE)].map((match) =>
141
+ Number.parseInt(match[1] as string, 10),
142
+ );
143
+ }