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

take-back.mjsskills/follow-ticket-changes/scripts/

#!/usr/bin/env node
// Does every write of a `taken-back` round on a Linear issue, each only while
// the issue is still taken back: cancels each pending implement or shepherd
// run on the issue and on its Tessl pull request, posts the stop note unless
// Tessl's newest comment on the issue is already that note, and ends each of
// Tessl's open sessions on it with a response. Before each write it reads the
// issue again with `issue-active.mjs`'s verdict, so a person who hands the
// issue back stops every write after that read.
// Exit 0: taken back, and each write was made or warned about on stderr.
// Exit 3: the issue is Tessl's again; nothing more is written.
// Exit 4: the issue is completed, canceled or a duplicate; nothing more is
// written, since the `issue-ended` round handles it.
// Exit 1: the issue could not be read, or a read the writes need failed (a
// `gh` or `tessl` read after retrying); nothing more is written. Exit 2: usage.
// Each write made, and each skipped, is printed on stdout.
import { spawnSync } from 'node:child_process';
import { pathToFileURL } from 'node:url';

import {
  checkIssue,
  graphqlUrl,
} from '../../implement-linear/scripts/issue-active.mjs';

export const ENDED_STATE_TYPES = ['completed', 'canceled', 'duplicate'];
export const NOTE_PREFIX = "Stopped: this issue left Tessl's queue";
export const SESSION_RESPONSE = "Work stopped: the issue left Tessl's queue.";
const SKILLS_TO_CANCEL = /implement|shepherd/;
const CLOSED_SESSION_STATUSES = ['complete', 'error'];
const READ_ATTEMPTS = 3;
const READ_BACKOFF_MS = 1000;

export class Stop extends Error {
  constructor(code, reason) {
    super(reason);
    this.code = code;
  }
}

/** What the issue is now, as an exit code: 3, 4, 1, or 0 while taken back. */
export function takeBackCode({ code, stateType }) {
  if (code === 0) return 3;
  if (code !== 3) return 1;
  return ENDED_STATE_TYPES.includes(stateType) ? 4 : 0;
}

export function note(startState) {
  return `${NOTE_PREFIX}, so Tessl cancelled its runs. To hand it back, delegate it to Tessl and move it to ${startState}.\n\n<!-- tessl-factory -->`;
}

/** The skill name in a run's skillRef: the part after its last `#` or `/`. */
export function skillName(run) {
  const ref = run?.attributes?.config?.skillRef;
  return typeof ref === 'string' ? ref.replace(/.*[#/]/, '') : '';
}

/** The ids of the runs to cancel in a `tessl launch list --json` output. */
export function runsToCancel(list, ownRunId) {
  if (!Array.isArray(list?.data)) return null;
  return list.data
    .filter((run) => typeof run?.id === 'string' && run.id)
    .filter((run) => run.id !== ownRunId)
    .filter((run) => SKILLS_TO_CANCEL.test(skillName(run)))
    .map((run) => run.id);
}

/** The team's first state of type unstarted by position. */
export function startState(states) {
  return (
    [...(states ?? [])]
      .filter((state) => state?.type === 'unstarted')
      .sort((a, b) => a.position - b.position)[0]?.name ?? null
  );
}

/**
 * Whether Tessl's newest top-level comment among `comments` is already the
 * note. Replies in a thread, such as a session's response, are skipped.
 */
export function noteAlreadyPosted(comments, viewer) {
  const newest = comments
    .filter((comment) => comment?.user?.id === viewer)
    .filter((comment) => !comment.parent)
    .sort((a, b) => String(b.createdAt).localeCompare(String(a.createdAt)))[0];
  return Boolean(newest?.body?.trimStart().startsWith(NOTE_PREFIX));
}

/** Tessl's sessions on the issue that are not dismissed, complete or error. */
export function openSessions(sessions, viewer) {
  return sessions
    .filter((session) => session?.appUser?.id === viewer)
    .filter((session) => !session.dismissedAt)
    .filter((session) => !CLOSED_SESSION_STATUSES.includes(session.status))
    .map((session) => session.id);
}

const ISSUE_QUERY =
  'query($id: String!) { viewer { id } issue(id: $id) { id identifier url team { states { nodes { name type position } } } } }';
const COMMENTS_QUERY =
  'query($id: String!, $after: String) { issue(id: $id) { comments(first: 100, after: $after) { nodes { body createdAt user { id } parent { id } } pageInfo { hasNextPage endCursor } } } }';
const SESSIONS_QUERY =
  'query($id: String!, $after: String) { issue(id: $id) { agentSessions(first: 100, after: $after) { nodes { id status dismissedAt appUser { id } } pageInfo { hasNextPage endCursor } } } }';
const COMMENT_MUTATION =
  'mutation($input: CommentCreateInput!) { commentCreate(input: $input) { success } }';
const ACTIVITY_MUTATION =
  'mutation($input: AgentActivityCreateInput!) { agentActivityCreate(input: $input) { success } }';

export function createTakeBack({
  identifier,
  env,
  fetchImpl,
  exec,
  out,
  warn,
  sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
}) {
  const base = env.LINEAR_API_URL;
  const token = env.LINEAR_TOKEN;

  async function graphql(query, variables) {
    const response = await fetchImpl(graphqlUrl(base), {
      method: 'POST',
      headers: {
        authorization: `Bearer ${token}`,
        'content-type': 'application/json',
      },
      body: JSON.stringify({ query, variables }),
    });
    const body = await response.json();
    if (response.ok === false || body.errors?.length || !body.data)
      throw new Error('Linear returned an error');
    return body.data;
  }

  async function paginate(query, field) {
    const nodes = [];
    const cursors = new Set();
    let after;
    for (;;) {
      const page = (await graphql(query, { id: identifier, after }))?.issue?.[
        field
      ];
      const info = page?.pageInfo;
      if (!Array.isArray(page?.nodes) || typeof info?.hasNextPage !== 'boolean')
        throw new Error(`could not read the issue's ${field}`);
      nodes.push(...page.nodes);
      if (!info.hasNextPage) return nodes;
      if (!info.endCursor || cursors.has(info.endCursor))
        throw new Error(`could not page the issue's ${field}`);
      cursors.add(info.endCursor);
      after = info.endCursor;
    }
  }

  // Reads the issue again and throws a Stop unless it is still taken back.
  async function guard() {
    const result = await checkIssue(identifier, {
      base,
      token,
      fetchImpl,
    });
    const code = takeBackCode(result);
    if (code !== 0) throw new Stop(code, result.reason);
  }

  function jsonOnce(command, args) {
    const result = exec(command, args);
    if (result.status !== 0) return null;
    try {
      return JSON.parse(result.stdout);
    } catch {
      return null;
    }
  }

  // Runs a read, retrying with backoff while it fails or prints no JSON.
  async function json(command, args) {
    for (let attempt = 1; ; attempt += 1) {
      const value = jsonOnce(command, args);
      if (value !== null || attempt === READ_ATTEMPTS) return value;
      await sleep(READ_BACKOFF_MS * 2 ** (attempt - 1));
    }
  }

  function readOrStop(value, what) {
    if (value === null || value === undefined)
      throw new Stop(1, `could not read ${what}`);
    return value;
  }

  async function issueFacts() {
    let data;
    try {
      data = await graphql(ISSUE_QUERY, { id: identifier });
    } catch {
      throw new Stop(1, 'could not read the issue');
    }
    const issue = data?.issue;
    const viewer = data?.viewer?.id;
    if (!issue?.id || !issue.url || !viewer)
      throw new Stop(1, 'could not read the issue');
    const start = startState(issue.team?.states?.nodes);
    if (!start) throw new Stop(1, "could not read the team's start state");
    return { issue, viewer, start };
  }

  // The URLs whose pending runs are cancelled: the issue's, and each open
  // pull request from the issue's branch in the home repository with the
  // `tessl` label.
  async function linkedUrls(issue) {
    const branch = `tessl/${issue.identifier.toLowerCase()}`;
    const prs = readOrStop(
      await json('gh', [
        'pr',
        'list',
        '--head',
        branch,
        '--state',
        'open',
        '--label',
        'tessl',
        '--json',
        'url,isCrossRepository',
      ]),
      "the issue's Tessl pull request",
    );
    return [
      ['linear_issue', issue.url],
      ...prs
        .filter((pr) => pr && !pr.isCrossRepository && pr.url)
        .map((pr) => ['github_pr', pr.url]),
    ];
  }

  async function cancelRuns(issue) {
    const ids = new Set();
    for (const [type, url] of await linkedUrls(issue)) {
      const list = await json('tessl', [
        'launch',
        'list',
        '--link-type',
        type,
        '--link-value',
        url,
        '--status',
        'pending',
        '--limit',
        '100',
        '--json',
      ]);
      for (const id of readOrStop(
        runsToCancel(list, env.TESSL_LAUNCH_RUN_ID),
        `the pending runs on ${url}`,
      ))
        ids.add(id);
    }
    for (const id of ids) {
      await guard();
      if (exec('tessl', ['launch', 'cancel', id, '--json']).status === 0)
        out(`cancelled run ${id}`);
      else warn(`could not cancel run ${id}`);
    }
  }

  async function postNote({ issue, viewer, start }) {
    await guard();
    let comments;
    try {
      comments = await paginate(COMMENTS_QUERY, 'comments');
    } catch {
      throw new Stop(1, "could not read the issue's comments");
    }
    if (noteAlreadyPosted(comments, viewer)) {
      out("the note is already Tessl's newest comment; not posted again");
      return;
    }
    await guard();
    try {
      const data = await graphql(COMMENT_MUTATION, {
        input: { issueId: issue.id, body: note(start) },
      });
      if (data.commentCreate?.success !== true) throw new Error();
      out('posted the note');
    } catch {
      warn('could not post the note');
    }
  }

  async function endSessions({ viewer }) {
    let sessions;
    try {
      sessions = await paginate(SESSIONS_QUERY, 'agentSessions');
    } catch {
      warn("could not read the issue's sessions; none ended");
      return;
    }
    for (const id of openSessions(sessions, viewer)) {
      await guard();
      try {
        const data = await graphql(ACTIVITY_MUTATION, {
          input: {
            agentSessionId: id,
            content: { type: 'response', body: SESSION_RESPONSE },
          },
        });
        if (data.agentActivityCreate?.success !== true) throw new Error();
        out(`ended session ${id}`);
      } catch {
        warn(`could not end session ${id}`);
      }
    }
  }

  return async function takeBack() {
    try {
      if (!base || !token)
        throw new Stop(1, 'LINEAR_API_URL and LINEAR_TOKEN must be set');
      if (!env.TESSL_LAUNCH_RUN_ID)
        throw new Stop(1, 'TESSL_LAUNCH_RUN_ID must be set');
      await guard();
      const facts = await issueFacts();
      await cancelRuns(facts.issue);
      await postNote(facts);
      await endSessions(facts);
      return 0;
    } catch (error) {
      if (!(error instanceof Stop)) throw error;
      (error.code === 1 ? warn : out)(error.message);
      return error.code;
    }
  };
}

function exec(command, args) {
  const result = spawnSync(command, args, { encoding: 'utf8' });
  return { status: result.status ?? 1, stdout: result.stdout ?? '' };
}

async function main() {
  const identifier = process.argv[2];
  if (!identifier) {
    console.error('usage: node take-back.mjs <identifier>');
    process.exit(2);
  }
  const takeBack = createTakeBack({
    identifier,
    env: process.env,
    fetchImpl: fetch,
    exec,
    out: (line) => console.log(line),
    warn: (line) => console.error(`warning: ${line}`),
  });
  process.exit(await takeBack());
}

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

README.md

tile.json