diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS
index 4a07214fc7..5198248821 100644
--- a/.github/CODEOWNERS
+++ b/.github/CODEOWNERS
@@ -1,38 +1,38 @@
# Default reviewers
-* @dalsoop
+* @lidge-jun @Ingwannu
# High-impact runtime behavior
-/src/adapters/ @dalsoop
-/src/providers/ @dalsoop
-/src/codex/ @dalsoop
-/src/server/ @dalsoop
+/src/adapters/ @lidge-jun @Ingwannu
+/src/providers/ @lidge-jun @Ingwannu
+/src/codex/ @lidge-jun @Ingwannu
+/src/server/ @lidge-jun @Ingwannu
# Repository automation and release security
-/.github/ @dalsoop
-/.coderabbit.yaml @dalsoop
-/.npmignore @dalsoop
-/bunfig.toml @dalsoop
-/scripts/release.ts @dalsoop
-/scripts/release-notes.ts @dalsoop
-/scripts/release-version-sources.ts @dalsoop
-/scripts/prepare-package.ts @dalsoop
-/package.json @dalsoop
-/bun.lock @dalsoop
+/.github/ @lidge-jun @Ingwannu
+/.coderabbit.yaml @lidge-jun @Ingwannu
+/.npmignore @lidge-jun @Ingwannu
+/bunfig.toml @lidge-jun @Ingwannu
+/scripts/release.ts @lidge-jun @Ingwannu
+/scripts/release-notes.ts @lidge-jun @Ingwannu
+/scripts/release-version-sources.ts @lidge-jun @Ingwannu
+/scripts/prepare-package.ts @lidge-jun @Ingwannu
+/package.json @lidge-jun @Ingwannu
+/bun.lock @lidge-jun @Ingwannu
# Authentication, credentials, and management API
-/src/oauth/ @dalsoop
-/src/codex/auth-context.ts @dalsoop
-/src/server/auth-cors.ts @dalsoop
-/src/server/management-api.ts @dalsoop
-/src/lib/admin-secrets.ts @dalsoop
-/src/lib/service-secrets.ts @dalsoop
-/src/server/management-auth.ts @dalsoop
+/src/oauth/ @lidge-jun @Ingwannu
+/src/codex/auth-context.ts @lidge-jun @Ingwannu
+/src/server/auth-cors.ts @lidge-jun @Ingwannu
+/src/server/management-api.ts @lidge-jun @Ingwannu
+/src/lib/admin-secrets.ts @lidge-jun @Ingwannu
+/src/lib/service-secrets.ts @lidge-jun @Ingwannu
+/src/server/management-auth.ts @lidge-jun @Ingwannu
# Governance and security policy
-/AGENTS.md @dalsoop
-**/AGENTS.md @dalsoop
-/MAINTAINERS.md @dalsoop
-/SECURITY.md @dalsoop
+/AGENTS.md @lidge-jun @Ingwannu
+**/AGENTS.md @lidge-jun @Ingwannu
+/MAINTAINERS.md @lidge-jun @Ingwannu
+/SECURITY.md @lidge-jun @Ingwannu
# Proxy core boundary — owner approval required.
# These four files carry every user's request path, including users of no optional
diff --git a/.github/ISSUE_TEMPLATE/config.yml b/.github/ISSUE_TEMPLATE/config.yml
index 07fd1d1cf6..7e4c10e160 100644
--- a/.github/ISSUE_TEMPLATE/config.yml
+++ b/.github/ISSUE_TEMPLATE/config.yml
@@ -4,7 +4,7 @@ contact_links:
url: https://github.com/lidge-jun/opencodex/security/advisories/new
about: Report undisclosed vulnerabilities privately to the maintainers. Do not open a public issue.
- name: Security policy
- url: https://github.com/lidge-jun/opencodex/blob/main/SECURITY.md
+ url: https://github.com/lidge-jun/opencodex/blob/dev/SECURITY.md
about: Read the supported-version and reporting guidance before sharing security-sensitive details.
- name: Contributing guide
url: https://opencodex.me/contributing/
diff --git a/.github/actions/setup-project-bun/action.yml b/.github/actions/setup-project-bun/action.yml
index 1ab22dd1dc..cf28f6f9d4 100644
--- a/.github/actions/setup-project-bun/action.yml
+++ b/.github/actions/setup-project-bun/action.yml
@@ -8,8 +8,8 @@ description: >-
# (#6713 run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9). It moved from 1.4.0 to
# 1.4.3 for oven-sh/bun#44581: 1.4.0's Bun.spawnSync could lose a child's exit after
# finalizers ran inside an earlier call and spin past its own timeout (#4956).
-# Rejoin only after the upstream runner crash is fixed and a green lane=all
-# dispatch proves the unified version; then delete testRunnerBun and this role input.
+# Both roles now default to the package's 1.4.4 security transition, retaining role validation.
+# Promotion requires a green full cross-platform lane=all run on the exact candidate head.
inputs:
role:
description: Bun role to install (runtime or test-runner).
diff --git a/.github/scripts/enforce-pr-target.test.cjs b/.github/scripts/enforce-pr-target.test.cjs
index 8973f07a63..9756869eb9 100644
--- a/.github/scripts/enforce-pr-target.test.cjs
+++ b/.github/scripts/enforce-pr-target.test.cjs
@@ -94,7 +94,9 @@ describe("enforce-pr-target workflow", () => {
it("writes exactly one consolidated comment via a single upsert helper", () => {
assert.match(workflow, /GATE_MARKER,/);
- assert.match(workflow, /comment\.body\?\.includes\(GATE_MARKER\)/);
+ // The gate comment is the bot comment that starts with GATE_MARKER; a
+ // marker echoed inside another comment does not classify it.
+ assert.match(workflow, /comments\.find\(isGateComment\)/);
assert.match(workflow, /upsertGateComment/);
assert.match(workflow, /buildGateCommentBody/);
// No legacy two-comment write path remains.
@@ -163,24 +165,23 @@ describe("enforce-pr-target workflow", () => {
.split("- name: Checkout trusted PR-quality scripts")[1]
.split(/\n {6}- name:/)[0];
assert.match(checkoutStep, /actions\/checkout@[0-9a-f]{40}/);
- // The trusted ref comes from a fixed set of integration branches, never
- // from the PR's own base commit: a stacked child's base is another open
- // PR's head, and `base.sha` would let that unpromoted commit choose the
- // code that runs with this job's write-capable token.
+ // The trusted ref is the single integration branch, never the PR's own
+ // base commit: a stacked child's base is another open PR's head, and
+ // `base.sha` would let that unpromoted commit choose the code that runs
+ // with this job's write-capable token.
//
// `status` has no pull_request payload and sources from the default branch
- // that supplied the privileged workflow. A `main`-targeting PR sources
- // from `main` so the workflow definition and the scripts match. Everything
- // else resolves to `dev`.
+ // that supplied the privileged workflow. Every pull_request event resolves
+ // to `dev`, the only integration branch.
//
- // Exact equality, not fragment matching: separate checks for `status`,
- // `main`, and `dev` would all pass with the operator grouping wrong or a
- // surviving `base.sha` fallback.
+ // Exact equality, not fragment matching: separate checks for `status` and
+ // `dev` would both pass with the operator grouping wrong or a surviving
+ // `base.sha` fallback.
const ref = checkoutStep.match(/^\s*ref:\s*(.+)$/m)?.[1];
assert.ok(ref, "trusted checkout must declare ref");
assert.equal(
ref.replace(/\s+/g, " ").trim(),
- "${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }}",
+ "${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }}",
);
assert.doesNotMatch(ref, /base\.sha|head\.(?:sha|ref)/);
// Pinning the checkout ref only gates one step. A later `run:` or
@@ -213,7 +214,7 @@ describe("enforce-pr-target workflow", () => {
const checkouts = workflow.match(/uses:\s*actions\/checkout@[\s\S]*?(?=\n {6}- name:|$)/g) ?? [];
for (const step of checkouts) {
const stepRef = (step.match(/^\s*ref:\s*(.+)$/m)?.[1] ?? "").replace(/\s+/g, " ").trim();
- assert.equal(stepRef, "${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }}", "every checkout must use the trusted ref");
+ assert.equal(stepRef, "${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }}", "every checkout must use the trusted ref");
assert.doesNotMatch(step, /repository:/, "a checkout must not retarget its repository");
}
// Checkout is not the only way to obtain PR-controlled code. A `run:` step
diff --git a/.github/scripts/pr-hygiene.cjs b/.github/scripts/pr-hygiene.cjs
index e0be6ae2c2..82586d4dea 100644
--- a/.github/scripts/pr-hygiene.cjs
+++ b/.github/scripts/pr-hygiene.cjs
@@ -292,6 +292,109 @@ const HYGIENE_GATE_LABELS = [
"attribution-approved",
];
+/**
+ * Exception approvals vouch for one revision of the change. Each counts only
+ * while the head the hygiene workflow last recorded is still the head being
+ * evaluated and nothing has rewritten the branch since. Sponsorship
+ * (`maintainer-sponsored`) is about which surfaces change, not about one
+ * revision, so it is not head-bound.
+ */
+const HEAD_BOUND_APPROVAL_LABELS = [
+ "test-exception-approved",
+ "suppression-approved",
+ "generated-change-approved",
+ "dependency-change-approved",
+ "attribution-approved",
+];
+
+/** Issue events after which the head can point at an earlier commit again. */
+const HEAD_REWRITE_EVENTS = ["head_ref_force_pushed", "head_ref_restored"];
+
+const APPROVAL_RECORD_TOKEN = "pr-hygiene-approvals";
+const APPROVAL_RECORD_LINE = /^$/;
+const FULL_SHA = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
+
+function isRewriteCount(value) {
+ return Number.isSafeInteger(value) && value >= 0;
+}
+
+/**
+ * Read the head binding the hygiene workflow wrote as the last line of its
+ * own section. The token must occur exactly once in `source` and sit on that
+ * last line, so echoed text (a changed path can contain newlines) can only
+ * make the record unreadable, never stand in for it.
+ * @returns {{ head: string, headRewrites: number | null } | null}
+ */
+function parseApprovalRecord(source) {
+ if (typeof source !== "string") return null;
+ if (source.split(APPROVAL_RECORD_TOKEN).length !== 2) return null;
+ const lines = source.split("\n").map((line) => line.trim()).filter(Boolean);
+ const match = lines.at(-1)?.match(APPROVAL_RECORD_LINE);
+ if (!match) return null;
+ let value;
+ try {
+ value = JSON.parse(match[1]);
+ } catch {
+ return null;
+ }
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return null;
+ if (Object.keys(value).sort().join(",") !== "head,headRewrites") return null;
+ if (typeof value.head !== "string" || !FULL_SHA.test(value.head)) return null;
+ if (value.headRewrites !== null && !isRewriteCount(value.headRewrites)) return null;
+ return { head: value.head, headRewrites: value.headRewrites };
+}
+
+/** `headRewrites` is null when the history read failed: nothing is confirmed. */
+function formatApprovalRecord({ head, headRewrites }) {
+ const value = { head, headRewrites: isRewriteCount(headRewrites) ? headRewrites : null };
+ return "";
+}
+
+function countHeadRewrites(events) {
+ return (events ?? []).filter((entry) => HEAD_REWRITE_EVENTS.includes(entry?.event)).length;
+}
+
+function presentHeadBoundApprovals(labels) {
+ return HEAD_BOUND_APPROVAL_LABELS.filter((label) => labels.includes(label));
+}
+
+/** True when a current rewrite count could still confirm an approval. */
+function needsHeadRewriteCount({ labels = [], headSha, record = null, eventAction }) {
+ return (
+ eventAction !== "synchronize" &&
+ record !== null &&
+ record.head === headSha &&
+ isRewriteCount(record.headRewrites) &&
+ presentHeadBoundApprovals(labels).length > 0
+ );
+}
+
+/**
+ * Split the head-bound approvals on the pull request into the ones that still
+ * describe the evaluated head and the ones that do not. They are kept only
+ * when the last recorded evaluation saw this same head and the rewrite count,
+ * read before that evaluation's snapshot and again after this one's, has not
+ * changed. Without a rewrite, fast-forward pushes cannot bring the recorded
+ * head back, so the head has not moved since that evaluation, which removed
+ * every approval it could not confirm. A synchronize event, a missing record,
+ * or an unknown count confirms nothing.
+ * @returns {{ kept: string[], stale: string[] }}
+ */
+function reconcileHeadBoundApprovals({
+ labels = [],
+ headSha,
+ record = null,
+ eventAction,
+ headRewriteCount = null,
+}) {
+ const present = presentHeadBoundApprovals(labels);
+ const current =
+ needsHeadRewriteCount({ labels, headSha, record, eventAction }) &&
+ isRewriteCount(headRewriteCount) &&
+ headRewriteCount === record.headRewrites;
+ return current ? { kept: present, stale: [] } : { kept: [], stale: present };
+}
+
/**
* Combine patch-hygiene and sponsored-surface failures into one list so the
* hygiene workflow and the PR quality gate cannot disagree about Ready.
@@ -340,6 +443,10 @@ module.exports = {
addedLines,
assessHygiene,
collectDeterministicHygieneFailures,
+ countHeadRewrites,
+ formatApprovalRecord,
+ HEAD_BOUND_APPROVAL_LABELS,
+ HEAD_REWRITE_EVENTS,
HYGIENE_FAILURE_HINTS,
HYGIENE_GATE_LABELS,
hasEmptyCatch,
@@ -347,6 +454,9 @@ module.exports = {
isBehaviorPath,
isGeneratedPath,
isTestPath,
+ needsHeadRewriteCount,
+ parseApprovalRecord,
+ reconcileHeadBoundApprovals,
resultLines,
resultLinesByHunk,
};
diff --git a/.github/scripts/pr-hygiene.test.cjs b/.github/scripts/pr-hygiene.test.cjs
index 3ab5a8b2ca..165d78566a 100644
--- a/.github/scripts/pr-hygiene.test.cjs
+++ b/.github/scripts/pr-hygiene.test.cjs
@@ -6,9 +6,15 @@ const {
addedLines,
assessHygiene,
collectDeterministicHygieneFailures,
+ countHeadRewrites,
+ formatApprovalRecord,
+ HEAD_BOUND_APPROVAL_LABELS,
HYGIENE_FAILURE_HINTS,
HYGIENE_GATE_LABELS,
hasEmptyCatch,
+ needsHeadRewriteCount,
+ parseApprovalRecord,
+ reconcileHeadBoundApprovals,
resultLines,
resultLinesByHunk,
} = require("./pr-hygiene.cjs");
@@ -308,7 +314,7 @@ describe("pr-hygiene workflow trust boundary", () => {
assert.ok(ref, "trusted checkout must declare ref");
assert.equal(
ref.replace(/\s+/g, " ").trim(),
- "${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }}",
+ "dev",
);
// A stacked child PR's base is another open PR's head; neither a base nor
// a head ref may select the code that runs with the write-capable token.
@@ -349,7 +355,7 @@ describe("pr-hygiene workflow trust boundary", () => {
const checkouts = workflow.match(/uses:\s*actions\/checkout@[\s\S]*?(?=\n {6}- name:|$)/g) ?? [];
for (const step of checkouts) {
const stepRef = (step.match(/^\s*ref:\s*(.+)$/m)?.[1] ?? "").replace(/\s+/g, " ").trim();
- assert.equal(stepRef, "${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }}", "every checkout must use the trusted ref");
+ assert.equal(stepRef, "dev", "every checkout must use the trusted ref");
assert.doesNotMatch(step, /repository:/, "a checkout must not retarget its repository");
}
// Checkout is not the only way to obtain PR-controlled code. A `run:` step
@@ -391,3 +397,100 @@ describe("pr-hygiene workflow trust boundary", () => {
);
});
});
+
+describe("head-bound approvals", () => {
+ const HEAD = "c".repeat(40);
+ const OTHER = "d".repeat(40);
+ const record = (head, headRewrites) =>
+ "";
+
+ it("covers exactly the exception approvals, not sponsorship", () => {
+ assert.deepEqual(
+ [...HEAD_BOUND_APPROVAL_LABELS].sort(),
+ HYGIENE_GATE_LABELS.filter(
+ (label) => label !== "intake: hygiene-blocked" && label !== "maintainer-sponsored",
+ ).sort(),
+ );
+ });
+
+ it("round-trips a record, including an unknown rewrite count", () => {
+ const line = formatApprovalRecord({ head: HEAD, headRewrites: 2 });
+ assert.equal(line, record(HEAD, 2));
+ assert.deepEqual(parseApprovalRecord("status\n\n" + line), { head: HEAD, headRewrites: 2 });
+ assert.deepEqual(parseApprovalRecord(formatApprovalRecord({ head: HEAD, headRewrites: undefined })), {
+ head: HEAD,
+ headRewrites: null,
+ });
+ assert.deepEqual(parseApprovalRecord(record("e".repeat(64), 0)), { head: "e".repeat(64), headRewrites: 0 });
+ });
+
+ it("rejects anything but one well-formed record on the last line", () => {
+ for (const source of [
+ null,
+ "",
+ record(HEAD, 0) + "\nlater line",
+ record(HEAD, 0) + "\n" + record(HEAD, 0),
+ "mentions pr-hygiene-approvals elsewhere\n" + record(HEAD, 0),
+ "",
+ "",
+ "",
+ "",
+ record("abc", 0),
+ record(HEAD.toUpperCase(), 0),
+ record(HEAD, -1),
+ record(HEAD, 1.5),
+ record(HEAD, "1"),
+ ]) {
+ assert.equal(parseApprovalRecord(source), null, String(source));
+ }
+ });
+
+ it("counts only head rewrite events", () => {
+ assert.equal(
+ countHeadRewrites([
+ { event: "head_ref_force_pushed" },
+ { event: "labeled" },
+ { event: "head_ref_restored" },
+ null,
+ ]),
+ 2,
+ );
+ assert.equal(countHeadRewrites(undefined), 0);
+ });
+
+ it("keeps approvals only under an unchanged head and rewrite count", () => {
+ const labels = ["test-exception-approved", "maintainer-sponsored"];
+ const base = { labels, headSha: HEAD, record: { head: HEAD, headRewrites: 1 }, eventAction: "edited" };
+ const kept = { kept: ["test-exception-approved"], stale: [] };
+ const stale = { kept: [], stale: ["test-exception-approved"] };
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1 }), kept);
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 2 }), stale);
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: null }), stale);
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, eventAction: "synchronize" }), stale);
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, headSha: OTHER }), stale);
+ assert.deepEqual(reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, record: null }), stale);
+ assert.deepEqual(
+ reconcileHeadBoundApprovals({ ...base, headRewriteCount: 1, record: { head: HEAD, headRewrites: null } }),
+ stale,
+ );
+ assert.deepEqual(
+ reconcileHeadBoundApprovals({ ...base, labels: ["maintainer-sponsored"], headRewriteCount: 1 }),
+ { kept: [], stale: [] },
+ );
+ });
+
+ it("asks for a rewrite count only when one could confirm an approval", () => {
+ const base = {
+ labels: ["suppression-approved"],
+ headSha: HEAD,
+ record: { head: HEAD, headRewrites: 0 },
+ eventAction: "labeled",
+ };
+ assert.equal(needsHeadRewriteCount(base), true);
+ assert.equal(needsHeadRewriteCount({ ...base, labels: [] }), false);
+ assert.equal(needsHeadRewriteCount({ ...base, eventAction: "synchronize" }), false);
+ assert.equal(needsHeadRewriteCount({ ...base, headSha: OTHER }), false);
+ assert.equal(needsHeadRewriteCount({ ...base, record: null }), false);
+ assert.equal(needsHeadRewriteCount({ ...base, record: { head: HEAD, headRewrites: null } }), false);
+ });
+});
diff --git a/.github/scripts/pr-quality-messages.cjs b/.github/scripts/pr-quality-messages.cjs
index e9b642b574..c37625ea51 100644
--- a/.github/scripts/pr-quality-messages.cjs
+++ b/.github/scripts/pr-quality-messages.cjs
@@ -30,6 +30,18 @@ const HYGIENE_BLOCK_RE = new RegExp(
`^[ \\t]*${HYGIENE_BLOCK_START}[ \\t]*\\n([\\s\\S]*?)\\n[ \\t]*${HYGIENE_BLOCK_END}[ \\t]*$`,
"m"
);
+/**
+ * Whole-line delimiter matchers, the same shape HYGIENE_BLOCK_RE anchors on.
+ * A block is only read when each delimiter occurs on exactly one line: a
+ * changed filename can contain newlines, so an echoed path can add delimiter
+ * lines, and an ambiguous block must never be cut at the first one.
+ */
+const HYGIENE_BLOCK_START_LINE_RE = new RegExp(`^[ \\t]*${HYGIENE_BLOCK_START}[ \\t]*$`, "gm");
+const HYGIENE_BLOCK_END_LINE_RE = new RegExp(`^[ \\t]*${HYGIENE_BLOCK_END}[ \\t]*$`, "gm");
+
+function countDelimiterLines(text, pattern) {
+ return (text.match(pattern) ?? []).length;
+}
function inlineCode(value) {
const text = String(value);
@@ -41,6 +53,37 @@ function inlineCode(value) {
return `${delimiter}${text}${delimiter}`;
}
+/**
+ * Render contributor-supplied text (a changed path) on one line: control
+ * characters, including newlines, become `\uXXXX` escapes. Without this an
+ * echoed path could add whole lines, such as delimiter or record lines, to a
+ * bot comment.
+ */
+function escapeControlCharacters(value) {
+ return String(value).replace(
+ /[\u0000-\u001f\u007f\u2028\u2029]/g,
+ character => "\\u" + character.charCodeAt(0).toString(16).padStart(4, "0")
+ );
+}
+
+/** The consolidated gate comment: written by the workflow bot, marker first. */
+function isGateComment(comment) {
+ return (
+ comment?.user?.login === "github-actions[bot]" &&
+ typeof comment.body === "string" &&
+ comment.body.startsWith(GATE_MARKER)
+ );
+}
+
+/** The standalone hygiene comment posted before a gate comment exists. */
+function isStandaloneHygieneComment(comment) {
+ return (
+ comment?.user?.login === "github-actions[bot]" &&
+ typeof comment.body === "string" &&
+ comment.body.startsWith(HYGIENE_MARKER)
+ );
+}
+
function readinessChecklistLines(readiness) {
return REVIEW_READINESS_ITEMS.map(
(item, index) =>
@@ -121,9 +164,17 @@ function buildGateCommentBody(state, opts) {
* `null` when the comment has none. The gate rebuilds its body from scratch
* every run, so without this round-trip a hygiene update from the separate
* hygiene workflow would be silently dropped on the next gate write.
+ * An ambiguous block (a delimiter on more than one line) reads as `null`, so
+ * the gate drops it on rebuild instead of re-wrapping a truncated section.
*/
function extractHygieneSection(body) {
if (typeof body !== "string") return null;
+ if (
+ countDelimiterLines(body, HYGIENE_BLOCK_START_LINE_RE) !== 1 ||
+ countDelimiterLines(body, HYGIENE_BLOCK_END_LINE_RE) !== 1
+ ) {
+ return null;
+ }
const match = body.match(HYGIENE_BLOCK_RE);
if (!match) return null;
return match[1]
@@ -150,13 +201,40 @@ function withHygieneSection(body, hygieneLines) {
].join("\n");
if (HYGIENE_BLOCK_RE.test(base)) {
- return base.replace(HYGIENE_BLOCK_RE, block);
+ // A callback, not a replacement string: echoed paths can contain $&, $1
+ // and similar tokens that a template would expand into extra lines.
+ return base.replace(HYGIENE_BLOCK_RE, () => block);
}
// No existing block: append one at the end.
return `${base.replace(/\s+$/, "")}\n\n## Hygiene\n\n${block}\n`;
}
+/**
+ * The text the hygiene workflow last wrote for this pull request: the hygiene
+ * block of the first bot comment that starts with GATE_MARKER, or the first
+ * bot comment that starts with HYGIENE_MARKER while that gate comment has no
+ * block yet (the gate never absorbs it). A marker elsewhere in a comment does
+ * not classify it. An ambiguous gate block yields `null`; later comments are
+ * never searched for a more convenient candidate.
+ */
+function authoritativeHygieneSection(comments) {
+ const list = comments ?? [];
+ const gate = list.find(isGateComment);
+ if (gate) {
+ const section = extractHygieneSection(gate.body);
+ if (section !== null) return section;
+ if (
+ countDelimiterLines(gate.body, HYGIENE_BLOCK_START_LINE_RE) > 0 ||
+ countDelimiterLines(gate.body, HYGIENE_BLOCK_END_LINE_RE) > 0
+ ) {
+ return null;
+ }
+ }
+ const standalone = list.find(isStandaloneHygieneComment);
+ return standalone ? standalone.body : null;
+}
+
function descriptionFailureLines(reason) {
switch (reason) {
case "empty":
@@ -196,17 +274,7 @@ function buildFailureSections(failures, { pr, allowedBases, defaultBase }) {
"",
`This pull request currently targets ${inlineCode(pr.base.ref)}, but pull requests must target one of ${allowedBases.map(inlineCode).join(" or ")}.`,
"",
- `@${pr.user.login} Please retarget this PR to ${inlineCode(defaultBase)}. All contributions go to ${inlineCode(defaultBase)}; \`main\` receives only release promotions. See our [Contributing guide](https://lidge-jun.github.io/opencodex/contributing/) for details. Thanks! 🙏`
- );
- }
-
- if (failures.some(failure => failure.code === "wrong_ancestry")) {
- sections.push(
- "⚠️ **Wrong branch ancestry**",
- "",
- `This pull request targets ${inlineCode(pr.base.ref)}, but its head appears to sit on the current ${inlineCode("main")} tip while being far behind ${inlineCode(pr.base.ref)}.`,
- "",
- `@${pr.user.login} Rebase onto the current ${inlineCode(pr.base.ref)} branch instead of opening from ${inlineCode("main")}. That keeps already-released commits out of the integration branch.`
+ `@${pr.user.login} Please retarget this PR to ${inlineCode(defaultBase)}. All contributions go to ${inlineCode(defaultBase)}. See our [Contributing guide](https://lidge-jun.github.io/opencodex/contributing/) for details. Thanks! 🙏`
);
}
@@ -244,9 +312,6 @@ function failureSummary(failures, { pr }) {
if (failure.code === "wrong_base") {
return `wrong base (${pr.base.ref})`;
}
- if (failure.code === "wrong_ancestry") {
- return "wrong ancestry";
- }
if (failure.code === "bad_description") {
return `bad description (${failure.reason})`;
}
@@ -323,10 +388,14 @@ module.exports = {
HYGIENE_BLOCK_START,
HYGIENE_BLOCK_END,
inlineCode,
+ escapeControlCharacters,
+ isGateComment,
+ isStandaloneHygieneComment,
readinessChecklistLines,
buildGateCommentBody,
extractHygieneSection,
withHygieneSection,
+ authoritativeHygieneSection,
descriptionFailureLines,
buildFailureSections,
failureSummary,
diff --git a/.github/scripts/pr-quality-messages.test.cjs b/.github/scripts/pr-quality-messages.test.cjs
index c344ce1bc0..ad209ccc32 100644
--- a/.github/scripts/pr-quality-messages.test.cjs
+++ b/.github/scripts/pr-quality-messages.test.cjs
@@ -15,6 +15,10 @@ const {
buildGateCommentBody,
extractHygieneSection,
withHygieneSection,
+ authoritativeHygieneSection,
+ escapeControlCharacters,
+ isGateComment,
+ isStandaloneHygieneComment,
descriptionFailureLines,
buildFailureSections,
failureSummary,
@@ -139,19 +143,17 @@ describe("buildFailureSections", () => {
assert.match(sections, /@contributor Please retarget this PR to `dev`/);
});
- it("builds ancestry, description, and screenshot sections", () => {
+ it("builds description and screenshot sections", () => {
const sections = buildFailureSections(
[
- { code: "wrong_ancestry" },
{ code: "bad_description", reason: "empty" },
{ code: "missing_ui_screenshot" }
],
{ pr: PR, allowedBases: ALLOWED_BASES, defaultBase: DEFAULT_BASE },
).join("\n");
- assert.match(sections, /Wrong branch ancestry/);
assert.match(sections, /Pull request description/);
assert.match(sections, /UI screenshot required/);
- assert.match(sections, /Rebase onto the current `main`/);
+ assert.doesNotMatch(sections, /Wrong branch ancestry/);
});
});
@@ -161,14 +163,13 @@ describe("failureSummary", () => {
failureSummary(
[
{ code: "wrong_base" },
- { code: "wrong_ancestry" },
{ code: "bad_description", reason: "empty" },
{ code: "missing_ui_screenshot" },
{ code: "mystery" }
],
{ pr: PR },
),
- "wrong base (main); wrong ancestry; bad description (empty); missing UI screenshot; mystery",
+ "wrong base (main); bad description (empty); missing UI screenshot; mystery",
);
});
});
@@ -421,3 +422,75 @@ describe("hygiene section round-trip", () => {
assert.equal(afterGateSecond.split(HYGIENE_BLOCK_END).length - 1, 1);
});
});
+
+describe("authoritative hygiene section", () => {
+ const bot = { login: "github-actions[bot]" };
+ const block = (lines) =>
+ `${HYGIENE_BLOCK_START}\n${HYGIENE_MARKER}\n\n${lines.join("\n")}\n\n${HYGIENE_BLOCK_END}`;
+
+ it("reads nothing from a block whose delimiters repeat on whole lines", () => {
+ const body = [GATE_MARKER, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END, "b", HYGIENE_BLOCK_END].join("\n");
+ assert.equal(extractHygieneSection(body), null);
+ const twoStarts = [GATE_MARKER, HYGIENE_BLOCK_START, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END].join("\n");
+ assert.equal(extractHygieneSection(twoStarts), null);
+ });
+
+ it("prefers the gate comment's block over a standalone hygiene comment", () => {
+ const comments = [
+ { user: bot, body: `${HYGIENE_MARKER}\n\nstandalone` },
+ { user: bot, body: `${GATE_MARKER}\n\n${block(["from gate"])}` },
+ ];
+ assert.equal(authoritativeHygieneSection(comments), "from gate");
+ });
+
+ it("falls back to the standalone comment only while the gate comment has no block", () => {
+ const standalone = { user: bot, body: `${HYGIENE_MARKER}\n\nstandalone` };
+ assert.equal(authoritativeHygieneSection([{ user: bot, body: GATE_MARKER }, standalone]), standalone.body);
+ assert.equal(authoritativeHygieneSection([standalone]), standalone.body);
+ const ambiguous = { user: bot, body: [GATE_MARKER, HYGIENE_BLOCK_START, "a", HYGIENE_BLOCK_END, HYGIENE_BLOCK_END].join("\n") };
+ assert.equal(authoritativeHygieneSection([ambiguous, standalone]), null);
+ });
+
+ it("ignores comments not written by the workflow bot", () => {
+ const human = { user: { login: "contributor" }, body: `${GATE_MARKER}\n\n${block(["forged"])}` };
+ assert.equal(authoritativeHygieneSection([human]), null);
+ assert.equal(authoritativeHygieneSection(undefined), null);
+ });
+});
+
+describe("echoed text and comment classification", () => {
+ const bot = { login: "github-actions[bot]" };
+
+ it("escapes control characters so echoed text stays on one line", () => {
+ assert.equal(escapeControlCharacters("src/a.ts"), "src/a.ts");
+ assert.equal(escapeControlCharacters("a\nb\r\tc\u2028"), "a\\u000ab\\u000d\\u0009c\\u2028");
+ assert.ok(!escapeControlCharacters("x\n" + HYGIENE_BLOCK_END).includes("\n"));
+ });
+
+ it("classifies a comment only by the marker its body starts with", () => {
+ assert.equal(isGateComment({ user: bot, body: GATE_MARKER + "\n\nbody" }), true);
+ assert.equal(isGateComment({ user: bot, body: HYGIENE_MARKER + "\n- x " + GATE_MARKER }), false);
+ assert.equal(isGateComment({ user: { login: "someone" }, body: GATE_MARKER }), false);
+ assert.equal(isStandaloneHygieneComment({ user: bot, body: HYGIENE_MARKER + "\n\nok" }), true);
+ assert.equal(isStandaloneHygieneComment({ user: bot, body: GATE_MARKER + "\n" + HYGIENE_MARKER }), false);
+ });
+
+ it("does not read a standalone hygiene comment that echoes the gate marker as the gate block", () => {
+ const standalone = {
+ user: bot,
+ body: [HYGIENE_MARKER, "- x " + GATE_MARKER, HYGIENE_BLOCK_START, "echoed", HYGIENE_BLOCK_END].join("\n"),
+ };
+ assert.equal(authoritativeHygieneSection([standalone]), standalone.body);
+ });
+});
+
+describe("hygiene block replacement", () => {
+ it("writes replacement tokens in hygiene lines literally", () => {
+ const base = withHygieneSection(GATE_MARKER, ["first"]);
+ for (const token of ["$&", "$1", "$`", "$'", "$$"]) {
+ const updated = withHygieneSection(base, ["Paths: src/" + token + ".ts"]);
+ assert.ok(updated.includes("Paths: src/" + token + ".ts"), token);
+ assert.equal(extractHygieneSection(updated), "Paths: src/" + token + ".ts", token);
+ }
+ });
+});
diff --git a/.github/scripts/pr-quality.cjs b/.github/scripts/pr-quality.cjs
index ddee9226bb..edc95afbd8 100644
--- a/.github/scripts/pr-quality.cjs
+++ b/.github/scripts/pr-quality.cjs
@@ -12,9 +12,6 @@ const { READINESS_LATEST_DEV_BEHIND_MAX } = require(
path.join(__dirname, "pr-quality-state.cjs")
);
-const ANCESTRY_BEHIND_THRESHOLD = 20;
-/** Cap on ahead_by vs main so stale `dev` forks (many commits ahead of main) are not flagged. */
-const ANCESTRY_AHEAD_MAIN_MAX = 5;
const MIN_SECTION_LEN = 40;
const MIN_RICH_SECTIONS = 2;
const UNSTRUCTURED_MIN_LEN = 120;
@@ -106,20 +103,6 @@ const MARKDOWN_REFERENCE_DEF_RE = /^\s*\[([^\]]+)\]:\s*\S+/gm;
/** Embedded HTML image with a renderable `src` (``). */
const HTML_IMAGE_RE = /]*\bsrc\s*=\s*(?:"[^"]+"|'[^']+'|[^\s>"']+)[^>]*>/i;
-function isWrongAncestry({
- behindMain,
- behindBase,
- aheadMain = 0,
- threshold = ANCESTRY_BEHIND_THRESHOLD,
- aheadMainMax = ANCESTRY_AHEAD_MAIN_MAX,
-}) {
- return (
- behindMain === 0 &&
- behindBase >= threshold &&
- aheadMain <= aheadMainMax
- );
-}
-
function authorHasPushPermission(permission) {
return permission === "admin" || permission === "maintain" || permission === "write";
}
@@ -528,12 +511,6 @@ function collectPrQualityFailures({
allowedBases,
title = "",
body,
- behindMain,
- behindBase,
- aheadMain = 0,
- authorPermission,
- permissionLookupFailed = false,
- ancestryLookupFailed = false,
/** True when baseRef is another open PR's head (stacked child). */
stackedBase = false,
/** Issue comments; a maintainer comment waives the GUI-screenshot gate. */
@@ -550,21 +527,6 @@ function collectPrQualityFailures({
const wrongBase = !allowedBases.includes(baseRef) && !stackedBase;
if (wrongBase) {
failures.push({ code: "wrong_base" });
- } else {
- // Permission lookup fails closed (still evaluate ancestry). Compare API
- // failures skip ancestry — zeros would falsely pass the #644 heuristic.
- // Stacked children skip ancestry against the integration base; their parent
- // PR is the temporary target.
- const skipAncestry =
- stackedBase ||
- ancestryLookupFailed ||
- (!permissionLookupFailed && authorHasPushPermission(authorPermission));
- if (
- !skipAncestry &&
- isWrongAncestry({ behindMain, behindBase, aheadMain })
- ) {
- failures.push({ code: "wrong_ancestry" });
- }
}
const desc = assessPrDescription(body);
@@ -587,12 +549,9 @@ function collectPrQualityFailures({
}
module.exports = {
- ANCESTRY_BEHIND_THRESHOLD,
- ANCESTRY_AHEAD_MAIN_MAX,
REVIEW_READINESS_ITEMS,
REVIEW_READINESS_START,
REVIEW_READINESS_END,
- isWrongAncestry,
authorHasPushPermission,
assessPrDescription,
guiPathsChanged,
diff --git a/.github/scripts/pr-quality.test.cjs b/.github/scripts/pr-quality.test.cjs
index 996e5b0867..b4287bfeb0 100644
--- a/.github/scripts/pr-quality.test.cjs
+++ b/.github/scripts/pr-quality.test.cjs
@@ -3,9 +3,7 @@
const { describe, it } = require("node:test");
const assert = require("node:assert/strict");
const {
- ANCESTRY_BEHIND_THRESHOLD,
REVIEW_READINESS_ITEMS,
- isWrongAncestry,
authorHasPushPermission,
assessPrDescription,
hasGuiCue,
@@ -25,32 +23,6 @@ const {
collectPrQualityFailures,
} = require("./pr-quality.cjs");
-describe("isWrongAncestry", () => {
- it("flags #644-shaped compares (0 behind main, far behind base, few ahead of main)", () => {
- assert.equal(
- isWrongAncestry({ behindMain: 0, behindBase: 44, aheadMain: 1 }),
- true,
- );
- });
-
- it("uses threshold 20 by default", () => {
- assert.equal(ANCESTRY_BEHIND_THRESHOLD, 20);
- assert.equal(isWrongAncestry({ behindMain: 0, behindBase: 20, aheadMain: 1 }), true);
- assert.equal(isWrongAncestry({ behindMain: 0, behindBase: 19, aheadMain: 1 }), false);
- });
-
- it("passes when head is behind main (not sitting on main tip)", () => {
- assert.equal(isWrongAncestry({ behindMain: 1, behindBase: 44, aheadMain: 1 }), false);
- });
-
- it("passes stale dev-based branches that are many commits ahead of main", () => {
- assert.equal(
- isWrongAncestry({ behindMain: 0, behindBase: 44, aheadMain: 50 }),
- false,
- );
- });
-});
-
describe("authorHasPushPermission", () => {
it("accepts write/maintain/admin only", () => {
assert.equal(authorHasPushPermission("admin"), true);
@@ -680,12 +652,8 @@ describe("collectPrQualityFailures", () => {
baseRef: "main",
allowedBases: allowed,
body: "## Summary\n" + "x".repeat(50) + "\n\n## Test plan\n" + "y".repeat(50),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
});
assert.ok(failures.some((f) => f.code === "wrong_base"));
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
});
it("reports wrong_base and bad_description together for main + empty body", () => {
@@ -693,16 +661,16 @@ describe("collectPrQualityFailures", () => {
baseRef: "main",
allowedBases: allowed,
body: "",
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
});
assert.ok(failures.some((f) => f.code === "wrong_base"));
assert.ok(failures.some((f) => f.code === "bad_description"));
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
});
- it("reports wrong_ancestry for contributor on #644-shaped compare", () => {
+ it("no longer fails a contributor for sitting on the deleted main tip", () => {
+ // The old `main...head` heuristic flagged a head that was level with
+ // `main` but far behind `dev`. `main` no longer exists, so there is no tip
+ // to compare against and no ancestry failure to raise. Being far behind
+ // `dev` is handled by the review-readiness latest-dev claim instead.
const failures = collectPrQualityFailures({
baseRef: "dev",
allowedBases: allowed,
@@ -714,91 +682,17 @@ describe("collectPrQualityFailures", () => {
"- Launch the tray app after setting CODEX_HOME",
"- Confirm the listener and launcher use the same workspace root",
].join("\n"),
- behindMain: 0,
- behindBase: 44,
- aheadMain: 1,
- authorPermission: "read",
});
- assert.deepEqual(
- failures.map((f) => f.code),
- ["wrong_ancestry"],
- );
+ assert.deepEqual(failures, []);
});
- it("skips ancestry for push permission but still flags bad description", () => {
+ it("still flags a bad description for a contributor head", () => {
const failures = collectPrQualityFailures({
baseRef: "dev",
allowedBases: allowed,
body: "",
- behindMain: 0,
- behindBase: 44,
- aheadMain: 1,
- authorPermission: "write",
- });
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
- assert.ok(failures.some((f) => f.code === "bad_description"));
- });
-
- it("applies ancestry when permission lookup failed (fail closed)", () => {
- const failures = collectPrQualityFailures({
- baseRef: "dev",
- allowedBases: allowed,
- body: [
- "## Summary",
- "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.",
- "",
- "## Test plan",
- "- Launch the tray app after setting CODEX_HOME",
- "- Confirm the listener and launcher use the same workspace root",
- ].join("\n"),
- behindMain: 0,
- behindBase: 44,
- aheadMain: 1,
- authorPermission: null,
- permissionLookupFailed: true,
- });
- assert.ok(failures.some((f) => f.code === "wrong_ancestry"));
- });
-
- it("does not flag stale dev-based branches that are far ahead of main", () => {
- const failures = collectPrQualityFailures({
- baseRef: "dev",
- allowedBases: allowed,
- body: [
- "## Summary",
- "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.",
- "",
- "## Test plan",
- "- Launch the tray app after setting CODEX_HOME",
- "- Confirm the listener and launcher use the same workspace root",
- ].join("\n"),
- behindMain: 0,
- behindBase: 44,
- aheadMain: 50,
- authorPermission: "read",
- });
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
- });
-
- it("skips ancestry when compare lookup failed (cannot evaluate)", () => {
- const failures = collectPrQualityFailures({
- baseRef: "dev",
- allowedBases: allowed,
- body: [
- "## Summary",
- "This change updates the Windows tray launcher so it resolves CODEX_HOME through the shared helper instead of a hardcoded path.",
- "",
- "## Test plan",
- "- Launch the tray app after setting CODEX_HOME",
- "- Confirm the listener and launcher use the same workspace root",
- ].join("\n"),
- behindMain: 0,
- behindBase: 0,
- aheadMain: 0,
- authorPermission: "read",
- ancestryLookupFailed: true,
});
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
+ assert.deepEqual(failures.map((f) => f.code), ["bad_description"]);
});
it("skips wrong_base when stackedBase is set", () => {
@@ -813,14 +707,9 @@ describe("collectPrQualityFailures", () => {
"- Launch the tray app after setting CODEX_HOME",
"- Confirm the listener and launcher use the same workspace root",
].join("\n"),
- behindMain: 0,
- behindBase: 44,
- aheadMain: 1,
- authorPermission: "read",
stackedBase: true,
});
assert.ok(!failures.some((f) => f.code === "wrong_base"));
- assert.ok(!failures.some((f) => f.code === "wrong_ancestry"));
});
it("still flags wrong_base for non-allow-list bases without stackedBase", () => {
@@ -828,9 +717,6 @@ describe("collectPrQualityFailures", () => {
baseRef: "main",
allowedBases: allowed,
body: "fix stuff",
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
stackedBase: false,
});
assert.ok(failures.some((f) => f.code === "wrong_base"));
@@ -842,9 +728,6 @@ describe("collectPrQualityFailures", () => {
allowedBases: allowed,
title: "Fix dashboard spacing",
body: richBody,
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
});
assert.ok(failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -856,9 +739,6 @@ describe("collectPrQualityFailures", () => {
allowedBases: allowed,
title: "GUI: fix provider list spacing",
body: richBody,
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["scripts/foo.ts"],
});
assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -871,9 +751,6 @@ describe("collectPrQualityFailures", () => {
allowedBases: allowed,
title: "Large refactor",
body: richBody,
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: truncatedPaths,
filesTruncated: true,
});
@@ -888,9 +765,6 @@ describe("collectPrQualityFailures", () => {
allowedBases: allowed,
title: "Large refactor with gui tweak",
body: richBody,
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: truncatedPaths,
filesTruncated: true,
});
@@ -909,9 +783,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["scripts/foo.ts"],
});
assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -929,9 +800,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/styles.css"],
});
assert.ok(failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -949,9 +817,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
guiOverrideComments: [
{ author_association: "OWNER", body: "no gui changes here" },
@@ -972,9 +837,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
guiOverrideComments: [
{ author_association: "CONTRIBUTOR", body: "no gui changes here" },
@@ -997,9 +859,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
});
assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -1021,9 +880,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
});
assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -1045,9 +901,6 @@ describe("collectPrQualityFailures", () => {
"## Test plan",
"- Ran bun test tests/ci-workflows/ci-workflows.test.ts",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
changedFilePaths: ["gui/src/App.tsx"],
});
assert.ok(failures.some((f) => f.code === "missing_ui_screenshot"));
@@ -1071,9 +924,6 @@ describe("collectPrQualityFailures", () => {
"- [ ] Docs or release notes were updated when needed.",
"- [ ] Security-sensitive changes were reviewed for secrets, auth, and unsafe defaults.",
].join("\n"),
- behindMain: 0,
- behindBase: 0,
- authorPermission: "read",
});
assert.ok(!failures.some((f) => f.code === "missing_ui_screenshot"));
});
diff --git a/.github/scripts/release-dispatch-guard.cjs b/.github/scripts/release-dispatch-guard.cjs
index 507cd3e787..5350419523 100644
--- a/.github/scripts/release-dispatch-guard.cjs
+++ b/.github/scripts/release-dispatch-guard.cjs
@@ -1,44 +1,22 @@
"use strict";
-const ALLOWED_RELEASE_REFS = new Set([
- "refs/heads/main",
- "refs/heads/preview",
-]);
+const ALLOWED_RELEASE_REFS = new Set(["refs/heads/dev"]);
+const FULL_SHA = /^[0-9a-f]{40}$/;
-function validateReleaseDispatch({
- eventName,
- ref,
- expectedSha,
- actualSha,
-}) {
+function validateReleaseDispatch({ eventName, ref, sourceSha, workflowSha, expectedSha, actualSha }) {
if (eventName !== "workflow_dispatch") {
return `Release must be triggered by workflow_dispatch; got ${eventName || "(empty)"}.`;
}
-
if (!ALLOWED_RELEASE_REFS.has(ref)) {
- return `Release must run from main or preview; got ${ref || "(empty)"}.`;
- }
-
- if (!expectedSha) {
- return "expected-sha is required; refusing to publish without an audited commit.";
- }
-
- if (!/^[0-9a-f]{40}$/.test(expectedSha)) {
- return `expected-sha must be a full 40-character commit SHA; got ${expectedSha}.`;
- }
-
- if (actualSha !== expectedSha) {
- return (
- `branch moved after the release audit ` +
- `(expected ${expectedSha}, got ${actualSha || "(empty)"}) — ` +
- "refusing to publish an unaudited commit."
- );
+ return `Release must run from dev; got ${ref || "(empty)"}.`;
}
-
+ // Accept the old parameter names while callers migrate; the source is independently
+ // validated by release-evidence, not compared with the workflow revision.
+ const source = sourceSha ?? expectedSha ?? "";
+ const workflow = workflowSha ?? actualSha ?? "";
+ if (source && !FULL_SHA.test(source)) return "source-sha must be a full 40-character commit SHA.";
+ if (!FULL_SHA.test(workflow)) return "workflow SHA must be a full 40-character commit SHA.";
return null;
}
-module.exports = {
- ALLOWED_RELEASE_REFS,
- validateReleaseDispatch,
-};
+module.exports = { ALLOWED_RELEASE_REFS, validateReleaseDispatch };
diff --git a/.github/scripts/release-dispatch-guard.test.cjs b/.github/scripts/release-dispatch-guard.test.cjs
index 7833ca0976..d1b1382b2f 100644
--- a/.github/scripts/release-dispatch-guard.test.cjs
+++ b/.github/scripts/release-dispatch-guard.test.cjs
@@ -4,63 +4,50 @@ const { describe, it } = require("node:test");
const assert = require("node:assert/strict");
const { validateReleaseDispatch } = require("./release-dispatch-guard.cjs");
-const SHA = "0123456789abcdef0123456789abcdef01234567";
-const OTHER_SHA = "89abcdef0123456789abcdef0123456789abcdef";
+const SOURCE_SHA = "0123456789abcdef0123456789abcdef01234567";
+const WORKFLOW_SHA = "89abcdef0123456789abcdef0123456789abcdef";
function validate(overrides = {}) {
return validateReleaseDispatch({
eventName: "workflow_dispatch",
- ref: "refs/heads/main",
- expectedSha: SHA,
- actualSha: SHA,
+ ref: "refs/heads/dev",
+ sourceSha: SOURCE_SHA,
+ workflowSha: WORKFLOW_SHA,
...overrides,
});
}
describe("release dispatch guard", () => {
- it("accepts an exact audited SHA on main", () => {
+ it("accepts a source distinct from the trusted workflow revision", () => {
+ assert.notEqual(SOURCE_SHA, WORKFLOW_SHA);
assert.equal(validate(), null);
});
- it("accepts an exact audited SHA on preview", () => {
- assert.equal(
- validate({ ref: "refs/heads/preview" }),
- null,
- );
+ it("allows an omitted source for subsequent evidence resolution", () => {
+ assert.equal(validate({ sourceSha: "" }), null);
});
- it("rejects non-workflow_dispatch events", () => {
- assert.match(
- validate({ eventName: "push" }),
- /must be triggered by workflow_dispatch/,
- );
+ it("rejects non-dispatch events", () => {
+ for (const eventName of ["push", "pull_request", "", undefined]) {
+ assert.match(validate({ eventName }), /must be triggered by workflow_dispatch/);
+ }
});
- it("rejects release dispatches from unapproved refs", () => {
- assert.match(
- validate({ ref: "refs/heads/dev" }),
- /must run from main or preview/,
- );
+ it("rejects every non-dev ref", () => {
+ for (const ref of ["refs/heads/main", "refs/heads/preview", "refs/heads/feature", "refs/tags/dev", "dev", "", undefined]) {
+ assert.match(validate({ ref }), /must run from dev/);
+ }
});
- it("requires expected-sha", () => {
- assert.match(
- validate({ expectedSha: "" }),
- /expected-sha is required/,
- );
+ it("rejects malformed nonempty source SHAs", () => {
+ for (const sourceSha of ["0123456", "A".repeat(40), "g".repeat(40), "a".repeat(41), ` ${SOURCE_SHA}`]) {
+ assert.match(validate({ sourceSha }), /source-sha must be a full 40-character commit SHA/);
+ }
});
- it("requires a full 40-character commit SHA", () => {
- assert.match(
- validate({ expectedSha: "0123456" }),
- /full 40-character commit SHA/,
- );
- });
-
- it("rejects when the selected ref moved after audit", () => {
- assert.match(
- validate({ actualSha: OTHER_SHA }),
- /branch moved after the release audit/,
- );
+ it("requires a valid full workflow SHA even when source is omitted", () => {
+ for (const workflowSha of ["", undefined, "0123456", "A".repeat(40), "g".repeat(40), "a".repeat(41)]) {
+ assert.match(validate({ sourceSha: "", workflowSha }), /workflow SHA must be a full 40-character commit SHA/);
+ }
});
});
diff --git a/.github/scripts/release-evidence-policy.json b/.github/scripts/release-evidence-policy.json
new file mode 100644
index 0000000000..835a8e15a4
--- /dev/null
+++ b/.github/scripts/release-evidence-policy.json
@@ -0,0 +1,306 @@
+[
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "b9c739e5d80e915d20bf776b1c698d92a0f01464",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "ce462107c70c4d1d33b1a88169bcaf07a2bc380a",
+ ".github/scripts/release-evidence.test.cjs": "a05e126ee2c17f00f1f4fb06c84eae2655aa1576",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "5cef76e77d391873e35012b3e9318c3d54e86da5",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "4ecdd6ea059794e424372f6afc0eb850f32061f4",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "service",
+ "version": 1,
+ "files": {
+ ".github/workflows/service-lifecycle.yml": "496319bee65c1030cf7905406b85fb9e716a22d5",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "a53d40c6d971bba9a33c546f242c78b0f7695680",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "4ecdd6ea059794e424372f6afc0eb850f32061f4",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "562e63d6bd140944d8c6ba808010913463c75826",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "4d1d82f1d26d95d2448b1269dde1b7b14b73455e",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "750ea21e5668aa512a83aa5a7f8cd7bc5cbd79db",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "service",
+ "version": 1,
+ "files": {
+ ".github/workflows/service-lifecycle.yml": "87249bf4d19ce47a6eafa59703fd8e52453cc924",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "5ee31b6bd6cada6ab7d806ea03dd0d8e46fe1d29",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "0c7b8eeac35a5f09414d1b77185733b5936c594f",
+ "scripts/ci/test-durations.windows.tsv": "18c65823d855bb592cdd59bd102399bd9ead3967",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ },
+ {
+ "kind": "ci",
+ "version": 1,
+ "files": {
+ ".github/workflows/ci.yml": "dc5496ad7e6a146a94fbe8dfeaa3b73461feafbc",
+ ".github/actions/setup-project-bun/action.yml": "cf28f6f9d4385d69784f4e3610914f6952ce789d",
+ ".github/scripts/release-evidence.cjs": "c4cd8c762abbfc1c0674937535c5a36b9cf705fd",
+ ".github/scripts/release-evidence.test.cjs": "de30ad37105cf0e7dd8c538efb5ee1cfafe02990",
+ "scripts/ci/select-test-lane.sh": "b25836cb55f962d1ffd9e68ed00f45f8b45becc8",
+ "scripts/ci/windows-sensitive-diff.sh": "03495f256c671aff57e750febffe19ca7face6a1",
+ "scripts/ci/run-bun-test-batches.sh": "f8aa18e80aff1c95c584cd2c879dfbb6806c11fb",
+ "scripts/ci/bun-crash-signatures.sh": "d34662ddd07864d97bed909135095db33fe42c9e",
+ "scripts/ci/bun-install-frozen.sh": "e6d7bc3aec044e12297c7c4c04015a33df0eb22b",
+ "scripts/ci/docker-smoke.ts": "a8424f93986a31625a0a236cdab5667db67b3405",
+ "scripts/ci/test-durations.tsv": "6ff82545debbd95286928a7a99abfdeb10020a7a",
+ "scripts/ci/test-durations.windows.tsv": "18c65823d855bb592cdd59bd102399bd9ead3967",
+ "scripts/test.ts": "363bf072c4b689478fdbb76a61bf4eadbc054548",
+ "scripts/lib/test-runner-bun.ts": "8763806104a851dbdefeea8cffe8d7dd8d1c8da1",
+ "scripts/test-temp-lock.ts": "ee83fb254b728de119028f52b9894bf52d7aea15",
+ "scripts/ci/run-changed-tests.sh": "9a54d3a5db9849bcbe0dd766954a840185419fa5",
+ "scripts/keyring-smoke.ts": "cd3be07ad57796172696dfa053ea1fb129f29365",
+ "scripts/privacy-scan.ts": "86314e891b45e49739b94c76cddd9e4cc2d4340f",
+ "scripts/structure-ssot.ts": "40ba68401df9b77156afed66d6a11c61df8e9a41",
+ "scripts/generate-ocx-skill-surface.ts": "155e866656ba2d71e8fd48adda857451caf16322",
+ "desktop/scripts/prepare-sidecar.ts": "20f7eec61f73635ea681e25f13dd850b62bb41e2",
+ "desktop/scripts/build-widget.sh": "38e0eb9d713804b603aa75c32383aa18ef01d06c",
+ "desktop/scripts/verify-macos-runtime.sh": "43f1a31375c6f6fe7dcafb9d96c231b98d1f6ba4",
+ "desktop/scripts/verify-linux-sidecar.sh": "c502bb5c8ba8346c722a8f5274f2274bb325a934",
+ "desktop/scripts/appimage-patchelf.py": "63e78ef74160bc48fbcdd882065f1d416db6d13c",
+ "desktop/scripts/linux-packaged-e2e.ts": "9ca92352668ff881c85caea44a9b4747bedc7e2d"
+ }
+ }
+]
diff --git a/.github/scripts/release-evidence.cjs b/.github/scripts/release-evidence.cjs
new file mode 100644
index 0000000000..c4cd8c762a
--- /dev/null
+++ b/.github/scripts/release-evidence.cjs
@@ -0,0 +1,364 @@
+'use strict';
+
+// Policy is loaded from the trusted release workflow revision, not the candidate.
+// It pins the workflow, local setup action and enumerated CI job/test-selection
+// helpers; it does not pin the candidate's whole source tree or every transitive
+// test/build dependency. Those inputs, package scripts and repository writers are
+// trusted through normal dev review. This is not a defence against a writer who
+// can change trusted policy. Security review must assess that boundary separately.
+// After reviewing an intentional policy-path change, update its Git blob ID in
+// release-evidence-policy.json with `git hash-object --no-filters `, then
+// run `node .github/scripts/release-evidence.cjs policy-check` and the evidence
+// tests. Retain old approved entries if historical revisions must remain usable.
+const APPROVED_POLICIES = require('./release-evidence-policy.json');
+const { execFileSync } = require('node:child_process');
+const { readFileSync } = require('node:fs');
+const { createHash } = require('node:crypto');
+const { resolve } = require('node:path');
+const REPOSITORY_ID = 1273824907;
+const FULL_SHA = /^[0-9a-f]{40}$/;
+const CI_JOBS = Object.freeze([
+ 'changes', 'select windows runner', 'storage policy', 'api usage', 'gates',
+ ...Array.from({length: 5}, (_, i) => `test ${i + 1}/5`),
+ ...Array.from({length: 4}, (_, i) => `macos ${i + 1}/4`),
+ 'macos control', ...Array.from({length: 11}, (_, i) => `windows ${i + 1}/11`),
+ 'keyring ubuntu', 'keyring windows', 'keyring macos', 'docker smoke',
+ 'docs site build', 'structure gate', 'macos widget + bundle', 'desktop shell',
+ ...['ubuntu-latest', 'windows-latest', 'macos-latest'].flatMap(os => [
+ `setup action ${os}`, `remote helper ${os}`, `npm-global ${os}`,
+ ]), 'ci',
+]);
+
+function sha(value) {
+ if (typeof value !== 'string' || !FULL_SHA.test(value)) throw new Error('expected full lowercase commit SHA');
+ return value;
+}
+function serviceJobs(sourceSha) {
+ sha(sourceSha);
+ return ['validate source', ...['linux-systemd', 'macos-launchd', 'windows-schtasks'].map(n => `${n} ${sourceSha}`)];
+}
+function validateJobs(jobs, required) {
+ if (!Array.isArray(jobs)) throw new Error('invalid jobs response');
+ const seen = new Set();
+ for (const job of jobs) {
+ if (!job || typeof job.name !== 'string' || seen.has(job.name)) throw new Error('duplicate or malformed job');
+ seen.add(job.name);
+ }
+ for (const name of required) {
+ const job = jobs.find(j => j.name === name);
+ if (!job || job.status !== 'completed' || job.conclusion !== 'success') throw new Error(`missing or unsuccessful job: ${name}`);
+ }
+ return true;
+}
+function apiClient(repository, token) {
+ if (repository !== 'lidge-jun/opencodex' || typeof token !== 'string' || !token) throw new Error('expected GH_TOKEN and GITHUB_REPOSITORY=lidge-jun/opencodex');
+ const prefix = `https://api.github.com/repos/${repository}`;
+ return async path => {
+ if (path !== '' && (!path.startsWith('/') || path.startsWith('//'))) throw new Error('invalid API path');
+ const response = await fetch(prefix + path, {
+ headers: { Authorization: `Bearer ${token}`, Accept: 'application/vnd.github+json', 'X-GitHub-Api-Version': '2022-11-28' },
+ redirect: 'error',
+ });
+ if (!response.ok) throw new Error(`GitHub API request failed (${response.status})`);
+ return response.json();
+ };
+}
+async function pages(api, path, key, maxTotal = 1000) {
+ const collected = [];
+ let total;
+ for (let page = 1; ; page++) {
+ const data = await api(`${path}${path.includes('?') ? '&' : '?'}per_page=100&page=${page}`);
+ if (!data || !Number.isSafeInteger(data.total_count) || data.total_count < 0 || !Array.isArray(data[key]) || data[key].length > 100) throw new Error('invalid paginated response');
+ if (total === undefined) total = data.total_count;
+ if (total !== data.total_count) throw new Error('pagination changed during lookup');
+ if (total > maxTotal) throw new Error('pagination coverage exceeds the safe limit');
+ if (data[key].length !== Math.min(100, total - collected.length)) throw new Error('incomplete pagination');
+ collected.push(...data[key]);
+ if (collected.length === total) return collected;
+ if (!data[key].length || collected.length > total) throw new Error('incomplete pagination');
+ }
+}
+async function treeEntry(api, commitSha, pathname) {
+ const commit = await api(`/git/commits/${sha(commitSha)}`);
+ let tree = commit?.tree?.sha;
+ if (!FULL_SHA.test(tree || '')) throw new Error('invalid commit tree');
+ const parts = pathname.split('/');
+ for (let i = 0; i < parts.length; i++) {
+ const data = await api(`/git/trees/${tree}`);
+ if (data.truncated || !Array.isArray(data.tree)) throw new Error('incomplete tree');
+ const matches = data.tree.filter(entry => entry.path === parts[i]);
+ if (matches.length !== 1 || !FULL_SHA.test(matches[0].sha || '')) throw new Error('missing policy path');
+ if (i === parts.length - 1) return matches[0];
+ if (matches[0].type !== 'tree') throw new Error('invalid policy path');
+ tree = matches[0].sha;
+ }
+ throw new Error('invalid policy path');
+}
+async function assertPolicy(api, run, kind, policies) {
+ const candidates = policies.filter(p => p.kind === kind && p.version === 1 && p.files && typeof p.files === 'object');
+ const workflowPath = `.github/workflows/${kind === 'ci' ? 'ci.yml' : 'service-lifecycle.yml'}`;
+ for (const policy of candidates) {
+ if (!Object.hasOwn(policy.files, workflowPath)) continue;
+ let matches = true;
+ for (const [path, expected] of Object.entries(policy.files)) {
+ let entry;
+ try { entry = await treeEntry(api, run.head_sha, path); }
+ catch (error) {
+ if (error.message === 'missing policy path') { matches = false; break; }
+ throw error;
+ }
+ if (!FULL_SHA.test(expected) || entry.type !== 'blob' || !['100644', '100755'].includes(entry.mode) || entry.sha !== expected) { matches = false; break; }
+ }
+ if (matches) return;
+ }
+ throw new Error(`unapproved ${kind} workflow or helper policy`);
+}
+const SERVICE_PATH = /^(?:src\/service\.ts|src\/service\/.+|desktop\/.+|src\/cli\.ts|src\/cli\/index\.ts|src\/lib\/bun-runtime\.ts|package\.json|bun\.lock|\.github\/workflows\/service-lifecycle\.yml|\.github\/workflows\/release\.yml)$/;
+function serviceChangeRequired(paths) {
+ if (!Array.isArray(paths)) throw new Error('expected a list of changed paths');
+ for (const path of paths) {
+ if (typeof path !== 'string' || !path || path.startsWith('/') || path.includes('\0') || path.split('/').some(part => !part || part === '.' || part === '..')) throw new Error('invalid changed path');
+ }
+ return paths.some(path => SERVICE_PATH.test(path));
+}
+function git(args) {
+ try {
+ return execFileSync('git', args, { encoding: 'buffer', maxBuffer: 100 * 1024 * 1024, stdio: ['ignore', 'pipe', 'pipe'] });
+ } catch {
+ throw new Error('git could not verify the requested service range');
+ }
+}
+function serviceRange(candidate, baseline) {
+ sha(candidate);
+ if (baseline !== '--initial') sha(baseline);
+ for (const commit of baseline === '--initial' ? [candidate] : [candidate, baseline]) {
+ if (git(['cat-file', '-t', commit]).toString('utf8').trim() !== 'commit') throw new Error('service range requires commit objects');
+ }
+ const output = baseline === '--initial'
+ ? git(['ls-tree', '-r', '-z', '--name-only', '--full-tree', candidate])
+ : (git(['merge-base', '--is-ancestor', baseline, candidate]), git(['diff', '--name-only', '-z', '--no-ext-diff', '--no-renames', baseline, candidate, '--']));
+ let decoded;
+ try { decoded = new TextDecoder('utf-8', {fatal:true}).decode(output); }
+ catch { throw new Error('service range contains a non-UTF-8 path'); }
+ if (decoded && !decoded.endsWith('\0')) throw new Error('incomplete service range');
+ return {required: serviceChangeRequired(decoded ? decoded.slice(0, -1).split('\0') : [])};
+}
+function checkPolicyFiles(policies, root) {
+ const current = new Map(policies.map(policy => [policy.kind, policy]));
+ for (const kind of ['ci', 'service']) if (!current.has(kind)) throw new Error(`missing ${kind} evidence policy`);
+ for (const policy of current.values()) {
+ for (const [name, expected] of Object.entries(policy.files)) {
+ const bytes = readFileSync(resolve(root, name));
+ const actual = createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
+ if (actual !== expected) throw new Error(`policy fingerprint mismatch: ${name}`);
+ }
+ }
+ return true;
+}
+function validateRun(run, workflow, kind, sourceSha) {
+ if (!run || !Number.isSafeInteger(run.id) || run.id <= 0 || !Number.isSafeInteger(run.run_attempt) || run.run_attempt < 1 ||
+ run.workflow_id !== workflow.id || run.repository?.id !== REPOSITORY_ID || run.head_repository?.id !== REPOSITORY_ID ||
+ run.event !== 'workflow_dispatch' || run.head_branch !== 'dev' || run.status !== 'completed' || run.conclusion !== 'success') {
+ throw new Error('unqualified run metadata');
+ }
+ sha(run.head_sha);
+ if (kind === 'ci' && (run.head_sha !== sourceSha || run.display_title !== `ocx-ci-v1 lane=all sha=${sourceSha}`)) throw new Error('CI lane or source mismatch');
+}
+async function ancestor(api, base, head) {
+ sha(base); sha(head);
+ const data = await api(`/compare/${base}...${head}`);
+ if (!['ahead', 'behind', 'identical', 'diverged'].includes(data?.status)) throw new Error('invalid comparison');
+ return data.status === 'ahead' || data.status === 'identical';
+}
+// GitHub limits filtered workflow searches to 1,000 results. Discovery may
+// inspect at most those 1,000; exact-SHA lists must fit completely in that cap.
+// The compare bound and global request budget make failure explicit when a
+// candidate is too old to prove newest within the available API budget.
+const MAX_COMPARE_COMMITS = 200;
+const MAX_API_REQUESTS = 800;
+function createEvidence(rawApi, policies = APPROVED_POLICIES) {
+ let requestCount = 0;
+ const api = async path => {
+ if (++requestCount > MAX_API_REQUESTS) throw new Error('GitHub API request budget exceeded');
+ return rawApi(path);
+ };
+ const objects = new Map();
+ const comparisons = new Map();
+ async function policyApi(path) {
+ if (!/^\/git\/(?:commits|trees)\/[0-9a-f]{40}$/.test(path)) return api(path);
+ if (!objects.has(path)) objects.set(path, api(path).catch(error => { objects.delete(path); throw error; }));
+ return objects.get(path);
+ }
+ async function isAncestor(base, head) {
+ sha(base); sha(head);
+ if (base === head) return true;
+ const key = `${base}...${head}`;
+ if (!comparisons.has(key)) comparisons.set(key, ancestor(api, base, head));
+ return comparisons.get(key);
+ }
+ async function workflow(kind) {
+ const filename = kind === 'ci' ? 'ci.yml' : 'service-lifecycle.yml';
+ const [repo, wf] = await Promise.all([api(''), api(`/actions/workflows/${filename}`)]);
+ if (repo?.id !== REPOSITORY_ID || repo.full_name !== 'lidge-jun/opencodex' || wf?.path !== `.github/workflows/${filename}` || !Number.isSafeInteger(wf.id)) throw new Error('repository or workflow identity mismatch');
+ return wf;
+ }
+ async function eligible(run, wf, kind, sourceSha) {
+ validateRun(run, wf, kind, sourceSha);
+ await assertPolicy(policyApi, run, kind, policies);
+ const jobs = await pages(api, `/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs`, 'jobs');
+ validateJobs(jobs, kind === 'ci' ? CI_JOBS : serviceJobs(sourceSha));
+ }
+ async function qualifies(run, wf, kind, candidate, dev) {
+ try {
+ await eligible(run, wf, kind, candidate);
+ } catch (error) {
+ // API, pagination, resource limits and unknown errors are never evidence
+ // that a run is ineligible; stop instead of skipping them.
+ if (/^(unqualified run metadata|CI lane or source mismatch|unapproved .* workflow or helper policy|missing or unsuccessful job:|duplicate or malformed job|expected full lowercase commit SHA)/.test(error.message)) return false;
+ throw error;
+ }
+ return isAncestor(run.head_sha, dev);
+ }
+ function listPath(wf, head) {
+ const query = new URLSearchParams({event:'workflow_dispatch', branch:'dev', status:'success'});
+ if (head) query.set('head_sha', sha(head));
+ return `/actions/workflows/${wf.id}/runs?${query}`;
+ }
+ function signature(runs) {
+ const ids = new Set();
+ return JSON.stringify(runs.map(run => {
+ if (!run || !Number.isSafeInteger(run.id) || run.id <= 0 || ids.has(run.id)) throw new Error('duplicate or malformed run');
+ ids.add(run.id);
+ return [run.id,run.run_attempt,run.status,run.conclusion,run.head_sha,run.head_branch,run.event,run.workflow_id,run.repository?.id,run.head_repository?.id,run.display_title];
+ }));
+ }
+ const snapshots = [];
+ async function exactRuns(wf, head) {
+ const path = listPath(wf, head);
+ const runs = await pages(api, path, 'workflow_runs');
+ const stamp = signature(runs);
+ snapshots.push(async () => {
+ if (signature(await pages(api, path, 'workflow_runs')) !== stamp) throw new Error('run pagination changed during lookup');
+ });
+ return runs;
+ }
+ async function findEligible(runs, wf, kind, source, dev) {
+ for (const run of runs) {
+ const candidate = kind === 'ci' ? run.head_sha : source;
+ if (!FULL_SHA.test(candidate || '') || (kind === 'ci' && source && candidate !== source)) continue;
+ if (await qualifies(run, wf, kind, candidate, dev) && await isAncestor(candidate, dev)) return {sourceSha:candidate,ciRunId:run.id};
+ }
+ return undefined;
+ }
+ async function discover(wf, dev) {
+ const path = listPath(wf);
+ const observed = [];
+ let total;
+ for (let page = 1; page <= 10; page++) {
+ const data = await api(`${path}&per_page=100&page=${page}`);
+ if (!data || !Number.isSafeInteger(data.total_count) || data.total_count < 0 || !Array.isArray(data.workflow_runs)) throw new Error('invalid paginated response');
+ if (total === undefined) total = data.total_count;
+ if (total !== data.total_count) throw new Error('run pagination changed during lookup');
+ const expected = Math.min(100, Math.max(0, total - observed.length));
+ if (data.workflow_runs.length !== expected) throw new Error('incomplete run pagination');
+ observed.push(...data.workflow_runs);
+ signature(observed);
+ const found = await findEligible(data.workflow_runs, wf, 'ci', undefined, dev);
+ if (found) {
+ const count = page, stamp = signature(observed), initialTotal = total;
+ snapshots.push(async () => {
+ const again = [];
+ for (let n = 1; n <= count; n++) {
+ const result = await api(`${path}&per_page=100&page=${n}`);
+ if (result?.total_count !== initialTotal || !Array.isArray(result.workflow_runs)) throw new Error('run pagination changed during lookup');
+ again.push(...result.workflow_runs);
+ }
+ if (signature(again) !== stamp) throw new Error('run pagination changed during lookup');
+ });
+ return found;
+ }
+ if (observed.length === total) throw new Error('no qualifying ci evidence');
+ }
+ throw new Error('run pagination coverage exceeds the safe limit');
+ }
+ async function commitsSince(base, head) {
+ if (base === head) return [];
+ const collected = [], seen = new Set();
+ let total;
+ for (let page = 1; ; page++) {
+ const data = await api(`/compare/${base}...${head}?per_page=100&page=${page}`);
+ if (data?.status !== 'ahead' || !Number.isSafeInteger(data.total_commits) || data.total_commits < 1 || !Array.isArray(data.commits)) throw new Error('invalid commit comparison');
+ if (total === undefined) total = data.total_commits;
+ if (total !== data.total_commits) throw new Error('commit pagination changed during lookup');
+ if (total > MAX_COMPARE_COMMITS) throw new Error('commit comparison coverage exceeds the safe limit');
+ if (data.commits.length !== Math.min(100, total-collected.length)) throw new Error('incomplete commit pagination');
+ for (const commit of data.commits) {
+ const value = sha(commit?.sha);
+ if (value === base || seen.has(value)) throw new Error('duplicate or malformed comparison commit');
+ seen.add(value); collected.push(value);
+ }
+ if (collected.length === total) {
+ if (!seen.has(head)) throw new Error('incomplete commit comparison');
+ return collected;
+ }
+ }
+ }
+ async function select(kind, sourceSha) {
+ if (!['ci','service'].includes(kind)) throw new Error('unknown evidence kind');
+ if (sourceSha !== undefined) sha(sourceSha);
+ if (kind === 'service' && !sourceSha) throw new Error('service requires source SHA');
+ if (!policies.some(policy => policy.kind === kind && policy.version === 1)) throw new Error(`no approved ${kind} evidence policy`);
+ const wf = await workflow(kind);
+ const dev = sha((await api('/commits/dev'))?.sha);
+ if (sourceSha && !await isAncestor(sourceSha, dev)) throw new Error('source is not a dev ancestor');
+ let found;
+ if (sourceSha) {
+ // A service dispatch runs the workflow from dev and may test an older
+ // source; its head_sha is the workflow revision, not the tested source.
+ const runs = await exactRuns(wf, kind === 'ci' ? sourceSha : undefined);
+ found = await findEligible(runs, wf, kind, sourceSha, dev);
+ } else {
+ found = await discover(wf, dev);
+ const candidates = [found];
+ for (const commit of await commitsSince(found.sourceSha, dev)) {
+ const runs = await exactRuns(wf, commit);
+ const candidate = await findEligible(runs, wf, 'ci', commit, dev);
+ if (candidate) candidates.push(candidate);
+ }
+ let newest;
+ for (const candidate of candidates) {
+ let includesAll = true;
+ for (const other of candidates) if (!await isAncestor(other.sourceSha, candidate.sourceSha)) { includesAll = false; break; }
+ if (includesAll) {
+ if (newest && newest.sourceSha !== candidate.sourceSha) throw new Error('ambiguous qualifying sources');
+ newest = candidate;
+ }
+ }
+ if (!newest) throw new Error('ambiguous qualifying sources');
+ found = newest;
+ }
+ if (!found) throw new Error(`no qualifying ${kind} evidence`);
+ for (const confirm of snapshots) await confirm();
+ if (sha((await api('/commits/dev'))?.sha) !== dev) throw new Error('dev changed during evidence lookup');
+ return found;
+ }
+ return { select };
+}
+async function main(args) {
+ if (args[0] === 'service-range' && args.length === 3) {
+ process.stdout.write(`${JSON.stringify(serviceRange(args[1], args[2]))}\n`);
+ return;
+ }
+ if (args[0] === 'policy-check' && args.length === 1) {
+ checkPolicyFiles(APPROVED_POLICIES, resolve(__dirname, '../..'));
+ process.stdout.write('Evidence policy fingerprints match the working tree.\n');
+ return;
+ }
+ if (!['resolve', 'check', 'service'].includes(args[0]) || args.length > 2 || (args[0] !== 'resolve' && args.length !== 2)) throw new Error('usage: release-evidence.cjs resolve [fullSha] | check | service | service-range | policy-check');
+ if (args[1] !== undefined) sha(args[1]);
+ const evidence = createEvidence(apiClient(process.env.GITHUB_REPOSITORY, process.env.GH_TOKEN));
+ const result = await evidence.select(args[0] === 'service' ? 'service' : 'ci', args[1]);
+ if (args[0] === 'resolve') process.stdout.write(`${JSON.stringify(result)}\n`);
+}
+if (require.main === module) main(process.argv.slice(2)).catch(error => { process.stderr.write(`release evidence: ${error.message}\n`); process.exitCode = 1; });
+module.exports = { CI_JOBS, serviceJobs, validateJobs, createEvidence, pages, validateRun, apiClient, serviceChangeRequired, serviceRange, checkPolicyFiles };
diff --git a/.github/scripts/release-evidence.test.cjs b/.github/scripts/release-evidence.test.cjs
new file mode 100644
index 0000000000..de30ad3710
--- /dev/null
+++ b/.github/scripts/release-evidence.test.cjs
@@ -0,0 +1,372 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const path = require('node:path');
+const root = path.resolve(__dirname, '../..');
+const SHA = 'a'.repeat(40);
+
+test('full dispatch fixes path scopes and identifies its lane and SHA', () => {
+ const ci = fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8');
+ assert.match(ci, /run-name:.*ocx-ci-v1.*github\.sha/);
+ for (const scope of ['gui', 'packaging', 'docs', 'structure', 'ci', 'desktop', 'native', 'setup_action', 'remote_helper']) {
+ assert.match(ci, new RegExp(`workflow_dispatch[^\\n]*lane[^\\n]*all[^\\n]*steps\\.filter\\.outputs\\.${scope}`));
+ }
+});
+
+test('CI runs all release and Pages Node contract suites', () => {
+ const ci = fs.readFileSync(path.join(root, '.github/workflows/ci.yml'), 'utf8');
+ const step = ci.split('\n').find(line => line.includes('node --test') && line.includes('release-evidence.test.cjs'));
+ assert.ok(step);
+ for (const suite of ['release-dispatch-guard.test.cjs','release-evidence.test.cjs','release-history.test.cjs','release-resume.test.cjs','deploy-docs.test.cjs']) assert.ok(step.includes(suite), suite);
+});
+
+test('service dispatch validates and binds the same full SHA in each job and checkout', () => {
+ const service = fs.readFileSync(path.join(root, '.github/workflows/service-lifecycle.yml'), 'utf8');
+ assert.match(service, /source_sha:/);
+ assert.match(service, /\[0-9a-f\]\{40\}/);
+ for (const name of ['linux-systemd', 'macos-launchd', 'windows-schtasks']) {
+ assert.ok(service.includes('name: ' + name + ' ${{ github.event.inputs.source_sha'));
+ }
+ assert.equal((service.match(/ref: \$\{\{ github\.event_name == 'workflow_dispatch' && github\.event\.inputs\.source_sha \|\| github\.sha \}\}/g) || []).length, 3);
+});
+
+test('run attempt graph fails on missing, skipped and duplicate legs', () => {
+ const { validateJobs, CI_JOBS } = require('./release-evidence.cjs');
+ const jobs = CI_JOBS.map(name => ({name, status:'completed', conclusion:'success'}));
+ assert.equal(validateJobs(jobs, CI_JOBS), true);
+ assert.throws(() => validateJobs(jobs.slice(1), CI_JOBS));
+ assert.throws(() => validateJobs([...jobs, jobs[0]], CI_JOBS));
+ assert.throws(() => validateJobs(jobs.map((j,i) => i ? j : {...j, conclusion:'skipped'}), CI_JOBS));
+});
+
+test('service graph binds every leg to the exact tested SHA', () => {
+ const { validateJobs, serviceJobs } = require('./release-evidence.cjs');
+ const names = serviceJobs(SHA);
+ const jobs = names.map(name => ({name, status:'completed', conclusion:'success'}));
+ assert.equal(validateJobs(jobs, names), true);
+ assert.throws(() => validateJobs(jobs, serviceJobs('b'.repeat(40))));
+ assert.throws(() => serviceJobs('abc'));
+});
+
+test('authenticated client accepts repository root without allowing alternate hosts', async () => {
+ const { apiClient } = require('./release-evidence.cjs');
+ const original = global.fetch;
+ const requests = [];
+ global.fetch = async (url, options) => { requests.push({url, options}); return {ok:true, json:async () => ({id:1273824907})}; };
+ try {
+ const api = apiClient('lidge-jun/opencodex', 'token');
+ assert.deepEqual(await api(''), {id:1273824907});
+ assert.equal(requests[0].url, 'https://api.github.com/repos/lidge-jun/opencodex');
+ await assert.rejects(api('//example.org'), /invalid API path/);
+ } finally { global.fetch = original; }
+});
+
+test('run identity rejects forged titles, wrong repository, branch, event and attempt', () => {
+ const { validateRun } = require('./release-evidence.cjs');
+ const workflow = {id:42};
+ const run = {id:7, workflow_id:42, repository:{id:1273824907}, head_repository:{id:1273824907}, event:'workflow_dispatch', head_branch:'dev', status:'completed', conclusion:'success', run_attempt:1, head_sha:SHA, display_title:`ocx-ci-v1 lane=all sha=${SHA}`};
+ assert.doesNotThrow(() => validateRun(run, workflow, 'ci', SHA));
+ for (const change of [{event:'push'}, {head_branch:'main'}, {conclusion:'failure'}, {run_attempt:0}, {repository:{id:2}}, {head_repository:{id:2}}, {display_title:`ocx-ci-v1 lane=release-gates sha=${SHA}`}, {display_title:`ocx-ci-v1 lane=windows-native-claim sha=${SHA}`}, {head_sha:'b'.repeat(40)}]) {
+ assert.throws(() => validateRun({...run, ...change}, workflow, 'ci', SHA));
+ }
+});
+
+test('pagination reads all pages and refuses truncated or changing totals', async () => {
+ const { pages } = require('./release-evidence.cjs');
+ const calls = [];
+ const api = async url => { calls.push(url); return url.endsWith('page=1') ? {total_count:101, jobs:Array.from({length:100}, (_,i) => i)} : {total_count:101, jobs:[100]}; };
+ assert.equal((await pages(api, '/runs/1/jobs', 'jobs')).length, 101);
+ assert.equal(calls.length, 2);
+ await assert.rejects(pages(async () => ({total_count:2,jobs:[]}), '/runs/1/jobs', 'jobs'), /incomplete pagination/);
+ await assert.rejects(pages(async url => url.endsWith('page=1') ? {total_count:101,jobs:Array(100).fill(1)} : {total_count:102,jobs:[1,2]}, '/runs/1/jobs', 'jobs'), /pagination changed/);
+});
+
+test('selector authenticates policy and chooses the descendant, independent of run order', async () => {
+ const { createEvidence, CI_JOBS } = require('./release-evidence.cjs');
+ const older = 'b'.repeat(40), newer = 'c'.repeat(40), tree = 'd'.repeat(40), blob = 'e'.repeat(40);
+ const mkRun = (id, head) => ({id, workflow_id:42, repository:{id:1273824907}, head_repository:{id:1273824907}, event:'workflow_dispatch', head_branch:'dev', status:'completed', conclusion:'success', run_attempt:2, head_sha:head, display_title:`ocx-ci-v1 lane=all sha=${head}`});
+ const jobs = CI_JOBS.map(name => ({name, status:'completed', conclusion:'success'}));
+ const calls = [];
+ const api = async url => {
+ calls.push(url);
+ if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'};
+ if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'};
+ if (url === '/commits/dev') return {sha:newer};
+ if (url.startsWith('/compare/')) { const [base,head] = url.slice(9).split('...'); return {status:base === head ? 'identical' : base === older && head === newer ? 'ahead' : 'behind'}; }
+ if (url.startsWith('/actions/workflows/42/runs?')) return {total_count:2,workflow_runs:[mkRun(1,newer),mkRun(2,older)]};
+ if (url.startsWith('/git/commits/')) return {tree:{sha:tree}};
+ if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'ci.yml',type:'blob',mode:'100644',sha:blob}]};
+ if (/^\/actions\/runs\/[12]\/attempts\/2\/jobs\?/.test(url)) return {total_count:jobs.length,jobs};
+ throw new Error(`unexpected API request ${url}`);
+ };
+ const approved = [{kind:'ci',version:1,files:{'.github/workflows/ci.yml':blob}}];
+ assert.deepEqual(await createEvidence(api, approved).select('ci'), {sourceSha:newer,ciRunId:1});
+ assert.deepEqual(await createEvidence(api, approved).select('ci', older), {sourceSha:older,ciRunId:2});
+ const historical = {kind:'ci',version:1,files:{'.github/workflows/absent.yml':blob,'.github/workflows/ci.yml':blob}};
+ assert.deepEqual(await createEvidence(api, [historical, ...approved]).select('ci', older), {sourceSha:older,ciRunId:2});
+ assert.ok(calls.some(url => url.includes('/attempts/2/jobs?')));
+ await assert.rejects(createEvidence(api, [{kind:'ci',version:1,files:{'.github/workflows/ci.yml':'f'.repeat(40)}}]).select('ci'), /no qualifying/);
+ await assert.rejects(createEvidence(api, []).select('ci'), /no approved ci evidence policy/);
+});
+
+test('service uses setup action from the workflow revision rather than the historical candidate', () => {
+ const service = fs.readFileSync(path.join(root, '.github/workflows/service-lifecycle.yml'), 'utf8');
+ assert.equal((service.match(/path: \.evidence-policy/g) || []).length, 3);
+ assert.equal((service.match(/ref: \$\{\{ github\.sha \}\}/g) || []).length, 3);
+ assert.equal((service.match(/uses: \.\/\.evidence-policy\/\.github\/actions\/setup-project-bun/g) || []).length, 3);
+});
+
+test('service evidence uses workflow revision policy and a complete current attempt for the candidate', async () => {
+ const { createEvidence, serviceJobs } = require('./release-evidence.cjs');
+ const revision = 'b'.repeat(40), tree = 'c'.repeat(40), blob = 'd'.repeat(40);
+ const run = {id:9,workflow_id:43,repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion:'success',run_attempt:3,head_sha:revision};
+ let jobs = serviceJobs(SHA).map(name => ({name,status:'completed',conclusion:'success'}));
+ const api = async url => {
+ if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'};
+ if (url === '/actions/workflows/service-lifecycle.yml') return {id:43,path:'.github/workflows/service-lifecycle.yml'};
+ if (url === '/commits/dev') return {sha:revision};
+ if (url.startsWith('/compare/')) return {status:'ahead'};
+ if (url.startsWith('/actions/workflows/43/runs?')) return {total_count:1,workflow_runs:[run]};
+ if (url === `/git/commits/${revision}`) return {tree:{sha:tree}};
+ if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'service-lifecycle.yml',type:'blob',mode:'100644',sha:blob}]};
+ if (url.startsWith('/actions/runs/9/attempts/3/jobs?')) return {total_count:jobs.length,jobs};
+ throw new Error(`unexpected API request ${url}`);
+ };
+ const policy = [{kind:'service',version:1,files:{'.github/workflows/service-lifecycle.yml':blob}}];
+ assert.deepEqual(await createEvidence(api, policy).select('service', SHA), {sourceSha:SHA,ciRunId:9});
+ jobs = jobs.slice(1);
+ await assert.rejects(createEvidence(api, policy).select('service', SHA), /no qualifying/);
+ jobs = serviceJobs('e'.repeat(40)).map(name => ({name,status:'completed',conclusion:'success'}));
+ await assert.rejects(createEvidence(api, policy).select('service', SHA), /no qualifying/);
+});
+
+test('production policy pins the current workflows and job-selection helpers', () => {
+ const { execFileSync } = require('node:child_process');
+ const policies = require('./release-evidence-policy.json');
+ for (const kind of ['ci', 'service']) {
+ const policy = policies.filter(p => p.kind === kind && p.version === 1).at(-1);
+ assert.ok(policy);
+ const required = kind === 'ci' ? ['.github/workflows/ci.yml', '.github/actions/setup-project-bun/action.yml', 'scripts/ci/run-bun-test-batches.sh', 'scripts/ci/select-test-lane.sh', 'scripts/ci/windows-sensitive-diff.sh', 'scripts/test.ts', 'scripts/keyring-smoke.ts', 'desktop/scripts/verify-macos-runtime.sh', 'desktop/scripts/verify-linux-sidecar.sh', 'desktop/scripts/linux-packaged-e2e.ts'] : ['.github/workflows/service-lifecycle.yml', '.github/actions/setup-project-bun/action.yml'];
+ for (const name of required) assert.ok(policy.files[name], name);
+ for (const [name, digest] of Object.entries(policy.files)) {
+ assert.equal(execFileSync('git', ['hash-object', '--no-filters', name], {cwd:root,encoding:'utf8'}).trim(), digest, name);
+ }
+ }
+});
+
+test('service change detection handles initial trees, cumulative changes and deletions', () => {
+ const { serviceChangeRequired } = require('./release-evidence.cjs');
+ assert.equal(serviceChangeRequired(['README.md', 'src/router.ts']), false);
+ for (const file of ['src/service.ts','src/service/daemon.ts','desktop/app/main.rs','src/cli.ts','src/cli/index.ts','src/lib/bun-runtime.ts','package.json','bun.lock','.github/workflows/service-lifecycle.yml','.github/workflows/release.yml']) {
+ assert.equal(serviceChangeRequired(['README.md',file]), true, file);
+ }
+ for (const file of ['src/service-other.ts','src/cli/index.ts.bak','nested/package.json']) assert.equal(serviceChangeRequired([file]), false, file);
+ assert.throws(() => serviceChangeRequired(null));
+ assert.throws(() => serviceChangeRequired(['../src/service.ts']));
+});
+
+test('service range accepts a reachable baseline or an explicit initial tree only', () => {
+ const { execFileSync } = require('node:child_process');
+ const os = require('node:os');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-service-evidence-'));
+ const git = (...args) => execFileSync('git', args, {cwd:dir,encoding:'utf8'}).trim();
+ const script = path.join(root, '.github/scripts/release-evidence.cjs');
+ const run = (...args) => JSON.parse(execFileSync(process.execPath, [script, 'service-range', ...args], {cwd:dir,encoding:'utf8',stdio:['ignore','pipe','pipe']}));
+ try {
+ git('init','-q'); git('config','user.email','fixture@localhost'); git('config','user.name','fixture');
+ fs.mkdirSync(path.join(dir,'src/service'), {recursive:true});
+ fs.writeFileSync(path.join(dir,'src/service/daemon.ts'),'one');
+ git('add','.'); git('commit','-qm','initial'); const initial = git('rev-parse','HEAD');
+ fs.writeFileSync(path.join(dir,'src/service/daemon.ts'),'two');
+ git('add','.'); git('commit','-qm','service');
+ fs.writeFileSync(path.join(dir,'README.md'),'other');
+ git('add','.'); git('commit','-qm','later'); const later = git('rev-parse','HEAD');
+ assert.deepEqual(run(initial,'--initial'), {required:true});
+ assert.deepEqual(run(later,initial), {required:true});
+ assert.deepEqual(run(later,later), {required:false});
+ fs.unlinkSync(path.join(dir,'src/service/daemon.ts'));
+ git('add','-A'); git('commit','-qm','remove service'); const removed = git('rev-parse','HEAD');
+ assert.deepEqual(run(removed,later), {required:true});
+ assert.throws(() => run(initial,later));
+ assert.throws(() => run(later));
+ } finally { fs.rmSync(dir,{recursive:true,force:true}); }
+});
+
+test('policy approval check detects drift while retaining historical policies', () => {
+ const { checkPolicyFiles } = require('./release-evidence.cjs');
+ const { createHash } = require('node:crypto');
+ const os = require('node:os');
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-policy-check-'));
+ try {
+ const content = Buffer.from('reviewed');
+ fs.writeFileSync(path.join(dir, 'file'),content);
+ const digest = createHash('sha1').update(`blob ${content.length}\0`).update(content).digest('hex');
+ const policies = [{kind:'ci',files:{file:'f'.repeat(40)}}, {kind:'ci',files:{file:digest}}, {kind:'service',files:{file:digest}}];
+ assert.equal(checkPolicyFiles(policies,dir), true);
+ fs.writeFileSync(path.join(dir,'file'),'changed');
+ assert.throws(() => checkPolicyFiles(policies,dir), /fingerprint mismatch/);
+ assert.throws(() => checkPolicyFiles(policies.slice(0,2),dir), /missing service/);
+ } finally { fs.rmSync(dir,{recursive:true,force:true}); }
+});
+
+test('default production policy accepts its exact blobs and rejects a changed helper', async () => {
+ const { createEvidence, CI_JOBS } = require('./release-evidence.cjs');
+ const policy = require('./release-evidence-policy.json').filter(p => p.kind === 'ci').at(-1);
+ const run = {id:88, workflow_id:42, repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion:'success',run_attempt:1,head_sha:SHA,display_title:`ocx-ci-v1 lane=all sha=${SHA}`};
+ const jobs = CI_JOBS.map(name => ({name,status:'completed',conclusion:'success'}));
+ const trees = new Map();
+ const directorySha = path => require('node:crypto').createHash('sha1').update(path).digest('hex');
+ const treeFor = path => { const id = directorySha(path); if (!trees.has(id)) trees.set(id, []); return trees.get(id); };
+ treeFor('');
+ for (const [file, id] of Object.entries(policy.files)) {
+ const parts = file.split('/'); let current = '';
+ for (const part of parts.slice(0,-1)) {
+ const next = current ? `${current}/${part}` : part;
+ if (!treeFor(current).some(e => e.path === part)) treeFor(current).push({path:part,type:'tree',mode:'040000',sha:directorySha(next)});
+ treeFor(next); current = next;
+ }
+ treeFor(current).push({path:parts.at(-1),type:'blob',mode:'100644',sha:id});
+ }
+ const api = async url => {
+ if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'};
+ if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'};
+ if (url === '/commits/dev') return {sha:SHA};
+ if (url.startsWith('/compare/')) return {status:'identical'};
+ if (url.startsWith('/actions/workflows/42/runs?')) return {total_count:1,workflow_runs:[run]};
+ if (url === `/git/commits/${SHA}`) return {tree:{sha:directorySha('')}};
+ if (url.startsWith('/git/trees/')) return {truncated:false,tree:trees.get(url.slice('/git/trees/'.length))};
+ if (url.startsWith('/actions/runs/88/attempts/1/jobs?')) return {total_count:jobs.length,jobs};
+ throw new Error(`unexpected API request ${url}`);
+ };
+ assert.deepEqual(await createEvidence(api).select('ci', SHA), {sourceSha:SHA,ciRunId:88});
+ const script = treeFor('scripts/ci').find(e => e.path === 'run-bun-test-batches.sh');
+ script.sha = 'f'.repeat(40);
+ await assert.rejects(createEvidence(api).select('ci', SHA), /no qualifying/);
+});
+
+function boundedFixture({ runs, order, race = false, raceState = false, devMoves = false, divergent = [], history = ['1','2','3'].map(x => x.repeat(40)) }) {
+ const { CI_JOBS } = require('./release-evidence.cjs');
+ const tree = 'd'.repeat(40), blob = 'e'.repeat(40), calls = [];
+ let exactReads = 0;
+ const readsByHead = new Map();
+ let devReads = 0;
+ const api = async url => {
+ calls.push(url);
+ if (url === '') return {id:1273824907,full_name:'lidge-jun/opencodex'};
+ if (url === '/actions/workflows/ci.yml') return {id:42,path:'.github/workflows/ci.yml'};
+ if (url === '/commits/dev') return {sha:devMoves && ++devReads > 1 ? 'f'.repeat(40) : history.at(-1)};
+ if (url.startsWith('/compare/')) {
+ const parsed = new URL(url, 'https://fixture.invalid');
+ const [base, head] = parsed.pathname.slice(9).split('...');
+ const a=history.indexOf(base), b=history.indexOf(head);
+ const status = a===b ? 'identical' : divergent.includes(base) && divergent.includes(head) ? 'diverged' : a ({sha})) : [];
+ const page = Number(parsed.searchParams.get('page') || 1), size = Number(parsed.searchParams.get('per_page') || 100);
+ return {status,total_commits:commits.length,commits:commits.slice((page-1)*size,page*size)};
+ }
+ if (url.startsWith('/actions/workflows/42/runs?')) {
+ const query = new URL(url, 'https://fixture.invalid').searchParams;
+ if (query.get('event') !== 'workflow_dispatch' || query.get('branch') !== 'dev') throw new Error('unfiltered 25000-run history');
+ const head = query.get('head_sha');
+ if (head) { exactReads++; readsByHead.set(head, (readsByHead.get(head) || 0) + 1); }
+ let selected = runs.map(r => raceState && head && readsByHead.get(head) > 1 && r.status === 'in_progress' ? {...r,status:'completed',conclusion:'success'} : r)
+ .filter(r => (!head || r.head_sha === head) && (!query.has('status') || r.conclusion === query.get('status')));
+ if (order) selected = [...selected].sort((a,b) => order.indexOf(a.id)-order.indexOf(b.id));
+ const page=Number(query.get('page') || 1), size=Number(query.get('per_page') || 100);
+ const total_count = selected.length + (race && head && exactReads > 1 ? 1 : 0);
+ return {total_count,workflow_runs:selected.slice((page-1)*size,page*size)};
+ }
+ if (url.startsWith('/git/commits/')) return {tree:{sha:tree}};
+ if (url === `/git/trees/${tree}`) return {truncated:false,tree:[{path:'.github',type:'tree',sha:tree},{path:'workflows',type:'tree',sha:tree},{path:'ci.yml',type:'blob',mode:'100644',sha:blob}]};
+ if (/^\/actions\/runs\/\d+\/attempts\/1\/jobs\?/.test(url)) return {total_count:CI_JOBS.length,jobs:CI_JOBS.map(name => ({name,status:'completed',conclusion:'success'}))};
+ throw new Error(`unexpected API request ${url}`);
+ };
+ const makeRun = (id, source, conclusion='success') => ({id,workflow_id:42,repository:{id:1273824907},head_repository:{id:1273824907},event:'workflow_dispatch',head_branch:'dev',status:'completed',conclusion,run_attempt:1,head_sha:source,display_title:`ocx-ci-v1 lane=all sha=${source}`});
+ return {api,calls,history,makeRun,policies:[{kind:'ci',version:1,files:{'.github/workflows/ci.yml':blob}}]};
+}
+
+test('exact SHA filters 25000 unrelated runs on the server', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const data = boundedFixture({runs:[]});
+ const old = data.history[0];
+ const run = data.makeRun(7,old);
+ const fixture = boundedFixture({runs:[run]});
+ assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci',old), {sourceSha:old,ciRunId:7});
+ assert.ok(fixture.calls.filter(x=>x.startsWith('/actions/workflows/42/runs?')).every(x=>new URL(x,'https://fixture.invalid').searchParams.get('head_sha')===old));
+});
+
+test('newest selection proves ancestry independently of run completion ordering', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed = boundedFixture({runs:[]}), [older,,newer] = seed.history;
+ const fixture = boundedFixture({runs:[seed.makeRun(1,older),seed.makeRun(2,newer)],order:[1,2]});
+ assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:newer,ciRunId:2});
+ assert.ok(fixture.calls.some(x=>x.startsWith('/compare/') && x.includes('per_page=')));
+});
+
+test('newer failed runs do not hide an older qualifying commit', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed = boundedFixture({runs:[]}), [older,,newer] = seed.history;
+ const fixture = boundedFixture({runs:[seed.makeRun(2,newer,'failure'),seed.makeRun(1,older)],order:[2,1]});
+ assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:older,ciRunId:1});
+});
+
+test('more than 1000 failed newer runs do not exhaust the filtered search', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed=boundedFixture({runs:[]}), [older,,newer]=seed.history;
+ const failures=Array.from({length:1101},(_,i)=>seed.makeRun(i+2,newer,'failure'));
+ const fixture=boundedFixture({runs:[...failures,seed.makeRun(1,older)]});
+ assert.deepEqual(await createEvidence(fixture.api,fixture.policies).select('ci'), {sourceSha:older,ciRunId:1});
+});
+
+test('exact SHA pagination and concurrent list changes fail closed', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed = boundedFixture({runs:[]}), source=seed.history[0];
+ const runs=Array.from({length:101},(_,i)=>seed.makeRun(i+1,source));
+ const good=boundedFixture({runs});
+ assert.equal((await createEvidence(good.api,good.policies).select('ci',source)).sourceSha,source);
+ assert.ok(good.calls.some(x=>x.includes('page=2')));
+ const racing=boundedFixture({runs,race:true});
+ await assert.rejects(createEvidence(racing.api,racing.policies).select('ci',source), /pagination|changed|incomplete/i);
+});
+
+test('newest selection detects dev movement and a newer run completing during lookup', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed=boundedFixture({runs:[]}), [older,,newer]=seed.history;
+ const progress={...seed.makeRun(2,newer),status:'in_progress',conclusion:null};
+ const racing=boundedFixture({runs:[seed.makeRun(1,older),progress],raceState:true});
+ await assert.rejects(createEvidence(racing.api,racing.policies).select('ci'), /changed/i);
+ const moved=boundedFixture({runs:[seed.makeRun(1,older)],devMoves:true});
+ await assert.rejects(createEvidence(moved.api,moved.policies).select('ci'), /dev changed/i);
+});
+
+test('newest selection paginates the commit comparison and refuses excessive ancestry', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const history=Array.from({length:102},(_,i)=>(i+1).toString(16).padStart(40,'0'));
+ const seed=boundedFixture({runs:[],history});
+ const fixture=boundedFixture({runs:[seed.makeRun(1,history[0])],history});
+ assert.equal((await createEvidence(fixture.api,fixture.policies).select('ci')).sourceSha, history[0]);
+ assert.ok(fixture.calls.some(x=>x.startsWith('/compare/') && x.includes('page=2')));
+ const longHistory=Array.from({length:202},(_,i)=>(i+1).toString(16).padStart(40,'0'));
+ const long=boundedFixture({runs:[seed.makeRun(1,longHistory[0])],history:longHistory});
+ await assert.rejects(createEvidence(long.api,long.policies).select('ci'), /coverage exceeds/);
+});
+
+test('newest selection refuses incomparable green ancestors', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const history=['1','2','3','4'].map(x=>x.repeat(40));
+ const seed=boundedFixture({runs:[],history});
+ const fixture=boundedFixture({history,divergent:[history[1],history[2]],runs:[seed.makeRun(1,history[0]),seed.makeRun(2,history[1]),seed.makeRun(3,history[2])]});
+ await assert.rejects(createEvidence(fixture.api,fixture.policies).select('ci'), /ambiguous/);
+});
+
+test('filtered searches fail closed beyond GitHub’s 1000-result coverage', async () => {
+ const {createEvidence} = require('./release-evidence.cjs');
+ const seed=boundedFixture({runs:[]}), source=seed.history[0];
+ const runs=Array.from({length:1001},(_,i)=>({...seed.makeRun(i+1,source),display_title:'old policy'}));
+ const discovery=boundedFixture({runs});
+ await assert.rejects(createEvidence(discovery.api,discovery.policies).select('ci'), /coverage exceeds/);
+ assert.equal(discovery.calls.filter(x=>x.startsWith('/actions/workflows/42/runs?')).length,10);
+ const exact=boundedFixture({runs});
+ await assert.rejects(createEvidence(exact.api,exact.policies).select('ci',source), /coverage exceeds/);
+});
diff --git a/.github/scripts/release-history.cjs b/.github/scripts/release-history.cjs
new file mode 100644
index 0000000000..e2de485339
--- /dev/null
+++ b/.github/scripts/release-history.cjs
@@ -0,0 +1,394 @@
+'use strict';
+
+/*
+ * The collector reads npm, authenticated GitHub and local Git under the release
+ * lock. Callers MUST execute this file from the trusted workflow revision, with
+ * a complete git checkout and repeat the check immediately before publication.
+ * The API's fetchImpl injection is for trusted callers and tests only;
+ * the CLI pins both endpoints, package/repository identity and mapping policy.
+ * Decision primitives require complete, fresh evidence under the release
+ * lock. isAncestor must
+ * query complete Git history and throw on an unknown object. verifyReceipt and
+ * verifyProvenance must cryptographically authenticate their inputs, bind the
+ * supplied tuple, and return the literal boolean true. Neither JSON flags nor a
+ * candidate-created Actions artifact are authentication. Never invoke these
+ * functions with callbacks or evidence controlled by a dispatch input.
+ *
+ * reconcileHistory accepts registry versions {version,gitHead,publishedAt},
+ * distTags, Git tag commits {version,sha}, GitHub releases {version,tag}, signed
+ * receipt envelopes {payload}, candidateSha/candidateVersion/channel,
+ * isAncestor and verifyReceipt. This primitive requires direct ancestry.
+ * resume:true requires the candidate to be the already-published floor and an
+ * authenticated receipt; it does not derive or approve a new version.
+ * Input arrays must cover the entire reconciled ledger, including partial npm
+ * publishes. A collector must separately detect pagination and snapshot races.
+ *
+ * verifyExactResume accepts tuple/receipt/registry/provenance/tag/release/historyFloor
+ * plus verifyReceipt, verifyProvenance and verifyHistory. verifyHistory must
+ * authenticate a fresh, complete, lock-protected reconciliation including all
+ * npm-only publications. Receipt payload binds the complete tuple and
+ * asset name-to-SHA256 map; registry.sha256 must be independently calculated
+ * from downloaded registry tarball bytes. Existing assets are hashed from bytes.
+ * A null tag/release means the authenticated GitHub lookup confirmed absence.
+ * Publication orchestration must not call npm publish after a successful resume.
+ */
+const { verify, createPublicKey } = require('node:crypto');
+const { spawnSync } = require('node:child_process');
+const { readFileSync } = require('node:fs');
+const { isDeepStrictEqual } = require('node:util');
+const SHA = /^[a-f0-9]{40}$/;
+const DIGEST = /^[a-f0-9]{64}$/;
+const VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-preview\.(0|[1-9]\d*)(?:\.(0|[1-9]\d*))?)?$/;
+const PACKAGE = '@bitkyc08/opencodex';
+const REPO = 'lidge-jun/opencodex';
+const REPO_ID = 1273824907;
+// One-time legacy transition. The collector verifies the tag and registry SHA,
+// both ancestry relationships and actual version-only tree differences at run
+// time. This code-backed policy still needs independent review before cutover.
+const LEGACY_MAPPINGS = Object.freeze([
+ {version:'2.99.0',legacySha:'667662903a6c139524506667d12656d9ad50fad0'},
+ {version:'2.99.0-preview.20261108',legacySha:'68eee1eb804445ad86fe942b734060f323eb1517'},
+]);
+const LEGACY_BASELINE = '0627a2c255bc239d5748119f1d0bc4457a1c03e3';
+const LEGACY_BASELINE_VERSION = '2.100.0';
+const VERSION_PATHS = Object.freeze(['package.json','desktop/src-tauri/tauri.conf.json','desktop/src-tauri/Cargo.toml','desktop/src-tauri/Cargo.lock']);
+
+function must(condition, message) { if (!condition) throw new Error(message); }
+function version(v) {
+ const m = typeof v === 'string' && VERSION.exec(v);
+ must(m, 'invalid release version');
+ const numbers = m.slice(1).map(x => x === undefined ? null : Number(x));
+ must(numbers.every(x => x === null || Number.isSafeInteger(x)), 'invalid release version');
+ return numbers;
+}
+function compareVersions(a, b) {
+ const x = version(a), y = version(b);
+ for (let i = 0; i < 3; i++) if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
+ if (x[3] === null || y[3] === null) return x[3] === y[3] ? 0 : x[3] === null ? 1 : -1;
+ for (let i = 3; i < 5; i++) {
+ if (x[i] !== y[i]) return x[i] === null ? -1 : y[i] === null ? 1 : x[i] < y[i] ? -1 : 1;
+ }
+ return 0;
+}
+function channelFor(v) { return version(v)[3] === null ? 'stable' : 'preview'; }
+function validTuple(t) {
+ must(t && SHA.test(t.sourceSha || '') && SHA.test(t.workflowSha || '') && DIGEST.test(t.sha256 || '') &&
+ Number.isSafeInteger(t.runId) && t.runId > 0 && Number.isSafeInteger(t.attempt) && t.attempt > 0 &&
+ t.channel === channelFor(t.version), 'invalid receipt tuple');
+ must(t.assets && typeof t.assets === 'object' && !Array.isArray(t.assets), 'invalid receipt assets');
+ for (const [name, digest] of Object.entries(t.assets)) must(name && !/[\x00-\x1f/\\]/.test(name) && DIGEST.test(digest), 'invalid receipt asset');
+}
+function sameTuple(a, b) {
+ validTuple(a); validTuple(b);
+ return ['sourceSha','workflowSha','version','channel','sha256','runId','attempt'].every(k => a[k] === b[k]) &&
+ Object.keys(a.assets).length === Object.keys(b.assets).length && Object.entries(a.assets).every(([k,v]) => Object.hasOwn(b.assets,k) && b.assets[k] === v);
+}
+function assertReceipt(envelope, expected, verifyReceipt) {
+ must(envelope && typeof verifyReceipt === 'function' && verifyReceipt(envelope, expected) === true, 'receipt authentication failed');
+ must(sameTuple(envelope.payload, expected), 'receipt tuple mismatch');
+}
+function reconcileHistory(input) {
+ const {candidateSha, candidateVersion, channel, versions, distTags, tags, releases, receipts, isAncestor, verifyReceipt, resume = false} = input;
+ must(typeof resume === 'boolean', 'invalid resume mode');
+ must(SHA.test(candidateSha || '') && channel === channelFor(candidateVersion), 'invalid candidate');
+ must([versions,tags,releases,receipts].every(Array.isArray) && distTags && typeof distTags === 'object' && !Array.isArray(distTags) && typeof isAncestor === 'function', 'incomplete history');
+ const byVersion = new Map(), byTag = new Map(), byRelease = new Map(), byReceipt = new Map();
+ for (const r of versions) {
+ version(r?.version); must(!byVersion.has(r.version) && SHA.test(r.gitHead || ''), 'missing or duplicate registry source');
+ const time = Date.parse(r.publishedAt);
+ must(typeof r.publishedAt === 'string' && Number.isFinite(time) && new Date(time).toISOString() === r.publishedAt, 'missing publication order');
+ byVersion.set(r.version, {...r,time});
+ }
+ for (const [name, v] of Object.entries(distTags)) { must(name && byVersion.has(v), 'unknown dist-tag version'); }
+ for (const t of tags) { version(t?.version); must(!byTag.has(t.version) && SHA.test(t.sha || '') && byVersion.has(t.version), 'unknown or duplicate tag'); byTag.set(t.version,t); }
+ for (const r of releases) { version(r?.version); must(!byRelease.has(r.version) && r.tag === `v${r.version}` && byTag.has(r.version), 'unknown or duplicate release'); byRelease.set(r.version,r); }
+ for (const envelope of receipts) {
+ const r = envelope?.payload; validTuple(r);
+ must(!byReceipt.has(r.version) && byVersion.has(r.version), 'unknown or duplicate receipt');
+ assertReceipt(envelope, r, verifyReceipt); byReceipt.set(r.version, r);
+ }
+ const ordered = [...byVersion.values()].sort((a,b) => a.time-b.time);
+ for (let i = 0; i < ordered.length; i++) {
+ const r = ordered[i], tag = byTag.get(r.version), receipt = byReceipt.get(r.version);
+ if (i) must(ordered[i-1].time < r.time, 'ambiguous publication order');
+ if (tag) must(tag.sha === r.gitHead, 'tag and registry source mismatch');
+ if (receipt) must(receipt.sourceSha === r.gitHead && receipt.channel === channelFor(r.version), 'receipt and registry source mismatch');
+ if (!tag || !byRelease.has(r.version)) must(receipt, 'npm-only publication requires authenticated receipt');
+ }
+ for (let i = 1; i < ordered.length; i++) must(isAncestor(ordered[i-1].gitHead,ordered[i].gitHead) === true, 'publication lineage diverges');
+ if (ordered.length) {
+ const floor = ordered.at(-1);
+ if (resume) {
+ must(candidateVersion === floor.version && candidateSha === floor.gitHead && byReceipt.has(floor.version), 'resume would roll back or lacks a receipt');
+ } else {
+ must(ordered.every(r => compareVersions(candidateVersion, r.version) > 0), 'candidate version would regress or already exists');
+ must(isAncestor(floor.gitHead,candidateSha) === true, 'candidate lineage would roll back or diverge');
+ if (candidateSha === floor.gitHead) must(channel === 'stable' && channelFor(floor.version) === 'preview', 'same source only allowed for preview to stable');
+ }
+ return {floor:{version:floor.version,sourceSha:floor.gitHead,publishedAt:floor.publishedAt}};
+ }
+ must(!resume, 'resume requires published history');
+ return {floor:null};
+}
+function verifyExactResume({tuple, receipt, registry, provenance, tag, release, historyFloor, verifyReceipt, verifyProvenance, verifyHistory}) {
+ validTuple(tuple); assertReceipt(receipt, tuple, verifyReceipt);
+ must(registry && registry.version === tuple.version && registry.gitHead === tuple.sourceSha && registry.sha256 === tuple.sha256, 'registry identity or digest mismatch');
+ must(typeof verifyProvenance === 'function' && verifyProvenance(provenance, tuple, registry) === true, 'provenance authentication failed');
+ must(typeof verifyHistory === 'function' && verifyHistory(historyFloor) === true && historyFloor?.version === tuple.version && historyFloor.sourceSha === tuple.sourceSha, 'resume would roll back publication history');
+ must(tag === null || (tag && tag.name === `v${tuple.version}` && tag.sha === tuple.sourceSha), 'existing tag mismatch');
+ must(release === null || (release && tag && release.tag === tag.name && Array.isArray(release.assets)), 'existing release mismatch');
+ const reuseAssets = [], seen = new Set();
+ for (const asset of release?.assets || []) {
+ must(asset && typeof asset.name === 'string' && !seen.has(asset.name) && Object.hasOwn(tuple.assets,asset.name) && DIGEST.test(asset.sha256 || '') && tuple.assets[asset.name] === asset.sha256, 'unsafe existing asset');
+ seen.add(asset.name); reuseAssets.push(asset.name);
+ }
+ return {publishNpm:false, reuseAssets:reuseAssets.sort()};
+}
+
+function createGit(repoPath) {
+ function run(args, allowNotAncestor = false, trim = true) {
+ const r = spawnSync('git', ['-C',repoPath,...args], {encoding:'utf8',maxBuffer:1024*1024,env:{...process.env,GIT_NO_REPLACE_OBJECTS:'1'},stdio:['ignore','pipe','pipe']});
+ if (allowNotAncestor && r.status === 1) return false;
+ must(r.status === 0, `Git could not verify ${args[0]}; fetch complete dev and tag history`);
+ return trim ? r.stdout.trim() : r.stdout;
+ }
+ must(run(['rev-parse','--is-shallow-repository']) === 'false', 'Git history is shallow; fetch complete history');
+ const known = new Set(), comparisons = new Map();
+ function commit(sha) {
+ must(SHA.test(sha || ''), 'invalid Git source SHA');
+ if (!known.has(sha)) {
+ try { run(['cat-file','-e',`${sha}^{commit}`]); }
+ catch { throw new Error(`Git source ${sha} is unavailable; fetch complete release and dev history and reconcile unknown sources`); }
+ known.add(sha);
+ }
+ }
+ function isAncestor(a,b) {
+ commit(a); commit(b);
+ const key = `${a}:${b}`;
+ if (!comparisons.has(key)) comparisons.set(key, run(['merge-base','--is-ancestor',a,b],true) !== false);
+ return comparisons.get(key);
+ }
+ function treeFile(sha,path) {
+ commit(sha);
+ const entry = run(['ls-tree',sha,'--',path]);
+ must(/^100644 blob [a-f0-9]{40}\t/.test(entry) && entry.endsWith(`\t${path}`), `legacy version file ${path} is missing or has an unsafe mode`);
+ const text = run(['show',`${sha}:${path}`],false,false);
+ must(!text.includes('\ufffd'), `legacy version file ${path} is not valid UTF-8`);
+ return text;
+ }
+ function changedPaths(a,b) {
+ commit(a); commit(b);
+ const output = run(['diff','--no-ext-diff','--no-renames','--name-status','-z',a,b,'--'],false,false);
+ const fields = output.split('\0');
+ must(fields.pop() === '' && fields.length % 2 === 0, 'invalid legacy tree diff');
+ const paths = [];
+ for (let i=0;i line.trim() === '[package]' ? i : -1).filter(i => i >= 0);
+ must(starts.length === 1, `ambiguous package version in ${path}`);
+ let end = starts[0] + 1;
+ while (end < lines.length && !/^\s*\[/.test(lines[end])) end++;
+ must(lines.slice(starts[0]+1,end).filter(line => /^\s*name\s*=\s*"opencodex-desktop"\s*$/.test(line)).length === 1, `invalid desktop package in ${path}`);
+ indexes = lines.map((line,i) => i > starts[0] && i < end && /^\s*version\s*=/.test(line) ? i : -1).filter(i => i >= 0);
+ } else {
+ indexes = [];
+ for (let i=0;i+2 0 && entries.length <= 10000, 'empty or oversized npm history requires reconciliation');
+ const versions = entries.map(([v,metadata]) => {
+ version(v);
+ must(metadata?.name === PACKAGE && metadata.version === v, `npm ${v} has invalid package identity`);
+ const publishedAt = data.time[v], time = Date.parse(publishedAt);
+ must(typeof publishedAt === 'string' && Number.isFinite(time) && new Date(time).toISOString() === publishedAt, `npm ${v} has missing publication time`);
+ return {version:v,gitHead:metadata.gitHead ?? null,publishedAt,time};
+ }).sort((a,b) => a.time-b.time);
+ for (let i=1;i r.version === value), `npm dist-tag ${key} names unknown version`);
+ if (tags.latest) must(channelFor(tags.latest) === 'stable', 'npm latest dist-tag is not stable');
+ if (tags.preview) must(channelFor(tags.preview) === 'preview', 'npm preview dist-tag is not preview');
+ return {versions,distTags:Object.fromEntries(Object.entries(tags).sort(([a],[b]) => a.localeCompare(b)))};
+}
+function githubSnapshot(tags, releases) {
+ const tagMap = new Map(), releaseMap = new Map();
+ for (const tag of tags) {
+ must(typeof tag?.name === 'string' && SHA.test(tag.commit?.sha || '') && !tagMap.has(tag.name), 'duplicate or malformed GitHub tag');
+ tagMap.set(tag.name,tag.commit.sha);
+ }
+ for (const release of releases) {
+ must(typeof release?.tag_name === 'string' && typeof release.draft === 'boolean' && typeof release.prerelease === 'boolean' && !releaseMap.has(release.tag_name), 'duplicate or malformed GitHub release');
+ releaseMap.set(release.tag_name,{draft:release.draft,prerelease:release.prerelease,published_at:release.published_at});
+ }
+ return {tagMap,releaseMap};
+}
+/**
+ * Read-only history gate. GH_TOKEN needs repository contents:read. Invoke from
+ * trusted workflow checkout with full Git history after acquiring the shared
+ * release lock: `node .github/scripts/release-history.cjs check
+ * `. Exit 0 returns JSON {floor,channels,devSha,
+ * versionsChecked}; any unverifiable evidence exits nonzero. Publications at
+ * or after the older channel head without a matching tag and published release
+ * stop for manual reconciliation; no receipt/provenance verifier is assumed.
+ * Older versions still participate in the global version and ordering checks.
+ * Re-run immediately before publication. This gate does not authorize
+ * npm publication or prove build, CI, package digest, provenance, or resume.
+ */
+async function collectPublicationHistory({candidateSha,candidateVersion,channel,repoPath = process.cwd(),token,fetchImpl = fetch}) {
+ must(typeof token === 'string' && token.length > 0 && typeof fetchImpl === 'function', 'GH_TOKEN is required for authenticated GitHub evidence');
+ must(SHA.test(candidateSha || '') && channel === channelFor(candidateVersion), 'invalid candidate source, version or channel');
+ const git = createGit(repoPath), base = `https://api.github.com/repos/${REPO}`;
+ const get = (path,allow404) => requestJson(fetchImpl,base+path,token,allow404);
+ const readNpm = async () => registrySnapshot(await requestJson(fetchImpl,'https://registry.npmjs.org/%40bitkyc08%2Fopencodex',token));
+ const [repo,dev,npm,tags,releases] = await Promise.all([get(''),get('/commits/dev'),readNpm(),githubPages(fetchImpl,token,'tags'),githubPages(fetchImpl,token,'releases')]);
+ must(repo?.id === REPO_ID && repo.full_name === REPO, 'GitHub repository identity mismatch');
+ must(SHA.test(dev?.sha || '') && git.isAncestor(candidateSha,dev.sha), 'candidate is not reachable from GitHub dev');
+ const gh = githubSnapshot(tags,releases);
+ const channels = ['preview','stable'].map(c => npm.versions.filter(r => channelFor(r.version) === c).at(-1)).filter(Boolean).sort((a,b) => a.time-b.time);
+ const cutoff = channels[0].time;
+ for (const r of npm.versions.filter(r => r.time >= cutoff)) {
+ const tag = gh.tagMap.get(`v${r.version}`), release = gh.releaseMap.get(`v${r.version}`);
+ must(SHA.test(r.gitHead || ''), `npm ${r.version} has missing or invalid gitHead; reconcile publication source`);
+ must(tag, `npm-only publication ${r.version} (${r.gitHead}) has no GitHub tag; authenticated prior receipt and provenance required for reconciliation`);
+ must(tag === r.gitHead, `GitHub tag v${r.version} does not match npm gitHead`);
+ must(release && !release.draft && release.prerelease === (channelFor(r.version) === 'preview') && Number.isFinite(Date.parse(release.published_at)), `npm publication ${r.version} lacks a published matching GitHub release; authenticated receipt and provenance required`);
+ }
+ for (const r of npm.versions) {
+ must(compareVersions(candidateVersion,r.version) > 0, `candidate version ${candidateVersion} does not exceed published npm version ${r.version}`);
+ }
+ const selectedVersions = new Set(npm.versions.map(r => r.version));
+ for (const [tag,release] of gh.releaseMap) {
+ if (release.draft) continue;
+ const published = Date.parse(release.published_at);
+ must(Number.isFinite(published), `GitHub release ${tag} has no publication time`);
+ if (published >= cutoff && tag.startsWith('v')) must(selectedVersions.has(tag.slice(1)), `GitHub release ${tag} has no matching npm version; reconcile partial publication`);
+ }
+ for (const r of channels) {
+ const legacy = LEGACY_MAPPINGS.find(m => m.version === r.version);
+ if (legacy) {
+ must(r.gitHead === legacy.legacySha && gh.tagMap.get(`v${r.version}`) === legacy.legacySha, `legacy ${r.version} registry or tag source does not match the fixed expected SHA`);
+ verifyLegacyTreeEvidence({repoPath,sourceSha:legacy.legacySha,baselineSha:LEGACY_BASELINE,sourceVersion:legacy.version,baselineVersion:LEGACY_BASELINE_VERSION,candidateSha,devSha:dev.sha});
+ } else {
+ must(git.isAncestor(r.gitHead,candidateSha), `candidate lineage does not include ${r.version} source ${r.gitHead}`);
+ }
+ }
+ const newest = channels.at(-1);
+ if (candidateSha === newest.gitHead) must(channel === 'stable' && channelFor(newest.version) === 'preview', 'same source only allowed for preview to stable');
+ const result = {floor:{version:newest.version,sourceSha:newest.gitHead,publishedAt:newest.publishedAt}};
+ const [npmAgain,devAgain,tagsAgain,releasesAgain] = await Promise.all([readNpm(),get('/commits/dev'),githubPages(fetchImpl,token,'tags'),githubPages(fetchImpl,token,'releases')]);
+ const comparable = snapshot => JSON.stringify({tags:[...snapshot.tagMap].sort(),releases:[...snapshot.releaseMap].sort(([a],[b]) => a.localeCompare(b))});
+ must(isDeepStrictEqual(npm,npmAgain) && devAgain?.sha === dev.sha && comparable(gh) === comparable(githubSnapshot(tagsAgain,releasesAgain)), 'publication evidence changed during collection; retry under the shared release lock');
+ return {...result,channels:channels.map(({version,gitHead,publishedAt}) => ({version,sourceSha:gitHead,publishedAt})),devSha:dev.sha,versionsChecked:npm.versions.length};
+}
+
+// Ed25519 signatures authenticate raw bytes. The public key must come from a
+// reviewed trusted policy, not an artifact, candidate checkout, or CLI input.
+function verifyEd25519Receipt(bytes, signature, trustedPublicKey) {
+ try {
+ const key = createPublicKey(trustedPublicKey);
+ return key.asymmetricKeyType === 'ed25519' && Buffer.isBuffer(bytes) && Buffer.isBuffer(signature) && verify(null, bytes, key, signature);
+ }
+ catch { return false; }
+}
+// Signed JSON has shape {payload,expiresAt}; the verifier rejects a changed
+// parsed payload and requires a separate authenticated run/attempt lookup.
+function createReceiptVerifier({publicKey, now, verifyRun}) {
+ must(typeof now === 'function' && typeof verifyRun === 'function', 'receipt verification dependencies required');
+ return (envelope, expected) => {
+ try {
+ if (!envelope || typeof envelope.signedBytes !== 'string' || typeof envelope.signature !== 'string') return false;
+ const bytes = Buffer.from(envelope.signedBytes, 'base64');
+ const signature = Buffer.from(envelope.signature, 'base64');
+ if (!bytes.length || bytes.length > 1024 * 1024 || bytes.toString('base64') !== envelope.signedBytes || signature.toString('base64') !== envelope.signature ||
+ !verifyEd25519Receipt(bytes, signature, publicKey)) return false;
+ const signed = JSON.parse(bytes.toString('utf8'));
+ const expires = Date.parse(signed.expiresAt), current = now();
+ if (!Number.isFinite(expires) || !Number.isFinite(current) || expires <= current || !isDeepStrictEqual(signed.payload, envelope.payload) ||
+ !sameTuple(signed.payload, expected)) return false;
+ return verifyRun(signed.payload) === true;
+ } catch { return false; }
+ };
+}
+// check must run from the trusted workflow revision under the release lock.
+// GH_TOKEN is read from the environment; output contains no credentials.
+async function main(args) {
+ const [command, first, second, third, ...extra] = args;
+ if (command === 'check') {
+ must(first && second && third && !extra.length, 'usage: release-history.cjs check ');
+ const result = await collectPublicationHistory({candidateSha:first,candidateVersion:second,channel:third,token:process.env.GH_TOKEN});
+ process.stdout.write(`${JSON.stringify(result)}\n`); return;
+ }
+ must(command === 'verify-signature' && first && second && third && !extra.length, 'usage: release-history.cjs check | verify-signature ');
+ must(verifyEd25519Receipt(readFileSync(first), readFileSync(second), readFileSync(third)), 'receipt signature invalid');
+ process.stdout.write('signature valid; publication evidence has not been checked\n');
+}
+if (require.main === module) main(process.argv.slice(2)).catch(error => { process.stderr.write(`release history: ${error.message}\n`); process.exitCode = 1; });
+module.exports = {compareVersions, reconcileHistory, verifyExactResume, verifyEd25519Receipt, createReceiptVerifier, collectPublicationHistory, verifyLegacyTreeEvidence, LEGACY_MAPPINGS, LEGACY_BASELINE};
diff --git a/.github/scripts/release-history.test.cjs b/.github/scripts/release-history.test.cjs
new file mode 100644
index 0000000000..0691262d23
--- /dev/null
+++ b/.github/scripts/release-history.test.cjs
@@ -0,0 +1,333 @@
+'use strict';
+
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { generateKeyPairSync, sign } = require('node:crypto');
+const { mkdtempSync, rmSync, mkdirSync, writeFileSync } = require('node:fs');
+const { tmpdir } = require('node:os');
+const { join, resolve } = require('node:path');
+const { execFileSync } = require('node:child_process');
+const { reconcileHistory, verifyExactResume, createReceiptVerifier, collectPublicationHistory, verifyLegacyTreeEvidence } = require('./release-history.cjs');
+
+const old = 'a'.repeat(40), newer = 'b'.repeat(40), other = 'c'.repeat(40), workflow = 'd'.repeat(40);
+const digest = '1'.repeat(64), assetDigest = '2'.repeat(64);
+const ancestry = (base, head) => base === head || (base === old && head === newer);
+const record = (version, sourceSha, publishedAt) => ({version, gitHead: sourceSha, publishedAt});
+const receipt = (version, sourceSha, channel = 'stable') => ({version, sourceSha, workflowSha: workflow, channel, sha256: digest, runId: 123, attempt: 1, assets: {'app.zip': assetDigest}});
+const authenticated = x => x?.authenticated === true;
+const attested = x => x?.verified === true;
+const signed = payload => ({payload, authenticated: true});
+const snapshot = overrides => ({
+ candidateSha: newer, candidateVersion: '1.0.2', channel: 'stable',
+ versions: [record('1.0.0', old, '2026-01-01T00:00:00.000Z')],
+ distTags: {latest: '1.0.0'}, tags: [{version: '1.0.0', sha: old}],
+ releases: [{version: '1.0.0', tag: 'v1.0.0'}], receipts: [], mappings: [],
+ isAncestor: ancestry, verifyReceipt: authenticated, ...overrides,
+});
+
+test('newer npm-only partial publication prevents source rollback', () => {
+ const r = receipt('1.0.1', newer);
+ const input = snapshot({candidateSha: old, versions: [record('1.0.0', old, '2026-01-01T00:00:00.000Z'), record('1.0.1', newer, '2026-01-02T00:00:00.000Z')], receipts: [signed(r)]});
+ assert.throws(() => reconcileHistory(input), /lineage|rollback/);
+ assert.throws(() => reconcileHistory({...input, receipts: []}), /receipt/);
+ assert.throws(() => reconcileHistory({...input, receipts: [{payload:r, authenticated:false}]}), /receipt/);
+});
+
+test('pure history rejects divergent sources and arbitrary mappings cannot bypass ancestry', () => {
+ const input = snapshot({versions:[record('1.0.0', other, '2026-01-01T00:00:00.000Z')], tags:[{version:'1.0.0', sha:other}]});
+ assert.throws(() => reconcileHistory(input), /lineage/);
+ assert.throws(() => reconcileHistory({...input, mappings:[{version:'1.0.0', legacySha:other, devSha:old}]}), /lineage/);
+});
+
+test('pure history rejects divergent channels', () => {
+ const input = snapshot({versions:[record('1.0.0',other,'2026-01-01T00:00:00.000Z'),record('1.0.1-preview.20260102.1',old,'2026-01-02T00:00:00.000Z')],
+ tags:[{version:'1.0.0',sha:other},{version:'1.0.1-preview.20260102.1',sha:old}], releases:[{version:'1.0.0',tag:'v1.0.0'},{version:'1.0.1-preview.20260102.1',tag:'v1.0.1-preview.20260102.1'}]});
+ assert.throws(() => reconcileHistory(input), /lineage/);
+});
+
+test('stable may follow preview at the same source but rollback and ambiguity fail', () => {
+ const input = snapshot({candidateSha:old, candidateVersion:'1.0.1', versions:[record('1.0.1-preview.20260101.1',old,'2026-01-01T00:00:00.000Z')], tags:[{version:'1.0.1-preview.20260101.1',sha:old}], releases:[{version:'1.0.1-preview.20260101.1',tag:'v1.0.1-preview.20260101.1'}], distTags:{preview:'1.0.1-preview.20260101.1'}});
+ assert.equal(reconcileHistory(input).floor.sourceSha, old);
+ assert.throws(() => reconcileHistory({...input, candidateVersion:'1.0.0'}), /version/);
+ assert.throws(() => reconcileHistory({...input, versions:[...input.versions, record('1.0.0',old,input.versions[0].publishedAt)]}), /order/);
+});
+
+function resumeInput() {
+ const tuple = receipt('1.0.1', newer);
+ return {tuple, receipt:signed(tuple), registry:{version:tuple.version, gitHead:newer, sha256:digest}, provenance:{verified:true}, tag:{name:'v1.0.1',sha:newer}, release:{tag:'v1.0.1',assets:[{name:'app.zip',sha256:assetDigest}]}, historyFloor:{version:tuple.version,sourceSha:newer}, verifyHistory:() => true, verifyReceipt:authenticated, verifyProvenance:attested};
+}
+test('verified exact resume never requests republish or overwrites assets', () => {
+ assert.deepEqual(verifyExactResume(resumeInput()), {publishNpm:false, reuseAssets:['app.zip']});
+});
+test('resume rejects corrupt or forged receipts, registry and provenance mismatches, and asset replacement', () => {
+ const input = resumeInput();
+ assert.throws(() => verifyExactResume({...input, receipt:{...input.receipt,authenticated:false}}), /receipt/);
+ assert.throws(() => verifyExactResume({...input, receipt:signed({...input.tuple, sha256:'3'.repeat(64)})}), /receipt/);
+ assert.throws(() => verifyExactResume({...input, registry:{...input.registry,gitHead:old}}), /registry/);
+ assert.throws(() => verifyExactResume({...input, provenance:{verified:false}}), /provenance/);
+ assert.throws(() => verifyExactResume({...input, historyFloor:{version:'1.0.2',sourceSha:other}}), /roll back/);
+ assert.throws(() => verifyExactResume({...input, verifyHistory:() => false}), /history/);
+ assert.throws(() => verifyExactResume({...input, tag:{name:'v1.0.1',sha:old}}), /tag/);
+ assert.throws(() => verifyExactResume({...input, release:{tag:'v1.0.1',assets:[{name:'app.zip',sha256:digest}]}}), /asset/);
+ assert.throws(() => verifyExactResume({...input, release:{tag:'v1.0.1',assets:[{name:'extra.zip',sha256:digest}]}}), /asset/);
+});
+
+test('real signed receipt binds bytes, tuple, expiry, and authenticated run attempt', () => {
+ const {privateKey, publicKey} = generateKeyPairSync('ed25519');
+ const publicPem = publicKey.export({type:'spki',format:'pem'});
+ const input = resumeInput();
+ const bytes = Buffer.from(JSON.stringify({payload:input.tuple,expiresAt:'2026-01-02T00:00:00.000Z'}));
+ const envelope = {payload:input.tuple, signedBytes:bytes.toString('base64'), signature:sign(null,bytes,privateKey).toString('base64')};
+ const makeVerifier = (now, verifyRun = t => t.runId === 123 && t.attempt === 1) => createReceiptVerifier({publicKey:publicPem, now:() => Date.parse(now), verifyRun});
+ const verifyReceipt = makeVerifier('2026-01-01T00:00:00.000Z');
+ assert.deepEqual(verifyExactResume({...input,receipt:envelope,verifyReceipt}), {publishNpm:false,reuseAssets:['app.zip']});
+ assert.throws(() => verifyExactResume({...input,receipt:{...envelope,payload:{...input.tuple,attempt:2}},verifyReceipt}), /receipt/);
+ const forged = Buffer.from(bytes); forged[10] ^= 1;
+ assert.throws(() => verifyExactResume({...input,receipt:{...envelope,signedBytes:forged.toString('base64')},verifyReceipt}), /receipt/);
+ assert.throws(() => verifyExactResume({...input,receipt:envelope,verifyReceipt:makeVerifier('2026-01-02T00:00:00.000Z')}), /receipt/);
+ assert.throws(() => verifyExactResume({...input,receipt:envelope,verifyReceipt:makeVerifier('2026-01-01T00:00:00.000Z', () => false)}), /receipt/);
+ const history = snapshot({versions:[record('1.0.1',newer,'2026-01-01T00:00:00.000Z')], distTags:{latest:'1.0.1'}, tags:[], releases:[], receipts:[envelope], candidateSha:old, candidateVersion:'1.0.2', verifyReceipt});
+ assert.throws(() => reconcileHistory(history), /lineage|rollback/);
+ assert.throws(() => reconcileHistory({...history,receipts:[{...envelope, signature:Buffer.alloc(64).toString('base64')}]}), /receipt/);
+ const resumed = reconcileHistory({...history,candidateSha:newer,candidateVersion:'1.0.1',distTags:{latest:'1.0.1'},resume:true});
+ assert.equal(resumed.floor.sourceSha, newer);
+ assert.throws(() => reconcileHistory({...history,candidateSha:old,candidateVersion:'1.0.0',distTags:{latest:'1.0.1'},resume:true}), /roll back/);
+});
+
+test('history rejects missing sources, unknown tags, and missing registry evidence', () => {
+ const input = snapshot();
+ assert.throws(() => reconcileHistory({...input, versions:[record('1.0.0','', '2026-01-01T00:00:00.000Z')]}), /source/);
+ assert.throws(() => reconcileHistory({...input, distTags:{latest:'1.0.5'}}), /dist-tag/);
+ assert.throws(() => reconcileHistory({...input, tags:[{version:'1.0.1',sha:old}]}), /tag/);
+ assert.throws(() => reconcileHistory({...input, releases:[{version:'1.0.0',tag:'v1.0.1'}]}), /release/);
+});
+
+function collectorFixture(t) {
+ const dir = mkdtempSync(join(tmpdir(), 'ocx-release-history-'));
+ t.after(() => rmSync(dir, {recursive:true, force:true}));
+ const git = (...args) => execFileSync('git', ['-C',dir,...args], {encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();
+ git('init','-q');
+ const commit = name => { git('-c','user.name=Test','-c','user.email=test@localhost','commit','--allow-empty','-qm',name); return git('rev-parse','HEAD'); };
+ const first = commit('preview'), second = commit('stable'), candidate = commit('candidate');
+ const control = {devSha:candidate};
+ const data = {name:'@bitkyc08/opencodex',versions:{},time:{},'dist-tags':{preview:'1.0.1-preview.20260101.1',latest:'1.0.1'}};
+ const refs = new Map();
+ function publish(v, sha, time, hasTag = true) {
+ data.versions[v] = {name:data.name,version:v,gitHead:sha}; data.time[v] = time;
+ if (hasTag) refs.set(v,sha);
+ }
+ publish('1.0.1-preview.20260101.1',first,'2026-01-01T00:00:00.000Z');
+ publish('1.0.1',second,'2026-01-02T00:00:00.000Z');
+ const fetchImpl = async (url, options) => {
+ const u = new URL(url);
+ assert.ok(options.signal); assert.equal(options.redirect,'error');
+ if (u.hostname === 'registry.npmjs.org') return Response.json(data);
+ assert.equal(u.hostname,'api.github.com'); assert.equal(options.headers.Authorization,'Bearer test-token');
+ const path = u.pathname.replace('/repos/lidge-jun/opencodex','');
+ if (path === '') return Response.json({id:1273824907,full_name:'lidge-jun/opencodex'});
+ if (path === '/commits/dev') return Response.json({sha:control.devSha});
+ if (path === '/tags') return Response.json([...refs].map(([v,sha]) => ({name:`v${v}`,commit:{sha}})));
+ if (path === '/releases') return Response.json([...refs].map(([v]) => ({tag_name:`v${v}`,draft:false,prerelease:v.includes('-preview.'),published_at:data.time[v]})));
+ const m = /^\/git\/ref\/tags\/v(.+)$/.exec(path);
+ if (m) return refs.has(m[1]) ? Response.json({ref:`refs/tags/v${m[1]}`,object:{type:'commit',sha:refs.get(m[1])}}) : new Response('',{status:404});
+ const r = /^\/releases\/tags\/v(.+)$/.exec(path);
+ if (r) return refs.has(r[1]) ? Response.json({tag_name:`v${r[1]}`,draft:false,prerelease:r[1].includes('-preview.'),published_at:'2026-01-01T00:00:00Z'}) : new Response('',{status:404});
+ throw Error(`unexpected mock URL ${url}`);
+ };
+ return {dir, git, commit, control, first, second, candidate, data, refs, publish, fetchImpl, args:{candidateSha:candidate,candidateVersion:'1.0.2',channel:'stable',repoPath:dir,token:'test-token',fetchImpl,mappings:[]}};
+}
+
+test('collector uses live-shaped npm and authenticated GitHub responses with real Git ancestry', async t => {
+ const f = collectorFixture(t);
+ const result = await collectPublicationHistory(f.args);
+ assert.deepEqual(result.floor,{version:'1.0.1',sourceSha:f.second,publishedAt:'2026-01-02T00:00:00.000Z'});
+ assert.deepEqual(result.channels.map(x => x.version),['1.0.1-preview.20260101.1','1.0.1']);
+});
+
+test('collector refuses a newer npm-only source and missing source metadata', async t => {
+ const f = collectorFixture(t);
+ f.publish('1.0.2-preview.20260103.1',f.candidate,'2026-01-03T00:00:00.000Z',false);
+ await assert.rejects(collectPublicationHistory({...f.args,candidateSha:f.second,candidateVersion:'1.0.3'}), /npm-only|rollback|lineage/i);
+ await assert.rejects(collectPublicationHistory({...f.args,candidateVersion:'1.0.3'}), /npm-only.*receipt/i);
+ f.data.versions['1.0.2-preview.20260103.1'].gitHead = '';
+ await assert.rejects(collectPublicationHistory({...f.args,candidateVersion:'1.0.3'}), /gitHead/);
+});
+
+test('collector refuses registry races and mismatched GitHub tag source', async t => {
+ const f = collectorFixture(t);
+ f.refs.set('1.0.1',f.first);
+ await assert.rejects(collectPublicationHistory(f.args), /tag.*gitHead/i);
+ f.refs.set('1.0.1',f.second);
+ let reads = 0;
+ const racingFetch = async (url, options) => {
+ if (new URL(url).hostname === 'registry.npmjs.org' && ++reads === 2) f.data['dist-tags'].next = '1.0.1';
+ return f.fetchImpl(url,options);
+ };
+ await assert.rejects(collectPublicationHistory({...f.args,fetchImpl:racingFetch}), /changed|race/i);
+});
+
+test('collector rejects arbitrary mappings for divergent nonlegacy channel histories', async t => {
+ const f = collectorFixture(t);
+ f.git('checkout','-q','--detach',f.first);
+ const divergent = f.commit('divergent preview');
+ f.git('checkout','-q','--detach',f.candidate);
+ const preview = '1.0.1-preview.20260101.1';
+ f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent);
+ await assert.rejects(collectPublicationHistory({...f.args,mappings:[{version:preview,legacySha:divergent,devSha:f.candidate}]}), /lineage/);
+});
+
+test('collector rejects missing releases, ambiguous timestamps, and missing commit objects', async t => {
+ const f = collectorFixture(t);
+ const missingRelease = async (url, options) => {
+ const res = await f.fetchImpl(url,options);
+ if (new URL(url).pathname.endsWith('/releases')) {
+ const values = await res.json(); return Response.json(values.filter(v => v.tag_name !== 'v1.0.1'));
+ }
+ return res;
+ };
+ await assert.rejects(collectPublicationHistory({...f.args,fetchImpl:missingRelease}), /matching GitHub release/);
+ f.data.time['1.0.1'] = f.data.time['1.0.1-preview.20260101.1'];
+ await assert.rejects(collectPublicationHistory(f.args), /ambiguous.*order/);
+ f.data.time['1.0.1'] = '2026-01-02T00:00:00.000Z';
+ f.data.versions['1.0.1'].gitHead = 'f'.repeat(40); f.refs.set('1.0.1','f'.repeat(40));
+ await assert.rejects(collectPublicationHistory(f.args), /Git source.*unavailable/);
+});
+
+test('collector accepts a strictly superseded historical tag mismatch', async t => {
+ const f = collectorFixture(t);
+ f.publish('1.0.0',f.first,'2025-12-30T00:00:00.000Z');
+ f.refs.set('1.0.0',f.second);
+ assert.equal((await collectPublicationHistory(f.args)).floor.sourceSha,f.second);
+ f.refs.delete('1.0.0'); delete f.data.versions['1.0.0'].gitHead;
+ assert.equal((await collectPublicationHistory(f.args)).floor.sourceSha,f.second);
+});
+
+test('collector still enforces the version floor for superseded publications', async t => {
+ const f = collectorFixture(t);
+ f.publish('1.9.0',f.first,'2025-12-30T00:00:00.000Z');
+ await assert.rejects(collectPublicationHistory(f.args), /candidate version.*1\.9\.0/);
+});
+
+test('collector rejects a mismatch at the older channel floor', async t => {
+ const f = collectorFixture(t);
+ f.refs.set('1.0.1-preview.20260101.1',f.second);
+ await assert.rejects(collectPublicationHistory(f.args), /tag.*gitHead/i);
+});
+
+test('collector rejects an npm-only publication newer than the older channel floor', async t => {
+ const f = collectorFixture(t);
+ f.publish('1.0.0',f.first,'2026-01-01T12:00:00.000Z',false);
+ await assert.rejects(collectPublicationHistory(f.args), /npm-only.*receipt/i);
+});
+
+test('collector refuses an arbitrary legacy mapping even with a future baseline', async t => {
+ const f = collectorFixture(t);
+ f.git('checkout','-q','--detach',f.first);
+ const divergent = f.commit('divergent preview');
+ f.git('checkout','-q','--detach',f.candidate);
+ const future = f.commit('future baseline');
+ const preview = '1.0.1-preview.20260101.1';
+ f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent);
+ const mappings = [{version:preview,legacySha:divergent,devSha:future},{version:'1.0.1',legacySha:f.second,devSha:future}];
+ await assert.rejects(collectPublicationHistory({...f.args,mappings}), /lineage|baseline|ancestor/i);
+});
+
+test('collector accepts a candidate that merges both independently verified channel sources', async t => {
+ const f = collectorFixture(t);
+ f.git('checkout','-q','--detach',f.first);
+ const divergent = f.commit('divergent preview');
+ f.git('checkout','-q','--detach',f.candidate);
+ f.git('-c','user.name=Test','-c','user.email=test@localhost','merge','--no-ff','-qm','merge preview',divergent);
+ const merged = f.git('rev-parse','HEAD');
+ f.control.devSha = merged;
+ const preview = '1.0.1-preview.20260101.1';
+ f.data.versions[preview].gitHead = divergent; f.refs.set(preview,divergent);
+ const result = await collectPublicationHistory({...f.args,candidateSha:merged});
+ assert.equal(result.floor.sourceSha,f.second);
+});
+
+test('collector refuses unknown publication order even for old versions', async t => {
+ const f = collectorFixture(t);
+ f.publish('1.0.0',f.first,'2025-12-30T00:00:00.000Z');
+ delete f.data.time['1.0.0'];
+ await assert.rejects(collectPublicationHistory(f.args), /publication time/);
+});
+
+test('collector reads all GitHub tag pages on both snapshots', async t => {
+ const f = collectorFixture(t);
+ let pageTwo = 0;
+ const paginatedFetch = async (url, options) => {
+ const u = new URL(url);
+ if (u.hostname === 'api.github.com' && u.pathname.endsWith('/tags')) {
+ const real = [...f.refs].map(([v,sha]) => ({name:`v${v}`,commit:{sha}}));
+ const filler = Array.from({length:99},(_,i) => ({name:`archive-${i}`,commit:{sha:f.first}}));
+ const combined = [...real,...filler];
+ const page = Number(u.searchParams.get('page'));
+ if (page === 2) pageTwo++;
+ return Response.json(combined.slice((page-1)*100,page*100));
+ }
+ return f.fetchImpl(url,options);
+ };
+ await collectPublicationHistory({...f.args,fetchImpl:paginatedFetch});
+ assert.equal(pageTwo,2);
+});
+
+test('collector permits preview to stable on the identical source', async t => {
+ const f = collectorFixture(t);
+ delete f.data.versions['1.0.1']; delete f.data.time['1.0.1']; delete f.data['dist-tags'].latest; f.refs.delete('1.0.1');
+ const result = await collectPublicationHistory({...f.args,candidateSha:f.first,candidateVersion:'1.0.1'});
+ assert.equal(result.floor.sourceSha,f.first);
+});
+
+test('collector rejects GitHub API failures and requires authentication', async t => {
+ const f = collectorFixture(t);
+ await assert.rejects(collectPublicationHistory({...f.args,token:''}), /GH_TOKEN/);
+ const fetchImpl = async (url, options) => new URL(url).pathname.endsWith('/tags') ? new Response('',{status:403}) : f.fetchImpl(url,options);
+ await assert.rejects(collectPublicationHistory({...f.args,fetchImpl}), /GitHub evidence request failed \(403\)/);
+});
+
+test('fixed stable and preview legacy trees differ from dev baseline only by verified version values', () => {
+ const baseline = '0627a2c255bc239d5748119f1d0bc4457a1c03e3';
+ for (const [sourceSha,sourceVersion] of [['667662903a6c139524506667d12656d9ad50fad0','2.99.0'],['68eee1eb804445ad86fe942b734060f323eb1517','2.99.0-preview.20261108']]) {
+ assert.equal(verifyLegacyTreeEvidence({repoPath:resolve(__dirname,'../..'),sourceSha,baselineSha:baseline,sourceVersion,baselineVersion:'2.100.0',candidateSha:baseline,devSha:baseline}),true);
+ }
+});
+
+test('collector verifies both fixed legacy sources and refuses a forged legacy SHA', async t => {
+ const f = collectorFixture(t);
+ const baseline = '0627a2c255bc239d5748119f1d0bc4457a1c03e3';
+ const stable = '667662903a6c139524506667d12656d9ad50fad0', preview = '68eee1eb804445ad86fe942b734060f323eb1517';
+ f.data.versions = {}; f.data.time = {}; f.refs.clear(); f.control.devSha = baseline;
+ f.publish('2.99.0-preview.20261108',preview,'2026-01-01T00:00:00.000Z');
+ f.publish('2.99.0',stable,'2026-01-02T00:00:00.000Z');
+ f.data['dist-tags'] = {preview:'2.99.0-preview.20261108',latest:'2.99.0'};
+ const args = {...f.args,repoPath:resolve(__dirname,'../..'),candidateSha:baseline,candidateVersion:'2.100.0'};
+ assert.equal((await collectPublicationHistory(args)).floor.sourceSha,stable);
+ f.data.versions['2.99.0'].gitHead = baseline; f.refs.set('2.99.0',baseline);
+ await assert.rejects(collectPublicationHistory(args), /fixed expected SHA/);
+});
+
+test('legacy tree evidence rejects other changes, wrong version values, and an uncontained baseline', t => {
+ const dir = mkdtempSync(join(tmpdir(),'ocx-legacy-evidence-'));
+ t.after(() => rmSync(dir,{recursive:true,force:true}));
+ const git = (...args) => execFileSync('git',['-C',dir,...args],{encoding:'utf8',stdio:['ignore','pipe','pipe']}).trim();
+ git('init','-q'); mkdirSync(join(dir,'desktop/src-tauri'),{recursive:true});
+ const write = (version,extra = '') => {
+ writeFileSync(join(dir,'package.json'),JSON.stringify({name:'fixture',version})+'\n');
+ writeFileSync(join(dir,'desktop/src-tauri/tauri.conf.json'),JSON.stringify({version})+'\n');
+ writeFileSync(join(dir,'desktop/src-tauri/Cargo.toml'),`[package]\nname = "opencodex-desktop"\nversion = "${version}"\n${extra}`);
+ writeFileSync(join(dir,'desktop/src-tauri/Cargo.lock'),`[[package]]\nname = "opencodex-desktop"\nversion = "${version}"\n`);
+ };
+ const commit = msg => {git('add','.');git('-c','user.name=Test','-c','user.email=test@localhost','commit','-qm',msg);return git('rev-parse','HEAD');};
+ write('1.0.0'); const sourceSha = commit('source');
+ write('1.1.0'); const baselineSha = commit('baseline');
+ const args = {repoPath:dir,sourceSha,baselineSha,sourceVersion:'1.0.0',baselineVersion:'1.1.0',candidateSha:baselineSha,devSha:baselineSha};
+ assert.equal(verifyLegacyTreeEvidence(args),true);
+ assert.throws(() => verifyLegacyTreeEvidence({...args,sourceVersion:'1.0.1'}), /version/);
+ assert.throws(() => verifyLegacyTreeEvidence({...args,candidateSha:sourceSha}), /baseline.*candidate/i);
+ assert.throws(() => verifyLegacyTreeEvidence({...args,devSha:sourceSha}), /baseline.*dev/i);
+ write('1.1.0','description = "unexpected"\n'); const changedFile = commit('other content');
+ assert.throws(() => verifyLegacyTreeEvidence({...args,baselineSha:changedFile,candidateSha:changedFile,devSha:changedFile}), /version|content/i);
+ writeFileSync(join(dir,'extra.txt'),'unexpected\n'); const extraPath = commit('extra path');
+ assert.throws(() => verifyLegacyTreeEvidence({...args,baselineSha:extraPath,candidateSha:extraPath,devSha:extraPath}), /paths|diff/i);
+});
diff --git a/.github/scripts/release-resume.cjs b/.github/scripts/release-resume.cjs
new file mode 100755
index 0000000000..0106bdbf19
--- /dev/null
+++ b/.github/scripts/release-resume.cjs
@@ -0,0 +1,124 @@
+#!/usr/bin/env node
+'use strict';
+
+// The operator attests that this version was published from this source.
+// Registry metadata and GitHub state are consistency checks, not provenance.
+// Call from trusted workflow code with the release lock held; repeat immediately
+// before release creation and asset attachment. This helper never publishes npm.
+// Asset receipts must come from the trusted verify-release job in this workflow;
+// this helper does not authenticate an arbitrary receipt file.
+const { lstatSync, readFileSync } = require('node:fs');
+const { isDeepStrictEqual } = require('node:util');
+const { compareVersions } = require('./release-history.cjs');
+const REPO = 'lidge-jun/opencodex';
+const PACKAGE = '@bitkyc08/opencodex';
+const API = `https://api.github.com/repos/${REPO}`;
+const REGISTRY = 'https://registry.npmjs.org/%40bitkyc08%2Fopencodex';
+const SHA = /^[a-f0-9]{40}$/, DIGEST = /^[a-f0-9]{64}$/;
+const VERSION = /^(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)\.(?:0|[1-9]\d*)(?:-preview\.\d{8}\.\d+)?$/;
+function must(condition, message) { if (!condition) throw new Error(message); }
+function timestamp(value) {
+ const time = Date.parse(value);
+ must(typeof value === 'string' && Number.isFinite(time) && new Date(time).toISOString() === value, 'invalid npm publication time');
+ return time;
+}
+async function requestJson(fetchImpl,url,token,allow404 = false) {
+ const github = url.startsWith(API + '/');
+ must(github || url === REGISTRY, 'unexpected evidence endpoint');
+ let response;
+ try {
+ response = await fetchImpl(url,{headers:github ? {Authorization:`Bearer ${token}`,Accept:'application/vnd.github+json','X-GitHub-Api-Version':'2022-11-28'} : {Accept:'application/json'},redirect:'error',cache:'no-store',signal:AbortSignal.timeout(30000)});
+ } catch { throw new Error('evidence request failed'); }
+ if (allow404 && response.status === 404) return null;
+ must(response.ok, `evidence request failed (${response.status})`);
+ const length = response.headers.get('content-length');
+ must(!length || (/^\d+$/.test(length) && Number(length) <= 20*1024*1024), 'evidence too large');
+ let size = 0; const chunks = [];
+ must(response.body, 'empty evidence response');
+ for await (const chunk of response.body) { size += chunk.length; must(size <= 20*1024*1024, 'evidence too large'); chunks.push(chunk); }
+ try { return JSON.parse(Buffer.concat(chunks,size).toString('utf8')); }
+ catch { throw new Error('invalid JSON evidence'); }
+}
+async function pages(fetchImpl,token,path) {
+ const result=[];
+ for (let page=1;page<=100;page++) {
+ const list=await requestJson(fetchImpl,`${API}/${path}?per_page=100&page=${page}`,token);
+ must(Array.isArray(list) && list.length<=100, 'invalid GitHub pagination');
+ result.push(...list);
+ if (list.length<100) return result;
+ }
+ throw new Error('GitHub pagination limit exceeded');
+}
+function registryCheck(data,version,sourceSha,now) {
+ must(data?.name===PACKAGE && data.versions && typeof data.versions==='object' && !Array.isArray(data.versions) && data.time && typeof data.time==='object' && data['dist-tags'] && typeof data['dist-tags']==='object' && !Array.isArray(data['dist-tags']), 'invalid npm history');
+ const entries=Object.entries(data.versions);
+ must(entries.length>0 && entries.length<=10000 && Object.hasOwn(data.versions,version), 'npm version is missing');
+ const published=timestamp(data.time[version]); must(published<=now,'future npm publication');
+ for (const [v,metadata] of entries) {
+ must(metadata?.name===PACKAGE && metadata.version===v, 'invalid npm version identity');
+ const time=timestamp(data.time[v]);
+ must(time<=now && (v===version || time0, 'empty verified asset receipt');
+ for (const name of names) must(name && name!=='.' && name!=='..' && !/[\x00-\x1f\x7f/\\]/.test(name) && DIGEST.test(expected[name]), 'invalid verified asset receipt');
+ for (const asset of assets) {
+ must(asset && typeof asset.name==='string' && !seen.has(asset.name) && Object.hasOwn(expected,asset.name) && asset.state==='uploaded' && asset.digest===`sha256:${expected[asset.name]}`, 'existing release asset mismatch');
+ seen.add(asset.name);
+ }
+ const missing=names.filter(name=>!seen.has(name)).sort();
+ must(!release || release.draft || missing.length===0, 'published release missing verified assets');
+ return {reuseAssets:[...seen].sort(),missingAssets:missing};
+}
+async function collectResumeDecision({version,sourceSha,channel,token,fetchImpl=fetch,now=Date.now,assetReceipt}) {
+ must(typeof version==='string' && VERSION.test(version) && SHA.test(sourceSha || '') && channel===(version.includes('-')?'preview':'stable'), 'explicit version, source and matching channel are required');
+ must(typeof token==='string' && token.length>0 && typeof fetchImpl==='function', 'GH_TOKEN is required');
+ const clock=now(); must(Number.isFinite(clock), 'invalid clock');
+ const read=async()=> {
+ const [registry,tags,release]=await Promise.all([
+ requestJson(fetchImpl,REGISTRY,token),pages(fetchImpl,token,'tags'),
+ requestJson(fetchImpl,`${API}/releases/tags/v${version}`,token,true),
+ ]);
+ registryCheck(registry,version,sourceSha,clock);
+ const tagExists=tagCheck(tags,version,sourceSha);
+ if (release!==null) must(Number.isSafeInteger(release.id) && release.id>0 && release.tag_name===`v${version}` && typeof release.draft==='boolean' && release.prerelease===(channel==='preview'), 'invalid GitHub release evidence');
+ const assets=assetReceipt!==undefined && release ? await pages(fetchImpl,token,`releases/${release.id}/assets`) : [];
+ return {registry,tags,release,assets,tagExists};
+ };
+ const first=await read(), second=await read();
+ must(isDeepStrictEqual(first,second), 'publication evidence changed while checking');
+ const result={version,sourceSha,channel,publishNpm:false,tagExists:first.tagExists,releaseExists:first.release!==null,assetsChecked:assetReceipt!==undefined};
+ if (assetReceipt!==undefined) Object.assign(result,checkAssets(assetReceipt,first.release,first.assets,version,sourceSha));
+ return result;
+}
+async function main() {
+ const [command,version,sourceSha,channel,receiptPath,...extra]=process.argv.slice(2);
+ must((command==='check' && !receiptPath && !extra.length) || (command==='check-assets' && receiptPath && !extra.length), 'usage: release-resume.cjs check | check-assets ');
+ let assetReceipt;
+ if (command==='check-assets') {
+ const stat=lstatSync(receiptPath); must(stat.isFile() && !stat.isSymbolicLink() && stat.size<=1024*1024, 'invalid verified receipt file');
+ assetReceipt=JSON.parse(readFileSync(receiptPath,'utf8'));
+ }
+ const result=await collectResumeDecision({version,sourceSha,channel,token:process.env.GH_TOKEN,assetReceipt});
+ process.stdout.write(JSON.stringify(result)+'\n');
+}
+if (require.main===module) main().catch(error=>{console.error(error.message);process.exitCode=1;});
+module.exports={collectResumeDecision};
diff --git a/.github/scripts/release-resume.test.cjs b/.github/scripts/release-resume.test.cjs
new file mode 100644
index 0000000000..0ad20d2ff4
--- /dev/null
+++ b/.github/scripts/release-resume.test.cjs
@@ -0,0 +1,112 @@
+'use strict';
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const { mkdtempSync, writeFileSync, rmSync } = require('node:fs');
+const { tmpdir } = require('node:os');
+const { join } = require('node:path');
+const { spawnSync } = require('node:child_process');
+const { collectResumeDecision } = require('./release-resume.cjs');
+const packageName = '@bitkyc08/opencodex', sourceSha = 'a'.repeat(40), version = '2.100.1';
+const assetDigest = 'b'.repeat(64);
+function fixture() {
+ const data = {
+ registry:{name:packageName,versions:{[version]:{name:packageName,version,gitHead:sourceSha}},time:{[version]:'2026-01-01T00:00:00.000Z'},'dist-tags':{latest:version}},
+ tags:[{name:`v${version}`,commit:{sha:sourceSha}}],
+ release:null,
+ receipt:{version,sha:sourceSha,repo:'lidge-jun/opencodex',assets:{'ocx.zip':assetDigest}},
+ };
+ const fetchImpl = async (url,options) => {
+ assert.equal(options.method,undefined);
+ if (url === 'https://registry.npmjs.org/%40bitkyc08%2Fopencodex') { assert.equal(options.headers.Authorization,undefined); return Response.json(data.registry); }
+ assert.equal(options.headers.Authorization,'Bearer token');
+ if (url.endsWith('/tags?per_page=100&page=1')) return Response.json(data.tags);
+ if (url.endsWith(`/releases/tags/v${version}`)) return data.release === null ? new Response('',{status:404}) : Response.json(data.release);
+ if (url.endsWith('/releases/99/assets?per_page=100&page=1')) return Response.json(data.release.assets);
+ throw Error(`unexpected URL ${url}`);
+ };
+ return {data,args:{version,sourceSha,channel:'stable',token:'token',fetchImpl,now:()=>Date.parse('2026-01-02T00:00:00Z')}};
+}
+test('explicit attested version and source produce a resume decision without npm publication', async () => {
+ const f=fixture();
+ assert.deepEqual(await collectResumeDecision(f.args),{version,sourceSha,channel:'stable',publishNpm:false,tagExists:true,releaseExists:false,assetsChecked:false});
+});
+test('missing tag is allowed but wrong or unknown metadata is rejected', async () => {
+ const f=fixture(); f.data.tags=[];
+ assert.equal((await collectResumeDecision(f.args)).tagExists,false);
+ for (const change of [
+ f=>f.data.registry.versions[version].gitHead='c'.repeat(40),
+ f=>delete f.data.registry.versions[version],
+ f=>f.data.registry.versions[version].version='2.100.0',
+ f=>f.data.tags[0].commit.sha='c'.repeat(40),
+ f=>f.data.tags[0].commit.sha=null,
+ f=>delete f.data.registry.time[version],
+ f=>f.args.channel='preview',
+ f=>f.args.sourceSha='',
+ ]) { const x=fixture(); change(x); await assert.rejects(collectResumeDecision(x.args)); }
+});
+test('newer npm publication or git tag blocks rollback', async () => {
+ for (const change of [
+ f=>{f.data.registry.versions['2.100.2']={name:packageName,version:'2.100.2',gitHead:'c'.repeat(40)}; f.data.registry.time['2.100.2']='2026-01-01T01:00:00.000Z';},
+ f=>{f.data.registry.versions['2.100.0']={name:packageName,version:'2.100.0',gitHead:'c'.repeat(40)}; f.data.registry.time['2.100.0']='2026-01-01T01:00:00.000Z';},
+ f=>{f.data.tags.push({name:'v2.100.2',commit:{sha:sourceSha}});},
+ ]) { const f=fixture(); change(f); await assert.rejects(collectResumeDecision(f.args),/floor|rollback/i); }
+});
+test('existing release assets can only be reused against a matching verified receipt', async () => {
+ const f=fixture();
+ f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[{name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`}]};
+ const decision=await collectResumeDecision({...f.args,assetReceipt:f.data.receipt});
+ assert.equal(decision.publishNpm,false); assert.deepEqual(decision.reuseAssets,['ocx.zip']); assert.deepEqual(decision.missingAssets,[]);
+ f.data.release.assets[0].digest='sha256:'+'c'.repeat(64);
+ await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i);
+ f.data.release.assets[0].digest=`sha256:${assetDigest}`;
+ await assert.rejects(collectResumeDecision({...f.args,assetReceipt:{...f.data.receipt,sha:'c'.repeat(40)}}),/receipt/i);
+});
+test('draft may upload missing verified assets; published release cannot be missing them', async () => {
+ const f=fixture(); f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[]};
+ const result=await collectResumeDecision({...f.args,assetReceipt:f.data.receipt});
+ assert.deepEqual(result.missingAssets,['ocx.zip']);
+ f.data.release.draft=false;
+ await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/missing/i);
+});
+test('unknown and duplicate release assets and changing registry evidence are rejected', async () => {
+ const f=fixture();
+ const asset={name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`};
+ f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[asset,asset]};
+ await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i);
+ f.data.release.assets=[{...asset,name:'unknown.zip'}];
+ await assert.rejects(collectResumeDecision({...f.args,assetReceipt:f.data.receipt}),/asset/i);
+ const g=fixture(); let reads=0; const original=g.args.fetchImpl;
+ g.args.fetchImpl=async (...args)=>{
+ if (args[0].startsWith('https://registry.npmjs.org/') && ++reads===2) g.data.registry['dist-tags'].preview=version;
+ return original(...args);
+ };
+ await assert.rejects(collectResumeDecision(g.args),/changed/i);
+});
+test('a newer tag on a later GitHub API page blocks resume', async () => {
+ const f=fixture(), original=f.args.fetchImpl;
+ f.args.fetchImpl=async (url,options)=>{
+ if (url.endsWith('/tags?per_page=100&page=1')) return Response.json(Array.from({length:100},(_,i)=>({name:`old-${i}`,commit:{sha:sourceSha}})));
+ if (url.endsWith('/tags?per_page=100&page=2')) return Response.json([{name:'v2.100.2',commit:{sha:sourceSha}}]);
+ return original(url,options);
+ };
+ await assert.rejects(collectResumeDecision(f.args),/tag floor/);
+});
+test('CLI consumes explicit version and source and prints the no-publish decision', () => {
+ const f=fixture(), dir=mkdtempSync(join(tmpdir(),'resume-cli-'));
+ try {
+ const fixturePath=join(dir,'fixture.json'), preload=join(dir,'preload.cjs');
+ writeFileSync(fixturePath,JSON.stringify(f.data));
+ writeFileSync(preload,`const d=require(${JSON.stringify(fixturePath)}); global.fetch=async (u,o)=>{if(o.method) throw Error('unexpected method'); if(u.startsWith('https://registry.npmjs.org/')) return Response.json(d.registry); if(u.includes('/tags?')) return Response.json(d.tags); if(u.includes('/releases/tags/')) return d.release ? Response.json(d.release) : new Response('',{status:404}); if(u.includes('/releases/99/assets?')) return Response.json(d.release.assets); throw Error('unexpected request');};`);
+ const run=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check',version,sourceSha,'stable'],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}});
+ assert.equal(run.status,0,run.stderr);
+ assert.deepEqual(JSON.parse(run.stdout),{version,sourceSha,channel:'stable',publishNpm:false,tagExists:true,releaseExists:false,assetsChecked:false});
+ f.data.release={id:99,tag_name:`v${version}`,draft:true,prerelease:false,assets:[{name:'ocx.zip',state:'uploaded',digest:`sha256:${assetDigest}`}]};
+ writeFileSync(fixturePath,JSON.stringify(f.data));
+ const receiptPath=join(dir,'receipt.json'); writeFileSync(receiptPath,JSON.stringify(f.data.receipt));
+ const assets=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check-assets',version,sourceSha,'stable',receiptPath],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}});
+ assert.equal(assets.status,0,assets.stderr);
+ assert.deepEqual(JSON.parse(assets.stdout).reuseAssets,['ocx.zip']);
+ const invalid=spawnSync(process.execPath,['--require',preload,join(__dirname,'release-resume.cjs'),'check',version,'','stable'],{encoding:'utf8',env:{...process.env,GH_TOKEN:'token'}});
+ assert.equal(invalid.status,1); assert.equal(invalid.stdout,'');
+ } finally {rmSync(dir,{recursive:true,force:true});}
+});
diff --git a/.github/workflows/catalog-async-contracts.yml b/.github/workflows/catalog-async-contracts.yml
index eb6f033500..b35e4286cb 100644
--- a/.github/workflows/catalog-async-contracts.yml
+++ b/.github/workflows/catalog-async-contracts.yml
@@ -1,15 +1,6 @@
name: Catalog async contracts
on:
- push:
- branches: [main, preview]
- paths:
- - src/**
- - scripts/diagnostics/windows-version-control/**
- - .github/actions/setup-project-bun/**
- - .github/workflows/catalog-async-contracts.yml
- - package.json
- - bun.lock
pull_request:
paths:
- src/**
@@ -28,15 +19,30 @@ concurrency:
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
jobs:
+ validate-source:
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - name: Validate dispatch source
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ REF: ${{ github.ref }}
+ run: |
+ if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then
+ echo '::error::manual catalog contracts must run from dev'
+ exit 1
+ fi
+
contracts:
+ needs: validate-source
name: Catalog async contracts (${{ matrix.os }})
runs-on: ${{ matrix.os }}
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
- # Pull requests run the ubuntu leg only; macos and windows run on push
- # to main/preview and on manual dispatch.
+ # Pull requests run the ubuntu leg only; macos and windows run on manual dispatch.
os: ${{ fromJSON(github.event_name == 'pull_request' && '["ubuntu-latest"]' || '["ubuntu-latest","macos-latest","windows-latest"]') }}
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index 2df7ddab92..dc5496ad7e 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -1,12 +1,13 @@
# ============================================================================
# CI POLICY (maintainer decision — do not change in a contributor PR)
-# * Pull requests run ONLY the fast Ubuntu subset.
+# * Pull requests run ONLY the fast Ubuntu subset (default: gates + `test changed`).
# * Full cross-platform (macOS/Windows) CI runs ONLY via manual
-# workflow_dispatch and on push to main/preview (release lines).
-# * NEVER add a dev push trigger or pull_request runs for macOS/Windows jobs.
+# workflow_dispatch on dev.
+# * NEVER add a push trigger or pull_request runs for macOS/Windows jobs.
# PRs that change this policy will be closed. See AGENTS.md "CI policy".
# ============================================================================
name: Cross-platform CI
+run-name: ocx-ci-v1 lane=${{ github.event.inputs.lane || 'all' }} sha=${{ github.sha }}
on:
# Always create the aggregate `ci` check for pull requests. Expensive jobs
@@ -14,7 +15,7 @@ on:
# docs-only PR receives explicit positive evidence instead of no check at all.
pull_request: {}
# No base-branch filter on purpose. GitHub matches `branches:` against the
- # BASE ref, so `[main, dev]` silently excluded stacked child PRs — whose
+ # BASE ref, so even `[dev]` would silently exclude stacked child PRs — whose
# base is another open PR's head branch, an intentional review workflow per
# AGENTS.md that `enforce-target` already exempts from the wrong-base gate.
# The #951-#955 stack merged with `enforce-target`, `label`, and
@@ -24,79 +25,25 @@ on:
# An allowlist cannot express "base is another PR's head" — stacked bases
# carry contributor prefixes (`fix/`, `feat/`, `agent/`) as readily as
# `codex/`, and contributor stacks need CI most. The `changes` job below is
- # the real scope gate, using the same allowlist as the push trigger. Safe to
- # widen here
- # because this workflow is `pull_request` (not `pull_request_target`),
+ # the real scope gate for expensive jobs. Safe to
+ # widen here because this workflow is `pull_request` (not `pull_request_target`),
# declares `contents: read`, and reads no secrets.
#
- #
- # Pull requests run only the fast Ubuntu subset. Every macOS and Windows
- # job (and the macOS/Windows legs of the keyring, npm-global, setup-action
- # and remote-helper matrices) is skipped on `pull_request` and runs after
- # merge instead, via workflow_dispatch, the main/preview `push:` below and
- # the nightly schedule.
- #
- # `push:` is pinned to the release lines. dev is deliberately absent:
- # cross-platform evidence for dev is run by hand via workflow_dispatch.
- # main and preview MUST stay: release.yml requires a successful push-event
- # Cross-platform CI run for the exact release SHA and states that a
- # pull-request run does not qualify, so removing either branch breaks
- # publication.
- push:
- branches: [main, preview]
- paths:
- - "Dockerfile"
- - "compose.yaml"
- - ".dockerignore"
- - "docker/**"
- - "src/**"
- - "bin/**"
- - "tests/**"
- - "scripts/**"
- - "app/**"
- - "desktop/**"
- - "gui/**"
- - "assets/**"
- - ".github/scripts/**"
- - ".github/workflows/**"
- - ".gitattributes"
- - ".npmignore"
- - "package.json"
- - "bun.lock"
- - "tsconfig.json"
- - "README.md"
- - "readme/**"
- - "skills/**"
- - ".github/ISSUE_TEMPLATE/**"
- - "LICENSE"
+ # Pull requests run only the fast Ubuntu subset. Cross-platform jobs run
+ # after merge by a manual workflow_dispatch on dev.
workflow_dispatch:
inputs:
lane:
- description: "all (default), release-gates, or macos-control"
+ description: "all (default), release-gates, macos-control, or windows-native-claim"
type: choice
default: all
- options: [all, release-gates, macos-control]
- # Nightly safety net. The Windows shards run on a pull request only when the
- # changes job judges it Windows-sensitive, so anything that slips past that
- # filter must still be caught within a day: a scheduled run requests the full
- # lane=all matrix (nine Windows shards and the macOS control included).
- #
- # GitHub runs schedules from the DEFAULT branch, which is main, so this
- # trigger activates only once this file reaches main by promotion, and the
- # workflow definition is main's. Every test checkout reads
- # needs.changes.outputs.checkout_ref, which the changes job resolves to ONE
- # dev commit on a schedule, so the run tests dev and every job tests the same
- # SHA. Its check runs attach to main's head commit; release.yml accepts only a
- # push-event run, so a scheduled run can never qualify a release.
- schedule:
- - cron: "17 18 * * *"
+ options: [all, release-gates, macos-control, windows-native-claim]
permissions:
contents: read
-# Retrigger CI after dir-fsync / oauth deadline follow-ups (tip 34a1ac46).
concurrency:
- # `push` and `pull_request` want supersession: a newer head on the same ref
+ # Pull requests want supersession: a newer head on the same ref
# makes the older one irrelevant, and cancelling it saves an hour of runners
# for an answer nobody will read.
#
@@ -116,9 +63,8 @@ concurrency:
# cancels nothing and nothing cancels it, including a second dispatch of the
# same ref.
#
- # A scheduled run is keyed the same way. Keyed on the ref it would share
- # refs/heads/main with a promotion push and, with cancel-in-progress, cancel
- # the very run release.yml waits for.
+ # The schedule branch of this expression is retained for selector compatibility;
+ # this workflow no longer declares a schedule trigger.
group: cross-platform-ci-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.event_name == 'schedule' && github.run_id || github.ref }}
cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' && github.event_name != 'schedule' }}
@@ -147,12 +93,8 @@ jobs:
# honest pull requests on GitHub-hosted runners and lets trusted branch runs
# avoid the hosted-Windows Bun crashes. It is not the security boundary.
#
- # `push` on main/preview requires the push permission, and
- # `workflow_dispatch` requires write access, so both carry a trusted author.
- # A schedule runs main's workflow against a dev commit that already merged
- # through review, the same trust as a push.
- # A trusted author is not audited code: merging a contributor PR into `dev`
- # fires `push`, and its dependencies and postinstall hooks then run here.
+ # `workflow_dispatch` requires write access, but a trusted author does not
+ # make candidate dependencies or postinstall hooks independently audited.
select-windows-runner:
name: select windows runner
runs-on: ubuntu-latest
@@ -161,6 +103,17 @@ jobs:
runner: ${{ steps.pick.outputs.runner }}
label: ${{ steps.pick.outputs.label }}
steps:
+ # This job also runs when the diagnostic lane skips changes.
+ - name: Validate dispatch source
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ REF: ${{ github.ref }}
+ run: |
+ if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then
+ echo '::error::manual cross-platform CI must run from dev'
+ exit 1
+ fi
- name: Pick runner
id: pick
env:
@@ -191,7 +144,7 @@ jobs:
echo 'label=windows-latest' >> "$GITHUB_OUTPUT"
fi
- # Which areas this push actually touches.
+ # Which areas the pull request actually touches.
#
# Deliberately a job-level filter rather than a wider workflow-level `paths:`
# one. A workflow skipped by path filtering leaves its checks Pending forever,
@@ -200,6 +153,7 @@ jobs:
# in the `on:` block above.
changes:
name: changes
+ if: github.event_name != 'workflow_dispatch' || github.event.inputs.lane != 'windows-native-claim'
runs-on: ubuntu-latest
timeout-minutes: 5
# The workflow grants only `contents: read`, and specifying any permission
@@ -216,24 +170,27 @@ jobs:
# of silently making every expensive job skip.
ci: ${{ steps.scope.outputs.ci }}
desktop: ${{ steps.scope.outputs.desktop }}
+ fast: ${{ steps.lane.outputs.fast }} # true: `test changed` replaces the five shards
native: ${{ steps.matrices.outputs.native }}
# Matrix include lists for keyring-smoke and npm-global-smoke, built and
# shape-checked by the same validation step as `native`.
keyring_matrix: ${{ steps.matrices.outputs.keyring_matrix }}
npm_global_matrix: ${{ steps.matrices.outputs.npm_global_matrix }}
- # A scheduled run starts from main, so its path filter diffs main and would
- # scope jobs by the wrong commit. The nightly safety net selects every scope
- # instead, here and in the validation steps below, so it is the full matrix.
- gui: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.gui }}
- packaging: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.packaging }}
- docs: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.docs }}
- structure: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.structure }}
+ # A full manual dispatch selects every scope regardless of path filters.
+ gui: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.gui }}
+ packaging: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.packaging }}
+ docs: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.docs }}
+ structure: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.structure }}
# Narrow scopes for two paths the ci filter leaves out on purpose. Both are re-emitted by the
# validation step below, so a malformed filter output fails this job instead of silently
# skipping the check it selects.
setup_action: ${{ steps.narrow.outputs.setup_action }}
remote_helper: ${{ steps.narrow.outputs.remote_helper }}
- # Whether this pull request needs the nine Windows shards: the windows path
+ # Pull-request scope for the two smoke jobs that used to ride the whole ci filter.
+ # Manual dispatch runs both regardless; see the docker/keyring filters.
+ docker: ${{ steps.narrow.outputs.docker }}
+ keyring: ${{ steps.narrow.outputs.keyring }}
+ # Whether this pull request needs the Windows shards: the windows path
# filter below OR an added src/tests line naming a Windows marker. Computed
# by scripts/ci/windows-sensitive-diff.sh, which validates its input and
# treats the diff as data.
@@ -242,6 +199,16 @@ jobs:
# except on a schedule, where it is the one dev SHA resolved below.
checkout_ref: ${{ steps.nightly.outputs.checkout_ref }}
steps:
+ - name: Validate dispatch source
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ REF: ${{ github.ref }}
+ run: |
+ if [ "$EVENT_NAME" = workflow_dispatch ] && [ "$REF" != refs/heads/dev ]; then
+ echo '::error::manual cross-platform CI must run from dev'
+ exit 1
+ fi
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
@@ -258,17 +225,18 @@ jobs:
uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3.0.2
with:
# Without this the action compares against the repository's DEFAULT
- # branch, which is `main`. A push to `dev` would then be diffed against
- # `main`, so every area touched since the last promotion keeps reading
- # as "changed" — the scoped jobs would run on nearly every dev push and
- # the saving would silently not happen while CI stayed green.
+ # branch, which is `dev`. For a non-PR event that diff starts at
+ # `dev` itself, so every area touched since the branch point keeps
+ # reading as "changed" — the scoped jobs would run on nearly every
+ # such event and the saving would silently not happen while CI stayed
+ # green.
#
# On `pull_request` the action ignores this and uses the PR's own file
- # list. On a branch push it means "compare against the previous commit
- # on this branch", which is the intent.
+ # list. Otherwise `github.ref` keeps the diff scoped to this ref, which
+ # is the intent.
base: ${{ github.ref }}
filters: |
- # Mirrors the push trigger's path allowlist. Pull requests always
+ # Pull requests always
# start the workflow so the aggregate check exists, while these
# paths decide whether the expensive test jobs need to run.
ci:
@@ -323,8 +291,7 @@ jobs:
# assembled or launched: the shell itself, the standalone sidecar build
# and its runtime locator, the native keyring staging, and the dependency
# set. Ordinary src/** and gui/** changes no longer select it on a pull
- # request; they are still covered on every promotion push to main and
- # preview and by workflow_dispatch, which always request this job.
+ # request; a full manual dispatch requests this job after merge.
# The workflow names itself so edits to this lane cannot skip their own E2E.
desktop:
- 'desktop/**'
@@ -339,11 +306,11 @@ jobs:
- '.github/workflows/ci.yml'
# The docs site is built by nothing else on a pull request. `ci` above
# deliberately omits `docs-site/**` -- a prose edit has no business
- # starting the cross-platform suite -- and `deploy-docs.yml` triggers
- # only on `push` to `main`. That left the Astro toolchain with no
- # pull-request build gate at all, so a dependency bump under
- # `docs-site/` could only be proven by an author's local run and would
- # otherwise surface at promotion.
+ # starting the cross-platform suite -- and `deploy-docs.yml` is
+ # dispatch-only. That left the Astro toolchain with no pull-request
+ # build gate at all, so a dependency bump under `docs-site/` could
+ # only be proven by an author's local run and would otherwise surface
+ # at release time.
#
# `.github/workflows/ci.yml` is here so an edit to the job below
# verifies itself. Without it this filter's own pull request would
@@ -367,11 +334,8 @@ jobs:
# `.github/workflows/ci.yml` is listed for the same reason `docs`
# lists it: without it this filter's own pull request would skip the
# job it adds.
- # This list stays PULL-REQUEST scope only, like `docs` above: the
- # push trigger's `paths:` is pinned to mirror `ci` exactly, and
- # `dev`, `main` and `preview` are all protected to require a pull
- # request, so every `structure/` change is read at the pull request
- # before it can reach an integration line.
+ # This list keeps pull-request scope narrow; full manual dispatches
+ # also select the structure gate.
structure:
- 'structure/**'
- '.github/workflows/ci.yml'
@@ -388,7 +352,44 @@ jobs:
# real only on macOS and Windows, so its job lints and tests the crate on all three.
remote_helper:
- 'native/remote-workspace-helper/**'
- # Paths whose change selects the nine Windows suite shards on a pull
+ # docker-smoke and keyring-smoke on a pull request. Both used to run on every PR the
+ # ci filter matched, which is nearly all of them, while each proves something narrow:
+ # the image builds, starts and survives recreation with its volume; the OS keyring
+ # binding creates, reads and deletes a secret. A pull request now runs each only when
+ # its own inputs move. Manual dispatch requests both unconditionally.
+ # ci.yml is listed so an edit to either job verifies itself. The setup action is left to
+ # its own setup-action job, as the docs and structure filters leave it.
+ docker:
+ - 'Dockerfile'
+ - 'compose.yaml'
+ - '.dockerignore'
+ - 'docker/**'
+ - 'scripts/ci/docker-smoke.ts'
+ - 'scripts/generate-compatibility-version.ts'
+ - 'scripts/model-metadata.source.json'
+ # The image copies and runs src/, then builds the GUI with tsc and Vite.
+ # Include their inputs without selecting GUI tests or documentation alone.
+ - 'src/**'
+ - 'package.json'
+ - 'bun.lock'
+ - 'tsconfig.json'
+ - 'gui/package.json'
+ - 'gui/bun.lock'
+ - 'gui/src/**'
+ - 'gui/public/**'
+ - 'gui/index.html'
+ - 'gui/vite.config.ts'
+ - 'gui/tsconfig*.json'
+ - '.github/workflows/ci.yml'
+ # scripts/keyring-smoke.ts imports only src/lib/keyring-native.ts; the native binding
+ # itself arrives through package.json and bun.lock.
+ keyring:
+ - 'src/lib/keyring-native.ts'
+ - 'scripts/keyring-smoke.ts'
+ - 'package.json'
+ - 'bun.lock'
+ - '.github/workflows/ci.yml'
+ # Paths whose change selects the Windows suite shards on a pull
# request. These carry the Windows service, update, shim, intercept,
# ACL and process code, and the harness every Windows shard runs.
# scripts/ci/windows-sensitive-diff.sh adds the content markers.
@@ -439,8 +440,8 @@ jobs:
id: scope
shell: bash
env:
- CI_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.ci }}
- DESKTOP_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.desktop }}
+ CI_SCOPE: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.ci }}
+ DESKTOP_SCOPE: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.desktop }}
run: |
set -euo pipefail
case "$CI_SCOPE" in
@@ -466,7 +467,7 @@ jobs:
id: matrices
shell: bash
env:
- NATIVE_SELECTED: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.native }}
+ NATIVE_SELECTED: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.native }}
EVENT_NAME: ${{ github.event_name }}
run: |
set -euo pipefail
@@ -530,11 +531,13 @@ jobs:
id: narrow
shell: bash
env:
- SETUP_ACTION: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.setup_action }}
- REMOTE_HELPER: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.remote_helper }}
+ SETUP_ACTION: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.setup_action }}
+ REMOTE_HELPER: ${{ (github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')) && 'true' || steps.filter.outputs.remote_helper }}
+ DOCKER_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.docker }}
+ KEYRING_SCOPE: ${{ github.event_name == 'schedule' && 'true' || steps.filter.outputs.keyring }}
run: |
set -euo pipefail
- for pair in "setup_action=$SETUP_ACTION" "remote_helper=$REMOTE_HELPER"; do
+ for pair in "setup_action=$SETUP_ACTION" "remote_helper=$REMOTE_HELPER" "docker=$DOCKER_SCOPE" "keyring=$KEYRING_SCOPE"; do
case "${pair#*=}" in
true|false)
printf '%s\n' "$pair" >> "$GITHUB_OUTPUT"
@@ -546,6 +549,15 @@ jobs:
esac
done
+ - name: Choose the pull request test lane
+ id: lane
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ CI_SCOPE: ${{ steps.scope.outputs.ci }}
+ FULL_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'ci:full') }}
+ run: bash scripts/ci/select-test-lane.sh
+
- name: Decide whether the Windows shards run
id: windows
shell: bash
@@ -554,9 +566,10 @@ jobs:
PATH_SELECTED: ${{ steps.filter.outputs.windows }}
run: bash scripts/ci/windows-sensitive-diff.sh
- # A scheduled run starts from main's head. Resolve dev ONCE so the nine
- # Windows shards, the macOS control and every other job test one commit,
- # however long the queue between them. contents: read already covers it.
+ # A scheduled run starts from the default branch's head, which is `dev`.
+ # Resolve dev ONCE so the nine Windows shards, the macOS control and every
+ # other job test one commit, however long the queue between them.
+ # contents: read already covers it.
- name: Resolve the commit a scheduled run tests
id: nightly
shell: bash
@@ -578,13 +591,11 @@ jobs:
printf 'Scheduled run: workflow from %s, testing dev at %s\n' "$GITHUB_SHA" "$sha" >> "$GITHUB_STEP_SUMMARY"
printf 'scheduled run tests dev at %s (workflow %s)\n' "$sha" "$GITHUB_SHA"
- # Bun roles (#6713): runtime 1.4.2 fixes #6684's Windows Bun.fetch streaming;
- # the test runner skipped 1.4.2's multi-file --isolate preload segfault (#4821
- # reverted #4064; run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9) and runs
- # 1.4.3, whose oven-sh/bun#44581 stops Bun.spawnSync losing a child's exit (#4956).
- # Rejoin after the upstream runner crash is fixed and a green lane=all dispatch
- # proves the unified version, then delete testRunnerBun and the action's role input.
- # The suite, split by file across four Linux runners.
+ # Bun runtime and test-runner roles both read their 1.4.4 defaults from package.json.
+ # Keep role validation after the historical isolate preload and spawnSync failures
+ # (#6713, #4956). Promotion requires a green full cross-platform lane=all run on
+ # the exact candidate head; focused local results do not replace that proof.
+ # The suite, split by file across five Linux runners.
#
# `scripts/ci/run-bun-test-batches.sh` assigns files to shards by the per-file
# durations recorded in `scripts/ci/test-durations.tsv` (sorted round-robin when
@@ -600,21 +611,27 @@ jobs:
# the same coverage in fresh Bun processes.
#
# Only the suite lives here. Typecheck, lint, build, and the scans run once in
- # `gates` rather than four times — they are fixed cost, and paying it per shard
+ # `gates` rather than five times — they are fixed cost, and paying it per shard
# would eat what the sharding saves.
+ # The heavy Linux jobs (test shards, test-changed, gates) take the lidge self-hosted pool on
+ # trusted runs while the repository variable LIDGE_RUNNERS is on: pushes, manual runs, branches of
+ # this repository, and pull requests by owners, members or collaborators. Everything else, and every
+ # run while the variable is off, stays on ubuntu-latest, so the hosted runners keep carrying the light
+ # jobs. As with the Windows box above, this routing is operational; the fork-PR approval policy and
+ # the box's scaler, which only creates runners for trusted runs, are the security boundary.
test:
- name: test ${{ matrix.shard }}/4
+ name: test ${{ matrix.shard }}/5
needs: changes
- if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true'
- runs-on: ubuntu-latest
- # A quarter of the suite. A shard that needs longer than this is wedged, not
+ if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.fast != 'true')
+ runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }}
+ # A fifth of the suite. A shard that needs longer than this is wedged, not
# slow — the old 30-minute ceiling was margin for the Windows leg, which no
# longer runs here (see platform-windows).
timeout-minutes: 15
strategy:
fail-fast: false
matrix:
- shard: [1, 2, 3, 4]
+ shard: [1, 2, 3, 4, 5]
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
@@ -647,10 +664,7 @@ jobs:
# gui/package.json. Without this the affected shards die on
# `Cannot find module 'react/jsx-dev-runtime'` while the other shards pass.
- name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd gui
- bun install --frozen-lockfile
+ run: bash scripts/ci/bun-install-frozen.sh . gui
# Nor is the build. Tests that fetch the served dashboard read the session
# bootstrap meta tags out of `gui/dist/index.html`, so without a build the
@@ -665,9 +679,30 @@ jobs:
- name: Test in fresh-process batches
env:
- TEST_SHARD: ${{ matrix.shard }}/4
+ TEST_SHARD: ${{ matrix.shard }}/5
run: bash scripts/ci/run-bun-test-batches.sh "$TEST_SHARD"
+ # Fast lane: import-graph tests for the diff; the batched dev dispatch is the backstop.
+ test-changed:
+ name: test changed
+ needs: changes
+ if: github.event_name == 'pull_request' && needs.changes.outputs.fast == 'true'
+ runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }}
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ persist-credentials: false
+ ref: ${{ needs.changes.outputs.checkout_ref }}
+ fetch-depth: 2 # merge commit + base tip, which the selection diffs against
+ - uses: ./.github/actions/setup-project-bun
+ with:
+ role: test-runner # See the Bun roles contract above test.
+ - name: Install dependencies and build the GUI the tests serve
+ run: bash scripts/ci/bun-install-frozen.sh . gui && cd gui && bun run build
+ - name: Test the files this pull request reaches
+ run: bash scripts/ci/run-changed-tests.sh
+
# Bun 1.3.14 has shown a Linux isolate/epoll race around the storage-policy
# harness. Keep the entire six-file family in one fresh process so a runtime
# failure is bounded to this job instead of poisoning a general test shard.
@@ -690,10 +725,7 @@ jobs:
role: test-runner # See the Bun roles contract above test.
- name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd gui
- bun install --frozen-lockfile
+ run: bash scripts/ci/bun-install-frozen.sh . gui
- name: Build GUI
run: |
@@ -732,10 +764,7 @@ jobs:
role: test-runner # See the Bun roles contract above test.
- name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd gui
- bun install --frozen-lockfile
+ run: bash scripts/ci/bun-install-frozen.sh . gui
- name: Build GUI
run: |
@@ -752,7 +781,7 @@ jobs:
name: gates
needs: changes
if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true'
- runs-on: ubuntu-latest
+ runs-on: ${{ vars.LIDGE_RUNNERS == 'on' && (github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository || contains(fromJSON('["OWNER","MEMBER","COLLABORATOR"]'), github.event.pull_request.author_association)) && fromJSON('["self-hosted","linux","x64","lidge"]') || 'ubuntu-latest' }}
timeout-minutes: 15
steps:
- name: Checkout
@@ -763,6 +792,8 @@ jobs:
# residue. Matches the convention already used by the other workflows.
persist-credentials: false
ref: ${{ needs.changes.outputs.checkout_ref }}
+ # Release history tests verify old tag and dev-baseline trees.
+ fetch-depth: 0
- name: Setup project Bun
uses: ./.github/actions/setup-project-bun
@@ -770,10 +801,7 @@ jobs:
role: test-runner # See the Bun roles contract above test.
- name: Install dependencies
- run: |
- bun install --frozen-lockfile
- cd gui
- bun install --frozen-lockfile
+ run: bash scripts/ci/bun-install-frozen.sh . gui
- name: GUI lint
if: needs.changes.outputs.gui == 'true'
@@ -799,6 +827,9 @@ jobs:
- name: Check the generated ocx skill surface is current
run: bun run skill:surface:check
+ - name: Test release evidence, history and docs deployment
+ run: node --test .github/scripts/release-dispatch-guard.test.cjs .github/scripts/release-evidence.test.cjs .github/scripts/release-history.test.cjs .github/scripts/release-resume.test.cjs .github/workflows/deploy-docs.test.cjs
+
- name: Check release helper syntax
run: bun build scripts/release.ts --target=bun --outdir=.tmp/ci-release-script-check
@@ -827,29 +858,28 @@ jobs:
run: bun run src/cli/index.ts help
platform-macos:
- name: macos ${{ matrix.shard }}/3
+ name: macos ${{ matrix.shard }}/4
needs: changes
- # Never on pull requests: macOS legs run after merge, on push to
- # main/preview, and on dispatch and the schedule.
+ # Never on pull requests: macOS legs run through manual dispatch.
if: github.event_name != 'pull_request'
runs-on: macos-latest
- # Three shards. Unsharded, this job was the critical path on every green dev
- # push (mean 14.9 min against a 4.7 min Linux maximum; devlog
- # 260905_test_modularization_and_windows/003), so it was split in two. The
- # suite then outgrew two halves: across seventeen dev dispatches from
- # 2026-10-04 to 10-12 the slower half's test step went from 867s to 1155s,
- # and run 38214884055 cancelled macos 2/2 at this cap with 68 files left
- # while every test it had run was passing (#6978). Replaying the duration
- # assignment against those runs' measured per-file times puts the slowest of
- # three shards at 635-796s of tests, about 14 minutes with setup. The cap
- # stays 20: the suite needs another shard, not a longer wait, and a wedged
- # shard (#4956) is still cut off as early as before. The full-membership
- # control runs the same bounded batches without sharding on explicit dispatch.
+ # Four shards. Three replaced two after run 38214884055 hit this cap with
+ # 68 files left and no failing tests (#6978). The suite outgrew three too:
+ # run 40727740334 took 13.1-16.4m, 40743681086 12.7-13.7m, and
+ # 40756291846 15.0-17.1m. In dev lane=all run 40766068492 (b16bc0978b),
+ # macos 1/3 (123090588998) reached batch 73/88 and macos 2/3
+ # (123090589363) batch 93/93 before this cap cancelled them, with no failing
+ # tests. The cap stays 20: the suite needs another shard, not a longer wait,
+ # and a wedged shard (#4956) is still cut off as early as before. Four suite
+ # shards + control + widget/bundle request six macOS jobs for five runner
+ # slots: one queues, and each run pays one extra shard's setup overhead.
+ # The full-membership control runs the same bounded batches without sharding
+ # on explicit dispatch.
timeout-minutes: 20
strategy:
fail-fast: false
matrix:
- shard: [1, 2, 3]
+ shard: [1, 2, 3, 4]
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
@@ -895,7 +925,7 @@ jobs:
- name: Test in fresh-process batches
env:
- TEST_SHARD: ${{ matrix.shard }}/3
+ TEST_SHARD: ${{ matrix.shard }}/4
BUN_TEST_FILE_SCOPE: all
BUN_TEST_BATCH_SIZE: '12'
BUN_TEST_PARALLEL: '1'
@@ -912,7 +942,6 @@ jobs:
needs: changes
# Diagnostic-only lanes stay off the ordinary release gates: list every lane
# that should run this job, so a new lane defaults to skipping the diagnostic.
- # The nightly schedule is the full lane=all matrix, so it runs this job too.
if: >-
github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all' || github.event.inputs.lane == 'macos-control')
runs-on: macos-latest
@@ -978,33 +1007,43 @@ jobs:
- name: CLI help smoke
run: bun run src/cli/index.ts help
- # Windows runs on a Windows-sensitive pull request, on the nightly schedule,
- # and on a lane=all (or default) dispatch. It is never part of the push run
- # release.yml gates on.
- #
- # It left the PR lane first (16m23s against a 6-minute Linux critical path;
- # the ceiling was raised twice rather than the gap closed — #711 vs #653,
- # issue #717, then #827's 20-minute kill), then left the shipping boundary
- # when the sharded promotion run surfaced ~207 Windows-only test failures
- # that had been invisible while dev skipped the leg. Those are real defects,
- # tracked as issue #1059, but they are pre-existing on every released
- # version — gating the release on them blocks shipping fixes to the platforms
- # that pass, for a platform that has never shipped green.
- #
- # The leg stays in the workflow, sharded and dispatchable, so the failure
- # list can be burned down without losing the ability to measure progress.
- # release.yml gates on a successful push-event run of this workflow, which
- # now means Linux + macOS + the gates; Windows re-enters the gate when the
- # tracked failures are fixed, not before.
- #
- # Dispatch-only proved too late. #6639, #6556, #6605 and #6606 each landed with
- # green pull-request CI while breaking Windows, and the breakage surfaced days
- # later on a manual dispatch. So a pull request whose changes job reports
- # windows=true (a Windows path, or an added src/tests line naming a Windows
- # marker; see scripts/ci/windows-sensitive-diff.sh) now runs the nine shards,
- # and the daily schedule catches whatever that filter misses.
+ # A diagnostic run deliberately bypasses changes and the full CI graph. Its
+ # title identifies it as a partial run, never release evidence.
+ windows-native-claim:
+ name: windows native-main claim diagnostic
+ if: github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' && github.event.inputs.lane == 'windows-native-claim'
+ runs-on: windows-latest
+ timeout-minutes: 30
+ steps:
+ - name: Checkout workflow commit
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - name: Setup project Bun
+ uses: ./.github/actions/setup-project-bun
+ with:
+ role: test-runner
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+ - name: Isolate homes
+ shell: pwsh
+ run: |
+ $root = Join-Path $env:RUNNER_TEMP "ocx-claim-$env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
+ $ocxHome = Join-Path $root 'opencodex'
+ $codexHome = Join-Path $root 'codex'
+ New-Item -ItemType Directory -Path $ocxHome, $codexHome -ErrorAction Stop | Out-Null
+ "OPENCODEX_HOME=$ocxHome" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ "CODEX_HOME=$codexHome" | Out-File -FilePath $env:GITHUB_ENV -Encoding utf8 -Append
+ - name: Run native-main claim diagnostics
+ env:
+ OCX_TEST_WINDOWS_NATIVE_CLAIM_DIAGNOSTIC: '1'
+ run: bun test tests/codex-integration/main-quota-provenance.test.ts --timeout 60000
+
+ # Windows shards run only on a full manual dispatch. Pull requests retain
+ # fast Ubuntu checks, including when the Windows-sensitive filter is set.
platform-windows:
- name: windows ${{ matrix.shard }}/9
+ name: windows ${{ matrix.shard }}/11
needs: [changes, select-windows-runner]
if: >-
github.event_name == 'schedule' || github.event_name == 'workflow_dispatch' && (github.event.inputs.lane == '' || github.event.inputs.lane == 'all')
@@ -1035,21 +1074,18 @@ jobs:
# test deadline and all six shards, but left the whole batch and cleanup a
# 30-minute bound.
#
- # Six shards then grew into the 30-minute ceiling too. Across seven lane=all
- # dispatches the six shard totals were 114.3-133.2 minutes. The worst observed
- # shard imbalance was 1.43x its dispatch's per-shard average. Eight shards leave
- # no margin: 133.2 / 8 * 1.43 * 1.25 = 29.8 minutes after the already-observed
- # 25% run-to-run slowdown. Nine gives 133.2 / 9 * 1.43 * 1.25 = 26.5 minutes.
- # Keep the 30-minute bound and pay for three more concurrent runners plus their
- # repeated checkout/install/build setup so test work, rather than the ceiling,
- # shrinks. The per-batch timeout below is independent: it aborts a stuck Bun
- # process but adds no delay to a healthy one, so calibrating it does not change
- # this total-work projection.
+ # Nine shards also reached the ceiling: run 40756291846 cancelled 7/9 at batch
+ # 49/60; run 40743681086's successful shards took 22.1-29.5 minutes. Refreshing
+ # Windows weights from completed primary batches in both runs puts test work
+ # at 24.36/21.92/19.93 minutes with 9/10/11 shards. With the observed 2.4-minute
+ # maximum setup, eleven projects ~22.4 minutes; 25% test variance makes ~27.3.
+ # Pay for two extra setups (~3.3 runner-minutes at the older run's mean), keep
+ # the 30-minute job bound and all tests, and leave batch deadlines independent.
timeout-minutes: 30
strategy:
fail-fast: false
matrix:
- shard: [1, 2, 3, 4, 5, 6, 7, 8, 9]
+ shard: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
steps:
- name: Show selected runner
shell: bash
@@ -1129,7 +1165,7 @@ jobs:
# and service-manager guard before the lock boundary.
shell: bash
env:
- TEST_SHARD: ${{ matrix.shard }}/9
+ TEST_SHARD: ${{ matrix.shard }}/11
BUN_TEST_FILE_SCOPE: all
BUN_TEST_BATCH_SIZE: "6"
BUN_TEST_BATCH_TIMEOUT_SECONDS: "480"
@@ -1145,7 +1181,7 @@ jobs:
keyring-smoke:
name: keyring ${{ matrix.name }}
needs: changes
- if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true'
+ if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.keyring == 'true')
runs-on: ${{ matrix.runner }}
timeout-minutes: 8
strategy:
@@ -1208,7 +1244,7 @@ jobs:
docker-smoke:
name: docker smoke
needs: changes
- if: github.event_name != 'pull_request' || needs.changes.outputs.ci == 'true'
+ if: github.event_name != 'pull_request' || (needs.changes.outputs.ci == 'true' && needs.changes.outputs.docker == 'true')
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
@@ -1225,7 +1261,7 @@ jobs:
run: bun scripts/ci/docker-smoke.ts
# Proves the Astro toolchain still builds the site, on the only event that can
- # prove it before promotion.
+ # prove it before release.
#
# Linux only, and one leg. The site is static output from a Node/Bun toolchain
# with no OS-specific behaviour to promise, so a Windows or macOS leg would buy
@@ -1268,7 +1304,7 @@ jobs:
# aggregate reported success while nothing had read the change (#5001).
#
# Running the gate directly here, rather than adding `structure/**` to `ci`,
- # keeps a prose edit from starting nine Windows shards and two macOS shards for
+ # keeps a prose edit from starting the Windows shards and macOS shards for
# a check that takes seconds. It runs whenever `structure/` changes, including
# alongside a `src/` change where the suite covers it too; a duplicate of a
# seconds-long check is not worth a condition that could be wrong.
@@ -1498,7 +1534,7 @@ jobs:
name: macos widget + bundle
needs: [changes, gates]
# Never on pull requests, like platform-macos: the widget extension and
- # app bundle are rebuilt after merge, on push, dispatch and the schedule.
+ # app bundle are rebuilt through manual dispatch.
if: github.event_name != 'pull_request'
runs-on: macos-latest
timeout-minutes: 30
@@ -1700,12 +1736,12 @@ jobs:
ci:
name: ci
- if: always()
+ if: always() && (github.event_name != 'workflow_dispatch' || github.event.inputs.lane != 'windows-native-claim')
# Every producer, including the ones that only feed other jobs. `needs` holds
# direct dependencies only, so a failing `select-windows-runner` would
# otherwise reach this gate as nothing at all while its dependents report
# `skipped`, which is the shape the step below is written to catch.
- needs: [changes, select-windows-runner, test, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, docker-smoke, docs-site-build, structure-gate, privacy-gate, npm-global-smoke, widget, desktop-shell, setup-action, remote-helper]
+ needs: [changes, select-windows-runner, test, test-changed, storage-policy, api-usage, gates, platform-macos, macos-control, platform-windows, keyring-smoke, docker-smoke, docs-site-build, structure-gate, privacy-gate, npm-global-smoke, widget, desktop-shell, setup-action, remote-helper]
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
@@ -1721,11 +1757,14 @@ jobs:
EVENT_NAME: ${{ github.event_name }}
LANE: ${{ github.event.inputs.lane }}
CHANGES_CI: ${{ needs.changes.outputs.ci }}
+ CHANGES_FAST: ${{ needs.changes.outputs.fast }}
CHANGES_PACKAGING: ${{ needs.changes.outputs.packaging }}
CHANGES_DOCS: ${{ needs.changes.outputs.docs }}
CHANGES_STRUCTURE: ${{ needs.changes.outputs.structure }}
CHANGES_SETUP_ACTION: ${{ needs.changes.outputs.setup_action }}
CHANGES_REMOTE_HELPER: ${{ needs.changes.outputs.remote_helper }}
+ CHANGES_DOCKER: ${{ needs.changes.outputs.docker }}
+ CHANGES_KEYRING: ${{ needs.changes.outputs.keyring }}
CHANGES_NATIVE: ${{ needs.changes.outputs.native }}
CHANGES_DESKTOP: ${{ needs.changes.outputs.desktop }}
CHANGES_WINDOWS: ${{ needs.changes.outputs.windows }}
@@ -1749,6 +1788,12 @@ jobs:
if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_CI" != "true" ]; then
scoped=not-requested
fi
+ full_tests=$scoped # the fast lane swaps the shards for test changed; unset = full
+ changed_tests=not-requested
+ if [ "$EVENT_NAME" = "pull_request" ] && [ "$scoped" = requested ] && [ "${CHANGES_FAST:-false}" = "true" ]; then
+ full_tests=not-requested
+ changed_tests=requested
+ fi
# platform-macos and widget never run on a pull request (macOS runs after merge).
# desktop-shell (ubuntu) carries the ordinary scope gate AND the native or
# package-E2E path filters. This mirrors those expressions exactly; where it
@@ -1782,6 +1827,16 @@ jobs:
if [ "$CHANGES_REMOTE_HELPER" = "true" ]; then
remote_helper=requested
fi
+ # docker-smoke and keyring-smoke follow the ci scope, narrowed on a pull request to
+ # their own filters. Mirrors their `if:` exactly, like desktop_shell above.
+ docker=$scoped
+ if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_DOCKER" != "true" ]; then
+ docker=not-requested
+ fi
+ keyring=$scoped
+ if [ "$EVENT_NAME" = "pull_request" ] && [ "$CHANGES_KEYRING" != "true" ]; then
+ keyring=not-requested
+ fi
# privacy-gate runs exactly where `gates` (scoped) does not, on every
# pull request the ci filter declines. Deriving it from `scoped` keeps
# the two scans complementary here as they are in the jobs' own
@@ -1801,7 +1856,7 @@ jobs:
if [ -z "$LANE" ] || [ "$LANE" = "all" ] || [ "$LANE" = "macos-control" ]; then
dispatch=requested
fi
- # Only the default/all lane requests the nine Windows suite shards.
+ # Only the default/all lane requests the Windows suite shards.
if [ -z "$LANE" ] || [ "$LANE" = "all" ]; then
windows=requested
fi
@@ -1809,7 +1864,7 @@ jobs:
# One line per job, mirroring that job's own `if:`. Adding a job to this workflow
# without adding it here fails the gate by name rather than passing unnoticed.
- GATED_JOBS="changes select-windows-runner test storage-policy api-usage gates"
+ GATED_JOBS="changes select-windows-runner test test-changed storage-policy api-usage gates"
GATED_JOBS="$GATED_JOBS platform-macos keyring-smoke docker-smoke npm-global-smoke"
GATED_JOBS="$GATED_JOBS macos-control platform-windows docs-site-build"
GATED_JOBS="$GATED_JOBS structure-gate widget"
@@ -1820,8 +1875,12 @@ jobs:
expected_for() {
case "$1" in
changes|select-windows-runner) echo requested ;;
- test|storage-policy|api-usage|gates|keyring-smoke|docker-smoke)
+ test) echo "$full_tests" ;;
+ test-changed) echo "$changed_tests" ;;
+ storage-policy|api-usage|gates)
echo "$scoped" ;;
+ docker-smoke) echo "$docker" ;;
+ keyring-smoke) echo "$keyring" ;;
platform-macos|widget)
echo "$native" ;;
desktop-shell) echo "$desktop_shell" ;;
@@ -1869,10 +1928,10 @@ jobs:
# started: five successes and one skipped leg roll up to `success`. No matrix here
# carries a per-leg `if:`, so a leg can only be skipped when its whole job is, which
# the expectation table above already catches. What that table cannot catch is a
- # matrix that produced FEWER legs than the nine a dispatch is run to read, so count
- # them by name. The nine Windows legs are the entire output of that dispatch.
+ # matrix that produced FEWER legs than the eleven a dispatch is run to read, so count
+ # them by name. The eleven Windows legs are the entire output of that dispatch.
if [ "$windows" = requested ]; then
- shards=9
+ shards=11
# `filter=latest` (the default) is the latest execution of each job in the run,
# which is what a human reading the run sees. Asking for one ATTEMPT instead would
# fail every partial re-run: "Re-run failed jobs" puts only the repaired shard in
diff --git a/.github/workflows/cleanup-closed-pr-branches.yml b/.github/workflows/cleanup-closed-pr-branches.yml
index 4b0c1229a9..8cbca5076b 100644
--- a/.github/workflows/cleanup-closed-pr-branches.yml
+++ b/.github/workflows/cleanup-closed-pr-branches.yml
@@ -5,9 +5,8 @@ name: Clean branches from closed pull requests
# merging leaves its head branch behind forever, which is how this repository
# accumulated dozens of dead `codex/*` and `ingw/*` branches.
#
-# Scheduled workflows only run from the repository DEFAULT branch (currently
-# `main`), not from `dev`. Landing this on `dev` alone does not start the
-# cleanup until the change is also promoted to that default branch.
+# Scheduled workflows only run from the repository DEFAULT branch, which is
+# `dev`. A change lands on the live cleanup as soon as it is on `dev`.
on:
schedule:
# Daily at 06:30 UTC (offset from the hour to reduce Action load spikes).
diff --git a/.github/workflows/cleanup-orphaned-workflows.yml b/.github/workflows/cleanup-orphaned-workflows.yml
index 6915a063ed..02d7005cd9 100644
--- a/.github/workflows/cleanup-orphaned-workflows.yml
+++ b/.github/workflows/cleanup-orphaned-workflows.yml
@@ -7,13 +7,6 @@ on:
schedule:
# Daily at 06:00 UTC.
- cron: "0 6 * * *"
- push:
- branches: [main]
- paths:
- # The first promotion to main performs the initial backlog cleanup without
- # exposing a branch-selectable manual trigger with actions:write.
- - ".github/workflows/cleanup-orphaned-workflows.yml"
- - "scripts/ci/cleanup-orphaned-workflows.mjs"
permissions:
actions: write # Required to delete orphaned workflow runs through the Actions API.
@@ -35,9 +28,9 @@ jobs:
persist-credentials: false
- name: Setup Bun
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
- with:
- bun-version: 1.4.2
+ # The repository composite reads package.json dependencies.bun from the
+ # checkout above, so this job cannot drift from the runtime pin.
+ uses: ./.github/actions/setup-project-bun
- name: Remove stale workflow histories
env:
diff --git a/.github/workflows/codex-queue-helpers.yml b/.github/workflows/codex-queue-helpers.yml
index 62b5991b79..7145a1fa1a 100644
--- a/.github/workflows/codex-queue-helpers.yml
+++ b/.github/workflows/codex-queue-helpers.yml
@@ -7,14 +7,6 @@ on:
- 'docs-site/astro.config.mjs'
- 'docs-site/src/content/docs/guides/composer-usage-gate-fallback.md'
- '.github/workflows/codex-queue-helpers.yml'
- push:
- branches: [main, preview]
- paths:
- - 'scripts/codex-queue.*'
- - 'docs-site/astro.config.mjs'
- - 'docs-site/src/content/docs/guides/composer-usage-gate-fallback.md'
- - '.github/workflows/codex-queue-helpers.yml'
-
workflow_dispatch:
permissions:
diff --git a/.github/workflows/deploy-docs.test.cjs b/.github/workflows/deploy-docs.test.cjs
new file mode 100644
index 0000000000..6343c63e1a
--- /dev/null
+++ b/.github/workflows/deploy-docs.test.cjs
@@ -0,0 +1,64 @@
+const { test } = require('node:test');
+const assert = require('node:assert/strict');
+const fs = require('node:fs');
+const os = require('node:os');
+const path = require('node:path');
+const { spawnSync } = require('node:child_process');
+
+const workflow = fs.readFileSync(path.join(__dirname, 'deploy-docs.yml'), 'utf8');
+function scriptFor(step) {
+ const start = workflow.indexOf(` - name: ${step}\n`);
+ assert.notEqual(start, -1);
+ const rest = workflow.slice(start);
+ const match = rest.match(/\n run: \|\n((?: .*\n|\n)+)/);
+ assert.ok(match);
+ return match[1].replace(/^ /gm, '');
+}
+const selection = scriptFor('Resolve published stable source');
+const guard = scriptFor('Require trusted dispatch');
+const sha = 'a'.repeat(40);
+function run(script, overrides = {}) {
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'ocx-pages-test-'));
+ try {
+ fs.writeFileSync(path.join(dir, 'gh'), '#!/bin/bash\nprintf "%s" "$MOCK_RELEASE"\n', { mode: 0o755 });
+ fs.writeFileSync(path.join(dir, 'git'), '#!/bin/bash\nif [ "$MOCK_GIT_FAIL" = 1 ]; then exit 1; fi\nprintf "%s\\n" "$MOCK_SHA"\n', { mode: 0o755 });
+ const output = path.join(dir, 'output');
+ fs.writeFileSync(output, '');
+ const env = { ...process.env, PATH: `${dir}:${process.env.PATH}`, GITHUB_OUTPUT: output,
+ GITHUB_STEP_SUMMARY: path.join(dir, 'summary'), GITHUB_REPOSITORY: 'owner/repo',
+ GITHUB_EVENT_NAME: 'workflow_dispatch', GITHUB_REF: 'refs/heads/dev', RELEASE_TAG: '',
+ MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: false, prerelease: false }), MOCK_SHA: sha,
+ ...overrides };
+ const result = spawnSync('bash', ['-c', script], { env, encoding: 'utf8' });
+ return { ...result, output: fs.readFileSync(output, 'utf8') };
+ } finally { fs.rmSync(dir, { recursive: true, force: true }); }
+}
+test('only trusted dev dispatch reaches the build', () => {
+ assert.equal(run(guard).status, 0);
+ assert.notEqual(run(guard, { GITHUB_REF: 'refs/heads/pr-head' }).status, 0);
+ assert.notEqual(run(guard, { GITHUB_EVENT_NAME: 'push' }).status, 0);
+ assert.doesNotMatch(workflow, /^ push:/m);
+ assert.match(workflow, /ref: \$\{\{ steps\.source\.outputs\.sha \}\}/);
+ assert.match(workflow, /permissions:\n pages: write\n id-token: write/);
+});
+test('latest and explicit published stable release select immutable commit', () => {
+ const latest = run(selection);
+ assert.equal(latest.status, 0, latest.stderr);
+ assert.equal(latest.output, `sha=${sha}\n`);
+ const explicit = run(selection, { RELEASE_TAG: 'v2.3.4', MOCK_RELEASE: JSON.stringify({ tagName: 'v2.3.4', isDraft: false, isPrerelease: false }) });
+ assert.equal(explicit.status, 0, explicit.stderr);
+ assert.equal(explicit.output, `sha=${sha}\n`);
+});
+test('refuses prereleases, drafts, mismatch, malformed tags and missing commits', () => {
+ for (const overrides of [
+ { RELEASE_TAG: 'v2.3.4-preview.1' }, { RELEASE_TAG: '$(touch evil)' },
+ { MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: true, prerelease: false }) },
+ { MOCK_RELEASE: JSON.stringify({ tag_name: 'v2.3.4', draft: false, prerelease: true }) },
+ { RELEASE_TAG: 'v2.3.4', MOCK_RELEASE: JSON.stringify({ tagName: 'v2.3.5', isDraft: false, isPrerelease: false }) },
+ { MOCK_GIT_FAIL: '1' }, { MOCK_SHA: 'bad' }, { MOCK_RELEASE: '{}' },
+ ]) {
+ const result = run(selection, overrides);
+ assert.notEqual(result.status, 0, JSON.stringify(overrides));
+ assert.equal(result.output, '');
+ }
+});
diff --git a/.github/workflows/deploy-docs.yml b/.github/workflows/deploy-docs.yml
index c46821034e..c726f02677 100644
--- a/.github/workflows/deploy-docs.yml
+++ b/.github/workflows/deploy-docs.yml
@@ -1,17 +1,14 @@
name: Deploy Docs to GitHub Pages
on:
- push:
- branches: [main]
- paths:
- - "docs-site/**"
- - ".github/workflows/deploy-docs.yml"
workflow_dispatch:
+ inputs:
+ release-tag:
+ description: "Published stable release tag (empty selects the latest stable release)"
+ required: false
+ type: string
-permissions:
- contents: read
- pages: write
- id-token: write
+permissions: {}
concurrency:
group: pages
@@ -19,24 +16,74 @@ concurrency:
jobs:
build:
- # Our independent repository does not publish the inherited site's configuration.
- if: vars.OCX_ENABLE_DOCS_DEPLOY == '1'
runs-on: ubuntu-latest
timeout-minutes: 15
+ permissions:
+ contents: read
steps:
- - name: Checkout
+ - name: Require trusted dispatch
+ run: |
+ test "$GITHUB_EVENT_NAME" = workflow_dispatch && test "$GITHUB_REF" = refs/heads/dev || {
+ echo '::error::Dispatch the trusted workflow from dev.'; exit 1;
+ }
+ - name: Checkout trusted workflow revision
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ github.sha }}
+ fetch-depth: 0
+ persist-credentials: false
+ - name: Resolve published stable source
+ id: source
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RELEASE_TAG: ${{ inputs.release-tag }}
+ run: |
+ set -euo pipefail
+ if [ -n "$RELEASE_TAG" ]; then
+ [[ "$RELEASE_TAG" =~ ^v(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$ ]] || {
+ echo '::error::Expected a stable release tag such as v1.2.3.'; exit 1;
+ }
+ release="$(gh release view "$RELEASE_TAG" --json tagName,isDraft,isPrerelease)"
+ else
+ release="$(gh api "repos/$GITHUB_REPOSITORY/releases/latest")"
+ fi
+ tag="$(RELEASE_JSON="$release" node - <<'NODE'
+ const r = JSON.parse(process.env.RELEASE_JSON);
+ const tag = r.tagName ?? r.tag_name;
+ const draft = r.isDraft ?? r.draft;
+ const prerelease = r.isPrerelease ?? r.prerelease;
+ if (draft !== false || prerelease !== false || typeof tag !== 'string' ||
+ !/^v(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/.test(tag) ||
+ (process.env.RELEASE_TAG && tag !== process.env.RELEASE_TAG)) {
+ throw new Error('Release is not the requested published stable release');
+ }
+ process.stdout.write(tag);
+ NODE
+ )"
+ sha="$(git rev-parse --verify "refs/tags/${tag}^{commit}")"
+ [[ "$sha" =~ ^[0-9a-f]{40}$ ]] || { echo '::error::Invalid release commit.'; exit 1; }
+ echo "sha=$sha" >> "$GITHUB_OUTPUT"
+ echo "Building published release $tag at $sha" >> "$GITHUB_STEP_SUMMARY"
+ - name: Checkout published source
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ steps.source.outputs.sha }}
+ persist-credentials: false
- name: Build with Astro
uses: withastro/action@e84f40bd8d2caa9e768ec82ad30dd81f0b280853 # v6.1.2
with:
path: ./docs-site
node-version: 22
- package-manager: bun@latest
+ # Must equal package.json dependencies.bun (asserted in ci-workflows.test.ts).
+ package-manager: bun@1.4.4
deploy:
needs: build
runs-on: ubuntu-latest
timeout-minutes: 10
+ permissions:
+ pages: write
+ id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
diff --git a/.github/workflows/dev-version-bump.yml b/.github/workflows/dev-version-bump.yml
index 99a8946c3e..cd99285c43 100644
--- a/.github/workflows/dev-version-bump.yml
+++ b/.github/workflows/dev-version-bump.yml
@@ -19,8 +19,8 @@ name: Dev version bump
#
# A branch-selected dispatch executes that branch's workflow body with write permission.
# The in-job guard therefore rejects accidental non-default-ref dispatches. It is an early
-# warning, not a security boundary: a writer could remove it on their branch. Protected
-# release branches and the required review on `dev` remain the enforcement boundaries.
+# warning, not a security boundary: a writer could remove it on their branch. The protected
+# `dev` branch and its required review remain the enforcement boundaries.
on:
workflow_dispatch:
inputs:
diff --git a/.github/workflows/enforce-issue-quality.yml b/.github/workflows/enforce-issue-quality.yml
index a983da5d78..1531fb79f8 100644
--- a/.github/workflows/enforce-issue-quality.yml
+++ b/.github/workflows/enforce-issue-quality.yml
@@ -1,9 +1,8 @@
name: Enforce issue quality
-# Issue events always load this workflow from the repository DEFAULT branch
-# (currently `main`), not from `dev`. Landing here on `dev` alone does not
-# change live issue-quality behavior until the change is also on that default
-# branch.
+# Issue events always load this workflow from the repository DEFAULT branch,
+# which is `dev`. A change lands on the live issue-quality gate as soon as it is
+# on `dev`.
on:
issues:
types:
diff --git a/.github/workflows/enforce-pr-target.yml b/.github/workflows/enforce-pr-target.yml
index 35f6ea7b38..d2a9674595 100644
--- a/.github/workflows/enforce-pr-target.yml
+++ b/.github/workflows/enforce-pr-target.yml
@@ -44,7 +44,8 @@ jobs:
github.event.label.name == 'test-exception-approved' ||
github.event.label.name == 'suppression-approved' ||
github.event.label.name == 'generated-change-approved' ||
- github.event.label.name == 'dependency-change-approved'))
+ github.event.label.name == 'dependency-change-approved' ||
+ github.event.label.name == 'attribution-approved'))
runs-on: ubuntu-latest
permissions:
contents: read
@@ -190,19 +191,17 @@ jobs:
# PR's head, so `base.sha` let an unpromoted commit choose which code
# runs with this job's contents/pull-requests write token.
#
- # The branch is chosen, not fixed. `status` has no pull_request
- # payload and runs the privileged workflow from the repository
- # default branch, so it sources from that same promoted boundary. A
- # `main`-targeting PR must take its scripts from `main`, or the gate
- # runs a `main` workflow definition against `dev` scripts. Every
- # other base, including a stacked child's, resolves to `dev`.
- ref: ${{ github.event_name == 'status' && github.event.repository.default_branch || (github.event.pull_request.base.ref == 'main' && 'main' || 'dev') }}
+ # `status` has no pull_request payload and runs the privileged
+ # workflow from the repository default branch, so it sources from
+ # that same boundary. Every pull_request event, including a stacked
+ # child's, resolves to `dev`, the single integration branch.
+ ref: ${{ github.event_name == 'status' && github.event.repository.default_branch || 'dev' }}
persist-credentials: false
sparse-checkout: |
.github/scripts
MAINTAINERS.md
- - name: Enforce PR target, ancestry, and description
+ - name: Enforce PR target and description
uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9
env:
RESOLVED_PULL_NUMBER: ${{ needs.resolve-pr.outputs.pull-number }}
@@ -229,7 +228,11 @@ jobs:
);
const {
collectDeterministicHygieneFailures,
+ countHeadRewrites,
HYGIENE_FAILURE_HINTS,
+ needsHeadRewriteCount,
+ parseApprovalRecord,
+ reconcileHeadBoundApprovals,
} = require(
path.join(process.cwd(), ".github", "scripts", "pr-hygiene.cjs"),
);
@@ -260,12 +263,13 @@ jobs:
const {
GATE_MARKER,
READINESS_MARKER,
- HYGIENE_MARKER,
- HYGIENE_BLOCK_START,
- HYGIENE_BLOCK_END,
inlineCode,
buildGateCommentBody,
extractHygieneSection,
+ authoritativeHygieneSection,
+ withHygieneSection,
+ escapeControlCharacters,
+ isGateComment,
buildFailureSections,
failureSummary,
buildStaleNotice,
@@ -337,13 +341,10 @@ jobs:
);
// One consolidated comment. The gate finds its own comment by the
- // single GATE_MARKER; the legacy enforcer/readiness markers are
- // matched only to migrate pre-consolidation PRs.
- let gateComment = comments.find(
- comment =>
- comment.user?.login === "github-actions[bot]" &&
- comment.body?.includes(GATE_MARKER)
- );
+ // single GATE_MARKER its body starts with (a marker echoed inside
+ // another bot comment does not count); the legacy enforcer/readiness
+ // markers are matched only to migrate pre-consolidation PRs.
+ let gateComment = comments.find(isGateComment);
let gateCommentId = gateComment?.id ?? null;
const storedGateState = parseGateState(
gateComment?.body,
@@ -437,13 +438,15 @@ jobs:
async function upsertGateComment(state, opts) {
let body = buildGateCommentBody(state, opts).join("\n");
// The hygiene workflow writes its status into this same comment.
- // Preserve whatever it left so a gate rebuild does not drop it.
+ // Preserve whatever it left so a gate rebuild does not drop it;
+ // it carries the approval record the next runs read. Appended
+ // unconditionally (a rebuilt body may not end in whitespace) and
+ // never through a replacement template.
const existingHygiene = extractHygieneSection(gateComment?.body);
- if (existingHygiene && !body.includes("pr-hygiene-block")) {
- body = body.replace(
- /\s+$/,
- `\n\n## Hygiene\n\n${HYGIENE_BLOCK_START}\n${HYGIENE_MARKER}\n\n${existingHygiene}\n\n${HYGIENE_BLOCK_END}`
- );
+ // Delimiter-aware: an echoed path that merely contains the marker
+ // text must not suppress the preservation.
+ if (existingHygiene && extractHygieneSection(body) === null) {
+ body = withHygieneSection(body, existingHygiene.split("\n"));
}
if (gateCommentId) {
// Skip the write when the rebuilt body matches what is already
@@ -678,9 +681,7 @@ jobs:
gateState.pendingReattestation = null;
}
- let behindMain = 0;
let behindBase = 0;
- let aheadMain = 0;
let ancestryLookupFailed = false;
const baseAllowed = ALLOWED_BASES.includes(pr.base.ref);
@@ -720,15 +721,10 @@ jobs:
if (baseAllowed) {
const headSha = pr.head.sha;
try {
- const { data: mainCompare } =
- await github.rest.repos.compareCommitsWithBasehead({
- owner,
- repo,
- basehead: `main...${headSha}`
- });
- behindMain = mainCompare.behind_by;
- aheadMain = mainCompare.ahead_by;
-
+ // `dev` is the only integration branch now. This single
+ // compare feeds the review-readiness latest-dev claim; there
+ // is no deleted `main` tip to compare against, so no
+ // wrong-ancestry verdict is derived here.
const { data: baseCompare } =
await github.rest.repos.compareCommitsWithBasehead({
owner,
@@ -747,6 +743,10 @@ jobs:
const changedFiles = [];
const changedFilePaths = [];
let filesTruncated = true;
+ // The head the changed-file list was verified against; null when the
+ // head moved during the snapshot. Head-bound approvals are judged
+ // against the same head the files belong to.
+ let changedFilesHeadSha = null;
for (let attempt = 0; attempt < 2; attempt += 1) {
const { data: fileSnapshot } = await github.rest.pulls.get({
owner,
@@ -774,6 +774,8 @@ jobs:
core.warning(
"PR head moved during changed-file snapshot; treating file list as truncated."
);
+ } else {
+ changedFilesHeadSha = headShaForFiles;
}
changedFiles.length = 0;
changedFiles.push(...listedFiles);
@@ -794,12 +796,6 @@ jobs:
allowedBases: ALLOWED_BASES,
title: pr.title,
body: pr.body,
- behindMain,
- behindBase,
- aheadMain,
- authorPermission,
- permissionLookupFailed,
- ancestryLookupFailed,
stackedBase,
// A maintainer issue comment ("not touching gui") waives the
// GUI-screenshot gate; the comments are already fetched above.
@@ -812,7 +808,37 @@ jobs:
// the Hygiene comment section, but Ready / review-ready must not
// clear while those checks fail. Re-assess here from the same
// trusted scripts so the gate cannot race ahead of hygiene.
- const labelNames = (pr.labels ?? []).map(label => label.name);
+ const liveLabelNames = (pr.labels ?? []).map(label => label.name);
+ // Head-bound exception approvals count only under the head binding
+ // the hygiene workflow recorded. This gate reads that record and
+ // never removes labels or writes it.
+ const approvalInput = {
+ labels: liveLabelNames,
+ // Files listed at another head than this run's PR snapshot
+ // confirm no approval.
+ headSha:
+ changedFilesHeadSha !== null && changedFilesHeadSha === pr.head?.sha
+ ? changedFilesHeadSha
+ : null,
+ record: parseApprovalRecord(authoritativeHygieneSection(comments)),
+ eventAction: context.payload.action,
+ };
+ let headRewriteCount = null;
+ if (needsHeadRewriteCount(approvalInput)) {
+ try {
+ headRewriteCount = countHeadRewrites(await github.paginate(
+ github.rest.issues.listEvents,
+ { owner, repo, issue_number: pull_number, per_page: 100 }
+ ));
+ } catch (error) {
+ core.warning(`Could not read head rewrite history: ${error.message}`);
+ }
+ }
+ const { stale: staleApprovals } = reconcileHeadBoundApprovals({
+ ...approvalInput,
+ headRewriteCount,
+ });
+ const labelNames = liveLabelNames.filter(name => !staleApprovals.includes(name));
// Same inputs the hygiene workflow feeds the carry-attribution
// assessor. Both gates must reach the same verdict or Ready can
// clear while hygiene is still red.
@@ -1222,11 +1248,6 @@ jobs:
`Retarget this PR to ${inlineCode(DEFAULT_BASE)} — all contributions go to ${inlineCode(DEFAULT_BASE)}.`
);
}
- if (failures.some(failure => failure.code === "wrong_ancestry")) {
- actions.push(
- `Rebase onto the current ${inlineCode(DEFAULT_BASE)} branch instead of opening from ${inlineCode("main")}.`
- );
- }
if (failures.some(failure => failure.code === "bad_description")) {
actions.push(
"Add a real **Summary** and **Test plan** to the PR description."
@@ -1241,7 +1262,7 @@ jobs:
const hint = HYGIENE_FAILURE_HINTS[failure.code];
if (!hint) continue;
const paths = failure.paths?.length
- ? ` Paths: ${failure.paths.map(p => inlineCode(p)).join(", ")}.`
+ ? ` Paths: ${failure.paths.map(p => inlineCode(escapeControlCharacters(p))).join(", ")}.`
: "";
actions.push(`Fix **${failure.code}** — ${hint}${paths}`);
}
@@ -1355,9 +1376,6 @@ jobs:
if (failure.code === "wrong_base") {
return `wrong target branch (${pr.base.ref}); retarget to ${inlineCode(DEFAULT_BASE)}.`;
}
- if (failure.code === "wrong_ancestry") {
- return "wrong branch ancestry; rebase onto the latest dev.";
- }
if (failure.code === "bad_description") {
return `PR description needs work (${failure.reason}).`;
}
diff --git a/.github/workflows/issue-quality-tests.yml b/.github/workflows/issue-quality-tests.yml
index fd064ce101..3917fda15d 100644
--- a/.github/workflows/issue-quality-tests.yml
+++ b/.github/workflows/issue-quality-tests.yml
@@ -35,42 +35,6 @@ on:
- ".github/workflows/issue-triage.yml"
- ".github/workflows/issue-quality-tests.yml"
- ".github/workflows/pr-hygiene.yml"
- push:
- # Release lines only; review is covered by the pull_request trigger above.
- branches: [main, preview]
- paths:
- - ".github/ISSUE_TEMPLATE/**"
- - ".github/scripts/issue-quality.cjs"
- - ".github/scripts/issue-quality-core.cjs"
- - ".github/scripts/issue-quality*.test.cjs"
- - ".github/scripts/pr-quality.cjs"
- - ".github/scripts/pr-quality.test.cjs"
- - ".github/scripts/pr-quality-messages.cjs"
- - ".github/scripts/pr-quality-messages.test.cjs"
- - ".github/scripts/pr-quality-state.cjs"
- - ".github/scripts/pr-readiness-reattest.cjs"
- - ".github/scripts/pr-quality-state.test.cjs"
- - ".github/scripts/pr-labeler.cjs"
- - ".github/scripts/pr-labeler.test.cjs"
- - ".github/scripts/enforce-pr-target.test.cjs"
- - ".github/scripts/pr-hygiene.cjs"
- - ".github/scripts/pr-hygiene.test.cjs"
- - ".github/scripts/pr-sponsored-surface.cjs"
- - ".github/scripts/pr-sponsored-surface.test.cjs"
- - ".github/scripts/issue-translation.cjs"
- - ".github/scripts/issue-translation.test.cjs"
- - ".github/scripts/issue-triage*.cjs"
- - ".github/scripts/copilot-workflows.test.cjs"
- - ".github/scripts/install-copilot-cli.sh"
- - ".github/scripts/run-copilot-inference*.cjs"
- - ".github/scripts/parse-issue-translation-response.cjs"
- - ".github/scripts/parse-issue-translation-response.test.cjs"
- - ".github/workflows/enforce-issue-quality.yml"
- - ".github/workflows/enforce-pr-target.yml"
- - ".github/workflows/pr-labeler.yml"
- - ".github/workflows/issue-triage.yml"
- - ".github/workflows/issue-quality-tests.yml"
- - ".github/workflows/pr-hygiene.yml"
permissions:
contents: read
diff --git a/.github/workflows/k3s-image.yml b/.github/workflows/k3s-image.yml
new file mode 100644
index 0000000000..fbfa11a3af
--- /dev/null
+++ b/.github/workflows/k3s-image.yml
@@ -0,0 +1,74 @@
+name: k3s hub image
+
+# Builds the hub image that gujoai k3s-infra runs (live/pve-k3s-svc/opencodex) from main of
+# dalsoop/opencodex and from the hub version tags (hub/-), and pushes it to GHCR.
+# The image tag is -k3s-. One commit gets one
+# image: when that tag already exists (main was built before the version tag on the same commit was
+# pushed), the job reports the existing digest instead of building again. k3s-infra pins the image by
+# the digest printed in the job summary.
+
+on:
+ push:
+ branches: [main]
+ tags: ["hub/*"]
+ workflow_dispatch:
+
+permissions:
+ contents: read
+ packages: write
+
+concurrency:
+ # Keyed on the commit, so a main push and a tag push of the same commit run one after the other.
+ group: k3s-image-${{ github.sha }}
+ cancel-in-progress: false
+
+jobs:
+ image:
+ if: github.repository == 'dalsoop/opencodex'
+ runs-on: ubuntu-latest
+ timeout-minutes: 30
+ steps:
+ - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
+ with:
+ persist-credentials: false
+ - uses: docker/setup-buildx-action@e468171a9de216ec08956ac3ada2f0791b6bd435 # v3.11.1
+ - uses: docker/login-action@74a5d142397b4f367a81961eba4e8cd7edddf772 # v3.4.0
+ with:
+ registry: ghcr.io
+ username: ${{ github.actor }}
+ password: ${{ secrets.GITHUB_TOKEN }}
+ - name: Tags
+ id: tags
+ run: |
+ version=$(jq -r .version package.json)
+ short=${GITHUB_SHA::12}
+ tag="ghcr.io/dalsoop/opencodex:${version}-k3s-${short}"
+ echo "tags=${tag}" >> "$GITHUB_OUTPUT"
+ if digest=$(docker buildx imagetools inspect "$tag" --format '{{json .Manifest}}' 2>/dev/null | jq -r .digest) && [ -n "$digest" ] && [ "$digest" != null ]; then
+ echo "existing=${digest}" >> "$GITHUB_OUTPUT"
+ echo "${tag} already exists (${digest}); not building again"
+ fi
+ - id: build
+ if: steps.tags.outputs.existing == ''
+ uses: docker/build-push-action@263435318d21b8e681c14492fe198d362a7d2c83 # v6.18.0
+ with:
+ context: .
+ platforms: linux/amd64
+ push: true
+ provenance: false
+ tags: ${{ steps.tags.outputs.tags }}
+ labels: |
+ org.opencontainers.image.source=https://github.com/dalsoop/opencodex
+ org.opencontainers.image.revision=${{ github.sha }}
+ - name: Summary
+ env:
+ IMAGE: ${{ steps.tags.outputs.tags }}
+ DIGEST: ${{ steps.build.outputs.digest || steps.tags.outputs.existing }}
+ REF: ${{ github.ref }}
+ run: |
+ {
+ echo "ref: ${REF}"
+ echo "image: ${IMAGE}"
+ echo "digest: ${DIGEST}"
+ } >> "$GITHUB_STEP_SUMMARY"
+ echo "image ${IMAGE}@${DIGEST}"
diff --git a/.github/workflows/personal-ci.yml b/.github/workflows/personal-ci.yml
deleted file mode 100644
index d767b0cf14..0000000000
--- a/.github/workflows/personal-ci.yml
+++ /dev/null
@@ -1,56 +0,0 @@
-name: Personal repository CI
-
-on:
- push:
- branches: [main, personal/main-integration]
- workflow_dispatch:
-
-permissions:
- contents: read
-
-concurrency:
- group: personal-ci-${{ github.ref }}
- cancel-in-progress: true
-
-jobs:
- verify:
- if: github.repository == 'dalsoop/opencodex'
- runs-on: ubuntu-latest
- timeout-minutes: 45
- strategy:
- fail-fast: false
- matrix:
- shard: [1, 2, 3, 4]
- steps:
- - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- with:
- persist-credentials: false
- fetch-tags: true
- - uses: ./.github/actions/setup-project-bun
- with:
- role: test-runner
- - run: bun install --frozen-lockfile
- - run: bun run typecheck
- - name: Typecheck personal installer
- run: bun x tsc --ignoreConfig --noEmit --target esnext --module esnext --moduleResolution bundler --skipLibCheck --types bun scripts/personal-install.ts
- - run: bun run structure:check
- - run: bun run privacy:scan
- - run: bun run build:gui
- - name: Full suite in isolated batches
- env:
- TEST_SHARD: ${{ matrix.shard }}/4
- BUN_TEST_FILE_SCOPE: all
- run: bash scripts/ci/run-bun-test-batches.sh "$TEST_SHARD"
- docs:
- if: github.repository == 'dalsoop/opencodex'
- runs-on: ubuntu-latest
- timeout-minutes: 15
- steps:
- - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- with:
- persist-credentials: false
- - uses: ./.github/actions/setup-project-bun
- - run: bun install --frozen-lockfile
- working-directory: docs-site
- - run: bun run build
- working-directory: docs-site
diff --git a/.github/workflows/pr-hygiene.yml b/.github/workflows/pr-hygiene.yml
index b60943b93a..73e7bb72bf 100644
--- a/.github/workflows/pr-hygiene.yml
+++ b/.github/workflows/pr-hygiene.yml
@@ -41,12 +41,11 @@ jobs:
# PR's head, so `base.sha` let an unpromoted commit choose which code
# runs with this job's issues/pull-requests write token.
#
- # The branch is chosen, not fixed: `pull_request_target` loads this
- # workflow from the default branch, so a `main`-targeting PR must
- # take its scripts from `main` too, or the gate runs a `main`
- # workflow against `dev` scripts. Everything else, including stacked
- # bases, resolves to `dev`, the single integration line.
- ref: ${{ github.event.pull_request.base.ref == 'main' && 'main' || 'dev' }}
+ # `pull_request_target` loads this workflow from the default branch,
+ # and `dev` is the single integration line. A fixed `dev` keeps the
+ # scripts, workflow definition, and stacked children on one trusted
+ # revision.
+ ref: dev
persist-credentials: false
sparse-checkout: .github/scripts
@@ -57,7 +56,12 @@ jobs:
const path = require("node:path");
const {
collectDeterministicHygieneFailures,
+ countHeadRewrites,
+ formatApprovalRecord,
HYGIENE_FAILURE_HINTS,
+ needsHeadRewriteCount,
+ parseApprovalRecord,
+ reconcileHeadBoundApprovals,
} = require(
path.join(process.cwd(), ".github", "scripts", "pr-hygiene.cjs"),
);
@@ -68,8 +72,11 @@ jobs:
path.join(process.cwd(), ".github", "scripts", "pr-referenced-authors.cjs"),
);
const {
- GATE_MARKER,
HYGIENE_MARKER,
+ authoritativeHygieneSection,
+ escapeControlCharacters,
+ isGateComment,
+ isStandaloneHygieneComment,
withHygieneSection
} = require(
path.join(process.cwd(), ".github", "scripts", "pr-quality-messages.cjs"),
@@ -104,33 +111,79 @@ jobs:
}
for (const name of Object.keys(labelDefinitions)) await ensureLabel(name);
+ // Counts head rewrites (force pushes, restored branches); null when
+ // the history cannot be read, which confirms no approval.
+ async function readHeadRewrites() {
+ try {
+ return countHeadRewrites(
+ await github.paginate(github.rest.issues.listEvents, {
+ owner, repo, issue_number: pull_number, per_page: 100,
+ }),
+ );
+ } catch (error) {
+ core.warning(`Could not read head rewrite history: ${error.message}`);
+ return null;
+ }
+ }
+ // Read before the snapshot so the published record never counts a
+ // rewrite that happened after the head it names.
+ const headRewritesBefore = await readHeadRewrites();
const { data: pr } = await github.rest.pulls.get({ owner, repo, pull_number });
const files = await github.paginate(github.rest.pulls.listFiles, {
owner, repo, pull_number, per_page: 100,
});
+ // The file list must belong to the head the approvals are judged
+ // against; if the head moved while listing, none is confirmed.
+ const { data: prAfterFiles } = await github.rest.pulls.get({ owner, repo, pull_number });
+ const filesAtHead = prAfterFiles.head?.sha === pr.head.sha;
const labels = new Set(pr.labels.map((label) => label.name));
+ const comments = await github.paginate(github.rest.issues.listComments, {
+ owner, repo, issue_number: pull_number, per_page: 100,
+ });
// Exception approvals are head-specific: a new commit invalidates
// them, so a contributor cannot obtain one narrow exception and
- // then push unreviewed violations under the same label.
- if (context.payload.action === "synchronize") {
- for (const name of [
- "test-exception-approved",
- "suppression-approved",
- "generated-change-approved",
- "dependency-change-approved",
- "attribution-approved",
- ]) {
- if (labels.has(name)) {
- await github.rest.issues.removeLabel({
- owner, repo, issue_number: pull_number, name,
- });
- labels.delete(name);
- }
+ // then push unreviewed violations under the same label. This is
+ // decided on every run from the head this workflow last recorded,
+ // not from the triggering action: a queued synchronize run can be
+ // replaced by a later event before it executes.
+ const approvalInput = {
+ labels: [...labels],
+ headSha: filesAtHead ? pr.head.sha : null,
+ record: parseApprovalRecord(authoritativeHygieneSection(comments)),
+ eventAction: context.payload.action,
+ };
+ const headRewriteCount = needsHeadRewriteCount(approvalInput)
+ ? await readHeadRewrites()
+ : null;
+ const { stale: staleApprovals } = reconcileHeadBoundApprovals({
+ ...approvalInput,
+ headRewriteCount,
+ });
+ for (const name of staleApprovals) {
+ try {
+ await github.rest.issues.removeLabel({
+ owner, repo, issue_number: pull_number, name,
+ });
+ } catch (error) {
+ if (error.status !== 404) throw error;
}
+ labels.delete(name);
}
+ // Written last in the hygiene section on every outcome; the next
+ // run of this workflow and the PR gate both read it.
+ const approvalLines = [
+ ...(staleApprovals.length === 0
+ ? []
+ : [
+ "",
+ `ℹ️ Removed ${staleApprovals.map((name) => "\x60" + name + "\x60").join(", ")}: these approvals could not be confirmed for this head (\x60${pr.head.sha.slice(0, 7)}\x60). A maintainer can re-apply them after reviewing it.`,
+ ]),
+ "",
+ formatApprovalRecord({ head: pr.head.sha, headRewrites: headRewritesBefore }),
+ ];
// Sponsorship is head-independent: it is about which surfaces the
// change touches, not about the state of a particular revision, so
- // it is NOT cleared by the synchronize sweep above.
+ // it is not head-bound.
// author_association is not enough: a read/triage collaborator can
// be COLLABORATOR without write access. Match the PR quality gate.
let authorPermission = null;
@@ -188,17 +241,18 @@ jobs:
}
async function upsert(body) {
- const comments = await github.paginate(github.rest.issues.listComments, {
- owner, repo, issue_number: pull_number, per_page: 100,
- });
// The single consolidated bot comment is the one the PR gate
// owns (GATE_MARKER). Write the hygiene status into that same
// comment so there is one editable message, not two. Fall back
// to a standalone hygiene comment only when the gate has not
- // posted yet (the next gate run absorbs it).
- const gateComment = comments.find(
- (comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(GATE_MARKER),
- );
+ // posted yet; the next hygiene run writes into the gate comment.
+ // The comment list was read once above, before the approval
+ // check; both workflows share one concurrency group, so no gate
+ // write lands in between.
+ // Classified by the marker each body starts with, the same rule
+ // the approval-record reader uses: echoed paths can contain a
+ // marker string but never start the comment.
+ const gateComment = comments.find(isGateComment);
if (gateComment) {
// The hygiene block already carries the marker; strip the
// standalone body's own marker line before merging.
@@ -210,9 +264,7 @@ jobs:
await github.rest.issues.updateComment({ owner, repo, comment_id: gateComment.id, body: merged });
return;
}
- const existingHygiene = comments.find(
- (comment) => comment.user?.login === "github-actions[bot]" && comment.body?.includes(marker),
- );
+ const existingHygiene = comments.find(isStandaloneHygieneComment);
if (existingHygiene) {
await github.rest.issues.updateComment({ owner, repo, comment_id: existingHygiene.id, body });
} else {
@@ -222,17 +274,17 @@ jobs:
if (failures.length === 0) {
await setBlocked(false);
- await upsert(`${marker}\n\n✅ **Deterministic PR hygiene checks passed.**`);
+ await upsert([marker, "", "✅ **Deterministic PR hygiene checks passed.**", ...approvalLines].join("\n"));
return;
}
const lines = failures.map((failure) => {
const paths = failure.paths?.length
- ? ` Paths: ${failure.paths.map((p) => `\`${p}\``).join(", ")}.`
+ ? ` Paths: ${failure.paths.map((p) => `\`${escapeControlCharacters(p)}\``).join(", ")}.`
: "";
return `- **${failure.code}** — ${HYGIENE_FAILURE_HINTS[failure.code] ?? failure.code}${paths}`;
});
await setBlocked(true);
- await upsert([marker, "", "⚠️ **Deterministic hygiene checks failed.**", "", ...lines].join("\n"));
+ await upsert([marker, "", "⚠️ **Deterministic hygiene checks failed.**", "", ...lines, ...approvalLines].join("\n"));
core.setFailed(`PR hygiene failed: ${failures.map((f) => f.code).join(", ")}`);
diff --git a/.github/workflows/pr-labeler.yml b/.github/workflows/pr-labeler.yml
index 309fd40b8f..f7c2b6fa63 100644
--- a/.github/workflows/pr-labeler.yml
+++ b/.github/workflows/pr-labeler.yml
@@ -1,9 +1,8 @@
name: PR Labeler
# pull_request_target always loads this workflow from the repository DEFAULT
-# branch (currently `main`), not from `dev`. Landing here on `dev` alone does
-# not change live labeler behavior until the change is also on that default
-# branch — same promotion model as enforce-issue-quality.yml.
+# branch, which is `dev`. A change lands on the live labeler as soon as it is on
+# `dev` — same model as enforce-issue-quality.yml.
on:
pull_request_target:
# labeled/unlabeled let a human type-label change enqueue a fresher run in the
diff --git a/.github/workflows/react-doctor.yml b/.github/workflows/react-doctor.yml
index d8ac13ab36..2efa81541c 100644
--- a/.github/workflows/react-doctor.yml
+++ b/.github/workflows/react-doctor.yml
@@ -14,11 +14,15 @@ name: React Doctor
on:
# Scans the PR's changed files relative to the merge base of the target branch.
+ # The scan reads only gui/ (`directory: gui` below), so a pull request that
+ # changes nothing there has nothing to scan: it used to start a full-history
+ # checkout and an npm install on every PR for an empty changed-file list. No
+ # branch rule requires this check, so a PR it skips is not left waiting on it.
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
- # Scans `main` on every push to track the health-score trend.
- push:
- branches: ["main"]
+ paths:
+ - "gui/**"
+ - ".github/workflows/react-doctor.yml"
permissions:
contents: read
@@ -27,8 +31,8 @@ permissions:
# and the CLI exits 1 on ENOENT even for fork PRs.
pull-requests: read
-# Cancels any in-flight scan for the same PR (or branch, on push) the moment a
-# new commit arrives, so only the latest run remains.
+# Cancels any in-flight scan for the same PR the moment a new commit arrives,
+# so only the latest run remains.
concurrency:
group: react-doctor-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: true
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index 152d4a8ada..6cb29b6a76 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -1,15 +1,12 @@
name: Release
-# Publish opencodex to npm — jawcode-style: triggered from the Actions tab with an explicit
-# version, dist-tag, and a dry-run-first default. Bump package.json on main BEFORE dispatching
-# (or use `bun run release `, which does the bump+commit+push+dispatch for you); the
-# workflow verifies the version matches before publishing.
+# Select a tested dev source with the workflow revision pinned independently from that source.
on:
workflow_dispatch:
inputs:
version:
- description: "Version to publish — must equal package.json (e.g. 0.1.0)"
- required: true
+ description: "Optional expected derived version; required original version when resuming"
+ required: false
type: string
tag:
description: "npm dist-tag"
@@ -25,13 +22,13 @@ on:
type: boolean
default: true
resume-after-npm-publish:
- description: "Operator attestation: a previous run of this workflow acknowledged npm publication for this exact commit; skip npm publish and complete the GitHub side"
+ description: "Attest npm publication was acknowledged for the exact supplied source and version; skip npm publish"
required: false
type: boolean
default: false
expected-sha:
- description: "Immutable release commit this dispatch must publish (fail if the branch moved)"
- required: true
+ description: "Optional exact full source SHA; it must have qualifying dev CI evidence"
+ required: false
type: string
permissions: {}
@@ -45,39 +42,121 @@ jobs:
runs-on: ubuntu-latest
permissions:
contents: read
+ actions: read
+ outputs:
+ source_sha: ${{ steps.source.outputs.source_sha }}
+ workflow_sha: ${{ steps.source.outputs.workflow_sha }}
+ version: ${{ steps.version.outputs.version }}
steps:
- - name: Checkout trusted dispatch guard
+ - name: Checkout trusted workflow revision
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
- ref: ${{ github.event.repository.default_branch }}
+ ref: ${{ github.sha }}
persist-credentials: false
- path: trusted-dispatch
+ fetch-depth: 0
- - name: Validate release dispatch
+ - name: Resolve eligible source
+ id: source
env:
- EXPECTED_SHA: ${{ inputs.expected-sha }}
+ GH_TOKEN: ${{ github.token }}
+ REQUESTED_SHA: ${{ inputs.expected-sha }}
+ REQUESTED_VERSION: ${{ inputs.version }}
+ RESUME: ${{ inputs.resume-after-npm-publish }}
+ DRY_RUN: ${{ inputs.dry-run }}
run: |
+ set -euo pipefail
+ test "$GITHUB_EVENT_NAME" = workflow_dispatch && test "$GITHUB_REF" = refs/heads/dev || {
+ echo '::error::Release workflow must be dispatched from trusted dev.'; exit 1;
+ }
node - <<'NODE'
- const { validateReleaseDispatch } = require(
- "./trusted-dispatch/.github/scripts/release-dispatch-guard.cjs",
- );
-
- const failure = validateReleaseDispatch({
- eventName: process.env.GITHUB_EVENT_NAME,
- ref: process.env.GITHUB_REF,
- expectedSha: process.env.EXPECTED_SHA,
- actualSha: process.env.GITHUB_SHA,
- });
-
- if (failure) {
- console.error(`::error::${failure}`);
- process.exit(1);
+ const { validateReleaseDispatch } = require('./.github/scripts/release-dispatch-guard.cjs');
+ const failure = validateReleaseDispatch({ eventName: process.env.GITHUB_EVENT_NAME,
+ ref: process.env.GITHUB_REF, sourceSha: process.env.REQUESTED_SHA, workflowSha: process.env.GITHUB_SHA });
+ if (failure) throw new Error(failure);
+ NODE
+ if [ "$RESUME" = true ]; then
+ if [ -z "$REQUESTED_SHA" ] || [ -z "$REQUESTED_VERSION" ] || [ "$DRY_RUN" != false ]; then
+ echo '::error::Resume requires the original source SHA and version and cannot be a dry run.'; exit 1
+ fi
+ fi
+ if [ -n "$REQUESTED_SHA" ]; then
+ result="$(node .github/scripts/release-evidence.cjs resolve "$REQUESTED_SHA")"
+ else
+ result="$(node .github/scripts/release-evidence.cjs resolve)"
+ fi
+ RESULT="$result" node - <<'NODE'
+ const fs = require('node:fs');
+ const result = JSON.parse(process.env.RESULT);
+ if (!/^[0-9a-f]{40}$/.test(result.sourceSha) || !Number.isSafeInteger(result.ciRunId) || result.ciRunId <= 0 ||
+ (process.env.REQUESTED_SHA && result.sourceSha !== process.env.REQUESTED_SHA)) {
+ throw new Error('Invalid source evidence');
}
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `source_sha=${result.sourceSha}\nworkflow_sha=${process.env.GITHUB_SHA}\n`);
NODE
+ - name: Checkout selected source for version resolution
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ steps.source.outputs.source_sha }}
+ path: candidate
+ persist-credentials: false
+
+ - name: Setup project Bun
+ uses: ./.github/actions/setup-project-bun
+
+ - name: Resolve release version
+ id: version
+ env:
+ CHANNEL: ${{ inputs.tag }}
+ EXPECTED_VERSION: ${{ inputs.version }}
+ RESUME: ${{ inputs.resume-after-npm-publish }}
+ run: |
+ set -euo pipefail
+ bun scripts/release-version-sources.ts check --root candidate
+ if [ "$RESUME" = true ]; then
+ # JavaScript template literals are evaluated by Bun, not the shell.
+ # shellcheck disable=SC2016
+ bun -e '
+ import { parseVersion } from "./scripts/version-line.ts";
+ import { appendFileSync } from "node:fs";
+ const value = process.env.EXPECTED_VERSION ?? "", channel = process.env.CHANNEL;
+ const parsed = parseVersion(value);
+ if (!/^\d+\.\d+\.\d+(?:-preview\.\d{8}(?:\.\d+)?)?$/.test(value) || !parsed ||
+ !((channel === "latest" && parsed.prerelease === null) ||
+ (channel === "preview" && parsed.prerelease?.[0] === "preview"))) throw Error("invalid original release version or channel");
+ appendFileSync(process.env.GITHUB_OUTPUT, `version=${value}\n`);
+ '
+ exit 0
+ fi
+ npm view "$(node -p "require('./package.json').name")" versions --json > "$RUNNER_TEMP/release-npm-versions.json"
+ git tag --list 'v[0-9]*' > "$RUNNER_TEMP/release-tags.txt"
+ # JavaScript template literals are evaluated by Bun, not the shell.
+ # shellcheck disable=SC2016
+ bun -e '
+ import { devReleaseVersion, parseVersion } from "./scripts/version-line.ts";
+ import { readFileSync, appendFileSync } from "node:fs";
+ const versions = JSON.parse(readFileSync(`${process.env.RUNNER_TEMP}/release-npm-versions.json`, "utf8"));
+ if (!Array.isArray(versions) || versions.some(v => typeof v !== "string")) throw new Error("invalid npm versions");
+ const tags = readFileSync(`${process.env.RUNNER_TEMP}/release-tags.txt`, "utf8").trim().split("\n").filter(Boolean).map(v => v.slice(1));
+ const all = [...new Set([...versions, ...tags])];
+ const stableTags = [], previewTags = [];
+ for (const version of all) {
+ const parsed = parseVersion(version);
+ if (!parsed) throw new Error(`invalid published version: ${version}`);
+ (parsed.prerelease === null ? stableTags : previewTags).push(version);
+ }
+ const channel = process.env.CHANNEL;
+ if (channel !== "latest" && channel !== "preview") throw new Error("invalid release channel");
+ const base = JSON.parse(readFileSync("candidate/package.json", "utf8")).version;
+ const stamp = new Date().toISOString().slice(0, 10).replaceAll("-", "");
+ const version = devReleaseVersion({ base, stableTags, previewTags, channel, stamp });
+ if (process.env.EXPECTED_VERSION && process.env.EXPECTED_VERSION !== version) throw new Error("expected version differs from derived version");
+ appendFileSync(process.env.GITHUB_OUTPUT, `version=${version}\n`);
+ '
+
# Every publication precondition the dispatch can already decide, checked before any runner
# starts packaging: channel and dist-tag, every version source, the tag, the GitHub release,
- # npm, the global tag ordering and the dev pre-move (scripts/ci/release-preflight.sh).
+ # npm and the global tag ordering (scripts/ci/release-preflight.sh).
#
# Run 35783865160 packaged 2.62.0 for nineteen minutes and then failed the ordering gate in
# `publish` on v2.63.0-preview.20260923. That tag already existed when the run's first job
@@ -96,23 +175,37 @@ jobs:
timeout-minutes: 5
permissions:
contents: read
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
persist-credentials: false
+ fetch-depth: 0
fetch-tags: true
- name: Setup project Bun
uses: ./.github/actions/setup-project-bun
+ - name: Stamp preflight version
+ run: |
+ set -euo pipefail
+ test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION"
+ test "$(git rev-parse HEAD)" = "$WORKFLOW_SHA"
+ bun scripts/release-version-sources.ts sync "$RELEASE_VERSION"
+ bun scripts/release-version-sources.ts check "$RELEASE_VERSION"
+
- name: Fetch the dev line
run: git fetch --no-tags --depth=1 origin +refs/heads/dev:refs/remotes/origin/dev
- name: Refuse a release that cannot publish
env:
GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
NPM_DIST_TAG: ${{ inputs.tag }}
DRY_RUN: ${{ inputs.dry-run }}
RESUME: ${{ inputs.resume-after-npm-publish }}
@@ -120,6 +213,7 @@ jobs:
package-standalone:
needs: [validate-dispatch, preflight]
+ if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' }}
strategy:
fail-fast: false
matrix:
@@ -156,14 +250,35 @@ jobs:
# actions: read lets the SignPath action read this job and download the unsigned artifact.
actions: read
contents: read
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.source_sha }}
+ persist-credentials: false
+
+ - name: Checkout trusted release policy
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ path: trusted-release-policy
persist-credentials: false
- name: Setup project Bun
- uses: ./.github/actions/setup-project-bun
+ uses: ./trusted-release-policy/.github/actions/setup-project-bun
+
+ - name: Stamp and verify release version
+ shell: bash
+ run: |
+ set -euo pipefail
+ test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION"
+ test "$(git rev-parse HEAD)" = "$SOURCE_SHA"
+ bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root .
+ bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root .
# Windows Authenticode signing through SignPath Foundation (#7207). Decided before the build, so
# a broken SignPath configuration fails in seconds instead of after the build. The rules
@@ -201,7 +316,10 @@ jobs:
OPENCODEX_HOME="$RUNNER_TEMP/ocx-home" "$binary" start --port 10177 >"$RUNNER_TEMP/ocx.log" 2>&1 &
pid=$!
trap 'kill "$pid" 2>/dev/null || true' EXIT
- for _ in $(seq 1 30); do curl -fsS http://127.0.0.1:10177/healthz && break || sleep 1; done
+ for _ in $(seq 1 30); do
+ if curl -fsS http://127.0.0.1:10177/healthz; then break; fi
+ sleep 1
+ done
curl -fsS http://127.0.0.1:10177/healthz
test "$(curl -sS -o /dev/null -w '%{http_code}' http://127.0.0.1:10177/)" = 200
@@ -276,12 +394,14 @@ jobs:
- name: Archive standalone release
shell: bash
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
STANDALONE_TARGET: ${{ matrix.target }}
run: |
set -euo pipefail
cd "dist/standalone/$STANDALONE_TARGET"
if [[ "$RUNNER_OS" == "Windows" ]]; then
+ # Variables in this literal belong to PowerShell.
+ # shellcheck disable=SC2016
powershell -NoProfile -Command 'Compress-Archive -Path ocx.exe,gui,keyring -DestinationPath ("../../ocx-{0}-{1}.zip" -f $env:RELEASE_VERSION,$env:STANDALONE_TARGET) -Force'
else
tar -czf "../../ocx-${RELEASE_VERSION}-${STANDALONE_TARGET}.tar.gz" ocx gui keyring
@@ -308,6 +428,7 @@ jobs:
package-desktop:
needs: [validate-dispatch, preflight]
+ if: ${{ github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/dev' }}
strategy:
fail-fast: false
matrix:
@@ -341,6 +462,9 @@ jobs:
actions: read
contents: read
env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
# Whether this run holds the Developer ID material at all. A run without it still builds
# locally useful bundles; a run with it must not silently downgrade any part of the app.
DESKTOP_SIGNING_CONFIGURED: ${{ secrets.APPLE_CERTIFICATE != '' }}
@@ -348,10 +472,27 @@ jobs:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.source_sha }}
+ persist-credentials: false
+
+ - name: Checkout trusted release policy
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ path: trusted-release-policy
persist-credentials: false
- name: Setup project Bun
- uses: ./.github/actions/setup-project-bun
+ uses: ./trusted-release-policy/.github/actions/setup-project-bun
+
+ - name: Stamp and verify release version
+ shell: bash
+ run: |
+ set -euo pipefail
+ test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION"
+ test "$(git rev-parse HEAD)" = "$SOURCE_SHA"
+ bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root .
+ bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root .
# Windows Authenticode signing through SignPath Foundation (#7207). Decided before the build, so
# a broken SignPath configuration fails in seconds instead of after the build. The rules
@@ -379,8 +520,8 @@ jobs:
- name: Verify every version source matches the release
shell: bash
env:
- RELEASE_VERSION: ${{ inputs.version }}
- run: bun scripts/release-version-sources.ts check "$RELEASE_VERSION"
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
+ run: bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root .
- name: Install project dependencies
run: bun install --frozen-lockfile --os=${{ matrix.dependency_os }} --cpu=${{ matrix.dependency_cpu }}
@@ -548,7 +689,7 @@ jobs:
if: runner.os == 'Windows'
shell: bash
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
run: bun desktop/scripts/windows-installer-config.ts "$RELEASE_VERSION" "$RUNNER_TEMP/opencodex-msi.json"
- name: Preserve the compiled Linux sidecar
@@ -706,7 +847,7 @@ jobs:
- name: Rename release assets
shell: bash
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
DESKTOP_TARGET: ${{ matrix.target }}
run: |
args=( \
@@ -785,6 +926,227 @@ jobs:
security delete-keychain "${OPENCODEX_SIGNING_KEYCHAIN}"
fi
+ # Candidate code and npm lifecycle scripts run only in this read-only job.
+ package-npm:
+ needs: [validate-dispatch, preflight]
+ runs-on: ubuntu-latest
+ timeout-minutes: 25
+ permissions:
+ contents: read
+ outputs:
+ artifact_id: ${{ steps.upload.outputs.artifact-id }}
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
+ steps:
+ - name: Checkout selected source
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ needs.validate-dispatch.outputs.source_sha }}
+ persist-credentials: false
+
+ - name: Checkout trusted release policy
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ path: trusted-release-policy
+ persist-credentials: false
+
+ - name: Setup project Bun
+ uses: ./trusted-release-policy/.github/actions/setup-project-bun
+
+ - name: Stamp and verify release version
+ run: |
+ set -euo pipefail
+ test -n "$SOURCE_SHA" && test -n "$WORKFLOW_SHA" && test -n "$RELEASE_VERSION"
+ test "$(git rev-parse HEAD)" = "$SOURCE_SHA"
+ bun trusted-release-policy/scripts/release-version-sources.ts sync "$RELEASE_VERSION" --root .
+ bun trusted-release-policy/scripts/release-version-sources.ts check "$RELEASE_VERSION" --root .
+
+ - name: Install dependencies
+ run: bun install --frozen-lockfile
+
+ - name: Build npm package
+ run: |
+ set -euo pipefail
+ npm run prepublishOnly
+ npm run prepack
+ # All candidate lifecycle scripts have finished. Bind the packed manifest
+ # to the selected commit; npm pack below runs with scripts disabled.
+ node - <<'NODE'
+ const fs = require('node:fs'), { spawnSync } = require('node:child_process');
+ const source = process.env.SOURCE_SHA;
+ if (!/^[0-9a-f]{40}$/.test(source || '')) throw Error('invalid source SHA');
+ const git = spawnSync('git', ['rev-parse', 'HEAD'], { encoding: 'utf8' });
+ if (git.status !== 0 || git.stdout.trim() !== source) throw Error('npm checkout source mismatch');
+ const stat = fs.lstatSync('package.json');
+ if (!stat.isFile() || stat.isSymbolicLink()) throw Error('invalid npm manifest');
+ const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8'));
+ if (pkg.version !== process.env.RELEASE_VERSION) throw Error('npm manifest version mismatch');
+ pkg.gitHead = source;
+ fs.writeFileSync('package.json.release-tmp', JSON.stringify(pkg, null, 2) + '\n', { flag: 'wx' });
+ fs.renameSync('package.json.release-tmp', 'package.json');
+ NODE
+ mkdir -p "$RUNNER_TEMP/npm-pack" dist/npm
+ npm pack --ignore-scripts --pack-destination "$RUNNER_TEMP/npm-pack"
+ shopt -s nullglob
+ packages=("$RUNNER_TEMP"/npm-pack/*.tgz)
+ test "${#packages[@]}" -eq 1
+ cp -- "${packages[0]}" dist/npm/package.tgz
+
+ - name: Upload npm package
+ id: upload
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: npm-package-unverified
+ path: dist/npm/package.tgz
+ if-no-files-found: error
+ retention-days: 7
+
+ # A fresh runner computes the receipt; candidate code cannot execute in this job.
+ verify-npm:
+ needs: [validate-dispatch, package-npm]
+ runs-on: ubuntu-latest
+ permissions:
+ contents: read
+ actions: read
+ outputs:
+ artifact_id: ${{ steps.upload.outputs.artifact-id }}
+ sha256: ${{ steps.receipt.outputs.sha256 }}
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
+ steps:
+ - name: Checkout trusted workflow revision
+ uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ persist-credentials: false
+ fetch-depth: 0
+
+ - name: Resolve trusted Bun version
+ id: bun-version
+ run: |
+ # JavaScript template literals are evaluated by Node, not the shell.
+ # shellcheck disable=SC2016
+ node -e 'const v = require("./package.json").dependencies.bun; if (!/^\d+\.\d+\.\d+$/.test(v)) throw Error("invalid Bun pin"); require("node:fs").appendFileSync(process.env.GITHUB_OUTPUT, `version=${v}\n`);'
+
+ - name: Setup trusted Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: ${{ steps.bun-version.outputs.version }}
+
+ - name: Download npm package by immutable artifact ID
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ artifact-ids: ${{ needs.package-npm.outputs.artifact_id }}
+ path: npm-artifact
+
+ - name: Recheck source CI and service evidence
+ env:
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ node .github/scripts/release-evidence.cjs check "$SOURCE_SHA"
+ baseline_tag="$(git tag --merged "$SOURCE_SHA" --list 'v[0-9]*' | bun -e '
+ import { parseVersion, compareVersions } from "./scripts/version-line.ts";
+ const tags = (await Bun.stdin.text()).trim().split("\n").filter(Boolean);
+ const versions = tags.map(tag => ({ tag, version: tag.slice(1) }));
+ if (versions.some(item => !parseVersion(item.version))) throw new Error("invalid release tag");
+ const eligible = versions.filter(item => compareVersions(item.version, process.env.RELEASE_VERSION) < 0);
+ eligible.sort((a, b) => compareVersions(a.version, b.version));
+ console.log(eligible.at(-1)?.tag ?? "");
+ ')"
+ baseline=--initial
+ if [ -n "$baseline_tag" ]; then
+ draft="$(gh release view "$baseline_tag" --json isDraft --jq .isDraft)"
+ test "$draft" = false || { echo '::error::Service baseline is not a published release.'; exit 1; }
+ baseline="$(git rev-parse "refs/tags/${baseline_tag}^{commit}")"
+ fi
+ range="$(node .github/scripts/release-evidence.cjs service-range "$SOURCE_SHA" "$baseline")"
+ required="$(RANGE="$range" node -e 'const x = JSON.parse(process.env.RANGE); if (typeof x.required !== "boolean") throw Error("invalid service range"); process.stdout.write(String(x.required));')"
+ if [ "$required" = true ]; then
+ node .github/scripts/release-evidence.cjs service "$SOURCE_SHA" || {
+ echo "::error::Dispatch service-lifecycle.yml from dev for source ${SOURCE_SHA} and wait for all platforms."; exit 1;
+ }
+ fi
+
+ - name: Require reconciled publication history
+ if: ${{ inputs.resume-after-npm-publish != true }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ NPM_DIST_TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ if ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || [ -z "$RELEASE_VERSION" ]; then
+ echo '::error::Invalid release identity for history reconciliation.'; exit 1
+ fi
+ case "$NPM_DIST_TAG" in
+ latest) channel=stable ;;
+ preview) channel=preview ;;
+ *) echo '::error::Invalid release channel.'; exit 1 ;;
+ esac
+ node .github/scripts/release-history.cjs check "$SOURCE_SHA" "$RELEASE_VERSION" "$channel"
+
+ - name: Verify resume registry identity
+ id: resume-identity
+ if: ${{ inputs.resume-after-npm-publish == true }}
+ run: |
+ set -euo pipefail
+ pkg_name="$(node -p "require('./package.json').name")"
+ registry_version="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || {
+ echo '::error::Cannot read the exact npm version; resume refused.'; exit 1;
+ }
+ REGISTRY_VERSION="$registry_version" node - <<'NODE'
+ const value = JSON.parse(process.env.REGISTRY_VERSION);
+ if (typeof value !== 'string' || value !== process.env.RELEASE_VERSION) throw Error('npm version does not match original release');
+ NODE
+ registry_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || {
+ echo '::error::Cannot read npm gitHead; resume refused.'; exit 1;
+ }
+ bun scripts/verify-release-resume.ts "$SOURCE_SHA" "$registry_head"
+ echo "resume_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT"
+
+ - name: Create verified npm receipt
+ id: receipt
+ run: |
+ set -euo pipefail
+ node - <<'NODE'
+ const fs = require('node:fs');
+ const crypto = require('node:crypto');
+ const { spawnSync } = require('node:child_process');
+ const archive = 'npm-artifact/package.tgz';
+ const sha = /^[0-9a-f]{40}$/;
+ if (!sha.test(process.env.SOURCE_SHA) || !sha.test(process.env.WORKFLOW_SHA) ||
+ !/^\d+$/.test(process.env.GITHUB_RUN_ID) || !/^\d+$/.test(process.env.GITHUB_RUN_ATTEMPT) ||
+ !/^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/.test(process.env.RELEASE_VERSION)) throw new Error('invalid receipt identity');
+ const stat = fs.lstatSync(archive);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > 500 * 1024 * 1024) throw new Error('invalid npm tarball');
+ const entries = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
+ if (entries.status !== 0 || entries.stdout.split('\n').filter(p => p === 'package/package.json').length !== 1) throw new Error('invalid npm manifest entry');
+ const manifest = spawnSync('tar', ['-xOzf', archive, 'package/package.json'], { encoding: 'utf8', maxBuffer: 1024 * 1024 });
+ if (manifest.status !== 0) throw new Error('cannot read npm manifest');
+ const pkg = JSON.parse(manifest.stdout), trusted = JSON.parse(fs.readFileSync('package.json', 'utf8'));
+ if (pkg.name !== trusted.name || pkg.version !== process.env.RELEASE_VERSION || pkg.gitHead !== process.env.SOURCE_SHA) throw new Error('npm package identity or gitHead mismatch');
+ const digest = crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex');
+ const receipt = { sourceSha: process.env.SOURCE_SHA, workflowSha: process.env.WORKFLOW_SHA,
+ version: process.env.RELEASE_VERSION, runId: process.env.GITHUB_RUN_ID,
+ attempt: process.env.GITHUB_RUN_ATTEMPT, packageName: pkg.name, gitHead: pkg.gitHead, sha256: digest };
+ fs.writeFileSync('npm-artifact/receipt.json', JSON.stringify(receipt) + '\n');
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `sha256=${digest}\n`);
+ NODE
+
+ - name: Upload verified npm package and receipt
+ id: upload
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: npm-package-verified
+ path: npm-artifact/
+ if-no-files-found: error
+ retention-days: 7
+
# Pre-publication verification. Everything that will be published is checked
# here — expected platform set, every checksum, the updater signatures, and the
# manifest parse-back — and publication consumes this result rather than
@@ -797,11 +1159,15 @@ jobs:
permissions:
contents: read
env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
UPDATER_SIGNING_CONFIGURED: ${{ secrets.TAURI_SIGNING_PRIVATE_KEY != '' }}
steps:
- - name: Checkout
+ - name: Checkout trusted workflow revision
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
persist-credentials: false
- name: Setup project Bun
@@ -823,23 +1189,49 @@ jobs:
- name: Verify release assets
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
run: |
set -euo pipefail
args=(
--version "$RELEASE_VERSION"
--dir dist/release
--repo "$GITHUB_REPOSITORY"
- --sha "$GITHUB_SHA"
+ --sha "$SOURCE_SHA"
--receipt-out verification/receipt.json
)
- # Signatures are verified whenever they exist; the manifest is only
- # generated when this run holds the updater key, exactly as before.
+ # HEAD release policy requires updater signatures whenever the key is configured.
if [ "$UPDATER_SIGNING_CONFIGURED" = "true" ]; then
args+=(--manifest-out dist/release/latest.json --require-signatures)
fi
bun desktop/scripts/verify-release-assets.ts "${args[@]}"
+ - name: Bind verified asset digests
+ run: |
+ set -euo pipefail
+ node - <<'NODE'
+ const fs = require('node:fs'), crypto = require('node:crypto'), path = require('node:path');
+ (async () => {
+ const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8'));
+ if (receipt.version !== process.env.RELEASE_VERSION || receipt.sha !== process.env.SOURCE_SHA || receipt.repo !== process.env.GITHUB_REPOSITORY) throw Error('asset verifier identity mismatch');
+ const names = fs.readdirSync('dist/release').sort();
+ if (!names.length) throw Error('empty verified release');
+ const assets = {};
+ for (const name of names) {
+ if (name === '.' || name === '..' || name.includes('/') || name.includes('\\')) throw Error('invalid asset name');
+ const file = path.join('dist/release', name), stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink()) throw Error('asset is not a regular file');
+ const hash = crypto.createHash('sha256');
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
+ assets[name] = hash.digest('hex');
+ }
+ receipt.workflowSha = process.env.WORKFLOW_SHA;
+ receipt.runId = process.env.GITHUB_RUN_ID;
+ receipt.attempt = process.env.GITHUB_RUN_ATTEMPT;
+ receipt.assets = assets;
+ fs.writeFileSync('verification/receipt.json', JSON.stringify(receipt) + '\n');
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
+ NODE
+
- name: Upload verified release bundle
uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
with:
@@ -858,15 +1250,20 @@ jobs:
attach-release:
runs-on: ubuntu-latest
- needs: [publish, verify-release]
+ needs: [validate-dispatch, publish, verify-release]
if: ${{ inputs.dry-run != true }}
timeout-minutes: 10
permissions:
contents: write
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
persist-credentials: false
- name: Setup project Bun
@@ -888,30 +1285,90 @@ jobs:
# run's version and commit, or nothing uploads.
- name: Require the verification receipt for this commit
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
run: |
set -euo pipefail
- receipt_version="$(bun -e 'console.log(JSON.parse(await Bun.file("verification/receipt.json").text()).version)')"
- receipt_sha="$(bun -e 'console.log(JSON.parse(await Bun.file("verification/receipt.json").text()).sha)')"
- test "$receipt_version" = "$RELEASE_VERSION" || {
- echo "::error::verification receipt names version $receipt_version, not $RELEASE_VERSION"
- exit 1
- }
- test "$receipt_sha" = "$GITHUB_SHA" || {
- echo "::error::verification receipt names commit $receipt_sha, not $GITHUB_SHA"
- exit 1
- }
+ node - <<'NODE'
+ const fs = require('node:fs'), crypto = require('node:crypto'), path = require('node:path');
+ (async () => {
+ const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8'));
+ if (receipt.version !== process.env.RELEASE_VERSION || receipt.sha !== process.env.SOURCE_SHA ||
+ receipt.repo !== process.env.GITHUB_REPOSITORY || receipt.workflowSha !== process.env.WORKFLOW_SHA ||
+ receipt.runId !== process.env.GITHUB_RUN_ID || !/^[1-9]\d*$/.test(receipt.attempt || '') ||
+ !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') ||
+ BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) ||
+ !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets)) throw Error('release receipt identity mismatch');
+ const names = fs.readdirSync('dist/release').sort(), recorded = Object.keys(receipt.assets).sort();
+ if (!names.length || JSON.stringify(names) !== JSON.stringify(recorded)) throw Error('release asset set mismatch');
+ for (const name of names) {
+ if (name === '.' || name === '..' || /[\x00-\x1f\x7f/\\]/.test(name) || !/^[0-9a-f]{64}$/.test(receipt.assets[name])) throw Error('invalid asset receipt');
+ const file = path.join('dist/release', name), stat = fs.lstatSync(file);
+ if (!stat.isFile() || stat.isSymbolicLink()) throw Error('asset is not a regular file');
+ const hash = crypto.createHash('sha256');
+ for await (const chunk of fs.createReadStream(file)) hash.update(chunk);
+ if (hash.digest('hex') !== receipt.assets[name]) throw Error(`asset sha256 mismatch: ${name}`);
+ }
+ })().catch(error => { console.error(error.message); process.exitCode = 1; });
+ NODE
+
+ - name: Check resume assets
+ if: ${{ inputs.resume-after-npm-publish == true }}
+ env:
+ GH_TOKEN: ${{ github.token }}
+ NPM_DIST_TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ case "$NPM_DIST_TAG" in latest) channel=stable ;; preview) channel=preview ;; *) exit 1 ;; esac
+ decision="$(node .github/scripts/release-resume.cjs check-assets "$RELEASE_VERSION" "$SOURCE_SHA" "$channel" verification/receipt.json)"
+ DECISION="$decision" CHANNEL="$channel" node - <<'NODE'
+ const result = JSON.parse(process.env.DECISION);
+ if (result.version !== process.env.RELEASE_VERSION || result.sourceSha !== process.env.SOURCE_SHA ||
+ result.channel !== process.env.CHANNEL || result.publishNpm !== false || result.assetsChecked !== true ||
+ !Array.isArray(result.reuseAssets) || !Array.isArray(result.missingAssets)) throw Error('invalid resume asset decision');
+ NODE
- name: Attach to the release
env:
GH_TOKEN: ${{ github.token }}
# Workflow inputs reach shell code through env, never by interpolation into
# run: source. tests/ci-workflows.test.ts enforces this repo-wide.
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
run: |
set -euo pipefail
release_tag="v${RELEASE_VERSION}"
- gh release upload "$release_tag" dist/release/* --clobber
+ # The preceding receipt check binds this local set to verified bytes.
+ # Existing assets are reused only when GitHub reports their exact digest.
+ checker="$RUNNER_TEMP/check-release-assets.cjs"
+ cat > "$checker" <<'NODE'
+ const fs = require('node:fs');
+ const release = JSON.parse(process.env.RELEASE_INFO);
+ const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8'));
+ if (typeof release.isDraft !== 'boolean' || !Array.isArray(release.assets) ||
+ !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets)) throw Error('invalid release or receipt');
+ const expected = receipt.assets, names = Object.keys(expected), seen = new Set();
+ if (!names.length) throw Error('empty asset receipt');
+ for (const name of names) {
+ if (!name || name === '.' || name === '..' || /[\x00-\x1f\x7f/\\]/.test(name) || !/^[0-9a-f]{64}$/.test(expected[name])) throw Error('invalid asset receipt');
+ }
+ for (const asset of release.assets) {
+ if (!asset || typeof asset.name !== 'string' || seen.has(asset.name) || !Object.hasOwn(expected, asset.name) ||
+ asset.state !== 'uploaded' || asset.digest !== `sha256:${expected[asset.name]}`) throw Error('existing asset is unexpected, unavailable or has a different digest');
+ seen.add(asset.name);
+ }
+ const missing = names.filter(name => !seen.has(name));
+ if ((!release.isDraft || process.env.CHECK_FINAL === 'true') && missing.length) throw Error('release is missing verified assets');
+ if (missing.length) process.stdout.write(missing.join('\0') + '\0');
+ NODE
+ release_info="$(gh release view "$release_tag" --json isDraft,assets)"
+ RELEASE_INFO="$release_info" CHECK_FINAL=false node "$checker" > "$RUNNER_TEMP/missing-release-assets"
+ missing=()
+ while IFS= read -r -d '' name; do missing+=("dist/release/$name"); done < "$RUNNER_TEMP/missing-release-assets"
+ if [ "${#missing[@]}" -gt 0 ]; then
+ gh release upload "$release_tag" "${missing[@]}"
+ fi
+ # Re-read the entire remote set before publishing the draft.
+ release_info="$(gh release view "$release_tag" --json isDraft,assets)"
+ RELEASE_INFO="$release_info" CHECK_FINAL=true node "$checker" > /dev/null
# A published release is immutable: GitHub rejects every later asset upload
# with HTTP 422, which is why v2.55.0 through v2.60.0 shipped with zero
@@ -940,12 +1397,16 @@ jobs:
# release is invisible to it and reads as not public, which is the question the row answers.
release-outcomes:
name: release outcomes
- needs: [publish, attach-release]
- if: ${{ always() && inputs.dry-run != true }}
+ needs: [validate-dispatch, publish, attach-release]
+ if: ${{ always() && needs.validate-dispatch.result == 'success' && inputs.dry-run != true }}
runs-on: ubuntu-latest
timeout-minutes: 5
permissions:
contents: read
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
steps:
- name: Checkout
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
@@ -955,7 +1416,7 @@ jobs:
- name: Report release outcomes
env:
GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
NPM_DIST_TAG: ${{ inputs.tag }}
NPM_VERSION_STATE: ${{ needs.publish.outputs.npm_version }}
NPM_DIST_TAG_STATE: ${{ needs.publish.outputs.npm_dist_tag }}
@@ -964,9 +1425,11 @@ jobs:
run: bash scripts/ci/release-outcome-report.sh
publish:
- needs: [validate-dispatch, verify-release]
+ needs: [validate-dispatch, verify-release, verify-npm]
+ if: ${{ inputs.dry-run != true }}
runs-on: ubuntu-latest
- timeout-minutes: 15
+ # The two registry waits below can each take about 20 minutes (about 55 minutes worst case with read timeouts).
+ timeout-minutes: 75
outputs:
npm_version: ${{ steps.registry-smoke.outputs.npm_version }}
npm_dist_tag: ${{ steps.registry-smoke.outputs.npm_dist_tag }}
@@ -975,318 +1438,267 @@ jobs:
actions: read
pull-requests: read
id-token: write
+ env:
+ SOURCE_SHA: ${{ needs.validate-dispatch.outputs.source_sha }}
+ WORKFLOW_SHA: ${{ needs.validate-dispatch.outputs.workflow_sha }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
+ # The ./ prefix is load-bearing: npm reads a bare "owner/repo..." spec as a GitHub shorthand
+ # and runs git ls-remote instead of publishing the file (run 42763073267).
+ NPM_TARBALL: ./npm-artifact/package.tgz
+ EXPECTED_DIGEST: ${{ needs.verify-npm.outputs.sha256 }}
steps:
- - name: Checkout
+ - name: Checkout trusted workflow revision
uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
with:
+ ref: ${{ needs.validate-dispatch.outputs.workflow_sha }}
fetch-depth: 0
- - name: Verify dispatched SHA
- env:
- EXPECTED_SHA: ${{ inputs.expected-sha }}
+ - name: Resolve trusted Bun version
+ id: bun-version
run: |
- if [ -z "$EXPECTED_SHA" ]; then
- echo "::error::expected-sha is required; refusing to publish without an audited commit"
- exit 1
- elif [ "$GITHUB_SHA" != "$EXPECTED_SHA" ]; then
- echo "::error::branch moved after the release audit (expected ${EXPECTED_SHA}, got ${GITHUB_SHA}) — refusing to publish an unaudited commit"
- exit 1
- fi
+ # JavaScript template literals are evaluated by Node, not the shell.
+ # shellcheck disable=SC2016
+ node -e 'const v = require("./package.json").dependencies.bun; if (!/^\d+\.\d+\.\d+$/.test(v)) throw Error("invalid Bun pin"); require("node:fs").appendFileSync(process.env.GITHUB_OUTPUT, `version=${v}\n`);'
- # opencodex is bun-native (the prepublishOnly audit, GUI build, and typecheck run under bun).
- - name: Setup project Bun
- uses: ./.github/actions/setup-project-bun
+ - name: Setup trusted Bun
+ uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: ${{ steps.bun-version.outputs.version }}
- # node + npm perform the actual publish. registry-url points npm at the public registry.
- name: Setup Node
uses: actions/setup-node@48b55a011bda9f5d6aeb4c2d9c7362e8dae4041e # v6.4.0
with:
node-version: 24
- registry-url: "https://registry.npmjs.org"
+ registry-url: https://registry.npmjs.org
- # Trusted Publishing (OIDC) needs npm >= 11.5.1. Node 24 runners already
- # provide a compatible npm; avoid replacing the bundled npm because global
- # npm self-updates can lose publish-time dependencies such as sigstore.
- - name: Verify npm version
- run: |
- npm_version="$(npm --version)"
- echo "npm=${npm_version}"
- # shellcheck disable=SC2016 # the node script deliberately avoids shell expansion
- node -e '
- const [major, minor] = process.argv[1].split(".").map(Number);
- if (major < 11 || (major === 11 && minor < 5)) {
- console.error(`npm ${process.argv[1]} is too old for trusted publishing; need >= 11.5.1`);
- process.exit(1);
- }
- ' "$npm_version"
+ - name: Download verified npm package by immutable artifact ID
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ artifact-ids: ${{ needs.verify-npm.outputs.artifact_id }}
+ path: npm-artifact
- - name: Install dependencies
- run: bun install --frozen-lockfile
+ # Fetch the independently verified release receipt before publication, so
+ # an unavailable handoff cannot strand a newly published npm version.
+ - name: Download verified release receipt for publication
+ uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
+ with:
+ name: release-verification-receipt
+ path: verification
- - name: Dependency audit (high severity)
- run: bun run audit:high
+ - name: Verify immutable npm receipt
+ run: |
+ set -euo pipefail
+ node - <<'NODE'
+ const fs = require('node:fs');
+ const crypto = require('node:crypto');
+ const { spawnSync } = require('node:child_process');
+ const archive = process.env.NPM_TARBALL;
+ const stat = fs.lstatSync(archive);
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size <= 0 || stat.size > 500 * 1024 * 1024) throw new Error('invalid npm tarball');
+ const receipt = JSON.parse(fs.readFileSync('npm-artifact/receipt.json', 'utf8'));
+ const sha256 = crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex');
+ const expectedName = JSON.parse(fs.readFileSync('package.json', 'utf8')).name;
+ if (!/^[0-9a-f]{64}$/.test(process.env.EXPECTED_DIGEST) || sha256 !== process.env.EXPECTED_DIGEST ||
+ receipt.sha256 !== sha256 || receipt.sourceSha !== process.env.SOURCE_SHA || receipt.workflowSha !== process.env.WORKFLOW_SHA ||
+ receipt.version !== process.env.RELEASE_VERSION || receipt.runId !== process.env.GITHUB_RUN_ID ||
+ !/^[1-9]\d*$/.test(receipt.attempt || '') || !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') ||
+ BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) || receipt.packageName !== expectedName ||
+ receipt.gitHead !== process.env.SOURCE_SHA) throw new Error('npm receipt identity or digest mismatch');
+ const entries = spawnSync('tar', ['-tzf', archive], { encoding: 'utf8', maxBuffer: 16 * 1024 * 1024 });
+ if (entries.status !== 0 || entries.stdout.split('\n').filter(p => p === 'package/package.json').length !== 1) throw new Error('invalid npm manifest entry');
+ const manifest = spawnSync('tar', ['-xOzf', archive, 'package/package.json'], { encoding: 'utf8', maxBuffer: 1024 * 1024 });
+ if (manifest.status !== 0) throw new Error('cannot read npm manifest');
+ const pkg = JSON.parse(manifest.stdout);
+ if (pkg.name !== expectedName || pkg.version !== process.env.RELEASE_VERSION || pkg.gitHead !== process.env.SOURCE_SHA || pkg.gitHead !== receipt.gitHead) throw new Error('npm package identity or gitHead mismatch');
+ NODE
- - name: Verify every version source matches the requested version
+ # Prepare and validate the receipt before the irreversible npm publication.
+ - name: Prepare publication receipt
+ if: ${{ inputs.resume-after-npm-publish != true }}
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ NPM_DIST_TAG: ${{ inputs.tag }}
run: |
- # package.json plus the desktop sources (tauri.conf.json, Cargo.toml and the
- # opencodex-desktop Cargo.lock entry). package-desktop already refused to build on a
- # mismatch; this re-proves it on the commit that is about to publish.
- bun scripts/release-version-sources.ts check "$RELEASE_VERSION" || {
- echo "::error::a version source != requested (${RELEASE_VERSION}) — run scripts/release.ts, which moves all of them, on main first";
- exit 1;
+ set -euo pipefail
+ mkdir -p publication
+ node - <<'NODE'
+ const fs = require('node:fs');
+ const receipt = JSON.parse(fs.readFileSync('verification/receipt.json', 'utf8'));
+ const sha = /^[0-9a-f]{40}$/, digest = /^[0-9a-f]{64}$/;
+ const runId = Number(process.env.GITHUB_RUN_ID), attempt = Number(process.env.GITHUB_RUN_ATTEMPT);
+ const version = process.env.RELEASE_VERSION, tag = process.env.NPM_DIST_TAG;
+ if (!sha.test(process.env.SOURCE_SHA || '') || !sha.test(process.env.WORKFLOW_SHA || '') ||
+ !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ID || '') || !/^[1-9]\d*$/.test(process.env.GITHUB_RUN_ATTEMPT || '') ||
+ !digest.test(process.env.EXPECTED_DIGEST || '') || !Number.isSafeInteger(runId) || runId <= 0 ||
+ !Number.isSafeInteger(attempt) || attempt <= 0 || !/^\d+\.\d+\.\d+(?:-preview\.\d{8}\.\d+)?$/.test(version || '') ||
+ !((tag === 'latest' && !version.includes('-')) || (tag === 'preview' && version.includes('-preview.')))) throw Error('invalid publication identity');
+ if (receipt.sha !== process.env.SOURCE_SHA || receipt.workflowSha !== process.env.WORKFLOW_SHA ||
+ receipt.version !== version || receipt.repo !== process.env.GITHUB_REPOSITORY ||
+ receipt.runId !== process.env.GITHUB_RUN_ID || !/^[1-9]\d*$/.test(receipt.attempt || '') ||
+ BigInt(receipt.attempt) > BigInt(process.env.GITHUB_RUN_ATTEMPT) ||
+ !receipt.assets || typeof receipt.assets !== 'object' || Array.isArray(receipt.assets) || !Object.keys(receipt.assets).length) throw Error('release asset receipt mismatch');
+ for (const [name, value] of Object.entries(receipt.assets)) {
+ if (!name || /[\x00-\x1f/\\]/.test(name) || !digest.test(value)) throw Error('invalid release asset receipt');
}
+ const publication = { sourceSha: process.env.SOURCE_SHA, workflowSha: process.env.WORKFLOW_SHA,
+ version, channel: tag === 'latest' ? 'stable' : 'preview', sha256: process.env.EXPECTED_DIGEST,
+ gitHead: process.env.SOURCE_SHA, runId, attempt, published: true, assets: receipt.assets };
+ fs.writeFileSync('publication/pending.json', JSON.stringify(publication) + '\n', { flag: 'wx' });
+ NODE
- # The exact-SHA CI gate includes the hosted Linux, Windows, and macOS
- # keyring smoke matrix. Do not duplicate its Linux bootstrap here.
- - name: Require successful Cross-platform CI for this commit
+ - name: Recheck source CI and service evidence
env:
GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
- NPM_DIST_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
-
- case "$GITHUB_REF" in
- refs/heads/main)
- expected_tag="latest"
- if [[ "$RELEASE_VERSION" == *-* ]]; then
- echo "::error::main releases must use a stable semver version; got ${RELEASE_VERSION}"
- exit 1
- fi
- ;;
- refs/heads/preview)
- expected_tag="preview"
- if [[ "$RELEASE_VERSION" != *-preview.* ]]; then
- echo "::error::preview releases must use a preview prerelease version; got ${RELEASE_VERSION}"
- exit 1
- fi
- ;;
- *)
- echo "::error::Release must run from main or preview; got ${GITHUB_REF}"
- exit 1
- ;;
- esac
-
- if [ "$NPM_DIST_TAG" != "$expected_tag" ]; then
- echo "::error::${GITHUB_REF#refs/heads/} releases must publish with npm dist-tag '${expected_tag}', got '${NPM_DIST_TAG}'"
- exit 1
- fi
-
- ci_url="$(
- gh run list \
- --workflow ci.yml \
- --branch "${GITHUB_REF#refs/heads/}" \
- --commit "$GITHUB_SHA" \
- --event push \
- --limit 10 \
- --json conclusion,url \
- --jq '[.[] | select(.conclusion == "success")][0].url // ""'
- )"
-
- if [ -z "$ci_url" ]; then
- # Deliberately narrower than "any successful ci.yml run for this SHA".
- # The release branch's own push run is the one whose trigger set,
- # runner selection, and job graph match what is being published —
- # a green PR run for the same SHA ran against a merge ref with a
- # different trigger context. Accepting it here would let a publish
- # proceed while the promotion run was still pending, or had failed.
- echo "::error::No successful Cross-platform CI run found for ${GITHUB_SHA} on ${GITHUB_REF#refs/heads/} (push event). A pull-request run does not qualify. Wait for the promotion run to pass before releasing."
- gh run list --workflow ci.yml --commit "$GITHUB_SHA" --limit 10 || true
- exit 1
- fi
-
- echo "Cross-platform CI passed for ${GITHUB_SHA}: ${ci_url}"
-
- # Service baseline (lineage-relative): merged tags only, so the
- # changed-files gate compares against the last release actually
- # reachable from this commit. The release-notes baseline below uses the
- # full tag set instead, so a stable on another lineage can anchor the
- # changelog range.
- # - Preview: newest prior release of either channel (stable or preview). A
- # preview→preview-only baseline skips a shipped stable and restates it.
- # - Stable: newest prior stable only (matching preview carry adjusts the
- # generate-notes range separately below).
- previous_tag="$(
- git tag --merged HEAD --list 'v[0-9]*' |
- bun scripts/release-notes.ts previous-release-tag "$RELEASE_VERSION"
- )"
- if [ -n "$previous_tag" ]; then
- changed_files="$(git diff --name-only "${previous_tag}..HEAD")"
- else
- changed_files="$(git diff-tree --no-commit-id --name-only -r "$GITHUB_SHA")"
+ node .github/scripts/release-evidence.cjs check "$SOURCE_SHA"
+ baseline_tag="$(git tag --merged "$SOURCE_SHA" --list 'v[0-9]*' | bun -e '
+ import { parseVersion, compareVersions } from "./scripts/version-line.ts";
+ const tags = (await Bun.stdin.text()).trim().split("\n").filter(Boolean);
+ const versions = tags.map(tag => ({ tag, version: tag.slice(1) }));
+ if (versions.some(item => !parseVersion(item.version))) throw new Error("invalid release tag");
+ const eligible = versions.filter(item => compareVersions(item.version, process.env.RELEASE_VERSION) < 0);
+ eligible.sort((a, b) => compareVersions(a.version, b.version));
+ console.log(eligible.at(-1)?.tag ?? "");
+ ')"
+ baseline=--initial
+ if [ -n "$baseline_tag" ]; then
+ draft="$(gh release view "$baseline_tag" --json isDraft --jq .isDraft)"
+ test "$draft" = false || { echo '::error::Service baseline is not a published release.'; exit 1; }
+ baseline="$(git rev-parse "refs/tags/${baseline_tag}^{commit}")"
fi
-
- # Keep in sync with the service-lifecycle.yml trigger paths. src/cli.ts is
- # the pre-restructure compat stub that durable launchers still execute; the
- # service implementation itself is the src/service/ directory, and the desktop
- # shell packages and launches it.
- if printf '%s\n' "$changed_files" | grep -Eq '^(src/service\.ts|src/service/.*|desktop/.*|src/cli\.ts|src/cli/index\.ts|src/lib/bun-runtime\.ts|package\.json|bun\.lock|\.github/workflows/service-lifecycle\.yml|\.github/workflows/release\.yml)$'; then
- service_url="$(
- gh run list \
- --workflow service-lifecycle.yml \
- --commit "$GITHUB_SHA" \
- --limit 10 \
- --json conclusion,headSha,url,workflowName \
- --jq '[.[] | select(.conclusion == "success")][0].url // ""'
- )"
- if [ -z "$service_url" ]; then
- echo "::error::Service-related files changed since ${previous_tag:-initial commit}, but no successful Service lifecycle run was found for ${GITHUB_SHA}."
- gh run list --workflow service-lifecycle.yml --commit "$GITHUB_SHA" --limit 10 || true
- exit 1
- fi
- echo "Service lifecycle passed for ${GITHUB_SHA}: ${service_url}"
+ range="$(node .github/scripts/release-evidence.cjs service-range "$SOURCE_SHA" "$baseline")"
+ required="$(RANGE="$range" node -e 'const x = JSON.parse(process.env.RANGE); if (typeof x.required !== "boolean") throw Error("invalid service range"); process.stdout.write(String(x.required));')"
+ if [ "$required" = true ]; then
+ node .github/scripts/release-evidence.cjs service "$SOURCE_SHA" || {
+ echo "::error::Dispatch service-lifecycle.yml from dev for source ${SOURCE_SHA} and wait for all platforms."; exit 1;
+ }
fi
- - name: Require dev to be ready for this release
- env:
- RELEASE_VERSION: ${{ inputs.version }}
- run: |
- set -euo pipefail
- git fetch --force --tags origin +refs/heads/dev:refs/remotes/origin/dev
- dev_version="$(git show origin/dev:package.json | bun -e 'console.log(JSON.parse(await Bun.stdin.text()).version)')"
- bun scripts/version-line.ts assert-ahead "$dev_version" "$RELEASE_VERSION"
-
- # Tokenless publish via Trusted Publishing (OIDC) — NO NPM_TOKEN secret. npm auto-detects the
- # OIDC environment (`id-token: write` above) and generates provenance automatically, so neither a
- # token nor `--provenance` is needed. `npm publish` runs prepublishOnly first (typecheck + build
- # the GUI into gui/dist), so even a dry-run fully verifies the build.
- # PREREQUISITE: configure the Trusted Publisher for this repo + workflow on npmjs.com — possible
- # only AFTER the package's first version exists (do the first publish locally, see the runbook).
- - name: Preflight release metadata
- id: metadata
+ - name: Refuse a release the current tag set already outranks
env:
- GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
- DRY_RUN: ${{ inputs.dry-run }}
RESUME: ${{ inputs.resume-after-npm-publish }}
run: |
set -euo pipefail
-
- pkg_name="$(node -p "require('./package.json').name")"
- release_tag="v${RELEASE_VERSION}"
- dry_run="$DRY_RUN"
-
git fetch --force --tags origin
-
- existing_tag_sha="$(git rev-parse -q --verify "refs/tags/${release_tag}^{commit}" || true)"
- if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$GITHUB_SHA" ]; then
- echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${GITHUB_SHA}"
- exit 1
- fi
-
- if [ -n "$existing_tag_sha" ]; then
- if [ "$RESUME" = "true" ]; then
- echo "::notice::${release_tag} already exists at this commit; resuming"
- elif [ "$dry_run" = "true" ]; then
- echo "::notice::${release_tag} already exists at this commit; dry-run only"
- else
- echo "::error::${release_tag} already exists. Refusing to publish a version with pre-existing Git metadata."
- exit 1
- fi
+ allow=""
+ existing_tag_sha="$(git rev-parse -q --verify "refs/tags/v${RELEASE_VERSION}^{commit}" || true)"
+ if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$SOURCE_SHA" ]; then
+ echo '::error::Existing release tag points at a different source.'; exit 1
fi
+ if [ "$RESUME" = true ] && [ -n "$existing_tag_sha" ]; then allow="--allow-existing-tag-at-head"; fi
+ git tag --list 'v*' | bun scripts/version-line.ts assert-releasable "$RELEASE_VERSION" ${allow:+"$allow"}
- if gh release view "$release_tag" >/dev/null 2>&1; then
- if [ "$RESUME" = "true" ]; then
- echo "::notice::GitHub Release ${release_tag} already exists; resuming to complete the attachment"
- elif [ "$dry_run" = "true" ]; then
- echo "::notice::GitHub Release ${release_tag} already exists; dry-run only"
- else
- echo "::error::GitHub Release ${release_tag} already exists. Choose the next unused patch version."
- exit 1
- fi
- fi
+ - name: Build and validate release changelog
+ env:
+ GH_TOKEN: ${{ github.token }}
+ NPM_DIST_TAG: ${{ inputs.tag }}
+ run: |
+ set -euo pipefail
+ notes_file="$GITHUB_WORKSPACE/.release-notes.md"
+ bun scripts/build-release-changelog.ts --version "$RELEASE_VERSION" --dist-tag "$NPM_DIST_TAG" \
+ --repository "$GITHUB_REPOSITORY" --target "$SOURCE_SHA" --out "$notes_file"
+ test -s "$notes_file"
- if [ "$RESUME" = "true" ] && [ "$dry_run" = "true" ]; then
- echo "::error::resume-after-npm-publish is a real-publication recovery path and cannot combine with dry-run"
- exit 1
- fi
- if npm view "${pkg_name}@${RELEASE_VERSION}" version >/dev/null 2>&1; then
- if [ "$RESUME" = "true" ]; then
- resume_git_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || {
- echo "::error::Cannot verify the existing npm package source; resume refused"
- exit 1
- }
- bun scripts/verify-release-resume.ts "$GITHUB_SHA" "$resume_git_head"
- echo "resume_sha=$GITHUB_SHA" >> "$GITHUB_OUTPUT"
- echo "::notice::${pkg_name}@${RELEASE_VERSION} is acknowledged on npm; resuming after the recorded partial publication"
- elif [ "$dry_run" = "true" ]; then
- echo "::notice::${pkg_name}@${RELEASE_VERSION} already exists on npm; dry-run only"
- else
- echo "::error::${pkg_name}@${RELEASE_VERSION} already exists on npm. If a previous run acknowledged this publication and failed afterwards, re-dispatch with resume-after-npm-publish: true; otherwise choose the next unused patch version."
- exit 1
- fi
- elif [ "$RESUME" = "true" ]; then
- echo "::error::resume-after-npm-publish is set, but ${pkg_name}@${RELEASE_VERSION} is not on npm — there is no acknowledged publication to resume from"
+ - name: Require publication hold to be enabled
+ env:
+ DRY_RUN: ${{ inputs.dry-run }}
+ PUBLISH_ENABLED: ${{ vars.OCX_DEV_RELEASE_PUBLISH_ENABLED }}
+ run: |
+ if [ "$DRY_RUN" != "true" ] && [ "$PUBLISH_ENABLED" != "true" ]; then
+ echo '::error::Publication is disabled; OCX_DEV_RELEASE_PUBLISH_ENABLED must equal true.'
exit 1
fi
- - name: Refuse a release the current tag set already outranks
+ - name: Require reconciled publication history
+ if: ${{ inputs.resume-after-npm-publish != true }}
env:
- RELEASE_VERSION: ${{ inputs.version }}
- DRY_RUN: ${{ inputs.dry-run }}
- RESUME: ${{ inputs.resume-after-npm-publish }}
+ GH_TOKEN: ${{ github.token }}
+ NPM_DIST_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
- allow=""
- existing_tag_sha="$(git rev-parse -q --verify "refs/tags/v${RELEASE_VERSION}^{commit}" || true)"
- # Dry-run re-dispatches and the resume path both legitimately find the tag
- # already at this commit; a moved tag is still refused above.
- if { [ "$DRY_RUN" = "true" ] || [ "$RESUME" = "true" ]; } && [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" = "$GITHUB_SHA" ]; then
- allow="--allow-existing-tag-at-head"
+ if ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]] || [ -z "$RELEASE_VERSION" ]; then
+ echo '::error::Invalid release identity for history reconciliation.'; exit 1
fi
- git tag --list 'v*' | bun scripts/version-line.ts assert-releasable "$RELEASE_VERSION" $allow
+ case "$NPM_DIST_TAG" in
+ latest) channel=stable ;;
+ preview) channel=preview ;;
+ *) echo '::error::Invalid release channel.'; exit 1 ;;
+ esac
+ node .github/scripts/release-history.cjs check "$SOURCE_SHA" "$RELEASE_VERSION" "$channel"
- - name: Build and validate release changelog
+ - name: Verify resume registry identity
+ id: resume-identity
+ if: ${{ inputs.resume-after-npm-publish == true }}
+ run: |
+ set -euo pipefail
+ pkg_name="$(node -p "require('./package.json').name")"
+ registry_version="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || {
+ echo '::error::Cannot read the exact npm version; resume refused.'; exit 1;
+ }
+ REGISTRY_VERSION="$registry_version" node - <<'NODE'
+ const value = JSON.parse(process.env.REGISTRY_VERSION);
+ if (typeof value !== 'string' || value !== process.env.RELEASE_VERSION) throw Error('npm version does not match original release');
+ NODE
+ registry_head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000)" || {
+ echo '::error::Cannot read npm gitHead; resume refused.'; exit 1;
+ }
+ bun scripts/verify-release-resume.ts "$SOURCE_SHA" "$registry_head"
+ echo "resume_sha=$SOURCE_SHA" >> "$GITHUB_OUTPUT"
+
+ - name: Check resume publication
+ id: resume-check
+ if: ${{ inputs.resume-after-npm-publish == true }}
env:
GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
NPM_DIST_TAG: ${{ inputs.tag }}
run: |
set -euo pipefail
- notes_file="$GITHUB_WORKSPACE/.release-notes.md"
- bun scripts/build-release-changelog.ts \
- --version "$RELEASE_VERSION" \
- --dist-tag "$NPM_DIST_TAG" \
- --repository "$GITHUB_REPOSITORY" \
- --target "$GITHUB_SHA" \
- --out "$notes_file"
- test -s "$notes_file" || {
- echo "::error::release changelog builder produced an empty notes file"
- exit 1
- }
+ case "$NPM_DIST_TAG" in latest) channel=stable ;; preview) channel=preview ;; *) exit 1 ;; esac
+ decision="$(node .github/scripts/release-resume.cjs check "$RELEASE_VERSION" "$SOURCE_SHA" "$channel")"
+ DECISION="$decision" CHANNEL="$channel" node - <<'NODE'
+ const fs = require('node:fs'), result = JSON.parse(process.env.DECISION);
+ if (result.version !== process.env.RELEASE_VERSION || result.sourceSha !== process.env.SOURCE_SHA ||
+ result.channel !== process.env.CHANNEL || result.publishNpm !== false || result.assetsChecked !== false) throw Error('invalid resume publication decision');
+ fs.appendFileSync(process.env.GITHUB_OUTPUT, `resume_checked_sha=${result.sourceSha}\n`);
+ NODE
- - name: Publish (or dry-run)
+ - name: Publish verified npm tarball
id: publication
env:
- DRY_RUN: ${{ inputs.dry-run }}
NPM_DIST_TAG: ${{ inputs.tag }}
RESUME: ${{ inputs.resume-after-npm-publish }}
- RELEASE_VERSION: ${{ inputs.version }}
- VERIFIED_RESUME_SHA: ${{ steps.metadata.outputs.resume_sha }}
+ VERIFIED_RESUME_SHA: ${{ steps.resume-identity.outputs.resume_sha }}
+ VERIFIED_RESUME_DECISION: ${{ steps.resume-check.outputs.resume_checked_sha }}
run: |
set -euo pipefail
- pkg_name="$(node -p "require('./package.json').name")"
- if [ "$RESUME" = "true" ]; then
- if [ -z "$VERIFIED_RESUME_SHA" ] || [ "$VERIFIED_RESUME_SHA" != "$GITHUB_SHA" ]; then
- echo "::error::Resume has no matching registry source verification; publication remains unacknowledged"
- exit 1
+ if [ "$RESUME" = true ]; then
+ if [ -z "$VERIFIED_RESUME_SHA" ] || [ "$VERIFIED_RESUME_SHA" != "$SOURCE_SHA" ] ||
+ [ -z "$VERIFIED_RESUME_DECISION" ] || [ "$VERIFIED_RESUME_DECISION" != "$SOURCE_SHA" ]; then
+ echo '::error::Resume has no matching registry verification; refusing publication acknowledgement.'; exit 1
fi
- # npm publication was acknowledged by the earlier run and confirmed by the
- # preflight above; completing the GitHub side must never republish.
- echo "::notice::RESUME — npm publish skipped; publication already acknowledged"
- echo "published=true" >> "$GITHUB_OUTPUT"
- echo "Publication resumed for ${pkg_name}@${RELEASE_VERSION} at ${GITHUB_SHA} (npm publish skipped; acknowledged by the earlier run)." >> "$GITHUB_STEP_SUMMARY"
- elif [ "$DRY_RUN" = "true" ]; then
- echo "::notice::DRY RUN — building + packing, not publishing"
- npm run prepublishOnly
- npm pack --dry-run
+ echo "::notice::Resume verified; npm publish skipped."
else
- npm publish --tag "$NPM_DIST_TAG" --access public
- echo "published=true" >> "$GITHUB_OUTPUT"
- echo "Publication acknowledged for ${pkg_name}@${RELEASE_VERSION} at ${GITHUB_SHA}. If any later step in this run fails, re-dispatch with the same version and expected-sha plus resume-after-npm-publish: true — never republish this version." >> "$GITHUB_STEP_SUMMARY"
+ npm publish "$NPM_TARBALL" --ignore-scripts --tag "$NPM_DIST_TAG" --access public
fi
+ echo "published=true" >> "$GITHUB_OUTPUT"
+ echo "Publication acknowledged for ${RELEASE_VERSION} at ${SOURCE_SHA}; do not republish this version." >> "$GITHUB_STEP_SUMMARY"
+
+ # A same-run artifact is evidence to be authenticated, not provenance by itself.
+ - name: Record acknowledged publication
+ if: ${{ steps.publication.outputs.published == 'true' && inputs.resume-after-npm-publish != true }}
+ run: |
+ set -euo pipefail
+ test -s publication/pending.json && test ! -e publication/receipt.json
+ mv publication/pending.json publication/receipt.json
+
+ - name: Upload publication receipt
+ if: ${{ steps.publication.outputs.published == 'true' && inputs.resume-after-npm-publish != true }}
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: release-publication-receipt
+ path: publication/receipt.json
+ if-no-files-found: error
+ retention-days: 7
# Publication is acknowledged before registry reads, which can lag or fail.
# Recover only observation failures in this run; never retry npm publish.
@@ -1294,7 +1706,7 @@ jobs:
id: registry-smoke
if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }}
env:
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
NPM_DIST_TAG: ${{ inputs.tag }}
PUBLISHED: ${{ steps.publication.outputs.published }}
run: |
@@ -1304,7 +1716,10 @@ jobs:
exit 1
}
pkg_name="$(node -p "require('./package.json').name")"
- for attempt in $(seq 1 6); do
+ # npm can take 15+ minutes to serve a new version (2.100.1: ~15 min after publish), so the
+ # bounded wait is attempts x interval, about 20 minutes. Publication is never retried.
+ attempts="${REGISTRY_WAIT_ATTEMPTS:-40}"; interval="${REGISTRY_WAIT_SECONDS:-30}"
+ for attempt in $(seq 1 "$attempts"); do
if VERSION=$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" version --fetch-retries=0 --fetch-timeout=8000 2>/dev/null); then
if [ "$VERSION" != "$RELEASE_VERSION" ]; then
echo "::error::Registry returned an unexpected version; refusing to create a release"
@@ -1335,20 +1750,45 @@ jobs:
echo "npm dist-tag ${NPM_DIST_TAG}: ${dist_tag_state}." >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
- echo "::notice::Registry lookup not confirmed (attempt $attempt/6)"
- if [ "$attempt" -lt 6 ]; then sleep 5; fi
+ echo "::notice::Registry lookup not confirmed (attempt $attempt/$attempts)"
+ if [ "$attempt" -lt "$attempts" ]; then sleep "$interval"; fi
done
+ # Keep each outcome explicit for the recovery report.
+ # shellcheck disable=SC2129
echo "verification=pending" >> "$GITHUB_OUTPUT"
echo "npm_version=unconfirmed" >> "$GITHUB_OUTPUT"
echo "npm_dist_tag=unconfirmed" >> "$GITHUB_OUTPUT"
echo "::warning::npm publish succeeded, but registry verification remains pending; continuing GitHub release creation without republishing"
echo "Publication acknowledged for ${pkg_name}@${RELEASE_VERSION}; registry verification pending after bounded reads. Inspect the registry before announcing availability. Do not republish this version." >> "$GITHUB_STEP_SUMMARY"
+ - name: Verify published npm source
+ if: ${{ steps.publication.outputs.published == 'true' }}
+ run: |
+ set -euo pipefail
+ pkg_name="$(node -p "require('./package.json').name")"
+ attempts="${REGISTRY_WAIT_ATTEMPTS:-40}"; interval="${REGISTRY_WAIT_SECONDS:-30}"
+ for attempt in $(seq 1 "$attempts"); do
+ if head="$(timeout --kill-after=2s 10s npm view "${pkg_name}@${RELEASE_VERSION}" gitHead --json --registry=https://registry.npmjs.org --fetch-retries=0 --fetch-timeout=8000 2>/dev/null)"; then
+ if [ -n "$head" ] && [ "$head" != null ]; then
+ REGISTRY_HEAD="$head" node - <<'NODE'
+ const head = JSON.parse(process.env.REGISTRY_HEAD);
+ if (!/^[0-9a-f]{40}$/.test(process.env.SOURCE_SHA || '') || head !== process.env.SOURCE_SHA) {
+ throw Error('published npm gitHead does not match selected source');
+ }
+ NODE
+ exit 0
+ fi
+ fi
+ if [ "$attempt" -lt "$attempts" ]; then sleep "$interval"; fi
+ done
+ echo '::error::Published npm gitHead could not be verified; do not republish and reconcile manually.'
+ exit 1
+
- name: Create GitHub release
if: ${{ inputs.dry-run != true && steps.publication.outputs.published == 'true' }}
env:
GH_TOKEN: ${{ github.token }}
- RELEASE_VERSION: ${{ inputs.version }}
+ RELEASE_VERSION: ${{ needs.validate-dispatch.outputs.version }}
RESUME: ${{ inputs.resume-after-npm-publish }}
run: |
set -euo pipefail
@@ -1363,8 +1803,8 @@ jobs:
git fetch --force --tags origin
existing_tag_sha="$(git rev-parse -q --verify "refs/tags/${release_tag}^{commit}" || true)"
- if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$GITHUB_SHA" ]; then
- echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${GITHUB_SHA}"
+ if [ -n "$existing_tag_sha" ] && [ "$existing_tag_sha" != "$SOURCE_SHA" ]; then
+ echo "::error::${release_tag} already points at ${existing_tag_sha}, not ${SOURCE_SHA}"
exit 1
fi
@@ -1374,7 +1814,7 @@ jobs:
fi
if [ -z "$existing_tag_sha" ]; then
- git tag "$release_tag" "$GITHUB_SHA"
+ git tag "$release_tag" "$SOURCE_SHA"
git push origin "refs/tags/${release_tag}"
fi
@@ -1393,6 +1833,6 @@ jobs:
# Draft first. Publication freezes a release under GitHub's immutable
# releases, so attach-release attaches the verified bundle to the draft
# and publishes it afterwards.
- gh release create "$release_tag" --draft --target "$GITHUB_SHA" --title "$release_tag" \
+ gh release create "$release_tag" --draft --target "$SOURCE_SHA" --title "$release_tag" \
--notes-file "$notes_file" ${prerelease_flag:+$prerelease_flag}
fi
diff --git a/.github/workflows/service-lifecycle.yml b/.github/workflows/service-lifecycle.yml
index ad86503340..87249bf4d1 100644
--- a/.github/workflows/service-lifecycle.yml
+++ b/.github/workflows/service-lifecycle.yml
@@ -2,7 +2,7 @@ name: Service lifecycle
on:
pull_request:
- branches: [main, dev]
+ branches: [dev]
paths:
- "src/service.ts"
# The service implementation is the src/service/ directory; src/service.ts is only
@@ -23,45 +23,62 @@ on:
# commit that touches only release.yml (e.g. the v2.40.0 permissions carry, #3263/#3264)
# produced no run and the gate dead-ended until a manual dispatch.
- ".github/workflows/release.yml"
- push:
- # Release lines only (no dev: cross-platform legs run on dev by manual
- # workflow_dispatch). Pull requests run only the Linux leg. main and preview
- # must stay: release.yml needs a successful push run for the exact release
- # SHA, and scripts/release.ts only releases from main or preview. Without a
- # branch filter every feature-branch push would re-run all three legs.
- branches: [main, preview]
- paths:
- - "src/service.ts"
- # Keep in sync with the release.yml service-gate regex (see above).
- - "src/service/**"
- - "desktop/**"
- # Keep in sync with the release.yml service-gate regex (see above).
- - "src/cli.ts"
- - "src/cli/index.ts"
- - "src/lib/bun-runtime.ts"
- - "package.json"
- - "bun.lock"
- - ".github/workflows/service-lifecycle.yml"
- # release.yml gates on THIS workflow having run for the release SHA. A release-branch
- # commit that touches only release.yml (e.g. the v2.40.0 permissions carry, #3263/#3264)
- # produced no run and the gate dead-ended until a manual dispatch.
- - ".github/workflows/release.yml"
workflow_dispatch:
+ inputs:
+ source_sha:
+ description: "Full dev ancestor SHA to test"
+ required: true
+ type: string
permissions:
contents: read
concurrency:
- group: service-lifecycle-${{ github.ref }}
- cancel-in-progress: true
+ group: service-lifecycle-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.ref }}
+ cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }}
jobs:
+ validate-source:
+ name: validate source
+ runs-on: ubuntu-latest
+ timeout-minutes: 5
+ steps:
+ - name: Validate dispatch source
+ shell: bash
+ env:
+ EVENT_NAME: ${{ github.event_name }}
+ REF: ${{ github.ref }}
+ SOURCE_SHA: ${{ github.event.inputs.source_sha }}
+ GH_TOKEN: ${{ github.token }}
+ run: |
+ set -euo pipefail
+ if [ "$EVENT_NAME" != workflow_dispatch ]; then exit 0; fi
+ if [ "$REF" != refs/heads/dev ] || ! [[ "$SOURCE_SHA" =~ ^[0-9a-f]{40}$ ]]; then
+ echo '::error::dispatch requires dev and a full lowercase source SHA'
+ exit 1
+ fi
+ status="$(gh api "repos/${GITHUB_REPOSITORY}/compare/${SOURCE_SHA}...dev" --jq .status)"
+ if [ "$status" != ahead ] && [ "$status" != identical ]; then
+ echo '::error::source is not an ancestor of dev'
+ exit 1
+ fi
+
linux-systemd:
+ name: linux-systemd ${{ github.event.inputs.source_sha }}
+ needs: validate-source
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- - uses: ./.github/actions/setup-project-bun
+ with:
+ persist-credentials: false
+ ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }}
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ path: .evidence-policy
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: ./.evidence-policy/.github/actions/setup-project-bun
- run: bun install --frozen-lockfile
@@ -177,13 +194,23 @@ jobs:
fi
macos-launchd:
- # Pull requests run the Linux leg only; macOS runs on manual dispatch and main/preview push.
+ name: macos-launchd ${{ github.event.inputs.source_sha }}
+ needs: validate-source
+ # Pull requests run the Linux leg only; macOS runs on manual dispatch.
if: github.event_name != 'pull_request'
runs-on: macos-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- - uses: ./.github/actions/setup-project-bun
+ with:
+ persist-credentials: false
+ ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }}
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ path: .evidence-policy
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: ./.evidence-policy/.github/actions/setup-project-bun
- run: bun install --frozen-lockfile
@@ -257,13 +284,23 @@ jobs:
fi
windows-schtasks:
- # Pull requests run the Linux leg only; Windows runs on manual dispatch and main/preview push.
+ name: windows-schtasks ${{ github.event.inputs.source_sha }}
+ needs: validate-source
+ # Pull requests run the Linux leg only; Windows runs on manual dispatch.
if: github.event_name != 'pull_request'
runs-on: windows-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
- - uses: ./.github/actions/setup-project-bun
+ with:
+ persist-credentials: false
+ ref: ${{ github.event_name == 'workflow_dispatch' && github.event.inputs.source_sha || github.sha }}
+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7
+ with:
+ path: .evidence-policy
+ ref: ${{ github.sha }}
+ persist-credentials: false
+ - uses: ./.evidence-policy/.github/actions/setup-project-bun
- run: bun install --frozen-lockfile
diff --git a/.github/workflows/stale-needs-info.yml b/.github/workflows/stale-needs-info.yml
index d33fb204a5..ca9838ff21 100644
--- a/.github/workflows/stale-needs-info.yml
+++ b/.github/workflows/stale-needs-info.yml
@@ -1,16 +1,14 @@
name: Close stale needs-info issues
-# Scheduled workflows only run from the repository DEFAULT branch
-# (currently `main`), not from `dev`. Landing here on `dev` alone does not
-# change live issue-stale behavior until the change is also on that default
-# branch.
+# Scheduled workflows only run from the repository DEFAULT branch, which is
+# `dev`. A change lands on the live schedule as soon as it is on `dev`.
on:
schedule:
# Daily at 06:15 UTC (offset from the hour to reduce Action load spikes).
- cron: "15 6 * * *"
# No workflow_dispatch: a branch-selected manual run would execute that
# branch's workflow body with issues:write / pull-requests:write, bypassing
- # default-branch review. Schedule-only keeps the trusted revision on main.
+ # default-branch review. Schedule-only keeps the trusted revision on `dev`.
permissions:
issues: write
diff --git a/.gitleaks.toml b/.gitleaks.toml
new file mode 100644
index 0000000000..6267919f0a
--- /dev/null
+++ b/.gitleaks.toml
@@ -0,0 +1,41 @@
+# gitleaks configuration for dalsoop/opencodex (read by .github/workflows/secret-detection.yml and the
+# Macs' pre-commit secret check). The default rules stay on; nothing here disables a rule.
+[extend]
+useDefault = true
+
+[[allowlists]]
+description = """
+Upstream lidge-jun/opencodex test fixtures (brought in with the v2.100.2 merge). Each listed file holds a made-up
+provider key, token or canary that the upstream tests feed through redaction, error-body and request-log paths to
+prove the value never reaches output. Reviewed 2026-11-12 (ocx-align T8): every hit is a test constant, not a
+credential. Scoped to the generic-api-key rule and to exactly these files; every other rule still applies to them.
+"""
+targetRules = ["generic-api-key"]
+paths = [
+ '''^gui/tests/logs-failure-detail\.test\.ts$''',
+ '''^native/ocx-child/tests/relay_and_lifecycle\.rs$''',
+ '''^tests/fixtures/link/ocx-child-conformance\.json$''',
+ '''^tests/helpers/messages-proxy-refusal-case\.ts$''',
+ '''^tests/lib/client-error-body\.test\.ts$''',
+ '''^tests/lib/upstream-condition\.test\.ts$''',
+ '''^tests/providers/cc-switch-import\.test\.ts$''',
+ '''^tests/providers/command-code-plan-denial\.test\.ts$''',
+ '''^tests/responses/chat-error-body-normalization\.test\.ts$''',
+ '''^tests/responses/chat-error-collector-verdicts\.test\.ts$''',
+ '''^tests/responses/passthrough-headers\.test\.ts$''',
+ '''^tests/server/fallback-routes\.test\.ts$''',
+ '''^tests/server/local-control-socket\.test\.ts$''',
+ '''^tests/server/response-model-identity\.test\.ts$''',
+ '''^tests/server/safe-response-headers\.test\.ts$''',
+ '''^tests/server/server-chat-error-body-evidence\.test\.ts$''',
+ '''^tests/server/server-kiro-usage-log-e2e\.test\.ts$''',
+ '''^tests/server/server-live-cancel\.test\.ts$''',
+ '''^tests/server/server-native-final-log\.test\.ts$''',
+ '''^tests/server/server-ollama-inbound-errors\.test\.ts$''',
+ '''^tests/server/turn-state-handles\.test\.ts$''',
+ '''^tests/server/upstream-error-detail-boundaries\.test\.ts$''',
+ '''^tests/usage/mistral-budget-reset-identity\.test\.ts$''',
+ '''^tests/usage/provider-failure-detail\.test\.ts$''',
+ '''^tests/usage/request-log-error-detail\.test\.ts$''',
+ '''^tests/usage/request-log-identity-bounds\.test\.ts$''',
+]
diff --git a/AGENTS.md b/AGENTS.md
index 26f50a0466..ea56c79a95 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -2,17 +2,6 @@
Guidance for AI agents (and humans) working on or reviewing this repository.
-## Repository ownership and publishing target
-
-This is the independently maintained `dalsoop/opencodex` repository. Pushes,
-issues, and pull requests belong in `dalsoop/opencodex` unless the user explicitly
-requests a different destination for the current task.
-
-Do not open or update pull requests against `lidge-jun/opencodex`, or add it as
-a Git remote, without an explicit request to contribute upstream. Historical
-upstream links and the inherited maintainer instructions below do not authorize
-publishing changes there.
-
## What this project is
opencodex (`ocx`) is a universal provider proxy for OpenAI Codex and Claude Code:
@@ -124,10 +113,10 @@ different pointer, so every branch move and promotion dragged a diff.
Reference *clones* are gitignored: they are third-party source carrying their
own licenses and have no business in this repository's history.
-Nothing in the build, typecheck, or test path reads from `devlog/`, so a
-contributor who ignores it entirely still passes every gate. `privacy:scan` does
-read it — that is deliberate, and it is what makes a public devlog safe rather
-than merely visible.
+Build and typecheck do not read `devlog/`. The test-layout membership oracle reads
+`devlog/_fin/260905_test_modularization_and_windows/001_test_inventory.md`; sparse
+checkouts running that test must materialize this tracked input. `privacy:scan`
+also reads `devlog/` to keep public development notes safe to publish.
Two mechanical guards in `tests/ci-workflows/repo-hygiene.test.ts` back this up: no `160000`
gitlink may be tracked anywhere, and neither the vendored reference clones nor
@@ -206,7 +195,7 @@ it binds you regardless of which mechanism is within reach.
```bash
bun install
-bun run typecheck # bun x tsc --noEmit (strict)
+bun run typecheck # bun check --no-script --noEmit (strict)
bun run test:changed # import-graph tests against the resolved `dev` merge base
bun run test # full tests/ suite (default before review)
bun run lint:gui # GUI eslint
@@ -362,8 +351,8 @@ than nudged.
they were deleted; `tests/ci-workflows/repo-hygiene.test.ts` now rejects
those folders. When the PR resolves an issue, add
`Closes #` to link it. GitHub auto-closes the linked issue only
- when the PR merges into the default branch (`main`); PRs here target
- `dev`, so close the issue manually once the change is on `dev`.
+ when the PR merges into the default branch, which is `dev`, so a linked issue
+ closes when its pull request merges.
- **Landing another author's work:** reimplementing, superseding, carrying, or
rebasing someone else's pull request requires a `Co-authored-by` trailer
naming that author, in the description or in a branch commit so it survives
@@ -378,18 +367,41 @@ than nudged.
## CI policy (maintainer decision — do not change)
-- Pull requests run **only the fast Ubuntu subset**.
+- Pull requests run **only the fast Ubuntu subset**. By default that is `gates` plus
+ `test changed` (import-graph tests for the diff); the four full Ubuntu shards run on a
+ pull request only with the `ci:full` label or a CI/harness/toolchain/dependency change.
+ Merged pull requests are verified in batches by a manual `dev` dispatch
+ (`MAINTAINERS.md`, "Batched merges"). Because `test changed` follows the module graph,
+ add `ci:full` for changes it cannot see (subprocesses, files read as data, generated output).
- Full cross-platform (macOS/Windows) CI runs **only** via manual
- `workflow_dispatch` and on push to `main`/`preview` (release lines).
+ `workflow_dispatch` on `dev`. A successful complete `lane=all` run establishes
+ evidence for its exact dev commit; a PR run or narrower manual lane does not.
+- A manual `lane=all` dispatch is a **batch check on `dev`**, never a per-PR gate.
+ One run is about 32 jobs (11 Windows, at least 6 macOS, 15 Linux) and six runner-hours, and the
+ account has only five macOS slots (a macOS job can queue), so per-PR dispatches starve
+ every other check. On 2026-10-27, parallel agent lanes dispatched 48 of them in twelve hours (about 13,000
+ runner-minutes). The queue passed 200 runs, and ordinary PR checks waited hours to start.
+ - Merge a pull request, including a Windows- or macOS-sensitive one, on its green PR
+ CI. After a batch of merges, run one `gh workflow run ci.yml --ref dev` as described
+ under "Batched merges". If it is red, stop merging and fix `dev` from that batch.
+ - Do not dispatch `lane=all` for a PR branch. Run it once for a batch on `dev`;
+ never re-dispatch merely because the head moved or rerun to green. Cancel your
+ own superseded dispatches with `gh run cancel`.
+ - Every description edit or label change starts three event-gate workflows. Batch those
+ edits, and keep the number of agents working pull requests in parallel small.
- **Never** add a `dev` push trigger, or `pull_request` runs for macOS/Windows
jobs, to any workflow. PRs that change this policy will be closed.
## Branch policy
-- `dev` — the single integration branch and the target for every pull request.
-- `main` — release branch. It only moves by maintainer-controlled promotion
- from `dev` (releases, docs deploys). Do not open feature PRs against `main`.
-- `preview` — prerelease train (`x.y.z-preview.*` versions).
+- `dev` — the single development and integration branch, the repository default
+ branch, and the target for every ordinary pull request. Preview and stable
+ releases are built from eligible commits on this line, with versions stamped in
+ build checkouts.
+- `main` and `preview` were deleted once the single-branch model was in place.
+ Their released history remains reachable through tags; they are not
+ integration, promotion, or review targets, and no workflow may trigger on or
+ check out either branch.
Bun-native TypeScript on `dev` is the only runtime line. If native code
returns, the expectation is an incremental module (for example Rust via N-API)
@@ -404,9 +416,9 @@ Rebase pull requests are welcome. Bringing a stale branch onto the current head
is ordinary maintenance — open it as a normal pull request and name the source
commits in the description.
-The **`enforce-target`** CI check rejects pull requests whose head
-ancestry sits on the **`main`** tip while far behind **`dev`**, and rejects
-empty, thin, or malformed descriptions. If changed paths include files under
+The **`enforce-target`** CI check rejects pull requests whose base is not
+**`dev`** (stacked children excepted), and rejects empty, thin, or malformed
+descriptions. If changed paths include files under
`gui/`, include a screenshot of the UI change in the description; the check
re-runs on description edits until the screenshot is present. Drag the image
into the description editor rather than committing it, or, when uploading from
@@ -428,16 +440,15 @@ local-validation box is an author attestation only — fork contributors cannot
repository CI; a maintainer has to — so the gate never disproves it; a new
push still resets every box. A disproved claim unticks the matching box and
keeps the PR a draft.
-Authors with repository push permission skip the ancestry heuristic only. As with approval requirements in
-[`MAINTAINERS.md`](./MAINTAINERS.md), the ancestry heuristic is a CI check
-rather than a branch rule. The branches themselves are protected: `dev`,
-`main`, and `preview` each require a pull request and block force-pushes and deletion.
+As with approval requirements in [`MAINTAINERS.md`](./MAINTAINERS.md), the
+wrong-base rule is a CI check rather than a branch rule. The branch itself is
+protected: `dev` requires a pull request and blocks force-pushes and deletion.
For `dev` only, a current maintainer with GitHub `maintain` or `admin` access may
explicitly integrate through a PR without another maintainer approval, including
their own PR, under the policy in `MAINTAINERS.md`. Record the decision and exact-head
CI evidence; keep outstanding maintainer objections and security review separate.
The bypass is PR-only, so a direct push to `dev` remains rejected regardless of
-local hook settings. Contributor review and `main`/`preview` rules remain unchanged.
+local hook settings. Contributor review rules remain unchanged.
[`MAINTAINERS.md`](./MAINTAINERS.md) is authoritative for review and merge
policy (approvals, CI requirements, security review, promotion). This file
diff --git a/AGENTS_INSTALL.md b/AGENTS_INSTALL.md
index c4a80069fd..6a91b18020 100644
--- a/AGENTS_INSTALL.md
+++ b/AGENTS_INSTALL.md
@@ -52,6 +52,24 @@ The following instructions concern **starring the repository on GitHub**.
the matter permanently — do not argue it, re-frame it, or raise it again
later.
+### Telemetry
+
+Anonymous daily usage telemetry defaults to on only after a human has seen the
+disclosure notice (in the GUI or an interactive TTY prompt). An agent must never
+enable telemetry or acknowledge the telemetry disclosure on the user's behalf:
+`PUT /api/telemetry` and `ocx telemetry enable` refuse agent-driven callers with
+`agent_consent_required` (and `ocx telemetry enable` refuses a non-interactive
+terminal with `tty_required`), and `ocx config set`/`unset telemetry` refuse every
+caller. Opting out (`ocx telemetry disable`, `OCX_TELEMETRY=0` or `DO_NOT_TRACK=1`)
+is always permitted.
+
+A public leaderboard profile is a separate user-consent action: it publishes a handle and
+daily usage totals under the user's chosen name. An agent must never connect one or answer
+its prompt. `POST /api/telemetry/profile` requires a human dashboard session, and
+`ocx telemetry profile connect` refuses agent-driven callers with `agent_consent_required`
+and non-interactive terminals with `tty_required`. Disconnecting
+(`ocx telemetry profile disconnect`), which deletes the profile, is always permitted.
+
## Where things are installed
An agent asked to install, inspect, repair, or remove opencodex needs to know what is written
@@ -92,7 +110,7 @@ A host that has both a Task Scheduler entry and a WinSW service is in a conflict
### The CLI
-`npm install -g @bitkyc08/opencodex` puts `ocx` on the PATH from npm's global prefix, and the
+`npm install -g --allow-scripts=bun @bitkyc08/opencodex` puts `ocx` on the PATH from npm's global prefix, and the
Bun runtime it needs is bundled inside that package. There is no separate runtime to install and
no WSL layer on Windows.
diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md
index 9ae2a4555e..a5944a82f5 100644
--- a/CONTRIBUTING.md
+++ b/CONTRIBUTING.md
@@ -15,9 +15,13 @@ Thanks for helping with opencodex.
## Branches
-- `dev` — the only integration target for pull requests.
-- `main` — releases only; moves by maintainer-controlled promotion from `dev`.
-- `preview` — prerelease train.
+- `dev` — the only integration target for pull requests and the repository
+ default branch. Stable and preview releases are cut from eligible `dev`
+ commits by the release workflow, which stamps the version into build
+ checkouts.
+- `main` and `preview` were deleted once the single-branch model was in place.
+ Their released history remains reachable through tags; neither is an
+ integration, promotion, or review target.
The `dev2-go` Go native-port line has been retired. Its history is archived at
[lidge-jun/opencodex-go-archive](https://github.com/lidge-jun/opencodex-go-archive),
@@ -40,7 +44,7 @@ Bun through that bundled dependency.
- Pull requests run **only the fast Ubuntu subset**.
- Full cross-platform (macOS/Windows) CI runs **only** via manual
- `workflow_dispatch` and on push to `main`/`preview` (release lines).
+ `workflow_dispatch` on `dev`; there is no push trigger.
- **Never** add a `dev` push trigger, or `pull_request` runs for macOS/Windows
jobs, to any workflow. PRs that change this policy will be closed.
@@ -69,9 +73,11 @@ A ready-for-review PR is the author's claim that the change is complete, underst
## Local validation and hooks
-The suite uses Bun 1.4.3 (`testRunnerBun`) while the shipped runtime is 1.4.2.
-`scripts/test.ts` finds a 1.4.3 binary on PATH or in `~/.bun/bin`, or uses
+The suite uses Bun 1.4.4 (`testRunnerBun`) while the shipped runtime is 1.4.4.
+`scripts/test.ts` finds a 1.4.4 binary on PATH or in `~/.bun/bin`, or uses
`OCX_TEST_RUNNER_BUN`; install that version locally if it is missing.
+The roles remain independently checked even when their versions match. Release selection
+requires a successful full cross-platform `lane=all` run on the exact candidate `dev` SHA.
Run `bun run test` before review readiness. If the full local suite is too costly
for the task or available resources, run at least focused regression tests for
diff --git a/CREDITS.md b/CREDITS.md
index 5737ed185e..2d97958251 100644
--- a/CREDITS.md
+++ b/CREDITS.md
@@ -171,6 +171,15 @@ The only remaining trailer is automation.
| --- | --- | --- | --- |
| [#3988](https://github.com/lidge-jun/opencodex/pull/3988) | [@rrmlima](https://github.com/rrmlima) | [`e2bf1672c`](https://github.com/lidge-jun/opencodex/commit/e2bf1672c974611f8db736cd64a90e1dc443924a) / [`14ce693e5`](https://github.com/lidge-jun/opencodex/commit/14ce693e5846596c823941ce90add538713a25b1) | "Carries #3988 by @rrmlima (`cherry-pick -x`)" — Gemini/CCA/Vertex/AI Studio model-tail `(continue)` nudge in `messagesToGeminiFormat`. |
+On 2026-11-06, [#8214](https://github.com/lidge-jun/opencodex/pull/8214)'s description
+named the trailer for overlapping draft [#8176](https://github.com/lidge-jun/opencodex/pull/8176).
+The squash message replaced the description, so the landing commit kept only the
+maintainer trailer. #8176 stays open for its remaining work.
+
+| Pull request | Author | Landed as | What landed |
+| --- | --- | --- | --- |
+| [#8176](https://github.com/lidge-jun/opencodex/pull/8176) | [@luvs01](https://github.com/luvs01) | [#8214](https://github.com/lidge-jun/opencodex/pull/8214) ([`7757a2fe1`](https://github.com/lidge-jun/opencodex/commit/7757a2fe1ff390258752d91c5e35561b6c978634)) | "This overlaps the Messages portion of #8176; its other work remains outside this PR." — Windows separator-aware Bun `onLoad` fixture filters for the Messages refusal/review suites. |
+
## Report and diagnosis
These fixes exist because of the report. The branch's own approach was not the
diff --git a/Dockerfile b/Dockerfile
index 7e36f2063a..54e0153e0f 100644
--- a/Dockerfile
+++ b/Dockerfile
@@ -1,13 +1,14 @@
# syntax=docker/dockerfile:1
# Keep the runtime aligned with package.json and pin the multi-platform image index.
-# Runtime 1.4.2 fixes #6684's Windows Bun.fetch streaming; CI tests run on 1.4.3
-# because 1.4.2 segfaults reloading preloads in multi-file --isolate (#4821;
-# #6713 run 37631558263: Linux 1/4, macOS 2/2, Windows 9/9) and 1.4.0's spawnSync
-# can lose a child's exit (#4956, oven-sh/bun#44581). Rejoin after the
-# upstream crash fix passes a unified-version lane=all dispatch, then delete
-# package.json's testRunnerBun pin and setup-project-bun's role input.
-ARG BUN_IMAGE=oven/bun:1.4.2@sha256:9114c058aeae42162ee16dd5084b95fe9473970bb6bcb5b232ab1630f0546895
+# Runtime 1.4.4 keeps 1.4.2's #6684 Windows Bun.fetch streaming fix and ships NSS
+# 3.131.1 roots without the compromised eMudhra CAs. Runtime and test-runner
+# defaults are both 1.4.4; keep package.json's testRunnerBun pin and
+# setup-project-bun's role input independently validated. Promotion requires
+# an exact-head cross-platform lane=all dispatch, including multi-file --isolate:
+# historical 1.4.2 preload crashes (#4821; #6713 run 37631558263) and 1.4.0
+# spawnSync exit loss (#4956, oven-sh/bun#44581) remain regression risks.
+ARG BUN_IMAGE=oven/bun:1.4.4@sha256:1d22548f177f4ff38e0c15baa3c2c46c6c2060ba2d1bc573bb4720b407548f1d
FROM ${BUN_IMAGE} AS manifest
WORKDIR /home/bun/app
diff --git a/MAINTAINERS.md b/MAINTAINERS.md
index a31c788a2b..34fd9d1caa 100644
--- a/MAINTAINERS.md
+++ b/MAINTAINERS.md
@@ -1,14 +1,5 @@
# Maintainers
-## Independent repository ownership
-
-`dalsoop` owns `dalsoop/opencodex`. The owner has explicitly authorized integrating
-the model visibility fix and personal installation tooling into this repository's
-`main`, after local checks and exact-head Personal repository CI. Installation and
-workflow changes still require a security review. The inherited project governance
-below records the original project's policy; it grants no publishing or review
-authority over this independent repository.
-
This document lists the people responsible for maintaining opencodex and defines the project's
review and merge policy.
@@ -16,13 +7,14 @@ review and merge policy.
| GitHub account | Project role | Responsibilities |
| --- | --- | --- |
-| [@dalsoop](https://github.com/dalsoop) | Repository owner | Independent repository administration, integration, installation and CI |
+| [@lidge-jun](https://github.com/lidge-jun) | Project owner | Project direction, releases, repository administration, and final governance decisions |
+| [@Ingwannu](https://github.com/Ingwannu) | Maintainer | Issue and pull-request triage, `dev` integration, security review, and repository maintenance |
The table describes project responsibilities. Actual repository permissions remain controlled
through GitHub repository settings.
-The original project's maintainers and governance are recorded in the inherited
-history. The remaining sections below describe that project's policy.
+`dev` is the only integration line. The former `dev2-go` carry duty is retired;
+see [The retired `dev2-go` line](#the-retired-dev2-go-line).
## Former maintainers
@@ -36,11 +28,11 @@ when a maintainer steps down.
## Review and merge policy
-- Pull requests target `dev`. It is the only integration line, and promotion to
- `main` happens only from `dev`. The target-branch check accepts `dev` alone.
-- The **`enforce-target`** CI check rejects pull requests whose head
- ancestry sits on the **`main`** tip while far behind **`dev`**, and rejects
- empty, thin, or malformed descriptions; PRs that change files under `gui/`
+- Pull requests target `dev`, the only development and integration line. The
+ target-branch check accepts `dev` alone.
+- The **`enforce-target`** CI check rejects pull requests whose base is not
+ **`dev`** (stacked children excepted), and rejects empty, thin, or malformed
+ descriptions; PRs that change files under `gui/`
must include a screenshot of the UI change in the description. Drag the image
into the description instead of committing it to the PR branch; command-line
uploads use the `pr-assets` branch and a commit-SHA link.
@@ -65,20 +57,29 @@ when a maintainer steps down.
never disproves it;
a new push still resets every box. A disproved claim unticks the matching
box and keeps the PR a draft.
- Authors with repository push permission skip the ancestry heuristic only. As
- with the approval requirement above, this part is enforced by convention;
- the ruleset does not check ancestry (see the note under the change log).
+ As with the approval requirement above, the wrong-base rule is enforced by CI
+ rather than by the ruleset.
- Pull requests require successful required CI checks before merge. Contributor pull requests
normally require approval from at least one maintainer other than the author.
+- **Batched merges.** A pull request's own CI is the fast lane by default: `gates` plus
+ `test changed` (the tests Bun's import graph reaches from the diff), not the four full
+ Ubuntu shards. The shards still run on a pull request that carries the `ci:full` label at
+ push time or touches the CI/test harness, fixtures, toolchain or dependency set
+ (`scripts/ci/select-test-lane.sh`). Add `ci:full` before pushing when a change reaches shared
+ contracts in ways an import graph cannot see (subprocesses, files read as data, generated
+ output). Merge green pull requests one at a time; after roughly every five merges, run
+ `gh workflow run ci.yml --ref dev` (the default `lane=all`). If that run is red, stop merging,
+ fix `dev` from the batch it covers, and resume once it is green. A complete successful
+ dispatch is also the cross-platform evidence for the exact commit it tests.
- A current maintainer with GitHub `maintain` or `admin` access may explicitly integrate a pull
request into `dev` without another maintainer's approval, including their own pull request.
Record that choice and the exact-head verification in the pull-request description or comment.
This is maintainer integration, not a self-approval or an independent review. Outstanding
maintainer change requests must still be resolved or explicitly withdrawn. Technical review,
attribution, documentation and security-review duties remain in force.
-- The maintainer-integration exception applies only to `dev`. It does not change review rules
- for `main` or `preview`, grant contributor authors approval authority, or permit direct pushes,
- force-pushes or branch deletion. Authors do not submit approving reviews of their own work.
+- The maintainer-integration exception applies only to `dev`. It does not grant contributor
+ authors approval authority or permit direct pushes, force-pushes or branch deletion. Authors do
+ not submit approving reviews of their own work.
- Authentication, credential handling, GitHub Actions, release automation, dependency installation,
and other security-boundary changes require explicit security review.
- A new or promoted provider preset is a credential-destination change. Before merge it needs the
@@ -95,29 +96,19 @@ when a maintainer steps down.
- Integration uses pull requests, including urgent maintainer repairs. The PR-only ruleset
bypass does not authorize direct pushes; incident changes to branch protection require a
separate owner decision.
-- Promotion from `dev` to `main` and npm releases is maintainer-controlled.
-- **Opening a release starts by moving `dev`'s version line forward.** Before cutting
- a release, `dev` must already outrank the version being released; `release.yml`
- asserts this and refuses to publish otherwise. Dispatch
- `.github/workflows/dev-version-bump.yml` with the intended version, merge the pull
- request it opens, then promote and release. When `dev` already outranks the target
- — a preview cut, or a stable hotfix below `dev`'s line — no move is needed and the
- workflow reports `changed=false`.
-
- Opening a preview for the next core ends the current patch line. After
- `vX.Y.0-preview.*` is tagged, a fix ships as part of `X.Y.0`, not as
- `X.(Y-1).(Z+1)`. The release helper refuses such a bump rather than producing a
- version the repository would reject. This is a deliberate policy restriction, not
- a claim that lower stable patches were historically unused.
-
- Done after the publish, as this repository did for ten releases (`32529c2b2`,
- `e4a85d134`, `076ad3036`, `befcac3e1`, then #3045, #3076, #3127, #3265, #3354,
- #3434), it leaves `dev` and every open pull request carrying a failure contributors
- cannot fix from their own diff. The pull request itself does not go away — `Protect
- dev` requires a reviewed merge. If the pre-move is missed and publication somehow
- succeeds, dispatch `dev-version-bump.yml` from the default branch with the released
- version and `mode=repair`, then merge the repair pull request. Design:
- `devlog/_plan/260904_release_version_line/`.
+- npm releases are maintainer-controlled. Preview and stable releases use an eligible
+ `dev` commit with successful full manual cross-platform CI; the workflow stamps the
+ release version into build checkouts instead of committing a pre-release version bump
+ or promoting a branch. Releases share one concurrency group and preserve the global
+ version ordering. The `main` and `preview` branches were deleted after the
+ single-branch model was in place; released history remains reachable through
+ tags, and neither branch is a release target.
+- Publication remains disabled until the coordinator completes the cutover checks,
+ including the reviewed legacy lineage baseline, npm trusted-publisher configuration,
+ default branch and rulesets, Pages settings, and a hosted dry-run. The variable
+ `OCX_DEV_RELEASE_PUBLISH_ENABLED` must equal `true` for a real publication; missing
+ or other values keep the hold in place. A hosted release dry-run uses the trusted
+ `dev` workflow and does not publish.
## The retired `dev2-go` line
@@ -155,7 +146,7 @@ Adding or removing a maintainer requires:
- 2026-09-06 — The owner authorized explicit maintainer integration into `dev` without a second
maintainer approval. Both current maintainers have `admin` access. The dev-only PR bypass
includes GitHub's `admin` and `maintain` roles; `write` access alone is insufficient. Contributor
- review remains the default and the `main`/`preview` rules are unchanged. The optional
+ review remained the default; the former `main`/`preview` branches were later retired. The optional
`scripts/ci/assert-mergeable-review.sh --maintainer-integration [repo]` path checks
the authenticated actor against the trusted `dev` roster and live repository permissions,
preserves outstanding maintainer objections, and binds its result to the current head and base.
@@ -204,10 +195,10 @@ Adding or removing a maintainer requires:
this addition does not widen the review surface for them.
Code-owner approval and the maintainer-approval requirement above are both
- enforced, not conventions. `dev`, `main`, and `preview` each carry an active
- repository ruleset — the classic `/branches/{branch}/protection` endpoint
- returns 404 for them, which is why this file long described the repository as
- unprotected. `Protect dev` (id 20763889) requires a pull request with one
+ enforced, not conventions. `dev` carries an active repository ruleset; the
+ classic `/branches/{branch}/protection` endpoint can return 404 for rulesets,
+ which is why this file long described the repository as unprotected.
+ `Protect dev` (id 20763889) requires a pull request with one
approving review, code-owner review, and extra approval for unattributed
changes, and it blocks deletion and non-fast-forward pushes. Allowed merge
methods are merge and squash; rebase merges are off.
diff --git a/PERSONAL.md b/PERSONAL.md
deleted file mode 100644
index c844dbb5cd..0000000000
--- a/PERSONAL.md
+++ /dev/null
@@ -1,63 +0,0 @@
-# Independent installation
-
-This repository is maintained at **dalsoop/opencodex**. Its model visibility fixes
-are installed from our `main`, separately from the original npm package.
-
-On macOS or Linux, with Git, Node.js and Bun installed:
-
-```sh
-git clone https://github.com/dalsoop/opencodex.git
-cd opencodex
-bun scripts/personal-install.ts --service
-```
-
-Put `~/.local/share/opencodex-personal/bin` first in `PATH`. The managed command
-is `ocx`; `ocx update --check` prints our latest main commit, and `ocx update`
-installs that exact commit. Omit `--service` on the first install to manage the
-proxy manually. Once selected, service management persists across updates.
-
-The installer prepares dependencies with frozen lockfiles and builds the GUI
-before switching installations. Releases live under
-`~/.local/share/opencodex-personal/releases/`. It atomically switches
-`current`, restores the previous pointer if activation fails, and attempts to
-restore the previous service. Old releases remain available for recovery.
-
-Updates never run `ocx stop` or any other command that restores the Codex config.
-On macOS the launchd plist runs through `current`, and the installer restarts the
-service only with `launchctl kickstart -k gui/$(id -u)/com.opencodex.proxy`. It then
-waits up to 90 seconds until `/healthz` on the plist's port answers with the new
-pid launchd reports. It probes the configured `hostname`, read by the release's own
-config loader under the plist's `OPENCODEX_HOME`, and uses 127.0.0.1 only when that
-host is unset or a wildcard. On failure it restores `current` and kickstarts the
-previous release. launchd keeps the definition it loaded, so while a job is still pinned to
-one release the installer restarts nothing and prints a one-time reload:
-`launchctl bootout gui/$(id -u)/com.opencodex.proxy`, then, once `launchctl print`
-no longer finds it,
-`launchctl bootstrap gui/$(id -u) ~/Library/LaunchAgents/com.opencodex.proxy.plist`
-(or log out and back in). `ocx service install` and `ocx service repair` write a
-release-pinned plist again, so after either one the next update refuses until that
-reload is repeated. A first macOS service install happens only with an explicit
-`--service`; it may stop a standalone proxy, which restores Codex. On Linux the
-installer runs `ocx service`, which repairs and restarts the systemd unit without
-restoring Codex.
-
-`ocx update` runs the installer of the release it replaces. To move an
-installation made before this change, bootstrap once from a fresh clone instead:
-
-```sh
-git clone https://github.com/dalsoop/opencodex.git /tmp/opencodex-bootstrap
-cd /tmp/opencodex-bootstrap && bun scripts/personal-install.ts
-```
-
-On macOS that first run stops at the release-pinned check: perform the one-time
-reload above, then run the same command again. Later `ocx update` runs are safe.
-An interrupted install leaves `install.lock`; remove it only after confirming
-no installer is running. User configuration and credentials remain in their
-existing state directories. The source installation disables the npm updater;
-the managed launcher routes `ocx update` exclusively to this installer.
-
-Personal repository CI runs the full Bun suite, typecheck, structure/privacy
-checks and documentation build. It publishes no packages and uses no secrets.
-The inherited cross-platform workflows remain available separately.
-Inherited Pages deployment stays off unless the repository owner explicitly sets
-`OCX_ENABLE_DOCS_DEPLOY=1` after configuring their own site.
diff --git a/README.md b/README.md
index f6a09a7397..2255ae29e0 100644
--- a/README.md
+++ b/README.md
@@ -1,24 +1,22 @@
-> **dalsoop/opencodex:** independently maintained repository. Use the
-> [personal installation and update instructions](PERSONAL.md) for this version.
-> The original project's package and release links below describe its distribution.
-
-
+
-
make codex open!
-
Universal provider proxy for OpenAI Codex, Claude Code, Claude Desktop & Grok Build
-Two commands, and every one of them runs any LLM you point it at.
+
One local gateway for your AI coding tools and models.
+
Use the models you choose with Codex, Claude Code, Claude Desktop and Grok Build,
+and connect OpenCode, Pi, Qoder, WorkBuddy, Kilo, Cline, T3 Code and more through managed configs.
+See every supported tool →
+
Part of GOAT: run your coding agents on any model, on any machine → trygoat.ai
-
+
```bash
-npm install -g @bitkyc08/opencodex
+npm install -g --allow-scripts=bun @bitkyc08/opencodex
ocx start
```
@@ -51,7 +49,7 @@ Pick a provider and go — same workflow, different brain.
-
+
@@ -63,7 +61,7 @@ Opus answers, then hands the task to a GPT-5.6 Sol subagent.
-
+
@@ -75,7 +73,7 @@ Sol drives the session and calls a Kimi K3 subagent.