@futurelastic/colab-handbook 1.19.1-rc.2 → 1.20.0-rc.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -33,5 +33,5 @@
33
33
  "engines": {
34
34
  "node": ">=18"
35
35
  },
36
- "version": "1.19.1-rc.2"
36
+ "version": "1.20.0-rc.1"
37
37
  }
@@ -85,6 +85,7 @@ header naming its new home ([`docs/compat-surfaces.md`](../docs/compat-surfaces.
85
85
  |---|---|---|
86
86
  | `ci-node.yml`, `ci-python.yml`, `ci-laravel.yml` (with the #625 `Migration round-trip` job), `ci-*-heavy.yml` | your forge's CI; `colab ship` / `promote` read or dispatch the runs; `colab template --roundtrip` writes the round-trip job | the adopter's CI layer; until it ships (#608), an optional starting file here |
87
87
  | `release-tag.yml`, `release-auto.yml` | your forge's CI; `release-auto.yml` runs `colab release cut` / `finalize --auto` | the release commands' new home (#608); an optional starting file here until then |
88
+ | `forgejo-release-auto.yml` | a Forgejo repo's CI; runs `colab release cut --auto` | the owner's #681 exception to #608 item 10 for Forgejo; an optional starting file here |
88
89
  | `dist-refs.yml`, `npx-launcher.mjs`, `npx-service.mjs` | your own release workflow and package `bin` | stays here, as an optional starting file |
89
90
  | `publish-downloads.yml`, `publish-downloads.mjs` | your own release workflow, as its last job | stays here, as an optional starting file |
90
91
  | `deploy-xserver.yml`, `deploy-container.yml`, `deploy-container-run.mjs`, `deploy-adapter-portainer.mjs` | your repo's deploy workflow | the adopter's deploy tooling; here as an optional starting file |
@@ -107,6 +108,7 @@ check that reads one of these files is that tool's behaviour, documented with th
107
108
  | `ci-python.yml` | `.github/workflows/ci.yml` | Python: FastAPI/Flask services, CLIs, libraries | Resolves Python from `project.yml` → `.python-version`/`requires-python` → **fails**. `requirements.txt` does not count. **Hybrid** Python+Node repo: copy this, then paste `ci-node.yml`'s `build:` job alongside — see the template header. Opt-in `Migration round-trip` job, as in `ci-node.yml`. |
108
109
  | `release-tag.yml` | `.github/workflows/release.yml` | Any repo cutting `v*.*.*` releases | Triggers on tag push. Publishes a grouped GitHub Release — a `-rc.N` tag as a pre-release, every summary since the previous *final* tag. No toolchain, no deploy; its header shows the `!v*.*.*-*` exclusion a deploy trigger needs. |
109
110
  | `release-auto.yml` | `.github/workflows/release-auto.yml` | A repo whose release tags land on `main` (`trunk: main`, `deploy: tag` or `none`) and whose §6 release route cuts candidates | Runs `colab release cut --auto` after CI goes green on main — at the sha that CI run tested (`--sha`, #622), even once main has moved on — and `colab release finalize --auto` daily — plus an hourly run that re-tries only a refused cut, once the fetched CLI has moved within `RETRY_WINDOW_MINUTES` or a run at main's head was cancelled (#547) — from a handbook ref (`HANDBOOK_REF` — the `stable` channel by default, `next` for the fast channel, or an exact tag to freeze; #445) — the handbook's own copy runs its checkout's CLI instead, since it ships the CLI it releases with (#428). **Publishes the Release in the same run** — a tag pushed with `GITHUB_TOKEN` triggers no other workflow, so `release-tag.yml` would never fire for it. A refusal is a warning, not a red run. Reads and creates tags, and fast-forwards the release channels `next` / `stable` (branches naming the newest candidate / final, #445); never pushes a commit. The audit recognises any workflow running `release cut/finalize --auto` and warns when the route leaves candidates off, when it tags without publishing while a tag-push workflow waits, or when it commits. |
111
+ | `forgejo-release-auto.yml` | `.forgejo/workflows/release-auto.yml` | A repo hosted on **Forgejo** (or Gitea) whose §6 release route cuts candidates, with the forge named in the machine config's `forges` (#678) | The Forgejo dialect of `release-auto.yml` (#681). It has no `workflow_run`: the job you append to your CI (in its header) dispatches it when CI ends green, with `source=ci-completed` and the sha it tested. It waits for CI at that sha (`colab ci-wait`), then runs `colab release cut --auto --sha`, which tags the candidate and publishes its pre-release through the forge's API. No `permissions:` blocks, full-URL `uses:`, the runner label from the `RELEASE_RUNNER` variable, verdicts printed to the log (Forgejo drops the step summary), no `jq`. A refusal stays green. No verdict is a red run. **No finalize step**: on a forge a final is a human's `release finalize` under the human bar, which also publishes the final's release, so no tag-push workflow is needed. Keep its `name:` equal to the file's base name, because the CLI drops its own statuses by that name. |
110
112
  | `dist-refs.yml` | `.github/workflows/dist-refs.yml` | A **private** repo shipping a **compiled** tool, installed as `npx github:<org>/<repo>#vX.Y.Z` ([CONVENTIONS §6, *Distribution*](../CONVENTIONS.md#distribution--one-install-surface-npx-442)) | `workflow_call`, called from the same run that cut the release tag (a tag pushed with `GITHUB_TOKEN` triggers nothing else). Takes one build artifact per `<os>-<arch>` and pushes each as an orphan commit at `refs/tags/dist/vX.Y.Z/<os>-<arch>` with a `SHA256SUMS`. Refuses a public or unreadable repository (a public compiled tool ships npm platform packages instead), a version that is not an existing tag, and a missing platform — before pushing any. Never moves a dist ref that exists. |
111
113
  | `npx-launcher.mjs` | anywhere in-repo (e.g. `bin/launch.mjs`), named by the root `package.json`'s `bin` | Pairs with `dist-refs.yml` | Node ≥ 18, zero dependencies, needs `git`. Reads the `#vX.Y.Z` npx installed, fetches that one dist ref with the same URL and credentials npx cloned with, verifies `SHA256SUMS`, installs to a stable per-user path (`$XDG_DATA_HOME`/`%LOCALAPPDATA%`), and execs it; `--print-path` prints that path. A **channel** committish (`#stable`, `#next`, #465) is resolved to the release tag on the commit npx installed, then installed as that version; any other branch is refused. Also the library `npx-service.mjs` imports. `*.mjs`, so `colab template npx-launcher.mjs --dest <path>` copies it stamped, `--dest` required. One edit point: `BIN` (defaults to the package name without its scope). |
112
114
  | `npx-service.mjs` | the same directory as your `npx-launcher.mjs` copy (e.g. `bin/service.mjs`), named by the root `package.json`'s `bin` | A tool that runs as a **per-machine service** (a dashboard, a daemon, a JS app a launch agent serves), installed with npx ([CONVENTIONS §6, *Services over npx*](../CONVENTIONS.md#services-over-npx--init-update-rollback-465)) | `npx github:<org>/<repo>#vX.Y.Z init [--auto-update 6h \| --no-auto-update]`, then `<tool> update [--check] [--version vX.Y.Z] [--channel next\|stable]`, `<tool> rollback`, `<tool> status`, `<tool> uninstall [--purge]` (#472: unit, timer, shim and every version go; config and state stay unless `--purge`); anything else runs the current version's payload. Versions side by side under `$XDG_DATA_HOME/<tool>/` with `current`/`previous` links the unit and the `~/.local/bin` shim go through; update installs beside, switches, restarts, health-checks, and **switches back** on failure. Config/secrets under `$XDG_CONFIG_HOME/<tool>/`, state and logs under `$XDG_STATE_HOME/<tool>/` — the unit carries their locations, never a value. launchd agent on macOS, systemd user unit on Linux, Windows refused; `<TOOL>_SERVICE_MANAGER=none` skips the manager. `--auto-update` (#471) adds a timer (launchd `StartInterval` agent / systemd user `.timer`) that runs the same `update`. Node ≥ 18, zero dependencies; needs `git`, `npm` for `update`, `tar` for `dist`. **Imports `./npx-launcher.mjs`** — copy both, or edit the import. Edit points: `KIND` (`binary` = a compiled tool from dist refs, `package` = a JS app run with node, `dist` = a prebuilt JS app unpacked from one verified tarball in the `dist/vX.Y.Z/any` ref, #470), `LABEL`, `SERVICE_ARGS`, `ENTRY`, `DIST_FILE`, `HEALTH_URL`, `KEEP`, `AUTO_UPDATE`, `VERBS`. The package's `files` must include both copies (and a `package` app's built output). `colab template npx-service.mjs --dest <path>`, `--dest` required. |
@@ -0,0 +1,220 @@
1
+ # Release (auto), Forgejo dialect — TEMPLATE (#681). Copy me into your repo at
2
+ # .forgejo/workflows/release-auto.yml.
3
+ #
4
+ # This is a starting point, not a dependency. Once you copy it, YOU OWN THIS FILE.
5
+ # Edit it freely; nothing calls it remotely and nothing will update it for you.
6
+ #
7
+ # EDIT POINTS are marked `# EDIT:` — walk them once after copying.
8
+ #
9
+ # WHAT IT DOES. The candidate half of CONVENTIONS.md §6's release rung, on a repo hosted on Forgejo
10
+ # (or Gitea): a green CI run on main cuts the next candidate `vX.Y.Z-rc.N`, pushes the tag and
11
+ # publishes its pre-release on the forge.
12
+ #
13
+ # trigger step
14
+ # ---------------------------------------------- ---------------------------------------------
15
+ # your CI workflow finished green on main and colab ci-wait --sha <sha>, then
16
+ # dispatched this one (source=ci-completed) colab release cut --auto --sha <sha>
17
+ # a daily schedule colab ci-wait, then colab release cut --auto
18
+ # at main's head (a head a missed dispatch
19
+ # left uncut)
20
+ #
21
+ # THE FINAL IS A HUMAN ACT ON A FORGE. There is no finalize step here: an automatic final leans on
22
+ # the release tracking issue, and the handbook writes no issue on a forge (#678). A human finalizes:
23
+ # COLAB_HUMAN=1 colab release finalize --tag vX.Y.Z-rc.N --answered-by <name>
24
+ # which tags the final and publishes its release object itself, so no separate tag-push workflow
25
+ # (the GitHub `release-tag.yml`) is needed here. A route that tags finals on its own
26
+ # (`release.route: deploy-tag-fast` / `library-fast`) is refused on a forge for the same reason.
27
+ #
28
+ # HOW IT DIFFERS FROM templates/release-auto.yml (the GitHub workflow), and why:
29
+ # - no `workflow_run` — Forgejo has none. Your CI dispatches this workflow when it ends green
30
+ # (the job to add is below, CI DISPATCH), with `source=ci-completed` and the sha it tested.
31
+ # - no `permissions:` blocks — Forgejo does not read them. The token is a secret you set
32
+ # (RELEASE_TOKEN), falling back to the job's own token.
33
+ # - full-URL `uses:` — a bare `actions/checkout` resolves against the instance's default action
34
+ # host, which differs between instances; the URL says which one.
35
+ # - the runner label comes from an Actions variable (RELEASE_RUNNER), not a literal.
36
+ # - verdicts are printed to the log — Forgejo drops `$GITHUB_STEP_SUMMARY`.
37
+ # - no `jq`: the verdict JSON is read with node, which the CLI needs anyway.
38
+ #
39
+ # THE CLI IGNORES THIS WORKFLOW'S OWN STATUSES when it reads CI at a commit (#425, #681): on a
40
+ # Forgejo runner a status context reads `<workflow> / <job> (<event>)`, and the CLI drops the ones
41
+ # whose `<workflow>` is this file's — by its path or its base name. So keep `name:` below equal to
42
+ # this file's base name (`release-auto` for release-auto.yml), and never fold these steps into the
43
+ # workflow that runs your test suite: that suite's statuses would be ignored with it.
44
+ #
45
+ # A REFUSAL IS NOT A FAILURE. `colab release cut --auto` refusing (nothing owed, a check failed) is
46
+ # the ordinary output of most runs: it is printed as a warning and the job stays green, because a
47
+ # red run at main's head reads as "main not green" to `colab ship`. A FAILED CLI STEP FAILS THE
48
+ # JOB: no verdict at all (a crash, bad flags, a CLI too old for Forgejo) is a red run, and a missing
49
+ # verdict is never read as "no candidate cut". CI that is red at the sha is not a candidate (exit 0,
50
+ # said so); CI still running when the wait's deadline passes is a warning — the next run cuts it.
51
+ #
52
+ # WHAT THE MACHINE CONFIG SAYS. The CLI knows a remote is Forgejo from `forges` in its machine
53
+ # config ($COLAB_HOME/config.json, never a tracked file). This workflow writes one for the run,
54
+ # naming this instance (github.server_url) — nothing to edit.
55
+ #
56
+ # CI DISPATCH — add this job to the END of your CI workflow (.forgejo/workflows/ci.yml):
57
+ #
58
+ # release-dispatch:
59
+ # needs: [test] # EDIT: every other job of your CI workflow
60
+ # if: github.event_name == 'push' && github.ref == 'refs/heads/main'
61
+ # runs-on: ${{ vars.RELEASE_RUNNER || 'docker' }}
62
+ # steps:
63
+ # - name: Dispatch the release workflow at this sha
64
+ # env:
65
+ # TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
66
+ # URL: ${{ github.server_url }}/api/v1/repos/${{ github.repository }}/actions/workflows/release-auto.yml/dispatches
67
+ # SHA: ${{ github.sha }}
68
+ # run: |
69
+ # node -e '
70
+ # const body = { ref: "main", inputs: { source: "ci-completed", sha: process.env.SHA } };
71
+ # fetch(process.env.URL, { method: "POST", body: JSON.stringify(body),
72
+ # headers: { authorization: "token " + process.env.TOKEN, "content-type": "application/json" } })
73
+ # .then(async (r) => { if (r.status >= 300) { console.error(r.status, await r.text()); process.exit(1); } });'
74
+ #
75
+ # It runs only after every other CI job passed (`needs:`), so a red CI run dispatches nothing. Its
76
+ # own status (`CI / release-dispatch (push)`) is part of CI: the release run's `ci-wait` waits for
77
+ # it, and it finishes seconds after the dispatch.
78
+ #
79
+ # SECRETS AND VARIABLES (repository or organisation settings → Actions):
80
+ # RELEASE_TOKEN secret, recommended — a token that may push tags, create releases and dispatch
81
+ # workflows on this repo (write:repository). Without it the job's own token is
82
+ # used, which some instances do not let create releases or dispatch.
83
+ # RELEASE_RUNNER variable, optional — the runner label (default `docker`).
84
+ #
85
+ # The tag this run pushes starts no other workflow (a tag pushed with an Actions token never does),
86
+ # which is why the cut publishes the pre-release itself.
87
+
88
+ name: release-auto
89
+
90
+ on:
91
+ workflow_dispatch:
92
+ inputs:
93
+ source:
94
+ description: "Who dispatched this run: ci-completed (your CI, at the sha it tested) or manual"
95
+ required: false
96
+ default: "manual"
97
+ type: string
98
+ sha:
99
+ description: "The main commit CI tested (ci-completed sets it); empty = main's head"
100
+ required: false
101
+ default: ""
102
+ type: string
103
+ dry_run:
104
+ description: "Dry run: decide everything, write nothing (no tag, no release)"
105
+ required: false
106
+ default: false
107
+ type: boolean
108
+ schedule:
109
+ # EDIT: when the daily catch-up cut runs (UTC). Off the hour on purpose.
110
+ - cron: "17 3 * * *"
111
+
112
+ env:
113
+ # EDIT: the handbook ref whose colab CLI makes the release decisions — `stable` (the newest final),
114
+ # `next` (the newest candidate) or an exact vX.Y.Z. It must carry #681 (Forgejo support): the
115
+ # "Fetch the colab CLI" step refuses an older CLI rather than letting it refuse every cut.
116
+ HANDBOOK_REF: "stable"
117
+ HANDBOOK_REPO: "https://github.com/futurelastic/colab-handbook.git"
118
+ # EDIT: how long the run waits for CI at the sha to finish before giving up for this run.
119
+ CI_WAIT_TIMEOUT: "30m"
120
+
121
+ jobs:
122
+ release:
123
+ name: Cut a candidate
124
+ runs-on: ${{ vars.RELEASE_RUNNER || 'docker' }}
125
+ env:
126
+ FORGEJO_TOKEN: ${{ secrets.RELEASE_TOKEN || github.token }}
127
+ SOURCE: ${{ inputs.source || github.event_name }}
128
+ RUN_SHA: ${{ inputs.sha }}
129
+ # A dispatch on any ref other than main is dry whether or not dry_run is set.
130
+ DRY_RUN: ${{ github.event_name == 'workflow_dispatch' && (inputs.dry_run || github.ref_name != 'main') }}
131
+ steps:
132
+ - uses: https://code.forgejo.org/actions/checkout@v4
133
+ with:
134
+ ref: main # EDIT: your trunk, if it is not main
135
+ # Full history plus tags: versions, bumps and "previous final" are read from git, and the
136
+ # on-trunk check refuses a shallow checkout outright.
137
+ fetch-depth: 0
138
+ # `colab release cut` pushes its tag over the checkout's origin with this token.
139
+ token: ${{ secrets.RELEASE_TOKEN || github.token }}
140
+
141
+ - name: Fetch the colab CLI
142
+ run: |
143
+ set -eu
144
+ rm -rf "$RUNNER_TEMP/colab-handbook"
145
+ git clone --quiet --depth 1 --branch "$HANDBOOK_REF" "$HANDBOOK_REPO" "$RUNNER_TEMP/colab-handbook"
146
+ COLAB="$RUNNER_TEMP/colab-handbook/tools/colab"
147
+ # A CLI older than #681 reads every Forgejo cut as "gh not usable" and refuses it forever.
148
+ if ! node "$COLAB" release cut --help | grep -q 'On a Forgejo remote'; then
149
+ echo "::error::HANDBOOK_REF \"$HANDBOOK_REF\" carries a colab CLI without Forgejo release support (#681) — set HANDBOOK_REF to a ref that has it"
150
+ exit 1
151
+ fi
152
+ echo "COLAB=$COLAB" >> "$GITHUB_ENV"
153
+ # The machine config naming this instance as a Forgejo forge (tools/lib/tracker.js engineFor).
154
+ COLAB_HOME="$RUNNER_TEMP/colab-home"
155
+ mkdir -p "$COLAB_HOME"
156
+ SERVER="${{ github.server_url }}" node -e '
157
+ const u = new URL(process.env.SERVER);
158
+ const api = process.env.SERVER.replace(/\/+$/, "") + "/api/v1";
159
+ require("fs").writeFileSync(process.argv[1], JSON.stringify({ forges: { [u.hostname]: { engine: "forgejo", api, tokenEnv: "FORGEJO_TOKEN" } } }));
160
+ ' "$COLAB_HOME/config.json"
161
+ echo "COLAB_HOME=$COLAB_HOME" >> "$GITHUB_ENV"
162
+ # The tags are annotated; git needs an identity to write one.
163
+ git config user.name "forgejo-actions"
164
+ git config user.email "forgejo-actions@noreply.invalid"
165
+
166
+ - name: Wait for CI at the sha (colab ci-wait)
167
+ id: wait
168
+ run: |
169
+ set -u
170
+ SHA="${RUN_SHA:-}"
171
+ [ -n "$SHA" ] || SHA="$(git rev-parse origin/main)"
172
+ echo "sha=$SHA" >> "$GITHUB_OUTPUT"
173
+ echo "release-auto ($SOURCE): waiting for CI at $SHA"
174
+ rc=0
175
+ node "$COLAB" ci-wait --sha "$SHA" --timeout "$CI_WAIT_TIMEOUT" || rc=$?
176
+ case "$rc" in
177
+ 0) echo "cut=true" >> "$GITHUB_OUTPUT" ;;
178
+ 1) echo "cut=false" >> "$GITHUB_OUTPUT"; echo "CI is red at $SHA — not a candidate, nothing to cut." ;;
179
+ 3) echo "cut=false" >> "$GITHUB_OUTPUT"; echo "::warning::CI at $SHA did not finish within $CI_WAIT_TIMEOUT — nothing cut this run; the next dispatch or the daily run cuts it." ;;
180
+ *) echo "::error::colab ci-wait gave no verdict (exit $rc) — the reason is in this step's log"; exit 1 ;;
181
+ esac
182
+
183
+ - name: Cut a candidate (colab release cut --auto)
184
+ if: steps.wait.outputs.cut == 'true'
185
+ env:
186
+ SHA: ${{ steps.wait.outputs.sha }}
187
+ run: |
188
+ set -u
189
+ OUT="$RUNNER_TEMP/cut.json"
190
+ DRY=""; [ "${DRY_RUN:-false}" = "true" ] && DRY="--dry"
191
+ rc=0
192
+ # The checkout sits on main's head; a release.guard-run reads the working tree, so it is
193
+ # detached at the sha being cut and restored afterwards.
194
+ HEAD="$(git rev-parse HEAD)"
195
+ [ "$HEAD" = "$SHA" ] || git checkout --quiet --detach "$SHA"
196
+ node "$COLAB" release cut --auto --sha "$SHA" $DRY --json > "$OUT" || rc=$?
197
+ [ "$HEAD" = "$SHA" ] || git checkout --quiet main
198
+ # A verdict is JSON carrying `ok`; anything else is a run that never decided — red.
199
+ node -e '
200
+ const fs = require("fs");
201
+ let v;
202
+ try { v = JSON.parse(fs.readFileSync(process.argv[1], "utf8")); } catch (_) { v = null; }
203
+ if (!v || typeof v !== "object" || !("ok" in v)) {
204
+ console.log("::error::colab release cut produced no verdict (exit " + process.argv[2] + ")");
205
+ process.stdout.write(fs.existsSync(process.argv[1]) ? fs.readFileSync(process.argv[1], "utf8") : "");
206
+ process.exit(1);
207
+ }
208
+ console.log("colab release cut --auto at " + v.sha);
209
+ for (const c of v.checks || []) console.log(" " + (c.checked === false ? "·" : c.ok ? "✓" : "✗") + " " + c.condition + " — " + c.detail);
210
+ const fail = (v.checks || []).filter((c) => c.ok === false && c.checked !== false).map((c) => c.condition + " — " + c.detail).join("; ");
211
+ if (process.env.DRY_RUN === "true") console.log("Dry run — would cut: " + (v.tag || "nothing"));
212
+ else if (v.created) {
213
+ console.log("Cut " + v.tag + " and pushed it.");
214
+ if (v.published && !v.published.ok) console.log("::warning::" + v.published.detail);
215
+ else if (v.published) console.log(v.published.detail);
216
+ } else if (v.noop) console.log("No-op: nothing owed, or a later commit already carries a candidate.");
217
+ else if (v.ok) console.log("Verdict ok but nothing created.");
218
+ else if ((v.standing || []).length) console.log("::error title=Release stalled::colab release cut refused on a condition that does not clear by itself (" + v.standing.join(", ") + "): " + fail);
219
+ else console.log("::warning::colab release cut refused: " + fail);
220
+ ' "$OUT" "$rc"
package/tools/colab CHANGED
@@ -261,6 +261,22 @@ function forgeCi(repoAbs) {
261
261
  return forgeEngine(repoAbs).engine === 'github' ? null : tracker.ciFor(repoAbs);
262
262
  }
263
263
 
264
+ /**
265
+ * #681: where the workflows that run at `sha` live. GitHub reads `.github/workflows`; Forgejo runs
266
+ * `.forgejo/workflows` when the tree has it and falls back to `.github/workflows` when it does not.
267
+ */
268
+ function releaseWorkflowDir(repoAbs, sha, forge) {
269
+ if (!forge) return '.github/workflows';
270
+ return git.git(['cat-file', '-e', `${sha}:.forgejo/workflows`], repoAbs).ok ? '.forgejo/workflows' : '.github/workflows';
271
+ }
272
+
273
+ /** #681: how a human publishes a release object the run could not — the forge's page, or the gh command. */
274
+ function publishByHandHint(repoAbs, tag, { prerelease }) {
275
+ const forge = forgeCi(repoAbs);
276
+ if (forge) return `publish it by hand on ${forgeEngine(repoAbs).host} (Releases → new release from the existing tag ${tag}${prerelease ? ', marked pre-release' : ''})`;
277
+ return `publish it by hand: gh release create ${tag} --verify-tag ${prerelease ? '--prerelease --latest=false' : '--latest'}`;
278
+ }
279
+
264
280
  /**
265
281
  * #344: the honest half of every "gh not usable" message — WHICH of isGhUsable's conditions failed.
266
282
  * The old fixed text "(no auth / no origin)" blamed both at once, and pointed an operator whose
@@ -1428,13 +1444,21 @@ alone. Best-effort like the pre-release (--json channel.ok false); the tag stand
1428
1444
  Needs origin reachable (the tag is recorded there) and gh usable (CI, suite and switch markers are
1429
1445
  read from GitHub). Exit code: 0 when a candidate was cut (or, with --dry, would be), or an --auto
1430
1446
  no-op; 1 when refused.
1447
+
1448
+ On a Forgejo remote (the machine config's \`forges\` names its host, #678) no gh is used (#681): CI
1449
+ and the suite are the commit statuses at the sha, the switch markers are read from the forge's issue
1450
+ list, and the candidate's pre-release is published through the forge's /releases API with the token
1451
+ in the engine's tokenEnv (default FORGEJO_TOKEN). Workflows are read from .forgejo/workflows when
1452
+ the tree has it. A route that tags finals (deploy-tag-fast, library-fast) refuses there: its writes
1453
+ are tracker writes the handbook does not make on a forge. Template: templates/forgejo-release-auto.yml.
1431
1454
  `;
1432
1455
 
1433
1456
  /** Every issue with state + body, for the switch markers. null when the read failed or may be truncated. */
1434
1457
  function readAllIssuesForSwitches(repoAbs) {
1435
1458
  const LIMIT = 5000;
1436
1459
  // title/labels/createdAt/url are additive (#339): `release finalize` finds its tracking issue in the same read.
1437
- const r = tracker.forRepo(repoAbs).issueListAll({
1460
+ // #681: on a forge remote the list is read from the forge (a READ — the forge engine writes no issue).
1461
+ const r = (forgeCi(repoAbs) || tracker.forRepo(repoAbs)).issueListAll({
1438
1462
  limit: LIMIT, fields: ['number', 'state', 'stateReason', 'body', 'title', 'labels', 'createdAt', 'closedAt', 'url'],
1439
1463
  maxBuffer: 512 * 1024 * 1024,
1440
1464
  });
@@ -1486,7 +1510,8 @@ function releaseCutChanges(repoAbs, from, sha, declared) {
1486
1510
  */
1487
1511
  function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, issues: knownIssues, verifying }) {
1488
1512
  let ci; let suite; let switches; let issues = null;
1489
- if (!isGhUsable(repoAbs)) {
1513
+ // #681: a forge remote is read through its engine (readRuns and the issue list both), never gh.
1514
+ if (!forgeCi(repoAbs) && !isGhUsable(repoAbs)) {
1490
1515
  const why = ghUnusableWhy(repoAbs);
1491
1516
  ci = { ok: false, detail: `gh not usable (${why}) — cannot confirm CI at ${at}` };
1492
1517
  suite = { ok: false, detail: `gh not usable (${why}) — cannot confirm the suite ran at ${at}` };
@@ -1499,7 +1524,7 @@ function measureCandidateConditions(repoAbs, { sha, lastFinal, at, readRuns, iss
1499
1524
  const note = releaseCut.verifyingNote(read);
1500
1525
  const rows = releaseCut.withoutSkippedOnlyWorkflows(read.rows);
1501
1526
  const run = git.summarizeRunsForCommit(rows, sha);
1502
- if (!run) ci = { ok: false, detail: `gh run list failed — cannot confirm CI at ${at}` };
1527
+ if (!run) ci = { ok: false, detail: `${forgeCi(repoAbs) ? 'the forge\'s commit statuses could not be read' : 'gh run list failed'} — cannot confirm CI at ${at}` };
1503
1528
  else { const v = classifyCiRun(repoAbs, run, at); ci = { ok: v.ok, detail: v.detail + note }; }
1504
1529
  suite = releaseCut.fullSuiteVerdict(rows, at);
1505
1530
  if (note && rows) suite = { ...suite, detail: suite.detail + note };
@@ -1771,13 +1796,17 @@ function cmdReleaseCut(argv) {
1771
1796
  sha = r.stdout;
1772
1797
  }
1773
1798
  const at = `main@${shortSha(sha)}`;
1799
+ // #681: a Forgejo remote — CI from commit statuses, the release object through the forge's API.
1800
+ const forge = forgeCi(repoAbs);
1774
1801
 
1775
- const wf = git.git(['ls-tree', '--name-only', `${sha}:.github/workflows`], repoAbs);
1802
+ const wfDir = releaseWorkflowDir(repoAbs, sha, !!forge);
1803
+ const wf = git.git(['ls-tree', '--name-only', `${sha}:${wfDir}`], repoAbs);
1776
1804
  const workflows = wf.ok ? wf.stdout.split('\n').map((s) => s.trim()).filter((f) => /\.ya?ml$/.test(f)) : [];
1777
1805
  const triggers = workflowTriggers.prereleaseTagTriggers({
1778
1806
  readFile: (rel) => { const r = git.git(['show', `${sha}:${rel}`], repoAbs); return r.ok ? r.stdout : null; },
1779
1807
  workflows,
1780
1808
  deploy: doc.deploy === undefined || doc.deploy === null ? 'none' : String(doc.deploy),
1809
+ dir: wfDir,
1781
1810
  });
1782
1811
 
1783
1812
  // #617: every tag this cut reads is one the push remote holds — a fresh CI checkout sees only those,
@@ -1794,7 +1823,7 @@ function cmdReleaseCut(argv) {
1794
1823
  const tagsAtSha = lines(git.git(['tag', '--points-at', sha], repoAbs)).filter(onRemote);
1795
1824
 
1796
1825
  const { ci, suite, schema, switches, issues, migrations: migrationPathsSince, migrationLayout, migrationsNone, migrationsMissing } = measureCandidateConditions(repoAbs, {
1797
- sha, lastFinal, at, readRuns: () => releaseCut.withoutOwnWorkflow(git.ghRunsForCommit(repoAbs, 'main', sha)), // #425
1826
+ sha, lastFinal, at, readRuns: () => releaseCut.withoutOwnWorkflow(forge ? forge.ciRunsAt(sha) : git.ghRunsForCommit(repoAbs, 'main', sha)), // #425, #681
1798
1827
  verifying: verifyingPolicy(repoAbs), // #624: the ship gate's rule for which runs may veto
1799
1828
  });
1800
1829
  const { manifests, ancestry } = measurePreTag(repoAbs, sha, `${remote}/main`); // #424
@@ -1809,6 +1838,12 @@ function cmdReleaseCut(argv) {
1809
1838
  // #446: route deploy-tag-fast — the grant, the human veto, the migration gate and the spacing are
1810
1839
  // measured only there, so every candidate route's run is what it was.
1811
1840
  const fast = releaseCut.isFastRoute(policy) && !policy.findings.length;
1841
+ // #681: a final route's writes are tracker writes (tracking issue, "released in" announcements) and a
1842
+ // heavy-lane dispatch — none of which the handbook performs on a forge (#678). The candidate route
1843
+ // cuts there; a final route is refused before anything is written.
1844
+ if (forge && (fast || (releaseCut.isLibraryRoute(policy) && !policy.findings.length))) {
1845
+ throw new UserError(`release.route ${fast ? 'deploy-tag-fast' : 'library-fast'} tags a final that announces itself on the tracker, and on a ${forge.kind} remote (${forgeEngine(repoAbs).host}) the handbook writes no issue (#678). Drop \`release.route\` from .github/project.yml so the default route cuts candidates, then run \`colab release cut --auto\`; a final there is a human's \`COLAB_HUMAN=1 colab release finalize --tag <vX.Y.Z-rc.N> --answered-by <name>\` (#681)`);
1846
+ }
1812
1847
  const fastFacts = fast ? measureFastRoute(repoAbs, { policy, remote, issues, lastFinal, tags, auto, migrationPaths: migrationPathsSince, migrationLayout, migrationsNone, migrationsMissing, remoteTags }) : {};
1813
1848
  if (fast && auto) auto.spacing = fastFacts.spacing;
1814
1849
  // #590: route library-fast — a final with nothing deployed. The release-hold veto is its one extra
@@ -1950,7 +1985,7 @@ function cmdReleaseCut(argv) {
1950
1985
  else {
1951
1986
  print(`✓ tagged the final ${verdict.tag} on ${at} and pushed it to ${remote} — route library-fast: a library released per merge, nothing deploys from it.`);
1952
1987
  if (published && published.ok) print(`✓ ${published.detail}`);
1953
- else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --latest`);
1988
+ else if (published) warn(`${published.detail} — the tag stands; ${publishByHandHint(repoAbs, verdict.tag, { prerelease: false })}`);
1954
1989
  if (announced && announced.issues.length) print(`released in ${verdict.tag}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'}`);
1955
1990
  }
1956
1991
  } else if (verdict.final) {
@@ -1958,14 +1993,14 @@ function cmdReleaseCut(argv) {
1958
1993
  else {
1959
1994
  print(`✓ tagged the final ${verdict.tag} on ${at} and pushed it to ${remote} — route deploy-tag-fast, by the operator's grant (decision #${verdict.grant.issue}); the release workflow deploys it in this run.`);
1960
1995
  if (published && published.ok) print(`✓ ${published.detail}`);
1961
- else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --latest`);
1996
+ else if (published) warn(`${published.detail} — the tag stands; ${publishByHandHint(repoAbs, verdict.tag, { prerelease: false })}`);
1962
1997
  if (announced && announced.issues.length) print(`released in ${verdict.tag}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'}`);
1963
1998
  }
1964
1999
  } else if (opts.dry) print(`[--dry] would create ${verdict.tag} on ${at}, push it to ${remote}, publish its GitHub pre-release and move the next channel. Nothing created.`);
1965
2000
  else {
1966
2001
  print(`✓ cut ${verdict.tag} on ${at} and pushed it to ${remote} — a candidate, not a release; finalizing it is the release skill's.`);
1967
2002
  if (published && published.ok) print(`✓ ${published.detail}`);
1968
- else if (published) warn(`${published.detail} — the tag stands; publish it by hand: gh release create ${verdict.tag} --verify-tag --prerelease --latest=false`);
2003
+ else if (published) warn(`${published.detail} — the tag stands; ${publishByHandHint(repoAbs, verdict.tag, { prerelease: true })}`);
1969
2004
  }
1970
2005
  if (channel && channel.ok) print(`${opts.dry ? '·' : '✓'} ${channel.detail}`);
1971
2006
  else if (channel) warn(`${channel.detail} — the tag stands`);
@@ -1983,9 +2018,13 @@ function cmdReleaseCut(argv) {
1983
2018
  function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false }) {
1984
2019
  // #446: a deploy-tag-fast final is published as a full release, marked latest.
1985
2020
  const kind = final ? 'release' : 'pre-release';
1986
- if (!isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
1987
- const view = tracker.forRepo(repoAbs).releaseView(tag);
1988
- if (view.ok) return { ok: true, detail: `${tag} already has a GitHub Release — left as it is` };
2021
+ // #681: on a forge remote the release object is the forge's (`/releases`), written through its engine.
2022
+ const forge = forgeCi(repoAbs);
2023
+ if (!forge && !isGhUsable(repoAbs)) return { ok: false, detail: `${kind} NOT published: gh not usable (${ghUnusableWhy(repoAbs)})` };
2024
+ const host = forge || tracker.forRepo(repoAbs);
2025
+ const where = forge ? (forge.kind === 'forgejo' ? 'Forgejo' : forge.kind) : 'GitHub';
2026
+ const view = host.releaseView(tag);
2027
+ if (view.ok) return { ok: true, detail: `${tag} already has a ${where} Release — left as it is` };
1989
2028
  let notes;
1990
2029
  try {
1991
2030
  notes = lastFinal ? buildReleaseNotes(repoAbs, `${lastFinal}..${tag}`, lastFinal).out : `## ${tag}\n\nFirst release.\n`;
@@ -1996,9 +2035,9 @@ function publishPrerelease(repoAbs, { tag, lastFinal, message, final = false })
1996
2035
  const file = path.join(os.tmpdir(), `colab-release-notes-${process.pid}-${tag}.md`);
1997
2036
  fs.writeFileSync(file, notes);
1998
2037
  try {
1999
- const r = tracker.forRepo(repoAbs).releaseCreate(tag, { notesFile: file, final });
2000
- if (!r.ok) return { ok: false, detail: `${kind} NOT published: gh release create ${tag} failed (${(r.stderr || '').split('\n')[0] || r.code})` };
2001
- return { ok: true, detail: `published the GitHub ${kind} ${tag}` };
2038
+ const r = host.releaseCreate(tag, { notesFile: file, final });
2039
+ if (!r.ok) return { ok: false, detail: `${kind} NOT published: ${forge ? `POST /releases on ${forgeEngine(repoAbs).host} for` : 'gh release create'} ${tag} failed (${(r.stderr || '').split('\n')[0] || r.code})` };
2040
+ return { ok: true, detail: `published the ${where} ${kind} ${tag}` };
2002
2041
  } finally {
2003
2042
  try { fs.unlinkSync(file); } catch (_) { /* best-effort */ }
2004
2043
  }
@@ -2128,6 +2167,13 @@ Conditions (--json checks[].condition; required:false means reported, not blocki
2128
2167
  Needs origin and gh (the tracking issue, runs and edges live on GitHub). Never cuts a candidate, never
2129
2168
  a major, never removes a label or an edge. Exit 0 when finalized (or would be) or candidate-ready; 1
2130
2169
  otherwise.
2170
+
2171
+ On a Forgejo remote (#678, #681) a final is the human bar's alone: --auto, and any run without the
2172
+ bar except --dry, is refused — an automatic final leans on the tracking record, and the handbook
2173
+ writes no issue on a forge. Under the bar: CI from commit statuses, the trunk window from the
2174
+ statuses of every commit on main since the period started, no tracking issue opened (the period
2175
+ runs from the candidate's tag), no comment, close or "Released in" announcement — and the final's
2176
+ release object is published through the forge's /releases API (--json published).
2131
2177
  `;
2132
2178
 
2133
2179
  /** The tracking issue's blocked_by edges as [{number, state, closedAt}], or null when unread. */
@@ -2172,7 +2218,14 @@ function cmdReleaseFinalize(argv) {
2172
2218
  throw new UserError('--early finalizes before the test period elapses only as a human act: run it with COLAB_HUMAN=1, --tag <vX.Y.Z-rc.N> and --answered-by <your name>');
2173
2219
  }
2174
2220
  const repoAbs = resolveRepo(opts);
2175
- if (!isGhUsable(repoAbs)) throw new UserError(`gh not usable (${ghUnusableWhy(repoAbs)}) — the tracking issue, runs and regression edges live on GitHub`);
2221
+ // #681: on a forge remote a final is the human bar's alone. An automatic final (and --auto) leans on
2222
+ // the release tracking record — the test period's start, regression edges, a grant, the announcements
2223
+ // — and the handbook writes no issue on a forge (#678). A --dry read by hand is still allowed.
2224
+ const forge = forgeCi(repoAbs);
2225
+ if (forge && (opts.auto || (!humanBar && !opts.dry))) {
2226
+ throw new UserError(`on a ${forge.kind} remote (${forgeEngine(repoAbs).host}) a final is a human act: an automatic final needs the release tracking record, and the handbook writes no issue there (#678, #681). Run it as a human: COLAB_HUMAN=1 colab release finalize --tag <vX.Y.Z-rc.N> --answered-by <your name> (add --dry to see the checks first)`);
2227
+ }
2228
+ if (!forge && !isGhUsable(repoAbs)) throw new UserError(`gh not usable (${ghUnusableWhy(repoAbs)}) — the tracking issue, runs and regression edges live on GitHub`);
2176
2229
  const doc = projectDoc(repoAbs);
2177
2230
  const policy = releasePolicy.evaluateRelease(doc);
2178
2231
  const windowBranches = releaseFinalize.windowBranches(doc && doc.trunk); // #437
@@ -2220,6 +2273,8 @@ function cmdReleaseFinalize(argv) {
2220
2273
  if (open.length > 1) return { error: `${open.length} open tracking issues for ${version} (${open.map((r) => `#${r.number}`).join(', ')}) — one per version; close the duplicate by hand` };
2221
2274
  if (open.length === 1) return { ...open[0] };
2222
2275
  if (isCandidate && mine.length) return { error: `the tracking issue for ${version} (#${mine[0].number}${mine[0].title ? ` ${JSON.stringify(mine[0].title)}` : ''}) is closed but ${version} is not final — reopen it; a closed record is never silently replaced` };
2276
+ // #681: a forge keeps no tracking record — the period runs from the candidate's tag alone.
2277
+ if (forge) return { number: null, createdAt: null, held: false, wouldCreate: false, none: `a ${forge.kind} remote keeps no tracking record (the handbook writes no issue there, #678) — the test period starts at the candidate's tag` };
2223
2278
  return { number: null, createdAt: null, held: false, wouldCreate: !opts.dry };
2224
2279
  };
2225
2280
  const version0 = newest ? newest.version : (selection.version || null);
@@ -2227,7 +2282,7 @@ function cmdReleaseFinalize(argv) {
2227
2282
  if (version0) trackings.set(version0, trackingFor(version0, { isCandidate: !!newest }));
2228
2283
  let trackingCreated = false;
2229
2284
  const t0 = version0 ? trackings.get(version0) : null;
2230
- if (newest && t0 && !t0.error && !t0.number && !opts.dry) {
2285
+ if (newest && t0 && !t0.error && !t0.number && !t0.none && !opts.dry) {
2231
2286
  const body = releaseFinalize.trackingBody({ version: version0, row: policy.derived.row, final: policy.effective.final, testPeriodDays: policy.effective.testPeriodDays });
2232
2287
  const c = tracker.forRepo(repoAbs).issueCreate({ title: releaseFinalize.trackingTitle(version0), body });
2233
2288
  if (!c.number) trackings.set(version0, { error: `could not open the tracking issue for ${version0} (${String(c.stderr || '').split('\n')[0] || 'no issue URL returned'})` });
@@ -2240,7 +2295,7 @@ function cmdReleaseFinalize(argv) {
2240
2295
  const grantDecl = policy.effective.finalGrant;
2241
2296
  const trust = grantDecl ? trustAt(repoAbs, `${remote}/main`) : null;
2242
2297
  const finalGrant = grantDecl
2243
- ? releasePolicy.finalGrantVerdict(git.ghIssueView(repoAbs, grantDecl.issue, ['state', 'labels', 'comments']), { issue: grantDecl.issue, trust })
2298
+ ? releasePolicy.finalGrantVerdict(forge ? null : git.ghIssueView(repoAbs, grantDecl.issue, ['state', 'labels', 'comments']), { issue: grantDecl.issue, trust }) // #681: no grant record on a forge
2244
2299
  : undefined;
2245
2300
 
2246
2301
  // ---- judge one candidate: every condition at its commit, its own period, its own trunk window ----
@@ -2253,21 +2308,21 @@ function cmdReleaseFinalize(argv) {
2253
2308
  sha: cand.sha,
2254
2309
  lastFinal: releaseTag.latestReleaseTag(repoAbs, { ref: cand.sha, onlyTags: remoteTags }),
2255
2310
  at: `${cand.tag}@${shortSha(cand.sha)}`,
2256
- readRuns: () => { rawRows = git.ghRunsAtCommit(repoAbs, cand.sha); rows = releaseCut.withoutOwnWorkflow(rawRows); return rows; }, // #425
2311
+ readRuns: () => { rawRows = forge ? forge.ciRunsAt(cand.sha) : git.ghRunsAtCommit(repoAbs, cand.sha); rows = releaseCut.withoutOwnWorkflow(rawRows); return rows; }, // #425, #681
2257
2312
  issues,
2258
2313
  });
2259
2314
  // #566: only the run that CUT the candidate vouches for what it published — read from the rows
2260
2315
  // BEFORE the #425 own-workflow filter (the release workflow is the cutter), minus this run itself.
2261
2316
  const cutRunOpts = {
2262
2317
  tag: cand.tag, cutAt: cand.cutAt, ownRunId: process.env.GITHUB_ACTIONS === 'true' ? process.env.GITHUB_RUN_ID || null : null,
2263
- jobCount: (id) => git.ghRunJobCount(repoAbs, id),
2318
+ jobCount: forge ? null : (id) => git.ghRunJobCount(repoAbs, id), // #681: a commit status has no jobs to count
2264
2319
  };
2265
2320
  const cutRun = releaseFinalize.cutRunVerdict(rawRows, cutRunOpts);
2266
2321
  // #565: a run that failed only in its deploy jobs (staging) — the three run-reading conditions
2267
2322
  // re-read with it counted as passed. decide() uses that reading on a human final only, and names
2268
2323
  // the failure either way. Jobs are read lazily: only when a condition already failed.
2269
2324
  let deployReport = null;
2270
- if (Array.isArray(rawRows) && !(conditions.ci.ok && conditions.suite.ok && cutRun.ok)) {
2325
+ if (!forge && Array.isArray(rawRows) && !(conditions.ci.ok && conditions.suite.ok && cutRun.ok)) { // #681: no job read on a forge
2271
2326
  const d = releaseFinalize.deployOnlyFailures(rawRows, (id) => git.ghRunJobs(repoAbs, id));
2272
2327
  if (d.failures.length) {
2273
2328
  const at = `${cand.tag}@${shortSha(cand.sha)}`;
@@ -2281,18 +2336,18 @@ function cmdReleaseFinalize(argv) {
2281
2336
  const period = releaseFinalize.periodVerdict({ cutAt: cand.cutAt, trackingCreatedAt: tracking && tracking.createdAt, testPeriodDays: policy.effective.testPeriodDays, now });
2282
2337
  // #437: the window is main plus project.yml's trunk: when that is another branch (trunk: dev).
2283
2338
  const since = releaseFinalize.mergeWindowRuns(windowBranches.map((branch) => {
2284
- const raw = git.ghRunsSince(repoAbs, branch, period.start.slice(0, 10));
2339
+ const raw = forge ? forge.ciRunsSince(branch, period.start.slice(0, 10), { remote }) : git.ghRunsSince(repoAbs, branch, period.start.slice(0, 10)); // #681
2285
2340
  return { branch, read: raw ? { ...raw, runs: releaseCut.withoutOwnWorkflow(raw.runs) } : null }; // #425
2286
2341
  }));
2287
2342
  const trunk = releaseFinalize.trunkGreenVerdict(since ? since.runs : null, {
2288
2343
  periodStart: period.start, periodEnd: ownClock ? period.endsAt : null, suiteWorkflows, truncated: !!(since && since.truncated), branches: windowBranches,
2289
2344
  });
2290
- const regressions = releaseFinalize.regressionVerdict(tracking && tracking.number ? readRegressionEdges(repoAbs, tracking.number) : [], { periodStart: period.start });
2345
+ const regressions = releaseFinalize.regressionVerdict(tracking && tracking.number ? (forge ? forge.blockedBy(tracking.number) : readRegressionEdges(repoAbs, tracking.number)) : [], { periodStart: period.start }); // #681: a hand-made record's edges, read
2291
2346
  const { manifests, ancestry } = measurePreTag(repoAbs, cand.sha, `${remote}/main`); // #424
2292
2347
  let migrations;
2293
2348
  if (grantDecl) {
2294
2349
  // #441: a migration since the last final needs a grant on THIS version's tracking issue.
2295
- const rec = tracking && tracking.number ? git.ghIssueView(repoAbs, tracking.number, ['state', 'labels', 'comments']) : null;
2350
+ const rec = tracking && tracking.number && !forge ? git.ghIssueView(repoAbs, tracking.number, ['state', 'labels', 'comments']) : null; // #681
2296
2351
  const mg = tracking && tracking.number
2297
2352
  ? migrationGrant.evaluateIssue(rec, cand.version, tracking.number, labels.MIGRATION_GRANT_LABEL, { trust })
2298
2353
  : { ok: false, reason: 'no tracking issue yet to carry a grant' };
@@ -2350,20 +2405,26 @@ function cmdReleaseFinalize(argv) {
2350
2405
  // ---- writes ----
2351
2406
  let tagged = false;
2352
2407
  let channel = null; // #445: { channel, ok, action, detail } once `stable` was (or could not be) moved
2408
+ // #681: on a forge none of these write — the forge's tracker is the adopter's (#678).
2353
2409
  const comment = (num, fields, text) => {
2410
+ if (forge) return;
2354
2411
  const view = git.ghIssueView(repoAbs, num, ['comments']);
2355
2412
  if (view && releaseFinalize.hasEvent(view.comments, fields)) return;
2356
2413
  const r = git.ghIssueComment(repoAbs, num, `${releaseFinalize.eventMarker(fields)}\n${text}`);
2357
2414
  if (!r.ok) warn(`could not comment on #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2358
2415
  };
2359
2416
  const close = (num) => {
2417
+ if (forge) return;
2360
2418
  const r = tracker.forRepo(repoAbs).issueClose(num);
2361
2419
  if (!r.ok) warn(`could not close #${num}: ${String(r.stderr || '').split('\n')[0]}`);
2362
2420
  };
2363
2421
  // #426: one "Released in vX.Y.Z" comment on every issue the version carries (release-finalize.js
2364
2422
  // carriedIssues — the closing references in (previous final, sha]). Idempotent by event marker.
2365
2423
  let announced = null;
2366
- const announceRelease = (version, sha, early = null) => announceCarried(repoAbs, { tagNames, exclude: records.map((r) => r.number), version, sha, early });
2424
+ const announceRelease = (version, sha, early = null) => (forge
2425
+ ? { range: null, issues: [], posted: [], skipped: [], detail: `not announced: a ${forge.kind} remote's tracker is the adopter's (#678)` }
2426
+ : announceCarried(repoAbs, { tagNames, exclude: records.map((r) => r.number), version, sha, early }));
2427
+ let published = null; // #681: { ok, detail } — the final's release object, published by finalize on a forge
2367
2428
  if (!opts.dry) {
2368
2429
  if (verdict.state === 'finalized') {
2369
2430
  const actor = humanBar && !verdict.grant ? `${opts.answeredBy} (human bar: COLAB_HUMAN=1${verdict.early ? ', --early' : ''})` : `automatic — clean test period (CONVENTIONS.md §6)${verdict.grant ? `, by the operator's grant (decision #${verdict.grant.issue})` : ''}${walk ? ', newest candidate clean on its own clock (--auto)' : ''}${selection.older ? `, an older candidate clean on its own clock (--tag; newest open: ${selection.newest})` : ''}`;
@@ -2376,6 +2437,10 @@ function cmdReleaseFinalize(argv) {
2376
2437
  throw new UserError(`git push ${remote} ${cand.version} failed — the local tag was deleted again, nothing is final (${(push.stderr || '').split('\n')[0]})`);
2377
2438
  }
2378
2439
  tagged = true;
2440
+ // #681: on GitHub a workflow publishes the final's Release page (release-tag.yml / release-auto.yml);
2441
+ // a forge's final is a human's run of this command, so the command publishes it. Best-effort: the
2442
+ // tag already stands.
2443
+ if (forge) published = publishPrerelease(repoAbs, { tag: cand.version, lastFinal: releaseTag.latestReleaseTag(repoAbs, { ref: cand.sha, onlyTags: remoteTags }), message, final: true });
2379
2444
  }
2380
2445
  // #445: the `stable` channel names the newest final — moved by the run that tags it, and repaired
2381
2446
  // on the already-final resume (a run that died between the tag push and the move finishes it).
@@ -2441,6 +2506,7 @@ function cmdReleaseFinalize(argv) {
2441
2506
  periodStart: period ? period.start : null, periodEndsAt: period ? period.endsAt : null,
2442
2507
  state: verdict.state, tagged, finalTag: verdict.finalTag, checks: verdict.checks, handoff: verdict.handoff,
2443
2508
  skipped: walk ? skipped : undefined, why, next: why ? why.next : null, announced, grant: verdict.grant || null, early: verdict.early || null, channel,
2509
+ ...(forge ? { published } : {}),
2444
2510
  }, null, 2));
2445
2511
  } else {
2446
2512
  print(`colab release finalize${opts.auto ? ' --auto' : ''} — ${shortRepo(repoAbs)} (last final: ${lastFinal || 'none'}${cand ? `, candidate: ${cand.tag}` : ''})`);
@@ -2455,6 +2521,8 @@ function cmdReleaseFinalize(argv) {
2455
2521
  if (verdict.early) print(`early final: ${releaseFinalize.earlyLine(verdict.early)}`);
2456
2522
  if (why) print(`why no final: ${why.line}`);
2457
2523
  if (announced && announced.issues.length) print(`released in ${verdict.finalTag || version0}: told ${announced.posted.length ? announced.posted.map((n) => `#${n}`).join(', ') : 'nobody new'} (carried: ${announced.issues.map((n) => `#${n}`).join(', ')}${announced.skipped.length ? `; unreadable: ${announced.skipped.map((n) => `#${n}`).join(', ')}` : ''})`);
2524
+ if (published && published.ok) print(`✓ ${published.detail}`);
2525
+ else if (published) warn(`${published.detail} — the final tag stands; ${publishByHandHint(repoAbs, verdict.finalTag || cand.version, { prerelease: false })}`);
2458
2526
  if (channel && channel.ok) print(`✓ ${channel.detail}`);
2459
2527
  else if (channel) warn(`${channel.detail} — the final tag stands`);
2460
2528
  if (verdict.handoff) print(`\nThe final is a human act here. The one command, for a human to run:\n ${verdict.handoff}`);
@@ -16706,7 +16774,9 @@ function cmdCiWait(argv) {
16706
16774
  }
16707
16775
 
16708
16776
  const verifyPolicy = verifyingPolicy(repoAbs);
16709
- const poll = fc ? () => ciWait.forgePoll(fc.ciVerdict(opts.sha, { branch: opts.branch || null }), fc.kind) : (etag) => {
16777
+ // #681: inside a Forgejo Actions run (the release workflow waiting on CI at its own sha) the calling
16778
+ // workflow's own contexts are dropped — a run never waits on itself (#425's rule; a no-op elsewhere).
16779
+ const poll = fc ? () => ciWait.forgePoll(fc.ciVerdict(opts.sha, { branch: opts.branch || null, rowsFilter: (rows) => releaseCut.withoutOwnWorkflow(rows) }), fc.kind) : (etag) => {
16710
16780
  const r = git.ghApiConditional(repoAbs, apiPath, etag);
16711
16781
  if (r.kind !== 'ok') return r;
16712
16782
  let summary;
@@ -17705,10 +17775,13 @@ function cmdPromote(argv) {
17705
17775
  }
17706
17776
 
17707
17777
  let ciOk = false;
17708
- if (!gh) checks.push(['✗', 'trunk CI green', `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI`]);
17778
+ // #681: a forge remote's trunk CI is its commit statuses at origin's trunk tip — what would be promoted.
17779
+ const forge = forgeCi(repoAbs);
17780
+ if (!gh && !forge) checks.push(['✗', 'trunk CI green', `gh not usable (${ghUnusableWhy(repoAbs)}) — cannot confirm CI`]);
17709
17781
  else {
17710
- const run = git.ghRunForSha(repoAbs, trunk);
17711
- if (!run) checks.push(['✗', 'trunk CI green', 'gh run list failed']);
17782
+ const tipR = forge ? git.git(['rev-parse', '--verify', '--quiet', `refs/remotes/${remote}/${trunk}^{commit}`], repoAbs) : null;
17783
+ const run = forge ? (tipR.ok && tipR.stdout ? forge.ciVerdict(tipR.stdout.trim(), { branch: trunk }) : null) : git.ghRunForSha(repoAbs, trunk);
17784
+ if (!run) checks.push(['✗', 'trunk CI green', forge ? `the forge's commit statuses at ${remote}/${trunk} could not be read` : 'gh run list failed']);
17712
17785
  else if (run.status === 'completed' && run.conclusion === 'success') { ciOk = true; checks.push(['✓', 'trunk CI green', `run for ${trunk}@${shortSha(run.sha)}: success`]); }
17713
17786
  else checks.push(['✗', 'trunk CI green', `${trunk}@${shortSha(run.sha)}: status=${run.status} conclusion=${run.conclusion || 'none'} (fail-to-start counts as not green)`]);
17714
17787
  }
@@ -1,12 +1,21 @@
1
1
  'use strict';
2
2
  /**
3
- * tools/lib/ci-forgejo.js — the CI half of the tracker contract on a Forgejo (or Gitea) forge
4
- * (#678). The owner's ruling on #678 was "landing only": on a Forgejo remote the CLI reads CI so
5
- * `colab ship` can land code, and writes nothing to the forge's issue tracker (claims, readiness,
6
- * holds and close-with-evidence stay frozen per #604/#608 — the adopter's own tracker layer owns
7
- * them there). So this module implements `tracker.CI_METHODS` only: `ciVerdict`.
3
+ * tools/lib/ci-forgejo.js — the forge engine on a Forgejo (or Gitea) remote (#678, #681). The owner's
4
+ * ruling on #678 was "landing only": on a Forgejo remote the CLI reads CI so `colab ship` can land
5
+ * code, and writes nothing to the forge's issue tracker (claims, readiness, holds and
6
+ * close-with-evidence stay frozen per #604/#608 — the adopter's own tracker layer owns them there).
7
+ * #681 adds the release half: `colab release cut` / `release finalize` (human bar) / `promote` read CI
8
+ * here and publish the release object here. So this module implements `tracker.FORGE_METHODS`:
9
+ * ciVerdict — the CI verdict at a commit (below);
10
+ * issueListAll — a READ of every issue (switch markers, the release hold, an existing tracking
11
+ * record), in the GitHub adapter's shape; nothing here writes an issue;
12
+ * releaseView / releaseCreate — the release object for a tag (`/releases`).
13
+ * Plus three reads that are NOT contract (forge-shaped, like the GitHub adapter's raw run lists):
14
+ * `ciRunsAt` (the status rows at a commit), `ciRunsSince` (rows for every commit on a branch since a
15
+ * day — finalize's trunk window) and `blockedBy` (an issue's dependencies — a tracking record's
16
+ * regression edges).
8
17
  *
9
- * The read: the commit's COMBINED status, `GET {api}/repos/{owner}/{repo}/commits/{sha}/status`,
18
+ * The CI read: the commit's COMBINED status, `GET {api}/repos/{owner}/{repo}/commits/{sha}/status`,
10
19
  * which already holds the newest status per context. Each status becomes one row in the shape
11
20
  * tools/lib/git.js summarizes for GitHub runs (`context` is the workflow name), and the verdict is
12
21
  * `git.summarizeRunsForCommit` over those rows — the same all-quantifier rule, so a forge cannot
@@ -19,13 +28,21 @@
19
28
  * never as "none". `databaseId` is always null: a forge status has no run whose jobs `gh run view`
20
29
  * could list, so nothing downstream ever reaches for gh with it.
21
30
  *
31
+ * #681: a row also carries `event`, read from the context's trailing `(<event>)` — a Forgejo Actions
32
+ * context is `<workflow> / <job> (<event>)`. Additive: the ship verdict never filters on it; release
33
+ * cut's verifying-runs rule (tools/lib/verify-runs.js) does, so a dispatched or scheduled run at the
34
+ * sha (the release workflow itself) is set aside exactly as on GitHub. Gotcha: a combined status
35
+ * keeps only the NEWEST status per context, so a finished row's `createdAt` is when it finished —
36
+ * there is no start time to read. finalize's cut-run check (#566) therefore finds no run "in
37
+ * progress at the cut" on a forge and reports the candidate as cut by hand; that is the honest read.
38
+ *
22
39
  * The token: read from the environment variable the engine map names (default FORGEJO_TOKEN),
23
40
  * inside the child process that makes the request — never on an argument list, never logged. No
24
- * token is not an error: a public repo's statuses read anonymously; a private one answers 404/401,
25
- * which is null.
41
+ * token is not an error for a read: a public repo's statuses read anonymously; a private one answers
42
+ * 404/401, which is null. A write without a token answers 401/403, which is ok:false.
26
43
  *
27
44
  * Synchronous like the rest of the CLI: the request runs in a child `node` (global fetch, Node >= 18)
28
- * through spawnSync. `withFetcher` is the test seam.
45
+ * through spawnSync; a request body travels on the child's stdin. `withFetcher` is the test seam.
29
46
  */
30
47
 
31
48
  const { spawnSync } = require('child_process');
@@ -36,31 +53,45 @@ const TIMEOUT_MS = 30000;
36
53
 
37
54
  let _fetcher = null; // test seam only — see withFetcher
38
55
 
39
- // The child: GET argv[1] with the token from the env var COLAB_FORGE_TOKEN_ENV names; print
40
- // {status, body} as JSON on stdout. Network failures print {status: 0, error}.
56
+ // The child: send argv[2] (a method) to argv[1] with the token from the env var COLAB_FORGE_TOKEN_ENV
57
+ // names, and stdin as a JSON body when there is one; print {status, body} as JSON on stdout. Network
58
+ // failures print {status: 0, error}.
41
59
  const CHILD = `
42
- const [url] = process.argv.slice(1);
60
+ const [url, method] = process.argv.slice(1);
43
61
  const name = process.env.COLAB_FORGE_TOKEN_ENV;
44
62
  const token = name ? process.env[name] : '';
45
63
  const headers = { accept: 'application/json' };
46
64
  if (token) headers.authorization = 'token ' + token;
47
- fetch(url, { headers, signal: AbortSignal.timeout(${TIMEOUT_MS - 2000}) })
65
+ let input = '';
66
+ try { input = require('fs').readFileSync(0, 'utf8'); } catch (_) { input = ''; }
67
+ const init = { method: method || 'GET', headers, signal: AbortSignal.timeout(${TIMEOUT_MS - 2000}) };
68
+ if (input) { headers['content-type'] = 'application/json'; init.body = input; }
69
+ fetch(url, init)
48
70
  .then(async (r) => process.stdout.write(JSON.stringify({ status: r.status, body: await r.text() })))
49
71
  .catch((e) => process.stdout.write(JSON.stringify({ status: 0, error: String(e && e.message || e) })));
50
72
  `;
51
73
 
52
- /** GET `url` → `{ status, body }` (status 0 = the request never completed). Never throws. */
53
- function httpGet(url, tokenEnv) {
54
- if (_fetcher) return _fetcher(url, { tokenEnv });
55
- const r = spawnSync(process.execPath, ['-e', CHILD, url], {
56
- encoding: 'utf8', timeout: TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024,
74
+ /**
75
+ * `method` `url` (JSON `body` when given) → `{ status, body }` (status 0 = the request never
76
+ * completed). Never throws. The fetcher seam sees `(url, { tokenEnv, method, body })`.
77
+ */
78
+ function httpRequest(method, url, tokenEnv, body = null) {
79
+ const payload = body === null || body === undefined ? '' : JSON.stringify(body);
80
+ if (_fetcher) return _fetcher(url, { tokenEnv, method, ...(payload ? { body: payload } : {}) });
81
+ const r = spawnSync(process.execPath, ['-e', CHILD, url, method], {
82
+ encoding: 'utf8', timeout: TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, input: payload,
57
83
  env: { ...process.env, COLAB_FORGE_TOKEN_ENV: tokenEnv || '' },
58
84
  });
59
85
  if (r.error || r.status !== 0) return { status: 0, body: '' };
60
86
  try { const o = JSON.parse(r.stdout || '{}'); return { status: Number(o.status) || 0, body: o.body || '' }; } catch (_) { return { status: 0, body: '' }; }
61
87
  }
62
88
 
63
- /** Run `fn` with every HTTP read answered by `fetcher(url, { tokenEnv })` → `{status, body}`. */
89
+ /** GET `url` → `{ status, body }`. Never throws. */
90
+ function httpGet(url, tokenEnv) {
91
+ return httpRequest('GET', url, tokenEnv);
92
+ }
93
+
94
+ /** Run `fn` with every HTTP request answered by `fetcher(url, { tokenEnv, method, body })` → `{status, body}`. */
64
95
  function withFetcher(fetcher, fn) {
65
96
  const prev = _fetcher;
66
97
  _fetcher = fetcher;
@@ -71,14 +102,17 @@ function withFetcher(fetcher, fn) {
71
102
  function statusRow(sha, st) {
72
103
  const state = String((st && st.status) || (st && st.state) || '').toLowerCase();
73
104
  const done = state !== 'pending' && state !== '';
105
+ const ev = /\(([a-z_]+)\)\s*$/.exec(String((st && st.context) || ''));
74
106
  return {
75
107
  headSha: sha,
76
108
  workflowName: (st && st.context) || null,
77
109
  status: done ? 'completed' : 'in_progress',
78
110
  conclusion: done ? state : '',
79
111
  createdAt: (st && (st.updated_at || st.created_at)) || null,
112
+ updatedAt: (st && (st.updated_at || st.created_at)) || null,
80
113
  databaseId: null,
81
114
  url: (st && st.target_url) || null,
115
+ ...(ev ? { event: ev[1] } : {}), // #681: `<workflow> / <job> (<event>)`
82
116
  };
83
117
  }
84
118
 
@@ -92,8 +126,55 @@ function rowsFromPages(sha, pages) {
92
126
  return rows;
93
127
  }
94
128
 
129
+ /** One issue from Forgejo's issue API → the GitHub adapter's issue shape (`gh issue list --json`). Pure. */
130
+ function issueShape(i) {
131
+ return {
132
+ number: i.number,
133
+ title: i.title == null ? null : String(i.title),
134
+ body: i.body == null ? '' : String(i.body),
135
+ state: String(i.state || '').toLowerCase() === 'closed' ? 'CLOSED' : 'OPEN',
136
+ stateReason: null, // Forgejo records no close reason
137
+ labels: Array.isArray(i.labels) ? i.labels.map((l) => ({ name: typeof l === 'string' ? l : (l && l.name) })) : [],
138
+ assignees: Array.isArray(i.assignees) ? i.assignees.map((u) => ({ login: u && u.login })) : [],
139
+ createdAt: i.created_at || null,
140
+ closedAt: i.closed_at || null,
141
+ url: i.html_url || null,
142
+ };
143
+ }
144
+
145
+ function pick(o, fields) {
146
+ if (!Array.isArray(fields) || !fields.length) return o;
147
+ const out = {};
148
+ for (const f of fields) if (Object.prototype.hasOwnProperty.call(o, f)) out[f] = o[f];
149
+ return out;
150
+ }
151
+
152
+ const result = (ok, extra = {}) => ({ ok, code: ok ? 0 : 1, stdout: '', stderr: '', ...extra });
153
+
95
154
  function create(repoAbs, eng) {
96
155
  const base = `${eng.api}/repos/${encodeURIComponent(eng.owner)}/${encodeURIComponent(eng.repo)}`;
156
+ const fullOf = (sha) => (/^[0-9a-f]{40}$/i.test(String(sha || '')) ? String(sha).toLowerCase() : require('./git').fullSha(repoAbs, sha));
157
+
158
+ /** The status rows at a full sha, or null when any page failed. */
159
+ const rowsAt = (full) => {
160
+ const pages = [];
161
+ let seen = 0;
162
+ for (let page = 1; page <= MAX_PAGES; page++) {
163
+ const r = httpGet(`${base}/commits/${full}/status?page=${page}&limit=${PAGE_LIMIT}`, eng.tokenEnv);
164
+ if (r.status !== 200) return null;
165
+ let j;
166
+ try { j = JSON.parse(r.body); } catch (_) { return null; }
167
+ if (!j || typeof j !== 'object') return null;
168
+ pages.push(j);
169
+ const n = Array.isArray(j.statuses) ? j.statuses.length : 0;
170
+ seen += n;
171
+ const total = Number(j.total_count);
172
+ if (n < PAGE_LIMIT || (Number.isFinite(total) && seen >= total)) break;
173
+ if (page === MAX_PAGES) return null; // more statuses than we read: never a partial verdict
174
+ }
175
+ return rowsFromPages(full, pages);
176
+ };
177
+
97
178
  return {
98
179
  kind: 'forgejo',
99
180
  repo: repoAbs,
@@ -101,33 +182,102 @@ function create(repoAbs, eng) {
101
182
 
102
183
  /**
103
184
  * The CI verdict at `sha` (tracker contract, #678). `branch` is accepted and ignored: a commit
104
- * status belongs to the commit, whatever ref carries it.
185
+ * status belongs to the commit, whatever ref carries it. `rowsFilter` (#681) narrows the rows
186
+ * before the verdict — ci-wait inside the release workflow drops that workflow's own contexts.
105
187
  */
106
- ciVerdict: (sha) => {
107
- const full = /^[0-9a-f]{40}$/i.test(String(sha || '')) ? String(sha).toLowerCase() : require('./git').fullSha(repoAbs, sha);
188
+ ciVerdict: (sha, { rowsFilter = null } = {}) => {
189
+ const full = fullOf(sha);
108
190
  if (!full) return null;
109
- const pages = [];
110
- let seen = 0;
111
- for (let page = 1; page <= MAX_PAGES; page++) {
112
- const r = httpGet(`${base}/commits/${full}/status?page=${page}&limit=${PAGE_LIMIT}`, eng.tokenEnv);
113
- if (r.status !== 200) return null;
114
- let j;
115
- try { j = JSON.parse(r.body); } catch (_) { return null; }
116
- if (!j || typeof j !== 'object') return null;
117
- pages.push(j);
118
- const n = Array.isArray(j.statuses) ? j.statuses.length : 0;
119
- seen += n;
120
- const total = Number(j.total_count);
121
- if (n < PAGE_LIMIT || (Number.isFinite(total) && seen >= total)) break;
122
- if (page === MAX_PAGES) return null; // more statuses than we read: never a partial verdict
123
- }
124
- const rows = rowsFromPages(full, pages);
191
+ let rows = rowsAt(full);
125
192
  if (rows === null) return null;
193
+ if (typeof rowsFilter === 'function') rows = rowsFilter(rows);
126
194
  const summary = require('./git').summarizeRunsForCommit(rows, full);
127
195
  // #682: additive — the contexts that keep this sha from green, so a refusal can name them.
128
196
  const ng = notGreen(rows);
129
197
  return ng.length ? { ...summary, notGreen: ng } : summary;
130
198
  },
199
+
200
+ /** #681, not contract: the status rows at `sha` (statusRow's shape), or null when the read failed. */
201
+ ciRunsAt: (sha) => {
202
+ const full = fullOf(sha);
203
+ return full ? rowsAt(full) : null;
204
+ },
205
+
206
+ /**
207
+ * #681, not contract: the rows of every commit on `<remote>/<branch>` committed on or after
208
+ * `sinceDay` (YYYY-MM-DD) — `git.ghRunsSince`'s `{ runs, truncated }`, each row carrying `branch`.
209
+ * The commits come from git (the caller fetched); a forge has no run list to filter by date. null
210
+ * when git or any status read failed. `truncated` when more than `limit` commits fall in the window.
211
+ */
212
+ ciRunsSince: (branch, sinceDay, { remote = null, limit = 100 } = {}) => {
213
+ const g = require('./git');
214
+ const rem = remote || g.remoteFor(repoAbs);
215
+ const log = g.git(['log', `--since=${sinceDay}T00:00:00Z`, '--format=%H', `refs/remotes/${rem}/${branch}`], repoAbs);
216
+ if (!log.ok) return null;
217
+ const shas = log.stdout.split('\n').map((x) => x.trim()).filter(Boolean);
218
+ const runs = [];
219
+ for (const sha of shas.slice(0, limit)) {
220
+ const rows = rowsAt(sha.toLowerCase());
221
+ if (rows === null) return null;
222
+ for (const r of rows) runs.push({ ...r, branch });
223
+ }
224
+ return { runs, truncated: shas.length > limit };
225
+ },
226
+
227
+ /**
228
+ * Every issue, open and closed, newest first (tracker contract). Pull requests are not issues here:
229
+ * `type=issues`. `data` null when any page failed — never a partial list read as complete.
230
+ */
231
+ issueListAll: ({ limit = 1000, fields = null } = {}) => {
232
+ const out = [];
233
+ const max = Math.max(1, Math.ceil(limit / PAGE_LIMIT));
234
+ for (let page = 1; page <= max && out.length < limit; page++) {
235
+ const r = httpGet(`${base}/issues?state=all&type=issues&page=${page}&limit=${PAGE_LIMIT}`, eng.tokenEnv);
236
+ if (r.status !== 200) return result(false, { stderr: `GET issues page ${page}: HTTP ${r.status || 'no reply'}`, data: null });
237
+ let j;
238
+ try { j = JSON.parse(r.body); } catch (_) { return result(false, { stderr: `GET issues page ${page}: not JSON`, data: null }); }
239
+ if (!Array.isArray(j)) return result(false, { stderr: `GET issues page ${page}: not a list`, data: null });
240
+ for (const i of j) if (i && !i.pull_request) out.push(issueShape(i));
241
+ if (j.length < PAGE_LIMIT) break;
242
+ }
243
+ out.sort((x, y) => y.number - x.number);
244
+ return result(true, { data: out.slice(0, limit).map((i) => pick(i, fields)) });
245
+ },
246
+
247
+ /** #681, not contract: the issues blocking issue `num` — `[{ number, state, closedAt }]`, null when unread. */
248
+ blockedBy: (num) => {
249
+ const r = httpGet(`${base}/issues/${Number(num)}/dependencies?limit=${PAGE_LIMIT}`, eng.tokenEnv);
250
+ if (r.status !== 200) return null;
251
+ try {
252
+ const list = JSON.parse(r.body);
253
+ if (!Array.isArray(list)) return null;
254
+ return list.map((i) => ({ number: i.number, state: String(i.state || '').toLowerCase(), closedAt: i.closed_at || null }));
255
+ } catch (_) { return null; }
256
+ },
257
+
258
+ /** The release for `tag` (tracker contract): ok when it exists, ok:false (data) when not or unread. */
259
+ releaseView: (tag) => {
260
+ const r = httpGet(`${base}/releases/tags/${encodeURIComponent(tag)}`, eng.tokenEnv);
261
+ if (r.status === 200) return result(true, { stdout: JSON.stringify({ tagName: tag }) });
262
+ return result(false, { code: r.status || 1, stderr: r.status === 404 ? 'release not found' : `HTTP ${r.status || 'no reply'}` });
263
+ },
264
+
265
+ /**
266
+ * Publish the release for an EXISTING tag (tracker contract): a pre-release unless `final`. The
267
+ * notes are the file's text. A tag that already has a release answers 409 — ok:false, as data.
268
+ */
269
+ releaseCreate: (tag, { notesFile = null, final = false } = {}) => {
270
+ let notes = '';
271
+ if (notesFile) { try { notes = require('fs').readFileSync(notesFile, 'utf8'); } catch (_) { notes = ''; } }
272
+ const r = httpRequest('POST', `${base}/releases`, eng.tokenEnv, { tag_name: tag, name: tag, body: notes, draft: false, prerelease: !final });
273
+ if (r.status === 200 || r.status === 201) {
274
+ let url = '';
275
+ try { url = (JSON.parse(r.body) || {}).html_url || ''; } catch (_) { url = ''; }
276
+ return result(true, { stdout: url || `${String(eng.api).replace(/\/api\/v1$/, '')}/${eng.owner}/${eng.repo}/releases/tag/${tag}` });
277
+ }
278
+ const why = r.status === 409 ? `a release with tag ${tag} already exists` : r.status === 401 || r.status === 403 ? `HTTP ${r.status} — the token in ${eng.tokenEnv} cannot write releases` : `HTTP ${r.status || 'no reply'}`;
279
+ return result(false, { code: r.status || 1, stderr: why });
280
+ },
131
281
  };
132
282
  }
133
283
 
@@ -140,4 +290,4 @@ function notGreen(rows) {
140
290
  .map((x) => ({ name: x.workflowName || 'unnamed', status: x.status, conclusion: x.conclusion || null }));
141
291
  }
142
292
 
143
- module.exports = { create, withFetcher, statusRow, rowsFromPages, notGreen, PAGE_LIMIT };
293
+ module.exports = { create, withFetcher, statusRow, rowsFromPages, notGreen, issueShape, PAGE_LIMIT };
@@ -781,7 +781,26 @@ function withoutOwnWorkflow(rows, env = process.env) {
781
781
  if (!Array.isArray(rows)) return rows;
782
782
  const own = env && env.GITHUB_ACTIONS === 'true' ? String(env.GITHUB_WORKFLOW || '') : '';
783
783
  if (!own) return rows;
784
- return rows.filter((r) => (r && r.workflowName) !== own);
784
+ const prefixes = forgeOwnPrefixes(own, env);
785
+ return rows.filter((r) => {
786
+ const name = (r && r.workflowName) || '';
787
+ return name !== own && !prefixes.some((p) => name.startsWith(p));
788
+ });
789
+ }
790
+
791
+ /**
792
+ * #681: inside Forgejo (or Gitea) Actions a row is a commit status whose name is the context
793
+ * `<workflow> / <job> (<event>)`, not the workflow's name — so the exact match above never fires
794
+ * there. Forgejo also sets `github.workflow` (GITHUB_WORKFLOW) to the workflow FILE's path, while the
795
+ * context carries the workflow's `name:` (the file's base name when it has none). Both spellings are
796
+ * matched as a `<x> / ` prefix: the full value and its base name without `.yml`/`.yaml`. Keep the
797
+ * release workflow's `name:` equal to its file's base name (templates/forgejo-release-auto.yml does).
798
+ * Empty off a Forgejo runner — GitHub rows keep the exact rule.
799
+ */
800
+ function forgeOwnPrefixes(own, env) {
801
+ if (!(env && (env.FORGEJO_ACTIONS === 'true' || env.GITEA_ACTIONS === 'true'))) return [];
802
+ const base = own.replace(/^.*\//, '').replace(/\.ya?ml$/i, '');
803
+ return [...new Set([own, base].filter(Boolean))].map((x) => `${x} / `);
785
804
  }
786
805
 
787
806
  // ---- §6 condition 3: schema changes are additive -----------------------------------------------
@@ -622,7 +622,8 @@ function handoffCommand(tag) {
622
622
  * policy release-policy.js evaluateRelease(doc)
623
623
  * selection selectCandidate(...)
624
624
  * tracking { number|null, title|null, createdAt|null, held, wouldCreate } | { error } — `title` is the
625
- * matched issue's own, shown so a record that is not `release: vX.Y.Z` is visible (#575)
625
+ * matched issue's own, shown so a record that is not `release: vX.Y.Z` is visible (#575);
626
+ * `none: '<why>'` (#681) names why no record is opened at all (a forge remote)
626
627
  * supersededHeld [issue numbers]
627
628
  * period periodVerdict(...) (when there is a candidate)
628
629
  * trunk trunkGreenVerdict(...)
@@ -675,7 +676,8 @@ function decide(facts) {
675
676
 
676
677
  const t = f.tracking || {};
677
678
  if (t.error) { add('tracking-issue', false, t.error); return out('refused'); }
678
- add('tracking-issue', true, t.number ? `#${t.number} (${t.title ? JSON.stringify(t.title) : trackingTitle(cand.version)})` : `none yet — ${t.wouldCreate ? 'this run opens' : 'a non-dry run opens'} "${trackingTitle(cand.version)}"`);
679
+ // #681: `none` — a remote where no run opens a tracking record (a forge: the adopter's tracker).
680
+ add('tracking-issue', true, t.number ? `#${t.number} (${t.title ? JSON.stringify(t.title) : trackingTitle(cand.version)})` : t.none ? `none — ${t.none}` : `none yet — ${t.wouldCreate ? 'this run opens' : 'a non-dry run opens'} "${trackingTitle(cand.version)}"`);
679
681
 
680
682
  const held = [...(t.held && t.number ? [t.number] : []), ...(f.supersededHeld || [])];
681
683
  add('release-hold', !held.length, held.length
@@ -188,6 +188,29 @@
188
188
  { "call": "releaseCreate", "args": ["v1.1.0-rc.1", { "notesFile": "notes.md" }], "expect": { "ok": false } }
189
189
  ]
190
190
  },
191
+ {
192
+ "id": "issue-list-all",
193
+ "description": "issueListAll alone — the one issue READ a forge engine implements (#681): every issue, open and closed, newest first, with the requested fields, labels as objects.",
194
+ "given": {
195
+ "login": "alice",
196
+ "issues": [
197
+ { "number": 3, "title": "release: v1.2.0", "body": "<!-- colab:release v1.2.0 -->", "state": "OPEN", "labels": ["release-hold"] },
198
+ { "number": 4, "title": "closed one", "body": "done", "state": "CLOSED", "stateReason": "COMPLETED" }
199
+ ]
200
+ },
201
+ "steps": [
202
+ { "call": "issueListAll", "args": [{ "limit": 100, "fields": ["number", "state", "body", "labels"] }],
203
+ "expect": { "ok": true, "data": [{ "number": 4, "state": "CLOSED", "body": "done", "labels": [] }, { "number": 3, "state": "OPEN", "body": "<!-- colab:release v1.2.0 -->", "labels": [{ "name": "release-hold" }] }] } }
204
+ ]
205
+ },
206
+ {
207
+ "id": "issue-list-all-unreadable",
208
+ "description": "issueListAll on an unreachable tracker: ok false and data null — could not read, never an empty list a caller would take for no issues.",
209
+ "given": { "login": "alice", "offline": true, "issues": [{ "number": 1, "title": "exists, unreachable", "state": "OPEN" }] },
210
+ "steps": [
211
+ { "call": "issueListAll", "args": [{ "limit": 100, "fields": ["number"] }], "expect": { "ok": false, "data": null } }
212
+ ]
213
+ },
191
214
  {
192
215
  "id": "offline",
193
216
  "description": "An unreachable tracker never throws: every read is `could not read` (null, data: null, or an error), every write is ok:false — and none of them is mistaken for `none`.",
@@ -19,8 +19,10 @@
19
19
  * `{ status, conclusion, sha, createdAt, databaseId, runCount, … }` (tools/lib/git.js
20
20
  * `summarizeRunsForCommit`'s shape, the one ship's CI rows and the docs-only row already read), or
21
21
  * null when the read failed. `status: 'none'` is "no run at this sha", never "could not read". A
22
- * forge that only lands code (no issue tracker the CLI writes to) implements just `CI_METHODS`:
23
- * tools/lib/ci-forgejo.js, Forgejo commit statuses. Which engine a repo gets is `engineFor` below.
22
+ * forge the CLI lands code on and releases on, but never writes issues to, implements
23
+ * `FORGE_METHODS` (#681): the CI verdict, a READ of the issue list, and the release object —
24
+ * tools/lib/ci-forgejo.js, Forgejo commit statuses and `/releases`. `CI_METHODS` stays the subset
25
+ * the landing path (#678) needs. Which engine a repo gets is `engineFor` below.
24
26
  *
25
27
  * Deliberately NOT in the contract yet (#501 left it so: no scenario needs them, and each would
26
28
  * pin a GitHub-only shape into a spec other trackers must satisfy): the raw CI-run lists and REST
@@ -50,9 +52,16 @@ const METHODS = Object.freeze([
50
52
  { name: 'releaseCreate', kind: 'write', returns: 'result' },
51
53
  ].map(Object.freeze));
52
54
 
53
- /** The methods a CI-only engine implements (#678): a forge the CLI lands code on but never writes issues to. */
55
+ /** The methods the landing path reads on a forge (#678): the CI verdict alone. */
54
56
  const CI_METHODS = Object.freeze(['ciVerdict']);
55
57
 
58
+ /**
59
+ * The methods a forge engine implements (#681): landing (`CI_METHODS`) plus what a release needs —
60
+ * the issue list READ (switch markers, the release hold, an existing tracking record) and the release
61
+ * object. No issue write is here on purpose: #678's ruling keeps the forge's tracker the adopter's.
62
+ */
63
+ const FORGE_METHODS = Object.freeze([...CI_METHODS, 'issueListAll', 'releaseView', 'releaseCreate']);
64
+
56
65
  /**
57
66
  * Throw, naming every contract method `impl` lacks. Returns `impl` when it is complete.
58
67
  * `names` narrows the check to a subset (CI_METHODS for a CI-only engine); default: the whole contract.
@@ -156,20 +165,20 @@ function engineFor(repoAbs, { configFile = null } = {}) {
156
165
  const CI_KINDS = { forgejo: () => require('./ci-forgejo') };
157
166
 
158
167
  /**
159
- * The CI reader for one repo, or null when its engine is GitHub — the caller keeps its existing,
168
+ * The forge engine for one repo, or null when its engine is GitHub — the caller keeps its existing,
160
169
  * gh-based reads there, which `ciVerdict` on the GitHub tracker wraps one-for-one. Non-null only
161
- * for an engine the map names (#678).
170
+ * for an engine the map names (#678); it implements FORGE_METHODS (#681).
162
171
  */
163
172
  function ciFor(repoAbs, opts = {}) {
164
173
  const eng = engineFor(repoAbs, opts);
165
174
  const load = CI_KINDS[eng.engine];
166
175
  if (!load) return null;
167
176
  const impl = load().create(repoAbs, eng);
168
- if (!_checked.has(`ci:${eng.engine}`)) { assertImplements(impl, `CI engine "${eng.engine}"`, CI_METHODS); _checked.add(`ci:${eng.engine}`); }
177
+ if (!_checked.has(`ci:${eng.engine}`)) { assertImplements(impl, `forge engine "${eng.engine}"`, FORGE_METHODS); _checked.add(`ci:${eng.engine}`); }
169
178
  return impl;
170
179
  }
171
180
 
172
181
  module.exports = {
173
- METHODS, CI_METHODS, ENGINES, assertImplements, forRepo,
182
+ METHODS, CI_METHODS, FORGE_METHODS, ENGINES, assertImplements, forRepo,
174
183
  parseRemoteUrl, engineFromConfig, engineFor, ciFor, _resetEngineCache,
175
184
  };
@@ -236,11 +236,12 @@ function isReleaseTagTemplateCopy(file, text) {
236
236
  * `readFile(relPath)` returns a workflow's text (or null); `workflows` are file names under
237
237
  * .github/workflows/; `deploy` is project.yml's value. Returns [{ workflow, trigger, level, text }].
238
238
  */
239
- function prereleaseTagTriggers({ readFile, workflows, deploy }) {
239
+ function prereleaseTagTriggers({ readFile, workflows, deploy, dir = ".github/workflows" }) {
240
+ // #681: `dir` — a Forgejo remote runs `.forgejo/workflows` when the repo has it.
240
241
  const isTagDeploy = deploy === "tag";
241
242
  const out = [];
242
243
  for (const wf of workflows || []) {
243
- const text = readFile(`.github/workflows/${wf}`);
244
+ const text = readFile(`${dir}/${wf}`);
244
245
  if (isReleaseTagTemplateCopy(wf, text)) continue;
245
246
  const on = parseWorkflowOn(text);
246
247
  const inScope = isDeployWorkflow(wf) || (isTagDeploy && (on.pushTags !== null || on.pushTagsIgnore !== null));
@@ -255,7 +256,7 @@ function prereleaseTagTriggers({ readFile, workflows, deploy }) {
255
256
  trigger,
256
257
  level: isTagDeploy ? "fail" : "warn",
257
258
  text:
258
- `.github/workflows/${wf}: ${trigger} matches the pre-release tag ${PRERELEASE_TAG_PROBE} — ` +
259
+ `${dir}/${wf}: ${trigger} matches the pre-release tag ${PRERELEASE_TAG_PROBE} — ` +
259
260
  "GitHub's tag glob `*` matches `-`, so a release-candidate tag " +
260
261
  (isTagDeploy ? "would deploy to production" : "would run this deploy") +
261
262
  `. Fix: add "!v*.*.*-*" after the pattern, or use a strict pattern that cannot match "-" ` +