@codyswann/lisa 4.101.4 → 4.101.6

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.
Files changed (110) hide show
  1. package/dist/core/nightly-e2e-guard-behavior-certificate.js +2 -2
  2. package/dist/core/upstream-evidence-manifest.d.ts.map +1 -1
  3. package/dist/core/upstream-evidence-manifest.js +24 -5
  4. package/dist/core/upstream-evidence-manifest.js.map +1 -1
  5. package/dist/opencode/hooks-installer.d.ts.map +1 -1
  6. package/dist/opencode/hooks-installer.js +8 -0
  7. package/dist/opencode/hooks-installer.js.map +1 -1
  8. package/dist/opencode/plugin-catalog.d.ts.map +1 -1
  9. package/dist/opencode/plugin-catalog.js +5 -0
  10. package/dist/opencode/plugin-catalog.js.map +1 -1
  11. package/dist/opencode/plugin-templates/block-host-name-leak.mjs +511 -0
  12. package/dist/opencode/plugin-templates/block-host-name-leak.sh +69 -0
  13. package/dist/opencode/plugin-templates/host-name-command-context.mjs +455 -0
  14. package/dist/opencode/plugin-templates/lisa-block-host-name-leak.ts +62 -0
  15. package/package.json +4 -4
  16. package/plugins/lisa/.claude-plugin/plugin.json +1 -1
  17. package/plugins/lisa/.codex-plugin/plugin.json +1 -1
  18. package/plugins/lisa/.codex-plugin/scripts/automation-run-record.mjs +678 -0
  19. package/plugins/lisa/.codex-plugin/scripts/blocker-edge-resolution.mjs +150 -0
  20. package/plugins/lisa/.codex-plugin/scripts/intake-blocker-reprobe.mjs +1379 -0
  21. package/plugins/lisa/.codex-plugin/scripts/intake-prework-denominator.mjs +249 -0
  22. package/plugins/lisa/.codex-plugin/scripts/operator-id-kinds.mjs +120 -0
  23. package/plugins/lisa/.codex-plugin/scripts/qa-signal-lifecycle.mjs +523 -0
  24. package/plugins/lisa/.codex-plugin/scripts/ready-queue-order.mjs +549 -0
  25. package/plugins/lisa/.codex-plugin/scripts/resolve-lifecycle-role.mjs +347 -0
  26. package/plugins/lisa/hooks/block-host-name-leak.mjs +11 -5
  27. package/plugins/lisa/hooks/host-name-command-context.mjs +45 -2
  28. package/plugins/lisa-agy/hooks/block-host-name-leak.mjs +11 -5
  29. package/plugins/lisa-agy/hooks/host-name-command-context.mjs +45 -2
  30. package/plugins/lisa-agy/plugin.json +1 -1
  31. package/plugins/lisa-cdk/.claude-plugin/plugin.json +1 -1
  32. package/plugins/lisa-cdk/.codex-plugin/plugin.json +1 -1
  33. package/plugins/lisa-cdk-agy/plugin.json +1 -1
  34. package/plugins/lisa-cdk-copilot/.claude-plugin/plugin.json +1 -1
  35. package/plugins/lisa-cdk-cursor/.claude-plugin/plugin.json +1 -1
  36. package/plugins/lisa-cdk-devin/.claude-plugin/plugin.json +1 -1
  37. package/plugins/lisa-cdk-devin/.devin-plugin/plugin.json +1 -1
  38. package/plugins/lisa-copilot/.claude-plugin/plugin.json +1 -1
  39. package/plugins/lisa-copilot/hooks/block-host-name-leak.mjs +11 -5
  40. package/plugins/lisa-copilot/hooks/host-name-command-context.mjs +45 -2
  41. package/plugins/lisa-cursor/.claude-plugin/plugin.json +1 -1
  42. package/plugins/lisa-cursor/hooks/block-host-name-leak.mjs +11 -5
  43. package/plugins/lisa-cursor/hooks/host-name-command-context.mjs +45 -2
  44. package/plugins/lisa-devin/.claude-plugin/plugin.json +1 -1
  45. package/plugins/lisa-devin/.devin-plugin/plugin.json +1 -1
  46. package/plugins/lisa-devin/hooks/block-host-name-leak.mjs +11 -5
  47. package/plugins/lisa-devin/hooks/host-name-command-context.mjs +45 -2
  48. package/plugins/lisa-expo/.claude-plugin/plugin.json +1 -1
  49. package/plugins/lisa-expo/.codex-plugin/plugin.json +1 -1
  50. package/plugins/lisa-expo-agy/plugin.json +1 -1
  51. package/plugins/lisa-expo-copilot/.claude-plugin/plugin.json +1 -1
  52. package/plugins/lisa-expo-cursor/.claude-plugin/plugin.json +1 -1
  53. package/plugins/lisa-expo-devin/.claude-plugin/plugin.json +1 -1
  54. package/plugins/lisa-expo-devin/.devin-plugin/plugin.json +1 -1
  55. package/plugins/lisa-harper-fabric/.claude-plugin/plugin.json +1 -1
  56. package/plugins/lisa-harper-fabric/.codex-plugin/plugin.json +1 -1
  57. package/plugins/lisa-harper-fabric-agy/plugin.json +1 -1
  58. package/plugins/lisa-harper-fabric-copilot/.claude-plugin/plugin.json +1 -1
  59. package/plugins/lisa-harper-fabric-cursor/.claude-plugin/plugin.json +1 -1
  60. package/plugins/lisa-harper-fabric-devin/.claude-plugin/plugin.json +1 -1
  61. package/plugins/lisa-harper-fabric-devin/.devin-plugin/plugin.json +1 -1
  62. package/plugins/lisa-nestjs/.claude-plugin/plugin.json +1 -1
  63. package/plugins/lisa-nestjs/.codex-plugin/plugin.json +1 -1
  64. package/plugins/lisa-nestjs-agy/plugin.json +1 -1
  65. package/plugins/lisa-nestjs-copilot/.claude-plugin/plugin.json +1 -1
  66. package/plugins/lisa-nestjs-cursor/.claude-plugin/plugin.json +1 -1
  67. package/plugins/lisa-nestjs-devin/.claude-plugin/plugin.json +1 -1
  68. package/plugins/lisa-nestjs-devin/.devin-plugin/plugin.json +1 -1
  69. package/plugins/lisa-openclaw/.claude-plugin/plugin.json +1 -1
  70. package/plugins/lisa-openclaw/.codex-plugin/plugin.json +1 -1
  71. package/plugins/lisa-openclaw-agy/plugin.json +1 -1
  72. package/plugins/lisa-openclaw-copilot/.claude-plugin/plugin.json +1 -1
  73. package/plugins/lisa-openclaw-cursor/.claude-plugin/plugin.json +1 -1
  74. package/plugins/lisa-openclaw-devin/.claude-plugin/plugin.json +1 -1
  75. package/plugins/lisa-openclaw-devin/.devin-plugin/plugin.json +1 -1
  76. package/plugins/lisa-phaser/.claude-plugin/plugin.json +1 -1
  77. package/plugins/lisa-phaser/.codex-plugin/plugin.json +1 -1
  78. package/plugins/lisa-phaser-agy/plugin.json +1 -1
  79. package/plugins/lisa-phaser-copilot/.claude-plugin/plugin.json +1 -1
  80. package/plugins/lisa-phaser-cursor/.claude-plugin/plugin.json +1 -1
  81. package/plugins/lisa-phaser-devin/.claude-plugin/plugin.json +1 -1
  82. package/plugins/lisa-phaser-devin/.devin-plugin/plugin.json +1 -1
  83. package/plugins/lisa-rails/.claude-plugin/plugin.json +1 -1
  84. package/plugins/lisa-rails/.codex-plugin/plugin.json +1 -1
  85. package/plugins/lisa-rails-agy/plugin.json +1 -1
  86. package/plugins/lisa-rails-copilot/.claude-plugin/plugin.json +1 -1
  87. package/plugins/lisa-rails-cursor/.claude-plugin/plugin.json +1 -1
  88. package/plugins/lisa-rails-devin/.claude-plugin/plugin.json +1 -1
  89. package/plugins/lisa-rails-devin/.devin-plugin/plugin.json +1 -1
  90. package/plugins/lisa-typescript/.claude-plugin/plugin.json +1 -1
  91. package/plugins/lisa-typescript/.codex-plugin/plugin.json +1 -1
  92. package/plugins/lisa-typescript-agy/plugin.json +1 -1
  93. package/plugins/lisa-typescript-copilot/.claude-plugin/plugin.json +1 -1
  94. package/plugins/lisa-typescript-cursor/.claude-plugin/plugin.json +1 -1
  95. package/plugins/lisa-typescript-devin/.claude-plugin/plugin.json +1 -1
  96. package/plugins/lisa-typescript-devin/.devin-plugin/plugin.json +1 -1
  97. package/plugins/lisa-wiki/.claude-plugin/plugin.json +1 -1
  98. package/plugins/lisa-wiki/.codex-plugin/plugin.json +1 -1
  99. package/plugins/lisa-wiki-agy/plugin.json +1 -1
  100. package/plugins/lisa-wiki-copilot/.claude-plugin/plugin.json +1 -1
  101. package/plugins/lisa-wiki-cursor/.claude-plugin/plugin.json +1 -1
  102. package/plugins/lisa-wiki-devin/.claude-plugin/plugin.json +1 -1
  103. package/plugins/lisa-wiki-devin/.devin-plugin/plugin.json +1 -1
  104. package/plugins/src/base/hooks/block-host-name-leak.mjs +11 -5
  105. package/plugins/src/base/hooks/host-name-command-context.mjs +45 -2
  106. package/scripts/copy-opencode-plugin-templates.mjs +3 -0
  107. package/scripts/generate-codex-plugin-artifacts.mjs +6 -0
  108. package/scripts/lib/codex-shared-scripts.mjs +156 -0
  109. package/scripts/lib/host-name-launcher-cases.mjs +280 -0
  110. package/scripts/verify-host-name-target-scope.mjs +9 -0
@@ -0,0 +1,549 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Vendor-neutral Ready-queue normalization and operator-first dispatch order.
4
+ *
5
+ * ## Why this exists
6
+ *
7
+ * Intake has always taken Ready work in whatever order the tracker returned
8
+ * it, and `intake.assignee` only NARROWS a selection — it never ranks one. A
9
+ * dispatcher that runs several workers at once needs a stable answer to "what
10
+ * next?": work assigned to the operator first (the person the dispatcher works
11
+ * for), then work assigned to me (the identity the tracker credential belongs
12
+ * to, often an agent account rather than the operator), then unassigned work,
13
+ * most urgent and oldest first. Work assigned to anyone else is theirs, so it
14
+ * is excluded, never re-ordered. When the credential IS the operator's, the
15
+ * first two groups coincide. With "me" as the only identity, an operator whose
16
+ * credential is an agent account had every one of their own items excluded as
17
+ * someone else's (CodySwannGT/lisa#4467).
18
+ *
19
+ * The three trackers disagree on every field this needs — GitHub has priority
20
+ * LABELS, Linear a native 0..4 number where 0 means "none", Jira a priority
21
+ * NAME from a scheme that varies by site — so each vendor gets one normalizer
22
+ * onto a single item shape, and ordering only ever sees that shape.
23
+ *
24
+ * `queue-status-build-readers.mjs` reads raw GitHub only; Jira and Linear
25
+ * arrive here already fetched by their vendor access skills. This module never
26
+ * fetches: the caller pages the tracker to completion, and
27
+ * {@link assertPagedToCompletion} refuses to order a half-read queue, because
28
+ * a truncated sweep silently reorders by omission (#3529, #4105).
29
+ *
30
+ * Operator and trusted-author entries may be kind-keyed (#4623): `login:<v>`
31
+ * matches only a GitHub login, `id:<v>` only an account id, and a plain entry
32
+ * is compared exactly as before (with the normalized assignee id, or the
33
+ * normalized author id). Each normalizer therefore also carries the login and
34
+ * the account id of the assignee and the login of the author, where its
35
+ * tracker has them, so the kinds never have to be guessed.
36
+ *
37
+ * Held items are judged by {@link isHumanGated}, the one shared answer to "is
38
+ * a person holding this?", rather than by a local label check (#3805).
39
+ *
40
+ * {@link orderBacklogQueue} ranks a second, lower tier: open leaf items in no
41
+ * lifecycle role, which the session manager may promote to Ready when
42
+ * `sessionManager.backlogPickup` is on. It applies every Ready exclusion plus
43
+ * two of its own (an unfinished blocker, an unchanged validation failure), and
44
+ * its list is always walked after the whole Ready queue.
45
+ * @module ready-queue-order
46
+ */
47
+
48
+ import {
49
+ DEFAULT_HUMAN_NEEDED_LABEL,
50
+ isHumanGated,
51
+ } from "./intake-blocker-reprobe.mjs";
52
+ import { entryMatches, parseIdEntries } from "./operator-id-kinds.mjs";
53
+
54
+ /** Rank for GitHub `priority:<value>` labels; no label ranks 4. */
55
+ const GITHUB_PRIORITY_RANKS = Object.freeze({
56
+ critical: 0,
57
+ high: 1,
58
+ medium: 2,
59
+ low: 3,
60
+ });
61
+ const GITHUB_NO_PRIORITY = 4;
62
+
63
+ /** Rank for Jira priority names, across the default and legacy schemes. */
64
+ const JIRA_PRIORITY_RANKS = Object.freeze({
65
+ highest: 0,
66
+ blocker: 0,
67
+ high: 1,
68
+ critical: 1,
69
+ medium: 2,
70
+ major: 2,
71
+ low: 3,
72
+ minor: 3,
73
+ lowest: 4,
74
+ trivial: 4,
75
+ });
76
+ const JIRA_UNKNOWN_PRIORITY = 5;
77
+
78
+ /** Linear native priority: 1 urgent .. 4 low, and 0 means no priority. */
79
+ const LINEAR_NO_PRIORITY = 4;
80
+
81
+ /** Linear workflow state types that leave a child finished. */
82
+ const LINEAR_FINISHED_STATE_TYPES = new Set(["completed", "canceled"]);
83
+
84
+ /** Jira link types whose inward side reads as "this item is blocked by". */
85
+ const JIRA_BLOCKED_BY = /blocked by/i;
86
+
87
+ /**
88
+ * @param {unknown} value
89
+ * @returns {string}
90
+ */
91
+ function text(value) {
92
+ return typeof value === "string" ? value : "";
93
+ }
94
+
95
+ /**
96
+ * A stable id as a string, or null. Numeric GitHub ids become strings so every
97
+ * comparison in this module is string-to-string.
98
+ * @param {unknown} value
99
+ * @returns {string | null}
100
+ */
101
+ function idOrNull(value) {
102
+ if (typeof value === "string" && value.trim().length > 0) {
103
+ return value.trim();
104
+ }
105
+ return Number.isSafeInteger(value) ? String(value) : null;
106
+ }
107
+
108
+ /**
109
+ * A non-negative integer count, 0 for anything else.
110
+ * @param {unknown} value
111
+ * @returns {number}
112
+ */
113
+ function count(value) {
114
+ const number = Number(value);
115
+ return Number.isInteger(number) && number > 0 ? number : 0;
116
+ }
117
+
118
+ /**
119
+ * The rows of an array or a GraphQL `{nodes}` connection.
120
+ * @param {unknown} list
121
+ * @returns {any[]}
122
+ */
123
+ function nodesOf(list) {
124
+ if (Array.isArray(list)) return list;
125
+ return Array.isArray(list?.nodes) ? list.nodes : [];
126
+ }
127
+
128
+ /**
129
+ * Label names from strings, `{name}` objects or a GraphQL `{nodes}` connection.
130
+ * @param {unknown} labels
131
+ * @returns {string[]}
132
+ */
133
+ function labelNames(labels) {
134
+ const list = Array.isArray(labels)
135
+ ? labels
136
+ : Array.isArray(labels?.nodes)
137
+ ? labels.nodes
138
+ : [];
139
+ return list
140
+ .map(label => (typeof label === "string" ? label : text(label?.name)))
141
+ .map(label => label.trim())
142
+ .filter(label => label.length > 0);
143
+ }
144
+
145
+ /**
146
+ * The `repo:<name>` labels, lowercased, as `repo-scope-split` reads them.
147
+ * @param {readonly string[]} labels
148
+ * @returns {string[]}
149
+ */
150
+ function repoLabelsOf(labels) {
151
+ return labels
152
+ .map(label => label.toLowerCase())
153
+ .filter(label => label.startsWith("repo:") && label.length > 5);
154
+ }
155
+
156
+ /**
157
+ * Flatten an Atlassian Document Format node to plain text, one line per block.
158
+ * A string description (the Markdown some access paths return) passes through.
159
+ * @param {unknown} node
160
+ * @returns {string}
161
+ */
162
+ function adfText(node) {
163
+ if (typeof node === "string") return node;
164
+ if (!node || typeof node !== "object") return "";
165
+ if (node.type === "text") return text(node.text);
166
+ if (node.type === "hardBreak") return "\n";
167
+ const children = Array.isArray(node.content) ? node.content : [];
168
+ const joiner = node.type === "doc" ? "\n" : "";
169
+ return children.map(adfText).join(joiner);
170
+ }
171
+
172
+ /**
173
+ * Normalize one GitHub REST issue row. Returns null for a pull-request row,
174
+ * which the issues endpoint returns alongside issues and which is never a
175
+ * dispatchable leaf.
176
+ * @param {Record<string, any>} issue - REST `issues` list row
177
+ * @param {{ repo?: string }} [options] - `owner/repo`, else read from repository_url
178
+ * @returns {ReturnType<typeof shape> | null}
179
+ */
180
+ export function normalizeGithubIssue(issue, options = {}) {
181
+ if (!issue || issue.pull_request) return null;
182
+ const labels = labelNames(issue.labels);
183
+ const ranks = labels
184
+ .map(label => label.toLowerCase())
185
+ .filter(label => label.startsWith("priority:"))
186
+ .map(label => GITHUB_PRIORITY_RANKS[label.slice("priority:".length)])
187
+ .filter(rank => rank !== undefined);
188
+ const repo =
189
+ text(options.repo) || text(issue.repository_url).split("/repos/")[1] || "";
190
+ const summary = issue.sub_issues_summary;
191
+ const assignee = issue.assignee ?? issue.assignees?.[0] ?? null;
192
+
193
+ return shape({
194
+ ref: `${repo}#${issue.number}`,
195
+ title: text(issue.title),
196
+ // GitHub "me" is the login (`gh api user --jq .login`), so match on it.
197
+ assigneeId: idOrNull(assignee?.login),
198
+ assigneeLogin: idOrNull(assignee?.login),
199
+ assigneeAccountId: idOrNull(assignee?.id),
200
+ priorityRank: ranks.length > 0 ? Math.min(...ranks) : GITHUB_NO_PRIORITY,
201
+ createdAt: text(issue.created_at),
202
+ updatedAt: text(issue.updated_at),
203
+ labels,
204
+ body: text(issue.body),
205
+ // Plain and `id:` trusted-author entries trust by stable id (ready-role-
206
+ // filing); a `login:` entry trusts a login the operator opted into
207
+ // explicitly, knowing a freed login can be re-registered (#4623).
208
+ authorId: idOrNull(issue.user?.id),
209
+ authorLogin: idOrNull(issue.user?.login),
210
+ isContainer: Number(summary?.total ?? 0) > Number(summary?.completed ?? 0),
211
+ // `blocked_by` in the dependency summary counts only OPEN blockers.
212
+ openBlockers: count(issue.issue_dependencies_summary?.blocked_by),
213
+ });
214
+ }
215
+
216
+ /**
217
+ * Normalize one Jira REST/MCP issue. An epic (hierarchy level above 0) or an
218
+ * issue with any subtask not yet in the done category is a container.
219
+ * @param {Record<string, any>} issue - Issue with `key` and `fields`
220
+ * @returns {ReturnType<typeof shape>}
221
+ */
222
+ export function normalizeJiraIssue(issue) {
223
+ const fields = issue?.fields ?? {};
224
+ const labels = labelNames(fields.labels);
225
+ const priority = text(fields.priority?.name).trim().toLowerCase();
226
+ const type = fields.issuetype ?? {};
227
+ const openSubtasks = (Array.isArray(fields.subtasks) ? fields.subtasks : [])
228
+ .map(sub => sub?.fields?.status?.statusCategory?.key)
229
+ .filter(category => category !== "done");
230
+ const openBlockers = nodesOf(fields.issuelinks).filter(
231
+ link =>
232
+ link?.inwardIssue &&
233
+ JIRA_BLOCKED_BY.test(text(link.type?.inward)) &&
234
+ link.inwardIssue.fields?.status?.statusCategory?.key !== "done"
235
+ ).length;
236
+
237
+ return shape({
238
+ ref: text(issue?.key),
239
+ title: text(fields.summary),
240
+ assigneeId: idOrNull(fields.assignee?.accountId),
241
+ assigneeLogin: null,
242
+ assigneeAccountId: idOrNull(fields.assignee?.accountId),
243
+ priorityRank: JIRA_PRIORITY_RANKS[priority] ?? JIRA_UNKNOWN_PRIORITY,
244
+ createdAt: text(fields.created),
245
+ updatedAt: text(fields.updated),
246
+ labels,
247
+ body: adfText(fields.description),
248
+ authorId: idOrNull(fields.reporter?.accountId ?? fields.creator?.accountId),
249
+ authorLogin: null,
250
+ isContainer:
251
+ Number(type.hierarchyLevel ?? 0) > 0 ||
252
+ text(type.name).toLowerCase() === "epic" ||
253
+ openSubtasks.length > 0,
254
+ openBlockers,
255
+ });
256
+ }
257
+
258
+ /**
259
+ * Normalize one Linear GraphQL issue. An issue with any child not completed
260
+ * or canceled is a container.
261
+ * @param {Record<string, any>} issue - Issue node
262
+ * @returns {ReturnType<typeof shape>}
263
+ */
264
+ export function normalizeLinearIssue(issue) {
265
+ const native = Number(issue?.priority ?? 0);
266
+ const children = Array.isArray(issue?.children?.nodes)
267
+ ? issue.children.nodes
268
+ : Array.isArray(issue?.children)
269
+ ? issue.children
270
+ : [];
271
+ const labels = labelNames(issue?.labels);
272
+ // Linear has no "blocked by" relation type: B blocked by A is A's `blocks`
273
+ // relation, read from B as an inverse relation.
274
+ const openBlockers = nodesOf(issue?.inverseRelations).filter(
275
+ relation =>
276
+ relation?.type === "blocks" &&
277
+ !LINEAR_FINISHED_STATE_TYPES.has(relation.issue?.state?.type)
278
+ ).length;
279
+
280
+ return shape({
281
+ ref: text(issue?.identifier),
282
+ title: text(issue?.title),
283
+ assigneeId: idOrNull(issue?.assignee?.id),
284
+ assigneeLogin: null,
285
+ assigneeAccountId: idOrNull(issue?.assignee?.id),
286
+ priorityRank:
287
+ Number.isInteger(native) && native >= 1 && native <= 4
288
+ ? native - 1
289
+ : LINEAR_NO_PRIORITY,
290
+ createdAt: text(issue?.createdAt),
291
+ updatedAt: text(issue?.updatedAt),
292
+ labels,
293
+ body: text(issue?.description),
294
+ authorId: idOrNull(issue?.creator?.id),
295
+ authorLogin: null,
296
+ isContainer: children.some(
297
+ child => !LINEAR_FINISHED_STATE_TYPES.has(child?.state?.type)
298
+ ),
299
+ openBlockers,
300
+ });
301
+ }
302
+
303
+ /**
304
+ * The one item shape every normalizer returns, in a fixed key order.
305
+ * `updatedAt` keys the backlog tier's validation cache; `openBlockers` counts
306
+ * dependencies whose blocker is not finished. The Ready tier ignores both.
307
+ * `assigneeLogin` / `authorLogin` are GitHub logins (null on trackers with
308
+ * none) and `assigneeAccountId` the assignee's account id, for kind-keyed
309
+ * entries (#4623).
310
+ * @param {{ ref: string, title: string, assigneeId: string | null, assigneeLogin: string | null, assigneeAccountId: string | null, priorityRank: number, createdAt: string, updatedAt: string, labels: string[], body: string, authorId: string | null, authorLogin: string | null, isContainer: boolean, openBlockers: number }} input
311
+ */
312
+ function shape(input) {
313
+ return {
314
+ ref: input.ref,
315
+ title: input.title,
316
+ assigneeId: input.assigneeId,
317
+ assigneeLogin: input.assigneeLogin,
318
+ assigneeAccountId: input.assigneeAccountId,
319
+ priorityRank: input.priorityRank,
320
+ createdAt: input.createdAt,
321
+ updatedAt: input.updatedAt,
322
+ labels: input.labels,
323
+ body: input.body,
324
+ authorId: input.authorId,
325
+ authorLogin: input.authorLogin,
326
+ isContainer: input.isContainer,
327
+ openBlockers: input.openBlockers,
328
+ repoLabels: repoLabelsOf(input.labels),
329
+ };
330
+ }
331
+
332
+ /**
333
+ * Whether an operator entry names the item's assignee: a plain entry by the
334
+ * normalized assignee id, as before; `login:` by the assignee's GitHub login;
335
+ * `id:` by the assignee's account id.
336
+ * @param {Record<string, any>} item
337
+ * @param {ReturnType<typeof orderingContext>} context
338
+ * @returns {boolean}
339
+ */
340
+ function isOperatorItem(item, context) {
341
+ const fields = {
342
+ plain: idOrNull(item.assigneeId),
343
+ login: idOrNull(item.assigneeLogin),
344
+ id: idOrNull(item.assigneeAccountId),
345
+ };
346
+ return context.operators.some(entry => entryMatches(entry, fields));
347
+ }
348
+
349
+ /**
350
+ * Whether a trusted-author entry names the item's author: a plain entry by
351
+ * the normalized author id, as before; `login:` by the author's GitHub login;
352
+ * `id:` by the author id (a GitHub numeric id, Jira accountId, Linear id).
353
+ * @param {Record<string, any>} item
354
+ * @param {ReturnType<typeof orderingContext>} context
355
+ * @returns {boolean}
356
+ */
357
+ function isTrustedAuthor(item, context) {
358
+ const author = idOrNull(item.authorId);
359
+ const fields = {
360
+ plain: author,
361
+ login: idOrNull(item.authorLogin),
362
+ id: author,
363
+ };
364
+ return context.trusted.some(entry => entryMatches(entry, fields));
365
+ }
366
+
367
+ /**
368
+ * Why an item may not be dispatched, or null when it may.
369
+ *
370
+ * Order matters only for the reason reported: an item can fail several rules,
371
+ * and "someone else owns it" is the most useful thing to say about it.
372
+ * @param {Record<string, any>} item
373
+ * @param {ReturnType<typeof orderingContext>} context
374
+ * @returns {string | null}
375
+ */
376
+ function exclusionReason(item, context) {
377
+ const assignee = idOrNull(item.assigneeId);
378
+ if (
379
+ assignee !== null &&
380
+ assignee !== context.me &&
381
+ !isOperatorItem(item, context)
382
+ ) {
383
+ return "assigned-to-other";
384
+ }
385
+ if (item.isContainer === true) return "container";
386
+ if (
387
+ isHumanGated({
388
+ labels: item.labels,
389
+ body: item.body,
390
+ comments: item.comments,
391
+ trustedHumanActorIds: item.trustedHumanActorIds,
392
+ humanNeededLabel: context.humanNeededLabel,
393
+ })
394
+ ) {
395
+ return "human-gated";
396
+ }
397
+ if (context.trusted.length > 0 && !isTrustedAuthor(item, context)) {
398
+ return "untrusted-author";
399
+ }
400
+ return null;
401
+ }
402
+
403
+ /**
404
+ * @param {Record<string, any>} left
405
+ * @param {Record<string, any>} right
406
+ * @returns {number}
407
+ */
408
+ function compareWithinGroup(left, right) {
409
+ return (
410
+ Number(left.priorityRank) - Number(right.priorityRank) ||
411
+ text(left.createdAt).localeCompare(text(right.createdAt)) ||
412
+ text(left.ref).localeCompare(text(right.ref))
413
+ );
414
+ }
415
+
416
+ /**
417
+ * Order normalized Ready items for dispatch: the operator's, then mine, then
418
+ * unassigned.
419
+ *
420
+ * Group 0 is assigned to an operator, group 1 to `me`, group 2 unassigned;
421
+ * within a group, priority rank ascending, then creation time ascending, then
422
+ * ref as a stable tiebreak. Excluded items keep their input order. With no
423
+ * `me` and no operators, every assigned item is someone else's — the safe
424
+ * direction, since claiming assigned work steals it.
425
+ *
426
+ * A plain `operators` entry matches the way `me` does, against the
427
+ * normalized assignee id: GitHub login, Jira accountId, Linear user id. A
428
+ * `login:` entry matches only a GitHub assignee login, an `id:` entry only
429
+ * the assignee's account id (#4623).
430
+ * @param {readonly Record<string, any>[]} items - Normalized items
431
+ * @param {{ me?: string | null, operators?: readonly unknown[], trustedAuthorIds?: readonly unknown[], humanNeededLabel?: string }} [options]
432
+ * @returns {{ ordered: Record<string, any>[], excluded: { ref: string, reason: string }[] }}
433
+ */
434
+ export function orderReadyQueue(items, options = {}) {
435
+ const context = orderingContext(options);
436
+ return rank(items, item => exclusionReason(item, context), context);
437
+ }
438
+
439
+ /**
440
+ * Order normalized backlog items — open leaves in no lifecycle role — for
441
+ * promotion, the tier walked only after the whole Ready queue.
442
+ *
443
+ * Every Ready exclusion applies, then two more: an item with an unfinished
444
+ * blocker (`blocked-by-open-item`) cannot be taken to completion, and an item
445
+ * that already failed validation at its current `updatedAt`
446
+ * (`failed-validation-unchanged`, from `validationFailures`) would only fail
447
+ * again, so it waits until someone edits it. Grouping and ordering match
448
+ * {@link orderReadyQueue}.
449
+ * @param {readonly Record<string, any>[]} items - Normalized items
450
+ * @param {{ me?: string | null, operators?: readonly unknown[], trustedAuthorIds?: readonly unknown[], humanNeededLabel?: string, validationFailures?: Readonly<Record<string, { updatedAt?: string }>> }} [options]
451
+ * @returns {{ ordered: Record<string, any>[], excluded: { ref: string, reason: string }[] }}
452
+ */
453
+ export function orderBacklogQueue(items, options = {}) {
454
+ const context = orderingContext(options);
455
+ const failures = options.validationFailures ?? {};
456
+ return rank(
457
+ items,
458
+ item => {
459
+ const reason = exclusionReason(item, context);
460
+ if (reason !== null) return reason;
461
+ if (count(item.openBlockers) > 0) return "blocked-by-open-item";
462
+ const failed = Object.hasOwn(failures, item.ref)
463
+ ? failures[item.ref]
464
+ : null;
465
+ return failed && text(failed.updatedAt) === text(item.updatedAt)
466
+ ? "failed-validation-unchanged"
467
+ : null;
468
+ },
469
+ context
470
+ );
471
+ }
472
+
473
+ /**
474
+ * Parsed operator or trusted-author entries. A plain entry is trimmed and a
475
+ * blank one dropped, as before; an invalid kind-keyed entry is kept so it
476
+ * still counts as a configured filter while matching nobody.
477
+ * @param {readonly unknown[] | undefined} entries
478
+ * @returns {import("./operator-id-kinds.mjs").IdEntry[]}
479
+ */
480
+ function configuredEntries(entries) {
481
+ return parseIdEntries(entries)
482
+ .map(entry =>
483
+ entry.kind === "plain"
484
+ ? { ...entry, value: idOrNull(entry.value) }
485
+ : entry
486
+ )
487
+ .filter(entry => entry.kind !== "plain" || entry.value !== null);
488
+ }
489
+
490
+ /**
491
+ * The identities and policy every ordering judges against.
492
+ * @param {{ me?: string | null, operators?: readonly unknown[], trustedAuthorIds?: readonly unknown[], humanNeededLabel?: string }} options
493
+ */
494
+ function orderingContext(options) {
495
+ return {
496
+ me: idOrNull(options.me),
497
+ operators: configuredEntries(options.operators),
498
+ trusted: configuredEntries(options.trustedAuthorIds),
499
+ humanNeededLabel: options.humanNeededLabel ?? DEFAULT_HUMAN_NEEDED_LABEL,
500
+ };
501
+ }
502
+
503
+ /**
504
+ * Split items into ordered eligible ones and excluded ones with reasons.
505
+ * @param {readonly Record<string, any>[] | undefined} items
506
+ * @param {(item: Record<string, any>) => string | null} judge - Exclusion reason, or null
507
+ * @param {ReturnType<typeof orderingContext>} context
508
+ * @returns {{ ordered: Record<string, any>[], excluded: { ref: string, reason: string }[] }}
509
+ */
510
+ function rank(items, judge, context) {
511
+ const judged = (items ?? []).map(item => ({ item, reason: judge(item) }));
512
+ const eligible = judged
513
+ .filter(one => one.reason === null)
514
+ .map(one => one.item);
515
+ const group = item => {
516
+ const assignee = idOrNull(item.assigneeId);
517
+ if (assignee === null) return 2;
518
+ return isOperatorItem(item, context) ? 0 : 1;
519
+ };
520
+
521
+ return {
522
+ ordered: [...eligible].sort(
523
+ (left, right) =>
524
+ group(left) - group(right) || compareWithinGroup(left, right)
525
+ ),
526
+ excluded: judged
527
+ .filter(one => one.reason !== null)
528
+ .map(one => ({ ref: one.item.ref, reason: one.reason })),
529
+ };
530
+ }
531
+
532
+ /**
533
+ * Refuse a queue envelope that was not paged to completion.
534
+ *
535
+ * The vendor fetch writes `{complete, pages, items}`; anything but a literal
536
+ * `complete: true` means some pages may be missing, and ordering a partial
537
+ * queue would dispatch the wrong item with full confidence.
538
+ * @template T
539
+ * @param {T} envelope - `{ complete: true, pages, items }`
540
+ * @returns {T} The same envelope
541
+ */
542
+ export function assertPagedToCompletion(envelope) {
543
+ if (envelope?.complete !== true) {
544
+ throw new Error(
545
+ "Ready queue was not paged to completion (envelope.complete !== true); refusing to order a partial queue."
546
+ );
547
+ }
548
+ return envelope;
549
+ }