@altopelago/sansa 0.10.1 → 0.11.0

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/CHANGELOG.md CHANGED
@@ -7,6 +7,20 @@ versions may still include breaking changes when the SANSA specifications move.
7
7
 
8
8
  ## Unreleased
9
9
 
10
+ ## 0.11.0 - 2026-09-14
11
+
12
+ ### Added
13
+
14
+ - Added reader-only Film v1 input to the Query CLI and direct Query Workbench
15
+ runtime. Film records use the same portable AES namespace adapter as Telex,
16
+ without reconstructing AEON source or parser events.
17
+
18
+ ### Changed
19
+
20
+ - Require complete Film streams when no external namespace state is supplied.
21
+ Film remains a byte-oriented query input and is not exposed through the
22
+ browser JSON request envelope, mutation, re-encoding, or durable writing.
23
+
10
24
  ## 0.10.1 - 2026-09-11
11
25
 
12
26
  ### Added
package/README.md CHANGED
@@ -61,7 +61,8 @@ The Instruction and Mutate CTS lanes are experimental and are not included in `n
61
61
  ## Query Tool
62
62
 
63
63
  The package includes a standalone query tool for exercising SANSA.Query against
64
- AEON source, portable Telex AES, or a host-neutral JSON namespace fixture:
64
+ AEON source, portable Telex AES, reader-only Film AES, or a host-neutral JSON
65
+ namespace fixture:
65
66
 
66
67
  ```bash
67
68
  npm run query -- --query 'from $.inventory.items.* where contains(.sku, "B") select .sku'
@@ -73,6 +74,9 @@ support is optional and uses an AEON TypeScript Core runtime when one is
73
74
  available. `.telex.aes` fixture support uses the optional
74
75
  `@altopelago/aeon-aes` runtime and projects complete portable records directly
75
76
  into a SANSA namespace without rebuilding an AEON parser AST.
77
+ `.film.aes` fixtures use the same portable-record namespace after complete Film
78
+ and AES validation. Film support is query-only; SANSA does not expose a Film
79
+ mutation target or writer.
76
80
 
77
81
  For browser-based technical testing, run the Query Workbench:
78
82
 
@@ -568,8 +568,8 @@ Options:
568
568
 
569
569
  - `--query`, `-q`: query source
570
570
  - `--query-file`: read query source from a file
571
- - `--fixture`, `-f`: AEON, Telex AES, or JSON namespace fixture, defaulting to `fixtures/query-inventory.json`
572
- - `--fixture-kind`: force fixture kind as `aeon`, `telex`, or `json`; otherwise inferred from the file extension
571
+ - `--fixture`, `-f`: AEON, Telex AES, Film AES, or JSON namespace fixture, defaulting to `fixtures/query-inventory.json`
572
+ - `--fixture-kind`: force fixture kind as `aeon`, `telex`, `film`, or `json`; otherwise inferred from the file extension
573
573
  - `--params`: JSON params mounted at `$.<"params">`
574
574
  - `--params-file`: read JSON params from a file and mount them at `$.<"params">`
575
575
  - `--mode`: `evaluate` or `parse`
@@ -581,9 +581,9 @@ Options:
581
581
  - `--max-order-candidates`: fail if order by would sort more than this many candidates
582
582
  - `--max-result-records`: fail if select would produce more than this many result records
583
583
 
584
- The default CLI fixture is JSON so `sansa-query` can run without optional host integrations after package install. AEON fixtures are compiled with an optional AEON TypeScript Core runtime and adapted into a SANSA resolver namespace. Telex fixtures use an optional AEON AES runtime and adapt complete portable records directly, preserving flat attributes, structural identities, datatype components, record order, and expanded node heads. Partial streams require external state and are rejected by this adapter. JSON fixture bindings remain host-neutral objects. The built-in JSON adapter reads `root`, `children`, `attributeSpace` or `attributes`, `localSpaces`, and scalar values through `value` or `scalar`.
584
+ The default CLI fixture is JSON so `sansa-query` can run without optional host integrations after package install. AEON fixtures are compiled with an optional AEON TypeScript Core runtime and adapted into a SANSA resolver namespace. Telex fixtures use an optional AEON AES runtime and adapt complete portable records directly, preserving flat attributes, structural identities, datatype components, record order, and expanded node heads. Film fixtures are read as bytes, decoded by the same optional AES runtime, and passed through that portable-record adapter. Telex and Film partial streams require external state and are rejected. Film support is reader-only: the query tool does not mutate, re-encode, or provide a durable Film writer. JSON fixture bindings remain host-neutral objects. The built-in JSON adapter reads `root`, `children`, `attributeSpace` or `attributes`, `localSpaces`, and scalar values through `value` or `scalar`.
585
585
 
586
- AEON fixture support is optional. The tool resolves AEON Core from `SANSA_AEON_CORE_MODULE`, from an installed `@altopelago/aeon-core` visible to the calling project, or from the sibling aeon-family development workspace path. Telex support resolves the AES codec from `SANSA_AEON_AES_MODULE`, an installed `@altopelago/aeon-aes`, or the corresponding sibling development build. JSON fixtures and Query parsing require neither runtime.
586
+ AEON fixture support is optional. The tool resolves AEON Core from `SANSA_AEON_CORE_MODULE`, from an installed `@altopelago/aeon-core` visible to the calling project, or from the sibling aeon-family development workspace path. Telex and Film support resolve the AES codec from `SANSA_AEON_AES_MODULE`, an installed `@altopelago/aeon-aes`, or the corresponding sibling development build. JSON fixtures and Query parsing require neither runtime.
587
587
 
588
588
  Params may be supplied either as a full local-space fixture binding with `children`, or as a simple object map. Structured SANSA Address Literal values use `{ "type": "SansaAddressLiteral", "address": "..." }`; these are preserved as `sansa` bindings so query expressions can activate them with `path(...)`.
589
589
 
@@ -593,7 +593,7 @@ The package also includes a browser workbench:
593
593
  npm run query:web
594
594
  ```
595
595
 
596
- The workbench server serves [tools/query-web](../tools/query-web) and [tools/mutate-web](../tools/mutate-web). The Query Workbench defaults to `.aeon` source input and exposes a local `/api/query` endpoint. For `.aeon` source, the endpoint uses the optional AEON TypeScript core compiler to derive a host-neutral SANSA resolver namespace before running SANSA.Query. Its Telex mode consumes a complete portable AES stream directly, while JSON fixture mode remains available for resolver-shape debugging. A params editor mounts a small AEON source snippet as `$.<"params">`; top-level params bindings become children of that local address space. The browser UI includes a Normal/Validation policy toggle, a Transform extension toggle, and evaluation budget inputs. `/api/query` accepts `sourceKind: "aeon" | "telex" | "json"`, `policy: "validation"`, `transformExtensions: false`, and `budget` for evaluate requests.
596
+ The workbench server serves [tools/query-web](../tools/query-web) and [tools/mutate-web](../tools/mutate-web). The Query Workbench defaults to `.aeon` source input and exposes a local `/api/query` endpoint. For `.aeon` source, the endpoint uses the optional AEON TypeScript core compiler to derive a host-neutral SANSA resolver namespace before running SANSA.Query. Its Telex mode consumes a complete portable AES stream directly, while JSON fixture mode remains available for resolver-shape debugging. A params editor mounts a small AEON source snippet as `$.<"params">`; top-level params bindings become children of that local address space. The browser UI includes a Normal/Validation policy toggle, a Transform extension toggle, and evaluation budget inputs. `/api/query` accepts `sourceKind: "aeon" | "telex" | "json"`, `policy: "validation"`, `transformExtensions: false`, and `budget` for evaluate requests. Film remains available to the CLI and to direct `evaluateQueryForWorkbench(...)` callers that can supply bytes; it is not accepted through the browser's JSON request envelope in this release.
597
597
 
598
598
  The experimental Mutate Workbench exposes `/api/mutate`. It accepts `.aeon`
599
599
  source or complete portable Telex AES selected with `sourceKind: "aeon" |
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "implementation": "@altopelago/sansa",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "profiles": [
5
5
  "value-semantics-minimum-consumer",
6
6
  "aeon.value.default.v1",
@@ -1,7 +1,8 @@
1
1
  # SANSA Query Tool
2
2
 
3
3
  The package includes a standalone query tool for exercising SANSA.Query against
4
- AEON source, portable Telex AES, or a host-neutral JSON namespace fixture:
4
+ AEON source, portable Telex AES, reader-only Film AES, or a host-neutral JSON
5
+ namespace fixture:
5
6
 
6
7
  ```bash
7
8
  npm run query -- --query 'from $.inventory.items.* where contains(.sku, "B") select .sku'
@@ -34,6 +35,18 @@ identity, datatype components, and the explicit `NodeLiteral` → `NodeHead` →
34
35
  content hierarchy. Partial streams are rejected because this tool has no
35
36
  external namespace state with which to complete them.
36
37
 
38
+ `.film.aes` fixtures are decoded from bytes by the same optional AES runtime
39
+ and then use the identical portable-record adapter. The CLI accepts Film only
40
+ as complete query input. It does not expose Film mutation, re-encoding, or a
41
+ durable writer.
42
+
43
+ To create and query the minimal Film v1 scalar used by the test suite:
44
+
45
+ ```bash
46
+ node --input-type=module -e "import { writeFileSync } from 'node:fs'; writeFileSync('scalar.film.aes', Buffer.from('4f5f5fff010012000109242e6d6573736167650568656c6c6f', 'hex'))"
47
+ npm run query -- --query 'from $.message select .' --fixture scalar.film.aes
48
+ ```
49
+
37
50
  AEON fixture support is optional so SANSA can remain a lower-level package. For
38
51
  published-package use, install `@altopelago/aeon-core` in the calling project or
39
52
  set `SANSA_AEON_CORE_MODULE` to an AEON Core module path or specifier. Inside
@@ -79,6 +92,9 @@ npm run query:web
79
92
 
80
93
  Then open `http://127.0.0.1:4173/tools/query-web/`.
81
94
 
95
+ Film remains a byte-oriented CLI and direct runtime input in this release; the
96
+ browser workbench does not convert Film bytes into its JSON request envelope.
97
+
82
98
  The same server also exposes the experimental SANSA Mutate Workbench at
83
99
  `http://127.0.0.1:4173/tools/mutate-web/`. The Mutate Workbench uses `.aeon` or
84
100
  complete `.telex.aes` source input plus an editor that can accept structured JSON mutation requests
package/docs/releasing.md CHANGED
@@ -28,10 +28,26 @@ must be released from tag `vX.Y.Z`.
28
28
 
29
29
  ## Release steps
30
30
 
31
- 1. Update `package.json`, `docs/capabilities.json`, and `CHANGELOG.md`.
32
- 2. Merge the release-prep PR into `main`.
33
- 3. Confirm CI passes on `main`.
34
- 4. Create tag `vX.Y.Z` from the checked `main` commit.
35
- 5. Publish a GitHub Release for `vX.Y.Z`.
36
- 6. Let `Publish npm` run from GitHub Actions.
37
- 7. Confirm the npm package page shows the expected version and provenance.
31
+ 1. Run `npm run version:set -- X.Y.Z` to update machine-owned release metadata.
32
+ 2. Add the dated `X.Y.Z` release section and human-authored notes to
33
+ `CHANGELOG.md`.
34
+ 3. Run `npm run version:check`, the test suite, CTS, stress tests, and package
35
+ dry-run.
36
+ 4. Merge the release-prep PR into `main`.
37
+ 5. Confirm CI passes on `main`.
38
+ 6. Create tag `vX.Y.Z` from the checked `main` commit.
39
+ 7. Publish a GitHub Release for `vX.Y.Z`.
40
+ 8. Let `Publish npm` run from GitHub Actions.
41
+ 9. Confirm the npm package page shows the expected version and provenance.
42
+
43
+ `version:set` updates `package.json` and `docs/capabilities.json` together.
44
+ `version:check` is enforced by CI and the publish workflow; it also requires a
45
+ matching dated changelog heading. The setter accepts valid SemVer without a
46
+ leading `v`, permits an exact idempotent rerun, and otherwise requires the new
47
+ version to have higher SemVer precedence. Neither command commits, tags, or
48
+ publishes.
49
+ Updates use staged files, backups, and atomic renames. If a process is
50
+ interrupted, both `version:set` and `version:check` fail closed until
51
+ `npm run version:recover` either restores the original pair or finishes cleanup
52
+ for a committed pair. Run recovery only after confirming no other version
53
+ command is active.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@altopelago/sansa",
3
- "version": "0.10.1",
3
+ "version": "0.11.0",
4
4
  "description": "Semantic Address NameSpace Abstraction parser, resolver, and query toolkit.",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -61,6 +61,9 @@
61
61
  "query:web": "node scripts/query-web.mjs",
62
62
  "mutate:web": "node scripts/query-web.mjs",
63
63
  "stress": "node scripts/stress-addresses.mjs",
64
+ "version:set": "node scripts/version.mjs set",
65
+ "version:check": "node scripts/version.mjs check",
66
+ "version:recover": "node scripts/version.mjs recover",
64
67
  "validate:cts-claims": "node scripts/validate-cts-claims.mjs",
65
68
  "test": "node --test test/*.test.js"
66
69
  },
package/scripts/query.mjs CHANGED
@@ -3,7 +3,11 @@ import { readFileSync } from 'node:fs';
3
3
  import { dirname, resolve } from 'node:path';
4
4
  import { fileURLToPath } from 'node:url';
5
5
  import { evaluateQuery, parseQuery } from '../src/index.js';
6
- import { namespaceFromAeonSource, namespaceFromTelexSource } from '../tools/query-web/runtime.mjs';
6
+ import {
7
+ namespaceFromAeonSource,
8
+ namespaceFromFilmSource,
9
+ namespaceFromTelexSource,
10
+ } from '../tools/query-web/runtime.mjs';
7
11
 
8
12
  const here = dirname(fileURLToPath(import.meta.url));
9
13
  const root = resolve(here, '..');
@@ -187,7 +191,7 @@ async function readNamespaceFixture(path, explicitKind) {
187
191
  const kind = inferFixtureKind(path, explicitKind);
188
192
  let source;
189
193
  try {
190
- source = readFileSync(path, 'utf8');
194
+ source = kind === 'film' ? readFileSync(path) : readFileSync(path, 'utf8');
191
195
  } catch (error) {
192
196
  console.error(`SANSA Query tool error: could not read fixture '${path}': ${error.message}`);
193
197
  return { ok: false };
@@ -204,9 +208,15 @@ async function readNamespaceFixture(path, explicitKind) {
204
208
 
205
209
  const result = kind === 'telex'
206
210
  ? await namespaceFromTelexSource(source)
207
- : await namespaceFromAeonSource(source);
211
+ : kind === 'film'
212
+ ? await namespaceFromFilmSource(source)
213
+ : await namespaceFromAeonSource(source);
208
214
  if (!result.ok) {
209
- const description = kind === 'telex' ? 'load Telex fixture' : 'compile AEON fixture';
215
+ const description = kind === 'telex'
216
+ ? 'load Telex fixture'
217
+ : kind === 'film'
218
+ ? 'load Film fixture'
219
+ : 'compile AEON fixture';
210
220
  console.error(`SANSA Query tool error: could not ${description} '${path}':`);
211
221
  console.error(result.text);
212
222
  return { ok: false };
@@ -216,14 +226,15 @@ async function readNamespaceFixture(path, explicitKind) {
216
226
 
217
227
  function inferFixtureKind(path, explicitKind) {
218
228
  if (explicitKind !== undefined) {
219
- if (['json', 'aeon', 'telex'].includes(explicitKind)) return explicitKind;
220
- console.error(`SANSA Query tool error: unsupported --fixture-kind '${explicitKind}'. Expected 'json', 'aeon', or 'telex'.`);
229
+ if (['json', 'aeon', 'telex', 'film'].includes(explicitKind)) return explicitKind;
230
+ console.error(`SANSA Query tool error: unsupported --fixture-kind '${explicitKind}'. Expected 'json', 'aeon', 'telex', or 'film'.`);
221
231
  process.exit(2);
222
232
  }
223
233
  if (path.endsWith('.json')) return 'json';
224
234
  if (path.endsWith('.telex.aes')) return 'telex';
235
+ if (path.endsWith('.film.aes')) return 'film';
225
236
  if (path.endsWith('.aeon')) return 'aeon';
226
- console.error(`SANSA Query tool error: could not infer fixture kind from '${path}'. Use --fixture-kind json, aeon, or telex.`);
237
+ console.error(`SANSA Query tool error: could not infer fixture kind from '${path}'. Use --fixture-kind json, aeon, telex, or film.`);
227
238
  process.exit(2);
228
239
  }
229
240
 
@@ -587,14 +598,15 @@ Usage:
587
598
  npm run query -- --query "from $.inventory.items.*\\nselect .sku"
588
599
  npm run query -- --query-file query.sansaq --fixture fixture.aeon
589
600
  npm run query -- --query-file query.sansaq --fixture fixture.telex.aes
601
+ npm run query -- --query-file query.sansaq --fixture fixture.film.aes
590
602
  npm run query -- --query-file query.sansaq --fixture fixture.json
591
603
  npm run query -- --mode parse --query "from $.inventory.items.*\\nselect .sku"
592
604
 
593
605
  Options:
594
606
  -q, --query <source> Query source.
595
607
  --query-file <path> Read query source from a file.
596
- -f, --fixture <path> AEON, Telex, or JSON namespace fixture. Defaults to fixtures/query-inventory.json.
597
- --fixture-kind <kind> Force fixture kind: aeon, telex, or json. Inferred from extension by default.
608
+ -f, --fixture <path> AEON, Telex, Film, or JSON namespace fixture. Defaults to fixtures/query-inventory.json.
609
+ --fixture-kind <kind> Force fixture kind: aeon, telex, film, or json. Inferred from extension by default.
598
610
  --params <json> Mount JSON params at $.<"params">.
599
611
  --params-file <path> Read JSON params and mount them at $.<"params">.
600
612
  --mode <mode> evaluate or parse. Defaults to evaluate.
@@ -0,0 +1,486 @@
1
+ #!/usr/bin/env node
2
+
3
+ import { constants as fsConstants } from 'node:fs';
4
+ import {
5
+ copyFile,
6
+ lstat,
7
+ mkdir,
8
+ open,
9
+ readFile,
10
+ readdir,
11
+ rename,
12
+ rmdir,
13
+ unlink,
14
+ writeFile,
15
+ } from 'node:fs/promises';
16
+ import path from 'node:path';
17
+ import { fileURLToPath } from 'node:url';
18
+
19
+ const repositoryRoot = path.resolve(
20
+ path.dirname(fileURLToPath(import.meta.url)),
21
+ '..',
22
+ );
23
+ const expectedPackageName = '@altopelago/sansa';
24
+ const packagePath = path.join(repositoryRoot, 'package.json');
25
+ const capabilitiesPath = path.join(repositoryRoot, 'docs', 'capabilities.json');
26
+ const changelogPath = path.join(repositoryRoot, 'CHANGELOG.md');
27
+ const transactionPath = path.join(repositoryRoot, '.sansa-version-transaction');
28
+ const journalPath = path.join(transactionPath, 'journal.json');
29
+ const journalNextPath = path.join(transactionPath, 'journal.next');
30
+ const semverPattern = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*)?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/;
31
+ const transactionStates = new Set(['staging', 'prepared', 'committed']);
32
+
33
+ const transactionTargets = [
34
+ {
35
+ label: 'package.json',
36
+ path: packagePath,
37
+ next: path.join(transactionPath, 'package.next'),
38
+ backup: path.join(transactionPath, 'package.backup'),
39
+ restore: path.join(transactionPath, 'package.restore'),
40
+ },
41
+ {
42
+ label: 'docs/capabilities.json',
43
+ path: capabilitiesPath,
44
+ next: path.join(transactionPath, 'capabilities.next'),
45
+ backup: path.join(transactionPath, 'capabilities.backup'),
46
+ restore: path.join(transactionPath, 'capabilities.restore'),
47
+ },
48
+ ];
49
+
50
+ function fail(message) {
51
+ console.error(`Version validation failed: ${message}`);
52
+ process.exitCode = 1;
53
+ }
54
+
55
+ function errorMessage(error) {
56
+ return error instanceof Error ? error.message : String(error);
57
+ }
58
+
59
+ function escapeRegExp(value) {
60
+ return value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
61
+ }
62
+
63
+ function semverParts(version) {
64
+ const withoutBuild = version.split('+', 1)[0];
65
+ const separator = withoutBuild.indexOf('-');
66
+ const core = (separator === -1 ? withoutBuild : withoutBuild.slice(0, separator))
67
+ .split('.')
68
+ .map((part) => BigInt(part));
69
+ const prerelease = separator === -1
70
+ ? null
71
+ : withoutBuild.slice(separator + 1).split('.');
72
+ return { core, prerelease };
73
+ }
74
+
75
+ function compareSemver(left, right) {
76
+ const a = semverParts(left);
77
+ const b = semverParts(right);
78
+ for (let index = 0; index < 3; index += 1) {
79
+ if (a.core[index] < b.core[index]) return -1;
80
+ if (a.core[index] > b.core[index]) return 1;
81
+ }
82
+ if (a.prerelease === null && b.prerelease === null) return 0;
83
+ if (a.prerelease === null) return 1;
84
+ if (b.prerelease === null) return -1;
85
+ const length = Math.max(a.prerelease.length, b.prerelease.length);
86
+ for (let index = 0; index < length; index += 1) {
87
+ const leftPart = a.prerelease[index];
88
+ const rightPart = b.prerelease[index];
89
+ if (leftPart === undefined) return -1;
90
+ if (rightPart === undefined) return 1;
91
+ if (leftPart === rightPart) continue;
92
+ const leftNumeric = /^\d+$/.test(leftPart);
93
+ const rightNumeric = /^\d+$/.test(rightPart);
94
+ if (leftNumeric && rightNumeric) {
95
+ return BigInt(leftPart) < BigInt(rightPart) ? -1 : 1;
96
+ }
97
+ if (leftNumeric !== rightNumeric) return leftNumeric ? -1 : 1;
98
+ return leftPart < rightPart ? -1 : 1;
99
+ }
100
+ return 0;
101
+ }
102
+
103
+ async function exists(file) {
104
+ try {
105
+ await lstat(file);
106
+ return true;
107
+ } catch (error) {
108
+ if (error?.code === 'ENOENT') return false;
109
+ throw error;
110
+ }
111
+ }
112
+
113
+ async function unlinkIfPresent(file) {
114
+ try {
115
+ await unlink(file);
116
+ } catch (error) {
117
+ if (error?.code !== 'ENOENT') throw error;
118
+ }
119
+ }
120
+
121
+ async function assertRegularFile(file, label) {
122
+ const metadata = await lstat(file);
123
+ if (!metadata.isFile() || metadata.isSymbolicLink()) {
124
+ throw new Error(`${label} must be a regular file and must not be a symbolic link`);
125
+ }
126
+ return metadata;
127
+ }
128
+
129
+ async function assertTransactionDirectory() {
130
+ const metadata = await lstat(transactionPath);
131
+ if (!metadata.isDirectory() || metadata.isSymbolicLink()) {
132
+ throw new Error(
133
+ `${path.relative(repositoryRoot, transactionPath)} must be a directory and must not be a symbolic link`,
134
+ );
135
+ }
136
+ }
137
+
138
+ async function assertKnownTransactionArtifacts() {
139
+ const knownArtifacts = new Set([
140
+ path.basename(journalPath),
141
+ path.basename(journalNextPath),
142
+ ...transactionTargets.flatMap((target) => [
143
+ path.basename(target.next),
144
+ path.basename(target.backup),
145
+ path.basename(target.restore),
146
+ ]),
147
+ ]);
148
+ const unknown = (await readdir(transactionPath))
149
+ .filter((artifact) => !knownArtifacts.has(artifact));
150
+ if (unknown.length > 0) {
151
+ throw new Error(
152
+ `Unknown recovery artifacts are present (${unknown.join(', ')}); preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection`,
153
+ );
154
+ }
155
+ }
156
+
157
+ async function readJson(file, label) {
158
+ await assertRegularFile(file, label);
159
+ try {
160
+ return JSON.parse(await readFile(file, 'utf8'));
161
+ } catch (error) {
162
+ throw new Error(`${label} is not valid JSON: ${errorMessage(error)}`);
163
+ }
164
+ }
165
+
166
+ async function writeDurableNew(file, source, mode) {
167
+ const handle = await open(file, fsConstants.O_CREAT | fsConstants.O_EXCL | fsConstants.O_WRONLY, mode);
168
+ try {
169
+ await handle.writeFile(source);
170
+ await handle.sync();
171
+ } finally {
172
+ await handle.close();
173
+ }
174
+ }
175
+
176
+ async function syncFile(file) {
177
+ const handle = await open(file, 'r');
178
+ try {
179
+ await handle.sync();
180
+ } finally {
181
+ await handle.close();
182
+ }
183
+ }
184
+
185
+ async function writeJournal(state) {
186
+ await unlinkIfPresent(journalNextPath);
187
+ await writeDurableNew(
188
+ journalNextPath,
189
+ `${JSON.stringify({ schemaVersion: 1, state })}\n`,
190
+ 0o600,
191
+ );
192
+ await rename(journalNextPath, journalPath);
193
+ }
194
+
195
+ async function readJournal() {
196
+ if (!await exists(journalPath)) return null;
197
+ let journal;
198
+ try {
199
+ await assertRegularFile(journalPath, 'Version recovery journal');
200
+ journal = JSON.parse(await readFile(journalPath, 'utf8'));
201
+ } catch (error) {
202
+ throw new Error(
203
+ `Recovery journal is unreadable; preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection: ${errorMessage(error)}`,
204
+ );
205
+ }
206
+ if (journal?.schemaVersion !== 1 || !transactionStates.has(journal.state)) {
207
+ throw new Error(
208
+ `Recovery journal has an unsupported shape; preserve ${path.relative(repositoryRoot, transactionPath)} for manual inspection`,
209
+ );
210
+ }
211
+ return journal;
212
+ }
213
+
214
+ async function cleanupTransaction() {
215
+ for (const target of transactionTargets) {
216
+ await unlinkIfPresent(target.next);
217
+ await unlinkIfPresent(target.restore);
218
+ await unlinkIfPresent(target.backup);
219
+ }
220
+ await unlinkIfPresent(journalNextPath);
221
+ await unlinkIfPresent(journalPath);
222
+ try {
223
+ await rmdir(transactionPath);
224
+ } catch (error) {
225
+ if (error?.code !== 'ENOENT') throw error;
226
+ }
227
+ }
228
+
229
+ async function restorePreparedTransaction() {
230
+ for (const target of transactionTargets) {
231
+ if (!await exists(target.backup)) {
232
+ throw new Error(`Recovery backup is missing for ${target.label}`);
233
+ }
234
+ await assertRegularFile(target.backup, `Recovery backup for ${target.label}`);
235
+ const backup = await readFile(target.backup);
236
+ const current = await readFile(target.path).catch((error) => {
237
+ if (error?.code === 'ENOENT') return null;
238
+ throw error;
239
+ });
240
+ if (current !== null && current.equals(backup)) continue;
241
+ await unlinkIfPresent(target.restore);
242
+ const metadata = await lstat(target.backup);
243
+ await writeDurableNew(target.restore, backup, metadata.mode);
244
+ await rename(target.restore, target.path);
245
+ }
246
+ }
247
+
248
+ async function recoverVersionTransaction() {
249
+ if (!await exists(transactionPath)) return null;
250
+ await assertTransactionDirectory();
251
+ await assertKnownTransactionArtifacts();
252
+
253
+ const journal = await readJournal();
254
+ if (journal === null) {
255
+ const artifacts = await readdir(transactionPath);
256
+ await cleanupTransaction();
257
+ return artifacts.length === 0 ? 'empty' : 'staging';
258
+ }
259
+
260
+ if (journal.state === 'prepared') {
261
+ await restorePreparedTransaction();
262
+ }
263
+ if (journal.state === 'committed') {
264
+ for (const target of transactionTargets) {
265
+ await assertRegularFile(target.path, target.label);
266
+ }
267
+ }
268
+ await cleanupTransaction();
269
+ return journal.state;
270
+ }
271
+
272
+ async function assertNoPendingTransaction() {
273
+ if (await exists(transactionPath)) {
274
+ throw new Error(
275
+ 'An interrupted version transaction is present; ensure no other version command is running, then run `npm run version:recover`',
276
+ );
277
+ }
278
+ }
279
+
280
+ async function jsonWithReplacedVersion(file, label, currentVersion, nextVersion) {
281
+ const source = await readFile(file, 'utf8');
282
+ const current = JSON.stringify(currentVersion);
283
+ const matches = source.match(
284
+ new RegExp(`^ "version"\\s*:\\s*${escapeRegExp(current)}`, 'gm'),
285
+ ) ?? [];
286
+ if (matches.length !== 1) {
287
+ throw new Error(
288
+ `${label} must contain exactly one top-level version matching ${current}`,
289
+ );
290
+ }
291
+ return source.replace(
292
+ new RegExp(`^( "version"\\s*:\\s*)${escapeRegExp(current)}`, 'm'),
293
+ `$1${JSON.stringify(nextVersion)}`,
294
+ );
295
+ }
296
+
297
+ function releaseHeadingProblem(changelog, version) {
298
+ const releaseHeading = new RegExp(
299
+ `^## ${escapeRegExp(version)} - \\d{4}-\\d{2}-\\d{2}$`,
300
+ 'gm',
301
+ );
302
+ const matches = changelog.match(releaseHeading) ?? [];
303
+ return matches.length === 1
304
+ ? null
305
+ : `CHANGELOG.md must have exactly one dated release heading for ${version}`;
306
+ }
307
+
308
+ function metadataProblems(packageManifest, capabilities, changelog = null) {
309
+ const problems = [];
310
+ const version = packageManifest.version;
311
+ if (packageManifest.name !== expectedPackageName) {
312
+ problems.push(`package.json name must be ${JSON.stringify(expectedPackageName)}`);
313
+ }
314
+ if (typeof version !== 'string' || !semverPattern.test(version)) {
315
+ problems.push(`package.json has invalid SemVer version ${JSON.stringify(version)}`);
316
+ }
317
+ if (capabilities.implementation !== expectedPackageName) {
318
+ problems.push(
319
+ `docs/capabilities.json implementation must be ${JSON.stringify(expectedPackageName)}`,
320
+ );
321
+ }
322
+ if (capabilities.version !== version) {
323
+ problems.push(
324
+ `docs/capabilities.json version ${JSON.stringify(capabilities.version)} does not match package version ${JSON.stringify(version)}`,
325
+ );
326
+ }
327
+ if (changelog !== null && typeof version === 'string') {
328
+ const problem = releaseHeadingProblem(changelog, version);
329
+ if (problem !== null) problems.push(problem);
330
+ }
331
+ return problems;
332
+ }
333
+
334
+ async function loadMetadata({ includeChangelog }) {
335
+ const [packageManifest, capabilities, changelog] = await Promise.all([
336
+ readJson(packagePath, 'package.json'),
337
+ readJson(capabilitiesPath, 'docs/capabilities.json'),
338
+ includeChangelog
339
+ ? assertRegularFile(changelogPath, 'CHANGELOG.md').then(() => readFile(changelogPath, 'utf8'))
340
+ : Promise.resolve(null),
341
+ ]);
342
+ return { packageManifest, capabilities, changelog };
343
+ }
344
+
345
+ async function checkVersion() {
346
+ await assertNoPendingTransaction();
347
+ const metadata = await loadMetadata({ includeChangelog: true });
348
+ const problems = metadataProblems(
349
+ metadata.packageManifest,
350
+ metadata.capabilities,
351
+ metadata.changelog,
352
+ );
353
+ await Promise.all([
354
+ jsonWithReplacedVersion(
355
+ packagePath,
356
+ 'package.json',
357
+ metadata.packageManifest.version,
358
+ metadata.packageManifest.version,
359
+ ),
360
+ jsonWithReplacedVersion(
361
+ capabilitiesPath,
362
+ 'docs/capabilities.json',
363
+ metadata.capabilities.version,
364
+ metadata.capabilities.version,
365
+ ),
366
+ ]).catch((error) => problems.push(errorMessage(error)));
367
+ if (problems.length > 0) throw new Error(problems.join('; '));
368
+ console.log(
369
+ `Version consistency passed: ${metadata.packageManifest.name}@${metadata.packageManifest.version}`,
370
+ );
371
+ }
372
+
373
+ async function writeVersionTransaction(updates) {
374
+ try {
375
+ await mkdir(transactionPath, { mode: 0o700 });
376
+ } catch (error) {
377
+ if (error?.code === 'EEXIST') {
378
+ throw new Error(
379
+ 'A version transaction is already present; ensure no other version command is running, then run `npm run version:recover`',
380
+ );
381
+ }
382
+ throw error;
383
+ }
384
+
385
+ try {
386
+ await writeJournal('staging');
387
+ for (const [index, target] of transactionTargets.entries()) {
388
+ const metadata = await assertRegularFile(target.path, target.label);
389
+ await writeDurableNew(target.next, updates[index], metadata.mode);
390
+ await copyFile(target.path, target.backup, fsConstants.COPYFILE_EXCL);
391
+ await syncFile(target.backup);
392
+ }
393
+ await writeJournal('prepared');
394
+ for (const target of transactionTargets) {
395
+ await rename(target.next, target.path);
396
+ }
397
+ await writeJournal('committed');
398
+ await cleanupTransaction();
399
+ } catch (error) {
400
+ let recoveredState;
401
+ try {
402
+ recoveredState = await recoverVersionTransaction();
403
+ } catch (recoveryError) {
404
+ throw new Error(
405
+ `${errorMessage(error)}; automatic recovery failed: ${errorMessage(recoveryError)}`,
406
+ );
407
+ }
408
+ if (recoveredState === 'committed') return;
409
+ throw new Error(`${errorMessage(error)}; original version files were restored`);
410
+ }
411
+ }
412
+
413
+ async function setVersion(version) {
414
+ if (!semverPattern.test(version)) {
415
+ throw new Error(
416
+ `Expected a SemVer version without a leading "v", received ${JSON.stringify(version)}`,
417
+ );
418
+ }
419
+ await assertNoPendingTransaction();
420
+ const metadata = await loadMetadata({ includeChangelog: true });
421
+ const problems = metadataProblems(
422
+ metadata.packageManifest,
423
+ metadata.capabilities,
424
+ metadata.changelog,
425
+ );
426
+ if (problems.length > 0) {
427
+ throw new Error(`Refusing to update inconsistent release metadata: ${problems.join('; ')}`);
428
+ }
429
+ if (metadata.packageManifest.version === version) {
430
+ console.log(`${expectedPackageName} release metadata is already ${version}.`);
431
+ return;
432
+ }
433
+ if (compareSemver(version, metadata.packageManifest.version) <= 0) {
434
+ throw new Error(
435
+ `New version ${version} must have higher SemVer precedence than current version ${metadata.packageManifest.version}`,
436
+ );
437
+ }
438
+
439
+ const updates = await Promise.all([
440
+ jsonWithReplacedVersion(
441
+ packagePath,
442
+ 'package.json',
443
+ metadata.packageManifest.version,
444
+ version,
445
+ ),
446
+ jsonWithReplacedVersion(
447
+ capabilitiesPath,
448
+ 'docs/capabilities.json',
449
+ metadata.capabilities.version,
450
+ version,
451
+ ),
452
+ ]);
453
+ await writeVersionTransaction(updates);
454
+ console.log(`Set ${expectedPackageName} release metadata to ${version}.`);
455
+ console.log('Add the dated CHANGELOG.md heading, then run `npm run version:check`.');
456
+ }
457
+
458
+ async function recoverVersion() {
459
+ const state = await recoverVersionTransaction();
460
+ if (state === null) {
461
+ console.log('No interrupted version transaction was found.');
462
+ return;
463
+ }
464
+ const outcome = state === 'committed'
465
+ ? 'kept the committed version files'
466
+ : 'restored the pre-transaction version files';
467
+ console.log(`Recovered version transaction (${state}); ${outcome}.`);
468
+ }
469
+
470
+ const [command, ...args] = process.argv.slice(2);
471
+
472
+ try {
473
+ if (command === 'check' && args.length === 0) {
474
+ await checkVersion();
475
+ } else if (command === 'set' && args.length === 1) {
476
+ await setVersion(args[0]);
477
+ } else if (command === 'recover' && args.length === 0) {
478
+ await recoverVersion();
479
+ } else {
480
+ throw new Error(
481
+ 'Usage: node scripts/version.mjs check | set <version> | recover',
482
+ );
483
+ }
484
+ } catch (error) {
485
+ fail(errorMessage(error));
486
+ }
@@ -41,11 +41,16 @@ export async function evaluateQueryForWorkbench({
41
41
  valueSemantics = '',
42
42
  budget = {},
43
43
  }) {
44
- const namespaceResult = sourceKind === 'json'
45
- ? namespaceFromJsonSource(source)
46
- : sourceKind === 'telex'
47
- ? await namespaceFromTelexSource(source)
48
- : await namespaceFromAeonSource(source);
44
+ let namespaceResult;
45
+ if (sourceKind === 'json') {
46
+ namespaceResult = namespaceFromJsonSource(source);
47
+ } else if (sourceKind === 'telex') {
48
+ namespaceResult = await namespaceFromTelexSource(source);
49
+ } else if (sourceKind === 'film') {
50
+ namespaceResult = await namespaceFromFilmSource(source);
51
+ } else {
52
+ namespaceResult = await namespaceFromAeonSource(source);
53
+ }
49
54
 
50
55
  if (!namespaceResult.ok) {
51
56
  return namespaceResult;
@@ -279,6 +284,103 @@ export async function namespaceFromTelexSource(source) {
279
284
  }
280
285
  }
281
286
 
287
+ /**
288
+ * Build a SANSA namespace from a completely validated Film v1 byte stream.
289
+ * Film and Telex share the same portable record adapter; only their physical
290
+ * reader differs. No Film mutation or writer surface is implied.
291
+ */
292
+ export async function namespaceFromFilmSource(source) {
293
+ const loaded = await loadAeonAesRuntime();
294
+ if (!loaded.ok) {
295
+ const errors = [{
296
+ code: 'SANSA_QUERY_WORKBENCH_FILM_RUNTIME_UNAVAILABLE',
297
+ message: loaded.message,
298
+ }];
299
+ return {
300
+ ok: false,
301
+ mode: 'evaluate',
302
+ sourceKind: 'film',
303
+ text: renderDiagnosticText(errors),
304
+ errors,
305
+ };
306
+ }
307
+
308
+ const aes = loaded.module;
309
+ if (typeof aes.decodeFilm !== 'function') {
310
+ const errors = [{
311
+ code: 'SANSA_QUERY_WORKBENCH_FILM_RUNTIME_UNAVAILABLE',
312
+ message: 'The loaded @altopelago/aeon-aes runtime does not expose a Film v1 reader.',
313
+ }];
314
+ return {
315
+ ok: false,
316
+ mode: 'evaluate',
317
+ sourceKind: 'film',
318
+ text: renderDiagnosticText(errors),
319
+ errors,
320
+ };
321
+ }
322
+ let decoded;
323
+ try {
324
+ decoded = aes.decodeFilm(source);
325
+ } catch (error) {
326
+ const errors = [{
327
+ code: error?.code ?? 'FILM_DECODE_ERROR',
328
+ message: error instanceof Error ? error.message : String(error),
329
+ ...(Number.isInteger(error?.offset) ? { offset: error.offset } : {}),
330
+ ...(Number.isInteger(error?.record) ? { record: error.record } : {}),
331
+ }];
332
+ return {
333
+ ok: false,
334
+ mode: 'evaluate',
335
+ sourceKind: 'film',
336
+ text: renderDiagnosticText(errors),
337
+ errors,
338
+ };
339
+ }
340
+
341
+ if (decoded.profile !== aes.COMPLETE_AES_PROFILE) {
342
+ const errors = [{
343
+ code: 'SANSA_QUERY_WORKBENCH_PARTIAL_AES_UNSUPPORTED',
344
+ message: `SANSA query navigation requires '${aes.COMPLETE_AES_PROFILE}' when no external namespace state is supplied.`,
345
+ }];
346
+ return {
347
+ ok: false,
348
+ mode: 'evaluate',
349
+ sourceKind: 'film',
350
+ text: renderDiagnosticText(errors),
351
+ errors,
352
+ };
353
+ }
354
+
355
+ try {
356
+ return {
357
+ ok: true,
358
+ namespace: buildNamespaceFromPortableRecords(decoded.records),
359
+ diagnostics: [],
360
+ film: {
361
+ version: aes.FILM_VERSION,
362
+ profile: decoded.profile,
363
+ profileExplicit: decoded.profileExplicit,
364
+ projection: decoded.projection,
365
+ projectionExplicit: decoded.projectionExplicit,
366
+ records: decoded.records,
367
+ },
368
+ };
369
+ } catch (error) {
370
+ const errors = [{
371
+ code: 'SANSA_QUERY_WORKBENCH_INVALID_PORTABLE_AES',
372
+ message: error instanceof Error ? error.message : String(error),
373
+ }];
374
+ return {
375
+ ok: false,
376
+ mode: 'evaluate',
377
+ sourceKind: 'film',
378
+ text: renderDiagnosticText(errors),
379
+ errors,
380
+ };
381
+ }
382
+ }
383
+
282
384
  async function mountParamsLocalSpace(namespace, paramsSource) {
283
385
  if (String(paramsSource).trim().length === 0) {
284
386
  return { ok: true, namespace, diagnostics: [] };