ticket-runner 0.6.1 → 0.6.3

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.
@@ -0,0 +1,75 @@
1
+ import type { HostKind } from "./host.js";
2
+
3
+ /**
4
+ * Whose money a Run's Stages spend, decided once when the Run starts and held
5
+ * for the whole Run: the subscription the Host is logged in with, or the API
6
+ * key the Host exports, which a Run uses only when it was started with
7
+ * `--api-key`. The choice is the Host's business, so it is a flag and never a
8
+ * field of the Target's config.
9
+ */
10
+ export type Credential = "subscription" | "api-key";
11
+
12
+ /**
13
+ * The variable the CLI reads an API key from. Under `-p` it outranks the
14
+ * subscription login without asking, so a Stage of a subscription Run is
15
+ * started without it, whatever the Host exports.
16
+ */
17
+ export const API_KEY_ENV_VAR = "ANTHROPIC_API_KEY";
18
+
19
+ /** The credential, as the Run summary's header and the log name it. */
20
+ export const CREDENTIAL_WORDS: Record<Credential, string> = {
21
+ subscription: "subscription",
22
+ "api-key": "API key",
23
+ };
24
+
25
+ /**
26
+ * The `apiKeySource` a Stage's `system/init` event reports when it ran on the
27
+ * Run's credential. Any other is a Stage billed somewhere the Run did not
28
+ * choose: a key an `apiKeyHelper` in the Host's settings supplied, say, which
29
+ * no environment variable removes.
30
+ */
31
+ export function expectedKeySource(credential: Credential): string {
32
+ return credential === "api-key" ? API_KEY_ENV_VAR : "none";
33
+ }
34
+
35
+ /**
36
+ * A Stage that reported another `apiKeySource` than its Run's credential
37
+ * expects, which the Run's log and its summary each name.
38
+ */
39
+ export interface StrayStage {
40
+ ticket: number;
41
+ stage: string;
42
+ /** What the Stage's `system/init` event said it ran on. */
43
+ apiKeySource: string;
44
+ }
45
+
46
+ /**
47
+ * Why a Run on `credential` will not start on this Host, or nothing where it
48
+ * can.
49
+ *
50
+ * Only an `--api-key` Run can be refused. A cloud Host always runs its
51
+ * sessions on the subscription whatever its environment says, so the flag
52
+ * would be a Run spending the subscription without a word; and a Host that
53
+ * exports no key has none to hand the Stages.
54
+ */
55
+ export function credentialRefusal(
56
+ credential: Credential,
57
+ host: HostKind,
58
+ env: Record<string, string | undefined>,
59
+ ): string | undefined {
60
+ if (credential !== "api-key") return undefined;
61
+ if (host === "cloud") {
62
+ return (
63
+ "`--api-key` needs a workstation Host: a cloud session runs every Stage on the " +
64
+ `subscription, whatever \`${API_KEY_ENV_VAR}\` says. Run without \`--api-key\`, or ` +
65
+ "start the Run on a workstation."
66
+ );
67
+ }
68
+ if ((env[API_KEY_ENV_VAR] ?? "") === "") {
69
+ return (
70
+ `\`--api-key\` runs every Stage on the \`${API_KEY_ENV_VAR}\` this shell exports, and it ` +
71
+ "exports none. Export the key, or run without `--api-key` to run on the subscription."
72
+ );
73
+ }
74
+ return undefined;
75
+ }
@@ -0,0 +1,132 @@
1
+ /**
2
+ * Whether a Check a Ticket's branch failed is one it inherited.
3
+ *
4
+ * The Checks run on the Ticket's branch, and CI on its pull request, so a
5
+ * failure alone cannot say whether the branch brought it or the Base branch
6
+ * did. A test that starts failing on the Base branch fails on every branch at
7
+ * once, and a fix Stage per Ticket then mends it differently in each pull
8
+ * request, at the cost of every Ticket's Fix budget. So a failure is graded
9
+ * once more, at what the branch inherited: its merge-base with the Base branch,
10
+ * checked out clean in a worktree of its own. One that fails there too is the
11
+ * Base branch's, and the Ticket is released rather than charged for it.
12
+ */
13
+
14
+ import { baseWorktreePath } from "./branch.js";
15
+ import type { RoutedNote } from "./notes.js";
16
+ import type { CheckOutcome, Workspace } from "./ports/workspace.js";
17
+
18
+ /** A Check command the Base branch fails, and how. */
19
+ export interface FailingBase {
20
+ /** The merge-base it fails at, in full. */
21
+ commit: string;
22
+ command: string;
23
+ output: string;
24
+ timedOut: boolean;
25
+ }
26
+
27
+ /** What it takes to run a Check at a merge-base. */
28
+ export interface BaseCheckRun {
29
+ workspace: Workspace;
30
+ repoRoot: string;
31
+ /** The Check wall-clock limit, which a Check gets at a merge-base as anywhere. */
32
+ timeoutMs: number;
33
+ log?: (line: string) => void;
34
+ }
35
+
36
+ /**
37
+ * The Run's record of the Checks it ran at merge-bases, and of the Notes it
38
+ * posted about the ones that failed there.
39
+ *
40
+ * A Run has one and every Lane shares it, so the Tickets that fail together
41
+ * over one broken Base branch cost one run of the Check between them, and one
42
+ * Note. Runs at the same commit take turns, because they share its worktree.
43
+ * A run that could not be made — no worktree, no git — is forgotten rather
44
+ * than kept, as a standing Notes lookup that failed is: the Ticket that asked
45
+ * is charged as it always was, and the next one asks again.
46
+ */
47
+ export class BaseBranchChecks {
48
+ /** Each command's outcome at each commit, keyed `<commit> <command>`. */
49
+ readonly #outcomes = new Map<string, Promise<CheckOutcome>>();
50
+ /** The last run at each commit, which the next one there waits behind. */
51
+ readonly #turns = new Map<string, Promise<unknown>>();
52
+ /** The Note posted about each commit, or being posted. */
53
+ readonly #notes = new Map<string, Promise<RoutedNote>>();
54
+
55
+ /**
56
+ * The first of `commands` that fails at `commit`, run in that order and
57
+ * stopping there as the Checks do, or nothing when the commit passes them
58
+ * all. Each command runs at a commit at most once per Run.
59
+ */
60
+ async firstFailing(
61
+ run: BaseCheckRun,
62
+ commit: string,
63
+ commands: readonly string[],
64
+ ): Promise<FailingBase | undefined> {
65
+ for (const command of commands) {
66
+ const outcome = await this.#outcome(run, commit, command);
67
+ if (!outcome.ok) {
68
+ return { commit, command, output: outcome.output, timedOut: outcome.timedOut };
69
+ }
70
+ }
71
+ return undefined;
72
+ }
73
+
74
+ /**
75
+ * Post the Note about `commit` once this Run: the first caller posts it and
76
+ * gets it back, and every caller after it gets nothing. A post that failed
77
+ * is forgotten, so a Ticket that was waiting on it, or one released over the
78
+ * same commit later, tries again.
79
+ */
80
+ async noteOnce(commit: string, post: () => Promise<RoutedNote>): Promise<RoutedNote | undefined> {
81
+ const posted = this.#notes.get(commit);
82
+ if (posted !== undefined) {
83
+ const delivered = await posted.then(
84
+ () => true,
85
+ () => false,
86
+ );
87
+ return delivered ? undefined : await this.noteOnce(commit, post);
88
+ }
89
+ const posting = post();
90
+ this.#notes.set(commit, posting);
91
+ try {
92
+ return await posting;
93
+ } catch (error) {
94
+ this.#notes.delete(commit);
95
+ throw error;
96
+ }
97
+ }
98
+
99
+ #outcome(run: BaseCheckRun, commit: string, command: string): Promise<CheckOutcome> {
100
+ const key = `${commit} ${command}`;
101
+ const known = this.#outcomes.get(key);
102
+ if (known !== undefined) return known;
103
+
104
+ const before = this.#turns.get(commit) ?? Promise.resolve();
105
+ const outcome = before.catch(() => undefined).then(() => runAt(run, commit, command));
106
+ this.#turns.set(commit, outcome);
107
+ this.#outcomes.set(key, outcome);
108
+ outcome.catch(() => {
109
+ if (this.#outcomes.get(key) === outcome) this.#outcomes.delete(key);
110
+ });
111
+ return outcome;
112
+ }
113
+ }
114
+
115
+ /**
116
+ * One command in a clean worktree at `commit`, which goes again once it has
117
+ * run. A worktree that will not go is logged and nothing more: the outcome is
118
+ * still the answer, and the next run at the commit replaces what is left.
119
+ */
120
+ async function runAt(run: BaseCheckRun, commit: string, command: string): Promise<CheckOutcome> {
121
+ const path = baseWorktreePath(run.repoRoot, commit);
122
+ await run.workspace.createDetachedWorktree(path, commit);
123
+ try {
124
+ return await run.workspace.runCheck(command, path, run.timeoutMs);
125
+ } finally {
126
+ try {
127
+ await run.workspace.removeWorktree({ path });
128
+ } catch (error) {
129
+ run.log?.(`could not remove the worktree at ${commit}: ${(error as Error).message}`);
130
+ }
131
+ }
132
+ }
package/src/guards.ts CHANGED
@@ -53,7 +53,7 @@ export function skipReason(
53
53
  readyForAgent: string,
54
54
  /**
55
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
56
+ * claimed by a Run that never came back (GLOSSARY.md). Both refusals read the
57
57
  * Claim as somebody else's work, and a stranded Ticket wears it itself — the
58
58
  * assignee is this very user and `ready-for-agent` came off when the Claim was
59
59
  * made — so it passes them and is resumed rather than refused. The Planning
package/src/host.ts CHANGED
@@ -4,7 +4,7 @@ import { existsSync, readFileSync } from "node:fs";
4
4
  import { hostname } from "node:os";
5
5
 
6
6
  /**
7
- * Which kind of Host a Run executes on (CONTEXT.md), decided here and nowhere
7
+ * Which kind of Host a Run executes on (GLOSSARY.md), decided here and nowhere
8
8
  * else, so every part of the pipeline that behaves differently in the cloud
9
9
  * asks the same question the same way.
10
10
  */
@@ -0,0 +1,51 @@
1
+ /**
2
+ * The end of what a command printed, cut to fit where the pipeline quotes it.
3
+ *
4
+ * A CI log goes to a fix Stage and into a hand-off comment, and a failing Base
5
+ * branch's output goes into a Note on the standing Notes issue. Both have to
6
+ * stay readable, and a comment has to stay under what GitHub accepts, so both
7
+ * quote the same tail.
8
+ */
9
+
10
+ /** Lines kept from the tail. */
11
+ export const MAX_TAIL_LINES = 40;
12
+
13
+ /** Characters kept from the tail, for lines long enough to need it. */
14
+ export const MAX_TAIL_CHARS = 4_000;
15
+
16
+ /**
17
+ * The end of a log, under a fixed cap, saying what it left out, or nothing when
18
+ * the log holds nothing but blank space.
19
+ *
20
+ * The tail is the part worth carrying: a runner prints the assertion or the
21
+ * stack that ended the job last, under however much setup noise came first.
22
+ * Both callers pass the output as it came, so one output gives one tail
23
+ * wherever it is quoted.
24
+ */
25
+ export function logTail(log: string): string {
26
+ const lines = throughLastError(log).trim().split("\n");
27
+ let kept = lines.slice(-MAX_TAIL_LINES);
28
+ while (kept.length > 1 && kept.join("\n").length > MAX_TAIL_CHARS) kept = kept.slice(1);
29
+
30
+ const text = kept.join("\n");
31
+ const omitted = lines.length - kept.length;
32
+
33
+ // A single line longer than the whole cap keeps its own tail: the error is at
34
+ // the end of it. Its own start is cut too, which the count alone would not say.
35
+ if (text.length > MAX_TAIL_CHARS) {
36
+ const earlier = omitted > 0 ? `${omitted} earlier lines and the start of this one` : "the start of this line";
37
+ return `… (${earlier} omitted)\n${text.slice(-MAX_TAIL_CHARS)}`;
38
+ }
39
+ return omitted > 0 ? `… (${omitted} earlier lines omitted)\n${text}` : text;
40
+ }
41
+
42
+ /**
43
+ * Everything up to the last line an Actions runner marked `##[error]`, or all
44
+ * of it. What the post-job cleanup prints after the failure would otherwise be
45
+ * the tail that is kept; output with no such line is left whole.
46
+ */
47
+ function throughLastError(log: string): string {
48
+ const lines = log.split("\n");
49
+ const last = lines.findLastIndex((line) => line.includes("##[error]"));
50
+ return last === -1 ? log : lines.slice(0, last + 1).join("\n");
51
+ }
@@ -20,6 +20,9 @@
20
20
  * reading the whole Note, and tells one that waits on a decision from one that
21
21
  * only needs a Ticket by its `next`. `next` alone is optional, because a Stage
22
22
  * that knows neither a fix nor the decision in the way has nothing to put there.
23
+ *
24
+ * This is the list as the verify Stage reads it. The Stages that write code read
25
+ * {@link CODE_STAGE_NOTES_LIST_SCHEMA}, the same list with one more sentence.
23
26
  */
24
27
  export const NOTES_LIST_SCHEMA = {
25
28
  type: "array",
@@ -56,3 +59,21 @@ export const NOTES_LIST_SCHEMA = {
56
59
  additionalProperties: false,
57
60
  },
58
61
  } as const;
62
+
63
+ /**
64
+ * Whose a defect the branch itself introduced is, in the words both the code
65
+ * Stages' schema and their prompts use: one declaration, so the two cannot drift.
66
+ */
67
+ export const OWN_DEFECT =
68
+ "A defect this branch introduced, one that behaves correctly on the Base branch and wrongly here, or one in code this branch added, belongs to this Ticket";
69
+
70
+ /**
71
+ * The list as the implement and fix Stages read it: a defect their own branch
72
+ * introduced is theirs to fix, not to list. verify keeps the list without it,
73
+ * because it fixes nothing and grades the Acceptance Criteria alone, so a
74
+ * regression it demonstrates beside them still has only a Note to go in.
75
+ */
76
+ export const CODE_STAGE_NOTES_LIST_SCHEMA = {
77
+ ...NOTES_LIST_SCHEMA,
78
+ description: `Defects that belong to another Ticket, or to no Ticket yet. ${OWN_DEFECT}: fix it, and do not list it here. Empty when you found none, which is the ordinary case.`,
79
+ } as const;
package/src/notes.ts CHANGED
@@ -30,8 +30,8 @@ import { z } from "zod";
30
30
  * A Stage that ends with Notes.
31
31
  *
32
32
  * Narrower than a Stage name on purpose: the conflict Stage is given no Notes
33
- * channel — it finishes a rebase and touches no file the conflict did not — so
34
- * a Note that claimed to come from one would be a Note nothing could have made.
33
+ * channel — it finishes a rebase and implements nothing — so a Note that
34
+ * claimed to come from one would be a Note nothing could have made.
35
35
  */
36
36
  export type NotingStage = "implement" | "verify" | "fix";
37
37
 
@@ -57,9 +57,13 @@ export interface Note extends NoteText {
57
57
 
58
58
  /** A Note that reached GitHub, which is what a Run summary reports. */
59
59
  export interface RoutedNote {
60
- /** The Ticket whose Stage made the finding. */
60
+ /** The Ticket whose Stage made the finding, or whose Release did. */
61
61
  origin: number;
62
- stage: NotingStage;
62
+ /**
63
+ * The Stage that made it, or the pipeline itself: the one Note no Stage
64
+ * writes is the pipeline's, about a Base branch failing a Check.
65
+ */
66
+ stage: NotingStage | "pipeline";
63
67
  /** The issue the Note reached: the Ticket it named, or the standing Notes issue. */
64
68
  issue: number;
65
69
  /**