CtrlK
BlogDocsLog inGet started
Tessl Logo
PluginPublic

tessl/factory

Skills that Tessl factory loops run: implement a Linear or GitHub 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

87%

Does it follow best practices?

Run evals on this skill

Adds up to 20 points to the overall score

View guide
SecuritybySnyk

Low

Low-risk findings worth noting

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. 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 } } } }';

/**
 * Reads the issue from Linear and returns its verdict. `fetchImpl` defaults to
 * the global `fetch`.
 */
export async function checkIssue(id, { base, token, fetchImpl = fetch }) {
  try {
    const history = [];
    const cursors = new Set();
    let after;
    for (;;) {
      const response = await fetchImpl(graphqlUrl(base), {
        method: 'POST',
        headers: {
          authorization: `Bearer ${token}`,
          'content-type': 'application/json',
        },
        body: JSON.stringify({ query: QUERY, variables: { id, after } }),
      });
      const body = await response.json();
      if (response.ok === false || body.errors?.length) return verdict(null);
      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 } },
        });
      if (
        typeof info.endCursor !== 'string' ||
        !info.endCursor ||
        cursors.has(info.endCursor)
      )
        return verdict(null);
      cursors.add(info.endCursor);
      after = info.endCursor;
    }
  } catch {
    return verdict(null);
  }
}

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