Beautiful, AI-native markdown IDE and LLM wiki
TypeScript 2nd-brainagent-skillsclaudecodexcompany-braindocsknowledge-knowledge-baseknowledge-managementllmllm-wikillm-wiki-karpathymarkdownmarkdown-editormdmdxnotespkmsecond-brainskills
Close the GitHub issue with the stable reporter reply (PRD-9160) (#5993)
Andrew Mikofalvyb8efc9795665
diff --git a/.github/scripts/write-back-gate.mjs b/.github/scripts/write-back-gate.mjsindex 739c375b5..a054e501a 100644--- a/.github/scripts/write-back-gate.mjs+++ b/.github/scripts/write-back-gate.mjs@@ -205,6 +205,21 @@ export function evaluateFanIn({ ticket, descendants = [], resolveVersion, log =};}+const RESOLVED_STATE_TYPES = new Set(['completed', 'canceled', 'duplicate']);++export function planIssueClose({ issueState, carriers = [], carriersComplete = true }) {+ if (issueState === 'closed') return { close: false, reason: 'already-closed', open: [] };+ if (issueState !== 'open') return { close: false, reason: 'not-an-open-issue', open: [] };+ if (!carriersComplete) return { close: false, reason: 'carriers-truncated', open: [] };+ if (carriers.length === 0) return { close: false, reason: 'no-carrier', open: [] };+ const open = carriers+ .filter((carrier) => !RESOLVED_STATE_TYPES.has(carrier.stateType))+ .map((carrier) => carrier.identifier ?? 'an unreadable ticket')+ .sort();+ if (open.length > 0) return { close: false, reason: 'open-carrier', open };+ return { close: true, reason: null, open: [] };+}+export function composeReply({changeset = {},version,diff --git a/.github/scripts/write-back-gate.test.mjs b/.github/scripts/write-back-gate.test.mjsindex 9d2e1e529..bf5b70744 100644--- a/.github/scripts/write-back-gate.test.mjs+++ b/.github/scripts/write-back-gate.test.mjs@@ -7,6 +7,7 @@ import {highestVersion,isOriginRepliableFrom,partitionAttachments,+ planIssueClose,} from './write-back-gate.mjs';const GH_ISSUE = 'https://github.com/inkeep/open-knowledge/issues/769';@@ -253,6 +254,79 @@ describe('fan-in gate', () => {});});+describe('issue close decision', () => {+ const carrier = (identifier, stateType) => ({ identifier, stateType });++ test('an open issue closes when the canonical shipped and its synced ticket is a duplicate', () => {+ expect(+ planIssueClose({+ issueState: 'open',+ carriers: [carrier('PRD-8204', 'completed'), carrier('PRD-8646', 'duplicate')],+ }),+ ).toEqual({ close: true, reason: null, open: [] });+ });++ test('a canceled carrier is resolved, like the canceled descendant the fan-in gate passes over', () => {+ expect(+ planIssueClose({+ issueState: 'open',+ carriers: [carrier('PRD-1', 'completed'), carrier('PRD-2', 'canceled')],+ }).close,+ ).toBe(true);+ });++ test('any carrier still carrying work keeps the issue open and is named', () => {+ expect(+ planIssueClose({+ issueState: 'open',+ carriers: [+ carrier('PRD-3', 'triage'),+ carrier('PRD-1', 'completed'),+ carrier('PRD-2', 'started'),+ ],+ }),+ ).toEqual({ close: false, reason: 'open-carrier', open: ['PRD-2', 'PRD-3'] });+ });++ test('a carrier whose state could not be read keeps the issue open', () => {+ expect(+ planIssueClose({+ issueState: 'open',+ carriers: [carrier('PRD-1', 'completed'), { identifier: undefined, stateType: undefined }],+ }),+ ).toMatchObject({ close: false, reason: 'open-carrier', open: ['an unreadable ticket'] });+ });++ test('an issue that is already closed is never closed again, whatever its carriers say', () => {+ expect(+ planIssueClose({ issueState: 'closed', carriers: [carrier('PRD-1', 'completed')] }),+ ).toMatchObject({ close: false, reason: 'already-closed' });+ });++ test('anything but an open issue, such as a pull request, is never closed', () => {+ expect(+ planIssueClose({ issueState: 'pull-request', carriers: [carrier('PRD-1', 'completed')] }),+ ).toMatchObject({ close: false, reason: 'not-an-open-issue' });+ });++ test('no carrier at all is a lookup that missed, not permission to close', () => {+ expect(planIssueClose({ issueState: 'open', carriers: [] })).toMatchObject({+ close: false,+ reason: 'no-carrier',+ });+ });++ test('a carrier list known to be partial never closes', () => {+ expect(+ planIssueClose({+ issueState: 'open',+ carriers: [carrier('PRD-1', 'completed')],+ carriersComplete: false,+ }),+ ).toMatchObject({ close: false, reason: 'carriers-truncated' });+ });+});+describe('reply composition', () => {const CHANGESET_BODY ='Honor backslash escapes in the markdown promoters.\n\nTyping `\\==not a highlight\\==` now stays literal instead of turning into a highlight.';diff --git a/.github/scripts/write-back-recovery.test.mjs b/.github/scripts/write-back-recovery.test.mjsindex 53abcf88b..fdbbe8497 100644--- a/.github/scripts/write-back-recovery.test.mjs+++ b/.github/scripts/write-back-recovery.test.mjs@@ -6,6 +6,7 @@ import {runWriteBack,unavailableNotificationVersions,} from './write-back.mjs';+import { planIssueClose } from './write-back-gate.mjs';const origin = 'https://github.com/inkeep/open-knowledge/issues/1428';const pull = 'https://github.com/inkeep/agents-private/pull/4879';@@ -41,6 +42,8 @@ function recoveryHarness(overrides = {}) {marked.push(marker);},postReply: async (target, text) => posts.push({ target, text }),+ readIssueClosure: async () => planIssueClose({ issueState: 'closed' }),+ closeIssue: async () => {},log: (line) => logs.push(line),...overrides,};diff --git a/.github/scripts/write-back.mjs b/.github/scripts/write-back.mjsindex 33a0afeba..55e4057dc 100644--- a/.github/scripts/write-back.mjs+++ b/.github/scripts/write-back.mjs@@ -24,6 +24,7 @@ import {isOriginRepliableFrom,markerSuffixFor,partitionAttachments,+ planIssueClose,} from './write-back-gate.mjs';import writeBackPolicy from './write-back-policy.json' with { type: 'json' };@@ -68,6 +69,15 @@ export const CHILDREN_QUERY = `}`;+export const ISSUE_CARRIERS_QUERY = `+ query WriteBackIssueCarriers($url: String!) {+ attachmentsForURL(url: $url, first: ${PAGE_SIZE}) {+ pageInfo { hasNextPage }+ nodes { issue { identifier state { type } } }+ }+ }+`;+export function notificationMarkerUrl({ version, originUrl }) {const v = String(version ?? '').trim()@@ -282,6 +292,16 @@ export function createVersionFor(deps) {});}+const KEPT_OPEN_HINTS = {+ 'open-carrier': 'close it by hand once every ticket on it is resolved',+ 'no-carrier':+ 'no ticket was found under the canonical issue URL, so check which tickets carry it ' ++ 'and close it by hand if none is still open',+ 'carriers-truncated':+ 'the carrier list came back cut off, so check which tickets carry it ' ++ 'and close it by hand if none is still open',+};+export class NeedsHumanError extends Error {constructor(message) {super(message);@@ -319,6 +339,8 @@ export async function runWriteBack({readChangesetProse,postReply,recordNotification,+ readIssueClosure,+ closeIssue,classifyRelease,channel = 'stable',selfRepo = process.env.GITHUB_REPOSITORY,@@ -331,6 +353,12 @@ export async function runWriteBack({if (channel !== 'stable' && channel !== 'beta') {throw new Error(`runWriteBack requires channel 'stable' or 'beta', got '${channel}'`);}+ if (+ channel === 'stable' &&+ (typeof readIssueClosure !== 'function' || typeof closeIssue !== 'function')+ ) {+ throw new Error('Stable reconciliation requires readIssueClosure and closeIssue');+ }if (typeof isPublishedVersion !== 'function') {throw new Error('runWriteBack requires published release availability');}@@ -498,6 +526,15 @@ export async function runWriteBack({continue;}+ const closure =+ channel === 'stable' && origin.channel === 'github-issue'+ ? await readIssueClosure(origin)+ : null;+ const keptOpen =+ closure && !closure.close+ ? `${origin.url} (${closure.open.length ? `${closure.reason}: ${closure.open.join(', ')}` : closure.reason})`+ : null;+if (!live) {log(`::notice::write-back: [dry run] would reply to ${origin.url} for ${candidate.identifier} ` +@@ -506,11 +543,17 @@ export async function runWriteBack({log(`::notice::write-back: [dry run] ${recoveryFrom.length ? 'recovery correction' : 'release announcement'}: ${text.replaceAll('\n', ' ')}`,);+ if (closure) {+ log(+ `::notice::write-back: [dry run] ${closure.close ? `would close ${origin.url} as completed` : `would not close ${keptOpen}`}.`,+ );+ }posted.push({identifier: candidate.identifier,origin: origin.url,version: gate.version,dryRun: true,+ closed: closure?.close === true,});continue;}@@ -528,19 +571,43 @@ export async function runWriteBack({} catch (err) {throw new NeedsHumanError(`marker for ${origin.url} was written but the reply did NOT send (${err.message}). ` +- 'No future run will retry it; post the reply by hand.',+ `No future run will retry it; post the reply by hand${closure?.close ? ', then close the issue' : ''}.`,);}log(`::notice::write-back: replied to ${origin.url} for ${candidate.identifier} ` +`(v${gate.version}).`,);- posted.push({+ const entry = {identifier: candidate.identifier,origin: origin.url,version: gate.version,dryRun: false,- });+ closed: false,+ };+ posted.push(entry);+ if (!closure) continue;+ if (!closure.close) {+ const hint = KEPT_OPEN_HINTS[closure.reason];+ log(+ hint+ ? `::warning::write-back: did not close ${keptOpen}. No later run revisits it; ${hint}.`+ : `::notice::write-back: did not close ${keptOpen}.`,+ );+ continue;+ }+ try {+ await closeIssue(origin);+ } catch (err) {+ throw new NeedsHumanError(+ `the reply to ${origin.url} was sent but the issue did NOT close (${err.message}). ` ++ 'No future run will retry it; close it by hand.',+ );+ }+ entry.closed = true;+ log(+ `::notice::write-back: closed ${origin.url} for ${candidate.identifier} (v${gate.version}).`,+ );}};@@ -598,8 +665,8 @@ export function runFailureMessage({ errored = [], deferred } = {}) {}return (`${head}. ACTION REQUIRED: ${needsHuman.map((e) => e.identifier).join(', ')} ` +- `${needsHuman.length === 1 ? 'was' : 'were'} marked as notified but the reply never sent; ` +- 'no future run will retry, so post it by hand.'+ `${needsHuman.length === 1 ? 'was' : 'were'} marked as notified before a write failed; ` ++ 'no future run will retry, so finish what each message above names by hand.');}@@ -843,12 +910,13 @@ export function selectGhToken({ owner, repo, env }) {return `${owner}/${repo}`.toLowerCase() === self ? null : crossRepo;}-function gh(args, target) {+function gh(args, target, { timeout } = {}) {const token = target ? selectGhToken({ ...target, env: process.env }) : null;return execFileSync('gh', args, {encoding: 'utf8',stdio: ['ignore', 'pipe', 'pipe'],env: token ? { ...process.env, GH_TOKEN: token } : process.env,+ timeout,});}@@ -983,6 +1051,67 @@ async function realPostReply(origin, text) {throw new Error(`no reply transport for origin channel '${origin.channel}'`);}+export function createIssueClosureReader({ readIssueState, queryCarriers }) {+ return async (origin) => {+ const issueState = await readIssueState(origin);+ if (issueState !== 'open') return planIssueClose({ issueState });+ const data = await queryCarriers(+ `https://github.com/${origin.owner}/${origin.repo}/issues/${origin.number}`,+ );+ const connection = data?.attachmentsForURL;+ if (!connection) {+ throw new Error(+ `Linear returned no attachments connection for ${origin.url}; refusing to treat that as no carriers.`,+ );+ }+ return planIssueClose({+ issueState,+ carriers: connection.nodes.map((node) => ({+ identifier: node.issue?.identifier,+ stateType: node.issue?.state?.type,+ })),+ carriersComplete: connection.pageInfo?.hasNextPage === false,+ });+ };+}++export function readIssueStateWith(runGh, origin) {+ try {+ return runGh(+ [+ 'api',+ `repos/${origin.owner}/${origin.repo}/issues/${origin.number}`,+ '--jq',+ 'if .pull_request then "pull-request" else .state end',+ ],+ origin,+ { timeout: REQUEST_TIMEOUT_MS },+ ).trim();+ } catch (err) {+ if (/\(HTTP (?:404|410)\)/.test(String(err?.stderr ?? ''))) return 'gone';+ throw new Error(+ `gh api issues/${origin.number} failed: ${String(err?.stderr || err?.message || '').trim()}`,+ );+ }+}++function realCloseIssue(origin) {+ gh(+ [+ 'api',+ '--method',+ 'PATCH',+ `repos/${origin.owner}/${origin.repo}/issues/${origin.number}`,+ '-f',+ 'state=closed',+ '-f',+ 'state_reason=completed',+ ],+ origin,+ { timeout: REQUEST_TIMEOUT_MS },+ );+}+async function main() {const log = (message) => console.log(message);const apiKey = (process.env.LINEAR_API_KEY ?? '').trim();@@ -1051,6 +1180,12 @@ async function main() {channel,readChangesetProse: (candidate, ctx) => realReadChangesetProse(candidate, ctx),postReply: realPostReply,+ readIssueClosure: createIssueClosureReader({+ readIssueState: (origin) => readIssueStateWith(gh, origin),+ queryCarriers: (url) =>+ linearGraphql({ apiKey, query: ISSUE_CARRIERS_QUERY, variables: { url }, log, fetchImpl }),+ }),+ closeIssue: realCloseIssue,recordNotification: async ({ issueId, url, title }) => {const data = await linearGraphql({fetchImpl,@@ -1074,6 +1209,7 @@ async function main() {linearRequests,deferred: result.deferred,posted: result.posted.length,+ closed: result.posted.filter((entry) => entry.closed).length,skipped: result.skipped,errored: result.errored,}),diff --git a/.github/scripts/write-back.test.mjs b/.github/scripts/write-back.test.mjsindex 24be484c2..a25851588 100644--- a/.github/scripts/write-back.test.mjs+++ b/.github/scripts/write-back.test.mjs@@ -8,6 +8,7 @@ import { deriveChannel } from './published-release-tags.mjs';import {CANDIDATE_QUERY,changesetDirFor,+ createIssueClosureReader,deriveVersionForFixRefs,findChangesetPath,isFixRepoInRemit,@@ -24,13 +25,14 @@ import {parseChangeset,parseMergeShaOutput,parseRetryAfterSeconds,+ readIssueStateWith,retryDelayMs,runFailureMessage,runWriteBack,selectGhToken,toNode,} from './write-back.mjs';-import { composeReply } from './write-back-gate.mjs';+import { composeReply, planIssueClose } from './write-back-gate.mjs';const GH_ISSUE = 'https://github.com/inkeep/open-knowledge/issues/769';const GH_PULL = 'https://github.com/inkeep/agents-private/pull/2844';@@ -66,6 +68,8 @@ function harness(overrides = {}) {readChangesetProse: async () => CHANGESET,postReply: async (origin, text) => writes.push({ kind: 'post', origin: origin.url, text }),recordNotification: async (marker) => writes.push({ kind: 'mark', url: marker.url }),+ readIssueClosure: async () => planIssueClose({ issueState: 'closed' }),+ closeIssue: async (origin) => writes.push({ kind: 'close', origin: origin.url }),classifyRelease: makeReleaseWindow({ releaseTag: 'v0.36.0', minimumVersion: '0.35.0' }),selfRepo: 'inkeep/open-knowledge',log: (m) => logs.push(m),@@ -1789,6 +1793,340 @@ describe('the beta leg', () => {});});+describe('closing the GitHub issue the stable reply answers', () => {+ const resolvedCarriers = [+ { identifier: 'PRD-7539', stateType: 'completed' },+ { identifier: 'PRD-8646', stateType: 'duplicate' },+ ];+ const closable = async () => planIssueClose({ issueState: 'open', carriers: resolvedCarriers });+ const counting = () => {+ const reads = [];+ return {+ reads,+ readIssueClosure: async (origin) => {+ reads.push(origin.url);+ return closable();+ },+ };+ };++ test('an open issue whose synced ticket was marked duplicate is closed after the reply', async () => {+ const h = harness({ live: true, readIssueClosure: closable });+ const result = await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post', 'close']);+ expect(h.writes.find((w) => w.kind === 'close').origin).toBe(GH_ISSUE);+ expect(result.posted).toMatchObject([{ identifier: 'PRD-7539', closed: true }]);+ expect(h.logs.some((m) => m.includes(`closed ${GH_ISSUE} for PRD-7539`))).toBe(true);+ });++ test('a ticket still open on the issue keeps it open and is named in the log', async () => {+ const h = harness({+ live: true,+ readIssueClosure: async () =>+ planIssueClose({+ issueState: 'open',+ carriers: [+ ...resolvedCarriers,+ { identifier: 'PRD-9002', stateType: 'triage' },+ { identifier: 'PRD-9001', stateType: 'started' },+ ],+ }),+ });+ const result = await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ expect(result.posted).toMatchObject([{ closed: false }]);+ expect(+ h.logs.some(+ (m) =>+ m.startsWith('::warning::') &&+ m.includes(`did not close ${GH_ISSUE} (open-carrier: PRD-9001, PRD-9002)`) &&+ m.includes('once every ticket on it is resolved'),+ ),+ ).toBe(true);+ });++ test('a carrier lookup that found nothing is reported as a lookup to check, not a ticket to wait on', async () => {+ const h = harness({+ live: true,+ readIssueClosure: async () => planIssueClose({ issueState: 'open', carriers: [] }),+ });+ await h.run();+ const line = h.logs.find((m) => m.includes(`did not close ${GH_ISSUE} (no-carrier)`));+ expect(line).toMatch(/^::warning::/);+ expect(line).toContain('no ticket was found under the canonical issue URL');+ expect(line).not.toContain('once every ticket on it is resolved');+ });++ test('a pull request behind an issue url is a notice, not advice to close it by hand', async () => {+ const h = harness({+ live: true,+ readIssueClosure: async () => planIssueClose({ issueState: 'pull-request' }),+ });+ await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ const line = h.logs.find((m) => m.includes(`did not close ${GH_ISSUE}`));+ expect(line).toMatch(/^::notice::/);+ expect(line).not.toContain('by hand');+ });++ test('a gone issue is not closed, and its failed reply needs a person once', async () => {+ const h = harness({+ live: true,+ readIssueClosure: async () => planIssueClose({ issueState: 'gone' }),+ postReply: async () => {+ throw new Error('gh: Not Found (HTTP 404)');+ },+ });+ const result = await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark']);+ expect(result.errored[0].disposition).toBe('needs-human');+ });++ test('a lost reply that was going to close the issue says the close is owed too', async () => {+ const h = harness({+ live: true,+ readIssueClosure: closable,+ postReply: async () => {+ throw new Error('HTTP 502');+ },+ });+ const result = await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark']);+ expect(result.errored[0].message).toContain('post the reply by hand, then close the issue');+ });++ test('a Linear throttle while reading the close stops the scan before any marker', async () => {+ const h = harness({+ live: true,+ listCandidates: async () => [candidate(), candidate({ id: 'uuid-2', identifier: 'PRD-2' })],+ readIssueClosure: async () => {+ throw new LinearRateLimitError(new Headers());+ },+ });+ const result = await h.run();+ expect(h.writes).toEqual([]);+ expect(result.errored).toHaveLength(1);+ expect(result.errored[0].disposition).toBe('retried-next-run');+ expect(result.deferred).toBe(1);+ });++ test('an issue Linear already closed from its own synced ticket is left alone', async () => {+ const h = harness({ live: true });+ await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ });++ test('the beta reply promises a follow-up, so it never inspects or closes the issue', async () => {+ const spy = counting();+ const h = harness({+ live: true,+ channel: 'beta',+ versionFor: async () => '0.37.0-beta.0',+ classifyRelease: makeReleaseWindow({+ releaseTag: 'v0.37.0-beta.1',+ minimumVersion: '0.37.0-beta.0',+ }),+ readIssueClosure: spy.readIssueClosure,+ });+ await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ expect(spy.reads).toEqual([]);+ });++ test('a Discord thread is answered but has nothing to close', async () => {+ const spy = counting();+ const h = harness({+ live: true,+ listCandidates: async () => [candidate({ attachmentUrls: [GH_PULL, DISCORD_THREAD] })],+ readIssueClosure: spy.readIssueClosure,+ });+ await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ expect(spy.reads).toEqual([]);+ });++ test('an origin already told about this release is neither replied to nor closed', async () => {+ const marker = notificationMarkerUrl({ version: '0.36.0', originUrl: GH_ISSUE });+ const spy = counting();+ const h = harness({+ live: true,+ listCandidates: async () => [candidate({ attachmentUrls: [GH_PULL, GH_ISSUE, marker] })],+ readIssueClosure: spy.readIssueClosure,+ });+ const result = await h.run();+ expect(result.skipped).toEqual([{ identifier: 'PRD-7539', reason: 'already-notified' }]);+ expect(h.writes).toEqual([]);+ expect(spy.reads).toEqual([]);+ });++ test('a close lost after the reply was sent needs a person, because no run will retry it', async () => {+ const h = harness({+ live: true,+ readIssueClosure: closable,+ closeIssue: async () => {+ throw new Error('HTTP 403: Resource not accessible by integration');+ },+ });+ const result = await h.run();+ expect(h.writes.map((w) => w.kind)).toEqual(['mark', 'post']);+ expect(result.posted).toMatchObject([{ closed: false }]);+ const [failure] = result.errored;+ expect(failure.disposition).toBe('needs-human');+ expect(failure.message).toContain('was sent but the issue did NOT close');+ expect(failure.message).toContain('close it by hand');+ const verdict = runFailureMessage(result);+ expect(verdict).toContain('ACTION REQUIRED: PRD-7539');+ expect(verdict).not.toContain('reply never sent');+ });++ test('a failed closure read stops before the marker, so the next run tries again', async () => {+ const h = harness({+ live: true,+ readIssueClosure: async () => {+ throw new Error('gh api issues/769 failed: HTTP 502');+ },+ });+ const result = await h.run();+ expect(h.writes).toEqual([]);+ expect(result.errored[0].disposition).toBe('retried-next-run');+ });++ test('a dry run reports the close it would make and makes none', async () => {+ const h = harness({ readIssueClosure: closable });+ const result = await h.run();+ expect(h.writes).toEqual([]);+ expect(result.posted).toMatchObject([{ dryRun: true, closed: true }]);+ expect(h.logs.some((m) => m.includes(`[dry run] would close ${GH_ISSUE} as completed`))).toBe(+ true,+ );+ });++ test('stable reconciliation refuses to run without a way to close what it answers', async () => {+ await expect(harness({ readIssueClosure: undefined }).run()).rejects.toThrow(+ /readIssueClosure/,+ );+ await expect(harness({ closeIssue: undefined }).run()).rejects.toThrow(/closeIssue/);+ });+});++describe('reading whether an answered issue may close', () => {+ const origin = {+ channel: 'github-issue',+ url: GH_ISSUE,+ owner: 'inkeep',+ repo: 'open-knowledge',+ number: 769,+ };+ const carriers = (nodes, hasNextPage = false) => ({+ attachmentsForURL: { pageInfo: { hasNextPage }, nodes },+ });+ const carrier = (identifier, type) => ({ issue: { identifier, state: { type } } });++ test('an issue that is already closed costs no Linear request', async () => {+ const queried = [];+ const read = createIssueClosureReader({+ readIssueState: async () => 'closed',+ queryCarriers: async (url) => {+ queried.push(url);+ return carriers([]);+ },+ });+ expect(await read(origin)).toMatchObject({ close: false, reason: 'already-closed' });+ expect(queried).toEqual([]);+ });++ test('the carriers are looked up under the issue url the sync uses and judged by state type', async () => {+ const queried = [];+ const read = createIssueClosureReader({+ readIssueState: async () => 'open',+ queryCarriers: async (url) => {+ queried.push(url);+ return carriers([carrier('PRD-8204', 'completed'), carrier('PRD-8646', 'duplicate')]);+ },+ });+ expect(await read({ ...origin, url: `${GH_ISSUE}#issuecomment-1` })).toMatchObject({+ close: true,+ });+ expect(queried).toEqual([GH_ISSUE]);+ });++ test('a pull request reached through an issue url is never closed', async () => {+ const read = createIssueClosureReader({+ readIssueState: async () => 'pull-request',+ queryCarriers: async () => carriers([carrier('PRD-8204', 'completed')]),+ });+ expect(await read(origin)).toMatchObject({ close: false, reason: 'not-an-open-issue' });+ });++ test('a carrier list cut off by paging is not mistaken for the whole list', async () => {+ const read = createIssueClosureReader({+ readIssueState: async () => 'open',+ queryCarriers: async () => carriers([carrier('PRD-8204', 'completed')], true),+ });+ expect(await read(origin)).toMatchObject({ close: false, reason: 'carriers-truncated' });+ });++ test('the state read asks GitHub for the issue, bounded, and tells a pull request apart', () => {+ const calls = [];+ const state = readIssueStateWith((args, target, options) => {+ calls.push({ args, target, options });+ return 'pull-request\n';+ }, origin);+ expect(state).toBe('pull-request');+ expect(calls).toEqual([+ {+ args: [+ 'api',+ 'repos/inkeep/open-knowledge/issues/769',+ '--jq',+ 'if .pull_request then "pull-request" else .state end',+ ],+ target: origin,+ options: { timeout: expect.any(Number) },+ },+ ]);+ });++ test('a missing or deleted issue reads as gone, so it settles instead of retrying every run', () => {+ const failing = (stderr) => () => {+ throw Object.assign(new Error('Command failed: gh api'), { stderr });+ };+ expect(readIssueStateWith(failing('gh: Not Found (HTTP 404)\n'), origin)).toBe('gone');+ expect(readIssueStateWith(failing('gh: This issue was deleted (HTTP 410)\n'), origin)).toBe(+ 'gone',+ );+ });++ test('any other failed state read throws, so the next run retries it before any marker', () => {+ const failing = (error) => () => {+ throw error;+ };+ expect(() =>+ readIssueStateWith(+ failing(Object.assign(new Error('gh'), { stderr: 'gh: Bad Gateway (HTTP 502)\n' })),+ origin,+ ),+ ).toThrow(/issues\/769 failed: gh: Bad Gateway \(HTTP 502\)/);+ expect(() =>+ readIssueStateWith(+ failing(Object.assign(new Error('gh'), { stderr: 'gh: Forbidden (HTTP 403)\n' })),+ origin,+ ),+ ).toThrow(/HTTP 403/);+ expect(() => readIssueStateWith(failing(new Error('spawnSync gh ETIMEDOUT')), origin)).toThrow(+ /ETIMEDOUT/,+ );+ });++ test('a reply with no attachments connection throws rather than reading as no carriers', async () => {+ const read = createIssueClosureReader({+ readIssueState: async () => 'open',+ queryCarriers: async () => ({}),+ });+ await expect(read(origin)).rejects.toThrow(/no attachments connection/);+ });+});+describe('write-back boundary rule self-test', () => {const source = (tags = 'published()', contains = 'containment()') => `import { realPublishedReleaseTags as published } from './published-release-tags.mjs';diff --git a/.github/workflows/write-back.yml b/.github/workflows/write-back.ymlindex 5f94f9bf9..50afbf8c7 100644--- a/.github/workflows/write-back.yml+++ b/.github/workflows/write-back.yml@@ -60,7 +60,8 @@ on:permissions:contents: read- # Posting the reply onto a GitHub issue origin in this repo.+ # Posting the reply onto a GitHub issue origin in this repo, and closing that+ # issue with the stable reply once every Linear ticket carrying it is resolved.issues: writejobs: