Repository navigation
Expand file tree
/
Copy pathdispatch.go
More file actions
578 lines (561 loc) · 30 KB
/
Copy pathdispatch.go
File metadata and controls
578 lines (561 loc) · 30 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
// Package dispatch is the dispatcher. `dispatch run` starts a reconcile loop in
// the foreground, in a terminal the user watches. Events wake it, and each
// cycle runs the TypeScript rules over what Linear, the multiplexer, treehouse and GitHub
// say right now and over what dispatch has already done. A resync every few
// minutes re-reads everything as a backstop, so a failure or a missed event is
// retried.
package dispatch
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"regexp"
"runtime"
"strings"
"time"
"github.com/kapetan-io/dispatch/internal/clock"
"github.com/kapetan-io/dispatch/internal/config"
"github.com/kapetan-io/dispatch/internal/dispatchdb"
"github.com/kapetan-io/dispatch/internal/environment"
"github.com/kapetan-io/dispatch/internal/harness"
"github.com/kapetan-io/dispatch/internal/herdr"
"github.com/kapetan-io/dispatch/internal/httpservice"
"github.com/kapetan-io/dispatch/internal/inbox"
"github.com/kapetan-io/dispatch/internal/launcher"
"github.com/kapetan-io/dispatch/internal/linear"
"github.com/kapetan-io/dispatch/internal/loop"
"github.com/kapetan-io/dispatch/internal/notify"
"github.com/kapetan-io/dispatch/internal/pullrequest"
"github.com/kapetan-io/dispatch/internal/rules"
"github.com/kapetan-io/dispatch/internal/ticketbranch"
"github.com/kapetan-io/dispatch/internal/treehouse"
"github.com/kapetan-io/dispatch/internal/workers"
"github.com/kapetan-io/dispatch/internal/world"
)
// RuleTimeout bounds how long one call of a rule's if and then may run.
type RuleTimeout struct{ If, Then time.Duration }
func (o Options) ruleTimeouts() rules.Timeouts {
return rules.Timeouts{If: o.RuleTimeout.If, Then: o.RuleTimeout.Then, Clock: o.Clock}
}
// Options points the dispatcher at its config, its state and the tools it
// drives. Zero values take the defaults.
type Options struct {
// ConfigPath defaults to ~/.config/dispatch/config.toml.
ConfigPath string
// StateDir holds the lock, the loop's socket and the Stop records. Defaults to
// ~/.local/state/dispatch. Keep it short, because macOS caps a socket path at
// about 104 bytes.
StateDir string
// Linear opens the Linear workspace for an API key. Defaults to Linear's
// GraphQL API.
Linear linear.Connect
// LinearKey overrides LINEAR_API_KEY, the config's api_key_command and its keychain entry.
LinearKey string
// KeyCommandTimeout cuts off, on Clock, an api_key_command that never returns, such as a
// password manager waiting on an unlock prompt. Defaults to 1 minute.
KeyCommandTimeout time.Duration
// Multiplexer is the product that hosts the workers. Defaults to the real adapter for the
// configured host: the installed herdr, hc for the Herdr app, or rex when [plugins.rex] is written.
Multiplexer herdr.Multiplexer
// Treehouse is the pool of trees. Defaults to the installed treehouse.
Treehouse treehouse.Pool
// PullRequests is the GitHub repo's pull requests. Defaults to the installed
// gh, which cuts each call off after 30 seconds so a stalled network can't
// hold up the loop.
PullRequests pullrequest.Repository
// Inbox is the owner's GitHub notifications inbox. Defaults to the installed gh.
Inbox inbox.Inbox
// HTTP reaches the services config.toml names under [http.<name>]. Defaults to
// calling them over HTTP with the token each token_command prints.
HTTP httpservice.Services
// Harnesses are the programs workers can run, by the kind a [harness.<name>] table
// names. Defaults to Claude Code.
Harnesses harness.Registry
// Followers is the sessions following each ticket. Defaults to none, and `dispatch watch` adds to it.
Followers *notify.Followers
// Launcher starts the workers. Defaults to leasing a tree from Treehouse and
// starting the worker in the multiplexer.
Launcher launcher.Launcher
// Dir is the working directory of the command. It is where ticket-hint and repo-settings find the repo they are in, what a relative
// rules directory is relative to, and the directory every child process starts in.
// Defaults to the process's working directory.
Dir string
// Env is every environment variable dispatch reads (HOME, PATH, LINEAR_API_KEY and its own),
// and the environment of every child process it starts, except the claude-shim, which
// replaces itself with the real claude and keeps the process's. Defaults to the process's
// environment.
Env environment.Environment
// LaunchPace is the pause between launcher polls of herdr. Defaults to 1 second.
LaunchPace time.Duration
// RexSocket names the Rex server's socket, for tests that must stay off the user's own Rex
// server. Unset, rex picks its server as it always does.
RexSocket string
// RexPanes is the user's panes on the Rex server, which the pane record hooks and
// `dispatch rex restore` read and type into. Defaults to the installed rex.
RexPanes RexPanes
// RulesDir overrides [dispatch].rules, so tests run the repo's rules/ directory.
RulesDir string
// RuleTimeout cuts off a rule call on Clock. Zero means 1 second for
// an if and 30 seconds for a then.
RuleTimeout RuleTimeout
// LocalLockTimeout is how long `dispatch run` waits for a local ticket database another process
// holds. Defaults to 5 seconds.
LocalLockTimeout time.Duration
// Database holds the test-only hooks of dispatch.db. Zero in production.
Database dispatchdb.Hooks
// LaunchTimeout is how long a launch may take before it is given up on, 25 seconds by default and
// not counting time spent waiting behind another launch into the same repo,
// and ActionTimeout how long every other action may take, 1 minute by default.
LaunchTimeout, ActionTimeout time.Duration
// Clock runs the loop's timers (the resync and history rotation) and every timeout
// below, and stamps ingest times. Defaults to the wall clock.
Clock Clock
Stdin io.Reader
Stdout io.Writer
Stderr io.Writer
}
const usage = `usage: dispatch run
dispatch tick [ticket] [--timeout DURATION]
dispatch cycle
dispatch explain <ticket> [--json]
dispatch replay [--from TIME] [--to TIME] [--rules DIR]
dispatch collect-agent-failures [--from TIME] [--to TIME] [--json]
dispatch state reset [--quiet]
dispatch tell <ticket> "<text>"
dispatch tell <ticket> --turn <at> "<text>"
dispatch turn <ticket> [--json]
dispatch ask
dispatch ticket create|show|list|move|comment|edit|statuses|branch
dispatch rules init|check|test [dir]
dispatch ticket-hint
dispatch repo-settings
dispatch linear-viewer
dispatch claude-shim [CLAUDE ARGS]
dispatch record-stop
dispatch record-start
dispatch record-end
dispatch rex restore [--dry-run]
dispatch wake
dispatch watch <ticket>
dispatch unwatch <ticket>
run start the reconcile loop and run until interrupted (Ctrl-C). Holds the state
directory's lock, so a second run fails
tick ask the running loop to re-read every source now and wait until it has settled,
then print one line per ticket. Exits 3 with "dispatch: not running" when no loop runs
--timeout how long tick waits before it reports what is still pending; defaults to 2m
cycle print what the latest cycle acts on, waits for, holds and has covered, read from history
explain print why dispatch acted on the ticket, read from history: each cycle that changed what
the rules decided for it (a want, wait, hold, throw or dropped event) with what each
rule read, and each receipt. Exits 1 when kept history has no record of the ticket
--json with explain, print one JSON object per line instead of text, each with a "type" of
cycle, http or receipt
replay run the cycles in a stretch of history again over the world and ledger they ran over,
and print "N cycles, N match" and exit 0, or print the first difference and exit 1.
TIME is RFC 3339, "2006-01-02 15:04" or "15:04" today. With --rules, run the rules in
DIR over the same history, print the first action that differs from the live run and
exit 0. Exits 2 when no cycle could be replayed, because the history was written before it
recorded the world. A segment written before the rule vocabulary was renamed fails to
load its recorded rules, so replay stops there and exits 1; --from a time after the
rename starts past it, and --rules compares correctly only over segments written after it
collect-agent-failures
read the Claude Code transcripts under ~/.claude/projects ($CLAUDE_CONFIG_DIR/projects
when set) and print where agents went wrong in the window, as Markdown tables: tool
calls whose result is an error, grouped by a signature of the tool, the program and the
error's first line (or, after "Exit code N", its first diagnostic line) with paths,
numbers and ids replaced, leaving out signatures seen once; permission denials; each
denial a subagent hit, with whether its final report names it and what it did next;
files one agent or session edited successfully 5 or more times; and, for the PRs the
gh user wrote that merged in the window into a repo the config lists, fix chains (a
later merged PR that changed lines an earlier merged PR wrote within 30 days, printing
only reverts and Bug tickets where the earlier PR wrote at least half the deleted lines)
and the existing Go tests each PR changed, each PR with the session whose gh pr create
made it, else the one session that ran on its branch, else "not proven" or "not on
disk". It fetches each clone and otherwise only reads it. --to defaults to now and
--from to 7 days before --to. TIME is RFC 3339, "2006-01-02 15:04", "15:04" today or a
date such as 2026-11-13, which means the start of that day. --json prints the same
rows as JSON, with every fix chain and whether it passes the rule. Leaves out the
pattern miner's own sessions, and skips a transcript it cannot read with a line on
stderr. Reports rows: the fix chain table filters on the rule above, and calls no
chain a regression
state reset start a new history segment with an empty ledger, keeping what the world remembers.
With --quiet, record the messages the first cycle wants as sent, so none is repeated.
Exits 1 while dispatch run holds the lock
tell send text to the ticket's worker as a message to its session, through the running loop; fails
with nothing sent when the worker is blocked, reports no status, has no session id yet or its
session is not open. With --turn <at>, where at is the time dispatch turn printed, as RFC 3339
with milliseconds (2026-11-14T06:40:00.123Z), it
delivers at most once for that turn, and the checks run in this order: today's refusals
(exit 1); a repeat of the same turn prints "already told" and sends nothing (exit 0); no
turn that ended at <at> (exit 1); the worker moved past the turn, because its session took
a message after it or ended a later turn (exit 1); the worker is working, or its harness
can't say whether it took a message (exit 1); otherwise it prints "told <ticket>"
turn print the turn the ticket's worker waits at and its closing message, through the running
loop, and never wait. Plain output is the line "<ticket> turn <at>", where at is the
turn's end as RFC 3339 UTC with milliseconds (2026-11-14T06:40:00.123Z), then the message as the worker wrote it.
With --json, print {"ticket","at","message","cut"}, where cut is true when the message was
longer than 64 KiB and is shortened. Exits 1 with nothing printed on stdout when the ticket has
no worker, its worker is in a turn (working, took a message after its latest Stop, or left a
background task running), is blocked on a question, has ended no turn yet, its latest turn has
no closing message, or dispatch cannot read the multiplexer. Exits 3 with "dispatch: not running" when no loop runs
ask run by a worker that needs the user: tell the running dispatch this session is waiting on
an answer. Its workspace shows 🔴 once it is idle, until the session takes a message or
ends, and each follower of its ticket is told once. Moves no ticket. Prints "asked. Say
why in chat and end your turn." and exits 0, also when the session's ask is already
open, which records nothing more. Takes no arguments. Finds its tree from the working
directory and its session from the harness (CLAUDE_CODE_SESSION_ID for Claude Code),
and exits 1 outside a harness session or a tree a worker runs in. Exits 3 with
"dispatch: not running" when no loop runs
review review start <ticket> <head> reports that this session is reviewing the ticket's PR at
head, 7 to 40 hex digits of its head commit, and prints "reviewing <ticket> at <head>".
While the PR is at that head, the start is under an hour old and the worker is gone,
unconfirmed, or idle with a Stop that says it is waiting, an In Review ticket's
workspace shows 🔍. review done <ticket> ends the ticket's review, whoever started it,
and prints "review of <ticket> done", or exits 1 with "dispatch: <ticket> has no
review". A later start replaces the earlier one. Exits 1 on bad arguments and 3 with
"dispatch: not running" when no loop runs, recording nothing
ticket file, read and change tickets. Local tickets (LOC-<n>) are kept in a database that only
dispatch run opens and that [plugins.local] turns on. Talks to the running dispatch run, and
exits 3 with "dispatch: not running" when none runs. create, edit and branch work on Linear
tickets as well, and the other verbs on local tickets only; Linear tickets use the Linear tools
for those.
There is no delete.
create SYSTEM --repo LABEL --title TEXT [--description TEXT] [--label NAME]... [--attr KEY=VALUE]...
[--status NAME] [--parent LOC-N] [--blocked-by LOC-N]... [--start-pr NUMBER] [--team KEY]
SYSTEM is linear, or local when [plugins.local] is on; there is no default. Prints the
new id. --start-pr starts the ticket's branch at that PR's head. create linear files a
ticket dispatch manages: on the configured team (--team picks one of several), with the
ai label, the repo's label and --label names that exist, assigned to the owner of the
API key, and waiting in Todo or the paused status --status names. It takes no --parent,
--blocked-by or --start-pr. --attr writes the "## Attributes" section of its description
show LOC-N print the ticket's fields, description and every comment with its author and time
list [--status NAME] [--label NAME]... [--attr KEY=VALUE]... [--all]
one line per ticket, newest first; without --all, finished tickets are left out
move LOC-N STATUS move to the status named STATUS, ignoring case
comment LOC-N TEXT add a comment; its author is the ticket whose tree the command runs in, else you
edit ID [--title TEXT] [--description TEXT] [--repo LABEL] [--add-label NAME]...
[--remove-label NAME]... [--attr KEY=VALUE]... [--unset-attr KEY]... [--parent LOC-N|""]
[--blocked-by LOC-N|""]... [--start-pr NUMBER] changes only what it names; --start-pr 0 clears.
On a Linear ticket dispatch manages, only --attr and --unset-attr work, and they rewrite
the "## Attributes" section of the description and nothing else
statuses list the statuses and the jobs each does
branch ID [NAME | --unstack]
print the branch dispatch records for the ticket's work. With NAME, fetch it and record
it, after a rename by hand; refused when NAME is in neither the clone nor origin or is
another ticket's branch. --unstack ends the ticket's stack record, the last step of a
restack. Never writes to the ticket system
rules init writes the shipped TypeScript rules, check lints them and prints what each wants
now, and test runs their *.test.ts scenarios
ticket-hint print a reminder to use the dispatch:ticket skill when run in a repo listed under
[repos] in the config, or a worktree of one; prints nothing elsewhere.
The plugin's SessionStart hook runs it
repo-settings print the [repos.<label>] table of the configured repo containing the working
directory, every setting at its effective value, in a form the config accepts. Fails
elsewhere
linear-viewer print the id and name of the Linear user who owns dispatch's API key, as one JSON
object, found the way run finds the key
claude-shim run the real claude with the plugin, the cross-session setting and, for a worker's Claude session,
the worker flags added. Claude subcommands and print runs pass through. The claude
shim in scripts/shims runs it
record-stop read a Stop hook's JSON on stdin and report to the running dispatch when the session in
this tree last ended a turn and whether it still has background tasks running.
Finds the session's harness from the terminal the hook runs in: HC_TERMINAL_ID (Herdr app),
HERDR_PANE_ID (herdr TUI) or REX_SESSION with REX_BLOCK (Rex). Drops the report
when no dispatch runs, when none of them is set or the terminal is unlisted or runs
no harness dispatch has an adapter for, and outside a worktree of a repo listed under [repos]. The
plugin's Stop hook runs it
record-start read a SessionStart hook's JSON on stdin and write the pane record of the Rex pane the
session runs in (REX_SESSION with REX_BLOCK): the session, its directory and the
Rex server's instance. Does nothing outside Rex, in a worker, or when Rex does not
answer. The plugin's SessionStart hook runs it, and record-stop writes the same
record for a pane that has none or names another session
record-end read a SessionEnd hook's JSON on stdin and remove the pane record when it names the
ending session and the user quit it. The plugin's SessionEnd hook runs it
rex restore [--dry-run]
after a Rex restart, resume each recorded Claude session in the pane it ran in, by
typing "cd <dir> && claude --resume <session>" into each recorded pane that is at
its shell prompt and whose record is older than the running Rex server. Prints one
line per pane record. Leaves alone a pane that runs a program or holds a worker,
and for a pane Rex did not bring back prints the line to run by hand and drops the
record. --dry-run prints the same and changes nothing. Needs no [plugins.rex]
wake read a Notification or UserPromptSubmit hook's JSON on stdin and ask the running loop
to read the multiplexer again and run a cycle without waiting for it, so the worker's workspace
label follows within seconds. Finds the session's harness from the terminal the hook
runs in: HC_TERMINAL_ID (Herdr app), HERDR_PANE_ID (herdr TUI) or REX_SESSION with
REX_BLOCK (Rex). Does nothing when none of them is set or the terminal is unlisted or
runs no harness dispatch has an adapter for, outside a worktree of a repo listed under
[repos], or when no loop runs. The plugin's Notification and UserPromptSubmit hooks run it
watch make this session follow the ticket, so each notification dispatch sends about
it is also sent to this session as a message through its harness. A session can follow
several tickets, and a ticket can have several followers. Fails outside a session of a
harness dispatch drives (for Claude Code, when CLAUDE_CODE_SESSION_ID is unset), or when
no dispatch is running. Dispatch addresses the session by its id.
Dispatch keeps followers in memory, so run it again after a restart
unwatch stop this session following the ticket; fails when no dispatch is running`
// Run executes one dispatch command. main is a thin wrapper around it.
func Run(ctx context.Context, args []string, opts Options) error {
opts = withDefaults(opts)
if len(args) == 0 {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return errors.New("no command given")
}
switch args[0] {
case "tick":
return tickCommand(ctx, opts, args[1:])
case "cycle":
return cycleCommand(opts)
case "explain":
ticket, asJSON, ok := explainArgs(args[1:])
if !ok {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return errors.New("explain takes a ticket")
}
return explainCommand(opts, ticket, asJSON)
case "replay":
return replayCommand(opts, args[1:])
case "collect-agent-failures":
return collectAgentFailures(ctx, opts, args[1:])
case "state":
return stateCommand(ctx, opts, args[1:])
case "rules":
return rulesCommand(ctx, opts, args[1:])
case "tell":
switch {
case len(args) == 3:
return tellCommand(ctx, opts, loop.Request{Op: loop.OpTell, Ticket: args[1], Text: args[2]})
case len(args) == 5 && args[2] == "--turn":
at, err := workers.ParseTurnTime(args[3])
if err != nil {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return fmt.Errorf("tell --turn takes the time the turn ended as dispatch turn prints it, such as 2026-11-14T06:40:00.123Z, not %q", args[3])
}
return tellCommand(ctx, opts, loop.Request{Op: loop.OpTellTurn, Ticket: args[1], Turn: at, Text: args[4]})
}
_, _ = fmt.Fprintln(opts.Stderr, usage)
return errors.New(`tell takes a ticket and the text to send, or a ticket, --turn, the time the turn ended and the text to send`)
case "turn":
ticket, asJSON, ok := explainArgs(args[1:])
if !ok {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return errors.New("turn takes a ticket")
}
return turnCommand(ctx, opts, ticket, asJSON)
case "ask":
return askCommand(ctx, opts, args[1:])
case "review":
return reviewCommand(ctx, opts, args[1:])
case "ticket":
return ticketCommand(ctx, opts, args[1:])
case "ticket-hint":
return ticketHint(ctx, opts)
case "repo-settings":
return repoSettings(ctx, opts)
case "linear-viewer":
return linearViewer(ctx, opts)
case "claude-shim":
return claudeShim(opts, args[1:])
case "wake":
return wakeLoop(ctx, opts)
case "record-stop":
return recordStop(ctx, opts)
case "record-start":
return recordStart(ctx, opts)
case "record-end":
return recordEnd(opts)
case "rex":
return rexCommand(ctx, opts, args[1:])
case "watch", "unwatch":
if len(args) != 2 {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return fmt.Errorf("%s takes a ticket", args[0])
}
return follow(ctx, opts, args[0] == "watch", strings.ToUpper(args[1]))
case "run":
if len(args) != 1 {
_, _ = fmt.Fprintln(opts.Stderr, usage)
return errors.New("run takes no arguments. The resync interval is [dispatch].resync in the config")
}
return runCommand(ctx, opts)
default:
_, _ = fmt.Fprintln(opts.Stderr, usage)
return fmt.Errorf("unknown command %q", args[0])
}
}
func withDefaults(o Options) Options {
if o.Harnesses == nil {
o.Harnesses = harness.Registry{config.KindClaudeCode: harness.ClaudeCode{Sessions: harness.SessionsDir(o.Env)}}
}
if o.Dir == "" {
o.Dir, _ = os.Getwd()
}
if o.ConfigPath == "" {
o.ConfigPath = o.Env.ExpandHome("~/.config/dispatch/config.toml")
}
if o.StateDir == "" {
o.StateDir = o.Env.ExpandHome("~/.local/state/dispatch")
}
if o.RexPanes == nil {
o.RexPanes = herdr.NewRex(o.StateDir).WithSocket(o.RexSocket).WithEnv(o.Env)
}
if o.Linear == nil {
o.Linear = func(key string) linear.Workspace { return linear.NewClient(linear.DefaultURL, key) }
}
if o.Treehouse == nil {
o.Treehouse = treehouse.NewCLI("treehouse").WithEnv(o.Env)
}
if o.PullRequests == nil {
o.PullRequests = pullrequest.NewCLI("gh", pullrequest.WithEnv(o.Env))
}
if o.Inbox == nil {
o.Inbox = inbox.NewCLI("gh", inbox.WithEnv(o.Env))
}
if o.Clock == nil {
o.Clock = clock.Wall{}
}
if o.Stdin == nil {
o.Stdin = os.Stdin
}
if o.Stdout == nil {
o.Stdout = os.Stdout
}
if o.Stderr == nil {
o.Stderr = os.Stderr
}
return o
}
// findLinearKey tries, in order, Options.LinearKey, LINEAR_API_KEY, the config's
// api_key_command, and the keychain entry named in the config.
func findLinearKey(ctx context.Context, opts Options, cfg config.Config) (string, error) {
if opts.LinearKey != "" {
return opts.LinearKey, nil
}
if env := opts.Env.Get("LINEAR_API_KEY"); env != "" {
return env, nil
}
if cmd := cfg.Plugins.Linear.APIKeyCommand; cmd != "" {
return keyFromCommand(ctx, opts, cmd)
}
if runtime.GOOS != "darwin" {
return "", errors.New("no Linear API key: LINEAR_API_KEY is unset and api_key_command is not set (only macOS has a keychain lookup)")
}
keychain := opts.Env.Command(ctx, "security", "find-generic-password", "-s", cfg.Plugins.Linear.APIKeyKeychain, "-w")
keychain.Dir = opts.Dir
out, err := keychain.Output()
if err != nil {
return "", fmt.Errorf("no Linear API key: LINEAR_API_KEY is unset, api_key_command is not set, and the keychain has no %q entry", cfg.Plugins.Linear.APIKeyKeychain)
}
return strings.TrimSpace(string(out)), nil
}
// keyFromCommand runs command in a shell. Its stderr goes to the user so an
// unlock prompt is visible, and its stdout is never echoed into an error.
func keyFromCommand(ctx context.Context, opts Options, command string) (string, error) {
timeout := opts.KeyCommandTimeout
if timeout <= 0 {
timeout = time.Minute
}
ctx, cancel := clock.WithTimeout(ctx, opts.Clock, "api_key_command", timeout)
defer cancel()
cmd := opts.Env.Command(ctx, "sh", "-c", command)
cmd.Dir = opts.Dir
cmd.Stderr = opts.Stderr
// A process the command started can hold stdout open after sh is killed.
cmd.WaitDelay = time.Second
out, err := cmd.Output()
if errors.Is(ctx.Err(), context.DeadlineExceeded) {
return "", fmt.Errorf("no Linear API key: api_key_command %q timed out after %s", command, timeout)
}
if err != nil {
return "", fmt.Errorf("no Linear API key: api_key_command %q failed: %w", command, err)
}
key := strings.TrimSpace(string(out))
if key == "" {
return "", fmt.Errorf("no Linear API key: api_key_command %q printed nothing (exit status 0)", command)
}
return key, nil
}
// linearViewer prints the owner of the API key, so skills can assign tickets
// without handling the key.
func linearViewer(ctx context.Context, opts Options) error {
cfg, err := loadConfig(opts)
if err != nil {
return err
}
key, err := findLinearKey(ctx, opts, cfg)
if err != nil {
return err
}
viewer, err := opts.Linear(key).Viewer(ctx)
if err != nil {
return err
}
return json.NewEncoder(opts.Stdout).Encode(viewer)
}
// follow makes the calling session start or stop following a ticket, through the
// harness the session runs.
func follow(ctx context.Context, opts Options, watch bool, ticket string) error {
if !ticketID.MatchString(ticket) {
return fmt.Errorf("%q is not a ticket identifier such as ENG-123", ticket)
}
kind, address, err := opts.Harnesses.Follower(opts.Env)
if err != nil {
return err
}
op, verb := loop.OpUnwatch, "unwatching"
if watch {
op, verb = loop.OpWatch, "watching"
}
resp, err := loop.Ask(ctx, opts.StateDir, loop.Request{Op: op, Ticket: ticket, Follower: ¬ify.Follower{Kind: kind, Address: address}})
if errors.Is(err, loop.ErrNotRunning) {
return notRunning()
}
if err != nil {
return err
}
if resp.Error != "" {
return errors.New(resp.Error)
}
_, _ = fmt.Fprintf(opts.Stdout, "%s %s\n", verb, ticket)
return nil
}
// ticketID is the shape of a Linear identifier.
var ticketID = regexp.MustCompile(`^[A-Z][A-Z0-9]*-[0-9]+$`)
// abs makes a relative path relative to the command's working directory.
func (o Options) abs(path string) string {
if path == "" || filepath.IsAbs(path) {
return path
}
return filepath.Join(o.Dir, path)
}
// loadConfig reads the config, accepting the harness kinds dispatch drives.
func loadConfig(opts Options) (config.Config, error) {
cfg, err := config.Load(opts.ConfigPath, opts.Env, opts.Harnesses.Kinds())
// The local tickets live in dispatch.db, and a file at the path the key names would be ignored silently.
if err == nil && cfg.Plugins.Local.Path != "" {
return config.Config{}, fmt.Errorf("while reading config %s: [plugins.local] path is gone: move %s to %s, then remove the key",
opts.ConfigPath, cfg.Plugins.Local.Path, dispatchdb.Path(opts.StateDir))
}
return cfg, err
}
// sources are the tools one read goes through. The inbox is wired only while a loaded rule runs
// over it, so an owner with no inbox rule makes no gh call for it and a failing gh login costs them nothing.
func sources(opts Options, cfg config.Config, lin linear.Workspace, loaded *rules.Rules, rows *workers.Store, branches *ticketbranch.Store) world.Sources {
src := world.Sources{
Linear: lin, Multiplexer: opts.Multiplexer, Treehouse: opts.Treehouse, PullRequests: opts.PullRequests,
Env: opts.Env, StateDir: opts.StateDir, Stderr: opts.Stderr,
}
// A nil *Store assigned directly would make src.Workers a non-nil interface.
if rows != nil {
src.Workers = rows
}
if branches != nil {
src.Branches = branches
}
src.LocalOn = cfg.Plugins.Local.On
if loaded.RunsOver("inbox") {
src.Inbox = opts.Inbox
}
return src
}