@volter/twin-standard 1.0.148 → 1.0.150

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 (103) hide show
  1. package/README.md +12 -3
  2. package/client-sdks/bun.lock +0 -32
  3. package/client-sdks/package.json +0 -2
  4. package/dist/client-sdks/bun.lock +0 -32
  5. package/dist/client-sdks/package.json +0 -2
  6. package/dist/src/assessment.d.ts +6 -4
  7. package/dist/src/assessment.js +2 -1
  8. package/dist/src/cli.js +21 -6
  9. package/dist/src/clients/harness.d.ts +3 -1
  10. package/dist/src/clients/harness.js +4 -2
  11. package/dist/src/clients/jira.d.ts +2 -0
  12. package/dist/src/clients/jira.js +71 -0
  13. package/dist/src/clients/polar.d.ts +2 -0
  14. package/dist/src/clients/polar.js +73 -0
  15. package/dist/src/clients/resend.js +38 -0
  16. package/dist/src/clients/run.js +1 -1
  17. package/dist/src/clients/sentry.js +1 -26
  18. package/dist/src/clients/smtp.d.ts +2 -0
  19. package/dist/src/clients/smtp.js +54 -0
  20. package/dist/src/clients/stripe.js +1 -1
  21. package/dist/src/clients/volteridentity.js +4 -3
  22. package/dist/src/clients/x.d.ts +2 -0
  23. package/dist/src/clients/x.js +64 -0
  24. package/dist/src/conformance.d.ts +4 -3
  25. package/dist/src/conformance.js +293 -8
  26. package/dist/src/consumer.js +5 -1
  27. package/dist/src/create-pack.d.ts +5 -0
  28. package/dist/src/create-pack.js +38 -4
  29. package/dist/src/derive.js +21 -13
  30. package/dist/src/gate.d.ts +1 -0
  31. package/dist/src/gate.js +47 -4
  32. package/dist/src/grade.d.ts +1 -0
  33. package/dist/src/grade.js +1 -1
  34. package/dist/src/pack-facts.d.ts +9 -1
  35. package/dist/src/pack-facts.js +11 -2
  36. package/dist/src/pack-files.js +2 -1
  37. package/dist/src/protocol-3.js +40 -6
  38. package/dist/src/spec-ir-client.js +3 -2
  39. package/dist/src/spec-ir-commands.d.ts +73 -0
  40. package/dist/src/spec-ir-commands.js +63 -0
  41. package/dist/src/spec-ir.d.ts +2 -0
  42. package/dist/src/spec-ir.js +43 -0
  43. package/dist/src/tools/judge-brief.d.ts +1 -0
  44. package/dist/src/tools/judge-brief.js +67 -0
  45. package/dist/src/tools/life-coverage-walk.d.ts +2 -0
  46. package/dist/src/tools/life-coverage-walk.js +220 -0
  47. package/dist/src/tools/life-coverage.d.ts +2 -0
  48. package/dist/src/tools/life-coverage.js +271 -0
  49. package/dist/src/tools/packs-root.d.ts +9 -0
  50. package/dist/src/tools/packs-root.js +17 -0
  51. package/dist/src/tools/run-tool.d.ts +1 -0
  52. package/dist/src/tools/run-tool.js +18 -0
  53. package/dist/src/tools/score-pack.d.ts +2 -0
  54. package/dist/src/tools/score-pack.js +264 -0
  55. package/dist/src/tools/vendor-examples.d.ts +2 -0
  56. package/dist/src/tools/vendor-examples.js +1493 -0
  57. package/dist/src/types.d.ts +2 -0
  58. package/dist/src/verdict.js +1 -1
  59. package/dist/src/walk/behavior-journey.d.ts +6 -0
  60. package/dist/src/walk/behavior-journey.js +108 -8
  61. package/dist/src/walk/journey-kit.d.ts +23 -1
  62. package/dist/src/walk/journey-kit.js +7 -2
  63. package/dist/src/walk/rendered-scalar.d.ts +3 -0
  64. package/dist/src/walk/rendered-scalar.js +23 -0
  65. package/dist/src/walk/sse-example.js +45 -0
  66. package/package.json +2 -2
  67. package/src/assessment.ts +2 -1
  68. package/src/cli.ts +15 -2
  69. package/src/clients/harness.ts +4 -2
  70. package/src/clients/jira.ts +73 -0
  71. package/src/clients/polar.ts +73 -0
  72. package/src/clients/resend.ts +32 -0
  73. package/src/clients/run.ts +2 -2
  74. package/src/clients/sentry.ts +1 -25
  75. package/src/clients/smtp.ts +49 -0
  76. package/src/clients/stripe.ts +1 -1
  77. package/src/clients/volteridentity.ts +4 -3
  78. package/src/clients/x.ts +66 -0
  79. package/src/conformance.ts +226 -10
  80. package/src/consumer.ts +5 -1
  81. package/src/create-pack.ts +35 -5
  82. package/src/derive.ts +21 -14
  83. package/src/gate.ts +40 -6
  84. package/src/grade.ts +2 -2
  85. package/src/pack-facts.ts +10 -3
  86. package/src/pack-files.ts +2 -1
  87. package/src/protocol-3.ts +32 -6
  88. package/src/spec-ir-client.ts +3 -2
  89. package/src/spec-ir-commands.ts +81 -0
  90. package/src/spec-ir.ts +31 -0
  91. package/src/tools/judge-brief.ts +63 -0
  92. package/src/tools/life-coverage-walk.ts +173 -0
  93. package/src/tools/life-coverage.ts +237 -0
  94. package/src/tools/packs-root.ts +21 -0
  95. package/src/tools/run-tool.ts +10 -0
  96. package/src/tools/score-pack.ts +244 -0
  97. package/src/tools/vendor-examples.ts +1250 -0
  98. package/src/types.ts +2 -0
  99. package/src/verdict.ts +1 -1
  100. package/src/walk/behavior-journey.ts +65 -4
  101. package/src/walk/journey-kit.ts +21 -3
  102. package/src/walk/rendered-scalar.ts +17 -0
  103. package/src/walk/sse-example.ts +37 -0
@@ -0,0 +1,220 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ import { parseExactJson } from '@volter/world-core/exact-json';
10
+ // The walks `life-coverage.ts` measures: one pack's customer life, walked with its beats on
11
+ // the in-memory World, and the vendor's published examples replayed (journeys/vendor-examples.json, vendor-examples.ts)
12
+ // on a World of their own: a line only the vendor's own example reaches is reached for the reason the vendor gives. Bun measures coverage only inside `bun test`, so the measurement runs the walk through
13
+ // a test file life-coverage writes, which registers them (coverageWalks), and reads the lcov it leaves; the walk holding
14
+ // is its precondition, not what it measures. This module is no test file itself, so a published package holds it.
15
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ import { listActions, observeTransitions, stateOf } from '@volter/world-core/runtime';
18
+ import { inMemoryWorld, walk, usePacks } from "../walk/behavior-journey.js";
19
+ import { lanesOf, shapeChecker } from "../walk/shape.js";
20
+ import { sharingLanesIn } from "../lanes.js";
21
+ /** Registers, in the `bun test` run that imports it, the walks of `vendor` in the pack repository at `PACKS`. */
22
+ export async function coverageWalks(PACKS, vendor) {
23
+ const { expect, test } = await import('bun:test');
24
+ usePacks(PACKS);
25
+ const sharingLanes = (v) => (v.includes('/') ? [] : sharingLanesIn(join(PACKS, v), v));
26
+ const journeys = join(PACKS, vendor, 'journeys');
27
+ const walks = [{ file: 'customer-life.json', beats: true }, { file: 'vendor-examples.json', beats: false }].filter((w) => existsSync(join(journeys, w.file)));
28
+ const seen = new Set();
29
+ const undeclared = new Set();
30
+ for (const [n, w] of walks.entries())
31
+ test(`${vendor}: ${w.file} walks`, async () => {
32
+ const life = parseExactJson(readFileSync(join(journeys, w.file), 'utf8'));
33
+ const world = inMemoryWorld(`coverage-${vendor}-${n}`);
34
+ const failures = [];
35
+ // each declared transition the life moved through or was refused by, named by resource, field and its place
36
+ const { manifest } = (await import(__rewriteRelativeImportExtension(join(PACKS, vendor, 'src', 'manifest.ts'))));
37
+ // the lanes over the vendor's state its serve factory serves are walked by this life, their machines with the vendor's
38
+ // ("Pack layout"); two manifests naming one resource's field would collide in the keys below, so that refuses
39
+ const laneManifests = await Promise.all(sharingLanes(vendor).map(async (l) => (await import(__rewriteRelativeImportExtension(join(PACKS, vendor, l, 'src', 'manifest.ts')))).manifest));
40
+ // a vendor of lanes' root (a VendorManifest) declares no resources of its own: its lanes do
41
+ const allResources = [manifest, ...laneManifests].flatMap((mf) => Object.entries(mf.resources ?? {}));
42
+ const machines = new Map();
43
+ for (const [resource, decl] of allResources)
44
+ for (const [field, machine] of Object.entries(decl.state ?? {})) {
45
+ const name = `${resource}.${field}`;
46
+ const previous = machines.get(name);
47
+ // Lanes sharing one vendor import the same state declaration; distinct declarations still collide.
48
+ if (previous && previous !== machine)
49
+ throw new Error(`${vendor}: ${name} is declared by two manifests (the vendor's and a lane's)`);
50
+ machines.set(name, machine);
51
+ }
52
+ const where = new Map();
53
+ for (const mf of [manifest, ...laneManifests])
54
+ for (const [resource, decl] of Object.entries(mf.resources ?? {})) {
55
+ for (const [field, m] of Object.entries(decl.state ?? {}))
56
+ m.transitions.forEach((t, i) => {
57
+ const place = { at: `${resource}.${field}#${i}`, field, type: decl.storedAs ?? resource, service: mf.service ?? mf.vendor };
58
+ const places = where.get(t) ?? [];
59
+ if (!places.some((p) => p.at === place.at && p.type === place.type && p.service === place.service))
60
+ where.set(t, [...places, place]);
61
+ });
62
+ }
63
+ const moves = new Map();
64
+ const subjectKey = (service, type, id) => JSON.stringify([service, type, id]);
65
+ observeTransitions((_decl, t, outcome, from, entry) => {
66
+ const places = where.get(t) ?? [];
67
+ if (outcome === 'refused') {
68
+ // A failed check on an already committed write is no refusal the application received.
69
+ if (entry)
70
+ return;
71
+ const groups = new Set(places.map((p) => JSON.stringify([p.service, p.type, p.field])));
72
+ if (groups.size === 1)
73
+ for (const p of places)
74
+ seen.add(`${p.at}|refused|${from}`);
75
+ return;
76
+ }
77
+ // a move the machine allowed on a step with no write behind it (a line protocol's session, whose stage is the
78
+ // connection's): reached, as a refusal given is, where its declaration is unambiguous
79
+ if (!entry) {
80
+ const groups = new Set(places.map((p) => JSON.stringify([p.service, p.type, p.field])));
81
+ if (groups.size === 1)
82
+ for (const p of places)
83
+ seen.add(`${p.at}|moved|${from}`);
84
+ return;
85
+ }
86
+ if ((t.actor ?? 'api') !== entry.actor)
87
+ return;
88
+ const { action, field, actor } = entry;
89
+ const matching = places.filter((p) => p.service === action.service && p.type === action.subject.type && p.field === field);
90
+ if (!matching.length)
91
+ return;
92
+ for (const p of matching)
93
+ seen.add(`${p.at}|moved|${from}`);
94
+ const on = moves.get(action.id) ?? [];
95
+ on.push({ transition: t, from, field, actor, subject: subjectKey(action.service, action.subject.type, action.subject.id) });
96
+ moves.set(action.id, on);
97
+ });
98
+ const root = world.root();
99
+ // what each step was answered, by the spec operation it called: a refusal is seen at the wire, whichever code gave it
100
+ const shape = await shapeChecker(join(PACKS, vendor));
101
+ const answered = [];
102
+ try {
103
+ await walk(life, root, failures, { beats: w.beats, hooks: { after: (step, path, answer) => {
104
+ // a line step's refusals are the machine's own (observeTransitions); a request's are read off its answer
105
+ const op = 'method' in step ? shape?.operationOf(step.method, path, { ...(life.headers ?? {}), ...(step.headers ?? {}) })?.op.id : undefined;
106
+ if (op)
107
+ answered.push({ op, text: JSON.stringify(answer.body ?? ''), body: answer.body });
108
+ } } });
109
+ // a declared refusal is reached when a step on its operation was answered with it: its code, or its message
110
+ // up to the first placeholder
111
+ // a code is a value of the answer (X's `89` at errors[].code), never a run of digits inside another value (a token)
112
+ const holds = (value, code) => (value !== null && typeof value === 'object'
113
+ ? Object.values(value).some((v) => holds(v, code))
114
+ : (typeof value === 'string' || typeof value === 'number') && String(value) === code);
115
+ const answers = (a, r) => r.code !== undefined ? holds(a.body, String(r.code)) : a.text.includes(r.message.split('{')[0].trim());
116
+ for (const [resource, decl] of allResources) {
117
+ for (const [field, m] of Object.entries(decl.state ?? {})) {
118
+ m.transitions.forEach((t, i) => {
119
+ if (!t.operation)
120
+ return;
121
+ const on = answered.filter((a) => a.op === t.operation);
122
+ if (t.refusal && on.some((a) => answers(a, t.refusal)))
123
+ seen.add(`${resource}.${field}#${i}|refused|*`);
124
+ for (const [from, r] of Object.entries(t.refusals ?? {}))
125
+ if (on.some((a) => answers(a, r)))
126
+ seen.add(`${resource}.${field}#${i}|refused|${from}`);
127
+ });
128
+ }
129
+ }
130
+ // every change the life made to a declared state field, from the World's log in order: a move is the declared
131
+ // transition that allows it (from its state to the next, by its operation when both name one); a change no
132
+ // transition allows is an undeclared move
133
+ const fieldsOf = new Map();
134
+ for (const mf of [manifest, ...laneManifests])
135
+ for (const [resource, decl] of Object.entries(mf.resources ?? {})) {
136
+ const key = JSON.stringify([mf.service ?? mf.vendor, decl.storedAs ?? resource]);
137
+ for (const [field, m] of Object.entries(decl.state ?? {}))
138
+ fieldsOf.set(key, [...(fieldsOf.get(key) ?? []), [resource, field, m]]);
139
+ }
140
+ const current = new Map();
141
+ // the services the life wrote: the vendor's, or its lanes' (a vendor of lanes' root names none of its own)
142
+ const services = [...new Set([manifest, ...laneManifests].map((mf) => mf.service).filter((x) => typeof x === 'string'))];
143
+ if (!services.length)
144
+ services.push(manifest.vendor);
145
+ for (const a of services.flatMap((service) => listActions(service, root))) {
146
+ if (a.op !== 'set' || !a.fields)
147
+ continue;
148
+ const key = subjectKey(a.service, a.subject.type, a.subject.id);
149
+ const prev = current.get(key);
150
+ const next = { ...(prev ?? {}), ...a.fields };
151
+ current.set(key, next);
152
+ if (!prev)
153
+ continue;
154
+ const opId = typeof a.input?.operationId === 'string' ? a.input.operationId : undefined;
155
+ // resources stored as one type (a response the beta and the GA API both serve) share its fields: a
156
+ // change is declared when any of their machines allows it
157
+ const changed = new Map();
158
+ const valueOf = (row, field) => field.split('.').reduce((value, part) => value && typeof value === 'object' ? value[part] : undefined, row);
159
+ for (const [resource, field, m] of fieldsOf.get(JSON.stringify([a.service, a.subject.type])) ?? []) {
160
+ if (!(field.split('.')[0] in a.fields))
161
+ continue;
162
+ const from = stateOf(m, valueOf(prev, field));
163
+ const to = stateOf(m, valueOf(next, field));
164
+ if (from === to)
165
+ continue;
166
+ const allows = (t, at) => (moves.get(a.id) ?? []).some((move) => move.transition === t && move.from === at && move.field === field && move.actor === (t.actor ?? 'api') &&
167
+ move.subject === subjectKey(a.service, a.subject.type, a.subject.id));
168
+ const i = m.transitions.findIndex((t) => allows(t, from) && (t.to ?? from) === to);
169
+ if (i >= 0)
170
+ seen.add(`${resource}.${field}#${i}|moved|${from}`);
171
+ // one write may carry several declared moves the machine walked (a batch the vendor works from
172
+ // validating through to completed as a read first looks); each step was observed as it was asked
173
+ const reached = new Set([from]);
174
+ for (let grew = true; grew && !reached.has(to);) {
175
+ grew = false;
176
+ for (const at of [...reached])
177
+ for (const t of m.transitions)
178
+ if (allows(t, at) && t.to && !reached.has(t.to)) {
179
+ reached.add(t.to);
180
+ grew = true;
181
+ }
182
+ }
183
+ const was = changed.get(field);
184
+ changed.set(field, { declared: (was?.declared ?? false) || reached.has(to), name: was?.name ?? `${resource}.${field}: ${from} → ${to} by ${opId ?? a.operation ?? '(unnamed)'}` });
185
+ }
186
+ for (const c of changed.values())
187
+ if (!c.declared)
188
+ undeclared.add(c.name);
189
+ }
190
+ }
191
+ finally {
192
+ world.restore();
193
+ observeTransitions(undefined);
194
+ }
195
+ // each walk adds what it reached; the last one written holds them all
196
+ if (process.env.LIFE_TRANSITIONS)
197
+ writeFileSync(process.env.LIFE_TRANSITIONS, JSON.stringify({ seen: [...seen].sort(), undeclared: [...undeclared].sort() }));
198
+ expect(failures.filter((f) => f.beat !== 'SHAPE')).toEqual([]);
199
+ // a walk's time grows with its steps and the state they build (Stripe's 609 example steps took 70 s uninstrumented,
200
+ // measured 2026-09-26, each request catching the World up over every row it holds)
201
+ }, 180_000);
202
+ // A pack's lanes reach its code through the pack's router (a management-API life making a database branch the data
203
+ // plane then serves): their lives and examples, walked here too, count toward the pack's code, not its state logic
204
+ // (each lane's machines are its own, measured when the lane is). A lane is measured alone, with no lanes of its own.
205
+ const PACK = join(PACKS, vendor);
206
+ const laneWalks = vendor.includes('/') ? [] : lanesOf(PACK).flatMap((dir) => [{ file: 'customer-life.json', beats: true }, { file: 'vendor-examples.json', beats: false }]
207
+ .filter((w) => existsSync(join(dir, 'journeys', w.file))).map((w) => ({ ...w, path: join(dir, 'journeys', w.file), lane: dir.split('/').slice(-2).join('/') })));
208
+ for (const [n, w] of laneWalks.entries())
209
+ test(`${vendor}: ${w.lane} ${w.file} walks for the pack's code`, async () => {
210
+ const world = inMemoryWorld(`coverage-${vendor}-lane-${n}`);
211
+ const failures = [];
212
+ try {
213
+ await walk(parseExactJson(readFileSync(w.path, 'utf8')), world.root(), failures, { beats: w.beats });
214
+ }
215
+ finally {
216
+ world.restore();
217
+ }
218
+ expect(failures.filter((f) => f.beat !== 'SHAPE')).toEqual([]);
219
+ }, 180_000);
220
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};
@@ -0,0 +1,271 @@
1
+ #!/usr/bin/env bun
2
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
3
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
4
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
5
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
6
+ });
7
+ }
8
+ return path;
9
+ };
10
+ // life-coverage — how much of a pack's hand-written code and declared state logic its customer life and its vendor's
11
+ // published examples (vendor-examples.ts) reach
12
+ // (docs/contributing/architecture.md, "Protocol 3", Coverage). Hand-written is every file under the pack's src/ on disk
13
+ // (its sharing lanes' too), but for the generated core (src/generated/) and the command line (src/cli.ts), which no
14
+ // World's fetch runs; a file of data (seed.ts, budget.ts) is in scope and has nothing to reach. State logic is every declared transition and every refusal its guard gives, read from the World's
15
+ // log and the answers. The standard is all of it: each item is reached, or recorded in journeys/unreachable.json with
16
+ // the reason no World reaches it; what is neither is missing, and a pack is done when nothing is missing.
17
+ //
18
+ // The instrument's limits, measured on Bun 1.3.10 (`bun test --coverage --coverage-reporter=lcov`): a line is counted
19
+ // by its first statement, so both sides of `a ? b : c` count once either runs; the last line of a block that never ran
20
+ // can read as run once (a function `if (x > 0) { return x; } const y = x * 7; return y - 1;` called with 5 marked
21
+ // `return y - 1` hit while `const y` read 0), so a lone unrun statement at a block's end can be counted reached; and a
22
+ // function declared below module-scope constants it follows was seen to mark every line above it unrun (aws's
23
+ // schedule.ts, until the function moved above them). A function that never runs still reads 0 on its first line, so
24
+ // an unreached function is never counted reached.
25
+ //
26
+ // Whether a recorded declaration ran in part is printed as advice, never counted: a `function`'s first line ran, or a
27
+ // body line before its last did, but measured on planetscale (life, 2026-09-26) an arrow constant read 0 on its first
28
+ // line and 140 on a property line inside it (SHOW_TABLES_FIELD, which nothing in that life calls), while arrow
29
+ // functions every UPDATE and GROUP BY runs (targetRows, computeAggregate) read 0 on their first line. The judge reads
30
+ // the advice; a record whose declaration did run in part is split, its unrun branch recorded as its own function.
31
+ //
32
+ // A walk that fails, and a file in scope (the pack's src/ on disk, its sharing lanes' too) that declares code yet
33
+ // measures no line, stop the measurement: neither is a file with nothing to reach.
34
+ //
35
+ // Usage: twin-standard coverage <vendor> [--write | --out <file>] [--prune] (from the pack repository's root; twin-world's
36
+ // bun scripts/life-coverage.ts runs the same) (--prune removes the stale records) (--write keeps journeys/coverage.json)
37
+ import { spawnSync } from 'node:child_process';
38
+ import ts from 'typescript';
39
+ import { existsSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
40
+ import { tmpdir } from 'node:os';
41
+ import { join, normalize } from 'node:path';
42
+ import { functionIndex, stateCoverage } from "../walk/journey-kit.js";
43
+ import { sharingLanesIn } from "../lanes.js";
44
+ import { packsRoot, toolPath } from "./packs-root.js";
45
+ const PACKS = packsRoot();
46
+ const sharingLanes = (v) => (v.includes('/') ? [] : sharingLanesIn(join(PACKS, v), v));
47
+ const vendor = process.argv[2];
48
+ if (!vendor || vendor.startsWith('-')) {
49
+ console.error('usage: twin-standard coverage <vendor> [--write | --out <file>] [--prune] (from the pack repository\'s root)');
50
+ process.exit(1);
51
+ }
52
+ const PKG = join(PACKS, vendor);
53
+ // An unsuccessful current walk replaces stale retained coverage with explicit failed measurement evidence.
54
+ const invalidMeasurement = (error) => {
55
+ const outAt = process.argv.includes('--out') ? process.argv[process.argv.indexOf('--out') + 1] : undefined;
56
+ if (process.argv.includes('--write') || outAt)
57
+ writeFileSync(outAt ?? join(PKG, 'journeys', 'coverage.json'), `${JSON.stringify({ vendor, measured: false, error }, null, 2)}\n`);
58
+ console.error(error);
59
+ process.exit(1);
60
+ };
61
+ // a lane of a multi-API vendor (`aws/secretsmanager`) is named with a slash
62
+ const dir = mkdtempSync(join(tmpdir(), `life-coverage-${vendor.replaceAll('/', '-')}-`));
63
+ const transitionsPath = join(dir, 'transitions.json');
64
+ // Bun measures coverage only inside `bun test`: a test file of the scratch directory's registers the walks
65
+ // (life-coverage-walk.ts), which a published package holds as a module, never as a test file of its own
66
+ const walkTest = join(dir, 'life-coverage.walk.test.ts');
67
+ writeFileSync(walkTest, `import { coverageWalks } from ${JSON.stringify(toolPath('life-coverage-walk'))};\nawait coverageWalks(${JSON.stringify(PACKS)}, ${JSON.stringify(vendor)});\n`);
68
+ const child = spawnSync(process.execPath, ['test', '--coverage', '--coverage-reporter=lcov', `--coverage-dir=${dir}`, walkTest], {
69
+ // run from the pack repository, so the pack's files lie under the walk's directory and bun measures them
70
+ cwd: PACKS, stdio: ['ignore', 'ignore', 'inherit'], env: { ...process.env, LIFE_TRANSITIONS: transitionsPath },
71
+ });
72
+ const lcovPath = join(dir, 'lcov.info');
73
+ if (!existsSync(lcovPath)) {
74
+ invalidMeasurement(`${vendor}: the walk left no coverage`);
75
+ }
76
+ // a walk that failed measured only what loaded before it failed: its coverage is no measure of the pack (a vendor of
77
+ // lanes' walk once threw before its fetch loaded, and the manifests alone read as all of its code, all of it run)
78
+ if (child.status !== 0) {
79
+ invalidMeasurement(`${vendor}: the coverage walk failed (journey instrument exited ${child.status}); its coverage measures nothing`);
80
+ }
81
+ /** Why no World reaches it (architecture, "Coverage"), each record naming one in `world`: a record
82
+ * naming none, or another, is no exemption and its code counts as missing. */
83
+ const WORLDS = new Set(['host-process', 'door', 'configured-otherwise', 'hostile-peer', 'bug-guard', 'vendor-backed', 'sealed-refusal']);
84
+ const ruled = (u) => u.world !== undefined && WORLDS.has(u.world);
85
+ const unreachablePath = join(PKG, 'journeys', 'unreachable.json');
86
+ const unreachable = existsSync(unreachablePath) ? JSON.parse(readFileSync(unreachablePath, 'utf8')) : {};
87
+ const recordedCode = (file, fn) => (unreachable.code ?? []).some((u) => ruled(u) && u.file === file && u.declarations.includes(fn ?? '(module scope)'));
88
+ const recordedState = (item) => (unreachable.state ?? []).some((u) => ruled(u) && u.item === item);
89
+ // ── code ─────────────────────────────────────────────────────────────────────────────────────
90
+ const lcov = readFileSync(lcovPath, 'utf8');
91
+ const prefix = `${vendor}/src/`;
92
+ // the lanes over this vendor's state that its serve factory serves ("Pack layout"): their code and states are this
93
+ // life's to reach, measured here beside the vendor's own
94
+ const sharedLanes = sharingLanes(vendor);
95
+ const lanePrefixes = sharedLanes.map((l) => `${vendor}/${l}/src/`);
96
+ const inScope = (f) => [prefix, ...lanePrefixes].find((p) => f.startsWith(p) && !f.startsWith(`${p}generated/`));
97
+ // the scope is the pack's hand-written files ON DISK (its src/ and its sharing lanes'), never the files the walk happened to
98
+ // load: a screen not wired into fetch.ts or a family missing from the handler map is in scope and measures nothing
99
+ const onDisk = (rel) => {
100
+ const at = join(PACKS, rel);
101
+ if (!existsSync(at))
102
+ return [];
103
+ return readdirSync(at, { withFileTypes: true }).flatMap((e) => (e.isDirectory() ? onDisk(`${rel}${e.name}/`) : /\.tsx?$/.test(e.name) ? [`${rel}${e.name}`] : []));
104
+ };
105
+ const handWritten = [prefix, ...lanePrefixes].flatMap(onDisk)
106
+ .filter((f) => inScope(f) !== undefined && !/\.(test|uitest)\.tsx?$/.test(f) && !/\.d\.ts$/.test(f))
107
+ // the command line a person runs the twin with (a unit's src/cli.ts) is code no World's fetch runs; everything else is
108
+ // in scope, a unit's budget.ts (D8's data) and seed.ts (data) passing as data below
109
+ .filter((f) => !/^[^/]+(?:\/[^/]+)?\/src\/cli\.ts$/.test(f));
110
+ const readSource = (file) => (existsSync(join(PACKS, file)) ? readFileSync(join(PACKS, file), 'utf8') : undefined);
111
+ const measuredFiles = stateCoverage(lcov, handWritten, readSource);
112
+ // a file in scope that measures no line is not dropped: one that declares code and reads 0 lines found was not loaded by
113
+ // the walk or not measured, an error of the measurement, never a file with nothing to reach. Data is not code: a module
114
+ // of only imports, re-exports, types and constants whose values are data (literals, with no function, call, `new`,
115
+ // accessor or tagged template in them, as the grade holds a manifest's data: twin-standard's manifest-data) has nothing a
116
+ // walk could run, loaded or not: `semantics/seed.ts`'s `seed: SeedCall[]`, which `volter-world init` copies into a World
117
+ // and sends as requests, never a module the twin's fetch loads. A function, a class, an enum or any other statement is
118
+ // code, so no handler hides as data.
119
+ const isCode = (n) => ts.isCallExpression(n) || ts.isNewExpression(n) || ts.isArrowFunction(n) || ts.isFunctionExpression(n)
120
+ || ts.isClassExpression(n) || ts.isTaggedTemplateExpression(n) || ts.isGetAccessor(n) || ts.isSetAccessor(n) || ts.isMethodDeclaration(n)
121
+ || ts.forEachChild(n, isCode) === true;
122
+ const declaresCode = (file, text) => ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true, file.endsWith('.tsx') ? ts.ScriptKind.TSX : ts.ScriptKind.TS).statements.some((st) => {
123
+ if (ts.isImportDeclaration(st) || ts.isImportEqualsDeclaration(st) || ts.isTypeAliasDeclaration(st) || ts.isInterfaceDeclaration(st))
124
+ return false;
125
+ if (ts.isExportDeclaration(st))
126
+ return false;
127
+ // an ambient declaration (`declare const x: T`) is a type, nothing that runs
128
+ if (ts.canHaveModifiers(st) && ts.getModifiers(st)?.some((m) => m.kind === ts.SyntaxKind.DeclareKeyword))
129
+ return false;
130
+ // `export default <data>` is data as a constant's value is
131
+ if (ts.isExportAssignment(st))
132
+ return isCode(st.expression);
133
+ if (ts.isVariableStatement(st))
134
+ return st.declarationList.declarations.some((d) => !d.initializer || isCode(d.initializer));
135
+ return true;
136
+ });
137
+ const unmeasured = measuredFiles.filter((c) => c.lines.found === 0 && declaresCode(c.file, readSource(c.file) ?? ''));
138
+ if (unmeasured.length) {
139
+ invalidMeasurement(`${vendor}: ${unmeasured.length} file(s) in the pack's scope declare code and measure no line (the walk did not load them, or bun did not measure them): ${unmeasured.map((c) => c.file).join(', ')}`);
140
+ }
141
+ const files = measuredFiles.filter((c) => c.lines.found > 0).map((c) => {
142
+ // a lane's file is named from the vendor's src/ (`../fapi/src/semantics/client.ts`), as unreachable.json records it
143
+ const file = c.file.startsWith(prefix) ? c.file.slice(prefix.length) : `../${c.file.slice(`${vendor}/`.length)}`;
144
+ const recorded = c.never.filter((n) => recordedCode(file, n.fn));
145
+ const missing = c.never.filter((n) => !recordedCode(file, n.fn));
146
+ const size = (ns) => ns.reduce((s, n) => s + n.to - n.from + 1, 0);
147
+ return { file, lines: c.lines, recorded: size(recorded), missing, missingLines: size(missing) };
148
+ });
149
+ const total = files.reduce((t, c) => ({ found: t.found + c.lines.found, hit: t.hit + c.lines.hit, recorded: t.recorded + c.recorded, missing: t.missing + c.missingLines }), { found: 0, hit: 0, recorded: 0, missing: 0 });
150
+ // ── state logic ──────────────────────────────────────────────────────────────────────────────
151
+ const { manifest } = (await import(__rewriteRelativeImportExtension(join(PKG, 'src', 'manifest.ts'))));
152
+ const laneManifests = await Promise.all(sharedLanes.map(async (l) => (await import(__rewriteRelativeImportExtension(join(PKG, l, 'src', 'manifest.ts')))).manifest));
153
+ const observed = existsSync(transitionsPath) ? JSON.parse(readFileSync(transitionsPath, 'utf8')) : { seen: [], undeclared: [] };
154
+ const seen = new Set(observed.seen);
155
+ const was = (at, outcome, from) => [...seen].some((s) => s.startsWith(`${at}|${outcome}|`) && (from === undefined || s.endsWith(`|${from}`)));
156
+ const state = [];
157
+ for (const [resource, decl] of [manifest, ...laneManifests].flatMap((mf) => Object.entries(mf.resources ?? {}))) {
158
+ for (const [field, m] of Object.entries(decl.state ?? {})) {
159
+ // transitions of one operation from the same states refuse as one rule (a confirm that lands on one of
160
+ // four outcomes refuses with the first of its four identical refusals), so their refusal is one item
161
+ const refusalOf = new Map();
162
+ m.transitions.forEach((t, i) => {
163
+ const at = `${resource}.${field}#${i}`;
164
+ const name = `${resource}.${field}: ${t.operation ?? t.actor ?? 'api'} ${t.from === '*' ? '*' : t.from.join('|')} → ${t.to ?? '(stays)'}`;
165
+ if (!(t.to === undefined && t.refusal !== undefined))
166
+ state.push({ item: `move ${name}`, reached: was(at, 'moved') });
167
+ const refusals = [...(t.refusal ? [['', t.refusal]] : []), ...Object.entries(t.refusals ?? {})];
168
+ for (const [from, r] of refusals) {
169
+ const key = JSON.stringify([t.operation ?? t.actor, t.from, from, r]);
170
+ const known = refusalOf.get(key);
171
+ const reached = from ? was(at, 'refused', from) : was(at, 'refused');
172
+ if (known) {
173
+ known.reached ||= reached;
174
+ continue;
175
+ }
176
+ const item = { item: `refusal ${name}${from ? ` from ${from}` : ''}`, reached };
177
+ refusalOf.set(key, item);
178
+ state.push(item);
179
+ }
180
+ });
181
+ }
182
+ }
183
+ const stateMissing = state.filter((s) => !s.reached && !recordedState(s.item)).map((s) => s.item);
184
+ // ── stale records ────────────────────────────────────────────────────────────────────────────
185
+ // a record is a claim that no World reaches something: one that names a declaration, a file or a state item the pack
186
+ // no longer has, or one the walks now reach, is false, and counts as missing until it is corrected
187
+ const stale = [];
188
+ /** Records whose declaration may have run in part: to read, and split where it did (architecture.md, Coverage). */
189
+ const partlyRun = [];
190
+ const keptCode = [];
191
+ for (const u of unreachable.code ?? []) {
192
+ const keep = [];
193
+ const source = readSource(`${prefix}${u.file}`);
194
+ const names = new Set(source === undefined ? [] : functionIndex(source).map((f) => f.name));
195
+ const measured = files.find((f) => f.file === u.file);
196
+ const coverage = stateCoverage(lcov, [normalize(`${prefix}${u.file}`)], readSource)[0];
197
+ const unrun = new Set([...(measured?.missing ?? []), ...(coverage?.never ?? [])].map((n) => n.fn ?? '(module scope)'));
198
+ // a record is by declaration: one part of whose body ran is not unreachable, its unrun branch is (architecture.md,
199
+ // Coverage: "the branch moves into its own function first")
200
+ const partly = new Set(coverage?.ran ?? []);
201
+ for (const d of u.declarations) {
202
+ if (source === undefined)
203
+ stale.push(`${u.file}: no such file`);
204
+ else if (d !== '(module scope)' && !names.has(d))
205
+ stale.push(`${u.file}: no declaration ${d}`);
206
+ else if (measured && !unrun.has(d))
207
+ stale.push(`${u.file}: ${d} is reached`);
208
+ else {
209
+ // advice, not a count: bun's line hits cannot always tell a declaration that ran in part (see the header)
210
+ if (measured && partly.has(d))
211
+ partlyRun.push(`${u.file}: ${d}`);
212
+ keep.push(d);
213
+ }
214
+ }
215
+ if (keep.length)
216
+ keptCode.push({ ...u, declarations: keep });
217
+ }
218
+ const keptState = [];
219
+ for (const u of unreachable.state ?? []) {
220
+ if (!state.some((s) => s.item === u.item))
221
+ stale.push(`state: no item ${u.item}`);
222
+ else if (state.some((s) => s.item === u.item && s.reached))
223
+ stale.push(`state: ${u.item} is reached`);
224
+ else
225
+ keptState.push(u);
226
+ }
227
+ // `--prune` removes exactly the false records: a record removed wrongly shows again as missing, so pruning hides nothing
228
+ if (stale.length && process.argv.includes('--prune')) {
229
+ writeFileSync(unreachablePath, `${JSON.stringify({ ...unreachable, code: keptCode, state: keptState }, null, 2)}\n`);
230
+ console.log(`${vendor}: pruned ${stale.length} stale records from journeys/unreachable.json`);
231
+ stale.length = 0;
232
+ }
233
+ const stateRecorded = state.filter((s) => !s.reached && recordedState(s.item)).length;
234
+ // ── the report ───────────────────────────────────────────────────────────────────────────────
235
+ const pct = (hit, found) => (found ? `${((hit / found) * 100).toFixed(1)}%` : 'n/a');
236
+ const missing = (child.status === 0 ? 0 : 1) + total.missing + stateMissing.length + observed.undeclared.length + stale.length;
237
+ console.log(`${vendor}: ${missing === 0 ? 'meets the standard' : `${missing} missing`}${child.status === 0 ? '' : ' (the walk did not hold)'}`);
238
+ // a record whose reason is none the standard names exempts nothing: say which, so the author reaches it or names its World
239
+ const unruled = [...(unreachable.code ?? []).map((u) => `${u.file} ${u.declarations.join(', ')}`), ...(unreachable.state ?? []).map((u) => u.item)]
240
+ .filter((_, i) => !ruled([...(unreachable.code ?? []), ...(unreachable.state ?? [])][i]));
241
+ if (unruled.length)
242
+ console.log(` ${unruled.length} record(s) name no World of the standard (world: ${[...WORLDS].join(' | ')}), so they exempt nothing: ${unruled.slice(0, 6).join('; ')}${unruled.length > 6 ? ' …' : ''}`);
243
+ console.log(` code: the life and the vendor's examples run ${pct(total.hit, total.found)} of ${total.found} hand-written lines; ${total.recorded} recorded unreachable; ${total.missing} missing`);
244
+ console.log(` state: ${state.filter((s) => s.reached).length}/${state.length} declared moves and refusals reached; ${stateRecorded} recorded unreachable; ${stateMissing.length} missing; ${observed.undeclared.length} moves no declared transition allows`);
245
+ for (const u of observed.undeclared)
246
+ console.log(` undeclared: ${u}`);
247
+ if (stale.length)
248
+ console.log(` records: ${stale.length} stale`);
249
+ for (const r of stale)
250
+ console.log(` stale ${r}`);
251
+ for (const s of stateMissing)
252
+ console.log(` missing ${s}`);
253
+ if (partlyRun.length)
254
+ console.log(` advice: ${partlyRun.length} recorded declaration(s) may have run in part (read each; split where it did):\n${partlyRun.map((p) => ` ${p}`).join('\n')}`);
255
+ for (const f of files.filter((c) => c.missingLines).sort((a, b) => b.missingLines - a.missingLines)) {
256
+ const byFn = new Map();
257
+ for (const n of f.missing)
258
+ byFn.set(n.fn ?? '(module scope)', (byFn.get(n.fn ?? '(module scope)') ?? 0) + n.to - n.from + 1);
259
+ console.log(` ${f.file} (${f.missingLines} lines): ${[...byFn].sort((a, b) => b[1] - a[1]).map(([fn, n]) => `${fn} ${n}`).join(', ')}`);
260
+ }
261
+ // `--write` keeps journeys/coverage.json; `--out <file>` writes the same report elsewhere (score-pack's own measurement,
262
+ // which leaves the checkout as it found it)
263
+ const outAt = process.argv.includes('--out') ? process.argv[process.argv.indexOf('--out') + 1] : undefined;
264
+ if (process.argv.includes('--write') || outAt) {
265
+ writeFileSync(outAt ?? join(PKG, 'journeys', 'coverage.json'), `${JSON.stringify({
266
+ vendor, missing, stale,
267
+ code: { lines: total.found, run: total.hit, recorded: total.recorded, missing: total.missing },
268
+ state: { declared: state.length, reached: state.filter((s) => s.reached).length, recorded: stateRecorded, missing: stateMissing, undeclared: observed.undeclared },
269
+ files: files.map((f) => ({ file: f.file, lines: f.lines, missing: f.missing.map((n) => ({ from: n.from, to: n.to, fn: n.fn })) })),
270
+ }, null, 2)}\n`);
271
+ }
@@ -0,0 +1,9 @@
1
+ /** The pack repository the tools read (`<root>/<vendor>/`). */
2
+ export declare const packsRoot: () => string;
3
+ export declare function setPacksRoot(dir: string): void;
4
+ /** The checkout whose kernel a walk measures, when one is required (twin-world's own scripts); a contributor's walk
5
+ * measures whichever kernel its repository resolves, and says which. */
6
+ export declare const kernelCheckout: () => string | undefined;
7
+ export declare function setKernelCheckout(dir: string): void;
8
+ /** A tool of this directory, by name, in the form this module was loaded as (source `.ts`, or the published `.js`). */
9
+ export declare const toolPath: (name: string) => string;
@@ -0,0 +1,17 @@
1
+ // Where the contributor's tools (walk, examples, coverage, judge-brief) find the pack they are given: a vendor's directory
2
+ // under the pack repository they run from. A contributor runs them from their own repository's root (`twin-standard walk
3
+ // <vendor>`), so that root is the working directory; twin-world's scripts, which find Volter's pack repository beside
4
+ // their checkout, name it before loading a tool (setPacksRoot), and the kernel checkout a walk must measure
5
+ // (setKernelCheckout). Each tool reads both once, when it loads.
6
+ import { join } from 'node:path';
7
+ let packs = process.cwd();
8
+ let kernel;
9
+ /** The pack repository the tools read (`<root>/<vendor>/`). */
10
+ export const packsRoot = () => packs;
11
+ export function setPacksRoot(dir) { packs = dir; }
12
+ /** The checkout whose kernel a walk measures, when one is required (twin-world's own scripts); a contributor's walk
13
+ * measures whichever kernel its repository resolves, and says which. */
14
+ export const kernelCheckout = () => kernel;
15
+ export function setKernelCheckout(dir) { kernel = dir; }
16
+ /** A tool of this directory, by name, in the form this module was loaded as (source `.ts`, or the published `.js`). */
17
+ export const toolPath = (name) => join(import.meta.dir, `${name}${import.meta.path.endsWith('.js') ? '.js' : '.ts'}`);
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,18 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ // Runs one contributor tool in a process of its own, as the tool that started it names the pack repository and the
10
+ // kernel checkout (packs-root.ts): bun run-tool.ts <packs root> <kernel checkout or ''> <tool path> <tool args…>
11
+ import { setKernelCheckout, setPacksRoot } from "./packs-root.js";
12
+ const [packs, checkout, tool, ...args] = process.argv.slice(2);
13
+ setPacksRoot(packs);
14
+ if (checkout)
15
+ setKernelCheckout(checkout);
16
+ // a tool is a script over process.argv: its first argument is its own
17
+ process.argv = [process.argv[0], tool, ...args];
18
+ await import(__rewriteRelativeImportExtension(tool));
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env bun
2
+ export {};