@git.zone/cli 7.2.6 → 7.2.7

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
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@git.zone/cli",
3
3
  "private": false,
4
- "version": "7.2.6",
4
+ "version": "7.2.7",
5
5
  "description": "A comprehensive CLI tool for enhancing and managing local development workflows with gitzone utilities, focusing on project setup, version control, code formatting, and template management.",
6
6
  "main": "dist_ts/index.js",
7
7
  "typings": "dist_ts/index.d.ts",
package/readme.md CHANGED
@@ -192,7 +192,7 @@ The release core is not configurable plumbing. It always follows the same profes
192
192
  4. With `--merge`, fast-forward and lease-push `main` before release metadata is created.
193
193
  5. Update version files and baked commit info.
194
194
  6. Move pending changelog entries into the new version section.
195
- 7. Create the local release commit and tag on `main`.
195
+ 7. Create the local release commit and tag on `main`, and record the release intent, so any later failure is resumable (see [Resuming a release that failed before its journal](#resuming-a-release-that-failed-before-its-journal)).
196
196
  8. Create a disposable detached checkout of that release commit, install its locked dependencies when the commit carries a `package.json`, and run the configured release build there. An active Docker target additionally builds the release worktree its qualification reads.
197
197
  9. When npm is selected, prepare every named tspublish module outside the repository, then pack each module and the public root package once into an exact tarball from that checkout.
198
198
  10. Atomically install a durable journal before final publication. A release that publishes only the root package to npm uses journal schema 1, one that also or only publishes tspublish modules uses schema 3, a Docker release uses schema 2 with or without modules, and a Gitea asset release uses schema 4, all in the same storage tree.
@@ -252,16 +252,16 @@ Consequences worth knowing before upgrading:
252
252
  - An install that fails in the checkout for an environmental reason — an
253
253
  unreachable registry, a missing credential, an unusable store — stops the
254
254
  release with the local release commit and tag created, nothing pushed, and no
255
- release journal written. Fix the environment, then: a release with a Git
256
- target plus an npm and/or Docker target continues with `gitzone release
257
- recover <version>`, which prepares and publishes that exact tagged commit
258
- without moving any ref. Other configurations — Gitea-asset releases and
259
- single-target releases — have no recovery path,
260
- because nothing was published: delete the tag and drop the release commit
261
- (`git tag -d v<version>` and `git reset --hard HEAD^` on `main`), then release
262
- again. Confirm first that `HEAD` is the release commit — `git log -1
263
- --format=%s` prints `v<version>` — so that a commit made on top of it is never
264
- dropped.
255
+ release journal written. The release recorded its intent, so fix the
256
+ environment and run `gitzone release resume <version> -y`: it prepares and
257
+ publishes that exact tagged commit without moving any ref. A tag created by
258
+ GitZone 7.2.6 or earlier has no recorded intent; a release with a Git target
259
+ plus an npm and/or Docker target continues with `gitzone release recover
260
+ <version>`, and other configurations of that age delete the tag and drop the
261
+ release commit (`git tag -d v<version>` and `git reset --hard HEAD^` on
262
+ `main`) and release again. Confirm first that `HEAD` is the release commit —
263
+ `git log -1 --format=%s` prints `v<version>` — so that a commit made on top
264
+ of it is never dropped.
265
265
  - The `--plan` step list names the isolated work: `preflight.lockfile` for a
266
266
  project with a `package.json`, then `core.releaseCheckout`,
267
267
  `core.releaseCheckout.build`, then `core.packNpmArtifact`.
@@ -629,6 +629,13 @@ the stall bound), or still progressing but below the rate floor. All of them
629
629
  leave the target inconclusive for `gitzone release resume`. The settings tune transfers
630
630
  only and may change between runs and resumes.
631
631
 
632
+ Any other request failure is inconclusive too, and says why without a URL,
633
+ header or token: the HTTP status it reached, each error of the cause chain by
634
+ name and code, a message only when it is plain words, and how far the transfer
635
+ got, for example `Gitea public asset verification is inconclusive (HTTP 200;
636
+ TypeError: terminated; SocketError [UND_ERR_SOCKET]: other side closed; 1048576
637
+ of 461373440 bytes received)`.
638
+
632
639
  The complete remote attachment set must equal the manifest. Extra names,
633
640
  duplicates, changed release identity, or conflicting bytes stop publication;
634
641
  the CLI has no deletion or replacement path. It verifies the complete set again
@@ -675,9 +682,49 @@ Resume probes remotely observable targets before acting. A published Git release
675
682
 
676
683
  Schema 1 resumes final Git release-ref and npm publication after the journal is atomically installed. Schema 2 additionally resumes Docker qualification, ordered promotion, and cleanup. Schema 3 resumes the complete npm package set. `--merge` remains available only for non-Docker releases because its pre-release Git push would violate qualification-before-publication ordering.
677
684
 
685
+ ### Resuming a release that failed before its journal
686
+
687
+ Once the local release commit and annotated tag exist, a release records its
688
+ intent before it builds, packs or checks the remote again:
689
+
690
+ ```text
691
+ <git-common-dir>/gitzone/releases/v1/v<version>.intent.json
692
+ ```
693
+
694
+ The intent binds the release commit and tag object, the version floor record,
695
+ the targets and release-build choice the command line selected, and, for a Git
696
+ target, the remote name, the hashed push destination and the remote `main` the
697
+ push will lease. Any failure between the tag and the installed journal — the
698
+ release build, packing, freezing Gitea assets, Docker validation, or a remote
699
+ that cannot be inspected — is then resumable:
700
+
701
+ ```bash
702
+ gitzone release resume 6.0.0 -y
703
+ ```
704
+
705
+ Without a journal, resume reads the intent, resolves the release from the
706
+ `.smartconfig.json` the release commit carries with the recorded targets and
707
+ build choice, and requires clean `main` at the release commit, the recorded tag
708
+ object, the recorded push destination and a remote `main` that still equals the
709
+ leased value. It then prepares the journal exactly as the release would have —
710
+ the Docker worktree build, the disposable checkout with its build, packing and
711
+ frozen assets — and continues as a normal resume from that journal. Tests are
712
+ not run again: preflight ran them on the source the release commit only adds
713
+ version metadata to. Installing the journal removes the intent, and from then on
714
+ the journal alone decides what resume does. A failed resume leaves the intent in
715
+ place for the next one. `recover` on a version with a recorded intent runs this
716
+ resume.
717
+
718
+ To abandon such a release instead of resuming it (nothing reached a remote, and
719
+ you delete the local tag and reset `main` to the commit before the release
720
+ commit), delete its intent file as well; otherwise a later tag of the same version
721
+ is handed to a resume that refuses it.
722
+
723
+ ### Recovering a tag without a recorded intent
724
+
678
725
  For a Git release with npm and/or Docker targets whose local release commit
679
- and annotated tag already exist, but whose build or pack failed before journal
680
- installation, use:
726
+ and annotated tag were created by GitZone 7.2.6 or earlier, which recorded no
727
+ intent, and whose build or pack failed before journal installation, use:
681
728
 
682
729
  ```bash
683
730
  gitzone release recover 6.0.0 --plan
@@ -780,7 +827,8 @@ CLI workflow config lives under `@git.zone/cli` in `.smartconfig.json`. Docker r
780
827
  "enabled": true,
781
828
  "remote": "origin",
782
829
  "pushBranch": true,
783
- "pushTags": true
830
+ "pushTags": true,
831
+ "remoteTimeoutSeconds": 180
784
832
  },
785
833
  "npm": {
786
834
  "enabled": true,
@@ -1558,10 +1606,11 @@ package's `files` list; `.npmignore` does not prevent that traversal when
1558
1606
  `files` is present. Keep service data and its permissions intact.
1559
1607
 
1560
1608
  Inspect the release journal before retrying. An installed journal must be
1561
- resumed with its original artifacts. A failure before journal installation has
1562
- not started final publication and cannot use `release resume`; reconcile the
1563
- local release commit and tag explicitly, preserving their identities. A later
1564
- source correction can be released as a new version from the clean checkout.
1609
+ resumed with its original artifacts. A failure after the release tag but before
1610
+ journal installation has not started final publication; `gitzone release resume
1611
+ <version> -y` prepares the journal from the recorded intent and publishes. A
1612
+ later source correction can be released as a new version from the clean
1613
+ checkout.
1565
1614
 
1566
1615
  A release step fails on a Git, pnpm or tSDocker command:
1567
1616
 
@@ -1569,11 +1618,21 @@ The error names the step, then the command and how it ended, then the end of
1569
1618
  its error output on one line:
1570
1619
 
1571
1620
  ```text
1572
- Unable to inspect main at the configured Git push destination. `git ls-remote` timed out after 60 s and was terminated by SIGTERM
1621
+ Unable to inspect main at the configured Git push destination. Step: publication state check. `git ls-remote` timed out after 180 s and was terminated by SIGTERM; gave up after 3 attempts over 565.2 s
1573
1622
  ```
1574
1623
 
1575
- A timeout means the remote did not answer in time: Git inspections allow 60
1576
- seconds, `git fetch` and `git push` five minutes. Check the remote with the
1624
+ Every `git ls-remote` of a release — the preflight before the tests, the check
1625
+ after them, the check before each publication step and the Git target's own
1626
+ probe — runs under `release.targets.git.remoteTimeoutSeconds` (default 180, at
1627
+ most 3600) per attempt. A timeout, a reset or dropped connection, and a transport failure Git reports
1628
+ as "RPC failed" (other than HTTP 401, 403 or 404) are retried twice, after 5 and 20 seconds;
1629
+ authentication failures, a missing repository and Git's own answers are final
1630
+ at once. The error names the release step, the per-attempt bound, and the
1631
+ attempts and time spent. The preflight reads the remote before the configured
1632
+ tests run, so a remote that is down fails the release before a long test run;
1633
+ the check immediately before the push stays authoritative. A failure after the
1634
+ release tag is resumable with `gitzone release resume <version> -y`. `git
1635
+ fetch` and `git push` keep their five-minute bound. Check the remote with the
1577
1636
  same command, for example `git ls-remote <push-url> refs/heads/main`, and
1578
1637
  retry once it answers promptly. An exit code comes with Git's own message,
1579
1638
  such as `does not appear to be a git repository` for a wrong push URL. The
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@git.zone/cli',
6
- version: '7.2.6',
6
+ version: '7.2.7',
7
7
  description: 'A comprehensive CLI tool for enhancing and managing local development workflows with gitzone utilities, focusing on project setup, version control, code formatting, and template management.'
8
8
  }
@@ -15,6 +15,10 @@ import {
15
15
  planReleaseNpmPackages,
16
16
  type IReleaseNpmPackageSet,
17
17
  } from "./mod_release/helpers.npmpackages.js";
18
+ import {
19
+ defaultReleaseGitRemoteTimeoutSeconds,
20
+ maximumReleaseGitRemoteTimeoutSeconds,
21
+ } from "./mod_release/helpers.gitremote.js";
18
22
 
19
23
  export type TConfirmationMode = "prompt" | "auto" | "plan";
20
24
 
@@ -51,6 +55,8 @@ export interface IReleaseGitTargetConfig {
51
55
  remote?: string;
52
56
  pushBranch?: boolean;
53
57
  pushTags?: boolean;
58
+ /** Seconds one `git ls-remote` attempt may take; default 180. */
59
+ remoteTimeoutSeconds?: number;
54
60
  }
55
61
 
56
62
  export interface IReleaseNpmTargetConfig {
@@ -275,6 +281,8 @@ export interface IResolvedReleaseWorkflow {
275
281
  versionFloor?: string;
276
282
  gitEnabled: boolean;
277
283
  gitRemote: string;
284
+ /** Bound of one attempt of every Git remote inspection. */
285
+ gitRemoteTimeoutSeconds: number;
278
286
  pushBranch: boolean;
279
287
  pushTags: boolean;
280
288
  npmEnabled: boolean;
@@ -298,8 +306,19 @@ export interface IResolvedReleaseWorkflow {
298
306
  dockerNoBuild: boolean;
299
307
  }
300
308
 
309
+ /**
310
+ * The release choices a command line can override. A release records them
311
+ * with its local commit and tag, so a resume re-resolves exactly that release
312
+ * from the configuration its commit carries.
313
+ */
314
+ export type TReleaseRecordedPlan = Pick<
315
+ IResolvedReleaseWorkflow,
316
+ "targets" | "runBuild"
317
+ >;
318
+
301
319
  export interface IResolvedReleaseResumeConfiguration {
302
320
  gitRemote: string;
321
+ gitRemoteTimeoutSeconds: number;
303
322
  npmRegistries: string[];
304
323
  npmAccessLevel: "public" | "private";
305
324
  npmAlreadyPublished: "success" | "error";
@@ -850,6 +869,22 @@ export const resolveCommitWorkflow = async (
850
869
  };
851
870
  };
852
871
 
872
+ /** Remote inspection is tuning, not identity: it may change between resumes. */
873
+ export const resolveGitRemoteTimeoutSeconds = (valueArg: unknown): number => {
874
+ if (valueArg === undefined) return defaultReleaseGitRemoteTimeoutSeconds;
875
+ if (
876
+ typeof valueArg !== "number" ||
877
+ !Number.isSafeInteger(valueArg) ||
878
+ valueArg < 1 ||
879
+ valueArg > maximumReleaseGitRemoteTimeoutSeconds
880
+ ) {
881
+ throw new Error(
882
+ `release.targets.git.remoteTimeoutSeconds must be a whole number of seconds between 1 and ${maximumReleaseGitRemoteTimeoutSeconds}`,
883
+ );
884
+ }
885
+ return valueArg;
886
+ };
887
+
853
888
  /** One accepted upload may wait this long for the registry to serve it. */
854
889
  export const resolveNpmVerificationWindowMinutes = (
855
890
  valueArg: unknown,
@@ -884,8 +919,14 @@ const assertNoRemovedNpmTargetSettings = (
884
919
  }
885
920
  };
886
921
 
922
+ /**
923
+ * Resolves the release from its configuration and command line. A resume of
924
+ * a recorded release passes `recordedPlanArg`, which replaces every command
925
+ * line override with the choices that release was created with.
926
+ */
887
927
  export const resolveReleaseWorkflow = async (
888
928
  argvArg: any,
929
+ recordedPlanArg?: TReleaseRecordedPlan,
889
930
  ): Promise<IResolvedReleaseWorkflow> => {
890
931
  const cliConfig = await readCliWorkflowConfig();
891
932
  const releaseConfig = cliConfig.release || {};
@@ -937,6 +978,7 @@ export const resolveReleaseWorkflow = async (
937
978
  if (argvArg.b || argvArg.build) runBuild = true;
938
979
  if (isDisabled(argvArg, "test")) runTests = false;
939
980
  if (isDisabled(argvArg, "build")) runBuild = false;
981
+ if (recordedPlanArg) runBuild = recordedPlanArg.runBuild;
940
982
 
941
983
  const configuredTargets: TReleaseTarget[] = [];
942
984
  if (gitEnabled) configuredTargets.push("git");
@@ -951,6 +993,7 @@ export const resolveReleaseWorkflow = async (
951
993
  if (isDisabled(argvArg, "publish")) {
952
994
  targets = targets.filter((target) => target === "git");
953
995
  }
996
+ if (recordedPlanArg) targets = recordedPlanArg.targets;
954
997
  const selectedTargets = unique(targets);
955
998
  targets = releaseTargetOrder.filter((target) =>
956
999
  selectedTargets.includes(target),
@@ -1051,6 +1094,10 @@ export const resolveReleaseWorkflow = async (
1051
1094
  ...(versionFloor ? { versionFloor } : {}),
1052
1095
  gitEnabled,
1053
1096
  gitRemote: gitConfig.remote || "origin",
1097
+ // Dormant settings of an inactive target are not validated.
1098
+ gitRemoteTimeoutSeconds: targets.includes("git")
1099
+ ? resolveGitRemoteTimeoutSeconds(gitConfig.remoteTimeoutSeconds)
1100
+ : defaultReleaseGitRemoteTimeoutSeconds,
1054
1101
  pushBranch,
1055
1102
  pushTags,
1056
1103
  npmEnabled,
@@ -1146,6 +1193,9 @@ export const resolveReleaseResumeConfiguration = async (optionsArg: {
1146
1193
 
1147
1194
  return {
1148
1195
  gitRemote,
1196
+ gitRemoteTimeoutSeconds: optionsArg.git
1197
+ ? resolveGitRemoteTimeoutSeconds(gitConfig.remoteTimeoutSeconds)
1198
+ : defaultReleaseGitRemoteTimeoutSeconds,
1149
1199
  npmRegistries,
1150
1200
  npmAccessLevel,
1151
1201
  npmAlreadyPublished,
@@ -24,6 +24,7 @@ import {
24
24
  getDeclaredTsdockerRange,
25
25
  resolveGiteaAssetsConfiguration,
26
26
  resolveGiteaAssetTransferLimits,
27
+ resolveGitRemoteTimeoutSeconds,
27
28
  resolveNpmVerificationWindowMinutes,
28
29
  } from "../helpers.workflow.js";
29
30
  import { hasInstalledProjectTsdockerBinary } from "../helpers.tsdocker.js";
@@ -2181,6 +2182,24 @@ async function validateGitTarget(
2181
2182
  fix: "Set release.targets.git.pushTags to true or disable the Git target.",
2182
2183
  });
2183
2184
  }
2185
+ try {
2186
+ const timeoutSeconds = resolveGitRemoteTimeoutSeconds(
2187
+ gitTarget.remoteTimeoutSeconds,
2188
+ );
2189
+ findings.push({
2190
+ level: "ok",
2191
+ message: `Git remote inspection waits up to ${timeoutSeconds} s per attempt`,
2192
+ });
2193
+ } catch (error) {
2194
+ findings.push({
2195
+ level: "error",
2196
+ message:
2197
+ error instanceof Error
2198
+ ? error.message
2199
+ : "Invalid Git remote inspection timeout",
2200
+ fix: "Set release.targets.git.remoteTimeoutSeconds to a whole number of seconds between 1 and 3600 or remove it.",
2201
+ });
2202
+ }
2184
2203
  findings.push({
2185
2204
  level: "ok",
2186
2205
  message: `Git release target is enabled (${gitTarget.remote || "origin"})`,
@@ -1,7 +1,11 @@
1
1
  import * as plugins from "./mod.plugins.js";
2
2
  import { formatCommandFailure } from "./helpers.commandfailure.js";
3
3
  import { InterProcessLock } from "../mod_services/classes.interprocesslock.js";
4
- import { resolveGiteaAssetsConfiguration } from "../helpers.workflow.js";
4
+ import {
5
+ resolveGiteaAssetsConfiguration,
6
+ type TReleaseRecordedPlan,
7
+ type TReleaseTarget,
8
+ } from "../helpers.workflow.js";
5
9
  import {
6
10
  assertGiteaFrozenAssets,
7
11
  validateGiteaAssets,
@@ -33,6 +37,7 @@ export const legacyReleaseJournalSchemaVersion = 1 as const;
33
37
  export const releaseJournalSchemaVersion = 2 as const;
34
38
  export const releaseArtifactFileName = "package.tgz" as const;
35
39
  export const releaseJournalFileName = "journal.json" as const;
40
+ export const releaseIntentKind = "gitzone-release-intent" as const;
36
41
 
37
42
  /**
38
43
  * `accepted` records a destination that took the upload without rejecting it
@@ -1724,6 +1729,106 @@ const assertSchema4AppendOnlyTransition = (
1724
1729
  }
1725
1730
  };
1726
1731
 
1732
+ /** The Git destination state a recorded release leases when it publishes. */
1733
+ export interface IReleaseIntentGit {
1734
+ remote: string;
1735
+ destinationHash: string;
1736
+ expectedRemoteMainOid: string;
1737
+ }
1738
+
1739
+ /**
1740
+ * What a release settled before it prepared its journal: its local commit and
1741
+ * tag, the Git destination state it leases, and the command-line choices that
1742
+ * shaped it. It is recorded as soon as the tag exists, so a failure before the
1743
+ * journal is installed resumes from the release commit instead of stranding
1744
+ * it. The installed journal supersedes it.
1745
+ */
1746
+ export interface IReleaseIntent {
1747
+ kind: typeof releaseIntentKind;
1748
+ release: IReleaseIdentity;
1749
+ plan: TReleaseRecordedPlan;
1750
+ git: IReleaseIntentGit | null;
1751
+ createdAt: string;
1752
+ }
1753
+
1754
+ const releaseTargets: readonly TReleaseTarget[] = [
1755
+ "git",
1756
+ "giteaAssets",
1757
+ "npm",
1758
+ "docker",
1759
+ ];
1760
+
1761
+ const assertReleaseIntentPlan = (valueArg: unknown): TReleaseRecordedPlan => {
1762
+ if (!isPlainObject(valueArg)) {
1763
+ throw new Error("Release intent plan must be an object.");
1764
+ }
1765
+ assertExactKeys(valueArg, ["targets", "runBuild"], "Release intent plan");
1766
+ const targets = valueArg.targets;
1767
+ if (
1768
+ !Array.isArray(targets) ||
1769
+ typeof valueArg.runBuild !== "boolean" ||
1770
+ targets.some(
1771
+ (targetArg, indexArg) =>
1772
+ !releaseTargets.includes(targetArg) ||
1773
+ (indexArg > 0 &&
1774
+ releaseTargets.indexOf(targets[indexArg - 1]) >=
1775
+ releaseTargets.indexOf(targetArg)),
1776
+ )
1777
+ ) {
1778
+ throw new Error(
1779
+ "Release intent plan must name unique release targets in canonical order.",
1780
+ );
1781
+ }
1782
+ return valueArg as unknown as TReleaseRecordedPlan;
1783
+ };
1784
+
1785
+ const assertReleaseIntentGit = (valueArg: unknown): IReleaseIntentGit | null => {
1786
+ if (valueArg === null) return null;
1787
+ if (!isPlainObject(valueArg)) {
1788
+ throw new Error("Release intent Git destination must be an object or null.");
1789
+ }
1790
+ assertExactKeys(
1791
+ valueArg,
1792
+ ["remote", "destinationHash", "expectedRemoteMainOid"],
1793
+ "Release intent Git destination",
1794
+ );
1795
+ if (
1796
+ typeof valueArg.remote !== "string" ||
1797
+ normalizeReleaseGitRemoteName(valueArg.remote) !== valueArg.remote ||
1798
+ typeof valueArg.destinationHash !== "string" ||
1799
+ !sha256Regex.test(valueArg.destinationHash) ||
1800
+ typeof valueArg.expectedRemoteMainOid !== "string" ||
1801
+ !gitOidRegex.test(valueArg.expectedRemoteMainOid)
1802
+ ) {
1803
+ throw new Error("Release intent Git destination data is invalid.");
1804
+ }
1805
+ return valueArg as unknown as IReleaseIntentGit;
1806
+ };
1807
+
1808
+ export const assertReleaseIntent = (valueArg: unknown): IReleaseIntent => {
1809
+ if (!isPlainObject(valueArg)) {
1810
+ throw new Error("Release intent root must be a JSON object.");
1811
+ }
1812
+ assertExactKeys(
1813
+ valueArg,
1814
+ ["kind", "release", "plan", "git", "createdAt"],
1815
+ "Release intent",
1816
+ );
1817
+ if (valueArg.kind !== releaseIntentKind) {
1818
+ throw new Error("Release intent kind is invalid.");
1819
+ }
1820
+ assertReleaseIdentity(valueArg.release);
1821
+ const plan = assertReleaseIntentPlan(valueArg.plan);
1822
+ const git = assertReleaseIntentGit(valueArg.git);
1823
+ if (plan.targets.includes("git") !== (git !== null)) {
1824
+ throw new Error(
1825
+ "A release intent records a Git destination exactly when Git is a target.",
1826
+ );
1827
+ }
1828
+ assertIsoTimestamp(valueArg.createdAt, "Release intent createdAt");
1829
+ return valueArg as unknown as IReleaseIntent;
1830
+ };
1831
+
1727
1832
  export const createReleaseAttempt = (): IReleaseAttempt => ({
1728
1833
  id: plugins.crypto.randomBytes(16).toString("hex"),
1729
1834
  pid: process.pid,
@@ -1815,6 +1920,77 @@ export class ReleaseJournalStore {
1815
1920
  );
1816
1921
  }
1817
1922
 
1923
+ /** Beside the release directory, so installing the journal never meets it. */
1924
+ public getIntentPath(versionArg: string): string {
1925
+ return `${this.getReleaseDirectory(versionArg)}.intent.json`;
1926
+ }
1927
+
1928
+ public async hasJournal(versionArg: string): Promise<boolean> {
1929
+ try {
1930
+ await plugins.fs.lstat(this.getReleaseDirectory(versionArg));
1931
+ return true;
1932
+ } catch (error) {
1933
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return false;
1934
+ throw error;
1935
+ }
1936
+ }
1937
+
1938
+ /**
1939
+ * Records the intent atomically. A fresh release just created its tag, so
1940
+ * an intent left behind by an earlier, unwound attempt at this version no
1941
+ * longer names an existing tag and is replaced.
1942
+ */
1943
+ public async recordIntent(intentArg: IReleaseIntent): Promise<void> {
1944
+ const intent = assertReleaseIntent(intentArg);
1945
+ await plugins.fs.mkdir(this.rootPath, { recursive: true, mode: 0o700 });
1946
+ const intentPath = this.getIntentPath(intent.release.version);
1947
+ const temporaryPath = `${intentPath}.tmp-${process.pid}-${plugins.crypto.randomBytes(12).toString("hex")}`;
1948
+ try {
1949
+ const handle = await plugins.fs.open(temporaryPath, "wx", 0o600);
1950
+ try {
1951
+ await handle.writeFile(`${JSON.stringify(intent, null, 2)}\n`, "utf8");
1952
+ await handle.sync();
1953
+ } finally {
1954
+ await handle.close();
1955
+ }
1956
+ await plugins.fs.rename(temporaryPath, intentPath);
1957
+ await syncDirectory(this.rootPath);
1958
+ } catch (error) {
1959
+ await plugins.fs.rm(temporaryPath, { force: true });
1960
+ throw new Error(
1961
+ `Release intent v${intent.release.version} could not be recorded.`,
1962
+ { cause: error },
1963
+ );
1964
+ }
1965
+ }
1966
+
1967
+ /** The recorded intent of a release without an installed journal, if any. */
1968
+ public async readIntent(versionArg: string): Promise<IReleaseIntent | null> {
1969
+ const version = normalizeReleaseVersion(versionArg);
1970
+ let content: string;
1971
+ try {
1972
+ content = await plugins.fs.readFile(this.getIntentPath(version), "utf8");
1973
+ } catch (error) {
1974
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
1975
+ throw new Error(`Release intent v${version} could not be read.`, {
1976
+ cause: error,
1977
+ });
1978
+ }
1979
+ let parsed: unknown;
1980
+ try {
1981
+ parsed = JSON.parse(content);
1982
+ } catch (error) {
1983
+ throw new Error(`Release intent v${version} is not valid JSON.`, {
1984
+ cause: error,
1985
+ });
1986
+ }
1987
+ const intent = assertReleaseIntent(parsed);
1988
+ if (intent.release.version !== version) {
1989
+ throw new Error("Release intent path and version do not match.");
1990
+ }
1991
+ return intent;
1992
+ }
1993
+
1818
1994
  public async read(versionArg: string): Promise<TReleaseJournal> {
1819
1995
  const version = normalizeReleaseVersion(versionArg);
1820
1996
  const filePath = plugins.path.join(
@@ -2014,6 +2190,10 @@ export class ReleaseJournalStore {
2014
2190
  }
2015
2191
  await syncDirectory(temporaryDirectory);
2016
2192
  await plugins.fs.rename(temporaryDirectory, releaseDirectory);
2193
+ // The journal now owns the release; its intent is superseded.
2194
+ await plugins.fs.rm(this.getIntentPath(journal.release.version), {
2195
+ force: true,
2196
+ });
2017
2197
  await syncDirectory(this.rootPath);
2018
2198
  return journal;
2019
2199
  });
@@ -34,6 +34,50 @@ class GiteaAssetHttpError extends Error {
34
34
  }
35
35
  }
36
36
 
37
+ /**
38
+ * A request ended for a reason that proves neither success nor conflict. The
39
+ * message carries a sanitized cause and never a URL, header, body or token.
40
+ */
41
+ export class GiteaAssetInconclusiveError extends Error {
42
+ constructor(message: string) {
43
+ super(message);
44
+ this.name = "GiteaAssetInconclusiveError";
45
+ }
46
+ }
47
+
48
+ const safeErrorName = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
49
+ const safeErrorCode = /^[A-Z][A-Z0-9_]{1,63}$/;
50
+ /** Plain words only: no digit, colon, slash or dot inside can carry a URL or token. */
51
+ const safeErrorMessage = /^[A-Za-z][A-Za-z ]{0,79}\.?$/;
52
+
53
+ /**
54
+ * Names why a request ended: the HTTP status it reached, each error of the
55
+ * cause chain by name and code, its message only when it is plain words
56
+ * ("terminated", "fetch failed", "other side closed"), and how far the
57
+ * transfer got.
58
+ */
59
+ export const describeGiteaRequestFailure = (
60
+ error: unknown,
61
+ evidence: { status?: number; progress: string },
62
+ ): string => {
63
+ const parts: string[] = [];
64
+ if (evidence.status !== undefined) parts.push(`HTTP ${evidence.status}`);
65
+ let current = error;
66
+ for (let depth = 0; depth < 4 && current instanceof Error; depth++) {
67
+ const name = safeErrorName.test(current.name) ? current.name : "Error";
68
+ const code = (current as NodeJS.ErrnoException).code;
69
+ const codeText =
70
+ typeof code === "string" && safeErrorCode.test(code) ? ` [${code}]` : "";
71
+ const messageText = safeErrorMessage.test(current.message)
72
+ ? `: ${current.message}`
73
+ : "";
74
+ parts.push(`${name}${codeText}${messageText}`);
75
+ current = current.cause;
76
+ }
77
+ parts.push(evidence.progress);
78
+ return `(${parts.join("; ")})`;
79
+ };
80
+
37
81
  export const defaultGiteaAssetTransferLimits: Readonly<IGiteaAssetTransferLimits> =
38
82
  Object.freeze({
39
83
  responseTimeoutMs: 2 * 60_000,
@@ -193,6 +237,11 @@ export class GiteaTransferWatchdog {
193
237
  return this.#failure;
194
238
  }
195
239
 
240
+ /** Bytes sent and received so far. */
241
+ get bytes(): number {
242
+ return this.#bytes;
243
+ }
244
+
196
245
  /** Wait for response headers; every redirect hop starts a new wait. */
197
246
  awaitResponse(): void {
198
247
  this.#arm("response");
@@ -765,8 +814,14 @@ export class GiteaAssetsClient implements IGiteaAssetsClient {
765
814
  // Never include response text, fetch errors, URLs or causes that can expose the token.
766
815
  if (watchdog.failure) throw watchdog.failure;
767
816
  if (error instanceof GiteaAssetHttpError) throw error;
768
- throw new Error(
769
- `Gitea asset ${method} result is inconclusive; inspect the retained release before another mutation.`,
817
+ throw new GiteaAssetInconclusiveError(
818
+ `Gitea asset ${method} result is inconclusive ${describeGiteaRequestFailure(
819
+ error,
820
+ {
821
+ status: response?.status,
822
+ progress: `${watchdog.bytes} bytes transferred`,
823
+ },
824
+ )}; inspect the retained release before another mutation.`,
770
825
  );
771
826
  } finally {
772
827
  watchdog.close();
@@ -993,6 +1048,9 @@ export class GiteaAssetsClient implements IGiteaAssetsClient {
993
1048
  asset.size,
994
1049
  );
995
1050
  let response: Response | undefined;
1051
+ /** Status of the response the failure followed; a redirect hop resets it. */
1052
+ let status: number | undefined;
1053
+ let size = 0;
996
1054
  try {
997
1055
  let url = new URL(asset.publicUrl);
998
1056
  for (let redirects = 0; ; redirects++) {
@@ -1004,11 +1062,13 @@ export class GiteaAssetsClient implements IGiteaAssetsClient {
1004
1062
  )
1005
1063
  throw new GiteaAssetConflictError("Unsafe anonymous asset redirect.");
1006
1064
  watchdog.awaitResponse();
1065
+ status = undefined;
1007
1066
  response = await this.fetchImplementation(url.href, {
1008
1067
  redirect: "manual",
1009
1068
  signal: watchdog.signal,
1010
1069
  headers: { "Accept-Encoding": "identity" },
1011
1070
  });
1071
+ status = response.status;
1012
1072
  watchdog.progress("received", 0);
1013
1073
  if (![301, 302, 303, 307, 308].includes(response.status)) break;
1014
1074
  if (redirects >= 5 || !response.headers.get("location"))
@@ -1032,7 +1092,6 @@ export class GiteaAssetsClient implements IGiteaAssetsClient {
1032
1092
  )
1033
1093
  throw new GiteaAssetConflictError("Anonymous asset size mismatch.");
1034
1094
  const hash = plugins.crypto.createHash("sha256");
1035
- let size = 0;
1036
1095
  const reader = response.body.getReader();
1037
1096
  try {
1038
1097
  while (true) {
@@ -1055,8 +1114,11 @@ export class GiteaAssetsClient implements IGiteaAssetsClient {
1055
1114
  } catch (error) {
1056
1115
  if (watchdog.failure) throw watchdog.failure;
1057
1116
  if (error instanceof GiteaAssetConflictError) throw error;
1058
- throw new Error(
1059
- "Gitea public asset verification is inconclusive; inspect availability before publication.",
1117
+ throw new GiteaAssetInconclusiveError(
1118
+ `Gitea public asset verification is inconclusive ${describeGiteaRequestFailure(
1119
+ error,
1120
+ { status, progress: `${size} of ${asset.size} bytes received` },
1121
+ )}; inspect availability before publication.`,
1060
1122
  );
1061
1123
  } finally {
1062
1124
  watchdog.close();