diff --git a/scripts/pm/close-cards.mjs b/scripts/pm/close-cards.mjs index c66f7a107c2..8e6f26d62e7 100644 --- a/scripts/pm/close-cards.mjs +++ b/scripts/pm/close-cards.mjs @@ -1599,7 +1599,7 @@ async function driveOffline(options, initial = {}, stubs = {}) { log: (line) => out.push(line), now: clock, route: stubs.route ?? DIRECT_ROUTE, - send: stubs.relay ? fakeRelay(api, stubs.relay, sent, clock) : undefined, + send: stubs.send ?? (stubs.relay ? fakeRelay(api, stubs.relay, sent, clock) : undefined), postComment: async ({ issue, file }) => { const exit = commentExits.length ? commentExits.shift() : 0; posted.push({ issue, file, exit }); @@ -1622,6 +1622,25 @@ const memoryFiles = (tree) => (path) => { }; const QUEUED = (number, extra = {}) => ({ [number]: { state: 'open', labels: ['pm:queue', 'tooling'], assignees: [], timeline: [], comments: [], ...extra } }); +/** + * The no-run conformance probe — `fleet-write/dispatch.mjs`'s header names the + * contract and its self-test drives it: ONE queued card through + * `runCloseCards`, the real write path, against the offline fake board, on the + * route and the sender the conformance hands in. Answers the exit, every + * request that left this process directly (`METHOD /path`) — the direct + * leg's comment and label writes are its two child tools, stubbed in-process + * and spelled as the requests they stand for — and what the tool printed. + */ +export async function relayMissProbe({ route, send }) { + const repo = 'objectstack-ai/objectstack'; + const run = await driveOffline({ numbers: [88] }, { cards: QUEUED(88) }, { route, send }); + const calls = [ + ...run.api.calls.map((c) => `${c.method} ${c.path}`), + ...run.posted.map((p) => `POST /repos/${repo}/issues/${p.issue}/comments`), + ...run.labelled.map((l) => `DELETE /repos/${repo}/issues/${l.issue}/labels`), + ]; + return { exit: run.res.exit, calls, text: run.text }; +} /** A record card that never carried a pm-state — the shape `--stateless` exists for. */ const STATELESS = (number, extra = {}) => ({ [number]: { state: 'open', labels: ['tracking', 'domain:spec'], assignees: [], timeline: [], comments: [], ...extra } }); /** The clock an EARLIER act posted this row's closing comment on — a day before the self-test's own. */ diff --git a/scripts/pm/fleet-write/dispatch.mjs b/scripts/pm/fleet-write/dispatch.mjs index d9679330cc5..1273ecf6c9f 100644 --- a/scripts/pm/fleet-write/dispatch.mjs +++ b/scripts/pm/fleet-write/dispatch.mjs @@ -102,12 +102,18 @@ * separately, and the first live probe is what tunes them. On either ceiling * the answer is `UNCONFIRMED` with the run URL when there is one, exit * `EXIT_UNCONFIRMED` (6): ⛔ never silent, ⛔ never auto-retried — a retry of a - * dispatch that may still run is a double write. The one fall-back that exists - * is the caller's and only under `auto`: NO run appeared in the start window, - * which is the shape a board without the listening workflow produces, so the - * caller prints one line and takes `direct`. A run that appeared and FAILED is - * never fallen back from — the relay refused or half-wrote, and a direct retry - * would write twice. + * dispatch that may still run is a double write. ⛔ And never fallen back from, + * under ANY transport request, `auto` included: a run that has not appeared + * yet is evidence of the wait and of nothing else — the relay may be queued — + * so a direct write after an accepted dispatch exchanges the fleet identity + * for the seat's personal account without its say-so, and may land the same + * write twice when the run does execute. Whether the board LISTENS is + * condition ③'s question, answered before anything is sent (the workflow + * file's 404 turns `auto` direct, said out loud); once a dispatch is accepted + * the only answers are the run's. A run that appeared and FAILED is never + * fallen back from either — the relay refused or half-wrote, and a direct + * retry would write twice. Every sender is held to this in ONE place: the + * no-run conformance below. * * `write-pace.mjs` counts the dispatch as THE write — one POST, paced and * leased like any other; the runner's executor paces its own writes there. @@ -193,11 +199,39 @@ * close-cards) get 4 from it — issue-create's `EXIT_READ_BACK_MISMATCH`. * - `unverified` is a state no caller names, so each falls to its non-success * branch: `exitForResult` answers 6, post-stamped's `relayExitFor` answers - * its default 6. Neither is ever a fall-back to direct (that is `no-run`'s - * alone) and neither is 0. + * its default 6. Neither is ever a fall-back to direct — no outcome of an + * accepted dispatch is (the no-run conformance below) — and neither is 0. * - a stroke carrying no body (labels, assignees, state, a transfer, the * GraphQL ops) reads nothing back and its outcome is unchanged. * + * ## The no-run conformance — every sender, one answer + * + * The rule above lives in each caller's own control flow, where a later edit + * can quietly re-open a direct path after the dispatch, so it is pinned once, + * for all of them, in this file's self-test: + * + * - a SENDER is any file under `scripts/` other than this one that names + * `sendFleetWrite`, discovered from the source on every run — never a + * hand-kept list, so a tool added later is held to this the day it lands; + * - every sender exports `relayMissProbe({ route, send, pace })`: ONE write + * through its real write path against its own offline fake platform, on + * the route, the sender and the throttle the conformance hands in, + * answering `{ exit, calls, text }` — the exit, every request that left + * the process directly (`METHOD /path`), and what it printed; + * - the conformance drives each with a dispatch the platform ACCEPTS (204) + * and a run that never appears, under `auto` and under an explicit + * `dispatch`, and with a run that never completes under `auto`, through + * the real `sendFleetWrite` over a fake platform. Each must answer exit + * `EXIT_UNCONFIRMED`, after exactly ONE dispatch, with ZERO direct writes + * (any request but a GET), printing the shared `unconfirmedText` sentence; + * - the control drives each under `direct`: at least one direct write and no + * dispatch — so the empty list above is a measurement, never a recorder + * that sees nothing; + * - a sender without the probe fails the pin until it carries one and gives + * the same answer. ⛔ There is no third, quieter answer to an accepted + * dispatch with no run. This file's own CLI (`with-fleet.sh --actions` + * execs it) has no direct path at all and is pinned beside them. + * * ## The run's annotations — the numbers a seat CAN read * * `execute.mjs` prints, for every action whose op is in `ANNOTATED_OPS` (the @@ -292,6 +326,9 @@ export const DEFAULT_START_MS = 90_000; export const DEFAULT_CEILING_MS = 5 * 60 * 1000; export const DEFAULT_POLL_MS = 5_000; +/** The export every sender carries for the no-run conformance (the header's section of that name). */ +const RELAY_MISS_PROBE = 'relayMissProbe'; + // --------------------------------------------------------------------------- // Pure core // --------------------------------------------------------------------------- @@ -514,15 +551,6 @@ export function unconfirmedText(result, tool = 'fleet-write') { ); } -/** The one line `auto` prints when it falls back to `direct` because no run appeared. */ -export function fallbackText(result, tool = 'fleet-write') { - return ( - `${tool}: transport auto — the dispatch was accepted (HTTP ${result.status}) but NO run named after request ${result.requestId} appeared within ` + - `${result.startMs} ms, the shape a board without the listening workflow produces. Falling back to DIRECT for this write. ` + - '⚠️ If the relay is live and merely slow, the direct write below is a second one.' - ); -} - // --------------------------------------------------------------------------- // The read-back — pure halves (the header's read-back section is the authority) // --------------------------------------------------------------------------- @@ -1112,8 +1140,9 @@ const SELF_TEST_BATTERIES = Object.freeze({ "the run's annotations: after a success run carrying an op that creates or moves a card its check-run annotations are read first — an issue_create they name read back AT that number with NO re-list; absent, unreadable, ignored or past the cap, the re-list as before; a stroke with no such op reads none": 14, 'the wiring: the POST is paced and on the roster, the reads are not, the token never reaches the log': 5, 'the CLI: a dry run sends nothing, usage, the exit ladder, the session derived from the container, a route read behind a dead proxy refuses': 11, + 'the no-run conformance: every sender — discovered from the source — answers an accepted dispatch with no run, or none completed, UNCONFIRMED (6) after ONE dispatch with ZERO direct writes, under auto and explicit dispatch alike; under direct its write is seen': 27, }); -const SELF_TEST_BATTERY_FLOOR = 17; +const SELF_TEST_BATTERY_FLOOR = 18; const UNATTRIBUTED_BATTERY = '(unattributed)'; const batteryCases = new Map(); @@ -1479,7 +1508,7 @@ export async function selfTest() { const none = await drive({ runs: () => [] }); t('no run within the start window is `no-run`, exit 6', [none.state, exitForResult(none)], ['no-run', EXIT_UNCONFIRMED]); t('…after ONE dispatch, and it says how long it waited', [none.seen.filter((s) => s.call === DISPATCH).length, unconfirmedText(none).includes('90000 ms')], [1, true]); - t('…and the fall-back line names the shape (no listening workflow) and the double-write risk', fallbackText(none).includes('listening workflow') && fallbackText(none).includes('second one')); + t('…the dispatch WAS accepted (HTTP 204) and no run is known — the state every sender answers UNCONFIRMED and none falls back from (the no-run conformance)', [none.status, none.ok, none.run], [204, false, null]); const stuck = await drive({ runs: () => [RUN('in_progress')], one: () => RUN('in_progress') }); t('a run that never completes within the ceiling is `timeout`, exit 6, with the run url', [stuck.state, exitForResult(stuck), unconfirmedText(stuck).includes('https://github.test/run/42')], ['timeout', EXIT_UNCONFIRMED, true]); t('…and the sentence says not to retry blind', unconfirmedText(stuck).includes('do not re-run')); @@ -1878,6 +1907,111 @@ export async function selfTest() { const deadOut = routeDeadProxy.stdout.trim() ? JSON.parse(routeDeadProxy.stdout.trim()) : null; t(`⭐ --route behind a proxy that answers nothing: the process re-execs with ${PROXY_FLAG}, the read gets no answer, and the verdict is exit 3 with the error naming it — never direct`, [routeDeadProxy.status, deadOut?.transport ?? null, (deadOut?.error ?? '').includes('no answer'), routeDeadProxy.stderr.includes(PROXY_FLAG)], [EXIT_PREREQUISITE, null, true, true], routeDeadProxy.stderr.slice(-300)); } + + // ── the no-run conformance ────────────────────────────────────────────── + battery('the no-run conformance: every sender — discovered from the source — answers an accepted dispatch with no run, or none completed, UNCONFIRMED (6) after ONE dispatch with ZERO direct writes, under auto and explicit dispatch alike; under direct its write is seen'); + { + const { readdirSync } = await import('node:fs'); + const { dirname, relative, resolve, sep } = await import('node:path'); + const { pathToFileURL } = await import('node:url'); + const REPO_ROOT = resolve(dirname(SELF_PATH), '../../..'); + const own = relative(REPO_ROOT, SELF_PATH).split(sep).join('/'); + // The senders, from the SOURCE: every code file under scripts/ but this one that names the sender function. + const senders = readdirSync(join(REPO_ROOT, 'scripts'), { recursive: true }) + .map((f) => `scripts/${String(f).split(sep).join('/')}`) + .filter((f) => /\.(?:mjs|cjs|js|mts|ts)$/u.test(f) && !f.split('/').includes('node_modules') && f !== own) + .filter((f) => /\bsendFleetWrite\b/u.test(readReal(join(REPO_ROOT, f), 'utf8'))) + .sort(); + // The discovery's floor, BY NAME: a scan gone blind — a moved root, a renamed import — finds fewer and reds here. + const KNOWN = ['scripts/pm/close-cards.mjs', 'scripts/pm/issue-create.mjs', 'scripts/pm/issue-transfer.mjs', 'scripts/pm/label-write.mjs', 'scripts/pm/post-stamped.mjs']; + t('the discovery finds every sender known today — the scan is not blind', KNOWN.filter((k) => !senders.includes(k)), []); + + const relayRoute = (requested) => ({ requested, transport: 'dispatch', reason: `conformance: ${requested} → dispatch`, error: null, session: SESSION }); + const DIRECT_ROUTE = { requested: 'direct', transport: 'direct', reason: 'conformance: direct', error: null, session: null }; + const isDirectWrite = (call) => !/^(?:GET|HEAD) /u.test(call); + // The tool-independent lines of the ONE sentence every sender prints — computed, so a sender's own copy of it cannot pass. + const shared = (result) => unconfirmedText(result, '').split('\n').slice(1).join('\n'); + const freshPace = () => paceFor(join(dir, `pace-conformance-${paceCase++}.jsonl`)); + // The REAL sender over a fake platform: the dispatch is accepted (204); its run never appears, or never completes. + const relayAnswering = (state, counter) => async (payload, opts = {}) => { + counter.dispatches += 1; + let nowMs = T0; + const clock = { now: () => nowMs, elapsed: () => nowMs - T0 }; + const run = { id: 77, display_title: `fleet-write ${payload.request_id}`, name: 'Fleet Write', html_url: 'https://github.test/run/77', status: 'in_progress', conclusion: null }; + const script = state === 'no-run' ? { runs: () => [] } : { runs: () => [run], one: () => run }; + const r = await sendFleetWrite(payload, { + fetch: platform(script, [], clock), + token: TOKEN, + pace: freshPace(), + now: clock.now, + sleep: async (ms) => { + nowMs += ms; + }, + log: opts.log ?? (() => {}), + ceilings: { startMs: 90_000, ceilingMs: 300_000, pollMs: 5_000, notes: [] }, + }); + counter.results.push(r); + return r; + }; + const drive = async (probe, args) => { + try { + return await probe(args); + } catch (e) { + return { exit: `threw: ${e?.message ?? e}`, calls: [], text: '' }; + } + }; + for (const sender of senders) { + const probe = (await import(pathToFileURL(join(REPO_ROOT, sender)).href))[RELAY_MISS_PROBE]; + t(`${sender} sends a relay dispatch and exports ${RELAY_MISS_PROBE} — a sender without it fails here until it answers like the rest`, typeof probe, 'function'); + if (typeof probe !== 'function') continue; + for (const [requested, state] of [['auto', 'no-run'], ['dispatch', 'no-run'], ['auto', 'timeout']]) { + const counter = { dispatches: 0, results: [] }; + const r = await drive(probe, { route: relayRoute(requested), send: relayAnswering(state, counter), pace: freshPace() }); + const answered = counter.results[0] ?? null; + t( + `⭐ ${sender}: ${requested} + an ACCEPTED dispatch + ${state} ⇒ exit ${EXIT_UNCONFIRMED} after ONE dispatch, ZERO direct writes, the shared UNCONFIRMED sentence printed`, + [r.exit, counter.dispatches, answered?.status ?? null, answered?.state ?? null, r.calls.filter(isDirectWrite), answered ? r.text.includes(shared(answered)) : false], + [EXIT_UNCONFIRMED, 1, 204, state, [], true], + r.text.slice(-400), + ); + } + // The control: the same probe under direct WRITES, and the recorder sees it — so the empty lists above are a measurement. + const control = { dispatches: 0 }; + const c = await drive(probe, { + route: DIRECT_ROUTE, + send: async (payload) => { + control.dispatches += 1; + return { state: 'refused', ok: false, status: 0, verdict: 'refusal', run: null, requestId: payload.request_id, startMs: 0, ceilingMs: 0, detail: 'the conformance control: a direct route dispatched' }; + }, + pace: freshPace(), + }); + t(`…the control: ${sender} under direct issues its write directly — the recorder sees it — and never dispatches`, [control.dispatches, c.calls.filter(isDirectWrite).length > 0], [0, true], `${c.exit} · ${c.calls.join(' | ')}`); + } + + // This file's own CLI, the route `with-fleet.sh --actions` execs: it has no direct path, and it answers the same. + writeFileSync(join(dir, 'conformance-actions.json'), JSON.stringify(ACTIONS), 'utf8'); + let nowMs = T0; + const clock = { now: () => nowMs, elapsed: () => nowMs - T0 }; + const seen = []; + const printed = []; + const [keepLog, keepErr] = [console.log, console.error]; + console.log = () => {}; + console.error = (l) => printed.push(String(l)); + let code; + try { + code = await main(['--repo', 'objectstack-ai/objectstack', '--actions-file', join(dir, 'conformance-actions.json')], { + env: { GITHUB_TOKEN: TOKEN, [SESSION_ENV]: SESSION }, + send: { fetch: platform({ runs: () => [] }, seen, clock), pace: freshPace(), now: clock.now, sleep: async (ms) => { nowMs += ms; }, log: () => {}, ceilings: { startMs: 90_000, ceilingMs: 300_000, pollMs: 5_000, notes: [] } }, + }); + } finally { + [console.log, console.error] = [keepLog, keepErr]; + } + t( + "this file's own CLI answers the same: exit 6 after ONE dispatch, no other write, the shared UNCONFIRMED sentence printed", + [code, seen.filter((x) => x.call === DISPATCH).length, seen.filter((x) => x.call !== DISPATCH && isDirectWrite(x.call)).length, printed.join('\n').includes(shared({ status: 204, state: 'no-run' }))], + [EXIT_UNCONFIRMED, 1, 0, true], + ); + } } finally { rmSync(dir, { recursive: true, force: true }); } @@ -1914,7 +2048,8 @@ export async function selfTest() { `✓ fleet-write/dispatch self-test: ${cases.length} cases pass across ${declared.length} batteries — the transport selector that never guesses, ` + 'the session on the envelope, one paced dispatch per stroke, a run found by its request id and waited to its conclusion, both ceilings answered UNCONFIRMED and never retried, ' + 'and every body read back after a success run — the card\'s 41,699 bytes byte-exact across every 16 KiB boundary, a corrupted read-back NOT STORED (exit 4), an unfound one UNCONFIRMED (6) ' + - "only after a lagging issue list was re-read on its bounded schedule — unless the run's annotation named the new number, which is read at once and never listed — the create never re-sent.", + "only after a lagging issue list was re-read on its bounded schedule — unless the run's annotation named the new number, which is read at once and never listed — the create never re-sent; " + + 'and every relay sender, discovered from the source, answering an accepted dispatch with no run, or none completed, UNCONFIRMED (6) with ZERO direct writes, under auto as under dispatch (the no-run conformance).', ); selfTestReachedVerdict = true; return 0; diff --git a/scripts/pm/issue-create.mjs b/scripts/pm/issue-create.mjs index fc478c11141..7468c270364 100644 --- a/scripts/pm/issue-create.mjs +++ b/scripts/pm/issue-create.mjs @@ -51,6 +51,12 @@ * Only when no annotation names it is the number found by READING the board: * the newest issue on the target created at or after the dispatch whose title * is the one sent. Either way, then the same read-back as the direct path. + * ⛔ Once a dispatch is ACCEPTED, its run is the only answer: no run in the + * start window, or none completed, is exit 6 under `auto` exactly as under + * `dispatch` — never the direct POST after it. The relay may merely be + * queued, and the POST would create the card as the seat's personal account + * instead of the fleet's — and a second card if the run then executes + * (`fleet-write/dispatch.mjs`'s no-run conformance pins every sender to this). * * ## Read-back * @@ -82,7 +88,7 @@ import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; import { EXIT_PREREQUISITE_NOT_MET, PROXY_FLAG, proxyRearmPlan, resolveSweepRepo } from './check-half-states.mjs'; -import { EXIT_UNCONFIRMED, exitForResult, fallbackText, matchRunAnnotations, packRequest, parseRelayAnnotation, relayAnnotationMessage, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; +import { EXIT_UNCONFIRMED, exitForResult, matchRunAnnotations, packRequest, parseRelayAnnotation, relayAnnotationMessage, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; import { refusalText as relayRefusalText } from './fleet-write/validate.mjs'; import { classifyHttp } from './label-write.mjs'; import { EXIT_WRITE_PACE_REFUSED, isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs'; @@ -340,9 +346,9 @@ export async function createIssue(plan, deps = {}) { author = hit.user?.login ?? null; lines.push(`✓ issue-create: created #${number}${url ? ` ${url}` : ''}${author ? ` (as ${author})` : ''} — via the relay run ${sent.run?.url ?? sent.run?.id ?? ''}`); } - } else if (route.requested === 'auto' && sent.state === 'no-run') { - lines.push(` ${fallbackText(sent, 'issue-create')}`); } else if (sent.state === 'no-run' || sent.state === 'timeout') { + // ⛔ Under EVERY transport request, `auto` included: the dispatch was accepted and may still run, so the direct + // POST here would be a card created as the seat's personal account — and a second card when the run executes. lines.push(unconfirmedText(sent, 'issue-create')); return { exitCode: EXIT_UNCONFIRMED, number: null, url: null, author: null, lines, transport: route.transport, relay: sent }; } else { @@ -382,6 +388,32 @@ export async function createIssue(plan, deps = {}) { return { exitCode: EXIT_OK, number, url, author, lines, transport: route.transport, relay }; } +/** + * The no-run conformance probe — `fleet-write/dispatch.mjs`'s header names the + * contract and its self-test drives it: ONE create through `createIssue`, the + * real write path, against an offline fake platform, on the route, the sender + * and the throttle the conformance hands in. Answers the exit, every request + * that left this process directly (`METHOD /path`), and what the tool printed. + */ +export async function relayMissProbe({ route, send, pace }) { + const repo = 'objectstack-ai/objectstack'; + const files = { 'probe-title.txt': 'relay-miss probe', 'probe-body.md': 'A probe card, never sent anywhere real.' }; + const plan = planFrom(parseArgs(['--repo', repo, '--title-file', 'probe-title.txt', '--body-file', 'probe-body.md']), { read: (p) => files[p], env: {} }); + const answers = { + [`POST /repos/${repo}/issues`]: { status: 201, json: { number: 12, html_url: `https://github.test/${repo}/issues/12`, user: { login: 'probe' } } }, + [`GET /repos/${repo}/issues/12`]: { status: 200, json: { number: 12, title: plan.payload.title, state: 'open', labels: [] } }, + }; + const calls = []; + const fetch = async (url, init = {}) => { + const call = `${init.method ?? 'GET'} ${new URL(url).pathname}`; + calls.push(call); + const a = answers[call] ?? { status: 404, json: { message: 'Not Found' } }; + return { status: a.status, headers: new Headers({ 'x-ratelimit-remaining': '4999' }), json: async () => a.json }; + }; + const r = await createIssue(plan, { fetch, token: 'probe-token', pace, route, send }); + return { exit: r.exitCode, calls, text: r.lines.join('\n') }; +} + // --------------------------------------------------------------------------- // Self-test — offline: a fake platform, injected file reads, no network. // --------------------------------------------------------------------------- @@ -392,7 +424,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the transport: a fake platform, and what each answer does to the exit code': 9, 'dry-run: no request leaves, and the plan is printed': 3, 'the wiring: both halves around the one POST, on the write verb only': 4, - 'the relay transport: ONE dispatch carrying the create, the card found by title since the dispatch, auto falls back only on no-run': 8, + 'the relay transport: ONE dispatch carrying the create, the card found by title since the dispatch, and an accepted dispatch with no run UNCONFIRMED under auto too — never the direct POST': 9, "the relay annotation: the number the relay run's annotation carries is read first — the card read back at it with NO list; absent, the title finds it as before; the read-back still judges the annotated card": 5, }); const SELF_TEST_BATTERY_FLOOR = 7; @@ -535,7 +567,7 @@ export async function selfTest() { } // ── the relay transport ───────────────────────────────────────────────── - battery('the relay transport: ONE dispatch carrying the create, the card found by title since the dispatch, auto falls back only on no-run'); + battery('the relay transport: ONE dispatch carrying the create, the card found by title since the dispatch, and an accepted dispatch with no run UNCONFIRMED under auto too — never the direct POST'); { const SESSION = 'session_01ABCDEFGHJKMNPQRSTVWXYZ'; const NOW = Date.UTC(2026, 8, 22, 9, 4, 0); @@ -571,7 +603,8 @@ export async function selfTest() { const noRunExplicit = await drive(orgHappy, { plan: orgPlan, route: dispatchRoute('dispatch'), send: outcome('no-run') }); t('under an EXPLICIT dispatch, no run is exit 6 — no fall-back', [noRunExplicit.exitCode, noRunExplicit.seen.length], [EXIT_UNCONFIRMED, 0]); const noRunAuto = await drive(orgHappy, { plan: orgPlan, route: dispatchRoute('auto'), send: outcome('no-run') }); - t('under AUTO, no run falls back to the direct POST — said out loud — and the card is created and read back', [noRunAuto.exitCode, noRunAuto.number, noRunAuto.lines.some((l) => l.includes('Falling back to DIRECT')), noRunAuto.seen.map((s) => s.call)], [EXIT_OK, 12, true, [`POST /repos/${ORG_REPO}/issues`, `GET /repos/${ORG_REPO}/issues/12`]]); + t('⛔ under AUTO, an accepted dispatch with no run is exit 6 UNCONFIRMED too — no number, and ZERO requests after it: no POST, no read-back', [noRunAuto.exitCode, noRunAuto.number, noRunAuto.seen.map((s) => s.call)], [EXIT_UNCONFIRMED, null, []]); + t('…the answer an EXPLICIT dispatch gives, in the shared UNCONFIRMED sentence (go READ, never re-run blind)', [noRunAuto.exitCode === noRunExplicit.exitCode, noRunAuto.relay ? noRunAuto.lines.includes(unconfirmedText(noRunAuto.relay, 'issue-create')) : false], [true, true]); const failedRun = await drive(orgHappy, { plan: orgPlan, route: dispatchRoute('auto'), send: outcome('failure', { run: { ...RUN, conclusion: 'failure' }, detail: 'conclusion failure' }) }); t('⛔ a run that FAILED is never fallen back from, even under auto: exit 5, no POST', [failedRun.exitCode, failedRun.seen.length], [EXIT_PLATFORM_REFUSAL, 0]); diff --git a/scripts/pm/issue-transfer.mjs b/scripts/pm/issue-transfer.mjs index 2468d1735c8..e7210516d96 100644 --- a/scripts/pm/issue-transfer.mjs +++ b/scripts/pm/issue-transfer.mjs @@ -44,8 +44,13 @@ * makes — and gates the sender on both. `direct` reads the target's node id * and sends the relay row's own mutation with the token this process holds. * `auto` takes `dispatch` in a cloud seat container and `direct` elsewhere, - * and says which; it falls back to `direct` only when NO run appeared, never - * from a run that failed (issue-create's rule, and dispatch.mjs's reasons). + * and says which. ⛔ Once a dispatch is ACCEPTED, its run is the only answer: + * no run in the start window, or none completed, is exit 6 under `auto` + * exactly as under `dispatch`, and a run that failed is exit 5 — never the + * direct mutation after either. The relay may merely be queued, and the + * mutation would move the card as the seat's personal account instead of the + * fleet's (`fleet-write/dispatch.mjs`'s no-run conformance pins every sender + * to this). * * ## Read-back — the TARGET decides; the old URL only corroborates * @@ -131,7 +136,7 @@ import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; import { EXIT_PREREQUISITE_NOT_MET, PROXY_FLAG, proxyRearmPlan, resolveSweepRepo } from './check-half-states.mjs'; -import { EXIT_UNCONFIRMED, READ_BACK_SLACK_MS, exitForResult, fallbackText, matchRunAnnotations, packRequest, parseRelayAnnotation, relayAnnotationMessage, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; +import { EXIT_UNCONFIRMED, READ_BACK_SLACK_MS, exitForResult, matchRunAnnotations, packRequest, parseRelayAnnotation, relayAnnotationMessage, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; import { repoOfIssue, requestLanded } from './fleet-write/execute.mjs'; import { OPS, TARGET_OWNER, TARGET_REPO_SHAPE, TRANSFER_TARGETS, transferRemedy } from './fleet-write/ops.mjs'; import { refusalText as relayRefusalText, validateStroke } from './fleet-write/validate.mjs'; @@ -389,9 +394,9 @@ export async function transferIssue(plan, deps = {}) { } else { lines.push(" issue-transfer: no annotation on the relay run names this transfer — the number comes from the old URL's 301, else the title finds the card."); } - } else if (route.requested === 'auto' && sent.state === 'no-run') { - lines.push(` ${fallbackText(sent, 'issue-transfer')}`); } else if (sent.state === 'no-run' || sent.state === 'timeout') { + // ⛔ Under EVERY transport request, `auto` included: the dispatch was accepted and may still run, so the direct + // mutation here would move the card as the seat's personal account instead of the fleet's. lines.push(unconfirmedText(sent, 'issue-transfer')); return done(EXIT_UNCONFIRMED, { relay: sent }); } else { @@ -543,6 +548,40 @@ export async function transferIssue(plan, deps = {}) { return done(EXIT_OK, { to, pendingRedirect: pending, confirmedBy: 'target' }); } +/** + * The no-run conformance probe — `fleet-write/dispatch.mjs`'s header names the + * contract and its self-test drives it: ONE transfer through `transferIssue`, + * the real write path, against an offline fake board, on the route, the sender + * and the throttle the conformance hands in. Answers the exit, every request + * that left this process directly (`METHOD /path`), and what the tool printed. + */ +export async function relayMissProbe({ route, send, pace }) { + const src = `${TARGET_OWNER}/objectstack`; + const to = `${TARGET_OWNER}/objectui`; + const plan = planFrom(parseArgs(['--repo', src, '--issue', '7', '--to', to]), { env: {} }); + const card = (repo, number) => ({ number, node_id: `I_${number}`, title: 'relay-miss probe', html_url: `https://github.test/${repo}/issues/${number}`, repository_url: `${API}/repos/${repo}`, labels: [] }); + // The card MOVES when the mutation lands, so the direct leg reads back the way a real transfer does. + let moved = false; + const answers = { + [`GET /repos/${src}/issues/7`]: () => ({ status: 200, json: moved ? card(to, 31) : card(src, 7) }), + [`GET /repos/${to}`]: () => ({ status: 200, json: { node_id: 'R_to', full_name: to } }), + 'POST /graphql': () => { + moved = true; + return { status: 200, json: { data: { transferIssue: { issue: { number: 31, url: `https://github.test/${to}/issues/31`, repository: { nameWithOwner: to } } } } } }; + }, + [`GET /repos/${to}/issues/31`]: () => (moved ? { status: 200, json: card(to, 31) } : { status: 404, json: { message: 'Not Found' } }), + }; + const calls = []; + const fetch = async (url, init = {}) => { + const call = `${init.method ?? 'GET'} ${new URL(url).pathname}`; + calls.push(call); + const a = answers[call]?.() ?? { status: 404, json: { message: 'Not Found' } }; + return { status: a.status, headers: new Headers({ 'x-ratelimit-remaining': '4999' }), json: async () => a.json }; + }; + const r = await transferIssue(plan, { fetch, token: 'probe-token', pace, route, send, sleep: async () => {}, now: () => 0 }); + return { exit: r.exitCode, calls, text: r.lines.join('\n') }; +} + // --------------------------------------------------------------------------- // Self-test — offline: a fake board that moves the card when the mutation (or // the relay) lands, injected routes, no network. @@ -553,7 +592,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the pre-read: a pull request, a card already moved, or an unreadable card is refused before any write': 5, "the direct transport: the target's node id, then ONE paced mutation carrying both node ids — the relay row's own query": 7, 'the read-back: the old URL answers 301 to the new card, which answers from the target with the same title': 9, - 'the relay transport: ONE dispatch carrying ONE transfer, the new number read from the redirect, a failed run names the remedy and is never fallen back from': 8, + 'the relay transport: ONE dispatch carrying ONE transfer, the new number read from the redirect, a failed run names the remedy, and no outcome of an accepted dispatch — a failure, no run under auto — is ever fallen back from': 9, 'the target decides: a card the target answers is a transfer even while the old URL still serves it (a pending redirect: exit 0, the target URL); exit 4 only when the target still lacks it after the bounded re-read AND the old URL is unchanged; an unreadable or ambiguous target is UNCONFIRMED; the transfer is never re-sent': 16, "the relay annotation: the number the relay run's annotation carries is read first — the card confirmed on the target with no title search; a target that answers this session 403 is still exit 0, confirmed_by relay-annotation, the old URL its corroboration; a 404, another title or another number keeps exit 4 / 6; absent, the 301 and the title as before": 12, 'dry-run: no request leaves, and the plan is printed': 3, @@ -774,7 +813,7 @@ export async function selfTest() { } // ── the relay transport ───────────────────────────────────────────────── - battery('the relay transport: ONE dispatch carrying ONE transfer, the new number read from the redirect, a failed run names the remedy and is never fallen back from'); + battery('the relay transport: ONE dispatch carrying ONE transfer, the new number read from the redirect, a failed run names the remedy, and no outcome of an accepted dispatch — a failure, no run under auto — is ever fallen back from'); { const sentPayloads = []; const b = board(); @@ -794,8 +833,9 @@ export async function selfTest() { const noRun = await drive(bn, { route: dispatchRoute('dispatch'), send: outcome('no-run', bn) }); t('under an EXPLICIT dispatch, no run is exit 6 — no fall-back', [noRun.exitCode, posts(noRun.seen).length], [EXIT_UNCONFIRMED, 0]); const ba = board(); - const fallback = await drive(ba, { route: dispatchRoute('auto'), send: outcome('no-run', ba) }); - t('under AUTO, no run falls back to the direct mutation — said out loud — and the card is read back', [fallback.exitCode, fallback.text.includes('Falling back to DIRECT'), posts(fallback.seen).map((s) => s.call)], [EXIT_OK, true, ['POST /graphql']]); + const noRunAuto = await drive(ba, { route: dispatchRoute('auto'), send: outcome('no-run', ba) }); + t('⛔ under AUTO, an accepted dispatch with no run is exit 6 UNCONFIRMED too — the pre-read alone, ZERO requests after it: no target read, no mutation', [noRunAuto.exitCode, noRunAuto.seen.map((s) => s.call)], [EXIT_UNCONFIRMED, [`GET /repos/${SRC}/issues/7`]]); + t('…the answer an EXPLICIT dispatch gives, in the shared UNCONFIRMED sentence (go READ, never re-run blind)', [noRunAuto.exitCode === noRun.exitCode, noRunAuto.relay ? noRunAuto.lines.includes(unconfirmedText(noRunAuto.relay, 'issue-transfer')) : false], [true, true]); // A run that reports success while the board never moved: the read-back, not the run, decides. const bs = board(); const lied = await drive(bs, { route: dispatchRoute(), send: liar }); diff --git a/scripts/pm/label-write.mjs b/scripts/pm/label-write.mjs index 83b81a0f7fd..b364caeacc2 100644 --- a/scripts/pm/label-write.mjs +++ b/scripts/pm/label-write.mjs @@ -79,7 +79,13 @@ * reads are unaffected, and the read-back is what closes the write either * way. `auto` (the default) picks `dispatch` in a cloud seat container and * `direct` elsewhere, and prints which. The whole-set `PATCH` fallback below - * belongs to `direct` alone: the relay only has additive verbs. + * belongs to `direct` alone: the relay only has additive verbs. ⛔ Once a + * dispatch is ACCEPTED, its run is the only answer: no run in the start + * window, or none completed, is exit 6 under `auto` exactly as under + * `dispatch` — never a direct write after it. The relay may merely be queued, + * and the direct write would book the stroke against the seat's personal + * account instead of the fleet's and may land it twice + * (`fleet-write/dispatch.mjs`'s no-run conformance pins every sender to this). * * ## Exit codes — capture them BEFORE any pipe * @@ -120,7 +126,7 @@ import { readFileSync } from 'node:fs'; import { fileURLToPath } from 'node:url'; import { isEntrypoint } from '../invoked-as.mjs'; -import { EXIT_UNCONFIRMED, exitForResult, fallbackText, packRequest, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; +import { EXIT_UNCONFIRMED, exitForResult, packRequest, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; import { refusalText as relayRefusalText } from './fleet-write/validate.mjs'; import { isProxyRefusal, isWriteMethod, noteResponse, paceWrite, releaseWriteLease } from './write-pace.mjs'; import { @@ -638,9 +644,9 @@ export async function runLabelWrite(options, deps = {}) { httpCalls.push({ op: 'relay', call: `dispatch ${packed.payload.request_id}`, status: sent.status, verdict: sent.state, detail: sent.run?.url ?? sent.detail ?? '' }); if (sent.ok) { relay = sent; - } else if (route.requested === 'auto' && sent.state === 'no-run') { - record(`[${stamp()}] ③ ${fallbackText(sent, 'label-write')}`); } else if (sent.state === 'no-run' || sent.state === 'timeout') { + // ⛔ Under EVERY transport request, `auto` included: the dispatch was accepted and may still run, so a direct + // write here would be the same stroke booked against the seat's personal account — and possibly a second one. record(unconfirmedText(sent, 'label-write')); return result(EXIT_UNCONFIRMED, { stoppedAt: 3, labels, assignees, transport: route.transport, relay: sent }); } else { @@ -921,6 +927,18 @@ async function driveOffline(argv, boardInit = {}, extra = {}) { return { parsed, exit: res.exit, res, fake, out, sent, text: out.join('\n') }; } +/** + * The no-run conformance probe — `fleet-write/dispatch.mjs`'s header names the + * contract and its self-test drives it: ONE stroke (an add) through this tool's + * real write path against the offline fake board, on the route and the sender + * the conformance hands in. Answers the exit, every request that left this + * process directly (`METHOD /path`), and what the tool printed. + */ +export async function relayMissProbe({ route, send }) { + const run = await driveOffline(['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--add', 'x'], { labels: [] }, { route, send }); + return { exit: run.exit, calls: run.fake.calls.map((c) => `${c.method} ${c.path}`), text: run.text }; +} + // The battery ledger this self-test's floor is evaluated against. A battery // that stops registering cases is the bug; a pinned TOTAL would hide it the // moment a sibling battery grows (#13489, the shape post-stamped.mjs carries). @@ -934,7 +952,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the fallback: one PATCH, and the assignee echo that makes it survivable': 7, 'the remaining exits: refusal, mismatch, the ONE-OF block and the dry run': 5, 'the CLI: what a typo must never be allowed to mean': 8, - 'the relay transport: ONE dispatch carrying the whole stroke, the same read-back, auto falls back only on no-run': 12, + 'the relay transport: ONE dispatch carrying the whole stroke, the same read-back, and an accepted dispatch with no run UNCONFIRMED under auto too — never a direct write': 14, }); const SELF_TEST_BATTERY_FLOOR = 10; const UNATTRIBUTED_BATTERY = '(unattributed)'; @@ -1132,7 +1150,7 @@ export async function selfTest() { t('--repo defaults to this board, never to a sibling', parseOptions(['--issue', '7', '--add', 'x']).options.repo, resolveSweepRepo(process.env).repo); // ── the relay transport ────────────────────────────────────────────────── - battery('the relay transport: ONE dispatch carrying the whole stroke, the same read-back, auto falls back only on no-run'); + battery('the relay transport: ONE dispatch carrying the whole stroke, the same read-back, and an accepted dispatch with no run UNCONFIRMED under auto too — never a direct write'); { const SESSION = 'session_01ABCDEFGHJKMNPQRSTVWXYZ'; const dispatchRoute = (requested = 'dispatch') => ({ requested, transport: 'dispatch', reason: 'self-test: dispatch', error: null, session: SESSION }); @@ -1153,7 +1171,8 @@ export async function selfTest() { const noRunExplicit = await driveOffline(['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--add', 'x'], { labels: [] }, { route: dispatchRoute('dispatch'), relay: 'no-run' }); t('under an EXPLICIT dispatch, no run is exit 6 — no fall-back', [noRunExplicit.exit, noRunExplicit.fake.calls.map((c) => c.op)], [EXIT_UNCONFIRMED, ['card-read']]); const noRunAuto = await driveOffline(['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--add', 'x'], { labels: [] }, { route: dispatchRoute('auto'), relay: 'no-run' }); - t('under AUTO, no run falls back to direct — said out loud — and the write lands and reads back', [noRunAuto.exit, noRunAuto.text.includes('Falling back to DIRECT'), noRunAuto.fake.calls.map((c) => c.op)], [EXIT_OK, true, ['card-read', 'label-add', 'card-read']]); + t('⛔ under AUTO, an accepted dispatch with no run is exit 6 UNCONFIRMED too — ONE dispatch, and ZERO direct calls after it: the pre-read alone, no POST, no DELETE, no read-back', [noRunAuto.exit, noRunAuto.sent.length, noRunAuto.fake.calls.map((c) => `${c.method} ${c.path}`)], [EXIT_UNCONFIRMED, 1, ['GET /repos/objectstack-ai/objectstack/issues/7']]); + t('…the answer an EXPLICIT dispatch gives, in the shared UNCONFIRMED sentence (go READ, never re-run blind)', [noRunAuto.exit === noRunExplicit.exit, noRunAuto.res.relay ? noRunAuto.text.includes(unconfirmedText(noRunAuto.res.relay, 'label-write')) : false], [true, true]); const failedRun = await driveOffline(['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--add', 'x'], { labels: [] }, { route: dispatchRoute('auto'), relay: 'failure' }); t('⛔ a run that FAILED is never fallen back from, even under auto: exit 5, no direct write', [failedRun.exit, failedRun.fake.calls.map((c) => c.op)], [EXIT_PLATFORM_REFUSAL, ['card-read']]); const refusedDispatch = await driveOffline(['--repo', 'objectstack-ai/objectstack', '--issue', '7', '--add', 'x'], { labels: [] }, { route: dispatchRoute('auto'), relay: 'refused' }); diff --git a/scripts/pm/post-stamped.mjs b/scripts/pm/post-stamped.mjs index 1a889f26fd0..f51c37c8f5c 100644 --- a/scripts/pm/post-stamped.mjs +++ b/scripts/pm/post-stamped.mjs @@ -876,7 +876,7 @@ import { CONTRACT_REVIEW_TIER, CONTRACT_REVIEW_TIER_NAME, TIER_DEFAULT, TIER_FLO // The record's `Local-runs:` line is read by the file that owns the record's // every other line — judged when present, an absent line not re-judged. import { localRunsStand, readLocalRuns } from './record-recognisers.mjs'; -import { EXIT_UNCONFIRMED, fallbackText, packRequest, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; +import { EXIT_UNCONFIRMED, packRequest, resolveRoute, sendFleetWrite, unconfirmedText } from './fleet-write/dispatch.mjs'; import { MAX_BODY_BYTES, TRANSPORT_ENV } from './fleet-write/ops.mjs'; import { refusalText as relayRefusalText } from './fleet-write/validate.mjs'; import { isWriteMethod, noteResponse, paceWrite } from './write-pace.mjs'; @@ -2932,17 +2932,19 @@ export function sizeRoute(route, body) { // Live layer // --------------------------------------------------------------------------- -async function rest(path, { method = 'GET', body = null } = {}) { +// `deps` (`fetch`, `token`, `pace`) is `relayMissProbe`'s door and nothing else's; the live path passes none. +async function rest(path, { method = 'GET', body = null } = {}, deps = {}) { + const token = deps.token ?? TOKEN; // ⏱ The throttle (#19572), on the write verbs only — the comment `POST` and // the body `PATCH`. A spent budget or a live stop marker refuses here, before // the request is made and therefore before anything can be half-written. const paced = isWriteMethod(method); - if (paced) await paceWrite({ token: TOKEN, kind: `post-stamped ${method}` }); - const res = await fetch(`${API}${path}`, { + if (paced) await paceWrite({ token, kind: `post-stamped ${method}` }, deps.pace); + const res = await (deps.fetch ?? fetch)(`${API}${path}`, { method, headers: { accept: 'application/vnd.github+json', - ...(TOKEN ? { authorization: `Bearer ${TOKEN}` } : {}), + ...(token ? { authorization: `Bearer ${token}` } : {}), ...(body ? { 'content-type': 'application/json' } : {}), }, ...(body ? { body: JSON.stringify(body) } : {}), @@ -2955,7 +2957,7 @@ async function rest(path, { method = 'GET', body = null } = {}) { const said = platformRefusalText(await res.text().catch(() => '')); // ⏱ …and the sentence is what names a SECONDARY rate limit, so the marker // is written from the failing answer BEFORE this throws past every caller. - if (paced) noteResponse({ token: TOKEN, status: res.status, headers: res.headers, body: said }); + if (paced) noteResponse({ token, status: res.status, headers: res.headers, body: said }, deps.pace); const err = new Error(`${method} ${path} -> HTTP ${res.status}`); err.status = res.status; err.refusalText = said; @@ -2963,7 +2965,7 @@ async function rest(path, { method = 'GET', body = null } = {}) { } // ⏱ A 2xx carries a signal too: `x-ratelimit-remaining: 0` on the answer that // spent the last unit is the one reading that precedes the first refusal. - if (paced) noteResponse({ token: TOKEN, status: res.status, headers: res.headers }); + if (paced) noteResponse({ token, status: res.status, headers: res.headers }, deps.pace); if (res.status === 204) return null; return res.json(); } @@ -2974,26 +2976,26 @@ async function rest(path, { method = 'GET', body = null } = {}) { * superset of what `unreadComments` judges, so the pages fetched are the tail * and nothing the pure filter needs is left behind. */ -async function readCardTail(repo, number, sinceMs) { - const card = await rest(`/repos/${repo}/issues/${number}`); +async function readCardTail(repo, number, sinceMs, deps = {}) { + const card = await rest(`/repos/${repo}/issues/${number}`, {}, deps); const since = Number.isFinite(sinceMs) ? `&since=${encodeURIComponent(new Date(sinceMs).toISOString())}` : ''; const comments = []; for (let page = 1; ; page++) { - const rows = await rest(`/repos/${repo}/issues/${number}/comments?per_page=100&page=${page}${since}`); + const rows = await rest(`/repos/${repo}/issues/${number}/comments?per_page=100&page=${page}${since}`, {}, deps); comments.push(...(Array.isArray(rows) ? rows : [])); if (!Array.isArray(rows) || rows.length < 100) break; } return { card, comments }; } -async function writeArtefact(repo, options, body) { +async function writeArtefact(repo, options, body, deps = {}) { if (options.mode === 'comment') { - const created = await rest(`/repos/${repo}/issues/${options.number}/comments`, { method: 'POST', body: { body } }); - const back = await rest(`/repos/${repo}/issues/comments/${created?.id}`); + const created = await rest(`/repos/${repo}/issues/${options.number}/comments`, { method: 'POST', body: { body } }, deps); + const back = await rest(`/repos/${repo}/issues/comments/${created?.id}`, {}, deps); return { id: created?.id ?? null, url: back?.html_url ?? created?.html_url ?? null, writtenAt: back?.created_at ?? created?.created_at ?? null, stored: back?.body }; } - const patched = await rest(`/repos/${repo}/issues/${options.number}`, { method: 'PATCH', body: { body } }); - const back = await rest(`/repos/${repo}/issues/${options.number}`); + const patched = await rest(`/repos/${repo}/issues/${options.number}`, { method: 'PATCH', body: { body } }, deps); + const back = await rest(`/repos/${repo}/issues/${options.number}`, {}, deps); return { id: options.number, url: back?.html_url ?? patched?.html_url ?? null, writtenAt: back?.updated_at ?? patched?.updated_at ?? null, stored: back?.body }; } @@ -3004,26 +3006,96 @@ async function writeArtefact(repo, options, body) { * `{ sent }` when the relay did not succeed; `{ sent, unfound }` when the run * succeeded and the board does not show the write. */ -async function writeViaRelay(repo, options, body, route) { +async function writeViaRelay(repo, options, body, route, deps = {}) { const packed = packRequest({ repo, session: route.session, actions: [relayAction(options, body)] }); if (!packed.ok) return { refused: packed.errors }; const dispatchedAt = Date.now(); - const sent = await sendFleetWrite(packed.payload, { token: TOKEN }); + const sent = await (deps.send ?? sendFleetWrite)(packed.payload, { token: deps.token ?? TOKEN }); if (!sent.ok) return { sent }; try { if (options.mode === 'comment') { - const tail = await readCardTail(repo, options.number, dispatchedAt - 60_000); + const tail = await readCardTail(repo, options.number, dispatchedAt - 60_000, deps); const hit = pickRelayComment(tail.comments, body, dispatchedAt); if (!hit) return { sent, unfound: true }; return { id: hit.id, url: hit.html_url ?? null, writtenAt: hit.created_at ?? null, stored: hit.body, sent }; } - const back = await rest(`/repos/${repo}/issues/${options.number}`); + const back = await rest(`/repos/${repo}/issues/${options.number}`, {}, deps); return { id: options.number, url: back?.html_url ?? null, writtenAt: back?.updated_at ?? null, stored: back?.body, sent }; } catch (err) { return { sent, unfound: true, error: err?.message ?? 'the read-back threw' }; } } +/** + * The write itself, through the transport `main` resolved: the relay's ONE + * dispatch, or the direct verb — never both. Returns `{ written, relayed }` + * (`relayed` null on the direct transport), or `{ exit }` once the reason it + * stopped is printed; a REST failure throws to `main`'s classifier as before. + * + * ⛔ A dispatch the platform ACCEPTED is answered by its run alone. No run in + * the start window, or none completed, is UNCONFIRMED (6) under EVERY + * transport request, `auto` included — never the direct verb after it: the + * relay may merely be queued, and a direct write would book this act against + * the seat's personal account instead of the fleet's, and may land it twice. + * `fleet-write/dispatch.mjs`'s no-run conformance pins every sender to this, + * this one through `relayMissProbe` below. + * + * `deps` (`fetch`, `token`, `pace`, `send`, `log`) is that probe's door and + * nothing else's; `main` passes none. + */ +export async function writeThroughRoute(repo, options, body, route, deps = {}) { + const log = deps.log ?? ((line) => console.error(line)); + if (route.transport !== 'dispatch') return { written: await writeArtefact(repo, options, body, deps), relayed: null }; + const relayed = await writeViaRelay(repo, options, body, route, deps); + if (relayed.refused) { + log(relayRefusalText(relayed.refused)); + return { exit: EXIT_REFUSED }; + } + if (relayed.sent && !relayed.sent.ok) { + if (relayed.sent.state === 'no-run' || relayed.sent.state === 'timeout') { + log(unconfirmedText(relayed.sent, 'post-stamped')); + return { exit: EXIT_UNCONFIRMED }; + } + log( + `post-stamped: relay ${relayed.sent.state === 'refused' ? `REFUSED the dispatch (HTTP ${relayed.sent.status})` : 'run FAILED'} — ${relayed.sent.detail}` + + `${relayed.sent.run?.url ? ` ${relayed.sent.run.url}` : ''}. ⛔ Not retried and not fallen back: go READ the run and the card.`, + ); + return { exit: relayExitFor(relayed.sent) }; + } + if (relayed.unfound) { + log( + `post-stamped: UNCONFIRMED — the relay run ${relayed.sent.run?.url ?? relayed.sent.run?.id ?? ''} completed, but ` + + `${relayed.error ? `the read-back threw (${relayed.error})` : `no comment created since the dispatch on ${repo}#${options.number} stores the body this act sent`}. ` + + `Go READ the card; ⛔ do not re-run blind — a second dispatch is a second write. Exit ${EXIT_UNCONFIRMED}.`, + ); + return { exit: EXIT_UNCONFIRMED }; + } + return { written: relayed, relayed }; +} + +/** + * The no-run conformance probe — `fleet-write/dispatch.mjs`'s header names the + * contract and its self-test drives it: ONE comment through + * `writeThroughRoute`, the real write step, against an offline fake platform, + * on the route, the sender and the throttle the conformance hands in. Answers + * the exit (0 once a write landed), every request that left this process + * directly (`METHOD /path`), and what the tool printed. + */ +export async function relayMissProbe({ route, send, pace }) { + const repo = 'objectstack-ai/objectstack'; + const body = 'A relay-miss probe comment, never sent anywhere real.\n'; + const calls = []; + const out = []; + const fetch = async (url, init = {}) => { + const u = new URL(url); + calls.push(`${init.method ?? 'GET'} ${u.pathname}`); + const json = { id: 501, number: 7, body, html_url: `https://github.test/${repo}/issues/7#issuecomment-501`, created_at: '2026-10-05T00:00:00Z', updated_at: '2026-10-05T00:00:00Z' }; + return new Response(JSON.stringify(json), { status: init.method === 'POST' ? 201 : 200, headers: { 'content-type': 'application/json', 'x-ratelimit-remaining': '4999' } }); + }; + const step = await writeThroughRoute(repo, { mode: 'comment', number: 7 }, body, route, { fetch, token: 'probe-token', pace, send, log: (line) => out.push(line) }); + return { exit: step.exit ?? EXIT_OK, calls, text: out.join('\n') }; +} + /** * What a caller is told when there was no act at all — built as a string rather * than printed, so the ONE thing this text must never say can be pinned: the @@ -3225,36 +3297,9 @@ async function main(argv) { let written; let relayed = null; try { - if (route.transport === 'dispatch') { - relayed = await writeViaRelay(repoRes.repo, options, rendered.body, route); - if (relayed.refused) { - console.error(relayRefusalText(relayed.refused)); - return EXIT_REFUSED; - } - if (relayed.sent && !relayed.sent.ok) { - if (route.requested === 'auto' && relayed.sent.state === 'no-run') { - console.error(`post-stamped: ${fallbackText(relayed.sent, 'post-stamped')}`); - relayed = null; - } else if (relayed.sent.state === 'no-run' || relayed.sent.state === 'timeout') { - console.error(unconfirmedText(relayed.sent, 'post-stamped')); - return EXIT_UNCONFIRMED; - } else { - console.error( - `post-stamped: relay ${relayed.sent.state === 'refused' ? `REFUSED the dispatch (HTTP ${relayed.sent.status})` : 'run FAILED'} — ${relayed.sent.detail}` + - `${relayed.sent.run?.url ? ` ${relayed.sent.run.url}` : ''}. ⛔ Not retried and not fallen back: go READ the run and the card.`, - ); - return relayExitFor(relayed.sent); - } - } else if (relayed.unfound) { - console.error( - `post-stamped: UNCONFIRMED — the relay run ${relayed.sent.run?.url ?? relayed.sent.run?.id ?? ''} completed, but ` + - `${relayed.error ? `the read-back threw (${relayed.error})` : `no comment created since the dispatch on ${repoRes.repo}#${options.number} stores the body this act sent`}. ` + - `Go READ the card; ⛔ do not re-run blind — a second dispatch is a second write. Exit ${EXIT_UNCONFIRMED}.`, - ); - return EXIT_UNCONFIRMED; - } - } - written = relayed ?? (await writeArtefact(repoRes.repo, options, rendered.body)); + const step = await writeThroughRoute(repoRes.repo, options, rendered.body, route); + if (step.exit !== undefined) return step.exit; + ({ written, relayed } = step); } catch (err) { // ⛔ Only the WRITE path is classified. A read sends no body, so a size // refusal cannot be what it was answered with, and the pre-read above keeps @@ -3376,7 +3421,7 @@ const SELF_TEST_BATTERIES = Object.freeze({ 'the shared rule: this tool and H56 cannot come to disagree': 6, 'the keyed lines: a claim\'s exact-value fields, judged by the readers that own them': 30, 'the record line: a `## Contract review` record\'s `Local-runs:` value, judged when present — an absent line is not re-judged': 9, - 'the relay transport: the same act as one op, the comment found on the board, the exit register kept apart': 12, + 'the relay transport: the same act as one op, the comment found on the board, the exit register kept apart': 13, "the size route: over the relay's body cap under auto THIS write goes direct with one line naming bytes, cap and identity; at or under it the relay; explicit dispatch refuses naming the bytes; nothing else re-routes": 13, }); const SELF_TEST_BATTERY_FLOOR = 17; @@ -4500,7 +4545,24 @@ export function selfTest() { t('no run, or no completion, is exit 6 UNCONFIRMED', relayExitFor({ state: 'no-run' }) === EXIT_UNCONFIRMED && relayExitFor({ state: 'timeout' }) === EXIT_UNCONFIRMED); const ownSource = readFileSync(SELF_PATH, 'utf8'); const mainSource = ownSource.slice(ownSource.indexOf('async function main(argv)'), ownSource.indexOf('// --self-test — offline')); - t('structural: in main a dry run returns before the relay can be reached, and ONE read-back verdict serves both transports', mainSource.indexOf('if (options.dryRun) {') < mainSource.indexOf('await writeViaRelay(') && (mainSource.match(/readBackVerdict\(\{/g) ?? []).length === 1); + t('structural: in main a dry run returns before the relay can be reached, and ONE read-back verdict serves both transports', mainSource.indexOf('if (options.dryRun) {') < mainSource.indexOf('await writeThroughRoute(') && (mainSource.match(/readBackVerdict\(\{/g) ?? []).length === 1); + // The behaviour is driven by fleet-write/dispatch.mjs's no-run conformance (through `relayMissProbe`); this is the + // half this file's own gate can hold synchronously: ONE write step, and its only direct write sits on the + // non-dispatch branch, ahead of the relay — so no outcome of an accepted dispatch can reach it. + const stepSource = ownSource.slice(ownSource.indexOf('export async function writeThroughRoute('), ownSource.indexOf('export async function relayMissProbe(')); + const directAt = stepSource.indexOf('writeArtefact('); + const stepFacts = [ + ['writeArtefact(', 'writeViaRelay(', 'sendFleetWrite('].filter((call) => mainSource.includes(call)), + (stepSource.match(/writeArtefact\(/g) ?? []).length, + directAt > 0 && stepSource.slice(stepSource.lastIndexOf('\n', directAt), directAt).includes("route.transport !== 'dispatch'"), + directAt > 0 && directAt < stepSource.indexOf('writeViaRelay('), + /state === 'no-run' \|\| relayed\.sent\.state === 'timeout'\) \{\s*log\(unconfirmedText\(relayed\.sent, 'post-stamped'\)\);\s*return \{ exit: EXIT_UNCONFIRMED \};/.test(stepSource), + ]; + t( + 'structural: main writes only through writeThroughRoute, whose ONE direct write is on the non-dispatch branch before the relay is reached — an accepted dispatch with no run, or none completed, returns UNCONFIRMED and never reaches it', + JSON.stringify(stepFacts) === JSON.stringify([[], 1, true, true, true]), + `got ${JSON.stringify(stepFacts)}, want [[],1,true,true,true] (main's own direct calls · direct writes in the step · on the non-dispatch line · ahead of the relay · no-run/timeout answer UNCONFIRMED)`, + ); } // ── the size route ───────────────────────────────────────────────────────