diff --git a/.claude/skills/pm-dispatch/references/seat-post-protocol.md b/.claude/skills/pm-dispatch/references/seat-post-protocol.md index d8560b0622a..1ff1da0164b 100644 --- a/.claude/skills/pm-dispatch/references/seat-post-protocol.md +++ b/.claude/skills/pm-dispatch/references/seat-post-protocol.md @@ -25,7 +25,7 @@ - 会话座位查最近一条产出评论的时间戳;回收 = 改正文 + 审计评论。 - 常设半边是分诊轮的座位贴活性巡查,同一判据,细则见 `dispatch-runbook.md`。 - 可跑读法:本车道 `pm:dispatched` 卡按 `updated_at` 降序一搜,或读最近一条认领评论。 -- 写侧刷新点的三个时刻:派发时、收班时、暂停或交接前。 +- 写侧刷新三时刻:派发、收班、暂停或交接前;时间戳恒取自 `scripts/pm/post-stamped.mjs`。 - 协议升级迁移状态、或巡检发现正文不符时,当场改正文 + 审计评论。 - Routine 座位的收尾简报也落自己的座位贴,它是下一轮自退守卫的读数。 - 安置默认离任留守;留不了才热移交:在飞卡落收单注记 + 点名看护者。 diff --git a/.github/workflows/lint.yml b/.github/workflows/lint.yml index 12ac16bd0f9..52c54a7fc96 100644 --- a/.github/workflows/lint.yml +++ b/.github/workflows/lint.yml @@ -1103,6 +1103,26 @@ jobs: - name: Widening-tell gate self-test run: pnpm check:pm-widening-tells + # Stamped-post helper self-test (#17314) — the WRITE half of the rule that + # a timestamp a seat writes into GitHub comes from a clock read by the act + # that writes it. This tool POSTS: its live path mutates a card, so it is + # not a thing CI runs against the board, and the only half CI can hold is + # the offline one. Same split as every step around it, for one step's own + # reason as well — a production run here would write an artefact onto a + # card because a pull request happened to run CI. + # + # What the self-test instruments is the REFUSAL SET, which a clean tree + # cannot exercise: the positional refusal (a bare stamp where the writing + # act's own stamp goes), the mixed one, the unknown-token one, and the + # pass-through that keeps a quoted reading legal. Weakening any of them + # leaves every ordinary invocation just as green — the tool would simply + # post the estimate — which is the shape `check:self-test-wired` requires + # this step for. It shares `H56_STAMP_TOLERANCE_MIN` and the position + # reader with `check-half-states.mjs`, so the write side and the read-side + # patrol cannot come to disagree about what a stamp is. + - name: Stamped-post helper self-test + run: pnpm check:pm-post-stamped + # Changeset-deadline census self-test (#16850) — same family and the same # split as every step around it. The LIVE census reads the shared board # over the API and is REPORT-ONLY by ruling: #16850 takes option 1 (detect diff --git a/package.json b/package.json index 8a876e1192a..73acab32109 100644 --- a/package.json +++ b/package.json @@ -79,6 +79,7 @@ "check:pm-clause2-carriers": "node scripts/pm/check-clause2-carriers.mjs --self-test", "check:pm-widening-tells": "node scripts/pm/check-widening-tells.mjs --self-test", "check:pm-closed-card-sweep": "node scripts/pm/sweep-closed-cards.mjs --self-test", + "check:pm-post-stamped": "node scripts/pm/post-stamped.mjs --self-test", "check:pm-changeset-deadline-census": "node scripts/pm/changeset-deadline-census.mjs --self-test", "check:pm-governed-merges": "node scripts/pm/check-governed-merges.mjs --self-test", "check:pm-governed-prose": "node scripts/pm/check-governed-prose.mjs --self-test && node scripts/pm/check-governed-prose.mjs", diff --git a/scripts/pm/check-half-states.mjs b/scripts/pm/check-half-states.mjs index 0ec90893d36..2e42b28ad4c 100644 --- a/scripts/pm/check-half-states.mjs +++ b/scripts/pm/check-half-states.mjs @@ -10857,6 +10857,233 @@ export function h55LegacyCensus(issues, since = MAINTAINER_ACTION_LINE_SINCE) { return { count, undated, oldest }; } +// --------------------------------------------------------------------------- +// H56 — a stamp a seat WROTE that the platform's own clock contradicts (#17314). +// +// ## The defect this row reads +// +// H44 above reads a seat artefact stating a board reading with NO time on it. +// This row is its twin one field over: the artefact HAS a stamp, the stamp is +// well formed, and it is wrong — because it came from the seat's sense of +// elapsed time rather than from a clock read by the act that wrote the text. +// The two failures are one class and the second is the more dangerous half: an +// untimestamped reading announces itself as malformed and a reader is told to +// treat it as untaken, while an estimated one reads as a measurement and is +// believed. +// +// It is filed as MECHANICAL rather than as discipline because the discipline +// remedy is already spent. The triage seat post records the same failure twice +// — R+164 (「轮次计时全靠感觉,错了约 4 倍」) and then R+165, ~70 minutes off +// with roughly fifteen audit comments carrying the estimate — with a +// "measure it next time" note written BETWEEN them that did not hold. +// +// ## What the row compares, and the two positions it trusts +// +// A comment carries two clocks: the one the seat typed into the text, and the +// `created_at` the platform stamped when it stored that text. Where the first +// disagrees with the second by more than `H56_STAMP_TOLERANCE_MIN`, the typed +// one was not read by the act that wrote it. +// +// Which typed stamps are the ACT'S OWN is a question about meaning, and this +// row refuses to answer it. It reads two POSITIONS instead, both of which the +// protocol assigns to the writing act itself: +// +// - the OPENING line — where a claim, a dispatch, a verdict and a round +// report each put their `YYYY-MM-DDThh:mmZ`; and +// - a SUBSCRIPT reading-time line — the seat post's small-print stamp. +// +// A line carrying MORE THAN ONE stamp is held out and counted, never judged: a +// line that quotes another reading beside its own is exactly the meaning +// question above, and answering it by guessing would file a row against a +// correctly-stamped artefact. That is the bounded, stated over-read's opposite +// direction, and it is the safe one — this row's silence is a lower bound. +// +// ## Granularity and the EDIT window — the two false-positive sources, closed +// +// The protocol stamp is minute-grained, so `2026-09-10T06:37Z` names the whole +// minute `06:37:00`–`06:38:00` and a `created_at` of `06:37:48` is INSIDE it, +// not 48 seconds outside. `stampSpan` widens the stamp to its own grain before +// any comparison, so a perfectly stamped comment reads as zero drift rather +// than as one rounded minute. +// +// An EDITED comment keeps its original `created_at` while its text — stamp +// included — may legitimately have been rewritten at `updated_at`. So the +// comparison is against the WINDOW `created_at`..`updated_at`, and a stamp +// anywhere inside it is on time. Where a comment was edited long after it was +// posted that window is wide and this row goes quiet: a stated under-read, +// declared in the census clause, and the honest direction for a report-only +// patrol whose input is somebody else's artefact. +// +// ## Corpus and quota — it buys NOTHING +// +// The corpus is exactly the threads `commentCache` holds when H44 has finished +// reading it, so this row makes no request of its own and adds nothing to the +// cache. Its placement in `sweepInto` is load-bearing for that: it sits +// immediately after H44's loop and BEFORE H46, whose leg (b) widens the cache +// — reading after H46 would give this row a corpus H44 never saw, and the two +// counts in the summary would stop describing the same population. +// +// ## ⛔ Report-only, and no gate +// +// Like every row in this file it writes no label, relabels nothing and is not +// a verdict. The remedy it names has two halves: an EDIT of the offending +// comment, and — for the NEXT artefact — the token route, where +// `scripts/pm/post-stamped.mjs` substitutes a clock read in the same +// invocation that posts the text, so an estimated stamp has no spelling at +// all. This row is what sees the artefacts that did not come through it. +// --------------------------------------------------------------------------- + +/** + * The protocol's stamp shape — `YYYY-MM-DDThh:mmZ`, seconds optional. + * + * ⛔ NOT global. A `g`-flagged regex carries `lastIndex` across calls, and this + * one is exported and read by a second module (`scripts/pm/post-stamped.mjs`), + * where a shared cursor would make one caller's scan depend on another's. Use + * `protocolStamps` for the sweep. + */ +export const PROTOCOL_STAMP_RE = /\b\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2})?Z\b/; + +/** Every protocol stamp in this text, in order. */ +export function protocolStamps(text) { + const re = new RegExp(PROTOCOL_STAMP_RE.source, 'g'); + const out = []; + let m; + while ((m = re.exec(String(text ?? '')))) out.push(m[0]); + return out; +} + +/** + * How far a typed stamp may sit from the write that stored it before it stops + * being a reading. Fifteen minutes: long enough for a seat to compose a long + * artefact around a stamp it really did read, short enough that the recorded + * ~70-minute failure is loud. Exported because the WRITE side reads it too — + * one number for the tool that substitutes the stamp and the patrol that + * audits it, never two. + */ +export const H56_STAMP_TOLERANCE_MIN = 15; + +/** The subscript opener a seat post's small-print reading-time line carries. */ +export const H56_READING_LINE_OPENER = //; + +/** + * The instant-SPAN a stamp names, in ms: minute-grained unless it spells + * seconds. `null` when the text is not a stamp this scan can parse. + */ +export function stampSpan(stamp) { + const at = Date.parse(String(stamp ?? '')); + if (!Number.isFinite(at)) return null; + const grain = /\d{2}:\d{2}:\d{2}Z$/.test(String(stamp)) ? 1000 : 60000; + return { from: at, to: at + grain }; +} + +/** + * Minutes between the stamp's span and the write window `createdAt`..`updatedAt` + * — `0` when they overlap, `null` when either side is unreadable, and never a + * rounded `0` for a gap that exists. + */ +export function stampDriftMinutes(stamp, createdAt, updatedAt = createdAt) { + const span = stampSpan(stamp); + const from = Date.parse(String(createdAt ?? '')); + if (!span || !Number.isFinite(from)) return null; + const edited = Date.parse(String(updatedAt ?? '')); + const hi = Number.isFinite(edited) && edited > from ? edited : from; + if (span.from <= hi && span.to > from) return 0; + const gap = span.from > hi ? span.from - hi : from - span.to; + return Math.max(1, Math.round(gap / 60000)); +} + +/** + * The stamps this row is willing to read as the writing act's OWN, by position: + * the opening line, and any subscript reading-time line. A line carrying more + * than one stamp contributes nothing — see `h56AmbiguousLines`. + */ +export function h56StampedReadings(text) { + const lines = String(text ?? '').split('\n'); + const opening = lines.findIndex((line) => line.trim().length > 0); + const out = []; + for (let i = 0; i < lines.length; i++) { + const isOpening = i === opening; + const isReading = H56_READING_LINE_OPENER.test(lines[i]); + if (!isOpening && !isReading) continue; + const stamps = protocolStamps(lines[i]); + if (stamps.length !== 1) continue; + out.push({ stamp: stamps[0], where: isOpening ? 'the opening line' : 'a subscript reading-time line' }); + } + return out; +} + +/** How many of those positions were HELD OUT for carrying more than one stamp. */ +export function h56AmbiguousLines(text) { + const lines = String(text ?? '').split('\n'); + const opening = lines.findIndex((line) => line.trim().length > 0); + let held = 0; + for (let i = 0; i < lines.length; i++) { + if (i !== opening && !H56_READING_LINE_OPENER.test(lines[i])) continue; + if (protocolStamps(lines[i]).length > 1) held += 1; + } + return held; +} + +/** + * H56 — `null` when the comment is clean, unstamped or unjudgeable, else the + * WORST reading on it: `{ stamp, where, drift }`. + * + * An unreadable `created_at` returns `null` and is COUNTED as unjudged by the + * caller rather than presenting as clean (#4690): a comment with no platform + * clock has nothing to contradict its text. + */ +export function h56EstimatedStamp(comment, tolerance = H56_STAMP_TOLERANCE_MIN) { + const body = comment?.body; + if (typeof body !== 'string' || body.length === 0) return null; + if (!Number.isFinite(Date.parse(String(comment?.created_at ?? '')))) return null; + let worst = null; + for (const reading of h56StampedReadings(body)) { + const drift = stampDriftMinutes(reading.stamp, comment.created_at, comment.updated_at); + if (drift === null || drift <= tolerance) continue; + if (!worst || drift > worst.drift) worst = { ...reading, drift }; + } + return worst; +} + +/** + * The row. Report-only, and it names the comment so the remedy is an EDIT of a + * known artefact rather than a hunt. + * + * @param {object} hit — `h56EstimatedStamp`'s result. + * @param {object} comment — the REST comment row (id, created_at, updated_at). + * @param {number} total — how many comments on this carrier carry the defect. + */ +export function h56EstimatedStampRow(hit, comment, total = 1) { + if (!hit) return null; + const id = String(comment?.id ?? 'an unread id'); + const created = String(comment?.created_at ?? 'an unread instant'); + const edited = + comment?.updated_at && comment.updated_at !== comment.created_at + ? ` (edited, so the whole window to ${comment.updated_at} was allowed)` + : ''; + const more = + total > 1 + ? ` ${total - 1} further comment(s) on this carrier carry a stamp their own write time contradicts; this is the WIDEST.` + : ''; + return ( + `${hit.where} of comment \`${id}\` states \`${hit.stamp}\`, and the platform stored that comment at ` + + `${created}${edited} — ${hit.drift} minute(s) apart, beyond the ${H56_STAMP_TOLERANCE_MIN}-minute ` + + 'tolerance. A stamp on a seat artefact is a READING, and the protocol has readers treat it as the ' + + 'instant the board was looked at; one that disagrees with its own write by this much was not read by ' + + 'the act that wrote it — it was ESTIMATED, and every decision taken downstream on that line is dated ' + + 'to a board nobody looked at then.' + + more + + ' Remedy has two halves. This artefact: an EDIT of that comment carrying the time actually read — ' + + '⛔ never a fresh measurement written as if it were the original, which dates the artefact to a board ' + + 'it never read. The NEXT artefact: post it through `scripts/pm/post-stamped.mjs`, which substitutes a ' + + 'clock read in the same invocation that writes the text, so an estimated stamp has no spelling to ' + + 'reach for. ⚠️ Only two POSITIONS are read — the opening line and a subscript reading-time line — and ' + + 'a line carrying more than one stamp is held out rather than guessed at, so this row is a LOWER ' + + 'BOUND. Report-only patrol INPUT, not a verdict and not a gate: nothing is blocked by this row and no ' + + 'gate reads it.' + ); +} + // --------------------------------------------------------------------------- // Report rendering — pure over (findings, counts), so `--self-test` pins both // media offline. The live sweep below picks a renderer and prints it; nothing @@ -11005,6 +11232,12 @@ export const SWEEP_COUNT_KEYS = [ 'readingComments', 'readingSeatCandidates', 'readingSeatRead', + // H56's census (#17314). `stampComments` is the judged half of H44's own + // corpus — same threads, one field over — and the other two are the two ways + // a comment leaves this row unjudged rather than clean. + 'stampComments', + 'stampUnjudged', + 'stampAmbiguous', // H46's coverage pair. `claimlessCandidates` is how many BOUND, non-`pm:queue` // open cards leg (b) had to read a thread for, and `claimlessProbed` how many // of them it got — the pair that keeps a row that judged nothing separable @@ -11465,6 +11698,19 @@ export function summaryLine(counts, findingCount) { 'PULL REQUEST is NOT in this corpus: no listing here fetches a PR comment page, so this row\'s ' + 'silence about PRs is an unread surface and never a clean one, and every count above is a LOWER ' + 'BOUND. ' + + // H56's census (#17314). UNCONDITIONAL like every other window's, and it is + // the ONLY place the two silences of this row are visible: a comment with + // no readable `created_at` has nothing to contradict its text, and a line + // carrying two stamps is a meaning question this row refuses to guess at. + // Both are held out, so the rows are a LOWER BOUND and this clause says by + // how much. + `Estimated stamps (H56): ${counts.stampComments ?? 0} of the comment(s) above carried a platform ` + + `\`created_at\` to judge a typed stamp against, ${counts.stampUnjudged ?? 0} did not and are ` + + `UNJUDGED rather than clean, and ${counts.stampAmbiguous ?? 0} stamped line(s) carried more than one ` + + `stamp and were held out rather than guessed at. Tolerance ${H56_STAMP_TOLERANCE_MIN} min, measured ` + + 'against the whole `created_at`..`updated_at` window, so a stamp legitimately refreshed by a later ' + + 'EDIT never fires and a comment edited long after posting is judged against a wide window — a stated ' + + 'under-read, and the safe direction for a patrol reading somebody else\'s artefact. ' + // H46's coverage pair. UNCONDITIONAL like every other window's: a `0 of 0` // reading is a run where no open PR bound a closing keyword to a // non-`pm:queue` open card, never a row that went quiet. @@ -11609,6 +11855,7 @@ export const SUMMARY_CLAUSE_ANCHORS = [ ['h37Folds', 'Family folds (H37): '], ['h40References', 'Dangling references (H40): '], ['h44Readings', 'Untimestamped readings (H44): '], + ['h56Stamps', 'Estimated stamps (H56): '], ['h46Claimless', 'Claim-less implementations (H46): '], ['h45EpicParents', 'Epic parent reads (H45): '], ['h47Release', 'Release records (H47): '], @@ -12040,6 +12287,19 @@ export const HALF_STATE_FAMILY_BAND = Object.freeze({ // row this one is the awaiting-state twin of. H55: 'state', + // H56 is a `state` (#17314), and it is H44's band for H44's reason — the two + // are one class, a seat artefact whose reading cannot be dated (H44) and one + // whose date is wrong (H56). ⛔ Not `gate`: nothing was stripped and no + // absence reads as clearance; the artefact is present and says something + // false. ⛔ Not `stall`: no card is stopped by a wrong stamp and no scan is + // waiting on it — the cost is a decision dated to a board nobody looked at, + // not motion that never happens. ⛔ Not `inventory`: the row alarms about ONE + // comment on one carrier; the population reading — how many comments were + // judged, and the two ways one is held out — is a summary clause and takes no + // band at all (H39's shape). What is left is `state` exactly: a live artefact + // contradicting itself, the repair an edit on the board. + H56: 'state', + // H52 is a `stall` and not a `state` (#16662): the board is not contradicting // itself — every label on the card is correct — and no later sweep frees the // card, because the only thing that moves it is a maintainer who cannot see @@ -13382,6 +13642,12 @@ async function sweep(options = {}) { awaitingUndated: 0, maintainerActionCandidates: 0, maintainerActionProbed: 0, + // H56's census (#17314) — how many of the comments H44 already read carry + // a platform clock to judge a typed stamp against, and the two ways one + // does not. Initialised so a sweep that throws early renders numbers. + stampComments: 0, + stampUnjudged: 0, + stampAmbiguous: 0, // H19's coverage pair — distinct `Blocked-by:` targets seen, and how many // got a definite open/closed answer. blockerTargets: 0, @@ -15852,6 +16118,45 @@ async function sweepInto(findings, seen, seenPrs, seenMerged, seenUnscoped, seen stats.readingThreads = commentCache.size; stats.readingComments = h44Read; + // H56 (#17314) — the estimated-stamp patrol, H44's twin one field over and + // reading the SAME corpus: the threads already in `commentCache`. It buys + // nothing and puts nothing in the cache. + // + // Placed HERE — after H44's loop, BEFORE H46 — deliberately, and the reason is + // H46's own header in reverse: leg (b) below widens the cache, so judging this + // row after it would give H56 a corpus H44 never saw and the two census + // clauses would stop describing one population. + // + // One row per CARRIER, naming the WIDEST drift rather than the oldest offender + // (H44's choice): every offending comment needs its own edit, so the single + // row a reader gets should name the one whose date is furthest from the truth. + let h56Judged = 0; + let h56Unjudged = 0; + let h56Held = 0; + for (const [number, rows] of commentCache) { + const carrier = seen.get(number) ?? seenUnscoped.get(number); + if (!carrier) continue; + let worst = null; + let total = 0; + for (const row of rows ?? []) { + if (typeof row?.body !== 'string') continue; + h56Held += h56AmbiguousLines(row.body); + if (!Number.isFinite(Date.parse(String(row?.created_at ?? '')))) { + h56Unjudged += 1; + continue; + } + h56Judged += 1; + const hit = h56EstimatedStamp(row); + if (!hit) continue; + total += 1; + if (!worst || hit.drift > worst.hit.drift) worst = { hit, row }; + } + if (worst) findings.push([carrier, 'H56', h56EstimatedStampRow(worst.hit, worst.row, total)]); + } + stats.stampComments = h56Judged; + stats.stampUnjudged = h56Unjudged; + stats.stampAmbiguous = h56Held; + // H46 — the claim-less implementation. Placed HERE, AFTER H44, deliberately: // leg (b) adds threads to `commentCache`, and H44's corpus is whatever the // rows above it already fetched. Judging this row first would widen H44's @@ -23308,6 +23613,121 @@ Mutual exclusion: \`get_comments\` page 747 → \`[]\`, page 746 = my own R+117 t('H55 reconciliation: …and the ager\'s remedy reads the line before re-asking', h11row(parkedCard(['bug', AWAITING_MAINTAINER_LABEL]), NOW).includes('Maintainer-action'), true); t('H55 reconciliation: …without prescribing the re-check this state cannot have', h11row(parkedCard(['bug', AWAITING_MAINTAINER_LABEL]), NOW).includes('Restart-when'), false); + // -- H56 — a stamp whose own write time contradicts it (#17314) ------------ + // Fixtures are SYNTHETIC (⛔ the self-test never touches GitHub). The pair the + // filing card names is here first: an on-time stamp and the recorded ~70-minute + // miss, the same magnitude as the triage seat post's R+165 failure. + const C56 = '2026-09-10T06:37:48Z'; + const comment56 = (over = {}) => ({ + id: 5614267277, + body: 'Claim: skills seat, session `session_x`, 2026-09-10T06:37Z — dispatched into the round.', + created_at: C56, + updated_at: C56, + ...over, + }); + const h56 = (over = {}) => h56EstimatedStamp(comment56(over)); + const OFF56 = comment56({ body: 'Claim: skills seat, session `session_x`, 2026-09-10T05:27Z — dispatched into the round.' }); + + // ⭐ The fixture pair the card asks for, in both directions. + t('H56 pair: an ON-TIME stamp is silent', h56(), null); + t('H56 pair: …and the ~70-minute miss fires', typeof h56EstimatedStamp(OFF56), 'object'); + t('H56 pair: …with the drift measured, not guessed', h56EstimatedStamp(OFF56).drift, 70); + t('H56 pair: …and the offending stamp echoed verbatim', h56EstimatedStamp(OFF56).stamp, '2026-09-10T05:27Z'); + t('H56 pair: …named by POSITION, never by meaning', h56EstimatedStamp(OFF56).where, 'the opening line'); + + // Granularity: a minute-grained stamp names a MINUTE, so seconds inside it are + // zero drift rather than one rounded minute. This is the false positive that + // would fire on every correctly stamped comment in the corpus. + t('H56 grain: a minute stamp spans its whole minute', stampSpan('2026-09-10T06:37Z').to - stampSpan('2026-09-10T06:37Z').from, 60000); + t('H56 grain: …and a seconds stamp spans one second', stampSpan('2026-09-10T06:37:48Z').to - stampSpan('2026-09-10T06:37:48Z').from, 1000); + t('H56 grain: an unparseable stamp has no span, and never a NaN one', stampSpan('yesterday'), null); + t('H56 grain: a `created_at` 48s into the stamped minute is ON TIME', stampDriftMinutes('2026-09-10T06:37Z', C56), 0); + t('H56 grain: …and the seconds spelling of the same instant is too', stampDriftMinutes('2026-09-10T06:37:48Z', C56), 0); + + // The tolerance is a boundary, and both sides of it are pinned. + t('H56 tolerance: the shared constant is 15 minutes', H56_STAMP_TOLERANCE_MIN, 15); + t('H56 tolerance: exactly at the tolerance is clean', h56({ body: 'R9 2026-09-10T06:24Z open', created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T06:40:00Z' }), null); + t('H56 tolerance: one minute beyond it fires', h56({ body: 'R9 2026-09-10T06:23Z open', created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T06:40:00Z' })?.drift, 16); + t('H56 tolerance: a FUTURE-dated stamp fires too — the miss has two directions', h56({ body: 'R9 2026-09-10T07:40Z open', created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T06:40:00Z' })?.drift, 60); + t('H56 drift: an unreadable stamp is null, never 0', stampDriftMinutes('soon', C56), null); + t('H56 drift: an unreadable write time is null, never 0', stampDriftMinutes('2026-09-10T06:37Z', 'whenever'), null); + t('H56 drift: a gap under a minute still reads as ≥1, never as on time', stampDriftMinutes('2026-09-10T06:00Z', '2026-09-10T06:01:20Z'), 1); + + // The EDIT window — the second false-positive source, closed. + t('H56 edit: a stamp inside the created..updated window is on time', h56({ body: 'R9 2026-09-10T08:30Z open', created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T09:00:00Z' }), null); + // The gap is measured to the NEAR edge of the window on the side the stamp + // fell off, so an early stamp is judged against `created_at` (06:40) and not + // against the far `updated_at` — 99 minutes, never 240. + t('H56 edit: …and one outside it still fires', h56({ body: 'R9 2026-09-10T05:00Z open', created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T09:00:00Z' })?.drift, 99); + t('H56 edit: an unedited comment is judged against the instant alone', stampDriftMinutes('2026-09-10T05:27Z', C56, C56), 70); + + // Positions: the two the protocol assigns to the writing act, and nothing else. + t('H56 position: the opening line is read', h56StampedReadings('Dispatched — R9, 2026-09-10T06:38Z.').length, 1); + t('H56 position: …even behind leading blank lines', h56StampedReadings('\n\n R9 open 2026-09-10T06:38Z').length, 1); + t('H56 position: a subscript reading-time line is read', h56StampedReadings('Seat post\n\nread 2026-09-10T06:38Z')[0]?.where, 'a subscript reading-time line'); + t('H56 position: a stamp in ordinary prose four lines down is NOT read', h56StampedReadings('Title\n\nbody\n\nthe ruling of 2026-09-08T14:00Z stands').length, 0); + t('H56 position: an empty body reads nothing, and never crashes', h56StampedReadings('').length, 0); + t('H56 position: a missing body reads nothing either', h56StampedReadings(undefined).length, 0); + + // The meaning question this row REFUSES: a line quoting a second reading. + const AMBIG56 = 'Dispatched — R9, 2026-09-10T06:38Z, re-reading the board taken 2026-09-08T14:00Z.'; + t('H56 held out: a line with two stamps contributes NO reading', h56StampedReadings(AMBIG56).length, 0); + t('H56 held out: …and is COUNTED so the silence is visible', h56AmbiguousLines(AMBIG56), 1); + t('H56 held out: a single-stamp line is not held out', h56AmbiguousLines('R9 2026-09-10T06:38Z'), 0); + t('H56 held out: …so the row cannot fire on it', h56EstimatedStamp({ body: AMBIG56, created_at: C56, updated_at: C56 }), null); + + // #4690 — unjudged is never clean, and the caller counts it. + t('H56 unjudged: a comment with no readable `created_at` is null, for the census to count', h56EstimatedStamp({ body: OFF56.body, created_at: 'never' }), null); + t('H56 unjudged: a comment with no body is null', h56EstimatedStamp({ body: undefined, created_at: C56 }), null); + t('H56 unjudged: a missing comment does not crash', h56EstimatedStamp(undefined), null); + + // `protocolStamps` is read by a SECOND module, so the shared regex must not + // carry a cursor between calls — the classic `g`-flag defect. + t('H56 regex: the exported shape is NOT global', PROTOCOL_STAMP_RE.global, false); + t('H56 regex: …so two consecutive scans of one text agree', protocolStamps('a 2026-09-10T06:38Z b').length === protocolStamps('a 2026-09-10T06:38Z b').length, true); + t('H56 regex: seconds are optional', protocolStamps('2026-09-10T06:38:12Z').length, 1); + t('H56 regex: a bare HH:MMZ is H44\'s shape, not this one', protocolStamps('read at 06:38Z').length, 0); + + // The row sentence. + const ROW56 = h56EstimatedStampRow(h56EstimatedStamp(OFF56), OFF56, 3); + t('H56 row: null in, null out', h56EstimatedStampRow(null, OFF56), null); + t('H56 row: names the comment so the remedy is an edit, not a hunt', ROW56.includes('5614267277'), true); + t('H56 row: states both clocks', ROW56.includes('2026-09-10T05:27Z') && ROW56.includes(C56), true); + t('H56 row: …and the distance between them', ROW56.includes('70 minute(s) apart'), true); + t('H56 row: counts the rest on the carrier and says which one this is', ROW56.includes('2 further comment(s)') && ROW56.includes('WIDEST'), true); + t('H56 row: the word for what went wrong is ESTIMATED', ROW56.includes('ESTIMATED'), true); + t('H56 row: ⛔ refuses the re-measurement remedy by name', ROW56.includes('never a fresh measurement written as if it were the original'), true); + t('H56 row: points at the write-side token route for the NEXT artefact', ROW56.includes('scripts/pm/post-stamped.mjs'), true); + t('H56 row: declares itself a LOWER BOUND', ROW56.includes('LOWER BOUND'), true); + t('H56 row: report-only, and says no gate reads it', ROW56.includes('no gate reads it'), true); + // ⛔ The sentence is rendered into a GitHub issue body, which mutates + // less-than fragments — so the subscript position is named in WORDS. + t('H56 row: ⛔ carries no angle-bracket fragment at all', /[<>]/.test(ROW56), false); + t('H56 row: an edited carrier says the window was widened for it', h56EstimatedStampRow({ stamp: '2026-09-10T05:00Z', where: 'the opening line', drift: 100 }, { id: 1, created_at: '2026-09-10T06:40:00Z', updated_at: '2026-09-10T09:00:00Z' }).includes('edited, so the whole window'), true); + t('H56 row: an unread id is named as such rather than printed as undefined', h56EstimatedStampRow({ stamp: 'x', where: 'the opening line', drift: 99 }, {}).includes('an unread id'), true); + + // Census and forwarding. + t('H56 census: every count key rides the enumerated forwarding contract', ['stampComments', 'stampUnjudged', 'stampAmbiguous'].every((k) => SWEEP_COUNT_KEYS.includes(k)), true); + const SUM56 = saidBy('h56Stamps', summaryLine({ stampComments: 411, stampUnjudged: 2, stampAmbiguous: 7 }, 0)); + t('H56 census: the judged half is reported', SUM56.includes('411 of the comment(s) above'), true); + t('H56 census: …the unjudged half is UNJUDGED, never clean', SUM56.includes('2 did not and are UNJUDGED rather than clean'), true); + t('H56 census: …and the held-out lines are named', SUM56.includes('7 stamped line(s) carried more than one stamp'), true); + t('H56 census: the tolerance is stated in the clause, not left to the reader', SUM56.includes('Tolerance 15 min'), true); + t('H56 census: …and the edit-window under-read is declared', SUM56.includes('under-read'), true); + t('H56 census: the clause renders on a zero run too — silence is never absence', saidBy('h56Stamps', summaryLine({}, 0)).includes('0 of the comment(s) above'), true); + + // Band. + t('H56 band: registered as a STATE row — H44\'s band, because it is H44\'s class', familyBand('H56'), 'state'); + t('H56 band: …the same band its twin carries', familyBand('H56'), familyBand('H44')); + t('H56 band: ⛔ NOT `gate` — nothing was stripped and no absence reads as clearance', familyBand('H56') === 'gate', false); + t('H56 band: ⛔ NOT `stall` — a wrong stamp stops no card', familyBand('H56') === 'stall', false); + t('H56 band: ⛔ NOT `inventory` — the row alarms per comment; the census is a clause', familyBand('H56') === 'inventory', false); + t('H56 band: the sweep really pushes it, so the registry sees it', familyRegistryCoverage().emitted.includes('H56'), true); + t('H56 band: no code is left unregistered by this change', familyRegistryCoverage().missing.length, 0); + t('H56 band: …and no band names a family the sweep never emits', familyRegistryCoverage().extra.length, 0); + t('H56 band: the registry still fits inside the ledger ROW CAP', Object.keys(HALF_STATE_FAMILY_BAND).length <= FAMILY_LEDGER_ROW_CAP, true); + t('H56 band: a gate row still outranks it', familyRank('H31') < familyRank('H56'), true); + // -- The `[::]` collapse (#12090): behaviour-preserving, asserted as such --- // The class held U+003A TWICE, never the fullwidth U+FF1A its shape implied. // These cases pin that the collapse changed nothing a reader could observe. diff --git a/scripts/pm/post-stamped.mjs b/scripts/pm/post-stamped.mjs new file mode 100644 index 00000000000..0064873bb65 --- /dev/null +++ b/scripts/pm/post-stamped.mjs @@ -0,0 +1,719 @@ +#!/usr/bin/env node +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * post-stamped — write a seat artefact to GitHub with a stamp this act read (#17314). + * + * node scripts/pm/post-stamped.mjs --comment=17314 --file=body.md + * node scripts/pm/post-stamped.mjs --comment=17314 # body on stdin + * node scripts/pm/post-stamped.mjs --body=17314 --file=seat-post.md + * node scripts/pm/post-stamped.mjs --dry-run --comment=17314 --file=body.md + * node scripts/pm/post-stamped.mjs --self-test # offline, no network at all + * + * ## The invariant, and the spelling this removes + * + * Every timestamp a seat writes into a GitHub comment or body — the reading + * time in a subscript line, the `YYYY-MM-DDThh:mmZ` on claims, dispatches, + * verdicts, round reports and seat-post edits — must come from a clock read by + * the same act that writes the text, never from the seat's sense of elapsed + * time. The protocol has required the stamp for a while; what it could not + * remove is that an ESTIMATED stamp had a spelling. A seat typed the digits. + * + * Filed as MECHANICAL because the discipline remedy is spent: the triage seat + * post records the same failure twice — R+164 (「轮次计时全靠感觉,错了约 4 + * 倍」), then R+165, ~70 minutes off with roughly fifteen audit comments + * carrying the estimate — with a "measure it next time" note written BETWEEN + * them that did not hold. + * + * So the seat writes a TOKEN and this tool writes the time: + * + * `{{NOW}}` the clock read in THIS invocation. + * `{{WAS:2026-09-08T14:00Z}}` a stamp that is a reading of something ELSE, + * declared as such and rendered verbatim. + * + * There is no third spelling, and no flag that turns the contract off. + * + * ## What it refuses, and why the refusal is positional + * + * `check-half-states.mjs`'s H56 reads two POSITIONS as belonging to the writing + * act: the artefact's OPENING line, and a subscript reading-time line. This + * tool imports that same reader, so the write side refuses exactly what the + * read-side patrol would file: + * + * POSITIONAL a bare stamp sits in one of those two positions. That is the + * act's own stamp typed by hand, which is the whole defect. Write + * `{{NOW}}`, or `{{WAS:…}}` if it really is a quoted reading. + * MIXED the body uses `{{NOW}}` AND carries a bare stamp somewhere + * else. The author knows the token and typed a time anyway; that + * typed one is the estimate. This is the case the filing card + * names by hand. + * UNKNOWN a `{{…}}` token survives substitution. A mistyped `{{now}}` + * would otherwise post literally AND leave the artefact + * unstamped, which is the quiet direction. + * + * ⛔ The positional refusal is NOT the mixed one widened for tidiness. Mixed + * alone leaves the estimated stamp fully spellable — a seat that never types + * `{{NOW}}` is never refused — so mixed alone would not have caught the + * recorded failure, whose comments carried no token at all. + * + * A bare stamp OUTSIDE those two positions is passed through with a note on + * stderr rather than refused: prose quoting a ruling's date is a reading of + * something else, and refusing it would push seats back onto the channel this + * tool exists to replace. + * + * ## ⚖️ Why this ACTS by default, where `sweep-closed-cards.mjs` dry-runs + * + * Its sibling next door defaults to a dry run and needs `--write`, because it + * is a machine deciding BY ITSELF which of thousands of archived cards to + * write to: the blast radius is the board and the operator sees the list only + * afterwards. This tool writes ONE artefact, to a target the caller named on + * the command line, from a body the caller wrote. Demanding a second flag on + * top of `--comment=17314` is a second spelling of one decision, and a helper + * with friction gets bypassed for the channel that has none — which is the + * failure this card exists to close. `--dry-run` prints the substituted body + * and writes nothing. + * + * ## The read-back, which is what makes the transcript proof + * + * After the write the artefact is fetched again and three things are printed: + * the id and URL, the platform's own `created_at` (`updated_at` for a body + * edit, which is when that write happened), and the DRIFT between the stamp + * this run substituted and that instant — the same measurement H56 makes on + * the corpus, taken at write time, against the same imported tolerance. The + * stored bytes are compared with the bytes sent, so a body the platform's + * sanitizer mutated is reported instead of assumed. + */ + +import process from 'node:process'; +import { spawnSync } from 'node:child_process'; +import { readFileSync } from 'node:fs'; +import { fileURLToPath } from 'node:url'; +import { isEntrypoint } from '../invoked-as.mjs'; +import { + EXIT_PREREQUISITE_NOT_MET, + H56_STAMP_TOLERANCE_MIN, + PROXY_FLAG, + h56StampedReadings, + protocolStamps, + proxyRearmPlan, + resolveSweepRepo, + stampDriftMinutes, +} from './check-half-states.mjs'; + +const SELF_PATH = fileURLToPath(import.meta.url); +const API = 'https://api.github.com'; +const TOKEN = process.env.GITHUB_TOKEN ?? process.env.GH_TOKEN ?? ''; + +export const EXIT_OK = 0; +export const EXIT_USAGE = 1; +export const EXIT_REFUSED = 2; + +/** + * The re-exec guard, per script rather than shared with its neighbours: two + * scripts sharing one guard name means the first one's re-exec silently + * disarms the second's when they run in the same process tree. + */ +const PROXY_REARM_GUARD = 'OS_POST_STAMPED_PROXY_REARMED'; + +// --------------------------------------------------------------------------- +// Pure core — every function below is offline and is what `--self-test` pins. +// --------------------------------------------------------------------------- + +/** The token a seat writes where the act's own stamp goes. */ +export const STAMP_TOKEN = '{{NOW}}'; + +/** + * The declared QUOTED stamp — a reading of something else, rendered verbatim. + * + * ⛔ NOT global, for `PROTOCOL_STAMP_RE`'s reason: an exported `g`-flagged + * regex carries `lastIndex` between callers. Every use below builds its own. + */ +export const QUOTED_TOKEN_RE = /\{\{WAS:([^{}]*)\}\}/; + +/** Any `{{…}}` token, used to catch the ones substitution did not consume. */ +export const ANY_TOKEN_RE = /\{\{[^{}]*\}\}/; + +const globalOf = (re) => new RegExp(re.source, 'g'); + +/** The clock, in the protocol's own spelling. */ +export function stampNow(ms = Date.now()) { + return `${new Date(ms).toISOString().slice(0, 16)}Z`; +} + +/** + * The text with every declared quoted stamp blanked to spaces of equal length, + * so a scan for BARE stamps sees only the ones nobody declared — and so line + * numbers, columns and the opening line are all still where they were. + */ +export function maskQuotedStamps(text) { + return String(text ?? '').replace(globalOf(QUOTED_TOKEN_RE), (m) => ' '.repeat(m.length)); +} + +/** The values inside every `{{WAS:…}}` in this text. */ +export function quotedStampValues(text) { + const re = globalOf(QUOTED_TOKEN_RE); + const out = []; + let m; + while ((m = re.exec(String(text ?? '')))) out.push(m[1]); + return out; +} + +/** + * Every reason this body may not be posted, in the order a reader should fix + * them. An empty array is a body that may be written. + */ +export function stampRefusals(text) { + const raw = String(text ?? ''); + const masked = maskQuotedStamps(raw); + const refusals = []; + + for (const value of quotedStampValues(raw)) { + if (protocolStamps(value).length === 1 && protocolStamps(value)[0] === value.trim()) continue; + refusals.push({ + kind: 'quoted-not-a-stamp', + detail: + `\`{{WAS:${value}}}\` does not declare a stamp. The quoted route renders a reading of ` + + 'something else VERBATIM, so its contents must be one `YYYY-MM-DDThh:mmZ` and nothing else — ' + + 'it is a declaration, not a free-text escape from the contract.', + }); + } + + const positional = h56StampedReadings(masked); + for (const hit of positional) { + refusals.push({ + kind: 'positional', + detail: + `${hit.where} carries the bare stamp \`${hit.stamp}\`. That position belongs to the writing ` + + 'act, so a stamp typed there is the act\'s own time written from memory — the defect this tool ' + + `exists to make unspellable. Write \`${STAMP_TOKEN}\` there, or \`{{WAS:${hit.stamp}}}\` if it ` + + 'is genuinely a reading of something else.', + }); + } + + if (raw.includes(STAMP_TOKEN)) { + const seen = new Set(positional.map((hit) => hit.stamp)); + for (const stamp of protocolStamps(masked)) { + if (seen.has(stamp)) continue; + seen.add(stamp); + refusals.push({ + kind: 'mixed', + detail: + `this body uses \`${STAMP_TOKEN}\` and also carries the bare stamp \`${stamp}\`. One of the ` + + 'two clocks was read by this act and the other was typed; a reader cannot tell which. Declare ' + + `it with \`{{WAS:${stamp}}}\` if it is a quoted reading, or make it \`${STAMP_TOKEN}\` if it ` + + 'is this act\'s own.', + }); + } + } + + return refusals; +} + +/** The refusal a caller reads, from `stampRefusals`' rows. */ +export function refusalText(refusals) { + const rows = (refusals ?? []).map((r, i) => ` ${i + 1}. [${r.kind}] ${r.detail}`); + return ( + `post-stamped: REFUSED — ${rows.length} stamp-contract problem(s) in the body. Nothing was written.\n` + + `${rows.join('\n')}\n\n` + + ` The contract has exactly two spellings: \`${STAMP_TOKEN}\` for the clock this act reads, and\n` + + ' `{{WAS:YYYY-MM-DDThh:mmZ}}` for a stamp that is a reading of something else. There is no flag\n' + + ' that turns it off — a stamp typed from memory is the defect, not a formatting preference.' + ); +} + +/** + * The body as it will be written, or the refusal. Pure, so every branch that + * decides whether a write happens at all is pinned offline. + */ +export function renderBody(text, nowMs = Date.now()) { + const raw = String(text ?? ''); + if (raw.trim().length === 0) { + return { + ok: false, + kind: 'empty', + error: + 'post-stamped: REFUSED — the body is empty. An empty artefact posted to a card is noise a\n' + + ' reader has to judge; supply a body with --file=PATH or on stdin.', + }; + } + const refusals = stampRefusals(raw); + if (refusals.length > 0) return { ok: false, kind: 'stamp-contract', refusals, error: refusalText(refusals) }; + + const stamp = stampNow(nowMs); + let quoted = 0; + let body = raw.replace(globalOf(QUOTED_TOKEN_RE), (_m, inner) => { + quoted += 1; + return inner; + }); + const substituted = body.split(STAMP_TOKEN).length - 1; + body = body.split(STAMP_TOKEN).join(stamp); + + const leftover = body.match(globalOf(ANY_TOKEN_RE)); + if (leftover) { + return { + ok: false, + kind: 'unknown-token', + error: + `post-stamped: REFUSED — ${leftover.length} token(s) survived substitution: ${leftover.join(', ')}.\n` + + ` Posting them would put the literal text on the card AND leave the artefact unstamped, which is\n` + + ` the quiet direction. The tokens this tool knows are \`${STAMP_TOKEN}\` and \`{{WAS:…}}\`; a\n` + + ' mistyped one is a typo, and a typo must never decide whether a stamp was read.', + }; + } + + return { ok: true, body, stamp, substituted, quoted }; +} + +/** + * What the read-back proves, as lines a transcript carries. `writtenAt` is the + * platform's own clock for the write — `created_at` for a comment, `updated_at` + * for a body edit, which is when that write actually happened. + */ +export function readBackVerdict({ stamp, writtenAt, sent, stored, substituted = 0 }) { + const lines = []; + const drift = substituted > 0 ? stampDriftMinutes(stamp, writtenAt, writtenAt) : null; + if (substituted === 0) { + lines.push(` stamp: none substituted — this body carried no ${STAMP_TOKEN}, so there is no clock to check`); + } else if (drift === null) { + lines.push(` ⚠️ stamp: \`${stamp}\` substituted, but the platform returned no readable write time — NOT MEASURED`); + } else if (drift === 0) { + lines.push(` stamp: \`${stamp}\` · platform wrote it at ${writtenAt} · drift 0 — one clock, one act`); + } else { + lines.push( + ` ⚠️ stamp: \`${stamp}\` · platform wrote it at ${writtenAt} · drift ${drift} min` + + (drift > H56_STAMP_TOLERANCE_MIN + ? ` — BEYOND the ${H56_STAMP_TOLERANCE_MIN}-minute tolerance; H56 will file this artefact` + : ` — within the ${H56_STAMP_TOLERANCE_MIN}-minute tolerance`), + ); + } + const sentBytes = Buffer.byteLength(String(sent ?? ''), 'utf8'); + if (typeof stored !== 'string') { + lines.push(' ⚠️ read-back: the stored body could not be read — the write is UNVERIFIED, not verified'); + } else if (stored === sent) { + lines.push(` read-back: ${sentBytes} byte(s) stored, IDENTICAL to what was sent`); + } else { + lines.push( + ` ⚠️ read-back: sent ${sentBytes} byte(s), stored ${Buffer.byteLength(stored, 'utf8')} — the platform ` + + 'MUTATED the body. Read the artefact before trusting it: the sanitizer eats tag-shaped fragments.', + ); + } + return { lines, drift, mutated: typeof stored === 'string' && stored !== sent }; +} + +/** The flags this tool takes. An argument outside this set is a typo, and a typo is refused. */ +export const KNOWN_FLAGS = Object.freeze(['--dry-run', '--json', '--self-test', '--help', '-h']); +export const KNOWN_OPTIONS = Object.freeze(['comment', 'body', 'file', 'repo']); + +export function readOption(argv, name) { + const prefix = `--${name}=`; + const hit = (argv ?? []).find((a) => a.startsWith(prefix)); + return hit === undefined ? null : hit.slice(prefix.length); +} + +/** + * Parse argv into the run's options, or refuse. Pure, so the refusals are + * pinned offline — this is the layer that decides WHERE a write lands, and a + * misread target is an artefact posted onto somebody else's card. + */ +export function parseOptions(argv) { + const args = argv ?? []; + for (const arg of args) { + if (KNOWN_FLAGS.includes(arg)) continue; + const named = /^--([a-z-]+)=/.exec(arg); + if (named && KNOWN_OPTIONS.includes(named[1])) continue; + return { + ok: false, + error: `\`${arg}\` is not an argument this tool takes. Flags: ${KNOWN_FLAGS.join(' ')}; options: ${KNOWN_OPTIONS.map((o) => `--${o}=…`).join(' ')}.`, + }; + } + const comment = readOption(args, 'comment'); + const body = readOption(args, 'body'); + if (comment !== null && body !== null) { + return { ok: false, error: '--comment and --body name two different acts. Pass one: --comment=N posts a new comment, --body=N rewrites the card body.' }; + } + if (comment === null && body === null) { + return { ok: false, error: 'no target. Pass --comment=N to post a comment, or --body=N to rewrite a card body.' }; + } + const raw = comment ?? body; + const number = Number(raw); + if (!Number.isInteger(number) || number <= 0) { + return { ok: false, error: `\`${raw}\` is not a card number. --${comment === null ? 'body' : 'comment'}=N takes the issue number.` }; + } + return { + ok: true, + options: { + mode: comment === null ? 'body' : 'comment', + number, + file: readOption(args, 'file'), + repo: readOption(args, 'repo'), + dryRun: args.includes('--dry-run'), + json: args.includes('--json'), + }, + }; +} + +// --------------------------------------------------------------------------- +// Live layer +// --------------------------------------------------------------------------- + +async function rest(path, { method = 'GET', body = null } = {}) { + const res = await fetch(`${API}${path}`, { + method, + headers: { + accept: 'application/vnd.github+json', + ...(TOKEN ? { authorization: `Bearer ${TOKEN}` } : {}), + ...(body ? { 'content-type': 'application/json' } : {}), + }, + ...(body ? { body: JSON.stringify(body) } : {}), + }); + if (!res.ok) { + const err = new Error(`${method} ${path} -> HTTP ${res.status}`); + err.status = res.status; + throw err; + } + if (res.status === 204) return null; + return res.json(); +} + +async function writeArtefact(repo, options, body) { + 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}`); + 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}`); + return { id: options.number, url: back?.html_url ?? patched?.html_url ?? null, writtenAt: back?.updated_at ?? patched?.updated_at ?? null, stored: back?.body }; +} + +function reportPrerequisiteNotMet(err) { + console.error( + `\npost-stamped: PREREQUISITE NOT MET — ${err.message}\n\n` + + ` Fix: run this where node's fetch reaches api.github.com with a token that can write issues\n` + + ` (a GitHub Actions runner, or an agent container with ${PROXY_FLAG} — this script re-execs\n` + + ' itself with that flag when HTTPS_PROXY is set).\n\n' + + ' NOTHING WAS WRITTEN, and nothing was read back. This is not a failed post and not a successful\n' + + ' one — it is no act at all.\n' + + `\n (Exit code ${EXIT_PREREQUISITE_NOT_MET}, distinct from ${EXIT_REFUSED}'s "the body broke the stamp\n` + + ' contract". Capture it BEFORE any pipe: `node scripts/pm/post-stamped.mjs … > /tmp/p.log 2>&1; echo "EXIT=$?"`.)', + ); + return EXIT_PREREQUISITE_NOT_MET; +} + +function readInput(file) { + if (file) return readFileSync(file, 'utf8'); + return readFileSync(0, 'utf8'); +} + +function rearmThroughProxy(args) { + const plan = proxyRearmPlan({ + env: process.env, + execArgv: process.execArgv, + flagSupported: process.allowedNodeEnvironmentFlags.has(PROXY_FLAG), + }); + if (plan.hint) { + console.error(`ℹ️ ${plan.reason}. A refusal below may be about the route, not this container.`); + return null; + } + if (!plan.rearm) return null; + if (process.env[PROXY_REARM_GUARD] === '1') return null; + console.error(`ℹ️ re-exec with ${plan.flag}: ${plan.reason}.`); + const quiet = process.allowedNodeEnvironmentFlags.has('--disable-warning') ? ['--disable-warning=UNDICI-EHPA'] : []; + const child = spawnSync(process.execPath, [plan.flag, ...quiet, SELF_PATH, ...args], { + stdio: 'inherit', + env: { ...process.env, [PROXY_REARM_GUARD]: '1' }, + }); + if (typeof child.status === 'number') return child.status; + console.error(`⚠️ could not re-exec with ${plan.flag} (${child.error?.message ?? 'no exit status'}); continuing in-process — every request will bypass the proxy.`); + return null; +} + +const USAGE = [ + 'post-stamped — write a seat artefact to GitHub with a stamp this act read, never one typed from memory.', + '', + ' node scripts/pm/post-stamped.mjs --comment=N [--file=PATH] [--repo=OWNER/NAME] [--dry-run] [--json]', + ' node scripts/pm/post-stamped.mjs --body=N [--file=PATH] [--repo=OWNER/NAME] [--dry-run] [--json]', + ' node scripts/pm/post-stamped.mjs --self-test', + '', + ' With no --file the body is read from stdin.', + ` In the body: \`${STAMP_TOKEN}\` is the clock this run reads; \`{{WAS:YYYY-MM-DDThh:mmZ}}\` declares a`, + ' stamp that is a reading of something else. A bare stamp on the opening line, or on a subscript', + ' reading-time line, is REFUSED — that position belongs to the writing act.', + ' The attribution footer is the caller\'s: its form differs by channel and act, so this tool adds none.', +].join('\n'); + +async function main(argv) { + if (argv.includes('--help') || argv.includes('-h')) { + console.log(USAGE); + return EXIT_OK; + } + const parsed = parseOptions(argv); + if (!parsed.ok) { + console.error(`post-stamped: ${parsed.error}`); + return EXIT_USAGE; + } + const options = parsed.options; + + const repoRes = options.repo ? { repo: options.repo, source: '--repo', valid: /^[^/\s]+\/[^/\s]+$/.test(options.repo) } : resolveSweepRepo(process.env); + if (!repoRes.valid) { + console.error( + `post-stamped: ${repoRes.source}=${JSON.stringify(repoRes.repo)} is not a repository in \`owner\`/\`name\` ` + + 'form. Refusing to fall back to a different board — an artefact posted onto the wrong repo is worse ' + + 'than one not posted.', + ); + return EXIT_USAGE; + } + + let input; + try { + input = readInput(options.file); + } catch (err) { + console.error(`post-stamped: could not read the body (${err.message}).`); + return EXIT_USAGE; + } + + const rendered = renderBody(input); + if (!rendered.ok) { + console.error(rendered.error); + return EXIT_REFUSED; + } + + if (options.dryRun) { + console.error( + `post-stamped: DRY RUN — nothing was written. ${rendered.substituted} token(s) substituted with ` + + `\`${rendered.stamp}\`, ${rendered.quoted} quoted stamp(s) rendered verbatim. Target would be ` + + `${repoRes.repo}#${options.number} (${options.mode}).`, + ); + console.log(rendered.body); + return EXIT_OK; + } + + let written; + try { + written = await writeArtefact(repoRes.repo, options, rendered.body); + } catch (err) { + return reportPrerequisiteNotMet(err); + } + + const verdict = readBackVerdict({ + stamp: rendered.stamp, + writtenAt: written.writtenAt, + sent: rendered.body, + stored: written.stored, + substituted: rendered.substituted, + }); + + if (options.json) { + console.log( + JSON.stringify( + { + repo: repoRes.repo, + target: options.number, + mode: options.mode, + id: written.id, + url: written.url, + stamp: rendered.stamp, + substituted: rendered.substituted, + quoted: rendered.quoted, + written_at: written.writtenAt, + drift_minutes: verdict.drift, + body_mutated: verdict.mutated, + }, + null, + 2, + ), + ); + return EXIT_OK; + } + + console.log( + [ + `post-stamped: ${options.mode === 'comment' ? 'comment posted on' : 'body rewritten on'} ${repoRes.repo}#${options.number}`, + ` ${options.mode === 'comment' ? 'comment' : 'card'}: ${written.id} ${written.url ?? '(no url returned)'}`, + ...verdict.lines, + ` substitutions: ${rendered.substituted} ${STAMP_TOKEN}, ${rendered.quoted} quoted`, + ].join('\n'), + ); + return EXIT_OK; +} + +// --------------------------------------------------------------------------- +// --self-test — offline, no network, every branch above driven by fixtures. +// +// The battery ledger this self-test's floor is evaluated against: `battery()` +// opens one, every assertion is attributed to the one most recently opened, and +// a section that stops running names ITSELF at the floor rather than going +// quiet. The counts are a FLOOR, never an equality — adding cases is ordinary +// work and must not go red. +// --------------------------------------------------------------------------- + +const SELF_TEST_BATTERIES = Object.freeze({ + 'the token contract: the two spellings, and nothing else': 9, + 'the refusals: every route that must not reach the board': 20, + 'the substitution: one clock, read once, written everywhere': 9, + 'the read-back: what the transcript can actually prove': 11, + 'the CLI: the one decision a typo must never make': 12, + 'the shared rule: this tool and H56 cannot come to disagree': 6, +}); +const SELF_TEST_BATTERY_FLOOR = 6; +const UNATTRIBUTED_BATTERY = '(unattributed)'; + +let selfTestReachedVerdict = false; + +export function selfTest() { + const batterySeen = new Map(); + let openBattery = null; + const battery = (name) => { + openBattery = name; + }; + const cases = []; + const t = (name, ok, detail) => { + const b = openBattery ?? UNATTRIBUTED_BATTERY; + batterySeen.set(b, (batterySeen.get(b) ?? 0) + 1); + cases.push({ name, ok: Boolean(ok), detail }); + }; + + const NOW_MS = Date.parse('2026-09-10T06:37:48Z'); + const kinds = (text) => stampRefusals(text).map((r) => r.kind); + + battery('the token contract: the two spellings, and nothing else'); + t('the act-clock token is `{{NOW}}`', STAMP_TOKEN === '{{NOW}}'); + t('the clock renders in the protocol spelling — minutes, Z, no seconds', stampNow(NOW_MS) === '2026-09-10T06:37Z'); + t('…truncated, never rounded: 06:37:48 is still 06:37', stampNow(Date.parse('2026-09-10T06:37:48Z')) === stampNow(Date.parse('2026-09-10T06:37:02Z'))); + t('⛔ the quoted-token regex is NOT global — an exported `g` regex carries a cursor between callers', QUOTED_TOKEN_RE.global === false); + t('⛔ …and neither is the leftover-token one', ANY_TOKEN_RE.global === false); + t('masking a quoted stamp preserves the body length, so positions do not move', maskQuotedStamps('a {{WAS:2026-09-08T14:00Z}} b').length === 'a {{WAS:2026-09-08T14:00Z}} b'.length); + t('…and leaves no stamp behind for the bare scan to find', protocolStamps(maskQuotedStamps('{{WAS:2026-09-08T14:00Z}}')).length === 0); + t('the quoted values are readable on their own', quotedStampValues('x {{WAS:2026-09-08T14:00Z}} y')[0] === '2026-09-08T14:00Z'); + t('…and two of them are both read, not just the first', quotedStampValues('{{WAS:2026-09-08T14:00Z}} {{WAS:2026-09-09T01:00Z}}').length === 2); + + battery('the refusals: every route that must not reach the board'); + const OPENING = 'Claim: skills seat, session `session_x`, 2026-09-10T06:37Z — dispatched.'; + t('⭐ a bare stamp on the OPENING line is refused', kinds(OPENING).includes('positional')); + t('…and the refusal names the position rather than guessing at meaning', stampRefusals(OPENING)[0].detail.includes('the opening line')); + t('…and offers both legal spellings by name', stampRefusals(OPENING)[0].detail.includes('{{NOW}}') && stampRefusals(OPENING)[0].detail.includes('{{WAS:2026-09-10T06:37Z}}')); + t('a bare stamp on a subscript reading-time line is refused', kinds('Seat post\n\nread 2026-09-10T06:37Z').includes('positional')); + t('⭐ the same body with the token instead is ACCEPTED', stampRefusals('Claim: skills seat, {{NOW}} — dispatched.').length === 0); + t('⭐ MIXED — the token plus a bare stamp elsewhere is refused', kinds('Claim: {{NOW}}\n\nThe board was read at 2026-09-08T14:00Z.').includes('mixed')); + t('…and the mixed refusal says a reader cannot tell the two clocks apart', stampRefusals('Claim: {{NOW}}\n\nread 2026-09-08T14:00Z').find((r) => r.kind === 'mixed').detail.includes('a reader cannot tell which')); + t('⛔ a bare stamp in PROSE with no token is NOT refused — quoting a ruling is a reading of something else', stampRefusals('Title\n\nThe 2026-09-08T14:00Z ruling stands.').length === 0); + t('a DECLARED quoted stamp is accepted even in the opening position', stampRefusals('The {{WAS:2026-09-08T14:00Z}} ruling stands.').length === 0); + t('…and beside a token, which is the whole point of the declaration', stampRefusals('Verdict {{NOW}} — on the board read {{WAS:2026-09-08T14:00Z}}.').length === 0); + t('⛔ the quoted route is not a free-text escape: a non-stamp value is refused', kinds('{{WAS:yesterday}}').includes('quoted-not-a-stamp')); + t('⛔ …nor a smuggling route: a stamp with prose glued on is refused', kinds('{{WAS:2026-09-08T14:00Z ruling}}').includes('quoted-not-a-stamp')); + t('surrounding whitespace inside the declaration is tolerated', stampRefusals('{{WAS: 2026-09-08T14:00Z }}').length === 0); + t('a mistyped token is refused rather than posted literally', renderBody('Claim: {{now}} — dispatched.', NOW_MS).kind === 'unknown-token'); + t('…and the refusal names the survivor so the typo is findable', renderBody('Claim: {{now}}', NOW_MS).error.includes('{{now}}')); + t('…and says why the quiet direction is the dangerous one', renderBody('Claim: {{now}}', NOW_MS).error.includes('leave the artefact unstamped')); + t('an EMPTY body is refused — an empty artefact is noise a reader must judge', renderBody(' \n\n', NOW_MS).kind === 'empty'); + t('every refusal reaches the caller as text naming the two spellings', refusalText(stampRefusals(OPENING)).includes('{{WAS:YYYY-MM-DDThh:mmZ}}')); + t('…and states that no flag turns the contract off', refusalText(stampRefusals(OPENING)).includes('There is no flag')); + t('…and that nothing was written', refusalText(stampRefusals(OPENING)).includes('Nothing was written')); + + battery('the substitution: one clock, read once, written everywhere'); + const TWO = renderBody('Claim: {{NOW}}\n\nRound opened {{NOW}}.', NOW_MS); + t('a body that clears the contract renders', TWO.ok === true); + t('⭐ two tokens get the SAME stamp — one clock, read once', TWO.body.split('2026-09-10T06:37Z').length - 1 === 2); + t('…counted for the transcript', TWO.substituted === 2); + t('…and the stamp is the clock handed in, never a second read', TWO.stamp === '2026-09-10T06:37Z'); + const QUOTED = renderBody('Verdict {{NOW}} on the board read {{WAS:2026-09-08T14:00Z}}.', NOW_MS); + t('a quoted stamp renders VERBATIM', QUOTED.body.includes('board read 2026-09-08T14:00Z.')); + t('…counted apart from the substituted ones', QUOTED.quoted === 1 && QUOTED.substituted === 1); + t('nothing else in the body moves', renderBody('# Title\n\n- a\n- b\n', NOW_MS).body === '# Title\n\n- a\n- b\n'); + t('a body with no token at all is still postable', renderBody('os-dev-report\n\n{"issue": 17314}', NOW_MS).ok === true); + t('…and reports zero substitutions rather than pretending to a clock', renderBody('os-dev-report', NOW_MS).substituted === 0); + + battery('the read-back: what the transcript can actually prove'); + const SENT = 'Claim: 2026-09-10T06:37Z'; + const ON_TIME = readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: SENT, substituted: 1 }); + t('⭐ a stamp inside the minute the platform stored it reads as ZERO drift', ON_TIME.drift === 0); + t('…said in one line a transcript carries', ON_TIME.lines[0].includes('one clock, one act')); + t('…and the bytes are compared, not assumed', ON_TIME.lines[1].includes('IDENTICAL to what was sent')); + const LATE = readBackVerdict({ stamp: '2026-09-10T05:27Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: SENT, substituted: 1 }); + t('⭐ a stamp 70 minutes from its own write is loud', LATE.drift === 70); + t('…and names the patrol that will file it', LATE.lines[0].includes('H56 will file this artefact')); + t('a drift inside the tolerance says so instead', readBackVerdict({ stamp: '2026-09-10T06:30Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: SENT, substituted: 1 }).lines[0].includes('within the')); + t('an unreadable write time is NOT MEASURED, never zero drift', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: null, sent: SENT, stored: SENT, substituted: 1 }).lines[0].includes('NOT MEASURED')); + t('…and its drift is null rather than a number', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: null, sent: SENT, stored: SENT, substituted: 1 }).drift === null); + t('a body with no substitution claims no clock', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: SENT, substituted: 0 }).lines[0].includes('no clock to check')); + t('⭐ a body the platform MUTATED is reported, not assumed identical', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: `${SENT} x`, substituted: 1 }).mutated === true); + t('…and the sanitizer is named as the thing to go read about', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: `${SENT} x`, substituted: 1 }).lines[1].includes('sanitizer')); + t('an unreadable stored body is UNVERIFIED, never verified', readBackVerdict({ stamp: '2026-09-10T06:37Z', writtenAt: '2026-09-10T06:37:48Z', sent: SENT, stored: undefined, substituted: 1 }).lines[1].includes('UNVERIFIED')); + + battery('the CLI: the one decision a typo must never make'); + t('a comment target parses', parseOptions(['--comment=17314']).options.mode === 'comment'); + t('…with the number read as a number', parseOptions(['--comment=17314']).options.number === 17314); + t('a body target parses', parseOptions(['--body=17314']).options.mode === 'body'); + t('⛔ both targets at once is refused — they are two different acts', parseOptions(['--comment=1', '--body=2']).ok === false); + t('⛔ no target at all is refused, never defaulted', parseOptions([]).ok === false); + t('⛔ a non-numeric target is refused rather than coerced', parseOptions(['--comment=seventeen']).ok === false); + t('⛔ a zero or negative target is refused', parseOptions(['--comment=0']).ok === false); + t('⛔ an unknown flag is a typo and is refused', parseOptions(['--comment=1', '--wrte']).ok === false); + t('…and the refusal lists what the tool does take', parseOptions(['--comment=1', '--wrte']).error.includes('--dry-run')); + t('--dry-run is carried through', parseOptions(['--comment=1', '--dry-run']).options.dryRun === true); + t('--json is carried through', parseOptions(['--comment=1', '--json']).options.json === true); + t('--repo and --file are read as values, not flags', parseOptions(['--comment=1', '--repo=o/n', '--file=b.md']).options.repo === 'o/n'); + + battery('the shared rule: this tool and H56 cannot come to disagree'); + t('⭐ the positions this tool refuses are the ones H56 reads — one imported reader, never two', h56StampedReadings(maskQuotedStamps(OPENING)).length === 1); + t('⭐ …so a body this tool accepts leaves H56 nothing in those positions', h56StampedReadings(maskQuotedStamps(TWO.body.replace(/2026-09-10T06:37Z/g, '{{NOW}}'))).length === 0); + t('the tolerance is the imported constant, never a second number', H56_STAMP_TOLERANCE_MIN === 15); + t('a stamp this tool substitutes is zero-drift against its own write instant', stampDriftMinutes(stampNow(NOW_MS), '2026-09-10T06:37:48Z') === 0); + t('…and an estimate is beyond the tolerance by the same arithmetic', stampDriftMinutes('2026-09-10T05:27Z', '2026-09-10T06:37:48Z') > H56_STAMP_TOLERANCE_MIN); + t('the exit register keeps a contract refusal apart from a transport failure', EXIT_REFUSED !== EXIT_PREREQUISITE_NOT_MET); + + // The floor, evaluated last: a battery that stops running names itself here. + const failed = cases.filter((c) => !c.ok); + for (const c of cases) console.log(` ${c.ok ? '✓' : '✗'} ${c.name}`); + const declared = Object.keys(SELF_TEST_BATTERIES); + const floorFailures = []; + const floorFailure = (text) => floorFailures.push(text); + if (declared.length < SELF_TEST_BATTERY_FLOOR) { + floorFailure(`the battery ledger declares ${declared.length} batteries, below its floor of ${SELF_TEST_BATTERY_FLOOR} — a section that stopped being declared is a section nothing floors.`); + } + for (const [name, count] of batterySeen) { + if (!(name in SELF_TEST_BATTERIES)) { + floorFailure(`self-test battery "${name}" registered ${count} case(s) but is not declared in SELF_TEST_BATTERIES — an assertion attributed to no declared battery is one nothing floors.`); + } + } + for (const name of declared) { + const count = batterySeen.get(name) ?? 0; + if (count >= SELF_TEST_BATTERIES[name]) continue; + floorFailure( + count === 0 + ? `self-test battery "${name}" DID NOT RUN — 0 cases registered, ${SELF_TEST_BATTERIES[name]} pinned. The verdict below would have claimed those cases hold.` + : `self-test battery "${name}" registered ${count} case(s), below its pinned floor of ${SELF_TEST_BATTERIES[name]} — cases that used to run no longer do.`, + ); + } + for (const text of floorFailures) console.error(` ✗ ${text}`); + if (failed.length > 0 || floorFailures.length > 0) { + for (const c of failed) console.error(` ✗ ${c.name}${c.detail ? ` (${c.detail})` : ''}`); + console.error(`✗ post-stamped self-test: ${failed.length} of ${cases.length} case(s) failed, ${floorFailures.length} floor problem(s).`); + selfTestReachedVerdict = true; + return 1; + } + console.log(`✓ post-stamped self-test: ${cases.length} cases pass across ${declared.length} batteries — offline, no network, no token.`); + selfTestReachedVerdict = true; + return 0; +} + +if (isEntrypoint(import.meta.url)) { + if (process.argv.includes('--self-test')) { + const code = selfTest(); + if (!selfTestReachedVerdict) { + console.error( + '\n✗ post-stamped self-test: selfTest() returned without reaching its verdict, so no success\n' + + 'line was printed. Exiting 0 here would report a self-test that never finished as a self-test\n' + + 'that passed.\n', + ); + process.exit(1); + } + process.exit(code); + } else { + // ⛔ Not on a dry run: that path makes no request, so re-execing it would + // spawn a second process to prove a route nothing is about to use. + const rearmed = process.argv.includes('--dry-run') ? null : rearmThroughProxy(process.argv.slice(2)); + if (rearmed !== null) process.exit(rearmed); + main(process.argv.slice(2)).then((code) => process.exit(code)); + } +}