Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 60 additions & 1 deletion coderhelm-jira/src/issues.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,54 @@ function jqlFor(query) {
return `text ~ "${words}" ORDER BY updated DESC`;
}

/**
* The account ids an Atlassian document mentions (`@Name` nodes), each once,
* in reading order. A mention is a node of type "mention" whose `attrs.id`
* is the person's account id.
*/
function adfMentions(node, out = []) {
if (!node || typeof node !== "object") return out;
if (node.type === "mention" && node.attrs && typeof node.attrs.id === "string" && node.attrs.id) {
if (!out.includes(node.attrs.id)) out.push(node.attrs.id);
}
for (const child of Array.isArray(node.content) ? node.content : []) adfMentions(child, out);
return out;
}

/**
* The account id in a Jira user object, or "" when there is none. Jira user
* objects carry `accountId`; anything else (an old payload) has no id.
*/
function accountIdOf(user) {
return (user && typeof user.accountId === "string" && user.accountId) || "";
}

/**
* The JQL for "what is waiting on this person": the open issues assigned to
* them, most important and newest change first; and the open issues they
* watch or reported that changed lately (where they may be asked something).
* The account id is checked to be an account id, so it can't end the string.
*/
function mineJql(accountId) {
const id = String(accountId || "");
if (!/^[A-Za-z0-9:-]{8,128}$/.test(id)) return null;
return {
assigned: `assignee = "${id}" AND statusCategory != Done ORDER BY priority DESC, updated DESC`,
involved: `(watcher = "${id}" OR reporter = "${id}") AND statusCategory != Done AND updated >= -14d ORDER BY updated DESC`,
};
}

/** One issue as CoderHelm reads it, from the issue REST API's shape. */
function issueOf(raw, links) {
const f = (raw && raw.fields) || {};
const comments = ((f.comment && f.comment.comments) || [])
.slice(-MAX_ISSUE_COMMENTS)
.map((c) => ({
author: (c.author && c.author.displayName) || "",
// Who wrote it and who it mentions, as account ids, so CoderHelm can
// tell a question to a person they haven't answered yet.
author_id: accountIdOf(c.author),
mentions: adfMentions(c.body),
created: c.created || "",
text: adfText(c.body).trim().slice(0, MAX_COMMENT_CHARS),
}));
Expand All @@ -50,8 +91,13 @@ function issueOf(raw, links) {
summary: f.summary || "",
type: (f.issuetype && f.issuetype.name) || "",
status: (f.status && f.status.name) || "",
// "new", "indeterminate" or "done": where the status sits in the workflow.
status_category: (f.status && f.status.statusCategory && f.status.statusCategory.key) || "",
assignee: (f.assignee && f.assignee.displayName) || "",
assignee_id: accountIdOf(f.assignee),
reporter_id: accountIdOf(f.reporter),
priority: (f.priority && f.priority.name) || "",
due: f.duedate || "",
updated: f.updated || "",
created: f.created || "",
comments,
Expand All @@ -63,4 +109,17 @@ function issueOf(raw, links) {
};
}

module.exports = { adfText, jqlFor, issueOf, MAX_SEARCH, MAX_ISSUE_COMMENTS, MAX_COMMENT_CHARS };
/** The most issues one "what is waiting on me" read returns, of each kind. */
const MAX_MINE = 15;

module.exports = {
adfText,
adfMentions,
jqlFor,
mineJql,
issueOf,
MAX_SEARCH,
MAX_MINE,
MAX_ISSUE_COMMENTS,
MAX_COMMENT_CHARS,
};
63 changes: 60 additions & 3 deletions coderhelm-jira/src/release.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

const api = require("@forge/api");
const { storage, route } = api;
const { jqlFor, issueOf, MAX_SEARCH } = require("./issues");
const { jqlFor, mineJql, issueOf, MAX_SEARCH, MAX_MINE } = require("./issues");

const json = (statusCode, obj) => ({
statusCode,
Expand All @@ -24,7 +24,9 @@ async function authorized(body) {

/** One issue with its remote links; null when it can't be read. */
async function readIssue(key) {
const res = await api.asApp().requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,priority,updated,created,comment`);
const res = await api
.asApp()
.requestJira(route`/rest/api/3/issue/${key}?fields=summary,issuetype,status,assignee,reporter,priority,duedate,updated,created,comment`);
if (!res.ok) return null; // unknown key / no access → dropped
const raw = await res.json();
let links = [];
Expand All @@ -37,17 +39,72 @@ async function readIssue(key) {
return issueOf(raw, links);
}

/** The issue keys a JQL search finds (up to `max`), or [] when it can't run. */
async function keysFor(jql, max) {
const res = await api.asApp().requestJira(route`/rest/api/3/search/jql`, {
method: "POST",
headers: { Accept: "application/json", "Content-Type": "application/json" },
body: JSON.stringify({ jql, maxResults: max, fields: ["summary"] }),
});
if (!res.ok) return { keys: [], ok: false };
const found = await res.json();
return { keys: ((found && found.issues) || []).map((i) => i.key).filter(Boolean).slice(0, max), ok: true };
}

/** Reads issues by key, a few at a time, skipping any that can't be read. */
async function readIssues(keys) {
const issues = [];
for (let i = 0; i < keys.length; i += 5) {
const batch = await Promise.all(keys.slice(i, i + 5).map((k) => readIssue(k).catch(() => null)));
issues.push(...batch.filter(Boolean));
}
return issues;
}

/**
* The "what is waiting on me" read: the open issues assigned to the person,
* and the open ones they watch or reported that changed in the last two
* weeks (CoderHelm reads those for questions to them they haven't answered).
*/
async function mineHandler(mine) {
// CoderHelm sends the person's account id (from the Jira events it has
// seen); the app reads no user directory, so it needs no user scope.
const accountId = String((mine && mine.account_id) || "");
const jql = mineJql(accountId);
if (!jql) {
return json(200, { issues: [], mine: { found: false, why: "no Jira account id was sent" } });
}
const assigned = await keysFor(jql.assigned, MAX_MINE);
// Watchers can be hidden from the app; then only assigned issues are read.
const involved = await keysFor(jql.involved, MAX_MINE).catch(() => ({ keys: [], ok: false }));
const keys = [...new Set([...assigned.keys, ...involved.keys])];
return json(200, {
issues: await readIssues(keys),
mine: {
found: true,
account_id: accountId,
assigned: assigned.keys,
assigned_read: assigned.ok,
involved_read: involved.ok,
},
});
}

/**
* POST { forge_secret, keys: ["ABC-1", ...] } or { forge_secret, query: "words" }
* or { forge_secret, mine: { account_id?, email? } }
* → { issues: [{key, summary, type, status, assignee, priority, updated, created, comments, links}] }
*
* By keys: each issue the app can read (release notes, Chat). By query: the
* issues whose text matches, newest change first (Chat's ticket lookup).
* issues whose text matches, newest change first (Chat's ticket lookup). By
* mine: what is waiting on one person (Chat's "what needs me"), with a `mine`
* object that says whose it is; an older app version leaves `mine` out.
*/
exports.getIssuesHandler = async (request) => {
try {
const body = JSON.parse(request.body || "{}");
if (!(await authorized(body))) return json(403, { error: "forbidden" });
if (body.mine && typeof body.mine === "object") return await mineHandler(body.mine);
let keys = (Array.isArray(body.keys) ? body.keys : [])
.filter((k) => /^[A-Z][A-Z0-9]+-\d+$/.test(k))
.slice(0, 50);
Expand Down
36 changes: 35 additions & 1 deletion coderhelm-jira/test/issues.test.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
const { test } = require("node:test");
const assert = require("node:assert/strict");
const { adfText, jqlFor, issueOf } = require("../src/issues");
const { adfText, adfMentions, jqlFor, mineJql, issueOf } = require("../src/issues");

const doc = (text) => ({ type: "doc", version: 1, content: [{ type: "paragraph", content: [{ type: "text", text }] }] });

Expand Down Expand Up @@ -36,3 +36,37 @@ test("an issue carries its status, people, dates, newest comments and https link
assert.deepEqual(i.links, [{ title: "PR #5", url: "https://github.com/acme/web/pull/5" }]);
assert.equal(adfText(doc("hi")).trim(), "hi");
});

test("mentions and account ids come with each comment, for questions a person hasn't answered", () => {
const mention = (id, text) => ({ type: "mention", attrs: { id, text } });
const body = {
type: "doc",
content: [{ type: "paragraph", content: [mention("acc-dana-0001", "@Dana"), { type: "text", text: " can you confirm?" }, mention("acc-dana-0001", "@Dana")] }],
};
const i = issueOf({
key: "ABC-8",
fields: {
summary: "Pick the retry limit",
status: { name: "To Do", statusCategory: { key: "new" } },
assignee: { accountId: "acc-dana-0001", displayName: "Dana" },
reporter: { accountId: "acc-sam-0002", displayName: "Sam" },
duedate: "2026-11-20",
comment: { comments: [{ author: { accountId: "acc-sam-0002", displayName: "Sam" }, created: "c1", body }] },
},
});
assert.equal(i.status_category, "new");
assert.equal(i.assignee_id, "acc-dana-0001");
assert.equal(i.reporter_id, "acc-sam-0002");
assert.equal(i.due, "2026-11-20");
assert.equal(i.comments[0].author_id, "acc-sam-0002");
assert.deepEqual(i.comments[0].mentions, ["acc-dana-0001"]);
assert.deepEqual(adfMentions(null), []);
});

test("the waiting-on-me JQL takes only an account id, never more clauses", () => {
const q = mineJql("557058:0a1b2c3d-1111-2222-3333-444455556666");
assert.match(q.assigned, /^assignee = "557058:0a1b2c3d-1111-2222-3333-444455556666" AND statusCategory != Done/);
assert.match(q.involved, /watcher = .* OR reporter = /);
assert.equal(mineJql('x" OR project = SECRET'), null);
assert.equal(mineJql(""), null);
});
1 change: 1 addition & 0 deletions services/common/src/agent_policy/registry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -233,6 +233,7 @@ pub const BUILTIN: &[(&str, Risk)] = &[
("work_runs", Risk::Read),
("work_findings", Risk::Read),
("work_records", Risk::Read),
("work_needs_me", Risk::Read),
// A chat asking the person to connect an account (shows a sign-in card).
("request_sign_in", Risk::Read),
// Plugin runs: the plugin's own skills, and drafts kept in CoderHelm
Expand Down
Loading
Loading