1#!/usr/bin/env node
2const child_process = require("node:child_process");
3const fs = require("node:fs");
4const path = require("node:path");
5const process = require("node:process");
6
7const TEAM_KEY = "ALPHA";
8const API_URL = "https://api.linear.app/graphql";
9const API_KEY_PATH = path.join(process.env.HOME ?? "", ".config", "linear-api-key");
10const ISSUE_ID_RE = /^ALPHA-\d+$/i;
11const WORK_REPO_RE = /^\d+$/;
12const OPEN_STATE_TYPES = ["triage", "backlog", "unstarted", "started"];
13const OPEN_STATE_TYPE_SET = new Set(OPEN_STATE_TYPES);
14
15const OPEN_ALPHA_FILTER = {
16 team: { key: { eq: TEAM_KEY } },
17 state: { type: { in: OPEN_STATE_TYPES } },
18};
19
20const SEARCH_ISSUES = `
21 query SearchAlphaIssues(
22 $term: String!
23 $filter: IssueFilter
24 $first: Int!
25 $includeComments: Boolean!
26 ) {
27 searchIssues(
28 term: $term
29 filter: $filter
30 first: $first
31 includeArchived: false
32 includeComments: $includeComments
33 ) {
34 nodes {
35 id
36 identifier
37 title
38 url
39 priority
40 priorityLabel
41 description
42 createdAt
43 updatedAt
44 labelIds
45 state {
46 id
47 name
48 type
49 }
50 team {
51 id
52 key
53 name
54 }
55 }
56 }
57 }
58`;
59
60const ISSUE_QUERY = `
61 query AlphaIssue($id: String!) {
62 issue(id: $id) {
63 id
64 identifier
65 title
66 url
67 priority
68 priorityLabel
69 description
70 createdAt
71 updatedAt
72 labelIds
73 labels(first: 50) {
74 nodes {
75 id
76 name
77 }
78 }
79 state {
80 id
81 name
82 type
83 }
84 team {
85 id
86 key
87 name
88 }
89 }
90 }
91`;
92
93main().catch((error) => {
94 const message = error instanceof Error ? error.message : String(error);
95 console.error(`error: ${message}`);
96 process.exit(1);
97});
98
99async function main() {
100 const [command, ...argv] = process.argv.slice(2);
101
102 if (!command || command === "-h" || command === "--help") {
103 usage(0);
104 }
105
106 if (command === "search") {
107 const options = parseSearchArgs(argv);
108 assertWorkRepo();
109 await search(options);
110 } else if (command === "issue") {
111 const options = parseIssueArgs(argv);
112 assertWorkRepo();
113 await showIssue(options);
114 } else if (command === "jj") {
115 await runJj(argv);
116 } else if (command === "prompt") {
117 const event = JSON.parse(fs.readFileSync(0, "utf8"));
118 if (event.hook_event_name !== "UserPromptSubmit" || event.agent_id) {
119 return;
120 }
121 const messages = await startIssues(event.prompt, true);
122 if (messages.length > 0) {
123 writeJson({
124 hookSpecificOutput: {
125 hookEventName: "UserPromptSubmit",
126 additionalContext: messages.join("\n"),
127 },
128 });
129 }
130 } else {
131 throw new Error(`unknown command ${JSON.stringify(command)}`);
132 }
133}
134
135async function runJj([executable, ...argv]) {
136 const context = [];
137 const operation = [];
138 const revisions = [];
139 let command;
140 let positional = false;
141
142 for (let i = 0; i < argv.length; i++) {
143 const arg = argv[i];
144 const option = arg.split("=", 1)[0];
145 if (positional) {
146 revisions.push(arg);
147 continue;
148 }
149 if (arg === "--") {
150 positional = true;
151 continue;
152 }
153 if (
154 [
155 "-R",
156 "--repository",
157 "--config",
158 "--config-file",
159 "--color",
160 "--at-op",
161 "--at-operation",
162 ].includes(option)
163 ) {
164 const value = arg.includes("=") ? [] : [argv[++i]];
165 if (
166 ["-R", "--repository", "--config", "--config-file"].includes(option)
167 ) {
168 context.push(arg, ...value);
169 } else if (["--at-op", "--at-operation"].includes(option)) {
170 operation.push(arg, ...value);
171 }
172 } else if (arg.startsWith("-R") && arg.length > 2) {
173 context.push(arg);
174 } else if (arg === "-m" || arg === "--message") {
175 i++;
176 } else if (arg.startsWith("-r") && arg.length > 2) {
177 revisions.push(arg.slice(2).replace(/^=/, ""));
178 } else if (!arg.startsWith("-")) {
179 if (command) {
180 revisions.push(arg);
181 } else {
182 command = arg;
183 }
184 }
185 }
186
187 const describe = ["desc", "describe"].includes(command) &&
188 !argv.some((arg) =>
189 ["-h", "--help", "--no-integrate-operation"].includes(arg)
190 );
191
192 function readJj(args) {
193 const result = child_process.spawnSync(executable, [
194 ...context,
195 "--ignore-working-copy",
196 "--no-pager",
197 "--color=never",
198 ...args,
199 ], { encoding: "utf8", maxBuffer: 16 * 1024 * 1024 });
200 if (result.error || result.status !== 0) {
201 throw result.error ?? new Error(result.stderr.trim());
202 }
203 return result.stdout.trim();
204 }
205
206 let changes;
207 let hookError;
208 if (describe) {
209 try {
210 const revset = revisions.length > 0
211 ? revisions.map((revision) => `(${revision.replace(/^all:/, "")})`)
212 .join(" | ")
213 : "@";
214 changes = readJj([
215 ...operation,
216 "log",
217 "--no-graph",
218 "-r",
219 revset,
220 "-T",
221 'change_id ++ "\\n"',
222 ])
223 .split("\n").filter(Boolean);
224 } catch (error) {
225 hookError = error;
226 }
227 }
228
229 const result = child_process.spawnSync(executable, argv, {
230 stdio: "inherit",
231 });
232 if (result.error) {
233 throw result.error;
234 }
235 if (result.signal) {
236 process.kill(process.pid, result.signal);
237 return;
238 }
239 if (result.status !== 0 || !describe) {
240 process.exitCode = result.status;
241 return;
242 }
243
244 try {
245 if (hookError) {
246 throw hookError;
247 }
248 if (changes.length === 0) {
249 return;
250 }
251
252 const revset = changes.map((id) => `change_id("${id}")`).join(" | ");
253 const descriptions = readJj([
254 "log",
255 "--no-graph",
256 "-r",
257 revset,
258 "-T",
259 "description",
260 ]);
261 for (const message of await startIssues(descriptions)) {
262 console.error(message);
263 }
264 } catch (error) {
265 console.error(`linear: could not read the description: ${error.message}`);
266 }
267}
268
269async function startIssues(text, onlyUnclaimed = false) {
270 const prefixesPath = path.join(
271 process.env.XDG_CONFIG_HOME || path.join(process.env.HOME, ".config"),
272 "agent-linear",
273 "prefixes",
274 );
275 let prefixes;
276 try {
277 prefixes = new Set(
278 fs.readFileSync(prefixesPath, "utf8").toUpperCase().split(/\r?\n/)
279 .map((prefix) => prefix.trim()).filter(Boolean),
280 );
281 } catch (error) {
282 if (error.code === "ENOENT") {
283 return [];
284 }
285 throw error;
286 }
287
288 const issues = new Set(
289 [...text.matchAll(
290 /(?<![a-z0-9_-])[a-z][a-z0-9]*-\d+(?![a-z0-9_-]|\.\d)/gi,
291 )]
292 .map((match) => match[0].toUpperCase())
293 .filter((id) => prefixes.has(id.split("-", 1)[0])),
294 );
295
296 const messages = [];
297 let viewer;
298
299 for (const id of issues) {
300 try {
301 const data = await linearRequest(
302 `
303 query IssueProgress($id: String!) {
304 issue(id: $id) {
305 id
306 state { name }
307 assignee { id }
308 team { states { nodes { id name type } } }
309 }
310 }
311 `,
312 { id },
313 );
314 if (!data.issue) {
315 throw new Error(`${id} not found`);
316 }
317 if (
318 !/^(todo|backlog)$/i.test(data.issue.state?.name ?? "") ||
319 (onlyUnclaimed && data.issue.assignee)
320 ) {
321 continue;
322 }
323
324 const state = data.issue.team.states.nodes.find((state) =>
325 state.name.toLowerCase() === "in progress" && state.type === "started"
326 );
327 if (!state) {
328 throw new Error(`${id}'s team has no In Progress state`);
329 }
330
331 const input = { stateId: state.id };
332 if (!data.issue.assignee) {
333 viewer ??= (await linearRequest("{ viewer { id name } }", {})).viewer;
334 input.assigneeId = viewer.id;
335 }
336
337 const updated = await linearRequest(
338 `
339 mutation StartIssue($id: String!, $input: IssueUpdateInput!) {
340 issueUpdate(id: $id, input: $input) { success }
341 }
342 `,
343 { id: data.issue.id, input },
344 );
345 if (!updated.issueUpdate.success) {
346 throw new Error(`${id} was not updated`);
347 }
348 const assignment = input.assigneeId ? `, assigned to ${viewer.name}` : "";
349 messages.push(`linear: ${id} → In Progress${assignment}`);
350 } catch (error) {
351 messages.push(
352 `linear: could not start ${id}: ${error.message}. Send the issue again or run jj desc to retry.`,
353 );
354 }
355 }
356 return messages;
357}
358
359async function search(options) {
360 const found = new Map();
361
362 for (const query of options.queries) {
363 const data = await linearRequest(SEARCH_ISSUES, {
364 term: query,
365 filter: OPEN_ALPHA_FILTER,
366 first: options.limit,
367 includeComments: options.includeComments,
368 });
369
370 for (const issue of data.searchIssues.nodes) {
371 if (!isOpenIssue(issue)) {
372 continue;
373 }
374
375 const existing = found.get(issue.identifier);
376 if (existing) {
377 existing.matchedQueries.push(query);
378 } else {
379 found.set(issue.identifier, { ...issue, matchedQueries: [query] });
380 }
381 }
382 }
383
384 const issues = [...found.values()];
385 if (options.json) {
386 writeJson({ team: TEAM_KEY, queries: options.queries, issues: issues.map(issueJson) });
387 return;
388 }
389
390 if (issues.length === 0) {
391 console.log("no open alpha issues matched");
392 return;
393 }
394
395 for (const issue of issues) {
396 console.log(formatIssue(issue));
397 }
398}
399
400async function showIssue(options) {
401 const issue = await fetchIssue(options.issueId);
402 if (options.json) {
403 writeJson(issueJson(issue));
404 return;
405 }
406 console.log(formatIssue(issue, { includeLabels: true, fullDescription: true }));
407}
408
409async function fetchIssue(issueId) {
410 const id = normalizeIssueId(issueId);
411 const data = await linearRequest(ISSUE_QUERY, { id });
412 if (!data.issue) {
413 throw new Error(`${id} not found`);
414 }
415 if (data.issue.team?.key !== TEAM_KEY) {
416 throw new Error(`${id} belongs to ${data.issue.team?.key ?? "unknown"}, expected ${TEAM_KEY}`);
417 }
418 assertOpenIssue(data.issue);
419 return data.issue;
420}
421
422async function linearRequest(query, variables) {
423 const apiKey = readLinearApiKey();
424 if (!apiKey) {
425 throw new Error(`Linear API key is required in ${API_KEY_PATH} or LINEAR_API_KEY`);
426 }
427
428 const response = await fetch(API_URL, {
429 method: "POST",
430 headers: {
431 Authorization: apiKey,
432 "Content-Type": "application/json",
433 },
434 body: JSON.stringify({ query, variables }),
435 signal: AbortSignal.timeout(10000),
436 });
437
438 const body = await response.text();
439 let json;
440 try {
441 json = JSON.parse(body);
442 } catch {
443 throw new Error(`Linear returned non-JSON response (${response.status})`);
444 }
445
446 if (!response.ok) {
447 throw new Error(`Linear HTTP ${response.status}: ${body.slice(0, 500)}`);
448 }
449 if (json.errors?.length > 0) {
450 throw new Error(json.errors.map((error) => error.message).join("; "));
451 }
452
453 return json.data;
454}
455
456function readLinearApiKey() {
457 const envKey = process.env.LINEAR_API_KEY?.trim();
458 if (envKey) {
459 return envKey;
460 }
461
462 if (!process.env.HOME) {
463 return "";
464 }
465
466 try {
467 return fs.readFileSync(API_KEY_PATH, "utf8").trim();
468 } catch (error) {
469 if (error?.code === "ENOENT") {
470 return "";
471 }
472 throw error;
473 }
474}
475
476function parseSearchArgs(argv) {
477 const options = { json: false, limit: 8, includeComments: false, queries: [] };
478
479 while (argv.length > 0) {
480 const arg = argv.shift();
481 if (arg === "-h" || arg === "--help") {
482 searchUsage(0);
483 } else if (arg === "--json") {
484 options.json = true;
485 } else if (arg === "--comments") {
486 options.includeComments = true;
487 } else if (arg === "--limit") {
488 options.limit = parseLimit(argv.shift());
489 } else if (arg === "--") {
490 options.queries.push(...argv);
491 break;
492 } else if (arg.startsWith("-")) {
493 throw new Error(`unknown search option ${JSON.stringify(arg)}`);
494 } else {
495 options.queries.push(arg);
496 }
497 }
498
499 if (options.queries.length === 0 && !process.stdin.isTTY) {
500 options.queries.push(...fs.readFileSync(0, "utf8").split(/\r?\n/));
501 }
502
503 options.queries = options.queries.map((query) => query.trim()).filter(Boolean);
504 if (options.queries.length === 0) {
505 searchUsage(1);
506 }
507
508 return options;
509}
510
511function parseIssueArgs(argv) {
512 const options = { json: false, issueId: undefined };
513
514 while (argv.length > 0) {
515 const arg = argv.shift();
516 if (arg === "-h" || arg === "--help") {
517 issueUsage(0);
518 } else if (arg === "--json") {
519 options.json = true;
520 } else if (arg.startsWith("-")) {
521 throw new Error(`unknown issue option ${JSON.stringify(arg)}`);
522 } else if (!options.issueId) {
523 options.issueId = arg;
524 } else {
525 throw new Error(`unexpected issue argument ${JSON.stringify(arg)}`);
526 }
527 }
528
529 if (!options.issueId) {
530 issueUsage(1);
531 }
532
533 options.issueId = normalizeIssueId(options.issueId);
534 return options;
535}
536
537function assertWorkRepo() {
538 const result = child_process.spawnSync("jj", ["workspace", "root"], { encoding: "utf8" });
539 if (result.error || result.status !== 0) {
540 throw new Error("agent-linear must run inside a jj workspace");
541 }
542
543 const root = result.stdout.trim();
544 const home = process.env.HOME;
545 const relative = home ? path.relative(path.join(home, "dev"), root) : "";
546 if (!home || path.isAbsolute(relative) || relative.startsWith("..") || !WORK_REPO_RE.test(relative)) {
547 throw new Error(`agent-linear only runs from a numbered work repo under ~/dev, current workspace is ${root}`);
548 }
549}
550
551function normalizeIssueId(issueId) {
552 if (!ISSUE_ID_RE.test(issueId)) {
553 throw new Error(`expected an ${TEAM_KEY}-123 issue id, got ${JSON.stringify(issueId)}`);
554 }
555 return issueId.toUpperCase();
556}
557
558function parseLimit(value) {
559 const limit = Number(value);
560 if (!Number.isInteger(limit) || limit < 1 || limit > 25) {
561 throw new Error("--limit must be an integer from 1 to 25");
562 }
563 return limit;
564}
565
566function assertOpenIssue(issue) {
567 if (!isOpenIssue(issue)) {
568 throw new Error(`${issue.identifier} is closed (${issue.state?.name ?? "unknown"}/${issue.state?.type ?? "unknown"})`);
569 }
570}
571
572function isOpenIssue(issue) {
573 return OPEN_STATE_TYPE_SET.has(issue.state?.type);
574}
575
576function issueJson(issue) {
577 return {
578 id: issue.id,
579 identifier: issue.identifier,
580 title: issue.title,
581 url: issue.url,
582 state: issue.state ? { name: issue.state.name, type: issue.state.type } : null,
583 priority: issue.priority,
584 priorityLabel: issue.priorityLabel,
585 labels: issue.labels?.nodes?.map((label) => label.name) ?? undefined,
586 labelIds: issue.labelIds ?? [],
587 matchedQueries: issue.matchedQueries,
588 description: issue.description,
589 createdAt: issue.createdAt,
590 updatedAt: issue.updatedAt,
591 };
592}
593
594function formatIssue(issue, options = {}) {
595 const lines = [
596 `${issue.identifier} [${issue.state?.name ?? "unknown"}/${issue.state?.type ?? "unknown"}] ${issue.title}`,
597 ` ${issue.url}`,
598 ];
599 if (issue.priorityLabel) {
600 lines.push(` priority: ${issue.priorityLabel}`);
601 }
602 if (issue.matchedQueries) {
603 lines.push(` matched: ${issue.matchedQueries.join(" | ")}`);
604 }
605 if (options.includeLabels && issue.labels?.nodes?.length > 0) {
606 lines.push(` labels: ${issue.labels.nodes.map((label) => label.name).join(", ")}`);
607 }
608
609 if (options.fullDescription) {
610 const description = (issue.description ?? "").trim();
611 if (description) {
612 lines.push(" desc:");
613 lines.push(...description.split(/\r?\n/).map((line) => ` ${line}`));
614 }
615 } else {
616 const description = excerpt(issue.description);
617 if (description) {
618 lines.push(` desc: ${description}`);
619 }
620 }
621
622 return `${lines.join("\n")}\n`;
623}
624
625function excerpt(value) {
626 return (value ?? "").replace(/\s+/g, " ").trim().slice(0, 320);
627}
628
629function writeJson(value) {
630 process.stdout.write(`${JSON.stringify(value, null, 2)}\n`);
631}
632
633function usage(code) {
634 const stream = code === 0 ? process.stdout : process.stderr;
635 stream.write(`usage: agent-linear <command> [options]\n`);
636 stream.write(`\n`);
637 stream.write(`commands:\n`);
638 stream.write(` search search open ALPHA Linear issues\n`);
639 stream.write(` issue show one open ALPHA issue\n`);
640 stream.write(`\n`);
641 stream.write(`api key: ~/.config/linear-api-key or LINEAR_API_KEY\n`);
642 stream.write(`scope: only runs from numbered work repos under ~/dev\n`);
643 stream.write(`auto-start prefixes: $XDG_CONFIG_HOME/agent-linear/prefixes (default: ~/.config/agent-linear/prefixes)\n`);
644 stream.write(`one prefix per line, e.g. ALPHA; missing or empty disables auto-start in Claude, Codex, and jj desc\n`);
645 process.exit(code);
646}
647
648function searchUsage(code) {
649 const stream = code === 0 ? process.stdout : process.stderr;
650 stream.write(`usage: agent-linear search [--json] [--comments] [--limit n] <query>...\n`);
651 stream.write(`\n`);
652 stream.write(`each query is sent to Linear searchIssues with open ALPHA issue filters\n`);
653 process.exit(code);
654}
655
656function issueUsage(code) {
657 const stream = code === 0 ? process.stdout : process.stderr;
658 stream.write(`usage: agent-linear issue [--json] <ALPHA-123>\n`);
659 process.exit(code);
660}