CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

tessl/factory

Skills that Tessl factory loops run: implement a Linear, GitHub or Jira issue as a pull request, shepherd that pull request through review and checks, wake the shepherd for pull requests that a push to their base branch left in conflict, and keep the work in step when a person stops, ends, answers or closes it.

Quality

86%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Medium

Suggest reviewing before use

Overview
Quality
Evals
Security
Files

issue-active.mjsskills/implement-linear/scripts/

#!/usr/bin/env node
// Says whether a Linear issue is still Tessl's to work on: delegated to the
// Tessl app (this run's Linear viewer), in a state of type unstarted or
// started, and not a take-back Linear undid: its newest move out of backlog
// or triage was made by the Tessl app and no person has changed its state
// since. Linear's GitHub integration moves an issue to a started state when a
// pull request for it opens and records the Tessl app as the actor, so that
// move leaves a person's take-back standing until a person moves the issue
// again. A move with no actor is another automation, such as a triage rule,
// and does not count.
// Run it in the same command as a write, `node issue-active.mjs <issue id> &&
// <write>`, so a person who took the issue back stops the write.
// Exit 0: still Tessl's. Exit 3: a person has stopped the work (the reason is
// printed). Exit 1: the issue could not be read, after retrying transient
// failures (the HTTP status or error kind is printed). Exit 2: usage.
import { pathToFileURL } from 'node:url';

export const ACTIVE_STATE_TYPES = ['unstarted', 'started'];
export const PARKED_STATE_TYPES = ['backlog', 'triage'];

/**
 * The newest history entry that moved the issue out of backlog or triage, or
 * null when there is none.
 */
export function newestMoveOutOfParked(history) {
  return (
    (history ?? [])
      .filter((entry) => PARKED_STATE_TYPES.includes(entry?.fromState?.type))
      .sort((a, b) =>
        String(b.createdAt).localeCompare(String(a.createdAt)),
      )[0] ?? null
  );
}

/** The verdict for a GraphQL `data` holding `viewer { id }` and the issue. */
export function verdict(data) {
  const issue = data?.issue;
  const viewer = data?.viewer?.id;
  if (!issue || !viewer || typeof issue.state?.type !== 'string')
    return { code: 1, reason: 'could not read the issue' };
  const name = issue.identifier ?? 'the issue';
  if (issue.delegate?.id !== viewer)
    return { code: 3, reason: `${name} is no longer delegated to Tessl` };
  if (!ACTIVE_STATE_TYPES.includes(issue.state.type))
    return {
      code: 3,
      reason: `${name} is ${issue.state.name} (${issue.state.type}), so Tessl has stopped`,
    };
  const history = issue.history?.nodes;
  if (!Array.isArray(history))
    return { code: 1, reason: 'could not read the issue history' };
  const move = newestMoveOutOfParked(history);
  const personMovedSince =
    move &&
    history.some(
      (entry) =>
        entry?.fromState?.type &&
        String(entry.createdAt) > String(move.createdAt) &&
        entry.actor?.id &&
        entry.actor.id !== viewer,
    );
  if (move && move.actor?.id === viewer && !personMovedSince)
    return {
      code: 3,
      reason: `${name} was taken back to ${move.fromState.type}; Linear, not a person, moved it out again`,
    };
  return {
    code: 0,
    reason: `${name} is ${issue.state.name}, delegated to Tessl`,
  };
}

/** The GraphQL endpoint under a Linear API base URL, with or without `/graphql`. */
export function graphqlUrl(base) {
  const url = base.replace(/\/+$/, '');
  return url.endsWith('/graphql') ? url : `${url}/graphql`;
}

const QUERY =
  'query($id: String!, $after: String) { viewer { id } issue(id: $id) { identifier state { name type } delegate { id } history(first: 50, after: $after) { nodes { createdAt actor { id } fromState { type } } pageInfo { hasNextPage endCursor } } } }';

/** Thrown for a failure worth retrying; `detail` is what the exit 1 line says. */
class Transient extends Error {}

/** Why a read failed, for the exit 1 line. */
const unreadable = (detail) => ({
  code: 1,
  reason: `could not read the issue: ${detail}`,
});

/**
 * Reads every history page once. Returns a verdict, with the type of the
 * state it read when it read one, or throws `Transient`.
 * Each request, its body included, gets `timeoutMs` or what is left before
 * `deadline`, whichever is less.
 */
async function readOnce(id, { base, token, fetchImpl, timeoutMs, deadline }) {
  const history = [];
  const cursors = new Set();
  let after;
  for (;;) {
    const remaining = Math.min(timeoutMs, deadline - Date.now());
    if (remaining <= 0) throw new Transient('timeout');
    const signal = AbortSignal.timeout(remaining);
    let response;
    let body;
    try {
      response = await fetchImpl(graphqlUrl(base), {
        method: 'POST',
        headers: {
          authorization: `Bearer ${token}`,
          'content-type': 'application/json',
        },
        body: JSON.stringify({ query: QUERY, variables: { id, after } }),
        signal,
      });
    } catch (error) {
      const kind = error?.name === 'TimeoutError' ? 'timeout' : 'network error';
      throw new Transient(kind);
    }
    const status = response.status;
    if (status >= 500 || status === 429) throw new Transient(`HTTP ${status}`);
    try {
      body = await response.json();
    } catch {
      if (signal.aborted) throw new Transient('timeout');
      if (response.ok === false) return unreadable(`HTTP ${status}`);
      throw new Transient('unreadable response body');
    }
    if (response.ok === false) return unreadable(`HTTP ${status}`);
    if (body?.errors?.length) return unreadable('GraphQL error');
    const data = body?.data;
    const page = data?.issue?.history;
    const info = page?.pageInfo;
    if (!Array.isArray(page?.nodes) || typeof info?.hasNextPage !== 'boolean')
      return verdict(null);
    history.push(...page.nodes);
    if (!info.hasNextPage)
      return {
        ...verdict({
          ...data,
          issue: { ...data.issue, history: { nodes: history } },
        }),
        stateType: data.issue.state?.type,
      };
    if (
      typeof info.endCursor !== 'string' ||
      !info.endCursor ||
      cursors.has(info.endCursor)
    )
      return verdict(null);
    cursors.add(info.endCursor);
    after = info.endCursor;
  }
}

/**
 * Reads the issue from Linear and returns its verdict, with the type of the
 * state it read when it read one. A transient failure
 * (HTTP 5xx or 429, a network error, a timeout) restarts the whole read from
 * the first history page after a backoff, until `totalMs` has passed or
 * `attempts` reads have failed; any other answer ends it at once. `totalMs`
 * bounds the requests in flight as well as the backoffs. `fetchImpl`
 * defaults to the global `fetch` and `sleep` to a timer.
 */
export async function checkIssue(
  id,
  {
    base,
    token,
    fetchImpl = fetch,
    attempts = 4,
    backoffMs = 1000,
    timeoutMs = 15000,
    totalMs = 60000,
    sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
  },
) {
  const deadline = Date.now() + totalMs;
  let detail = 'unknown error';
  for (let attempt = 1; attempt <= attempts; attempt += 1) {
    try {
      return await readOnce(id, {
        base,
        token,
        fetchImpl,
        timeoutMs,
        deadline,
      });
    } catch (error) {
      if (!(error instanceof Transient)) return unreadable('unexpected error');
      detail = error.message;
    }
    const wait = backoffMs * 2 ** (attempt - 1);
    if (attempt === attempts || Date.now() + wait >= deadline) break;
    await sleep(wait);
  }
  return unreadable(`${detail}, after retrying`);
}

async function main() {
  const id = process.argv[2];
  if (!id) {
    console.error('usage: node issue-active.mjs <issue id>');
    process.exit(2);
  }
  const { LINEAR_API_URL: base, LINEAR_TOKEN: token } = process.env;
  if (!base || !token) {
    console.error('LINEAR_API_URL and LINEAR_TOKEN must be set');
    process.exit(1);
  }
  const { code, reason } = await checkIssue(id, { base, token });
  (code === 0 ? console.log : console.error)(reason);
  process.exit(code);
}

if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) await main();

README.md

tile.json