@sublang/spex 6.0.0 → 7.0.0-beta.2

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.
Files changed (108) hide show
  1. package/README.md +419 -12
  2. package/dist/cli.js +12 -1
  3. package/dist/commands/add.d.ts +1 -1
  4. package/dist/commands/add.js +2 -2
  5. package/dist/commands/environment.d.ts +3 -3
  6. package/dist/commands/environment.js +5 -7
  7. package/dist/commands/export.js +2 -2
  8. package/dist/commands/home.d.ts +2 -2
  9. package/dist/commands/home.js +3 -3
  10. package/dist/commands/list.js +1 -1
  11. package/dist/commands/login.js +12 -7
  12. package/dist/commands/logout.js +2 -3
  13. package/dist/commands/publish.js +1 -1
  14. package/dist/commands/remove.js +1 -1
  15. package/dist/commands/run.d.ts +1 -1
  16. package/dist/commands/run.js +16 -0
  17. package/dist/commands/settle.d.ts +1 -1
  18. package/dist/commands/settle.js +1 -1
  19. package/dist/guards/approval.d.ts +56 -0
  20. package/dist/guards/approval.js +158 -0
  21. package/dist/guards/checks.d.ts +207 -0
  22. package/dist/guards/checks.js +681 -0
  23. package/dist/guards/commands.d.ts +15 -0
  24. package/dist/guards/commands.js +313 -0
  25. package/dist/guards/copy.d.ts +67 -0
  26. package/dist/guards/copy.js +306 -0
  27. package/dist/guards/declaration.d.ts +45 -0
  28. package/dist/guards/declaration.js +224 -0
  29. package/dist/guards/files.d.ts +137 -0
  30. package/dist/guards/files.js +544 -0
  31. package/dist/guards/harness.d.ts +58 -0
  32. package/dist/guards/harness.js +420 -0
  33. package/dist/guards/items.d.ts +61 -0
  34. package/dist/guards/items.js +161 -0
  35. package/dist/guards/patch.d.ts +55 -0
  36. package/dist/guards/patch.js +258 -0
  37. package/dist/guards/processes.d.ts +49 -0
  38. package/dist/guards/processes.js +233 -0
  39. package/dist/guards/proofs.d.ts +88 -0
  40. package/dist/guards/proofs.js +503 -0
  41. package/dist/guards/records.d.ts +176 -0
  42. package/dist/guards/records.js +513 -0
  43. package/dist/guards/report.d.ts +26 -0
  44. package/dist/guards/report.js +492 -0
  45. package/dist/guards/runner.d.ts +42 -0
  46. package/dist/guards/runner.js +167 -0
  47. package/dist/guards/tla.d.ts +51 -0
  48. package/dist/guards/tla.js +352 -0
  49. package/dist/guards/tlapm.d.ts +81 -0
  50. package/dist/guards/tlapm.js +172 -0
  51. package/dist/guards/tlc.d.ts +191 -0
  52. package/dist/guards/tlc.js +457 -0
  53. package/dist/guards/translation.d.ts +66 -0
  54. package/dist/guards/translation.js +202 -0
  55. package/dist/guards/types.d.ts +185 -0
  56. package/dist/guards/types.js +437 -0
  57. package/dist/guards/verify.d.ts +290 -0
  58. package/dist/guards/verify.js +1191 -0
  59. package/dist/guards/xml.d.ts +18 -0
  60. package/dist/guards/xml.js +105 -0
  61. package/dist/lib/environment/archive.d.ts +2 -2
  62. package/dist/lib/environment/archive.js +1 -1
  63. package/dist/lib/environment/builtins.d.ts +10 -12
  64. package/dist/lib/environment/builtins.js +17 -19
  65. package/dist/lib/environment/exports.d.ts +14 -13
  66. package/dist/lib/environment/exports.js +31 -16
  67. package/dist/lib/environment/format.d.ts +2 -2
  68. package/dist/lib/environment/format.js +3 -3
  69. package/dist/lib/environment/git-source.js +6 -3
  70. package/dist/lib/environment/install.d.ts +14 -16
  71. package/dist/lib/environment/install.js +66 -61
  72. package/dist/lib/environment/lock.d.ts +4 -3
  73. package/dist/lib/environment/lock.js +6 -5
  74. package/dist/lib/environment/marker.js +1 -2
  75. package/dist/lib/environment/own-paths.d.ts +7 -10
  76. package/dist/lib/environment/own-paths.js +10 -13
  77. package/dist/lib/environment/placed-record.d.ts +3 -2
  78. package/dist/lib/environment/placed-record.js +5 -4
  79. package/dist/lib/environment/registry.d.ts +1 -1
  80. package/dist/lib/environment/registry.js +1 -1
  81. package/dist/lib/environment/requests.d.ts +2 -2
  82. package/dist/lib/environment/requests.js +2 -2
  83. package/dist/lib/environment/resolve.d.ts +4 -4
  84. package/dist/lib/environment/resolve.js +3 -4
  85. package/dist/lib/environment/store.d.ts +34 -8
  86. package/dist/lib/environment/store.js +138 -43
  87. package/dist/lib/files.d.ts +72 -12
  88. package/dist/lib/files.js +200 -65
  89. package/dist/lib/git-host.d.ts +52 -258
  90. package/dist/lib/git-host.js +52 -265
  91. package/dist/lib/home-file.d.ts +13 -10
  92. package/dist/lib/home-file.js +28 -18
  93. package/dist/lib/instance.d.ts +1 -1
  94. package/dist/lib/instance.js +1 -1
  95. package/dist/lint.d.ts +22 -0
  96. package/dist/lint.js +36 -0
  97. package/dist/testing/standin-registry.js +1 -1
  98. package/package.json +7 -3
  99. package/scaffold/.file-history.json +14 -7
  100. package/scaffold/i18n/zh/source-pins.json +41 -0
  101. package/scaffold/i18n/zh/specs/decisions/000-spec-structure-format.md +0 -1
  102. package/scaffold/i18n/zh/specs/intents/000-spdx-headers.md +0 -1
  103. package/scaffold/i18n/zh/specs/map.md +0 -1
  104. package/scaffold/i18n/zh/specs/meta.md +18 -35
  105. package/scaffold/i18n/zh/specs/packages/git.md +0 -1
  106. package/scaffold/i18n/zh/specs/packages/licensing.md +0 -1
  107. package/scaffold/specs/meta.md +18 -3
  108. package/scripts/test-exit-guard.mjs +28 -0
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // The home the package commands act on (cli-1, storage-1, storage-2):
3
+ // The home the package commands act on (cli-1, storage-63, storage-2):
4
4
  // `SPEX_HOME` where set, else `~/.spex`. The CLI reads `home.yaml` with
5
5
  // the library, checking no pairing — the app checks its own — and
6
6
  // writes it only where a command records something; it never reads or
@@ -113,7 +113,7 @@ export function nameOf(instance) {
113
113
  export function credentialsOf(dir, origin, scope = "space") {
114
114
  return fileCredentialStore(dir, origin, scope);
115
115
  }
116
- /** The client of one instance, signing in as this device (git-host-3). */
116
+ /** The client of one instance, signing in as this device (git-host-40). */
117
117
  export function clientOf(origin, credentials, onSignedOut, scope = "space") {
118
118
  let device = "this device";
119
119
  try {
@@ -122,7 +122,7 @@ export function clientOf(origin, credentials, onSignedOut, scope = "space") {
122
122
  catch { /* the label's fallback */ }
123
123
  return new GitHostClient({ url: origin, scope, label: `spex on ${device}`, credentials, ...(onSignedOut ? { onSignedOut } : {}) });
124
124
  }
125
- /** A host's answer in the CLI's words (git-host-11, cli-13): what the
125
+ /** A host's answer in the CLI's words (cli-13): what the
126
126
  * Space or registry said, its own words as the detail, and what to do —
127
127
  * `again`, the command that tries once more — never a secret. An answer
128
128
  * of no known kind, such as a page that is not there, comes from an
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // `spex list`, or `spex ls` (cli-6, environments-14): the packages of
3
+ // `spex list`, or `spex ls` (cli-6, environments-64): the packages of
4
4
  // this folder as its files stand, in a project's Packages tab's words
5
5
  // (DR-172) — the folder and its registry by name; each package added,
6
6
  // with its version or folder; each package installed, with its version,
@@ -1,7 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // `spex login [--registry <url> | --space <url>] [--force]` (cli-10,
4
- // git-host-3, DR-168): sign this computer in by the device flow at this
3
+ // `spex login [--registry <url> | --space <url>] [--force]` (cli-10, git-host-40, DR-168): sign this computer in by the device flow at this
5
4
  // folder's registry for its packages, or at the registry or Space named.
6
5
  // A registry sign-in keeps its app token alone and caches the registry's
7
6
  // display name (cli-22); a Space sign-in records the Space in
@@ -9,7 +8,7 @@
9
8
  // default — while the library's client keeps its app token in
10
9
  // `local/credentials.yaml` (storage-19).
11
10
  import { anotherAccountError, HostError, } from "../lib/git-host.js";
12
- import { homeFilePath, instanceAt, readHomeFile, updateHomeFile, withDisplayName, withSignIn } from "../lib/home-file.js";
11
+ import { homeFilePath, instanceAt, isSpaceGitOrigin, readHomeFile, updateHomeFile, withDisplayName, withSignIn } from "../lib/home-file.js";
13
12
  import { authTarget } from "./auth-target.js";
14
13
  import { instanceFolder } from "../lib/instance.js";
15
14
  import { cacheRegistryName, clientOf, credentialsOf, describedRegistryName, homeDir, hostCause, hostOf, listed, nameOf, readHome, registryName, signedIn } from "./home.js";
@@ -91,8 +90,10 @@ export const login = async (args, interrupt) => {
91
90
  const client = clientOf(origin, credentials, undefined, scope);
92
91
  // The registry's or Space's display name, read while the person
93
92
  // approves; a sign-in goes on where it does not answer.
94
- const described = scope === "registry" ? describedRegistryName(origin) : client.describe().then((description) => description.displayName || null, () => null);
95
- // At a listed instance, only its entry's account (git-host-2): read in
93
+ const described = scope === "registry"
94
+ ? describedRegistryName(origin).then((displayName) => ({ displayName }))
95
+ : client.describe().catch(() => null);
96
+ // At a listed instance, only its entry's account: read in
96
97
  // the turn that would store the token, so another stores nothing.
97
98
  const admit = (account) => {
98
99
  if (scope === "registry")
@@ -160,7 +161,9 @@ export const login = async (args, interrupt) => {
160
161
  const nameSkipped = new Promise((resolve) => { skipName = () => resolve(null); });
161
162
  const deferred = interrupt.hold(() => skipName());
162
163
  try {
163
- const displayName = await Promise.race([described, nameSkipped]);
164
+ const description = await Promise.race([described, nameSkipped]);
165
+ const displayName = description?.displayName || null;
166
+ const gitOrigin = description && "gitOrigin" in description && isSpaceGitOrigin(description.gitOrigin) ? description.gitOrigin : undefined;
164
167
  if (scope === "registry") {
165
168
  if (held)
166
169
  await clientOf(origin, heldOnly(held), undefined, scope).signOut().catch(() => undefined);
@@ -178,7 +181,9 @@ export const login = async (args, interrupt) => {
178
181
  try {
179
182
  recorded = updateHomeFile(dir, (current) => {
180
183
  const next = withSignIn(current, origin, account, homeFilePath(dir));
181
- return displayName === null ? next : withDisplayName(next, origin, displayName) ?? next;
184
+ if (displayName === null && gitOrigin === undefined)
185
+ return next;
186
+ return withDisplayName(next, origin, displayName ?? instanceAt(next, origin)?.displayName ?? null, gitOrigin) ?? next;
182
187
  });
183
188
  }
184
189
  catch (error) {
@@ -1,7 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // `spex logout [--registry <url> | --space <url>]` (cli-11, git-host-10,
4
- // DR-168): revoke this computer's sign-in for one purpose alone — this
3
+ // `spex logout [--registry <url> | --space <url>]` (cli-11, git-host-31, DR-168): revoke this computer's sign-in for one purpose alone — this
5
4
  // folder's registry for its packages by default, or the registry or
6
5
  // Space named — and, for a Space, in the turn its pair is removed, mark
7
6
  // its entry signed out in `home.yaml`, keeping the entry and every other
@@ -52,7 +51,7 @@ export const logout = async (args) => {
52
51
  const client = clientOf(entry.origin, credentialsOf(dir, entry.origin));
53
52
  let marked = null;
54
53
  try {
55
- // The pair's removal and the entry's mark are one step (git-host-10).
54
+ // The pair's removal and the entry's mark are one step (git-host-31).
56
55
  await client.signOut(() => {
57
56
  try {
58
57
  updateHomeFile(dir, (current) => withSignOut(current, entry.origin));
@@ -60,7 +60,7 @@ export const publish = async (args) => {
60
60
  if (!isPackageName(name))
61
61
  throw new Refusal(packageNameRefusal(name));
62
62
  // The folder: the one spex.yaml adds that name from, else
63
- // spex-packages/<org>/<pkg>/ under the root (environments-10).
63
+ // spex-packages/<org>/<pkg>/ under the root (environments-59).
64
64
  const request = read?.requests.packages[name];
65
65
  const path = request !== undefined && isPathRequest(request) ? request.path : `spex-packages/${name}`;
66
66
  const folder = resolve(env.root, path);
@@ -1,6 +1,6 @@
1
1
  // SPDX-License-Identifier: Apache-2.0
2
2
  // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
- // `spex remove <org>/<pkg>`, or `spex rm` (cli-3, environments-15): take
3
+ // `spex remove <org>/<pkg>`, or `spex rm` (cli-3, environments-65): take
4
4
  // the package out of `spex.yaml`, resolve, install and export what
5
5
  // remains, and print each package removed, an edited copy of its spec
6
6
  // left in `specs/` as the project's own and read as edited, in the words
@@ -1,6 +1,6 @@
1
1
  import { type ParseArgsConfig } from "node:util";
2
2
  /** The usage, as cli-21 writes it. */
3
- export declare const USAGE = "Usage: spex <command> [options]\n\nPackages in this folder (spex.yaml, spex.lock, .spex/)\n add <org>/<pkg>[@<version>] Add a package (newest by default)\n add <org>/<pkg> --path <folder> Add a package from a folder in this project\n remove, rm <org>/<pkg> Remove a package\n install, i Install what spex.lock records\n update Update to the newest versions spex.yaml allows\n list, ls What is added, installed, and placed for your agents\n search <query> Find packages at the registry\n\nYour packages\n export <org>/<pkg> [--spec <file>] [--skill <folder>]\u2026 Build it in spex-packages/<org>/<pkg>/ from your files\n publish [<org>/<pkg>] [--registry <url>] [--dry-run] Publish it to the registry\n\nSign-in\n login [--registry <url> | --space <url>] Sign in with a code in your browser\n logout [--registry <url> | --space <url>] Sign out\n whoami [--registry <url> | --space <url>] Who you are signed in as, and where\n\nSpecs\n scaffold [<path> | --update] Start specs/ and point your agents at it\n lint [<path>] Check specs/ for structure, IDs and citations\n\nspex --version \u00B7 spex <command> --help \u00B7 Home: $SPEX_HOME or ~/.spex";
3
+ export declare const USAGE = "Usage: spex <command> [options]\n\nPackages in this folder (spex.yaml, spex.lock, .spex/)\n add <org>/<pkg>[@<version>] Add a package (newest by default)\n add <org>/<pkg> --path <folder> Add a package from a folder in this project\n remove, rm <org>/<pkg> Remove a package\n install, i Install what spex.lock records\n update Update to the newest versions spex.yaml allows\n list, ls What is added, installed, and placed for your agents\n search <query> Find packages at the registry\n\nYour packages\n export <org>/<pkg> [--spec <file>] [--skill <folder>]\u2026 Build it in spex-packages/<org>/<pkg>/ from your files\n publish [<org>/<pkg>] [--registry <url>] [--dry-run] Publish it to the registry\n\nSign-in\n login [--registry <url> | --space <url>] Sign in with a code in your browser\n logout [--registry <url> | --space <url>] Sign out\n whoami [--registry <url> | --space <url>] Who you are signed in as, and where\n\nSpecs\n scaffold [<path> | --update] Start specs/ and point your agents at it\n lint [<path>] Check specs/ for structure, IDs and citations\n\nGuards\n verify [<guard>\u2026] Check that each guard's protected behavior still holds\n approve <guard> Record your approval of a guard's items and files\n\nspex --version \u00B7 spex <command> --help \u00B7 Home: $SPEX_HOME or ~/.spex";
4
4
  /** The command a word of the command line names, by its own name or an
5
5
  * alias, if any. */
6
6
  export declare function commandNamed(word: string): string | undefined;
@@ -38,6 +38,10 @@ Specs
38
38
  scaffold [<path> | --update] Start specs/ and point your agents at it
39
39
  lint [<path>] Check specs/ for structure, IDs and citations
40
40
 
41
+ Guards
42
+ verify [<guard>…] Check that each guard's protected behavior still holds
43
+ approve <guard> Record your approval of a guard's items and files
44
+
41
45
  spex --version · spex <command> --help · Home: $SPEX_HOME or ~/.spex`;
42
46
  const AGENTS = AGENT_TARGETS.flatMap((target) => target.agents).sort();
43
47
  /** "a or b", "a, b or c". */
@@ -109,6 +113,18 @@ const HELP = {
109
113
  usage: "spex lint [<path>]",
110
114
  options: [["<path>", "The folder holding specs/ (the Git repository's top level by default)"]],
111
115
  },
116
+ verify: {
117
+ usage: "spex verify [--keep <folder>] [<guard>…]",
118
+ options: [
119
+ ["<guard>…", "The guards to check, by name (every guard under guards/ by default)"],
120
+ ["--keep <folder>", "Leave every file generated for TLC and the proof system, with their command lines, in <folder>", "a folder"],
121
+ ],
122
+ },
123
+ approve: {
124
+ usage: "spex approve <guard>",
125
+ words: "<guard>",
126
+ options: [["<guard>", "The guard to approve, by name"]],
127
+ },
112
128
  };
113
129
  /** The aliases the usage names beside a command. */
114
130
  const ALIASES = { rm: "remove", i: "install", ls: "list" };
@@ -60,7 +60,7 @@ export declare function projectFolders(): {
60
60
  * as that folder's manifest names them. */
61
61
  export declare function exportedIn(root: string, folder: string): string[];
62
62
  /** Whether a package's files stand as the lock records them
63
- * (environments-14): `installed`; `not installed`; or `files missing`
63
+ * (environments-64): `installed`; `not installed`; or `files missing`
64
64
  * where the install placed it, or its folder is not at its path. */
65
65
  export type PackageState = "installed" | "not installed" | "files missing";
66
66
  export declare function packageState(root: string, lock: Lock, name: string, installed: Set<string>, recorded: Set<string>): PackageState;
@@ -36,7 +36,7 @@ export function staleReasons(root, lock, requestsText) {
36
36
  const staleness = lockStaleness(lock, requestsText, (path) => pathManifest(root, path));
37
37
  return staleness.stale ? staleness.reasons : null;
38
38
  }
39
- // -- Git locators as a reader is shown them (environments-29, DR-120) ---------
39
+ // -- Git locators as a reader is shown them (DR-120) ---------
40
40
  /** Whether a Git locator is a folder of this computer: a path, or a
41
41
  * file URL. */
42
42
  function localGit(repo) {
@@ -0,0 +1,56 @@
1
+ /** Digests by label, labels in order. */
2
+ export type Inputs = Record<string, string>;
3
+ /** The label of an item input. */
4
+ export declare function itemLabel(id: string): string;
5
+ /** The label of a file input; `path` is relative to the root, with `/`. */
6
+ export declare function fileLabel(path: string): string;
7
+ /**
8
+ * The digest of one input: SHA-256, in hex, of its text with LF line
9
+ * endings, so a checkout with CRLF endings digests the same. Bytes
10
+ * that are not UTF-8 text are digested as they are.
11
+ */
12
+ export declare function digest(content: Buffer | string): string;
13
+ /**
14
+ * The first of `paths`, each read under `folder` at the path it has
15
+ * from the root, whose digest is not the one `inputs` holds under its
16
+ * label, or null where every one is as the inputs hold it. A file
17
+ * that is not there, or cannot be read, has changed.
18
+ */
19
+ export declare function changedInput(inputs: Inputs, folder: string, paths: readonly string[]): string | null;
20
+ /** The same inputs with their labels in order. */
21
+ export declare function sortInputs(inputs: Inputs): Inputs;
22
+ /** How a guard's inputs stand against its approval record. Each list
23
+ * holds labels in order. */
24
+ export type ApprovalState = {
25
+ /** There is a record and nothing changed, was added or is gone. */
26
+ approved: boolean;
27
+ /** There is a record at all. */
28
+ recorded: boolean;
29
+ changed: string[];
30
+ /** In the tree, not in the record. */
31
+ added: string[];
32
+ /** In the record, not in the tree. */
33
+ gone: string[];
34
+ };
35
+ /** Compare a guard's inputs with its record (`null`: no record). */
36
+ export declare function compareApproval(inputs: Inputs, record: Inputs | null): ApprovalState;
37
+ /** Where a guard's approval record is, relative to the root. */
38
+ export declare function approvalPath(guard: string): string;
39
+ /** The record's text: keys in order, two-space indent, a final
40
+ * newline. */
41
+ export declare function approvalText(inputs: Inputs): string;
42
+ /** Read a record's text. Throws a GuardError saying what is wrong
43
+ * with it. */
44
+ export declare function parseApproval(text: string): Inputs;
45
+ /**
46
+ * Read a guard's approval record, or null when there is none. A
47
+ * record that cannot be read is a GuardError starting with its path.
48
+ */
49
+ export declare function readApproval(root: string, guard: string): Inputs | null;
50
+ /** Write a guard's approval record. Returns its path from the root,
51
+ * and whether the file was written: one that holds these bytes
52
+ * already is left as it is. */
53
+ export declare function writeApproval(root: string, guard: string, inputs: Inputs): {
54
+ path: string;
55
+ written: boolean;
56
+ };
@@ -0,0 +1,158 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // SPDX-FileCopyrightText: 2026 SubLang International <https://sublang.ai>
3
+ /*
4
+ * Guards package, DR-252: the approval record. A guard's inputs are
5
+ * its items and its files, each under a label (`item <id>` or
6
+ * `file <path from the root>`) with one SHA-256 digest. The record,
7
+ * `guards/<guard>/approval.json`, is a committed file holding the
8
+ * digests a person approved; a run compares the inputs with it and
9
+ * names each one that changed, was added or is gone.
10
+ */
11
+ import { createHash } from "node:crypto";
12
+ import { existsSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { GuardError, byText, mapping, showData } from "./types.js";
15
+ /** The label of an item input. */
16
+ export function itemLabel(id) {
17
+ return `item ${id}`;
18
+ }
19
+ /** The label of a file input; `path` is relative to the root, with `/`. */
20
+ export function fileLabel(path) {
21
+ return `file ${path}`;
22
+ }
23
+ /**
24
+ * The digest of one input: SHA-256, in hex, of its text with LF line
25
+ * endings, so a checkout with CRLF endings digests the same. Bytes
26
+ * that are not UTF-8 text are digested as they are.
27
+ */
28
+ export function digest(content) {
29
+ let text;
30
+ if (typeof content === "string")
31
+ text = content;
32
+ else {
33
+ text = content.toString("utf8");
34
+ if (!Buffer.from(text, "utf8").equals(content))
35
+ text = null;
36
+ }
37
+ const hash = createHash("sha256");
38
+ hash.update(text === null ? content : Buffer.from(text.replace(/\r\n/g, "\n"), "utf8"));
39
+ return hash.digest("hex");
40
+ }
41
+ /**
42
+ * The first of `paths`, each read under `folder` at the path it has
43
+ * from the root, whose digest is not the one `inputs` holds under its
44
+ * label, or null where every one is as the inputs hold it. A file
45
+ * that is not there, or cannot be read, has changed.
46
+ */
47
+ export function changedInput(inputs, folder, paths) {
48
+ for (const path of paths) {
49
+ let found;
50
+ try {
51
+ found = digest(readFileSync(join(folder, ...path.split("/"))));
52
+ }
53
+ catch {
54
+ found = null;
55
+ }
56
+ if (found === null || found !== inputs[fileLabel(path)])
57
+ return path;
58
+ }
59
+ return null;
60
+ }
61
+ /** The same inputs with their labels in order. */
62
+ export function sortInputs(inputs) {
63
+ const sorted = {};
64
+ for (const label of Object.keys(inputs).sort(byText))
65
+ sorted[label] = inputs[label];
66
+ return sorted;
67
+ }
68
+ /** Compare a guard's inputs with its record (`null`: no record). */
69
+ export function compareApproval(inputs, record) {
70
+ if (record === null) {
71
+ return { approved: false, recorded: false, changed: [], added: Object.keys(inputs).sort(byText), gone: [] };
72
+ }
73
+ const changed = [];
74
+ const added = [];
75
+ for (const label of Object.keys(inputs).sort(byText)) {
76
+ if (!Object.hasOwn(record, label))
77
+ added.push(label);
78
+ else if (record[label] !== inputs[label])
79
+ changed.push(label);
80
+ }
81
+ const gone = Object.keys(record)
82
+ .filter((label) => !Object.hasOwn(inputs, label))
83
+ .sort(byText);
84
+ return {
85
+ approved: changed.length === 0 && added.length === 0 && gone.length === 0,
86
+ recorded: true,
87
+ changed,
88
+ added,
89
+ gone,
90
+ };
91
+ }
92
+ /** Where a guard's approval record is, relative to the root. */
93
+ export function approvalPath(guard) {
94
+ return `guards/${guard}/approval.json`;
95
+ }
96
+ /** The record's text: keys in order, two-space indent, a final
97
+ * newline. */
98
+ export function approvalText(inputs) {
99
+ return `${JSON.stringify({ format: 1, inputs: sortInputs(inputs) }, null, 2)}\n`;
100
+ }
101
+ /** Read a record's text. Throws a GuardError saying what is wrong
102
+ * with it. */
103
+ export function parseApproval(text) {
104
+ let data;
105
+ try {
106
+ data = JSON.parse(text);
107
+ }
108
+ catch {
109
+ throw new GuardError("not readable as JSON");
110
+ }
111
+ const top = mapping(data, ["format", "inputs"]);
112
+ if (top.format !== 1)
113
+ throw new GuardError("format must be 1");
114
+ const inputs = {};
115
+ const recorded = mapping(top.inputs);
116
+ for (const label of Object.keys(recorded).sort(byText)) {
117
+ const value = recorded[label];
118
+ if (typeof value !== "string" || !/^[0-9a-f]{64}$/.test(value)) {
119
+ throw new GuardError(`'${label}' holds ${showData(value)}, not a SHA-256 digest`);
120
+ }
121
+ if (!label.startsWith("item ") && !label.startsWith("file ")) {
122
+ throw new GuardError(`'${label}' is not an input's label`);
123
+ }
124
+ inputs[label] = value;
125
+ }
126
+ return inputs;
127
+ }
128
+ /**
129
+ * Read a guard's approval record, or null when there is none. A
130
+ * record that cannot be read is a GuardError starting with its path.
131
+ */
132
+ export function readApproval(root, guard) {
133
+ const path = approvalPath(guard);
134
+ const file = join(root, ...path.split("/"));
135
+ if (!existsSync(file))
136
+ return null;
137
+ try {
138
+ return parseApproval(readFileSync(file, "utf8"));
139
+ }
140
+ catch (error) {
141
+ if (error instanceof GuardError)
142
+ throw new GuardError(`${path}: ${error.message}`);
143
+ throw error;
144
+ }
145
+ }
146
+ /** Write a guard's approval record. Returns its path from the root,
147
+ * and whether the file was written: one that holds these bytes
148
+ * already is left as it is. */
149
+ export function writeApproval(root, guard, inputs) {
150
+ const path = approvalPath(guard);
151
+ const file = join(root, ...path.split("/"));
152
+ const text = approvalText(inputs);
153
+ if (existsSync(file) && readFileSync(file, "utf8") === text)
154
+ return { path, written: false };
155
+ writeFileSync(file, text);
156
+ return { path, written: true };
157
+ }
158
+ //# sourceMappingURL=approval.js.map
@@ -0,0 +1,207 @@
1
+ import type { Guard } from "./files.js";
2
+ import { type Book, type Judged, type Sequence } from "./records.js";
3
+ import { type Tla } from "./tla.js";
4
+ import { type Tools } from "./tlc.js";
5
+ import { type Translation } from "./translation.js";
6
+ import { type Call, type Case, type Declaration, type Fields } from "./types.js";
7
+ /** `1 second`, `300 seconds`. */
8
+ export declare function seconds(count: number): string;
9
+ /** What every run of TLC for one guard shares. */
10
+ export type Shop = {
11
+ tools: Tools;
12
+ guard: Guard;
13
+ /** A fresh folder under the OS temp folder; each run of TLC gets a
14
+ * folder of its own in it. */
15
+ home: string;
16
+ /** Where every generated file is left, or null: `<folder>/<guard>`
17
+ * of `spex verify --keep <folder>`. */
18
+ keep: string | null;
19
+ /** TLC's version, set by its first run. */
20
+ version: {
21
+ tlc: string | null;
22
+ };
23
+ };
24
+ /** The first line of the file that marks a folder `--keep` wrote. */
25
+ export declare const KEPT_MARK = "Kept by spex verify.";
26
+ /** The name of that file in `<folder>/<guard>`. */
27
+ export declare const KEPT_FILE = "spex-verify.txt";
28
+ /**
29
+ * Whether `dir` is a folder `spex verify --keep` wrote for a guard, so
30
+ * that a later run may replace it: a folder, no link to one, holding
31
+ * the file that marks one, a file and no link, whose first line is
32
+ * the mark and nothing more. The mark decides this alone: no copy and
33
+ * no list of a guard's files looks for it (guards-41).
34
+ */
35
+ export declare function keptBySpex(dir: string): boolean;
36
+ /** A word of a command line as a POSIX shell takes it. */
37
+ export declare function quoted(word: string): string;
38
+ /** Prepare `<folder>/<guard>` of `--keep`: an empty folder with its
39
+ * mark. One that stands without the mark is not Spex's to replace. */
40
+ export declare function prepareKeep(keep: string, guard: string): string;
41
+ /** One step as a report shows it: the event with its params, and an
42
+ * effect in words, or null where none is shown. */
43
+ export type Shown = {
44
+ call: Call;
45
+ effect: string | null;
46
+ };
47
+ /** Why a guard cannot be checked: the cause, and where TLC met it. */
48
+ export type Cannot = {
49
+ cause: string;
50
+ note: string | null;
51
+ steps: Shown[];
52
+ };
53
+ /**
54
+ * Check one translation alone: its form by its text, then TLC parses
55
+ * it and reports what it loads. Returns each fault as
56
+ * `<file>[:<line>:<col>]: <what>`; none where its form holds.
57
+ */
58
+ export declare function checkForm(shop: Shop, translation: Translation): Promise<string[]>;
59
+ /** A case a translation does not allow or forbid as marked; `case`
60
+ * is null where the rule applies in no permitted case. */
61
+ export type CaseFailure = {
62
+ case: string | null;
63
+ kind: Case["kind"] | null;
64
+ translation: string;
65
+ /** What was found, in words. */
66
+ found: string;
67
+ };
68
+ export type CasesCheck = {
69
+ kind: "done";
70
+ failures: CaseFailure[];
71
+ } | {
72
+ kind: "stopped";
73
+ cause: string;
74
+ } | {
75
+ kind: "cannot";
76
+ cannot: Cannot[];
77
+ };
78
+ /**
79
+ * Evaluate each case under each translation in one run of TLC. A
80
+ * translation allows a permitted case where every step is legal, its
81
+ * model gives each effect field the step states and no step is
82
+ * forbidden. It forbids a forbidden case where the steps before the
83
+ * last go so and, at the last, the rule applies and forbids every
84
+ * declared effect that is as the step states.
85
+ */
86
+ export declare function checkCases(shop: Shop): Promise<CasesCheck>;
87
+ /** How a guard's translations compare. A difference is the
88
+ * distinguishing sequence: steps every translation agrees on, then
89
+ * the step `last` and the one question it puts, with each
90
+ * translation's answer in name order. */
91
+ export type Comparison = {
92
+ kind: "agreement";
93
+ } | {
94
+ kind: "differ";
95
+ about: "legal" | "effect" | "applies" | "forbidden";
96
+ steps: Shown[];
97
+ last: Call;
98
+ /** The effect the question is about, for `forbidden`, and the
99
+ * model's effect at that step, on which the translations agree. */
100
+ effect: string | null;
101
+ model: string | null;
102
+ answers: {
103
+ translation: string;
104
+ answer: string;
105
+ }[];
106
+ } | {
107
+ kind: "not compared";
108
+ cause: string;
109
+ };
110
+ export type CompareCheck = Comparison | {
111
+ kind: "cannot";
112
+ cannot: Cannot[];
113
+ };
114
+ /**
115
+ * Model-check the translations side by side in one run of TLC: at
116
+ * every step any of them reaches they give the same answers to the
117
+ * four questions.
118
+ * TLC's shortest sequence to a difference is the distinguishing
119
+ * sequence.
120
+ */
121
+ export declare function compareTranslations(shop: Shop): Promise<CompareCheck>;
122
+ /** One step of the model: a legal event in one state of the model,
123
+ * with the model's effect, the state after it and whether the rule
124
+ * applies. A state is held by the one text of its printed value. */
125
+ export type Row = {
126
+ from: string;
127
+ call: Call;
128
+ effect: Fields;
129
+ next: string;
130
+ applies: boolean;
131
+ };
132
+ /** TLC's table of the model's steps, in TLC's order, and a shortest
133
+ * sequence of steps from the start to each state the model reaches. */
134
+ export type Table = {
135
+ start: string;
136
+ rows: Row[];
137
+ paths: Map<string, Row[]>;
138
+ };
139
+ export type ModelCheck = {
140
+ kind: "checked";
141
+ table: Table;
142
+ /** The steps at which the rule applies. */
143
+ applied: number;
144
+ /** TLC's own estimate of the chance it missed a state. */
145
+ collision: string | null;
146
+ } | {
147
+ kind: "conflict";
148
+ steps: Shown[];
149
+ last: Call;
150
+ effect: string;
151
+ } | {
152
+ kind: "not checked";
153
+ cause: string;
154
+ } | {
155
+ kind: "cannot";
156
+ cannot: Cannot[];
157
+ };
158
+ /**
159
+ * TLC's table from its state dump: every dumped state whose `step`
160
+ * holds a step of the model is one row. The paths are found by
161
+ * walking the table breadth first from the start, ties in TLC's
162
+ * order.
163
+ */
164
+ export declare function tableOf(declaration: Declaration, states: readonly Record<string, Tla>[]): Table;
165
+ /**
166
+ * Model-check the judging translation in one run of TLC: in every
167
+ * state the model reaches, for every legal event, the model's effect
168
+ * is a declared effect and the rule does not forbid it. The same run
169
+ * writes TLC's table of the model's steps.
170
+ */
171
+ export declare function checkModel(shop: Shop, translation: Translation): Promise<ModelCheck>;
172
+ /** Why TLC judged no record of a run or of a later one: stopped at the
173
+ * time limit, or out of memory. `cause` is said after `a timeout: `
174
+ * for the first, as it stands for the second. */
175
+ export type Halted = {
176
+ kind: "timeout" | "memory";
177
+ cause: string;
178
+ };
179
+ export type RecordsCheck = {
180
+ kind: "judged";
181
+ /** For each sequence, in order: what TLC printed for it, or null
182
+ * where its run was not judged. */
183
+ judged: (Judged | null)[];
184
+ /** The run that was stopped, or null where every run ended. */
185
+ halted: Halted | null;
186
+ /** How many runs were made. */
187
+ runs: number;
188
+ } | {
189
+ kind: "cannot";
190
+ cannot: Cannot[];
191
+ /** The sequence at fault, by its place in the sequences. */
192
+ sequence: number;
193
+ };
194
+ /** The folder of the `k`-th run of `name`, from 1: `name`, then
195
+ * `name~2`, `name~3`. */
196
+ export declare function runFolder(name: string, k: number): string;
197
+ /**
198
+ * Have TLC judge every sequence of one copy, the module's and the
199
+ * tests', one run after another in the folders `name`, `name~2`, …,
200
+ * each from its own `SpexRecords.tla` with the copy's values. TLC
201
+ * walks each sequence through `translation`'s model no further than
202
+ * its first record that is not matched, and prints what it found.
203
+ */
204
+ export declare function judgeRecords(shop: Shop, name: string, translation: Translation, sequences: readonly Sequence[], book: Book, most?: {
205
+ records: number;
206
+ different: number;
207
+ }): Promise<RecordsCheck>;