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/handoff.ts ADDED
@@ -0,0 +1,82 @@
1
+ /**
2
+ * The hand-off comments a Ticket is already carrying when it is claimed.
3
+ *
4
+ * A hand-off is current for exactly as long as a human holds the Ticket. Once
5
+ * the Ticket is relabelled and a Run takes it again, the comment still reads as
6
+ * the last word on it — and on a Ticket that then merges it is the last thing
7
+ * on a closed issue, because the progress comment is edited in place above it
8
+ * and the merge writes nothing below. So the Claim marks every hand-off comment
9
+ * on the Ticket as history on its way past.
10
+ *
11
+ * Marked, not removed: the failure, the location and the evidence are worth
12
+ * reading afterwards, and an edit notifies nobody, which is what makes this
13
+ * cheap enough to do to every one of them. `docs/templates/handoff-comment.md`
14
+ * is the source of truth for the shape.
15
+ */
16
+
17
+ import type { IssueComment, Tracker } from "./ports/tracker.js";
18
+ import { HANDOFF_MARKER, findMarkedComments, handoffTakenComment } from "./templates.js";
19
+
20
+ /**
21
+ * Every hand-off comment the Ticket is still carrying as current, each with the
22
+ * body that would mark it as history.
23
+ *
24
+ * One question, asked twice: it is what the Claim edits, and it is also what
25
+ * says a human has been holding the Ticket since the last Run put it down.
26
+ */
27
+ function unmarkedHandoffs(
28
+ comments: IssueComment[],
29
+ ): { comment: IssueComment; marked: string }[] {
30
+ return findMarkedComments(comments, HANDOFF_MARKER).flatMap((comment) => {
31
+ const marked = handoffTakenComment(comment.body);
32
+ return marked === undefined ? [] : [{ comment, marked }];
33
+ });
34
+ }
35
+
36
+ /**
37
+ * Whether a human has been holding the Ticket since the last Run put it down.
38
+ *
39
+ * Asked of the comments as they were when the Ticket was claimed, so the Run
40
+ * marking them now still sees the hand-off it is answering.
41
+ */
42
+ export function carriesCurrentHandoff(comments: IssueComment[]): boolean {
43
+ return unmarkedHandoffs(comments).length > 0;
44
+ }
45
+
46
+ export interface HandoffOptions {
47
+ tracker: Tracker;
48
+ ticket: number;
49
+ /** The Ticket's comments as they were when it was claimed. */
50
+ comments: IssueComment[];
51
+ log?: (line: string) => void;
52
+ }
53
+
54
+ /**
55
+ * Mark every hand-off comment on a Ticket as history, the Ticket having just
56
+ * been taken again.
57
+ *
58
+ * Nothing here throws. This is a courtesy to whoever reads the Ticket next, not
59
+ * part of how it is decided, and a Ticket must not be handed off or ended
60
+ * because GitHub would not take an edit. A comment already marked costs no
61
+ * tracker call, so claiming a Ticket twice does not stack the line; one the
62
+ * tracker gave no id for cannot be edited at all and is passed over, exactly as
63
+ * the progress comment treats one.
64
+ */
65
+ export async function markHandoffsTaken({
66
+ tracker,
67
+ ticket,
68
+ comments,
69
+ log,
70
+ }: HandoffOptions): Promise<void> {
71
+ for (const { comment, marked } of unmarkedHandoffs(comments)) {
72
+ if (comment.id === undefined) continue;
73
+
74
+ try {
75
+ await tracker.updateComment(comment.id, marked);
76
+ } catch (error) {
77
+ log?.(
78
+ `#${ticket} could not mark a hand-off comment as history: ${(error as Error).message}`,
79
+ );
80
+ }
81
+ }
82
+ }
package/src/host.ts ADDED
@@ -0,0 +1,116 @@
1
+ import { execFileSync } from "node:child_process";
2
+ import { randomUUID } from "node:crypto";
3
+ import { existsSync, readFileSync } from "node:fs";
4
+ import { hostname } from "node:os";
5
+
6
+ /**
7
+ * Which kind of Host a Run executes on (CONTEXT.md), decided here and nowhere
8
+ * else, so every part of the pipeline that behaves differently in the cloud
9
+ * asks the same question the same way.
10
+ */
11
+
12
+ /** A workstation that outlives the Run, or a Claude Code cloud session's VM. */
13
+ export type HostKind = "workstation" | "cloud";
14
+
15
+ /** What a Claude Code cloud session sets, to `true`, in every process it starts. */
16
+ export const CLOUD_ENV_VAR = "CLAUDE_CODE_REMOTE";
17
+
18
+ /**
19
+ * The Host the environment says this process runs on.
20
+ *
21
+ * Takes the environment so either answer can be tested without `process.env`.
22
+ * Only the value the cloud session sets counts: anything else, the variable
23
+ * unset included, is a workstation, which is what every Host was before
24
+ * ADR-0008.
25
+ */
26
+ export function hostKind(env: Record<string, string | undefined>): HostKind {
27
+ return env[CLOUD_ENV_VAR] === "true" ? "cloud" : "workstation";
28
+ }
29
+
30
+ /**
31
+ * The Host a Run executes on, as the Run lock records it: which kind, which
32
+ * one, and what a human calls it.
33
+ *
34
+ * `id` is what two Hosts are told apart by, and it is stable for as long as the
35
+ * Host exists: a workstation's machine, which outlives every Run on it, and a
36
+ * cloud Host's session, which never repeats. Only a Run on the same Host can
37
+ * tell whether the process a lock names is still running, so this is the
38
+ * question the lock asks before it looks at a process at all.
39
+ */
40
+ export interface Host {
41
+ kind: HostKind;
42
+ id: string;
43
+ /** The machine's hostname, for a human; never compared. */
44
+ name: string;
45
+ }
46
+
47
+ /** How the machine a process runs on answers for itself. Seams for tests. */
48
+ export interface MachineProbe {
49
+ hostname: () => string;
50
+ /** The operating system's own id for the machine, when it keeps one. */
51
+ machineId: () => string | undefined;
52
+ }
53
+
54
+ /**
55
+ * What a cloud session is known by, in the order they are asked: the cloud's
56
+ * own name for the session, and then the session the Run's process was started
57
+ * from, which on a cloud Host is the Operator's and lives as long as the VM.
58
+ */
59
+ const SESSION_ENV_VARS = ["CLAUDE_CODE_REMOTE_SESSION_ID", "CLAUDE_CODE_SESSION_ID"];
60
+
61
+ /**
62
+ * The Host this process runs on.
63
+ *
64
+ * A cloud Host that names no session is given an id no other process will
65
+ * ever have, rather than the machine's: VMs made from one image can share a
66
+ * machine id and a hostname, and a second session taken for the first would
67
+ * find the first's pid missing and take a live Run's lock over. The cost is
68
+ * that a Run there is a stranger even to its own Host, so its lock is always
69
+ * one a human releases.
70
+ */
71
+ export function currentHost(
72
+ env: Record<string, string | undefined>,
73
+ machine: MachineProbe = { hostname, machineId: readMachineId },
74
+ ): Host {
75
+ const kind = hostKind(env);
76
+ const name = machine.hostname();
77
+ const session = SESSION_ENV_VARS.map((variable) => env[variable]).find((value) => value);
78
+ if (kind === "cloud") return { kind, id: session ?? `unnamed-${randomUUID()}`, name };
79
+ return { kind, id: machine.machineId() ?? name, name };
80
+ }
81
+
82
+ /** Whether two Hosts are the same one, which only then can see each other's processes. */
83
+ export function sameHost(a: Host, b: Host): boolean {
84
+ return a.kind === b.kind && a.id === b.id;
85
+ }
86
+
87
+ /** A Host as a sentence names it. */
88
+ export function describeHost(host: Host): string {
89
+ return host.kind === "cloud"
90
+ ? `the cloud Host of session \`${host.id}\``
91
+ : `the workstation \`${host.name}\``;
92
+ }
93
+
94
+ /**
95
+ * The id the operating system keeps for the machine: systemd's on Linux, the
96
+ * platform UUID on macOS. Undefined where there is none to read, and the
97
+ * hostname stands in.
98
+ */
99
+ function readMachineId(): string | undefined {
100
+ try {
101
+ if (process.platform === "darwin") {
102
+ const output = execFileSync("ioreg", ["-rd1", "-c", "IOPlatformExpertDevice"], {
103
+ encoding: "utf8",
104
+ });
105
+ return /"IOPlatformUUID" = "([^"]+)"/.exec(output)?.[1];
106
+ }
107
+ for (const path of ["/etc/machine-id", "/var/lib/dbus/machine-id"]) {
108
+ if (!existsSync(path)) continue;
109
+ const id = readFileSync(path, "utf8").trim();
110
+ if (id !== "") return id;
111
+ }
112
+ return undefined;
113
+ } catch {
114
+ return undefined;
115
+ }
116
+ }
package/src/init.ts ADDED
@@ -0,0 +1,405 @@
1
+ import { existsSync, mkdirSync, readdirSync, writeFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { CONFIG_FILENAME, type Config } from "./config.js";
4
+ import {
5
+ CLAUDE_SECTION,
6
+ CONVENTIONS_PATH,
7
+ conventionsDoc,
8
+ conventionsMark,
9
+ } from "./conventions.js";
10
+ import { ensureLabels } from "./labels.js";
11
+ import {
12
+ type AgentPreflight,
13
+ type AgentRunner,
14
+ SKILLS_PLUGIN,
15
+ } from "./ports/agent-runner.js";
16
+ import type { Authentication, Tracker } from "./ports/tracker.js";
17
+ import {
18
+ CLAUDE_FILENAME,
19
+ GH_FAILURE,
20
+ hasClaudePointer,
21
+ missingIgnoreLines,
22
+ readTargetFile,
23
+ } from "./readiness.js";
24
+ import { OPERATOR_SKILL_PATH, operatorSkill } from "./operator-skill.js";
25
+ import { nestedRunRefusal } from "./stage-guard.js";
26
+ import { newerVersionLine } from "./staleness.js";
27
+ import { isHigher, versionNumber } from "./version-number.js";
28
+
29
+ /**
30
+ * `ticket-runner init`: put in place what a Run will expect to find in a
31
+ * Target, and report on what only the human can put there.
32
+ *
33
+ * Three parts, in the order a reader of the report meets them: what was written
34
+ * into the Target, what was done on GitHub, and what was only looked at. It
35
+ * commits nothing and takes no Run lock, because it claims no Ticket, and
36
+ * running it twice is running it once: every write asks first whether the
37
+ * Target already has the thing.
38
+ *
39
+ * The files a human owns — `.gitignore`, `CLAUDE.md` — only ever gain lines.
40
+ * The conventions document and the Operator's skill are the exception, and the
41
+ * document says so in its own first paragraph: they are the pipeline's text, so
42
+ * a Target carrying another copy is rewritten and told that it was. The
43
+ * exception to the exception is a Target a newer pipeline set up, which the
44
+ * mark on the document's first line is how this knows: rewriting either would
45
+ * take the Target backwards, so both are left alone and the upgrade is named
46
+ * instead (ADR-0007).
47
+ *
48
+ * The Target's own files are read and written here rather than through a port,
49
+ * which every other external effect of the pipeline goes through. Setting a
50
+ * Target up is not something a Run does, so no port of a Run describes it, and
51
+ * a fourth port for five `writeFileSync` calls would be a port with one
52
+ * implementation and one caller. What the ports buy elsewhere — a fake to
53
+ * drive the state machine with — a temporary repository root buys here, which
54
+ * is how the local state under `.ticket-runner/` is already tested (ADR-0004).
55
+ */
56
+
57
+ /** Where GitHub Actions keeps a Target's workflows. */
58
+ const WORKFLOWS_DIR = join(".github", "workflows");
59
+
60
+ const PASS = "✓";
61
+ const FAIL = "✗";
62
+
63
+ export interface InitOptions {
64
+ repoRoot: string;
65
+ /**
66
+ * The Version doing the setting up, which the report's first line names. A
67
+ * string the CLI resolved, never something read from here (ADR-0007).
68
+ */
69
+ version: string;
70
+ /**
71
+ * The pipeline's own repository, as `owner/name`, which the newer-Version
72
+ * notice is looked up against; see {@link import("./staleness.js")}.
73
+ */
74
+ repository?: string | undefined;
75
+ config: Config;
76
+ tracker: Tracker;
77
+ runner: AgentRunner;
78
+ /**
79
+ * The shell `init` was started in, which the Stage mark is read from.
80
+ *
81
+ * The CLI refuses a marked shell before it parses a single argument, so this
82
+ * never fires in production. It is here because `init` is the one command
83
+ * that writes into the Target, and the CLI is deliberately untested: this is
84
+ * the seam the refusal is proved through.
85
+ */
86
+ env?: NodeJS.ProcessEnv;
87
+ log?: (line: string) => void;
88
+ error?: (line: string) => void;
89
+ }
90
+
91
+ /**
92
+ * Set the Target up and report on it. Returns the exit code: 2 when a Stage's
93
+ * shell was refused, 1 when any reported item failed, 0 when none did.
94
+ */
95
+ export async function initTarget(options: InitOptions): Promise<number> {
96
+ const { repoRoot, version, config, tracker, runner } = options;
97
+ const log = options.log ?? ((line: string) => console.log(line));
98
+ const error = options.error ?? ((line: string) => console.error(line));
99
+
100
+ // Before the first read and the first write of the Target.
101
+ const nested = nestedRunRefusal(options.env ?? process.env);
102
+ if (nested !== undefined) {
103
+ error(nested);
104
+ return 2;
105
+ }
106
+
107
+ log(`ticket-runner ${version} init · ${repoRoot}`);
108
+
109
+ // The first thing after the opening line, so a human setting a Target up with
110
+ // an old copy reads it before the report it is about to change their mind
111
+ // about. Never a refusal: `init` sets the Target up either way.
112
+ const newer = await newerVersionLine({
113
+ tracker,
114
+ version,
115
+ repository: options.repository,
116
+ });
117
+ if (newer !== undefined) log(newer);
118
+
119
+ const written = writeTargetFiles(repoRoot, version);
120
+
121
+ // Asked before the labels, because every other GitHub call throws without it
122
+ // and a report is more use to the human than a stack trace.
123
+ const authentication = await tracker.authentication();
124
+ const preflight = await runner.preflight();
125
+ const github = await updateGitHub(tracker, config, authentication);
126
+ const reported = reportedItems(repoRoot, config, authentication, preflight);
127
+
128
+ logGroup(log, "Wrote", written, "nothing to write");
129
+ logGroup(log, "GitHub", github);
130
+ logGroup(
131
+ log,
132
+ "Checked",
133
+ reported.map((item) => `${item.ok ? PASS : FAIL} ${item.line}`),
134
+ );
135
+
136
+ const failed = reported.filter((item) => !item.ok).length;
137
+ log("");
138
+ log(
139
+ failed === 0
140
+ ? "Ready: everything a Run expects of this Target is in place."
141
+ : `Not ready: ${failed} ${failed === 1 ? "item is" : "items are"} yours to put right.`,
142
+ );
143
+ return failed === 0 ? 0 : 1;
144
+ }
145
+
146
+ /** One headed group of the report, indented under its heading. */
147
+ function logGroup(
148
+ log: (line: string) => void,
149
+ heading: string,
150
+ lines: string[],
151
+ empty = "nothing to do",
152
+ ): void {
153
+ log("");
154
+ log(`${heading}:`);
155
+ for (const line of lines.length === 0 ? [empty] : lines) log(` ${line}`);
156
+ }
157
+
158
+ /** What the Target gained on disk, one line per file that changed. */
159
+ function writeTargetFiles(repoRoot: string, version: string): string[] {
160
+ // Read once, before the document it is read from is rewritten: it decides
161
+ // whether the skill is too.
162
+ const newer = newerSetUp(repoRoot, version);
163
+ return [
164
+ ensureGitignore(repoRoot),
165
+ ensureConfigFile(repoRoot),
166
+ ensureConventionsDoc(repoRoot, version, newer),
167
+ ensureClaudePointer(repoRoot),
168
+ ensureOperatorSkill(repoRoot, newer),
169
+ ].filter((line): line is string => line !== undefined);
170
+ }
171
+
172
+ /**
173
+ * The Version that set this Target up, where it is newer than the one setting
174
+ * it up now, and nothing otherwise.
175
+ *
176
+ * Read off the conventions document's mark, which is the only thing in a
177
+ * Target that says which pipeline wrote it, so it answers for the skill too.
178
+ */
179
+ export function newerSetUp(repoRoot: string, version: string): NewerSetUp | undefined {
180
+ const mark = conventionsMark(readTargetFile(join(repoRoot, CONVENTIONS_PATH)));
181
+ const own = versionNumber(version);
182
+ return mark !== undefined && own !== undefined && isHigher(mark, own)
183
+ ? { mark, own }
184
+ : undefined;
185
+ }
186
+
187
+ /** Which newer Version set a Target up, and which one found it. */
188
+ export interface NewerSetUp {
189
+ mark: string;
190
+ own: string;
191
+ }
192
+
193
+ /** The line for a file of the pipeline's own that a newer pipeline wrote. */
194
+ function leftAlone(path: string, { mark, own }: NewerSetUp): string {
195
+ return `${path}: left alone, because ${mark} set this Target up and this is ${own} — upgrade \`ticket-runner\` to rewrite it`;
196
+ }
197
+
198
+ /**
199
+ * Add whichever of the pipeline's two directories the Target does not already
200
+ * ignore, so a Target that ignores one of them under a comment of its own keeps
201
+ * its comment and gains nothing.
202
+ */
203
+ function ensureGitignore(repoRoot: string): string | undefined {
204
+ const missing = missingIgnoreLines(repoRoot);
205
+ if (missing.length === 0) return undefined;
206
+
207
+ const path = join(repoRoot, ".gitignore");
208
+ const existing = readTargetFile(path) ?? "";
209
+ const additions = missing.map((entry) => `${entry.comment}\n${entry.line}\n`).join("\n");
210
+ writeFileSync(path, `${existing}${separator(existing)}${additions}`);
211
+ return `.gitignore: added ${missing.map((entry) => `\`${entry.line}\``).join(" and ")}`;
212
+ }
213
+
214
+ /**
215
+ * An empty config file, so the Target has the obvious place to put a setting.
216
+ * Never read: whatever a Target's file says, it is the Target's.
217
+ */
218
+ function ensureConfigFile(repoRoot: string): string | undefined {
219
+ const path = join(repoRoot, CONFIG_FILENAME);
220
+ if (existsSync(path)) return undefined;
221
+ writeFileSync(path, "{}\n");
222
+ return `${CONFIG_FILENAME}: created, with every setting left at its default`;
223
+ }
224
+
225
+ /**
226
+ * The pipeline's own text, so a Target never carries an older copy of it —
227
+ * unless the copy here is a newer pipeline's, which is the one case where
228
+ * rewriting would take the Target backwards.
229
+ *
230
+ * The mark is read before the text, because it is the only thing that says
231
+ * which way round the two copies are. Nothing is refused either way: a Target
232
+ * is not worse for carrying a document from another Version.
233
+ */
234
+ function ensureConventionsDoc(
235
+ repoRoot: string,
236
+ version: string,
237
+ newer: NewerSetUp | undefined,
238
+ ): string | undefined {
239
+ if (newer !== undefined) return leftAlone(CONVENTIONS_PATH, newer);
240
+
241
+ const path = join(repoRoot, CONVENTIONS_PATH);
242
+ const existing = readTargetFile(path);
243
+ const mark = conventionsMark(existing);
244
+ const own = versionNumber(version);
245
+
246
+ const doc = conventionsDoc(version);
247
+ if (existing === doc) return undefined;
248
+
249
+ mkdirSync(dirname(path), { recursive: true });
250
+ writeFileSync(path, doc);
251
+ return `${CONVENTIONS_PATH}: ${rewritten(existing, mark, own)}`;
252
+ }
253
+
254
+ /**
255
+ * Which of the four ways a copy came to be rewritten this one was.
256
+ *
257
+ * A copy marked with this very Version is the odd one: nothing about the
258
+ * pipeline moved, so the difference is something the Target did to the file,
259
+ * and saying it was left by the Version now writing it would read as nonsense.
260
+ */
261
+ function rewritten(
262
+ existing: string | undefined,
263
+ mark: string | undefined,
264
+ own: string | undefined,
265
+ ): string {
266
+ if (existing === undefined) return "written";
267
+ if (mark === undefined) return "overwritten, because the copy here carried no Version";
268
+ if (mark === own) return "overwritten, because the copy here said something else";
269
+ return `overwritten, because the copy here was left by ${mark}`;
270
+ }
271
+
272
+ /**
273
+ * Point the Target's `CLAUDE.md` at the conventions document, where a Run would
274
+ * find no pointer. A second copy of the section would only be noise in the file
275
+ * every session reads.
276
+ */
277
+ function ensureClaudePointer(repoRoot: string): string | undefined {
278
+ const path = join(repoRoot, CLAUDE_FILENAME);
279
+ const existing = readTargetFile(path);
280
+ if (hasClaudePointer(existing)) return undefined;
281
+
282
+ const before = existing ?? "";
283
+ writeFileSync(path, `${before}${separator(before)}${CLAUDE_SECTION}`);
284
+ return existing === undefined
285
+ ? `${CLAUDE_FILENAME}: created, pointing at ${CONVENTIONS_PATH}`
286
+ : `${CLAUDE_FILENAME}: added the section pointing at ${CONVENTIONS_PATH}`;
287
+ }
288
+
289
+ /**
290
+ * The Operator's instructions, which a cloud session finds nowhere but in the
291
+ * Target (ADR-0008).
292
+ *
293
+ * The pipeline's own text, rewritten when it says something else, like the
294
+ * conventions document. It carries no mark of its own, so a Target a newer
295
+ * pipeline set up is known by the document's, and keeps what that pipeline
296
+ * wrote. One it left without a skill still gets this one: an older skill is
297
+ * something an Operator can follow, and no skill is a Target every Run refuses.
298
+ */
299
+ function ensureOperatorSkill(repoRoot: string, newer: NewerSetUp | undefined): string | undefined {
300
+ const path = join(repoRoot, OPERATOR_SKILL_PATH);
301
+ const existing = readTargetFile(path);
302
+ if (existing !== undefined && newer !== undefined) return leftAlone(OPERATOR_SKILL_PATH, newer);
303
+
304
+ const skill = operatorSkill();
305
+ if (existing === skill) return undefined;
306
+
307
+ mkdirSync(dirname(path), { recursive: true });
308
+ writeFileSync(path, skill);
309
+ return existing === undefined
310
+ ? `${OPERATOR_SKILL_PATH}: written`
311
+ : `${OPERATOR_SKILL_PATH}: overwritten, because the copy here said something else`;
312
+ }
313
+
314
+ /**
315
+ * What goes between what a file already says and what it is gaining: a blank
316
+ * line, and the newline the file's own last line may be missing.
317
+ */
318
+ function separator(existing: string): string {
319
+ if (existing === "") return "";
320
+ return existing.endsWith("\n") ? "\n" : "\n\n";
321
+ }
322
+
323
+ /** The three things `init` does on GitHub, and the one thing that stops them all. */
324
+ async function updateGitHub(
325
+ tracker: Tracker,
326
+ config: Config,
327
+ authentication: Authentication,
328
+ ): Promise<string[]> {
329
+ if (authentication !== "authenticated") return [`nothing done: ${GH_FAILURE[authentication].failure}`];
330
+
331
+ const created = await ensureLabels(tracker, config.labels);
332
+ // Asked for every time: the setting is the Target's to have on, and GitHub
333
+ // reports no difference between turning it on and finding it on.
334
+ await tracker.enableSquashMerge();
335
+ // Read first, because readiness reads it too: a report that says which of
336
+ // the two it found is one a human can match against a refusal.
337
+ const deletesBranches = await tracker.deletesBranchOnMerge();
338
+ if (!deletesBranches) await tracker.enableDeleteBranchOnMerge();
339
+ return [
340
+ created.length === 0
341
+ ? "labels: every triage label is already there"
342
+ : `labels: created ${created.join(", ")}`,
343
+ "merges: squash merging is on, and no other merge method was touched",
344
+ deletesBranches
345
+ ? "branches: a pull request's branch is already deleted when it merges"
346
+ : "branches: switched on deleting a pull request's branch when it merges",
347
+ ];
348
+ }
349
+
350
+ /** One item `init` can only report on, and whether it passed. */
351
+ interface Reported {
352
+ ok: boolean;
353
+ line: string;
354
+ }
355
+
356
+ /**
357
+ * What `init` cannot put in place itself: a login, two installs, a workflow the
358
+ * Target's own CI owns, and a Check that has to be the human's to name.
359
+ */
360
+ function reportedItems(
361
+ repoRoot: string,
362
+ config: Config,
363
+ authentication: Authentication,
364
+ preflight: AgentPreflight,
365
+ ): Reported[] {
366
+ return [
367
+ ghReported(authentication),
368
+ report(preflight.runs, "`claude` runs", "`claude` could not be run — install the Claude Code CLI"),
369
+ report(
370
+ preflight.plugin,
371
+ `the \`${SKILLS_PLUGIN}\` plugin is installed`,
372
+ `the \`${SKILLS_PLUGIN}\` plugin is not installed — an implement Stage has no skill without it`,
373
+ ),
374
+ report(
375
+ hasCiWorkflow(repoRoot),
376
+ `a CI workflow is present in \`${WORKFLOWS_DIR}\``,
377
+ `no CI workflow in \`${WORKFLOWS_DIR}\` — a pull request with no checks is never merged`,
378
+ ),
379
+ report(
380
+ config.checks.length > 0,
381
+ `a Check is configured or inferable: ${config.checks.join(", ")}`,
382
+ `no Check is configured or inferable — name one in \`checks\` in ${CONFIG_FILENAME}, or add \`test\` and \`typecheck\` scripts to package.json`,
383
+ ),
384
+ ];
385
+ }
386
+
387
+ /** The `gh` item, which fails two ways and names the fix for each. */
388
+ function ghReported(authentication: Authentication): Reported {
389
+ if (authentication === "authenticated") return { ok: true, line: "`gh` is authenticated" };
390
+ const { failure, remedy } = GH_FAILURE[authentication];
391
+ return { ok: false, line: `${failure} — ${remedy}` };
392
+ }
393
+
394
+ function report(ok: boolean, passed: string, failed: string): Reported {
395
+ return { ok, line: ok ? passed : failed };
396
+ }
397
+
398
+ /** Any workflow file at all; what it runs is the Target's business. */
399
+ function hasCiWorkflow(repoRoot: string): boolean {
400
+ try {
401
+ return readdirSync(join(repoRoot, WORKFLOWS_DIR)).some((entry) => /\.ya?ml$/i.test(entry));
402
+ } catch {
403
+ return false;
404
+ }
405
+ }
package/src/labels.ts ADDED
@@ -0,0 +1,42 @@
1
+ import type { Labels } from "./config.js";
2
+ import type { LabelSpec, Tracker } from "./ports/tracker.js";
3
+
4
+ /**
5
+ * The colour and meaning each triage role is created with. The names come from
6
+ * config, so a repo that calls them something else still gets them created.
7
+ */
8
+ const LABEL_SPECS: Record<keyof Labels, Omit<LabelSpec, "name">> = {
9
+ needsTriage: { color: "fbca04", description: "Maintainer needs to evaluate this issue" },
10
+ needsInfo: { color: "d876e3", description: "Waiting on reporter for more information" },
11
+ readyForAgent: { color: "0e8a16", description: "Fully specified, ready for an AFK agent" },
12
+ readyForHuman: { color: "d93f0b", description: "Requires human implementation" },
13
+ wontfix: { color: "cfd3d7", description: "Will not be actioned" },
14
+ inProgress: { color: "1d76db", description: "Claimed by a ticket-runner Run" },
15
+ };
16
+
17
+ /**
18
+ * Create whatever the triage state machine needs and the Target does not have
19
+ * yet, so a fresh Target works without manual label setup.
20
+ *
21
+ * `ticket-runner init` is the only caller: a Run that finds a label missing
22
+ * refuses the Target rather than creating it, so setup lives in one command.
23
+ *
24
+ * Returns the names it created; labels that already exist are left untouched,
25
+ * colour and description included. One GitHub added after the listing counts
26
+ * as already existing, since this call did not make it.
27
+ */
28
+ export async function ensureLabels(tracker: Tracker, labels: Labels): Promise<string[]> {
29
+ const existing = new Set(await tracker.listLabels());
30
+ const created: string[] = [];
31
+
32
+ for (const [role, spec] of Object.entries(LABEL_SPECS) as [
33
+ keyof Labels,
34
+ Omit<LabelSpec, "name">,
35
+ ][]) {
36
+ const name = labels[role];
37
+ if (existing.has(name)) continue;
38
+ if (await tracker.createLabel({ name, ...spec })) created.push(name);
39
+ }
40
+
41
+ return created;
42
+ }