@aiwg/cli 2026.9.24 → 2026.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/agentic/code/providers/capability-matrix.yaml +2 -1
  2. package/dist/src/artifacts/discovery-shadow-evaluator.js +177 -0
  3. package/dist/src/artifacts/discovery-shadow.js +195 -0
  4. package/dist/src/artifacts/index-builder.js +47 -9
  5. package/dist/src/artifacts/query-engine.js +94 -1
  6. package/dist/src/artifacts/types.js +1 -0
  7. package/dist/src/cli/handlers/decision.js +177 -0
  8. package/dist/src/cli/handlers/gates.js +154 -0
  9. package/dist/src/cli/handlers/index.js +5 -1
  10. package/dist/src/cli/handlers/sessions.js +10 -7
  11. package/dist/src/cli/handlers/utilities.js +20 -0
  12. package/dist/src/config/aiwg-config.js +15 -2
  13. package/dist/src/decision/acceptance.js +25 -0
  14. package/dist/src/decision/adapters/jev.js +29 -3
  15. package/dist/src/decision/ask.js +352 -0
  16. package/dist/src/decision/calibration/registry.js +9 -0
  17. package/dist/src/decision/compose.js +74 -15
  18. package/dist/src/decision/context-live-promotion.js +344 -0
  19. package/dist/src/decision/context-live-qualification.js +591 -0
  20. package/dist/src/decision/context-pruning.js +847 -0
  21. package/dist/src/decision/driver.js +432 -0
  22. package/dist/src/decision/egress-live-qualification.js +874 -0
  23. package/dist/src/decision/ensemble/contract.js +64 -1
  24. package/dist/src/decision/ensemble/index.js +1 -0
  25. package/dist/src/decision/ensemble/report.js +8 -42
  26. package/dist/src/decision/ensemble/runtime.js +571 -0
  27. package/dist/src/decision/ensemble-study/artifacts.js +85 -0
  28. package/dist/src/decision/ensemble-study/calibration.js +443 -0
  29. package/dist/src/decision/ensemble-study/corpus.js +229 -0
  30. package/dist/src/decision/ensemble-study/multifact-artifacts.js +23 -0
  31. package/dist/src/decision/ensemble-study/multifact-study.js +596 -0
  32. package/dist/src/decision/ensemble-study/multifact.js +241 -0
  33. package/dist/src/decision/ensemble-study/protocol.js +77 -0
  34. package/dist/src/decision/ensemble-study/score.js +462 -0
  35. package/dist/src/decision/ensemble-study/staged.js +87 -0
  36. package/dist/src/decision/ensemble-study/statistics.js +84 -0
  37. package/dist/src/decision/evaluate.js +227 -14
  38. package/dist/src/decision/export.js +4 -0
  39. package/dist/src/decision/feature-export.js +1074 -0
  40. package/dist/src/decision/graph-index.js +16 -0
  41. package/dist/src/decision/graph-live-qualification.js +1041 -0
  42. package/dist/src/decision/graph-live-workload.js +245 -0
  43. package/dist/src/decision/graph-skill-bridge.js +21 -3
  44. package/dist/src/decision/heldout/calibration.js +140 -0
  45. package/dist/src/decision/heldout/collector.js +430 -0
  46. package/dist/src/decision/heldout/contract.js +309 -0
  47. package/dist/src/decision/heldout/d29-generator-ids.js +12 -0
  48. package/dist/src/decision/heldout/d29-passage-baseline-v2.js +93 -0
  49. package/dist/src/decision/heldout/d29-passage-baseline-v3.js +100 -0
  50. package/dist/src/decision/heldout/d29-passage-baseline.js +66 -0
  51. package/dist/src/decision/heldout/d29-pools-v8.js +575 -0
  52. package/dist/src/decision/heldout/d29-pools.js +288 -0
  53. package/dist/src/decision/heldout/d29-v6.js +169 -0
  54. package/dist/src/decision/heldout/d29-v7.js +202 -0
  55. package/dist/src/decision/heldout/d29-v8.js +586 -0
  56. package/dist/src/decision/heldout/generator-registry.js +67 -0
  57. package/dist/src/decision/heldout/generators.js +696 -0
  58. package/dist/src/decision/heldout/index.js +8 -0
  59. package/dist/src/decision/heldout/journal.js +346 -0
  60. package/dist/src/decision/heldout/study-generators.js +64 -0
  61. package/dist/src/decision/heldout/types.js +2 -0
  62. package/dist/src/decision/host-policy.js +61 -0
  63. package/dist/src/decision/index.js +13 -0
  64. package/dist/src/decision/interop-profile.v1.json +112 -0
  65. package/dist/src/decision/interop.js +653 -0
  66. package/dist/src/decision/issue-triage/index.js +3 -0
  67. package/dist/src/decision/issue-triage/runtime.js +1069 -0
  68. package/dist/src/decision/issue-triage/types.js +2 -0
  69. package/dist/src/decision/jev-credentials.js +121 -0
  70. package/dist/src/decision/patterns/catalog.js +28 -8
  71. package/dist/src/decision/patterns/playground.js +28 -11
  72. package/dist/src/decision/patterns/specs.js +19 -10
  73. package/dist/src/decision/preprocessed-evidence.js +724 -0
  74. package/dist/src/decision/qualification/capture.js +8 -2
  75. package/dist/src/decision/qualification/gate-evidence.js +19 -4
  76. package/dist/src/decision/qualification/quality.js +57 -49
  77. package/dist/src/decision/qualification/release.js +76 -3
  78. package/dist/src/decision/qualification/runner.js +5 -2
  79. package/dist/src/decision/routing/contract.js +175 -0
  80. package/dist/src/decision/routing/index.js +5 -0
  81. package/dist/src/decision/routing/report.js +216 -0
  82. package/dist/src/decision/routing/runtime.js +685 -0
  83. package/dist/src/decision/routing/types.js +2 -0
  84. package/dist/src/decision/sdlc-screening.js +1157 -0
  85. package/dist/src/decision/sensitivity/comparative.js +154 -0
  86. package/dist/src/decision/sensitivity/contract.js +218 -0
  87. package/dist/src/decision/sensitivity/index.js +5 -0
  88. package/dist/src/decision/sensitivity/runtime.js +912 -0
  89. package/dist/src/decision/sensitivity/types.js +2 -0
  90. package/dist/src/decision/validate.js +26 -0
  91. package/dist/src/extensions/commands/definitions.js +38 -0
  92. package/dist/src/extensions/manifest.js +44 -0
  93. package/dist/src/gates/discovery.js +315 -0
  94. package/dist/src/gates/driver.js +388 -0
  95. package/dist/src/gates/evaluate.js +719 -0
  96. package/dist/src/gates/floors.js +255 -0
  97. package/dist/src/gates/index.js +17 -0
  98. package/dist/src/gates/providers/evidence.js +38 -0
  99. package/dist/src/gates/providers/index.js +21 -0
  100. package/dist/src/gates/providers/isolated-child-source.js +446 -0
  101. package/dist/src/gates/providers/loader.js +1069 -0
  102. package/dist/src/gates/providers/paired.js +52 -0
  103. package/dist/src/gates/providers/proportion.js +60 -0
  104. package/dist/src/gates/providers/registry.js +40 -0
  105. package/dist/src/gates/providers/scalar.js +41 -0
  106. package/dist/src/gates/providers/screening.js +53 -0
  107. package/dist/src/gates/providers/types.js +25 -0
  108. package/dist/src/gates/registry.js +1003 -0
  109. package/dist/src/gates/report.js +102 -0
  110. package/dist/src/gates/schema.js +56 -0
  111. package/dist/src/gates/stats/binomial.js +26 -0
  112. package/dist/src/gates/stats/bootstrap.js +62 -0
  113. package/dist/src/gates/stats/clopper-pearson.js +95 -0
  114. package/dist/src/gates/stats/digest.js +26 -0
  115. package/dist/src/gates/stats/error.js +5 -0
  116. package/dist/src/gates/stats/index.js +9 -0
  117. package/dist/src/gates/stats/normal.js +35 -0
  118. package/dist/src/gates/stats/paired.js +120 -0
  119. package/dist/src/gates/stats/splits.js +30 -0
  120. package/dist/src/gates/types.js +8 -0
  121. package/dist/src/governance/redaction.js +14 -4
  122. package/dist/src/mcp/muse-native-config.mjs +123 -0
  123. package/dist/src/mcp/tools/decision.mjs +228 -0
  124. package/dist/src/mcp/tools/subsystems.mjs +2 -0
  125. package/dist/src/providers/capability-matrix.yaml +2 -1
  126. package/dist/src/providers/provider-definitions.js +2 -1
  127. package/dist/src/sessions/adapters/muse.js +336 -39
  128. package/dist/src/sessions/batch-import.js +7 -0
  129. package/dist/src/sessions/workspace-discovery.js +13 -2
  130. package/package.json +1 -1
  131. package/schemas/decision/ConformalFrozenOpenData.v2.schema.json +371 -0
  132. package/schemas/decision/ConformalOpenDataReport.v2.schema.json +421 -0
  133. package/schemas/decision/ConformalPreregistration.v2.schema.json +529 -0
  134. package/schemas/decision/ContextPruningCandidate.v1.schema.json +47 -0
  135. package/schemas/decision/ContextPruningEvaluationReport.v1.schema.json +758 -0
  136. package/schemas/decision/ContextPruningPreregistration.v1.schema.json +175 -0
  137. package/schemas/decision/ContextPruningReceipt.v1.schema.json +72 -0
  138. package/schemas/decision/D17Multifact.v1.schema.json +1851 -0
  139. package/schemas/decision/D17StudyAnalysis.v1.schema.json +42 -0
  140. package/schemas/decision/D17StudyAnalysis.v2.schema.json +51 -0
  141. package/schemas/decision/D17StudyCalibration.v1.schema.json +819 -0
  142. package/schemas/decision/D17StudyDryRun.v1.schema.json +169 -0
  143. package/schemas/decision/D17StudyDryRun.v2.schema.json +239 -0
  144. package/schemas/decision/D17StudyGold.v1.schema.json +108 -0
  145. package/schemas/decision/D17StudyGuide.v1.schema.json +63 -0
  146. package/schemas/decision/D17StudyNativeTemplates.v1.schema.json +619 -0
  147. package/schemas/decision/D17StudyProtocol.v1.schema.json +241 -0
  148. package/schemas/decision/D17StudyReport.v1.schema.json +902 -0
  149. package/schemas/decision/D17StudyReport.v2.schema.json +1319 -0
  150. package/schemas/decision/D17StudyReview.v1.schema.json +175 -0
  151. package/schemas/decision/D17StudySplits.v1.schema.json +217 -0
  152. package/schemas/decision/D29Study.v1.schema.json +1903 -0
  153. package/schemas/decision/D29Study.v2.schema.json +1344 -0
  154. package/schemas/decision/D29Study.v3.schema.json +609 -0
  155. package/schemas/decision/D29Study.v4.schema.json +1133 -0
  156. package/schemas/decision/D29Study.v6.schema.json +1205 -0
  157. package/schemas/decision/D29Study.v7.schema.json +1471 -0
  158. package/schemas/decision/D29Study.v8.schema.json +671 -0
  159. package/schemas/decision/D29Study.v9.schema.json +778 -0
  160. package/schemas/decision/DecisionComparativeReplayAuditSample.v1.schema.json +137 -0
  161. package/schemas/decision/DecisionComparativeReplayCorpus.v1.schema.json +258 -0
  162. package/schemas/decision/DecisionComparativeReplayFreeze.v1.schema.json +74 -0
  163. package/schemas/decision/DecisionComparativeReplayGold.v1.schema.json +50 -0
  164. package/schemas/decision/DecisionComparativeReplayGoldAsset.v1.schema.json +37 -0
  165. package/schemas/decision/DecisionComparativeReplayIntegrity.v1.schema.json +81 -0
  166. package/schemas/decision/DecisionComparativeReplayMembers.v1.schema.json +52 -0
  167. package/schemas/decision/DecisionComparativeReplayPreregistration.v1.schema.json +113 -0
  168. package/schemas/decision/DecisionComparativeReplayReport.v1.schema.json +407 -0
  169. package/schemas/decision/DecisionComparativeReplayReviewPackets.v1.schema.json +260 -0
  170. package/schemas/decision/DecisionComparativeReplaySplit.v1.schema.json +84 -0
  171. package/schemas/decision/DecisionFeatureObservation.v1.schema.json +564 -0
  172. package/schemas/decision/DecisionFeatureSet.v1.schema.json +155 -0
  173. package/schemas/decision/DecisionInteropMapping.v1.schema.json +85 -0
  174. package/schemas/decision/DecisionIssueTriageEvaluationManifest.v1.schema.json +174 -0
  175. package/schemas/decision/DecisionIssueTriageEvaluationReport.v1.schema.json +280 -0
  176. package/schemas/decision/DecisionIssueTriagePilotPack.v1.schema.json +114 -0
  177. package/schemas/decision/DecisionRouteReceipt.v1.schema.json +155 -0
  178. package/schemas/decision/DecisionRoutingPolicy.v1.schema.json +132 -0
  179. package/schemas/decision/DecisionRoutingShadowReport.v1.schema.json +170 -0
  180. package/schemas/decision/DecisionRoutingTask.v1.schema.json +49 -0
  181. package/schemas/decision/DecisionRuleset.schema.json +8 -2
  182. package/schemas/decision/DecisionRuleset.v1alpha2.schema.json +8 -2
  183. package/schemas/decision/DecisionSensitivityPlan.v1.schema.json +191 -0
  184. package/schemas/decision/DecisionSensitivityReport.v1.schema.json +163 -0
  185. package/schemas/decision/HeldoutApproval.v1.schema.json +312 -0
  186. package/schemas/decision/HeldoutAttempt.v1.schema.json +211 -0
  187. package/schemas/decision/HeldoutBaseline.v1.schema.json +90 -0
  188. package/schemas/decision/HeldoutCalibrationPhase.v1.schema.json +87 -0
  189. package/schemas/decision/HeldoutCorpus.v1.schema.json +167 -0
  190. package/schemas/decision/HeldoutEvent.v1.schema.json +41 -0
  191. package/schemas/decision/HeldoutFrozen.v1.schema.json +142 -0
  192. package/schemas/decision/HeldoutPreregistration.v1.schema.json +222 -0
  193. package/schemas/decision/HeldoutSpendEvent.v1.schema.json +122 -0
  194. package/schemas/decision/HeldoutSpendHead.v1.schema.json +25 -0
  195. package/schemas/decision/HeldoutSpendHead.v2.schema.json +46 -0
  196. package/schemas/decision/HeldoutSummary.v1.schema.json +101 -0
  197. package/schemas/decision/OpaDecisionLogExport.v1.schema.json +65 -0
  198. package/schemas/decision/PreprocessedEvidence.v1.schema.json +306 -0
  199. package/schemas/decision/RulesetResult.v1alpha2.schema.json +175 -0
  200. package/schemas/decision/SdlcEvidenceScreening.v1.schema.json +499 -0
  201. package/schemas/decision/SdlcScreeningPreregistration.v1.schema.json +132 -0
  202. package/schemas/decision/SdlcScreeningPreregistration.v2.schema.json +138 -0
  203. package/schemas/decision/SdlcScreeningRelease.v1.schema.json +654 -0
  204. package/schemas/decision/SdlcScreeningRelease.v2.schema.json +654 -0
  205. package/tools/agents/deploy-agents.mjs +1 -1
  206. package/tools/agents/providers/base.mjs +40 -18
  207. package/tools/agents/providers/factory.mjs +10 -2
  208. package/tools/agents/providers/muse-hooks.mjs +1 -29
  209. package/tools/agents/providers/muse.mjs +6 -3
@@ -0,0 +1,446 @@
1
+ /**
2
+ * Embedded source of the isolated provider driver (gates P1, round 3).
3
+ *
4
+ * The parent (`loader.ts`) passes this verbatim to `node -e` inside a
5
+ * bubblewrap sandbox (see `isolationLaunchPlan`). Nothing is written to disk
6
+ * and the child reads no files: the request (provider module sources, frozen
7
+ * clock, seed, records) and a per-run random nonce arrive on stdin, which the
8
+ * driver consumes completely BEFORE any provider code is compiled.
9
+ *
10
+ * The driver is plain dependency-free JavaScript held in a `String.raw`
11
+ * template, so it must contain no backtick and no dollar-brace sequence
12
+ * (the scanner builds the backtick from its char code). Edit with care: the
13
+ * bytes below are exactly the bytes the child runs.
14
+ *
15
+ * Security model (see docs/decision/gate-providers.md): the `vm` context is
16
+ * NOT the boundary. The boundary is the OS sandbox (bubblewrap: no network,
17
+ * no host filesystem beyond the node binary and its libraries, empty
18
+ * environment, private pid/ipc/uts/user/mount namespaces) plus the parent's
19
+ * SIGKILL timeout, output cap and nonce-framed result channel. Inside, node
20
+ * runs with `--permission` (no fs, no child processes, no workers) and
21
+ * `--disallow-code-generation-from-strings`. The `vm` context is depth:
22
+ *
23
+ * - created with `codeGeneration: { strings: false, wasm: false }`, so no
24
+ * intrinsic `Function`/`eval` constructor can compile code;
25
+ * - every intrinsic reachable from the context global is frozen before
26
+ * provider code runs, so host-side awaits of context promises and stack
27
+ * hooks cannot be hijacked;
28
+ * - host -> context traffic is primitives only: the provider is driven by
29
+ * context-realm functions created by the bootstrap, results leave as a
30
+ * JSON string the host polls for, and the dynamic-import trap throws a
31
+ * context-realm Error. No host object or function ever reaches provider
32
+ * code.
33
+ */
34
+ export const ISOLATED_CHILD_SOURCE = String.raw `
35
+ import fs from 'node:fs';
36
+ import vm from 'node:vm';
37
+
38
+ var MAX_RESPONSE_BYTES = 1048576;
39
+ var FRAME = 'AIWG-RESULT ';
40
+ var BACKTICK = String.fromCharCode(96);
41
+ var nonce = null;
42
+ var responded = false;
43
+ var api = null;
44
+
45
+ function respond(body) {
46
+ if (responded) return;
47
+ responded = true;
48
+ var text;
49
+ try { text = JSON.stringify(body); } catch (e) { text = undefined; }
50
+ if (typeof text !== 'string' || Buffer.byteLength(text) > MAX_RESPONSE_BYTES) {
51
+ text = JSON.stringify({ ok: false, error: 'isolated provider response exceeds the output cap' });
52
+ }
53
+ if (nonce === null) process.exit(70);
54
+ process.stdout.write(FRAME + nonce + ' ' + text + '\n', function () { process.exit(0); });
55
+ }
56
+ function refuse(message) { respond({ ok: false, error: String(message).slice(0, 2000) }); }
57
+ function describe(error) {
58
+ if (typeof error === 'string') return error;
59
+ // Host-realm errors (driver/Node) are read here; anything else came from
60
+ // the context and is described by the context's own trusted function.
61
+ if (error instanceof Error) return String(error.message);
62
+ if (api !== null) {
63
+ try { var text = api.describe(error); if (typeof text === 'string') return text; } catch (e) { /* fall through */ }
64
+ }
65
+ return 'unknown';
66
+ }
67
+ process.on('uncaughtException', function (error) { refuse('isolated provider crashed: ' + describe(error)); });
68
+ process.on('unhandledRejection', function (error) { refuse('isolated provider crashed: ' + describe(error)); });
69
+
70
+ function readRequest() {
71
+ var raw = fs.readFileSync(0, 'utf8');
72
+ var newline = raw.indexOf('\n');
73
+ var candidate = newline === -1 ? '' : raw.slice(0, newline);
74
+ if (/^[0-9a-f]{64}$/.test(candidate) !== true) process.exit(71);
75
+ nonce = candidate;
76
+ var request = JSON.parse(raw.slice(newline + 1));
77
+ if (!request || typeof request !== 'object' || Array.isArray(request)) throw new Error('isolated provider request is invalid');
78
+ return request;
79
+ }
80
+
81
+ // Runs INSIDE the vm context (compiled there from this function's source).
82
+ // Captures the intrinsics it needs, strips I/O, clock and randomness, freezes
83
+ // every reachable intrinsic and returns frozen context-realm entry points.
84
+ function contextBootstrap(seed, clockMs, recordsJson) {
85
+ 'use strict';
86
+ var G = globalThis;
87
+ var R = Reflect;
88
+ var apply = R.apply;
89
+ var construct = R.construct;
90
+ var ownKeys = R.ownKeys;
91
+ var getProto = Object.getPrototypeOf;
92
+ var getDesc = Object.getOwnPropertyDescriptor;
93
+ var defineProperty = Object.defineProperty;
94
+ var freeze = Object.freeze;
95
+ var isArray = Array.isArray;
96
+ var keysOf = Object.keys;
97
+ var PromiseCtor = Promise;
98
+ var promiseResolve = Promise.resolve;
99
+ var promiseThen = Promise.prototype.then;
100
+ var stringify = JSON.stringify;
101
+ var parse = JSON.parse;
102
+ var ErrorCtor = Error;
103
+ var StringCtor = String;
104
+ var isSafeInteger = Number.isSafeInteger;
105
+ var OriginalDate = Date;
106
+ var dateParse = Date.parse;
107
+ var dateUTC = Date.UTC;
108
+
109
+ if (typeof clockMs !== 'number' || !isSafeInteger(clockMs)) throw new ErrorCtor('isolated clock is invalid');
110
+
111
+ // Intrinsics not reachable by name from the global object.
112
+ var hidden = [
113
+ function () {}, async function () {}, function* () {}, async function* () {},
114
+ (function* () {})(), (async function* () {})(),
115
+ [][Symbol.iterator](), new Map().entries(), new Set().values(), ''[Symbol.iterator](),
116
+ /x/[Symbol.matchAll](''), getProto(Int8Array), Promise.resolve(),
117
+ (function () { return arguments; })(),
118
+ ];
119
+ try { hidden.push([].values().map(function (x) { return x; })); } catch (e) { /* no iterator helpers */ }
120
+ try { hidden.push(G.Iterator.from({ next: function () { return { done: true }; } })); } catch (e) { /* none */ }
121
+
122
+ var FORBIDDEN = ['eval', 'Function', 'WebAssembly', 'Proxy', 'Reflect', 'console', 'Intl', 'Atomics',
123
+ 'SharedArrayBuffer', 'FinalizationRegistry', 'WeakRef', 'AsyncDisposableStack', 'DisposableStack',
124
+ 'SuppressedError', 'Iterator'];
125
+ for (var i = 0; i < FORBIDDEN.length; i++) {
126
+ var name = FORBIDDEN[i];
127
+ try { delete G[name]; } catch (e) { /* checked below */ }
128
+ if (typeof G[name] !== 'undefined') { try { G[name] = undefined; } catch (e) { /* checked below */ } }
129
+ if (typeof G[name] !== 'undefined') throw new ErrorCtor('isolated context retains ' + name);
130
+ }
131
+ try { delete Math.random; } catch (e) { /* checked below */ }
132
+ if (typeof Math.random !== 'undefined') throw new ErrorCtor('isolated context retains Math.random');
133
+
134
+ // Frozen clock: the real Date constructor becomes unreachable (no
135
+ // prototype link from the shim, prototype.constructor repointed).
136
+ var FROZEN_MS = clockMs;
137
+ var FrozenDate = function Date() {
138
+ if (new.target === undefined) return apply(OriginalDate.prototype.toString, construct(OriginalDate, [FROZEN_MS]), []);
139
+ var args = [];
140
+ for (var a = 0; a < arguments.length; a++) args.push(arguments[a]);
141
+ return construct(OriginalDate, args.length === 0 ? [FROZEN_MS] : args, new.target);
142
+ };
143
+ FrozenDate.prototype = OriginalDate.prototype;
144
+ defineProperty(OriginalDate.prototype, 'constructor', { value: FrozenDate, writable: false, enumerable: false, configurable: false });
145
+ FrozenDate.now = function now() { return FROZEN_MS; };
146
+ FrozenDate.parse = dateParse;
147
+ FrozenDate.UTC = dateUTC;
148
+ G.Date = FrozenDate;
149
+ G.clock = FROZEN_MS;
150
+
151
+ var state = (seed >>> 0) || 1;
152
+ G.random = function random() {
153
+ state = (state + 0x6D2B79F5) >>> 0;
154
+ var t = state;
155
+ t = Math.imul(t ^ (t >>> 15), t | 1);
156
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
157
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
158
+ };
159
+
160
+ var freezeDeep = function (value) {
161
+ if (value && typeof value === 'object') {
162
+ var keys = keysOf(value);
163
+ for (var k = 0; k < keys.length; k++) freezeDeep(value[keys[k]]);
164
+ freeze(value);
165
+ }
166
+ return value;
167
+ };
168
+ var records = typeof recordsJson === 'string' ? freezeDeep(parse(recordsJson)) : undefined;
169
+
170
+ // Harden: freeze every object reachable from the global object and the
171
+ // hidden intrinsics (values, accessors and prototype chains). The global
172
+ // object itself stays extensible for provider top-level state.
173
+ var seen = new Set();
174
+ var stack = [G, OriginalDate].concat(hidden);
175
+ while (stack.length > 0) {
176
+ var current = stack.pop();
177
+ if ((typeof current !== 'object' && typeof current !== 'function') || current === null || seen.has(current)) continue;
178
+ seen.add(current);
179
+ stack.push(getProto(current));
180
+ var own = ownKeys(current);
181
+ for (var o = 0; o < own.length; o++) {
182
+ var desc = getDesc(current, own[o]);
183
+ if (desc === undefined) continue;
184
+ if ('value' in desc) stack.push(desc.value);
185
+ if (desc.get) stack.push(desc.get);
186
+ if (desc.set) stack.push(desc.set);
187
+ }
188
+ }
189
+ seen.forEach(function (value) { if (value !== G) freeze(value); });
190
+
191
+ var result;
192
+ var finish = function (body) {
193
+ var text;
194
+ try { text = stringify(body); } catch (e) { text = undefined; }
195
+ if (typeof text !== 'string') text = stringify({ ok: false, error: 'provider result is not JSON-serializable' });
196
+ if (result === undefined) result = text;
197
+ };
198
+ var describeError = function (error) {
199
+ try {
200
+ if (typeof error === 'string') return error;
201
+ var message = error && error.message;
202
+ if (typeof message === 'string') return message;
203
+ return StringCtor(error);
204
+ } catch (e) {
205
+ return 'unknown';
206
+ }
207
+ };
208
+ var fail = function (error) { finish({ ok: false, error: describeError(error) }); };
209
+
210
+ var run = function (ns, mode, expectedId, expectedVersion) {
211
+ try {
212
+ var descriptor = (ns && ns.provider) || (ns && ns.default);
213
+ if (!descriptor || typeof descriptor !== 'object') throw new ErrorCtor('provider module has no provider export');
214
+ if (descriptor.id !== expectedId || descriptor.version !== expectedVersion) {
215
+ throw new ErrorCtor('provider module identity does not match its manifest declaration');
216
+ }
217
+ if (typeof descriptor.description !== 'string' || !descriptor.description) throw new ErrorCtor('provider description is invalid');
218
+ var metrics = descriptor.metrics;
219
+ if (!metrics || typeof metrics !== 'object' || isArray(metrics)) throw new ErrorCtor('provider metrics declaration is invalid');
220
+ if (mode === 'inspect') {
221
+ finish({ ok: true, descriptor: {
222
+ id: descriptor.id, version: descriptor.version, description: descriptor.description, metrics: metrics,
223
+ } });
224
+ return;
225
+ }
226
+ if (typeof descriptor.compute !== 'function') throw new ErrorCtor('provider compute is not a function');
227
+ var raw = descriptor.compute(records);
228
+ var settled = apply(promiseResolve, PromiseCtor, [raw]);
229
+ apply(promiseThen, settled, [function (value) {
230
+ try {
231
+ if (!value || typeof value !== 'object' || isArray(value)) throw new ErrorCtor('provider returned no metrics');
232
+ if (!value.metrics || typeof value.metrics !== 'object') throw new ErrorCtor('provider returned no metrics');
233
+ finish({ ok: true, result: value });
234
+ } catch (e) {
235
+ fail(e);
236
+ }
237
+ }, fail]);
238
+ } catch (e) {
239
+ fail(e);
240
+ }
241
+ };
242
+
243
+ return freeze({
244
+ run: run,
245
+ poll: function () { return result; },
246
+ describe: describeError,
247
+ makeError: function (message) { return new ErrorCtor(StringCtor(message)); },
248
+ });
249
+ }
250
+
251
+ function stripModule(code, rel) {
252
+ var failScan = function (why) { throw new Error('provider module cannot be scanned: ' + rel + ': ' + why); };
253
+ var n = code.length;
254
+ var kept = [];
255
+ var pos = 0;
256
+ var push = function (ch) { kept.push(ch); };
257
+ var skipLine = function () { while (pos < n && code[pos] !== '\n') { push(' '); pos++; } };
258
+ var skipBlock = function () {
259
+ push(' '); push(' '); pos += 2;
260
+ var closed = false;
261
+ while (pos < n) {
262
+ if (code[pos] === '*' && code[pos + 1] === '/') { push(' '); push(' '); pos += 2; closed = true; break; }
263
+ push(code[pos] === '\n' ? '\n' : ' '); pos++;
264
+ }
265
+ if (closed !== true) failScan('unterminated block comment');
266
+ };
267
+ var skipString = function (quote) {
268
+ push(' '); pos++;
269
+ var done = false;
270
+ while (pos < n) {
271
+ var c = code[pos];
272
+ if (c === '\\') { push(' '); push(' '); pos += 2; continue; }
273
+ if (c === '\n') failScan('unterminated string literal');
274
+ if (c === quote) { push(' '); pos++; done = true; break; }
275
+ push(' '); pos++;
276
+ }
277
+ if (done !== true) failScan('unterminated string literal');
278
+ };
279
+ var skipTemplate;
280
+ var scanBrace = function () {
281
+ var depth = 1;
282
+ while (pos < n && depth > 0) {
283
+ var c = code[pos];
284
+ if (c === '{') { push(c); depth++; pos++; continue; }
285
+ if (c === '}') { depth--; push(depth === 0 ? ' ' : c); pos++; continue; }
286
+ if (c === '/' && code[pos + 1] === '/') { skipLine(); continue; }
287
+ if (c === '/' && code[pos + 1] === '*') { skipBlock(); continue; }
288
+ if (c === "'" || c === '"') { skipString(c); continue; }
289
+ if (c === BACKTICK) { skipTemplate(); continue; }
290
+ push(c); pos++;
291
+ }
292
+ if (depth !== 0) failScan('unterminated substitution');
293
+ };
294
+ skipTemplate = function () {
295
+ push(' '); pos++;
296
+ while (pos < n) {
297
+ var c = code[pos];
298
+ if (c === '\\') { push(' '); push(' '); pos += 2; continue; }
299
+ if (c === BACKTICK) { push(' '); pos++; return; }
300
+ if (c === '$' && code[pos + 1] === '{') { push(' '); push(' '); pos += 2; scanBrace(); continue; }
301
+ push(c === '\n' ? '\n' : ' '); pos++;
302
+ }
303
+ failScan('unterminated template literal');
304
+ };
305
+ if (code.slice(0, 2) === '#!') { while (pos < n && code[pos] !== '\n') { push(' '); pos++; } }
306
+ while (pos < n) {
307
+ var ch = code[pos];
308
+ if (ch === '/' && code[pos + 1] === '/') { skipLine(); continue; }
309
+ if (ch === '/' && code[pos + 1] === '*') { skipBlock(); continue; }
310
+ if (ch === "'" || ch === '"') { skipString(ch); continue; }
311
+ if (ch === BACKTICK) { skipTemplate(); continue; }
312
+ push(ch); pos++;
313
+ }
314
+ return kept.join('');
315
+ }
316
+
317
+ function forbidDynamic(cleaned, rel) {
318
+ var pattern = /(^|[^.$\w])(import|require)(\s*)(\(|\.)?/g;
319
+ var match = null;
320
+ while ((match = pattern.exec(cleaned)) !== null) {
321
+ var keyword = match[2];
322
+ var punct = match[4];
323
+ if (keyword === 'import' && punct === '(') throw new Error('dynamic import() is forbidden in ' + rel + ': use static relative imports');
324
+ if (keyword === 'require' && punct === '(') throw new Error('require() is forbidden in ' + rel + ': use static relative imports');
325
+ }
326
+ }
327
+
328
+ async function main() {
329
+ var request = readRequest();
330
+ var entry = request.entry;
331
+ var sources = request.modules;
332
+ var mode = request.mode;
333
+ if (typeof entry !== 'string' || !entry || !sources || typeof sources !== 'object' || Array.isArray(sources)) {
334
+ throw new Error('isolated provider request is invalid');
335
+ }
336
+ if (mode !== 'inspect' && mode !== 'invoke') throw new Error('isolated provider request is invalid');
337
+ if (typeof request.clockMs !== 'number' || !Number.isSafeInteger(request.clockMs)) throw new Error('isolated clock is invalid');
338
+ if (typeof request.seed !== 'number' || !Number.isSafeInteger(request.seed) || request.seed < 0) throw new Error('isolated seed is invalid');
339
+ if (mode === 'invoke' && typeof request.recordsJson !== 'string') throw new Error('isolated provider records are invalid');
340
+ if (typeof request.expectedId !== 'string' || !request.expectedId
341
+ || typeof request.expectedVersion !== 'string' || !request.expectedVersion) {
342
+ throw new Error('isolated provider request is invalid');
343
+ }
344
+ var modules = new Map();
345
+ var names = Object.keys(sources).sort();
346
+ for (var s = 0; s < names.length; s++) {
347
+ if (typeof sources[names[s]] !== 'string') throw new Error('isolated provider request is invalid');
348
+ modules.set(names[s], sources[names[s]]);
349
+ }
350
+
351
+ var context = vm.createContext(Object.create(null), {
352
+ name: 'aiwg-gate-provider',
353
+ codeGeneration: { strings: false, wasm: false },
354
+ });
355
+ try {
356
+ var setup = vm.runInContext('(' + contextBootstrap.toString() + ')', context, { filename: '__aiwg_bootstrap.js' });
357
+ api = setup(request.seed >>> 0, request.clockMs, mode === 'invoke' ? request.recordsJson : undefined);
358
+ } catch (e) {
359
+ throw new Error('isolated context setup failed: ' + ((e && e.message) || 'unknown'));
360
+ }
361
+ var runInContext = api.run;
362
+ var pollContext = api.poll;
363
+ var makeContextError = api.makeError;
364
+
365
+ var cache = new Map();
366
+ function childLink(specifier, parentRel) {
367
+ if (typeof specifier !== 'string' || (specifier.startsWith('./') !== true && specifier.startsWith('../') !== true)) {
368
+ throw new Error('bare and external imports are forbidden in phase 1: ' + specifier);
369
+ }
370
+ var base = parentRel ? parentRel.slice(0, parentRel.lastIndexOf('/') + 1) : '';
371
+ var parts = (base + specifier).split('/');
372
+ var out = [];
373
+ for (var i = 0; i < parts.length; i++) {
374
+ if (parts[i] === '' || parts[i] === '.') continue;
375
+ if (parts[i] === '..') {
376
+ if (out.length === 0) throw new Error('provider import escapes the snapshot: ' + specifier);
377
+ out.pop();
378
+ } else out.push(parts[i]);
379
+ }
380
+ var rel = out.join('/');
381
+ if (rel.endsWith('.mjs') !== true) throw new Error('provider modules must be relative .mjs files: ' + specifier);
382
+ if (rel.indexOf('__aiwg_') === 0 || rel.indexOf('/__aiwg_') !== -1) throw new Error('provider module is reserved: ' + specifier);
383
+ if (modules.has(rel) !== true) throw new Error('provider module is not in the pinned snapshot: ' + specifier);
384
+ return rel;
385
+ }
386
+ // The dynamic-import trap answers with a CONTEXT-realm Error: a host Error
387
+ // would hand provider code the host Function constructor.
388
+ function denyDynamicImport() {
389
+ throw makeContextError('dynamic import() is forbidden: use static relative imports');
390
+ }
391
+ async function getModule(rel) {
392
+ if (cache.has(rel)) return cache.get(rel);
393
+ var mod = new vm.SourceTextModule(modules.get(rel), {
394
+ identifier: rel,
395
+ context: context,
396
+ importModuleDynamically: denyDynamicImport,
397
+ });
398
+ cache.set(rel, mod);
399
+ try {
400
+ await mod.link(async function (specifier) { return getModule(childLink(specifier, rel)); });
401
+ } catch (e) {
402
+ throw new Error('provider import failed for ' + rel + ': ' + ((e && e.message) || 'unknown'));
403
+ }
404
+ return mod;
405
+ }
406
+
407
+ modules.forEach(function (source, rel) {
408
+ if (rel.endsWith('.mjs') !== true) return;
409
+ try {
410
+ new vm.SourceTextModule(source, { identifier: rel, context: context, importModuleDynamically: denyDynamicImport });
411
+ } catch (e) {
412
+ throw new Error('provider module does not parse: ' + rel + ': ' + describe(e));
413
+ }
414
+ forbidDynamic(stripModule(source, rel), rel);
415
+ });
416
+ var entryMod = await getModule(childLink('./' + entry, ''));
417
+ try {
418
+ await entryMod.evaluate();
419
+ } catch (e) {
420
+ throw new Error('provider module threw during evaluation: ' + describe(e));
421
+ }
422
+ runInContext(entryMod.namespace, mode, request.expectedId, request.expectedVersion);
423
+ var text = await new Promise(function (resolve) {
424
+ var polls = 0;
425
+ var tick = function () {
426
+ var value = pollContext();
427
+ if (typeof value === 'string') { resolve(value); return; }
428
+ polls++;
429
+ if (polls < 64) setImmediate(tick); else setTimeout(tick, 2);
430
+ };
431
+ setImmediate(tick);
432
+ });
433
+ var body = JSON.parse(text);
434
+ if (!body || typeof body !== 'object' || Array.isArray(body)) throw new Error('isolated provider produced no result');
435
+ return body;
436
+ }
437
+
438
+ main().then(
439
+ function (body) {
440
+ if (body.ok === true) respond(body);
441
+ else refuse(typeof body.error === 'string' && body.error ? body.error : 'isolated provider failed');
442
+ },
443
+ function (error) { refuse(describe(error)); },
444
+ );
445
+ `;
446
+ //# sourceMappingURL=isolated-child-source.js.map