ticket-runner 0.6.4 → 0.6.5

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 (48) hide show
  1. package/README.ko.md +4 -4
  2. package/README.md +3 -3
  3. package/docs/templates/operator-skill.md +7 -7
  4. package/package.json +1 -1
  5. package/src/acceptance-criteria.ts +2 -2
  6. package/src/adapters/claude-agent-runner.ts +3 -3
  7. package/src/adapters/exec.ts +19 -4
  8. package/src/adapters/gh-tracker.ts +17 -17
  9. package/src/adapters/git-workspace.ts +12 -8
  10. package/src/adapters/liveness.ts +77 -0
  11. package/src/adapters/process-tree.ts +4 -7
  12. package/src/adapters/version.ts +5 -5
  13. package/src/branch.ts +1 -1
  14. package/src/cli.ts +2 -2
  15. package/src/config.ts +4 -4
  16. package/src/conventions.ts +21 -18
  17. package/src/credential.ts +14 -13
  18. package/src/criteria.ts +107 -15
  19. package/src/failing-base.ts +7 -7
  20. package/src/failure-message.ts +72 -0
  21. package/src/guards.ts +2 -2
  22. package/src/handoff.ts +2 -2
  23. package/src/init.ts +8 -8
  24. package/src/landing.ts +1 -1
  25. package/src/lifecycle.ts +2 -2
  26. package/src/lock.ts +10 -2
  27. package/src/note-schema.ts +3 -3
  28. package/src/notes.ts +8 -6
  29. package/src/operator-skill.ts +2 -2
  30. package/src/orchestrator.ts +168 -128
  31. package/src/ports/agent-runner.ts +1 -1
  32. package/src/ports/tracker.ts +14 -13
  33. package/src/ports/workspace.ts +23 -22
  34. package/src/progress.ts +2 -2
  35. package/src/prompts.ts +67 -24
  36. package/src/readiness.ts +11 -11
  37. package/src/remove.ts +7 -7
  38. package/src/resume.ts +12 -12
  39. package/src/run-log.ts +5 -5
  40. package/src/run.ts +7 -7
  41. package/src/staleness.ts +14 -14
  42. package/src/start.ts +17 -12
  43. package/src/stranded.ts +19 -19
  44. package/src/templates.ts +147 -66
  45. package/src/title.ts +44 -8
  46. package/src/verdict.ts +7 -7
  47. package/src/version-number.ts +13 -13
  48. package/src/version-pr.ts +12 -12
package/README.ko.md CHANGED
@@ -13,7 +13,7 @@
13
13
 
14
14
  체인은 둘로 나뉩니다. **Planning**은 사람 몫입니다. `/grilling`, `/to-spec`, `/to-tickets`(또는
15
15
  `/triage`)로 기능 하나를 작은 GitHub 이슈 여러 개로 나눕니다. 이슈마다 `ready-for-agent` 라벨과
16
- Acceptance Criteria 체크리스트가 달리고, blocker가 연결됩니다. **Execution**은 파이프라인 몫입니다.
16
+ Acceptance Criteria 체크리스트가 달리고, blocker가 연결됩니다. **실행**은 파이프라인 몫입니다.
17
17
  그런 이슈 가운데 blocker가 모두 닫힌 것마다 다음을 합니다.
18
18
 
19
19
  1. 이슈를 맡고, 그 이슈의 branch와 git worktree를 만듭니다.
@@ -40,7 +40,7 @@ Acceptance Criteria 체크리스트가 달리고, blocker가 연결됩니다. **
40
40
  [`mattpocock-skills`](https://github.com/mattpocock/skills) 플러그인 1.2.3 이상 버전을 설치한 `claude`가
41
41
  있습니다.
42
42
 
43
- 파이프라인은 묻지 않고 Base branch에 merge합니다. 그걸 원하는 저장소에 쓰세요.
43
+ 파이프라인은 묻지 않고 base branch에 merge합니다. 그걸 원하는 저장소에 쓰세요.
44
44
 
45
45
  ## 써 보기
46
46
 
@@ -55,7 +55,7 @@ npx ticket-runner run # 준비된 이슈를 모두 처리합니다
55
55
 
56
56
  `init`은 검토하고 commit할 파일 몇 개를 씁니다. `.gitignore` 줄, conventions 문서, `CLAUDE.md`의 한
57
57
  섹션, Claude skill 하나입니다. 또 triage 라벨을 만들고, squash merge와 merge 시 branch 삭제를 켭니다.
58
- commit은 하지 않습니다. 세션은 이 파일들이 Base branch에 올라간 뒤에야 읽으므로, 첫 `run` 전에
58
+ commit은 하지 않습니다. 세션은 이 파일들이 base branch에 올라간 뒤에야 읽으므로, 첫 `run` 전에
59
59
  push하세요.
60
60
 
61
61
  계속 쓰려면 전역으로 설치하세요.
@@ -73,7 +73,7 @@ npm install -g ticket-runner
73
73
  | `ticket-runner run --api-key` | 모든 세션을 Claude 요금제 대신 `ANTHROPIC_API_KEY`로 과금합니다. |
74
74
  | `ticket-runner stop` | 진행 중인 Run에게 맡은 것만 끝내고 더 맡지 말라고 합니다. |
75
75
  | `ticket-runner remove` | 이 저장소에서 파이프라인을 걷어 냅니다. |
76
- | `ticket-runner -v` | Version을 출력합니다. |
76
+ | `ticket-runner -v` | 버전을 출력합니다. |
77
77
 
78
78
  Claude 앱에서도 Run을 시작할 수 있습니다. Target에서 Claude Code 클라우드 세션을 열고 "run it"이라고
79
79
  말하면 됩니다. 클라우드 세션은 늘 요금제로 돌기 때문에 `--api-key`를 거절합니다.
package/README.md CHANGED
@@ -42,7 +42,7 @@ It fits a repository where:
42
42
  [`gh`](https://cli.github.com/), and `claude` with the
43
43
  [`mattpocock-skills`](https://github.com/mattpocock/skills) plugin, version 1.2.3 or later
44
44
 
45
- It merges to your Base branch without asking. It is for repositories where that is what you want.
45
+ It merges to your base branch without asking. It is for repositories where that is what you want.
46
46
 
47
47
  ## Try it
48
48
 
@@ -58,7 +58,7 @@ npx ticket-runner run # work through every ready issue
58
58
  `init` writes a few files for you to review and commit: `.gitignore` lines, a conventions
59
59
  document, a section in `CLAUDE.md` and a Claude skill. It also creates the triage labels and
60
60
  turns on squash merging and branch deletion on merge. It commits nothing, and a session reads
61
- those files only once they are on your Base branch, so push them before the first `run`.
61
+ those files only once they are on your base branch, so push them before the first `run`.
62
62
 
63
63
  To keep it, install it globally:
64
64
 
@@ -75,7 +75,7 @@ npm install -g ticket-runner
75
75
  | `ticket-runner run --api-key` | Bill every session to your `ANTHROPIC_API_KEY`, not your Claude plan |
76
76
  | `ticket-runner stop` | Ask the Run in progress to finish what it holds and take no more |
77
77
  | `ticket-runner remove` | Take the pipeline out of this repository |
78
- | `ticket-runner -v` | Print the Version |
78
+ | `ticket-runner -v` | Print the version |
79
79
 
80
80
  A Run can also be started from the Claude app, in a Claude Code cloud session on the Target:
81
81
  say "run it". A cloud session always runs on your plan, so it refuses `--api-key`.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: ticket-runner
3
- description: Operate ticket-runner on this repository from a Claude Code cloud session — ready the Host, start a Run in the background, narrowed to the Tickets the human names when they name any, report what it prints, pass on a Stop, and release a Run lock a vanished Host left behind. Use when the human asks to run the pipeline ("run it"), to work particular Tickets, to stop the Run, or to release its lock. Never from a Stage.
3
+ description: Operate ticket-runner on this repository from a Claude Code cloud session — ready the Host (the machine the pipeline runs on), start a Run (one invocation of the pipeline) in the background, narrowed to the Tickets (GitHub issues each sized for one session of work) the human names when they name any, report what it prints, pass on a Stop (the human's request that a Run finish the Tickets it holds and take no more), and release a Run lock a vanished Host left behind. Use when the human asks to run the pipeline ("run it"), to work particular Tickets, to stop the Run, or to release its lock. Never from a Stage (a Claude Code session a Run started for a single purpose).
4
4
  ---
5
5
 
6
6
  # Operating ticket-runner
@@ -11,15 +11,15 @@ If `TICKET_RUNNER_STAGE` is set in your shell, you are a Stage of a Run, not an
11
11
 
12
12
  ## Ready the Host
13
13
 
14
- Install only what this Host does not already have. What the cloud environment's setup script installed is used as it is, whichever Version it is.
14
+ Install only what this Host does not already have. What the cloud environment's setup script installed is used as it is, whichever version it is.
15
15
 
16
- 1. The pipeline. If `ticket-runner --version` answers, use that copy. Otherwise read the Version on the first line of `docs/agents/pipeline-conventions.md`, the `<number>` in `<!-- ticket-runner:version <number> -->`, and install that Version:
16
+ 1. The pipeline. If `ticket-runner --version` answers, use that copy. Otherwise read the version on the first line of `docs/agents/pipeline-conventions.md`, the `<number>` in `<!-- ticket-runner:version <number> -->`, and install that version:
17
17
 
18
18
  ```bash
19
19
  npm install -g ticket-runner@<number>
20
20
  ```
21
21
 
22
- If the first line carries no Version, install nothing and tell the human to run `ticket-runner init` on this repository from a workstation.
22
+ If the first line carries no version, install nothing and tell the human to run `ticket-runner init` on this repository from a workstation.
23
23
 
24
24
  2. The skills plugin. If `claude plugin list` lists `mattpocock-skills`, it is there. Otherwise register the official marketplace first, then install the plugin from it:
25
25
 
@@ -35,9 +35,9 @@ Install only what this Host does not already have. What the cloud environment's
35
35
  apt-get install -y gh
36
36
  ```
37
37
 
38
- The `gh` apt offers is older than GitHub's own, and enough: the pipeline reaches GitHub through `gh api` alone. If the install fails, start nothing and tell the human what apt printed: a Run started without `gh` is refused as a Target that is not set up, saying only that `gh` is not installed and must be installed first.
38
+ The `gh` apt offers is older than GitHub's own, and enough: the pipeline reaches GitHub through `gh api` alone. If the install fails, start nothing and tell the human what apt printed: a Run started without `gh` is refused, because its Target, the repository a Run takes its work from and merges into, is not set up, saying only that `gh` is not installed and must be installed first.
39
39
 
40
- 4. This repository's own dependencies, in this checkout. Every Ticket's worktree lives inside this checkout, and a Check that finds nothing installed in its worktree uses what is installed here, so without them every Check fails to start and spends its Ticket's fix budget on that. If they are installed here already, `node_modules/` beside a `package.json` for instance, use them as they are. Otherwise work out the install command from what this repository declares, its lockfile first and then its README or contributing guide, and run it at the root of this checkout: `npm ci` beside a `package-lock.json`, say. A repository that declares no dependencies needs nothing here. If the install fails, start nothing and tell the human what the install printed.
40
+ 4. This repository's own dependencies, in this checkout. Every Ticket's worktree lives inside this checkout, and a Check, a command the pipeline runs itself on a Ticket's code to gate it, such as its tests, uses what is installed here when it finds nothing installed in its worktree. Without them every Check fails to start and spends its Ticket's fix budget, the fix Stages it is allowed, on that. If they are installed here already, `node_modules/` beside a `package.json` for instance, use them as they are. Otherwise work out the install command from what this repository declares, its lockfile first and then its README or contributing guide, and run it at the root of this checkout: `npm ci` beside a `package-lock.json`, say. A repository that declares no dependencies needs nothing here. If the install fails, start nothing and tell the human what the install printed.
41
41
 
42
42
  Tell the human in one line which of these you installed, this repository's dependencies included, or that nothing was missing.
43
43
 
@@ -54,7 +54,7 @@ Start one at a time. While a Run of yours is running, start no other.
54
54
 
55
55
  ## Report
56
56
 
57
- Report what the Run prints as it prints it, in a form a phone screen reads: one short line per Ticket that ended, saying which Ticket and whether it merged, was handed off, was released or was skipped, and why when the Run gives a reason. Pass on a refusal as it is worded: it names what to do.
57
+ Report what the Run prints as it prints it, in a form a phone screen reads: one short line per Ticket that ended, saying which Ticket and whether it merged, was handed off (given to a human to carry on), was released (given back for a later Run to take up again) or was skipped, and why when the Run gives a reason. Pass on a refusal as it is worded: it names what to do.
58
58
 
59
59
  When the Run ends, report its summary and what its exit code means: `1` at least one Ticket was handed off to a human, `2` nothing was taken at all, because the Run was refused or because it was given Ticket numbers and took none of them, every one skipped or blocked, and `0` otherwise.
60
60
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ticket-runner",
3
- "version": "0.6.4",
3
+ "version": "0.6.5",
4
4
  "description": "Drives the mattpocock-skills chain: humans plan, the pipeline executes.",
5
5
  "keywords": [
6
6
  "claude-code",
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Readers recognise a criterion by its shape and would disagree about it if each
5
5
  * carried its own pattern: the `no-criteria` guard counts one to decide a Ticket
6
- * is usable, the merge ticks one a Verdict proved and then counts the boxes it
6
+ * is usable, the merge ticks one a verdict proved and then counts the boxes it
7
7
  * ticked, and a Note has one escaped before it is posted. Drift between them is
8
8
  * not a cosmetic bug — a criterion the guard sees but the escaper misses lets a
9
9
  * Note read as work somebody promised, and one the merge ticks but the guard
@@ -32,7 +32,7 @@ const ITEM_HEAD = String.raw`^([ \t]*[-*+] )`;
32
32
  export const UNCHECKED_BOX = String.raw`${ITEM_HEAD}\[ \]`;
33
33
 
34
34
  /**
35
- * The ticked twin, for the merge alone: having ticked what a Verdict proved, it
35
+ * The ticked twin, for the merge alone: having ticked what a verdict proved, it
36
36
  * counts the boxes now ticked to tell whether a met criterion matched nothing.
37
37
  *
38
38
  * It shares {@link UNCHECKED_BOX}'s head so that count cannot drift from the
@@ -29,7 +29,7 @@ export interface ClaudeAgentRunnerOptions {
29
29
  const STAGE_SHELL = "/bin/bash";
30
30
 
31
31
  /**
32
- * The Session mark: a variable every Stage carries at a value no other Stage
32
+ * The session mark: a variable every Stage carries at a value no other Stage
33
33
  * session shares, and every process it starts inherits. A Stage killed at its
34
34
  * time limit is killed with every process still carrying its value, whoever
35
35
  * their parent is by then.
@@ -363,7 +363,7 @@ function startStageLog(
363
363
  appendFileSync(path(suffix), text.slice(0, text.length - held));
364
364
  appended[suffix] += chunk.length;
365
365
  } catch {
366
- // Nothing is lost: the chunk is still part of the Execution.
366
+ // Nothing is lost: the chunk is still part of the execution.
367
367
  }
368
368
  };
369
369
 
@@ -430,7 +430,7 @@ function isInitEvent(event: unknown): event is InitEvent {
430
430
 
431
431
  /**
432
432
  * What the session said it was billed to: the first init event's word on it.
433
- * A waking for a background agent is the same session on the same credential.
433
+ * A waking for a background agent is the same session, billed to the same.
434
434
  */
435
435
  function keySource(events: unknown[]): string | undefined {
436
436
  const source = events.find(isInitEvent)?.apiKeySource;
@@ -186,20 +186,35 @@ export async function execOrThrow(
186
186
  return throwOnFailure(command, args, await exec(command, args, options));
187
187
  }
188
188
 
189
- /** Turn a non-zero exit into an error naming the command and its output. */
189
+ /**
190
+ * Turn a non-zero exit into an error naming the command and its output.
191
+ *
192
+ * The message's first line is the whole command and how it exited, and every
193
+ * line after it is what the command printed, so whatever shows the message on
194
+ * one line takes its first. An argument with a newline in it — a pull
195
+ * request's body, a commit message — is shown by its first line and ` …`:
196
+ * the rest is what the pipeline wrote, not what the command printed, and
197
+ * given whole it would carry the command onto lines a reader takes for its
198
+ * output.
199
+ */
190
200
  export function throwOnFailure(
191
201
  command: string,
192
202
  args: string[],
193
203
  result: Execution,
194
204
  ): Execution {
195
205
  if (result.exitCode !== 0) {
196
- throw new Error(
197
- `\`${command} ${args.join(" ")}\` exited ${result.exitCode}\n${result.output.trim()}`,
198
- );
206
+ const shown = [command, ...args.map(firstLineOf)].join(" ");
207
+ throw new Error(`\`${shown}\` exited ${result.exitCode}\n${result.output.trim()}`);
199
208
  }
200
209
  return result;
201
210
  }
202
211
 
212
+ /** An argument as a failed command's message shows it: on one line. */
213
+ function firstLineOf(arg: string): string {
214
+ const newline = arg.search(/\r?\n/);
215
+ return newline === -1 ? arg : `${arg.slice(0, newline).trimEnd()} …`;
216
+ }
217
+
203
218
  /**
204
219
  * The environment a child is given, or nothing where it inherits this
205
220
  * process's own untouched.
@@ -68,7 +68,7 @@ interface Blocker {
68
68
  open: boolean;
69
69
  }
70
70
 
71
- /** One entry of the REST release list, in the three fields a Version needs. */
71
+ /** One entry of the REST release list, in the three fields a version needs. */
72
72
  interface RawRelease {
73
73
  tag_name: string;
74
74
  draft: boolean;
@@ -234,14 +234,14 @@ export class GhTracker implements Tracker {
234
234
  }
235
235
 
236
236
  /**
237
- * The tag of the highest Version published on `repository` as a Release.
237
+ * The tag of the highest version published on `repository` as a Release.
238
238
  *
239
239
  * Every failure is the same answer — no answer — because nothing the caller
240
240
  * does with it may stop a Run: a rate limit, a repository nobody can see, a
241
241
  * `gh` that is not installed. The list is asked for rather than GitHub's own
242
242
  * `latest`, which is the newest by date: a patch cut on an old branch after a
243
- * minor would otherwise be reported as the Version to upgrade to. A hundred
244
- * of them is every Version this tool is likely to have, and they arrive
243
+ * minor would otherwise be reported as the version to upgrade to. A hundred
244
+ * of them is every version this tool is likely to have, and they arrive
245
245
  * newest first, so the highest is among them wherever the count lands: one
246
246
  * page, never every page.
247
247
  */
@@ -411,7 +411,7 @@ export class GhTracker implements Tracker {
411
411
  * Assign `user`, and refuse an assignment GitHub did not make.
412
412
  *
413
413
  * REST answers a user it cannot assign with the issue as it was and a
414
- * success, where `gh issue edit --add-assignee` failed. A Claim nobody can
414
+ * success, where `gh issue edit --add-assignee` failed. A claim nobody can
415
415
  * see is worse than one that fails, so the answer is read back.
416
416
  */
417
417
  async assign(number: number, user: string): Promise<void> {
@@ -517,17 +517,17 @@ export class GhTracker implements Tracker {
517
517
  }
518
518
 
519
519
  /**
520
- * Poll the PR's CI until it settles or the timeout runs out. A PR with no
521
- * checks is reported as such, never as a pass.
520
+ * Poll the pull request's CI until it settles or the timeout runs out. A
521
+ * pull request with no checks is reported as such, never as a pass.
522
522
  *
523
523
  * The checks are the head commit's check runs and commit statuses, which is
524
524
  * everything `gh pr checks` read through GraphQL.
525
525
  *
526
- * Right after a PR opens, GitHub answers "no checks" for a while before the
527
- * workflow's check run exists, so "no checks" only counts once the grace
528
- * period has passed. A PR GitHub finds conflicting with its base is the
529
- * exception: GitHub runs no `pull_request` workflow for it, so no check is
530
- * coming and the wait ends as soon as the conflict is seen.
526
+ * Right after a pull request opens, GitHub answers "no checks" for a while
527
+ * before the workflow's check run exists, so "no checks" only counts once the
528
+ * grace period has passed. A pull request GitHub finds conflicting with its
529
+ * base is the exception: GitHub runs no `pull_request` workflow for it, so no
530
+ * check is coming and the wait ends as soon as the conflict is seen.
531
531
  */
532
532
  async waitForCi(number: number, timeoutMs: number): Promise<CiOutcome> {
533
533
  const startedAt = this.now();
@@ -573,9 +573,9 @@ export class GhTracker implements Tracker {
573
573
  * A check that is not an Actions job has no log to fetch and yields nothing.
574
574
  *
575
575
  * The cap counts the jobs a log could be fetched for, not the red checks: a
576
- * PR whose external checks went red alongside one Actions job still gets the
577
- * one log there is. What it keeps out of a prompt is a whole matrix failing
578
- * a leg at a time, each leg with the same log.
576
+ * pull request whose external checks went red alongside one Actions job
577
+ * still gets the one log there is. What it keeps out of a prompt is a whole
578
+ * matrix failing a leg at a time, each leg with the same log.
579
579
  */
580
580
  private async failedJobLogs(failed: CiCheck[]): Promise<string> {
581
581
  const jobs = failed.flatMap((check) => {
@@ -845,8 +845,8 @@ function subIssues(issue: RawIssue): number {
845
845
  * `pending` means "ask again"; everything else is an answer. Checks GitHub
846
846
  * would not report read as none, as a failing `gh pr checks` did, so the grace
847
847
  * period still covers a wait that starts before the checks exist. No checks on
848
- * a PR GitHub finds conflicting is the conflict, since that is why there are
849
- * none; checks it does have are read as they are.
848
+ * a pull request GitHub finds conflicting is the conflict, since that is why
849
+ * there are none; checks it does have are read as they are.
850
850
  */
851
851
  function readCi({ checks, conflicting }: CiSnapshot): CiReading | "pending" {
852
852
  if (checks === undefined || checks.length === 0) {
@@ -106,9 +106,9 @@ interface TreeEntry {
106
106
  *
107
107
  * Commands that run in the main checkout go one at a time, because the Tickets
108
108
  * of a Run do not: adding and removing worktrees, deleting branches and moving
109
- * the Base branch all take git refs and index locks that git fails on rather
109
+ * the base branch all take git refs and index locks that git fails on rather
110
110
  * than waits for, and a read of a commit range taken while another Ticket is
111
- * moving the Base branch is a range nobody asked for. Commands inside a
111
+ * moving the base branch is a range nobody asked for. Commands inside a
112
112
  * worktree are left parallel — that is where a Run spends its time, and no two
113
113
  * Tickets share one.
114
114
  *
@@ -118,7 +118,7 @@ interface TreeEntry {
118
118
  * runs, which is what this gives; a pair that had to be indivisible would have
119
119
  * to say so, and none of them is.
120
120
  *
121
- * The State lives on the Target's remote, on {@link STATE_BRANCH}, so a Run on
121
+ * The state lives on the Target's remote, on {@link STATE_BRANCH}, so a Run on
122
122
  * any Host resumes a Ticket another left (ADR-0004). The branch is one snapshot
123
123
  * commit, rewritten whole and force-pushed with a lease on the tip it was built
124
124
  * from, and built from objects and a scratch index alone: the main checkout's
@@ -641,21 +641,24 @@ export class GitWorkspace implements Workspace {
641
641
  });
642
642
  }
643
643
 
644
+ // These messages name the Ticket as `ticket <n>`, never `#<n>`: GitHub links
645
+ // a pushed commit that mentions `#<n>` to issue `<n>`, on whatever branch the
646
+ // commit is, so every write would leave a line on the Ticket's timeline.
644
647
  async writeState(state: TicketState): Promise<void> {
645
- await this.changeState(`Record #${state.ticket} at ${state.state}`, [
648
+ await this.changeState(`Record ticket ${state.ticket} at ${state.state}`, [
646
649
  { name: stateFileName(state.ticket), contents: stateFileContents(state) },
647
650
  ]);
648
651
  }
649
652
 
650
653
  async removeState(ticket: number): Promise<void> {
651
- await this.changeState(`Forget #${ticket}`, [
654
+ await this.changeState(`Forget ticket ${ticket}`, [
652
655
  { remove: stateFileName(ticket) },
653
656
  { remove: transcriptsDir(ticket) },
654
657
  ]);
655
658
  }
656
659
 
657
660
  /**
658
- * Each file goes up under `ticket-<n>/<runId>/`, beside the Ticket's State
661
+ * Each file goes up under `ticket-<n>/<runId>/`, beside the Ticket's state
659
662
  * file, as the Run's own directory lays it out; a Ticket handed off by more
660
663
  * than one Run keeps each Run's apart, and {@link removeState} takes them
661
664
  * all.
@@ -665,8 +668,9 @@ export class GitWorkspace implements Workspace {
665
668
  if (files.length === 0) return undefined;
666
669
 
667
670
  const directory = `${transcriptsDir(ticket)}/${runId}/`;
671
+ // `ticket <n>`, not `#<n>`, for the reason given above writeState.
668
672
  await this.changeState(
669
- `Keep #${ticket}'s transcripts from ${runId}`,
673
+ `Keep ticket ${ticket}'s transcripts from ${runId}`,
670
674
  files.map((file) => ({ name: `${directory}${file.name}`, from: file.path })),
671
675
  );
672
676
  return { branch: STATE_BRANCH, path: directory };
@@ -952,7 +956,7 @@ function branchNames(refs: string[], prefix: string): string[] {
952
956
 
953
957
  /**
954
958
  * The directory of the state branch a handed-off Ticket's transcripts are kept
955
- * in, named like its State file without the extension, so the two sort together.
959
+ * in, named like its state file without the extension, so the two sort together.
956
960
  */
957
961
  function transcriptsDir(ticket: number): string {
958
962
  return `ticket-${ticket}`;
@@ -0,0 +1,77 @@
1
+ import { spawnSync } from "node:child_process";
2
+ import { readFileSync } from "node:fs";
3
+
4
+ /**
5
+ * Whether a process, or a process group, is still alive.
6
+ *
7
+ * `process.kill(id, 0)` alone would not say: it still succeeds on a zombie, a
8
+ * process that is dead but not yet reaped, and a killed orphan stays one until
9
+ * the machine's init reaps it, which on a cloud Host takes seconds and in a
10
+ * PID namespace whose init never reaps takes forever. The kill and the tests
11
+ * of it both judge by this.
12
+ */
13
+
14
+ /**
15
+ * Whether the process is alive: running, sleeping or stopped. A zombie is not,
16
+ * though it can still be signalled. Where its state cannot be read at all, the
17
+ * signal's answer stands.
18
+ */
19
+ export function alive(pid: number): boolean {
20
+ if (!signalled(pid)) return false;
21
+ const state = stateOf(pid);
22
+ if (state === null) return true;
23
+ return state !== undefined && !isDead(state);
24
+ }
25
+
26
+ /**
27
+ * Whether any process in the group is alive, by the same judgement. Where the
28
+ * process table cannot be read, the signal's answer stands.
29
+ */
30
+ export function groupAlive(pgid: number): boolean {
31
+ if (!signalled(-pgid)) return false;
32
+ const listed = spawnSync("ps", ["-A", "-o", "pgid=,stat="], { encoding: "utf8" });
33
+ if (listed.error !== undefined || listed.status !== 0) return true;
34
+ return listed.stdout.split("\n").some((line) => {
35
+ const [group, state] = line.trim().split(/\s+/);
36
+ return Number(group) === pgid && state !== undefined && !isDead(state);
37
+ });
38
+ }
39
+
40
+ /** Whether a signal 0 reaches anything; a negative id is a process group. */
41
+ function signalled(id: number): boolean {
42
+ try {
43
+ process.kill(id, 0);
44
+ return true;
45
+ } catch {
46
+ return false;
47
+ }
48
+ }
49
+
50
+ /** Zombie, or on Linux dead and on its way out of the table. */
51
+ function isDead(state: string): boolean {
52
+ return state.startsWith("Z") || state.startsWith("X");
53
+ }
54
+
55
+ /**
56
+ * The process's state letters, read from `/proc` where there is one and from
57
+ * `ps` where there is not; `undefined` once it has left the process table, and
58
+ * `null` when there is neither to ask.
59
+ */
60
+ function stateOf(pid: number): string | undefined | null {
61
+ let stat: string;
62
+ try {
63
+ stat = readFileSync(`/proc/${pid}/stat`, "utf8");
64
+ } catch {
65
+ return stateFromPs(pid);
66
+ }
67
+ // `pid (comm) state ...`, where comm may itself hold spaces and parentheses.
68
+ return stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[0];
69
+ }
70
+
71
+ /** The state `ps` prints for the process, nothing once it has gone, `null` without `ps`. */
72
+ function stateFromPs(pid: number): string | undefined | null {
73
+ const listed = spawnSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" });
74
+ if (listed.error !== undefined) return null;
75
+ const state = listed.stdout.trim();
76
+ return listed.status === 0 && state !== "" ? state : undefined;
77
+ }
@@ -1,5 +1,6 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { readFileSync, readdirSync } from "node:fs";
3
+ import { alive, groupAlive } from "./liveness.js";
3
4
 
4
5
  /**
5
6
  * Killing a command together with everything it started.
@@ -207,17 +208,13 @@ function signal(tree: Tree, name: NodeJS.Signals): void {
207
208
  for (const pid of tree.pids) send(pid, name);
208
209
  }
209
210
 
211
+ /** A zombie is gone: what is left of it waits only on its parent to reap it. */
210
212
  function anyAlive(tree: Tree): boolean {
211
- return [...tree.groups].some((group) => alive(-group)) || [...tree.pids].some(alive);
212
- }
213
-
214
- /** A negative id is a process group. */
215
- function alive(id: number): boolean {
216
- return send(id, 0);
213
+ return [...tree.pids].some(alive) || [...tree.groups].some(groupAlive);
217
214
  }
218
215
 
219
216
  /** Whether the signal reached anything; one already gone is not an error here. */
220
- function send(id: number, name: NodeJS.Signals | 0): boolean {
217
+ function send(id: number, name: NodeJS.Signals): boolean {
221
218
  try {
222
219
  process.kill(id, name);
223
220
  return true;
@@ -4,11 +4,11 @@ import { fileURLToPath } from "node:url";
4
4
  import { exec } from "./exec.js";
5
5
 
6
6
  /**
7
- * Which Version this copy of the pipeline is (ADR-0007).
7
+ * Which version this copy of the pipeline is (ADR-0007).
8
8
  *
9
9
  * Computed once, in the CLI, and handed to the Run and to `init` the way the
10
10
  * run id is. Nothing downstream asks again: every line one Run stamps — its
11
- * summary, each Progress comment, each State file, the file beside its
11
+ * summary, each progress comment, each state file, the file beside its
12
12
  * transcripts — has to say the same thing, and the only way to promise that is
13
13
  * to read it once.
14
14
  *
@@ -26,7 +26,7 @@ export const PACKAGE_ROOT = fileURLToPath(new URL("../..", import.meta.url));
26
26
  const UNKNOWN = "unknown";
27
27
 
28
28
  /**
29
- * The Version, as everything this Run writes will report it.
29
+ * The version, as everything this Run writes will report it.
30
30
  *
31
31
  * An installed copy is its number and nothing else, because a machine installs
32
32
  * a tag: two machines that say `0.4.0` run the same code. A development
@@ -45,7 +45,7 @@ export async function pipelineVersion(packageRoot: string = PACKAGE_ROOT): Promi
45
45
  * its package, and undefined where the package names none or names one this
46
46
  * cannot read.
47
47
  *
48
- * The one thing a Run has to know to ask whether a newer Version is out. It is
48
+ * The one thing a Run has to know to ask whether a newer version is out. It is
49
49
  * read from the package rather than written down here for the same reason the
50
50
  * number is: an installed copy and a checkout answer the same way, and a fork
51
51
  * asks about itself (ADR-0007).
@@ -66,7 +66,7 @@ export function pipelineRepository(packageRoot: string = PACKAGE_ROOT): string |
66
66
  return match?.[1];
67
67
  }
68
68
 
69
- /** The number in `package.json`, which is the whole of an installed Version. */
69
+ /** The number in `package.json`, which is the whole of an installed version. */
70
70
  function packageNumber(packageRoot: string): string {
71
71
  const version = packageField(packageRoot, "version");
72
72
  return typeof version === "string" && version !== "" ? version : UNKNOWN;
package/src/branch.ts CHANGED
@@ -33,7 +33,7 @@ export function worktreePath(repoRoot: string, ticket: number): string {
33
33
  }
34
34
 
35
35
  /**
36
- * The gitignored worktree a Check runs in at a merge-base with the Base branch,
36
+ * The gitignored worktree a Check runs in at a merge-base with the base branch,
37
37
  * beside the Tickets' own: named for the commit, shortened as git shortens one.
38
38
  */
39
39
  export function baseWorktreePath(repoRoot: string, commit: string): string {
package/src/cli.ts CHANGED
@@ -38,10 +38,10 @@ async function main(argv: string[]): Promise<number> {
38
38
  }
39
39
 
40
40
  // Resolved once, here, and handed to everything that stamps it the way the
41
- // run id is: a Run whose summary, comments, State files and transcripts all
41
+ // run id is: a Run whose summary, comments, state files and transcripts all
42
42
  // read it separately could report four different things (ADR-0007).
43
43
  const version = await pipelineVersion();
44
- // The repository a newer Version would be published on, read from the same
44
+ // The repository a newer version would be published on, read from the same
45
45
  // package the number came from, so a fork asks about itself (ADR-0007).
46
46
  const repository = pipelineRepository();
47
47
  if (commandLine.kind === "version") {
package/src/config.ts CHANGED
@@ -172,7 +172,7 @@ const LABEL_DEFAULTS: Labels = {
172
172
  * from package.json when the config does not name them.
173
173
  *
174
174
  * Throws {@link ConfigError} naming the offending field when the file is
175
- * unusable; a missing file is not an error. `version` is the Version doing the
175
+ * unusable; a missing file is not an error. `version` is the version doing the
176
176
  * refusing, which the message for an unknown key carries.
177
177
  */
178
178
  export function loadConfig(repoRoot: string, version: string): Config {
@@ -208,12 +208,12 @@ export function loadConfig(repoRoot: string, version: string): Config {
208
208
  }
209
209
 
210
210
  /**
211
- * Why the file was refused, and — for an unknown key — which Version refused it.
211
+ * Why the file was refused, and — for an unknown key — which version refused it.
212
212
  *
213
213
  * The schema is strict, so a key this install has never heard of is refused by
214
214
  * name. That is the right answer to a typo and a confusing one to a key a newer
215
- * Version added, and on a machine running a stale install the two look exactly
216
- * the same. So the Version is said out loud, and the config file itself is left
215
+ * version added, and on a machine running a stale install the two look exactly
216
+ * the same. So the version is said out loud, and the config file itself is left
217
217
  * without one to carry (ADR-0007).
218
218
  */
219
219
  function refusal(error: z.ZodError, version: string): string {