@kana-ai/edgar-ext-linear 0.1.1 → 0.1.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -24,9 +24,22 @@ export const createCardTool = {
24
24
  input: z.object({ spec: cardSpec, parent: z.string().min(1).exactOptional() }),
25
25
  output: z.object({ id: z.string(), url: z.string() }),
26
26
  };
27
- /** The input and output of `release_follow_ups`. */
27
+ /** The input and output of `park`. */
28
+ export const parkTool = {
29
+ input: z.object({ card: z.string().min(1), waits_for: z.string().min(1) }),
30
+ output: z.object({ id: z.string() }),
31
+ };
32
+ /** Where `release_follow_ups` moves the cards that wait for a card. */
33
+ export const followUpColumn = z.enum(["ready", "waiting_on_person"]);
34
+ /** The input and output of `release_follow_ups`. A close with no merge holds the waiting cards for a person, as a merge releases them. */
28
35
  export const releaseFollowUpsTool = {
29
- input: z.object({ card: z.string().min(1), pull_request: z.string().min(1) }),
36
+ input: z.object({
37
+ card: z.string().min(1),
38
+ pull_request: z.string().min(1),
39
+ column: followUpColumn
40
+ .exactOptional()
41
+ .describe("where the waiting cards move: ready, the default, after a merge; waiting_on_person after a close with no merge"),
42
+ }),
30
43
  output: z.object({ released: z.array(z.string()) }),
31
44
  };
32
45
  /** The input and output of `update_description` and of its lookup, `find_description`. */
@@ -123,6 +136,16 @@ export const batchCardsTool = {
123
136
  .describe("the ids of `only` that are not open cards of the batch; absent when none is"),
124
137
  }),
125
138
  };
139
+ /** The input and output of `set_priority`. */
140
+ export const setPriorityTool = {
141
+ input: z.object({
142
+ card: z.string().min(1),
143
+ priority: z
144
+ .enum(["urgent", "high", "medium", "low"])
145
+ .describe("the priority from EDGAR's analysis; a card that has one already keeps it"),
146
+ }),
147
+ output: z.object({ id: z.string() }),
148
+ };
126
149
  /** The input and output of `count_sighting`. */
127
150
  export const countSightingTool = {
128
151
  input: z.object({
@@ -145,3 +168,19 @@ export const handBackTool = {
145
168
  .describe("the id of the user the card was assigned to before, or an empty text for nobody"),
146
169
  }),
147
170
  };
171
+ /** The input and output of `retitle`. */
172
+ export const retitleTool = {
173
+ input: z.object({
174
+ card: z.string().min(1),
175
+ text: z
176
+ .string()
177
+ .min(1)
178
+ .describe("a stage's summary of the card; its first sentence becomes the title"),
179
+ }),
180
+ output: z.object({ id: z.string(), title: z.string() }),
181
+ };
182
+ /** The input and output of `mark_seen`. */
183
+ export const markSeenTool = {
184
+ input: z.object({ card: z.string().min(1) }),
185
+ output: z.object({ id: z.string() }),
186
+ };
@@ -2,7 +2,7 @@ import type { Card, CardSpec } from "@kana-ai/edgar-contracts/rpc";
2
2
  import { type Failure, type Outcome, type Result } from "@kana-ai/edgar-sdk";
3
3
  import { z } from "zod";
4
4
  import { type LinearCtx } from "#api/client";
5
- import type { batchCardsTool, findCardsTool } from "#schemas/tools";
5
+ import type { batchCardsTool, findCardsTool, setPriorityTool } from "#schemas/tools";
6
6
  /** The Linear id of the card `card`, or `not_found`. */
7
7
  export declare function issueId(ctx: LinearCtx, card: string): Promise<Result<string, Failure>>;
8
8
  /** The ids of the labels named `names`, the first match per name; a missing name is `invalid`. */
@@ -22,11 +22,15 @@ export declare function readCard(ctx: LinearCtx, id: string): Promise<Outcome<Ca
22
22
  export declare function findCards(ctx: LinearCtx, text: string, except?: string): Promise<Outcome<z.infer<typeof findCardsTool.output>>>;
23
23
  /** At most 20 open cards of the table's team and scope whose block names `batch` in `decided.batch`, with `except` left out; with `assignee_only`, only EDGAR's cards and those handed back. A card whose block does not read is left out. */
24
24
  export declare function batchCards(ctx: LinearCtx, batch: string, except: string, ids?: readonly string[]): Promise<Outcome<z.infer<typeof batchCardsTool.output>>>;
25
+ /** Gives the card `card` the Linear priority of `priority`, unless it has one already, which stays: then `skipped`. */
26
+ export declare function setPriority(ctx: LinearCtx, card: string, priority: z.infer<typeof setPriorityTool.input>["priority"]): Promise<Outcome<{
27
+ id: string;
28
+ }>>;
25
29
  /** Counts one more sighting, at `seen` or now, of the fault that the card `card` holds, for a fault that a run found again without filing a card. */
26
30
  export declare function countSightingOn(ctx: LinearCtx, card: string, seen: string | undefined): Promise<Outcome<{
27
31
  id: string;
28
32
  }>>;
29
- /** Files a card inside the table's scope, or returns the open card that already holds the block's fingerprint. With `assignee_only`, the new card is assigned to `assignee`, so it is in scope from its first sweep. Calls with one fingerprint run one at a time in this process, so the second finds the card the first filed. */
33
+ /** Files a card inside the table's scope, or returns the open card that already holds the block's fingerprint. With no open holder, a card done less than `REOPEN_DAYS` ago that holds it is opened again in `ready`; else the new card links the newest closed holder. With `assignee_only`, the new card is assigned to `assignee`, so it is in scope from its first sweep. Calls with one fingerprint run one at a time in this process, so the second finds the card the first filed. */
30
34
  export declare function createCard(ctx: LinearCtx, spec: CardSpec, parent?: string): Promise<Outcome<{
31
35
  id: string;
32
36
  url: string;
@@ -1,15 +1,23 @@
1
- import { blockLine, done, err, ok, oneAtATime, permanentFailure, readBlock, sighted, withBlock, } from "@kana-ai/edgar-sdk";
1
+ import { blockLine, done, earlierLine, lastNote, err, invalidBlock, ok, oneAtATime, permanentFailure, readBlock, reopenedDescription, reopens, sighted, skipped, withBlock, } from "@kana-ai/edgar-sdk";
2
2
  import { z } from "zod";
3
3
  import { keyOf, linear } from "#api/client";
4
- import { created, heldIssue, idNames, issue, issueFields, oneIssue, oneIssueFields, } from "#schemas/linear";
5
- import { WAITING, assigneeOf, columnOf, isState, settingsOf } from "#tracker/states";
6
- import { update } from "#tracker/transitions";
7
- function toCard(settings, value, strict, assignee) {
4
+ import { created, closedIssue, heldIssue, idNames, issue, issueFields, oneIssue, oneIssueFields, } from "#schemas/linear";
5
+ import { WAITING, assigneeOf, columnOf, isState, settingsOf, trustOf } from "#tracker/states";
6
+ import { transition, update } from "#tracker/transitions";
7
+ /** The card priority of each Linear priority a person sets: 1 is urgent and 2 high; medium, low and none give the card no priority. */
8
+ const priorities = { 1: "urgent", 2: "high" };
9
+ /** The card of an issue; a block that does not read is `invalid` when `strict`, else carried as why, for the engine to refuse. `own` holds the ids of EDGAR's own users, so `taken_by` is the assignee only when the assignee is a person. `taken_by_id` is that person's email, which only their own account can change, so the engine finds their keys by it; a display name any member can set. `trust` is the trust of the card's creator by `trustOf`, and `written_by_id` is the creator's email, as `taken_by_id` is the holder's. */
10
+ function toCard(settings, value, strict, assignee, own) {
8
11
  const description = value.description ?? "";
9
12
  const block = readBlock(description);
10
13
  if (!block.ok && strict)
11
14
  return block.error;
12
15
  const assigned = value.assignee?.displayName;
16
+ const person = own.has(value.assignee?.id ?? "") ? undefined : value.assignee;
17
+ const taken = person?.displayName;
18
+ const takenId = person?.email ?? undefined;
19
+ const writerId = value.creator?.email ?? undefined;
20
+ const priority = priorities[value.priority ?? 0];
13
21
  return done({
14
22
  id: value.identifier,
15
23
  title: value.title,
@@ -17,10 +25,19 @@ function toCard(settings, value, strict, assignee) {
17
25
  column: columnOf(settings, value.state.name, assignee, value.assignee?.id) ?? value.state.name,
18
26
  labels: value.labels.nodes.map((label) => label.name),
19
27
  url: value.url,
20
- block: block.ok ? block.value : null,
28
+ block: block.ok ? block.value : invalidBlock(block.error),
21
29
  ...(assigned === undefined ? {} : { assignee: assigned }),
30
+ ...(taken === undefined ? {} : { taken_by: taken }),
31
+ ...(takenId === undefined ? {} : { taken_by_id: takenId }),
32
+ ...(priority === undefined ? {} : { priority }),
33
+ trust: trustOf(value.creator?.id ?? "", value.creator, own),
34
+ ...(writerId === undefined ? {} : { written_by_id: writerId }),
22
35
  });
23
36
  }
37
+ /** The ids of EDGAR's own users: the `viewer` that a read asked with it, and `[extensions.linear] assignee` when the table needs one. */
38
+ function ownOf(viewer, assignee) {
39
+ return new Set([viewer.id, assignee].flatMap((id) => id ?? []));
40
+ }
24
41
  /** The Linear id of the card `card`, or `not_found`. */
25
42
  export async function issueId(ctx, card) {
26
43
  const found = await linear(ctx, "query IssueId($id: String!) { issue(id: $id) { id } }", { id: card }, z.object({ issue: z.object({ id: z.string() }).nullable() }));
@@ -122,13 +139,14 @@ export async function listCards(ctx, input) {
122
139
  ...(taken === undefined ? {} : { assigned }),
123
140
  ...(user === undefined ? {} : { assignee: user }),
124
141
  };
125
- const listed = await linear(ctx, `query Cards($team: String!, $states: [String!]!, $after: String${params}) { issues(first: 50, after: $after, filter: { team: { key: { eq: $team } }, ${state}${narrow.clauses} }) { nodes { ${issueFields} } pageInfo { hasNextPage endCursor } } }`, {
142
+ const listed = await linear(ctx, `query Cards($team: String!, $states: [String!]!, $after: String${params}) { viewer { id } issues(first: 50, after: $after, filter: { team: { key: { eq: $team } }, ${state}${narrow.clauses} }) { nodes { ${issueFields} } pageInfo { hasNextPage endCursor } } }`, {
126
143
  team: settings.value.team,
127
144
  states: names,
128
145
  after: input.cursor,
129
146
  ...extra,
130
147
  ...narrow.variables,
131
148
  }, z.object({
149
+ viewer: z.object({ id: z.string() }),
132
150
  issues: z.object({
133
151
  nodes: z.array(issue),
134
152
  pageInfo: z.object({ hasNextPage: z.boolean(), endCursor: z.string().nullable() }),
@@ -136,8 +154,9 @@ export async function listCards(ctx, input) {
136
154
  }));
137
155
  if (!listed.ok)
138
156
  return listed.error;
157
+ const own = ownOf(listed.value.viewer, assignee.value);
139
158
  const cards = listed.value.issues.nodes.flatMap((node) => {
140
- const read = toCard(settings.value, node, false, taken);
159
+ const read = toCard(settings.value, node, false, taken, own);
141
160
  return read.outcome === "done" ? [read.output] : [];
142
161
  });
143
162
  const page = listed.value.issues.pageInfo;
@@ -152,7 +171,7 @@ export async function readCard(ctx, id) {
152
171
  const settings = settingsOf(ctx);
153
172
  if (!settings.ok)
154
173
  return settings.error;
155
- const read = await linear(ctx, `query Card($id: String!) { issue(id: $id) { ${oneIssueFields} } }`, { id }, z.object({ issue: oneIssue.nullable() }));
174
+ const read = await linear(ctx, `query Card($id: String!) { viewer { id } issue(id: $id) { ${oneIssueFields} } }`, { id }, z.object({ viewer: z.object({ id: z.string() }), issue: oneIssue.nullable() }));
156
175
  if (!read.ok)
157
176
  return read.error;
158
177
  const found = read.value.issue;
@@ -166,7 +185,7 @@ export async function readCard(ctx, id) {
166
185
  if (settings.value.assignee_only && found.assignee?.id !== assignee.value && !handedBack) {
167
186
  return permanentFailure("not_found", `linear: card ${id} is not assigned to the user of [extensions.linear] assignee`);
168
187
  }
169
- return toCard(settings.value, found, true, assignee.value);
188
+ return toCard(settings.value, found, true, assignee.value, ownOf(read.value.viewer, assignee.value));
170
189
  }
171
190
  const found = z.object({
172
191
  identifier: z.string(),
@@ -280,6 +299,25 @@ async function countSighting(ctx, holder, at) {
280
299
  ctx.log(`sighting not counted on ${holder.identifier}: ${written.error.message}`);
281
300
  return ok(null);
282
301
  }
302
+ /** The Linear priority of each priority EDGAR's analysis gives. */
303
+ const linearPriorities = { urgent: 1, high: 2, medium: 3, low: 4 };
304
+ /** Gives the card `card` the Linear priority of `priority`, unless it has one already, which stays: then `skipped`. */
305
+ export async function setPriority(ctx, card, priority) {
306
+ const read = await linear(ctx, "query Priority($id: String!) { issue(id: $id) { id identifier priority } }", { id: card }, z.object({
307
+ issue: z
308
+ .object({ id: z.string(), identifier: z.string(), priority: z.number().nullish() })
309
+ .nullable(),
310
+ }));
311
+ if (!read.ok)
312
+ return read.error;
313
+ const found = read.value.issue;
314
+ if (found === null)
315
+ return permanentFailure("not_found", `linear: no card ${card}`);
316
+ if ((found.priority ?? 0) !== 0)
317
+ return skipped();
318
+ const set = await update(ctx, found.id, { priority: linearPriorities[priority] });
319
+ return set.ok ? done({ id: found.identifier }) : set.error;
320
+ }
283
321
  /** Counts one more sighting, at `seen` or now, of the fault that the card `card` holds, for a fault that a run found again without filing a card. */
284
322
  export async function countSightingOn(ctx, card, seen) {
285
323
  const read = await linear(ctx, "query Held($id: String!) { issue(id: $id) { id identifier url description } }", { id: card }, z.object({ issue: heldIssue.nullable() }));
@@ -291,22 +329,51 @@ export async function countSightingOn(ctx, card, seen) {
291
329
  const counted = await countSighting(ctx, holder, seen ?? new Date().toISOString());
292
330
  return counted.ok ? done({ id: holder.identifier }) : counted.error;
293
331
  }
294
- /** Files a card inside the table's scope, or returns the open card that already holds the block's fingerprint. With `assignee_only`, the new card is assigned to `assignee`, so it is in scope from its first sweep. Calls with one fingerprint run one at a time in this process, so the second finds the card the first filed. */
332
+ /** Files a card inside the table's scope, or returns the open card that already holds the block's fingerprint. With no open holder, a card done less than `REOPEN_DAYS` ago that holds it is opened again in `ready`; else the new card links the newest closed holder. With `assignee_only`, the new card is assigned to `assignee`, so it is in scope from its first sweep. Calls with one fingerprint run one at a time in this process, so the second finds the card the first filed. */
295
333
  export async function createCard(ctx, spec, parent) {
296
334
  const fingerprint = spec.block.fingerprint;
297
335
  if (fingerprint === undefined)
298
336
  return await fileCard(ctx, spec, parent);
299
337
  return await oneAtATime(`linear:${fingerprint}`, () => fileCard(ctx, spec, parent));
300
338
  }
301
- /** One `create_card` call: the holder search, then the new card. */
302
- async function fileCard(ctx, spec, parent) {
339
+ /** What the newest closed holder of a fingerprint comes to: opened again in `ready` when `reopens`, and answered; else the line that the new card ends with. A holder out of the table's scope is linked, since its column cannot change. */
340
+ async function comeBack(ctx, last, me, at) {
341
+ const closed_at = last.completedAt ?? last.canceledAt ?? at;
342
+ const said = last.comments.nodes.map((c) => ({ text: c.body, at: c.createdAt, by: c.user?.id }));
343
+ const note = lastNote(said, closed_at, (c) => c.by !== undefined && c.by !== me);
344
+ const holder = {
345
+ id: last.identifier,
346
+ url: last.url,
347
+ cancelled: last.canceledAt !== null,
348
+ closed_at,
349
+ ...(note === undefined ? {} : { note }),
350
+ };
351
+ if (!reopens(holder, at))
352
+ return earlierLine(holder);
353
+ const moved = await transition(ctx, last.identifier, "ready", true);
354
+ if (moved.outcome === "skipped")
355
+ return earlierLine(holder);
356
+ if (moved.outcome !== "done")
357
+ return moved;
358
+ const written = await update(ctx, last.id, {
359
+ description: reopenedDescription(last.description ?? "", at),
360
+ });
361
+ return written.ok ? done({ id: last.identifier, url: last.url }) : written.error;
362
+ }
363
+ /** One `create_card` call: the search for the open and the newest closed holder, then the new card. */
364
+ async function fileCard(ctx, asked, parent) {
303
365
  const settings = settingsOf(ctx);
304
366
  if (!settings.ok)
305
367
  return settings.error;
306
368
  const team = settings.value.team;
307
- const fingerprint = spec.block.fingerprint;
369
+ const fingerprint = asked.block.fingerprint;
370
+ let spec = asked;
308
371
  if (fingerprint !== undefined) {
309
- const held = await linear(ctx, `query Holder($team: String!, $text: String!) { issues(first: 1, filter: { team: { key: { eq: $team } }, description: { contains: $text }, state: { type: { nin: ["completed", "canceled"] } } }) { nodes { id identifier url description } } }`, { team, text: blockLine("fingerprint", fingerprint) }, z.object({ issues: z.object({ nodes: z.array(heldIssue) }) }));
372
+ const held = await linear(ctx, `query Holder($team: String!, $text: String!) { viewer { id } issues(first: 1, filter: { team: { key: { eq: $team } }, description: { contains: $text }, state: { type: { nin: ["completed", "canceled"] } } }) { nodes { id identifier url description } } closed: issues(first: 1, orderBy: updatedAt, filter: { team: { key: { eq: $team } }, description: { contains: $text }, state: { type: { in: ["completed", "canceled"] } } }) { nodes { id identifier url description completedAt canceledAt comments(last: 20) { nodes { body createdAt user { id } } } } } }`, { team, text: blockLine("fingerprint", fingerprint) }, z.object({
373
+ viewer: z.object({ id: z.string() }),
374
+ issues: z.object({ nodes: z.array(heldIssue) }),
375
+ closed: z.object({ nodes: z.array(closedIssue) }),
376
+ }));
310
377
  if (!held.ok)
311
378
  return held.error;
312
379
  const [holder] = held.value.issues.nodes;
@@ -315,6 +382,14 @@ async function fileCard(ctx, spec, parent) {
315
382
  const counted = await countSighting(ctx, holder, at);
316
383
  return counted.ok ? done({ id: holder.identifier, url: holder.url }) : counted.error;
317
384
  }
385
+ const [last] = held.value.closed.nodes;
386
+ if (last !== undefined) {
387
+ const at = spec.block.last_seen ?? new Date().toISOString();
388
+ const back = await comeBack(ctx, last, held.value.viewer.id, at);
389
+ if (typeof back === "object")
390
+ return back;
391
+ spec = { ...spec, description: `${spec.description.trimEnd()}\n\n${back}` };
392
+ }
318
393
  }
319
394
  const found = await linear(ctx, "query Team($team: String!) { teams(filter: { key: { eq: $team } }) { nodes { id states { nodes { id name } } } } }", { team }, z.object({
320
395
  teams: z.object({ nodes: z.array(z.object({ id: z.string(), states: idNames })) }),
@@ -1,11 +1,19 @@
1
- import type { Attachment, Comment } from "@kana-ai/edgar-contracts/rpc";
1
+ import type { Attachment, Comment, Mention } from "@kana-ai/edgar-contracts/rpc";
2
2
  import { type Outcome } from "@kana-ai/edgar-sdk";
3
3
  import { type LinearCtx } from "#api/client";
4
+ /** Reacts with eyes to the card as EDGAR's user; Linear answers a repeat with the first reaction, so a retry adds none. */
5
+ export declare function markSeen(ctx: LinearCtx, card: string): Promise<Outcome<{
6
+ id: string;
7
+ }>>;
4
8
  /** Posts a comment keyed by the operation id; a repeat finds the first comment instead of posting twice. */
5
9
  export declare function postComment(ctx: LinearCtx, card: string, body: string): Promise<Outcome<{
6
10
  id: string;
7
11
  }>>;
8
- /** The comments of card `id` since `since`, oldest first, each flagged when it mentions the token's user. */
12
+ /** The comments of card `id` made, edited or deleted since `since`, oldest first, each flagged when it mentions the token's user, with its writer's trust by `trustOf` and email by `authorId`. A deleted comment is an archived one. */
9
13
  export declare function listComments(ctx: LinearCtx, id: string, since: string | null): Promise<Outcome<Comment[]>>;
10
- /** The attachments of card `id`. */
14
+ /** At most 50 comments on any card made after `since` whose body holds `@` and the token user's display name, oldest first: one request for the name and one for the comments. */
15
+ export declare function listMentions(ctx: LinearCtx, since: string): Promise<Outcome<Mention[]>>;
16
+ /** The files uploaded into `bodies` that `listed` does not already hold, once each by url, named by their link text, else by the last part of their url. */
17
+ export declare function uploadsIn(bodies: readonly string[], listed: readonly Attachment[]): Attachment[];
18
+ /** The attachments of card `id`, then the files people uploaded into its live comments. */
11
19
  export declare function listAttachments(ctx: LinearCtx, id: string): Promise<Outcome<Attachment[]>>;
@@ -3,6 +3,18 @@ import { z } from "zod";
3
3
  import { keyOf, linear } from "#api/client";
4
4
  import { attachment, comment } from "#schemas/linear";
5
5
  import { issueId } from "#tracker/cards";
6
+ import { trustOf } from "#tracker/states";
7
+ /** Reacts with eyes to the card as EDGAR's user; Linear answers a repeat with the first reaction, so a retry adds none. */
8
+ export async function markSeen(ctx, card) {
9
+ const made = await linear(ctx, "mutation ReactionCreate($input: ReactionCreateInput!) { reactionCreate(input: $input) { success } }", { input: { issueId: card, emoji: "eyes" } }, z.object({ reactionCreate: z.object({ success: z.boolean() }) }));
10
+ if (!made.ok)
11
+ return made.error;
12
+ return made.value.reactionCreate.success
13
+ ? done({ id: card })
14
+ : permanentFailure("tool_error", "linear ReactionCreate: not applied", {
15
+ cause: "success: false",
16
+ });
17
+ }
6
18
  /** Posts a comment keyed by the operation id; a repeat finds the first comment instead of posting twice. */
7
19
  export async function postComment(ctx, card, body) {
8
20
  const target = await issueId(ctx, card);
@@ -17,10 +29,15 @@ export async function postComment(ctx, card, body) {
17
29
  const earlier = await linear(ctx, "query Comment($id: String!) { comment(id: $id) { id } }", { id }, z.object({ comment: z.object({ id: z.string() }).nullable() }));
18
30
  return earlier.ok && earlier.value.comment !== null ? done({ id }) : made.error;
19
31
  }
20
- /** The comments of card `id` since `since`, oldest first, each flagged when it mentions the token's user. */
32
+ /** A commenter's email as `author_id`, by which the engine finds them in `[people]`; none for an integration or a user Linear gives no email for. */
33
+ function authorId(user) {
34
+ const email = user?.email ?? undefined;
35
+ return email === undefined ? {} : { author_id: email };
36
+ }
37
+ /** The comments of card `id` made, edited or deleted since `since`, oldest first, each flagged when it mentions the token's user, with its writer's trust by `trustOf` and email by `authorId`. A deleted comment is an archived one. */
21
38
  export async function listComments(ctx, id, since) {
22
- const read = await linear(ctx, "query Comments($id: String!, $filter: CommentFilter) { viewer { displayName } issue(id: $id) { comments(first: 100, filter: $filter) { nodes { id body createdAt user { id } botActor { id } } } } }", { id, filter: since === null ? {} : { createdAt: { gt: since } } }, z.object({
23
- viewer: z.object({ displayName: z.string() }),
39
+ const read = await linear(ctx, "query Comments($id: String!, $filter: CommentFilter) { viewer { id displayName } issue(id: $id) { comments(first: 100, filter: $filter, includeArchived: true) { nodes { id body createdAt editedAt archivedAt user { id guest email } botActor { id } } } } }", { id, filter: since === null ? {} : { updatedAt: { gt: since } } }, z.object({
40
+ viewer: z.object({ id: z.string(), displayName: z.string() }),
24
41
  issue: z.object({ comments: z.object({ nodes: z.array(comment) }) }).nullable(),
25
42
  }));
26
43
  if (!read.ok)
@@ -28,25 +45,83 @@ export async function listComments(ctx, id, since) {
28
45
  if (read.value.issue === null)
29
46
  return permanentFailure("not_found", `linear: no card ${id}`);
30
47
  const mention = `@${read.value.viewer.displayName}`;
48
+ const own = new Set([read.value.viewer.id]);
31
49
  const comments = read.value.issue.comments.nodes
32
- .map((node) => ({
33
- id: node.id,
34
- author: node.user?.id ?? node.botActor?.id ?? "",
35
- text: node.body,
36
- at: node.createdAt,
37
- mentioned: node.body.includes(mention),
38
- }))
50
+ .map((node) => {
51
+ const changed = node.archivedAt ?? node.editedAt;
52
+ const author = node.user?.id ?? node.botActor?.id ?? "";
53
+ return {
54
+ id: node.id,
55
+ author,
56
+ text: node.body,
57
+ at: node.createdAt,
58
+ mentioned: node.body.includes(mention),
59
+ ...(changed === null || changed === undefined ? {} : { edited_at: changed }),
60
+ ...(node.archivedAt === null || node.archivedAt === undefined ? {} : { deleted: true }),
61
+ trust: trustOf(author, node.user, own),
62
+ ...authorId(node.user),
63
+ };
64
+ })
39
65
  .sort((a, b) => a.at.localeCompare(b.at));
40
66
  return done(comments);
41
67
  }
42
- /** The attachments of card `id`. */
68
+ /** At most 50 comments on any card made after `since` whose body holds `@` and the token user's display name, oldest first: one request for the name and one for the comments. */
69
+ export async function listMentions(ctx, since) {
70
+ const me = await linear(ctx, "query Viewer { viewer { id displayName } }", {}, z.object({ viewer: z.object({ id: z.string(), displayName: z.string() }) }));
71
+ if (!me.ok)
72
+ return me.error;
73
+ const mention = `@${me.value.viewer.displayName}`;
74
+ const own = new Set([me.value.viewer.id]);
75
+ const read = await linear(ctx, "query Mentions($filter: CommentFilter) { comments(first: 50, filter: $filter) { nodes { id body createdAt user { id guest email } botActor { id } issue { identifier } } } }", { filter: { createdAt: { gt: since }, body: { contains: mention } } }, z.object({
76
+ comments: z.object({
77
+ nodes: z.array(comment.extend({ issue: z.object({ identifier: z.string() }).nullable() })),
78
+ }),
79
+ }));
80
+ if (!read.ok)
81
+ return read.error;
82
+ return done(read.value.comments.nodes
83
+ .flatMap((node) => node.issue === null
84
+ ? []
85
+ : [
86
+ {
87
+ card: node.issue.identifier,
88
+ comment: {
89
+ id: node.id,
90
+ author: node.user?.id ?? node.botActor?.id ?? "",
91
+ text: node.body,
92
+ at: node.createdAt,
93
+ mentioned: true,
94
+ trust: trustOf(node.user?.id ?? node.botActor?.id ?? "", node.user, own),
95
+ ...authorId(node.user),
96
+ },
97
+ },
98
+ ])
99
+ .sort((a, b) => a.comment.at.localeCompare(b.comment.at)));
100
+ }
101
+ /** A file a person uploaded into a comment: a Markdown link or image to Linear's upload host, with its text as the name. */
102
+ const UPLOAD = /!?\[([^\]]*)\]\((https:\/\/uploads\.linear\.app\/[^)\s]+)\)/g;
103
+ /** The files uploaded into `bodies` that `listed` does not already hold, once each by url, named by their link text, else by the last part of their url. */
104
+ export function uploadsIn(bodies, listed) {
105
+ const seen = new Set(listed.map(({ url }) => url));
106
+ const found = [];
107
+ for (const [, text = "", url = ""] of bodies.flatMap((body) => [...body.matchAll(UPLOAD)])) {
108
+ if (seen.has(url))
109
+ continue;
110
+ seen.add(url);
111
+ const name = text.trim() === "" ? (url.split("/").at(-1) ?? url) : text.trim();
112
+ found.push({ id: url, name, url });
113
+ }
114
+ return found;
115
+ }
116
+ /** The attachments of card `id`, then the files people uploaded into its live comments. */
43
117
  export async function listAttachments(ctx, id) {
44
- const read = await linear(ctx, "query Attachments($id: String!) { issue(id: $id) { attachments(first: 50) { nodes { id title url } } } }", { id }, z.object({
118
+ const read = await linear(ctx, "query Attachments($id: String!) { issue(id: $id) { attachments(first: 50) { nodes { id title url } } comments(first: 100) { nodes { body } } } }", { id }, z.object({
45
119
  issue: z
46
120
  .object({
47
121
  attachments: z.object({
48
122
  nodes: z.array(attachment),
49
123
  }),
124
+ comments: z.object({ nodes: z.array(z.object({ body: z.string() })) }),
50
125
  })
51
126
  .nullable(),
52
127
  }));
@@ -54,9 +129,11 @@ export async function listAttachments(ctx, id) {
54
129
  return read.error;
55
130
  if (read.value.issue === null)
56
131
  return permanentFailure("not_found", `linear: no card ${id}`);
57
- return done(read.value.issue.attachments.nodes.map((node) => ({
132
+ const listed = read.value.issue.attachments.nodes.map((node) => ({
58
133
  id: node.id,
59
134
  name: node.title,
60
135
  url: node.url,
61
- })));
136
+ }));
137
+ const bodies = read.value.issue.comments.nodes.map(({ body }) => body);
138
+ return done([...listed, ...uploadsIn(bodies, listed)]);
62
139
  }
@@ -2,7 +2,7 @@ import { defineTracker, done, permanentFailure } from "@kana-ai/edgar-sdk";
2
2
  import { z } from "zod";
3
3
  import { apiAccess, linear } from "#api/client";
4
4
  import { createCard, issueId, labelIds, listCards, readCard } from "#tracker/cards";
5
- import { listAttachments, listComments, postComment } from "#tracker/comments";
5
+ import { listAttachments, listComments, listMentions, postComment } from "#tracker/comments";
6
6
  import { transition, update } from "#tracker/transitions";
7
7
  function asNull(outcome) {
8
8
  return outcome.outcome === "done" ? done(null) : outcome;
@@ -16,6 +16,7 @@ export const tracker = defineTracker({
16
16
  list_cards: async (input, ctx) => await listCards(ctx, input),
17
17
  card: async ({ id }, ctx) => await readCard(ctx, id),
18
18
  comments: async ({ id, since }, ctx) => await listComments(ctx, id, since),
19
+ mentions: async ({ since }, ctx) => await listMentions(ctx, since),
19
20
  attachments: async ({ id }, ctx) => await listAttachments(ctx, id),
20
21
  comment: async ({ card, text }, ctx) => asCreated(await postComment(ctx, card, text)),
21
22
  move: async ({ card, column }, ctx) => asNull(await transition(ctx, card, column)),
@@ -0,0 +1,2 @@
1
+ /** Reads a card of `[extensions.linear] team` that a card or its comments link, for a run's inbox, under the same rules as the tracker's card read: a card out of the scope is a failure. A link to a card of another team, or to anything else in Linear, is not this reader's. */
2
+ export declare const readLink: import("@kana-ai/edgar-sdk").ReadLink;
@@ -0,0 +1,22 @@
1
+ import { cardRead, defineReadLink, ok } from "@kana-ai/edgar-sdk";
2
+ import { apiAccess } from "#api/client";
3
+ import { readCard } from "#tracker/cards";
4
+ import { listComments } from "#tracker/comments";
5
+ import { settingsOf } from "#tracker/states";
6
+ /** The link of a Linear card, `https://linear.app/<workspace>/issue/<TEAM>-<number>`, with an optional title after it. */
7
+ const CARD_LINK = /^https:\/\/linear\.app\/[\w-]+\/issue\/([A-Z][A-Z0-9]*)-([1-9]\d*)(?:[/?#]|$)/;
8
+ /** Reads a card of `[extensions.linear] team` that a card or its comments link, for a run's inbox, under the same rules as the tracker's card read: a card out of the scope is a failure. A link to a card of another team, or to anything else in Linear, is not this reader's. */
9
+ export const readLink = defineReadLink({
10
+ hosts: ["linear.app"],
11
+ ...apiAccess,
12
+ read: async (ctx, url) => {
13
+ const settings = settingsOf(ctx);
14
+ if (!settings.ok)
15
+ return settings;
16
+ const [, team, number] = CARD_LINK.exec(url) ?? [];
17
+ if (team !== settings.value.team || number === undefined)
18
+ return ok({ kind: "not_mine" });
19
+ const id = `${team}-${number}`;
20
+ return cardRead(await readCard(ctx, id), await listComments(ctx, id, null));
21
+ },
22
+ });
@@ -1,3 +1,4 @@
1
+ import type { Trust } from "@kana-ai/edgar-contracts/rpc";
1
2
  import { type Failure, type Result } from "@kana-ai/edgar-sdk";
2
3
  import { type LinearCtx } from "#api/client";
3
4
  import { type Config, type State } from "#schemas/config";
@@ -5,6 +6,10 @@ import { type Config, type State } from "#schemas/config";
5
6
  export declare const WAITING = "edgar:waiting";
6
7
  /** The engine states in their forward order. */
7
8
  export declare const states: readonly ["intake", "ready", "working", "in_review", "waiting_on_person", "in_testing", "done", "cancelled"];
9
+ /** Whether `writer`, the id Linear answers as the writer of a card or a comment, is on the team: one of EDGAR's own users `own`, or a `user` of the workspace that Linear says is no guest. A guest, a writer whose guest flag is not read, and text an integration brings in for someone with no Linear account are outside. */
10
+ export declare function trustOf(writer: string, user: {
11
+ readonly guest?: boolean | null | undefined;
12
+ } | null | undefined, own: ReadonlySet<string>): Trust;
8
13
  /** True for a name the column mapping knows as an engine state. */
9
14
  export declare function isState(value: string): value is State;
10
15
  /** The engine state a Linear column maps to, or `undefined` for a column the mapping does not name. */
@@ -15,6 +20,24 @@ export declare function forward(from: State, to: State): boolean;
15
20
  export declare function settingsOf(ctx: LinearCtx): Result<Config, Failure>;
16
21
  /** The engine state of a card in column `name`: the mapped state, or `intake` for a card in a column of `assigned` whose assignee is `assignee`. */
17
22
  export declare function columnOf(settings: Config, name: string, assignee: string | undefined, cardAssignee: string | undefined): State | undefined;
23
+ /** The fields of a card that decide whether it is in the table's scope. */
24
+ export interface Scoped {
25
+ readonly title: string;
26
+ readonly project?: {
27
+ readonly name: string;
28
+ readonly slugId: string;
29
+ } | null | undefined;
30
+ readonly labels: {
31
+ readonly nodes: readonly {
32
+ readonly name: string;
33
+ }[];
34
+ };
35
+ readonly assignee?: {
36
+ readonly id: string;
37
+ } | null | undefined;
38
+ }
39
+ /** True when the card is in the table's scope: its title has `title_prefix`, it is in `project` by name or URL key, it has every label of `labels`, and with `assignee_only` it is assigned to `assignee` or labelled edgar:waiting. */
40
+ export declare function inScope(settings: Config, card: Scoped, assignee: string | undefined): boolean;
18
41
  /** The Linear id of the user that `user` names: `me` is the user of `LINEAR_TOKEN`, a text with `@` is an email, and any other text is an id that Linear must have. `undefined` when the workspace has no such user. A user is found once for the life of the process. */
19
42
  export declare function userId(ctx: LinearCtx, user: string): Promise<Result<string | undefined, Failure>>;
20
43
  /** The id of the user of `[extensions.linear] assignee`, who is the user of `LINEAR_TOKEN` when the table names none, or `undefined` when the table needs no user: `assigned` names no column and `assignee_only` is off. A user the workspace does not have is a permanent `invalid` that names it. */
@@ -15,6 +15,10 @@ export const states = [
15
15
  "done",
16
16
  "cancelled",
17
17
  ];
18
+ /** Whether `writer`, the id Linear answers as the writer of a card or a comment, is on the team: one of EDGAR's own users `own`, or a `user` of the workspace that Linear says is no guest. A guest, a writer whose guest flag is not read, and text an integration brings in for someone with no Linear account are outside. */
19
+ export function trustOf(writer, user, own) {
20
+ return own.has(writer) || user?.guest === false ? "team" : "outside";
21
+ }
18
22
  /** True for a name the column mapping knows as an engine state. */
19
23
  export function isState(value) {
20
24
  return states.some((state) => state === value);
@@ -46,6 +50,16 @@ export function columnOf(settings, name, assignee, cardAssignee) {
46
50
  const taken = assignee !== undefined && cardAssignee === assignee && settings.assigned.includes(name);
47
51
  return taken ? "intake" : undefined;
48
52
  }
53
+ /** True when the card is in the table's scope: its title has `title_prefix`, it is in `project` by name or URL key, it has every label of `labels`, and with `assignee_only` it is assigned to `assignee` or labelled edgar:waiting. */
54
+ export function inScope(settings, card, assignee) {
55
+ const names = card.labels.nodes.map((label) => label.name);
56
+ const { title_prefix: prefix, project, labels = [] } = settings;
57
+ const mine = !settings.assignee_only || names.includes(WAITING) || card.assignee?.id === assignee;
58
+ return ((prefix === undefined || card.title.startsWith(prefix)) &&
59
+ (project === undefined || card.project?.name === project || card.project?.slugId === project) &&
60
+ labels.every((label) => names.includes(label)) &&
61
+ mine);
62
+ }
49
63
  /** The Linear user ids found so far, by the text that names the user (`me`, an email or an id), kept for the life of the process. */
50
64
  const users = new Map();
51
65
  async function findUser(ctx, user) {
@@ -42,6 +42,7 @@ export declare const tools: {
42
42
  channel: string;
43
43
  thread: string;
44
44
  };
45
+ trust?: "outside" | "team";
45
46
  };
46
47
  };
47
48
  parent?: string;
@@ -49,13 +50,26 @@ export declare const tools: {
49
50
  id: string;
50
51
  url: string;
51
52
  }, "LINEAR_TOKEN">;
53
+ park: import("@kana-ai/edgar-sdk").Tool<{
54
+ card: string;
55
+ waits_for: string;
56
+ }, {
57
+ id: string;
58
+ }, "LINEAR_TOKEN">;
52
59
  release_follow_ups: import("@kana-ai/edgar-sdk").Tool<{
53
60
  card: string;
54
61
  pull_request: string;
62
+ column?: "ready" | "waiting_on_person";
55
63
  }, {
56
64
  released: string[];
57
65
  }, "LINEAR_TOKEN">;
58
66
  /** A retry with the same `seen_at` finds the sighting counted and writes nothing; with no `seen_at`, a retry whose first answer was lost counts it twice. */
67
+ set_priority: import("@kana-ai/edgar-sdk").Tool<{
68
+ card: string;
69
+ priority: "high" | "low" | "medium" | "urgent";
70
+ }, {
71
+ id: string;
72
+ }, "LINEAR_TOKEN">;
59
73
  count_sighting: import("@kana-ai/edgar-sdk").Tool<{
60
74
  card: string;
61
75
  seen_at?: string;
@@ -95,6 +109,12 @@ export declare const tools: {
95
109
  to: string;
96
110
  previous: string;
97
111
  }, "LINEAR_TOKEN">;
112
+ /** Linear keeps one reaction of a kind per user, so a retry adds none. */
113
+ mark_seen: import("@kana-ai/edgar-sdk").Tool<{
114
+ card: string;
115
+ }, {
116
+ id: string;
117
+ }, "LINEAR_TOKEN">;
98
118
  /** A retry writes the same text again, which changes nothing; the lookup tells boot whether a call that did not end wrote it. */
99
119
  update_description: import("@kana-ai/edgar-sdk").Tool<{
100
120
  card: string;
@@ -103,6 +123,13 @@ export declare const tools: {
103
123
  id: string;
104
124
  previous?: string | undefined;
105
125
  }, "LINEAR_TOKEN">;
126
+ retitle: import("@kana-ai/edgar-sdk").Tool<{
127
+ card: string;
128
+ text: string;
129
+ }, {
130
+ id: string;
131
+ title: string;
132
+ }, "LINEAR_TOKEN">;
106
133
  restore_description: import("@kana-ai/edgar-sdk").Tool<{
107
134
  stage_output: {
108
135
  id: string;