@inventarch/agent-composition-system 0.0.0-stage → 1.0.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.
Files changed (141) hide show
  1. package/LICENSE +202 -0
  2. package/NOTICE +4 -0
  3. package/README.md +2 -2
  4. package/SPEC.md +3 -0
  5. package/dist/adapters.d.ts +70 -0
  6. package/dist/adapters.d.ts.map +1 -0
  7. package/dist/adapters.js +212 -0
  8. package/dist/adapters.js.map +1 -0
  9. package/dist/authoring-format.d.ts +23 -0
  10. package/dist/authoring-format.d.ts.map +1 -0
  11. package/dist/authoring-format.js +288 -0
  12. package/dist/authoring-format.js.map +1 -0
  13. package/dist/authoring-index.d.ts +32 -0
  14. package/dist/authoring-index.d.ts.map +1 -0
  15. package/dist/authoring-index.js +252 -0
  16. package/dist/authoring-index.js.map +1 -0
  17. package/dist/authoring-manifest.d.ts +69 -0
  18. package/dist/authoring-manifest.d.ts.map +1 -0
  19. package/dist/authoring-manifest.js +387 -0
  20. package/dist/authoring-manifest.js.map +1 -0
  21. package/dist/authoring-types.d.ts +225 -0
  22. package/dist/authoring-types.d.ts.map +1 -0
  23. package/dist/authoring-types.js +2 -0
  24. package/dist/authoring-types.js.map +1 -0
  25. package/dist/authoring.d.ts +47 -0
  26. package/dist/authoring.d.ts.map +1 -0
  27. package/dist/authoring.js +565 -0
  28. package/dist/authoring.js.map +1 -0
  29. package/dist/candidate.d.ts +11 -0
  30. package/dist/candidate.d.ts.map +1 -0
  31. package/dist/candidate.js +84 -0
  32. package/dist/candidate.js.map +1 -0
  33. package/dist/catalog.d.ts +91 -0
  34. package/dist/catalog.d.ts.map +1 -0
  35. package/dist/catalog.js +6 -0
  36. package/dist/catalog.js.map +1 -0
  37. package/dist/compile.d.ts +13 -0
  38. package/dist/compile.d.ts.map +1 -0
  39. package/dist/compile.js +703 -0
  40. package/dist/compile.js.map +1 -0
  41. package/dist/compiled.d.ts +120 -0
  42. package/dist/compiled.d.ts.map +1 -0
  43. package/dist/compiled.js +9 -0
  44. package/dist/compiled.js.map +1 -0
  45. package/dist/corpus.d.ts +31 -0
  46. package/dist/corpus.d.ts.map +1 -0
  47. package/dist/corpus.js +174 -0
  48. package/dist/corpus.js.map +1 -0
  49. package/dist/execution.d.ts +6 -0
  50. package/dist/execution.d.ts.map +1 -0
  51. package/dist/execution.js +53 -0
  52. package/dist/execution.js.map +1 -0
  53. package/dist/fields.d.ts +16 -0
  54. package/dist/fields.d.ts.map +1 -0
  55. package/dist/fields.js +131 -0
  56. package/dist/fields.js.map +1 -0
  57. package/dist/index.d.ts +14 -0
  58. package/dist/index.d.ts.map +1 -0
  59. package/dist/index.js +9 -0
  60. package/dist/index.js.map +1 -0
  61. package/dist/inputs.d.ts +5 -0
  62. package/dist/inputs.d.ts.map +1 -0
  63. package/dist/inputs.js +28 -0
  64. package/dist/inputs.js.map +1 -0
  65. package/dist/installed-catalog.d.ts +4 -0
  66. package/dist/installed-catalog.d.ts.map +1 -0
  67. package/dist/installed-catalog.js +49 -0
  68. package/dist/installed-catalog.js.map +1 -0
  69. package/dist/installed-source-policy.d.ts +31 -0
  70. package/dist/installed-source-policy.d.ts.map +1 -0
  71. package/dist/installed-source-policy.js +95 -0
  72. package/dist/installed-source-policy.js.map +1 -0
  73. package/dist/lifecycle-profile.d.ts +46 -0
  74. package/dist/lifecycle-profile.d.ts.map +1 -0
  75. package/dist/lifecycle-profile.js +204 -0
  76. package/dist/lifecycle-profile.js.map +1 -0
  77. package/dist/lifecycle-transport.d.ts +21 -0
  78. package/dist/lifecycle-transport.d.ts.map +1 -0
  79. package/dist/lifecycle-transport.js +127 -0
  80. package/dist/lifecycle-transport.js.map +1 -0
  81. package/dist/lifecycle.d.ts +122 -0
  82. package/dist/lifecycle.d.ts.map +1 -0
  83. package/dist/lifecycle.js +437 -0
  84. package/dist/lifecycle.js.map +1 -0
  85. package/dist/local-store.d.ts +50 -0
  86. package/dist/local-store.d.ts.map +1 -0
  87. package/dist/local-store.js +186 -0
  88. package/dist/local-store.js.map +1 -0
  89. package/dist/projection-codex.d.ts +15 -0
  90. package/dist/projection-codex.d.ts.map +1 -0
  91. package/dist/projection-codex.js +74 -0
  92. package/dist/projection-codex.js.map +1 -0
  93. package/dist/projection-format.d.ts +146 -0
  94. package/dist/projection-format.d.ts.map +1 -0
  95. package/dist/projection-format.js +199 -0
  96. package/dist/projection-format.js.map +1 -0
  97. package/dist/projection-host.d.ts +41 -0
  98. package/dist/projection-host.d.ts.map +1 -0
  99. package/dist/projection-host.js +334 -0
  100. package/dist/projection-host.js.map +1 -0
  101. package/dist/projections.d.ts +24 -0
  102. package/dist/projections.d.ts.map +1 -0
  103. package/dist/projections.js +346 -0
  104. package/dist/projections.js.map +1 -0
  105. package/dist/publication.d.ts +7 -0
  106. package/dist/publication.d.ts.map +1 -0
  107. package/dist/publication.js +140 -0
  108. package/dist/publication.js.map +1 -0
  109. package/dist/resource-context.d.ts +26 -0
  110. package/dist/resource-context.d.ts.map +1 -0
  111. package/dist/resource-context.js +268 -0
  112. package/dist/resource-context.js.map +1 -0
  113. package/dist/resource-files.d.ts +10 -0
  114. package/dist/resource-files.d.ts.map +1 -0
  115. package/dist/resource-files.js +88 -0
  116. package/dist/resource-files.js.map +1 -0
  117. package/dist/resource-format.d.ts +106 -0
  118. package/dist/resource-format.d.ts.map +1 -0
  119. package/dist/resource-format.js +242 -0
  120. package/dist/resource-format.js.map +1 -0
  121. package/dist/resource-sources.d.ts +7 -0
  122. package/dist/resource-sources.d.ts.map +1 -0
  123. package/dist/resource-sources.js +16 -0
  124. package/dist/resource-sources.js.map +1 -0
  125. package/dist/resources.d.ts +24 -0
  126. package/dist/resources.d.ts.map +1 -0
  127. package/dist/resources.js +83 -0
  128. package/dist/resources.js.map +1 -0
  129. package/dist/sources.d.ts +45 -0
  130. package/dist/sources.d.ts.map +1 -0
  131. package/dist/sources.js +288 -0
  132. package/dist/sources.js.map +1 -0
  133. package/dist/templates.d.ts +35 -0
  134. package/dist/templates.d.ts.map +1 -0
  135. package/dist/templates.js +110 -0
  136. package/dist/templates.js.map +1 -0
  137. package/dist/tools.d.ts +32 -0
  138. package/dist/tools.d.ts.map +1 -0
  139. package/dist/tools.js +276 -0
  140. package/dist/tools.js.map +1 -0
  141. package/package.json +230 -3
@@ -0,0 +1,703 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { EditorSnapshot } from '@inventarch/db/editor';
3
+ import { systemMember } from '@inventarch/db';
4
+ import { context } from '@inventarch/runtime';
5
+ import { canonical, copy, digest } from '@inventarch/session-system';
6
+ import { MAX_MODEL_REQUEST_BYTES } from '@inventarch/agent-system';
7
+ import { verifyCapture } from './corpus.js';
8
+ import { CompositionError } from './compiled.js';
9
+ import { closedFields, fail, field, LIMIT_KEYS, limits, list, minimum, strings, unique, value } from './fields.js';
10
+ import { compatibleInputs } from './inputs.js';
11
+ const sha = (text) => createHash('sha256').update(text).digest('hex');
12
+ const effects = ['read', 'local-write', 'external-write'];
13
+ const outcomeKinds = [
14
+ 'answer',
15
+ 'deliverable',
16
+ 'clarification',
17
+ 'proposal',
18
+ 'follow-up',
19
+ 'handoff',
20
+ 'blocked',
21
+ 'refusal',
22
+ 'failure',
23
+ ];
24
+ const sort = (values, key) => values.sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
25
+ class Compiler {
26
+ task;
27
+ definitions;
28
+ options;
29
+ reader;
30
+ scope;
31
+ records;
32
+ components = new Map();
33
+ sources = new Map();
34
+ implementations = new Map();
35
+ provenance = {};
36
+ capabilities = {};
37
+ operations = {};
38
+ profiles = {};
39
+ bindings = [];
40
+ systems = new Set();
41
+ compilingCapabilities = new Set();
42
+ compilingProfiles = new Set();
43
+ operationBindings = new Map();
44
+ profileNodes = new Map();
45
+ host;
46
+ harness;
47
+ constructor(task, definitions, options) {
48
+ this.task = task;
49
+ this.definitions = definitions;
50
+ this.options = options;
51
+ this.reader = new EditorSnapshot({
52
+ root: process.cwd(),
53
+ sources: definitions.sources,
54
+ folders: definitions.folders,
55
+ floorOrigin: definitions.floorOrigin,
56
+ fingerprint: definitions.revision,
57
+ ...(definitions.activation ? { activation: definitions.activation } : {}),
58
+ });
59
+ this.scope = this.reader.resolveScope().token;
60
+ this.records = this.reader.records({ within: this.scope });
61
+ for (const source of definitions.sources.filter((s) => s.location.placement.kind === 'floor'))
62
+ this.source(source.path);
63
+ }
64
+ source(path) {
65
+ const source = this.definitions.sources.find((s) => s.path === path);
66
+ if (!source)
67
+ fail('IA-COMPOSITION-REFERENCE', 'Admitted component source is unavailable');
68
+ const hash = sha(source.text);
69
+ this.sources.set(path, hash);
70
+ return hash;
71
+ }
72
+ pin(node, reason) {
73
+ if (reason)
74
+ this.provenance[reason] = unique([...(this.provenance[reason] ?? []), node.identity]);
75
+ if (this.components.has(node.identity))
76
+ return;
77
+ if (this.components.size >= 2000)
78
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Executable closure exceeds 2,000 components', node);
79
+ this.components.set(node.identity, {
80
+ identity: node.identity,
81
+ owner: node.system,
82
+ physicalOwner: systemMember(node.source.path)?.name ?? null,
83
+ schema: node.schema,
84
+ source: { ...node.source, digest: this.source(node.source.path) },
85
+ digest: digest(node),
86
+ });
87
+ const registry = this.reader.inspect().graph.registry;
88
+ const schema = registry.schemas.get(registry.registrations.get(node.discriminator)?.schema ?? node.name);
89
+ if (schema)
90
+ this.source(schema.path);
91
+ this.pinSystem(node.system);
92
+ const physical = systemMember(node.source.path)?.name;
93
+ if (physical)
94
+ this.pinSystem(physical);
95
+ }
96
+ pinSystem(name) {
97
+ if (this.systems.has(name))
98
+ return;
99
+ this.systems.add(name);
100
+ // The selected floor is a built-in registry dependency; its exact source bytes are pinned above.
101
+ if (name === 'floor')
102
+ return;
103
+ const declaration = this.reader.inspect().graph.registry.systems.get(name);
104
+ if (!declaration)
105
+ fail('IA-COMPOSITION-REFERENCE', `System ${name} is unavailable`);
106
+ this.source(declaration.path);
107
+ for (const requirement of declaration.requires)
108
+ this.pinSystem(requirement.name);
109
+ if (declaration.steward)
110
+ this.pin(this.reference({ kind: 'ref', ...declaration.steward }, undefined, 'steward'));
111
+ }
112
+ select(id, discriminator) {
113
+ const candidates = this.records.filter((r) => r.discriminator === discriminator && (r.identity === id || r.name === id));
114
+ if (candidates.length !== 1) {
115
+ const refused = this.reader.refused.find((r) => r.identity === id || r.identity.endsWith(`/${id}`));
116
+ if (refused)
117
+ throw new CompositionError({
118
+ code: 'IA-COMPOSITION-REFERENCE',
119
+ message: `Expected one admitted ${discriminator}: ${id}`,
120
+ source: { identity: refused.identity, path: refused.path, line: refused.line },
121
+ admission: this.reader.report.findings
122
+ .filter((f) => f.path === refused.path)
123
+ .slice(0, 8)
124
+ .map(({ code, path, line }) => ({ code, path, line })),
125
+ });
126
+ fail('IA-COMPOSITION-REFERENCE', `Expected one admitted ${discriminator}: ${id}`);
127
+ }
128
+ const result = candidates[0];
129
+ this.pin(result);
130
+ return result;
131
+ }
132
+ reference(ref, from, path, expected) {
133
+ if (!ref || ref.kind !== 'ref' || ref.fragment || (expected && ref.discriminator !== expected))
134
+ fail('IA-COMPOSITION-REFERENCE', `Expected an admitted ${expected ?? 'record'} reference without fragment`, from, path);
135
+ const resolution = this.reader.resolve(ref, { within: this.scope });
136
+ if (!resolution.ok)
137
+ fail('IA-COMPOSITION-REFERENCE', resolution.code, from, path);
138
+ const node = this.reader.get(resolution.identity, { within: this.scope });
139
+ if (!node || (expected && node.discriminator !== expected))
140
+ fail('IA-COMPOSITION-REFERENCE', 'Referenced record is unavailable', from, path);
141
+ this.pin(node, from && path ? `${from.identity}:${path}` : undefined);
142
+ return node;
143
+ }
144
+ refs(node, section, key, expected) {
145
+ const found = list(node, section, key).map((ref) => this.reference(ref, node, `${section}.${key}`, expected));
146
+ if (new Set(found.map((r) => r.identity)).size !== found.length)
147
+ fail('IA-COMPOSITION-CONFLICT', 'Duplicate component reference', node, `${section}.${key}`);
148
+ return found;
149
+ }
150
+ use(group, id, node, path) {
151
+ const entries = this.options.catalog[group];
152
+ const descriptor = entries && Object.hasOwn(entries, id) ? entries[id] : undefined;
153
+ if (!descriptor)
154
+ fail('IA-COMPOSITION-UNAVAILABLE', `Installed ${group} contract is unavailable: ${id}`, node, path);
155
+ let valid = false;
156
+ try {
157
+ valid =
158
+ descriptor.version === 1 &&
159
+ descriptor.digest === digest({ version: descriptor.version, value: descriptor.value });
160
+ }
161
+ catch {
162
+ /* non-serializable descriptors refuse */
163
+ }
164
+ if (!valid)
165
+ fail('IA-COMPOSITION-CONFLICT', `Installed ${group} contract digest/version mismatch: ${id}`, node, path);
166
+ const address = `${group}:${id}`;
167
+ this.implementations.set(address, { group, id, digest: descriptor.digest });
168
+ this.provenance[`${node.identity}:${path}`] = unique([
169
+ ...(this.provenance[`${node.identity}:${path}`] ?? []),
170
+ address,
171
+ ]);
172
+ return copy(descriptor.value);
173
+ }
174
+ effectList(values, node, path) {
175
+ if (values.some((v) => !effects.includes(v)) || new Set(values).size !== values.length)
176
+ fail('IA-COMPOSITION-CONFLICT', 'Unknown or duplicate effect class', node, path);
177
+ return [...values];
178
+ }
179
+ bounds(values, node) {
180
+ if (Object.keys(values).some((k) => !LIMIT_KEYS.includes(k)) ||
181
+ Object.entries(values).some(([k, v]) => !Number.isSafeInteger(v) || v < 0 || (k === 'durationMs' && v === 0)))
182
+ fail('IA-COMPOSITION-CONFLICT', 'Invalid installed resource limits', node);
183
+ return values;
184
+ }
185
+ input(id, node, path) {
186
+ const { schema } = this.use('validators', id, node, path);
187
+ // Validate the schema itself, not a guessed sample value. Unknown vocabulary refuses at load.
188
+ const shape = (s) => {
189
+ if (!s ||
190
+ typeof s !== 'object' ||
191
+ Array.isArray(s) ||
192
+ Object.keys(s).some((k) => ![
193
+ 'type',
194
+ 'properties',
195
+ 'required',
196
+ 'additionalProperties',
197
+ 'items',
198
+ 'enum',
199
+ 'maxLength',
200
+ 'maxItems',
201
+ 'minimum',
202
+ 'maximum',
203
+ ].includes(k)))
204
+ return false;
205
+ for (const k of ['maxLength', 'maxItems'])
206
+ if (s[k] !== undefined && (!Number.isSafeInteger(s[k]) || s[k] < 0))
207
+ return false;
208
+ for (const k of ['minimum', 'maximum'])
209
+ if (s[k] !== undefined && (typeof s[k] !== 'number' || !Number.isFinite(s[k])))
210
+ return false;
211
+ if (typeof s['minimum'] === 'number' && typeof s['maximum'] === 'number' && s['minimum'] > s['maximum'])
212
+ return false;
213
+ if (s['enum'] !== undefined && (!Array.isArray(s['enum']) || !s['enum'].length))
214
+ return false;
215
+ if (s['type'] === 'object') {
216
+ const p = s['properties'];
217
+ return (!!p &&
218
+ typeof p === 'object' &&
219
+ !Array.isArray(p) &&
220
+ s['additionalProperties'] === false &&
221
+ Array.isArray(s['required']) &&
222
+ s['required'].every((k) => typeof k === 'string' && Object.hasOwn(p, k)) &&
223
+ Object.values(p).every(shape));
224
+ }
225
+ if (s['type'] === 'array')
226
+ return s['items'] !== undefined && shape(s['items']);
227
+ return ['string', 'number', 'integer', 'boolean', 'null'].includes(String(s['type']));
228
+ };
229
+ if (!shape(schema))
230
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Validator uses an unsupported or malformed schema', node, path);
231
+ return schema;
232
+ }
233
+ mapping(id, node) {
234
+ if (this.use('mappings', id, node, 'execution.mapping-profile').kind !== 'identity')
235
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Only the installed identity mapping is supported', node);
236
+ }
237
+ outcome(id, node) {
238
+ const result = this.use('outcomes', id, node, 'execution.outcomes');
239
+ if (!result.kinds.length ||
240
+ result.kinds.some((v) => !outcomeKinds.includes(v)) ||
241
+ !['response', 'proposal', 'artifact'].includes(result.completion))
242
+ fail('IA-COMPOSITION-CONFLICT', 'Invalid outcome contract', node);
243
+ return result;
244
+ }
245
+ operation(node) {
246
+ if (this.operations[node.identity])
247
+ return node.identity;
248
+ const candidates = this.operationBindings.get(node.identity) ?? [];
249
+ if (candidates.length !== 1)
250
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Operation requires exactly one admitted implementation binding', node);
251
+ const binding = candidates[0], implementation = field(binding, 'binding', 'implementation');
252
+ closedFields(node);
253
+ if (value(binding, 'binding', 'mapping'))
254
+ this.mapping(field(binding, 'binding', 'mapping'), binding);
255
+ this.pin(binding);
256
+ const descriptor = this.use('operations', implementation, node, 'execution.handler');
257
+ if (!/^[a-f0-9]{64}$/.test(descriptor.implementationDigest))
258
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Installed operation lacks a verified implementation digest', node, 'execution.handler');
259
+ const physicalOwner = systemMember(node.source.path)?.name;
260
+ if (descriptor.identity !== node.identity ||
261
+ descriptor.owner !== physicalOwner ||
262
+ node.system !== 'authoring-system' ||
263
+ field(node, 'execution', 'handler') !== implementation)
264
+ fail('IA-COMPOSITION-CONFLICT', 'Operation identity, physical owner or native handler differs from its installed binding', node);
265
+ if (field(node, 'execution', 'profile', '') !== 'governed-v1')
266
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Legacy operation has no general-executor profile', node, 'execution.profile');
267
+ const declaredEffect = field(node, 'execution', 'effects');
268
+ const nativeEffects = this.effectList([['read-only', 'draft-only'].includes(declaredEffect) ? 'read' : declaredEffect], node, 'execution.effects');
269
+ const contractEffects = this.effectList(descriptor.effects, node, 'execution.effects');
270
+ if (descriptor.purpose !== undefined &&
271
+ (descriptor.purpose !== 'candidate-validation' || contractEffects.some((effect) => effect !== 'read')))
272
+ fail('IA-COMPOSITION-CONFLICT', 'Candidate validation must use a read-only installed contract', node);
273
+ if (canonical(nativeEffects) !== canonical(contractEffects) ||
274
+ field(node, 'execution', 'input') !== descriptor.input ||
275
+ field(node, 'execution', 'output') !== descriptor.output ||
276
+ field(node, 'execution', 'recovery') !== descriptor.recovery)
277
+ fail('IA-COMPOSITION-CONFLICT', 'Native operation contract differs from its installed descriptor', node);
278
+ if (!['repeatable', 'idempotent', 'reconcile', 'manual'].includes(descriptor.recovery) ||
279
+ (descriptor.recovery === 'repeatable' && contractEffects.some((e) => e !== 'read')) ||
280
+ !['captured-workspace', 'managed-draft'].includes(descriptor.preflight) ||
281
+ (descriptor.preflight === 'managed-draft' &&
282
+ (canonical(contractEffects) !== canonical(['local-write']) || descriptor.recovery !== 'reconcile')) ||
283
+ !descriptor.handler ||
284
+ !Number.isSafeInteger(descriptor.timeoutMs) ||
285
+ descriptor.timeoutMs <= 0 ||
286
+ !Number.isSafeInteger(descriptor.maxOutputBytes) ||
287
+ descriptor.maxOutputBytes <= 0 ||
288
+ descriptor.maxOutputBytes > 65_536)
289
+ fail('IA-COMPOSITION-CONFLICT', 'Invalid effect, recovery or resource contract', node);
290
+ const input = this.input(descriptor.input, node, 'execution.input'), output = this.input(descriptor.output, node, 'execution.output');
291
+ const operation = {
292
+ id: node.identity,
293
+ native: node.identity,
294
+ owner: node.system,
295
+ physicalOwner: physicalOwner,
296
+ handler: descriptor.handler,
297
+ digest: digest({
298
+ descriptor,
299
+ native: this.components.get(node.identity),
300
+ binding: this.components.get(binding.identity),
301
+ input,
302
+ output,
303
+ }),
304
+ effects: contractEffects,
305
+ recovery: descriptor.recovery,
306
+ timeoutMs: descriptor.timeoutMs,
307
+ input,
308
+ output,
309
+ maxOutputBytes: descriptor.maxOutputBytes,
310
+ preflight: descriptor.preflight,
311
+ ...(descriptor.purpose ? { purpose: descriptor.purpose } : {}),
312
+ };
313
+ for (const prior of Object.values(this.operations))
314
+ if (prior.handler === operation.handler &&
315
+ canonical({
316
+ input: prior.input,
317
+ output: prior.output,
318
+ effects: prior.effects,
319
+ recovery: prior.recovery,
320
+ timeoutMs: prior.timeoutMs,
321
+ maxOutputBytes: prior.maxOutputBytes,
322
+ preflight: prior.preflight,
323
+ purpose: prior.purpose ?? null,
324
+ }) !==
325
+ canonical({
326
+ input,
327
+ output,
328
+ effects: contractEffects,
329
+ recovery: descriptor.recovery,
330
+ timeoutMs: descriptor.timeoutMs,
331
+ maxOutputBytes: descriptor.maxOutputBytes,
332
+ preflight: descriptor.preflight,
333
+ purpose: descriptor.purpose ?? null,
334
+ }))
335
+ fail('IA-COMPOSITION-CONFLICT', 'Shared handler contracts are incompatible', node);
336
+ this.operations[node.identity] = operation;
337
+ this.bindings.push({
338
+ identity: binding.identity,
339
+ kind: 'operation',
340
+ implementation,
341
+ target: node.identity,
342
+ digest: this.components.get(binding.identity).digest,
343
+ });
344
+ return node.identity;
345
+ }
346
+ capability(node) {
347
+ const prior = this.capabilities[node.identity];
348
+ if (prior)
349
+ return prior;
350
+ if (this.compilingCapabilities.has(node.identity))
351
+ fail('IA-COMPOSITION-CYCLE', 'Capability inclusion cycle', node, 'composition.includes');
352
+ if (this.compilingCapabilities.size >= 64)
353
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Capability inclusion exceeds 64 levels', node);
354
+ this.compilingCapabilities.add(node.identity);
355
+ closedFields(node);
356
+ const children = this.refs(node, 'composition', 'includes', 'capability').map((n) => this.capability(n));
357
+ const operations = unique([
358
+ ...children.flatMap((c) => c.operations),
359
+ ...this.refs(node, 'composition', 'operations', 'operation').map((n) => this.operation(n)),
360
+ ]);
361
+ const ownEffects = this.effectList(strings(node, 'execution', 'effects'), node, 'execution.effects');
362
+ const requiredEffects = unique([
363
+ ...children.flatMap((c) => c.effects),
364
+ ...operations.flatMap((id) => this.operations[id].effects),
365
+ ]);
366
+ if (requiredEffects.some((e) => !ownEffects.includes(e)))
367
+ fail('IA-COMPOSITION-CONFLICT', 'Included work exceeds the capability effect declaration', node, 'execution.effects');
368
+ const input = field(node, 'execution', 'input', this.host.defaults.input), outcomes = field(node, 'execution', 'outcomes', this.host.defaults.outcomes), context = field(node, 'execution', 'context-profile', this.host.defaults.context), mapping = field(node, 'execution', 'mapping-profile', this.host.defaults.mapping);
369
+ this.input(input, node, 'execution.input');
370
+ this.outcome(outcomes, node);
371
+ this.use('contexts', context, node, 'execution.context-profile');
372
+ this.mapping(mapping, node);
373
+ if (value(node, 'execution', 'procedure-profile'))
374
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Structured procedures require an installed scheduler consumer', node, 'execution.procedure-profile');
375
+ const checks = this.refs(node, 'composition', 'checks', 'check').map((check) => {
376
+ const id = field(check, 'check', 'runs');
377
+ this.use('evaluators', id, check, 'check.runs');
378
+ return id;
379
+ });
380
+ const result = {
381
+ identity: node.identity,
382
+ includes: children.map((c) => c.identity),
383
+ operations,
384
+ effects: ownEffects,
385
+ input,
386
+ outcomes,
387
+ context,
388
+ mapping,
389
+ limits: minimum(limits(node), ...children.map((c) => c.limits)),
390
+ checks: unique([...children.flatMap((c) => c.checks), ...checks]),
391
+ playbooks: unique([
392
+ ...children.flatMap((c) => c.playbooks),
393
+ ...this.refs(node, 'composition', 'playbooks', 'playbook').map((n) => n.identity),
394
+ ]),
395
+ templates: unique([
396
+ ...children.flatMap((c) => c.templates),
397
+ ...this.refs(node, 'composition', 'templates', 'template').map((n) => n.identity),
398
+ ]),
399
+ };
400
+ this.capabilities[node.identity] = result;
401
+ this.compilingCapabilities.delete(node.identity);
402
+ return result;
403
+ }
404
+ profile(node) {
405
+ const prior = this.profiles[node.identity];
406
+ if (prior)
407
+ return prior;
408
+ if (this.compilingProfiles.has(node.identity))
409
+ fail('IA-COMPOSITION-CYCLE', 'Delegate profile cycle', node, 'composition.delegates');
410
+ if (this.compilingProfiles.size >= 32)
411
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Profile dependency exceeds 32 levels', node);
412
+ this.compilingProfiles.add(node.identity);
413
+ this.pin(node);
414
+ closedFields(node);
415
+ const agent = this.reference(value(node, 'composition', 'agent', true), node, 'composition.agent', 'agent');
416
+ const voiceRef = value(node, 'composition', 'voice'), voice = voiceRef ? this.reference(voiceRef, node, 'composition.voice', 'voice') : undefined;
417
+ const mandateRef = value(node, 'composition', 'mandate'), mandate = mandateRef ? this.reference(mandateRef, node, 'composition.mandate', 'mandate') : undefined;
418
+ if (voice)
419
+ closedFields(voice);
420
+ if (mandate)
421
+ closedFields(mandate);
422
+ const roots = this.refs(node, 'composition', 'capabilities', 'capability').map((n) => this.capability(n));
423
+ const closure = new Map();
424
+ const expand = (c) => {
425
+ if (closure.has(c.identity))
426
+ return;
427
+ closure.set(c.identity, c);
428
+ for (const id of c.includes)
429
+ expand(this.capabilities[id]);
430
+ };
431
+ roots.forEach(expand);
432
+ const capabilities = [...closure.values()];
433
+ const contractIds = unique([
434
+ field(node, 'execution', 'mandate-contract'),
435
+ ...(mandate && value(mandate, 'execution', 'contract') ? [field(mandate, 'execution', 'contract')] : []),
436
+ ]);
437
+ const contracts = contractIds.map((id) => this.use('mandates', id, node, 'execution.mandate-contract'));
438
+ const outcomeIds = unique([
439
+ field(node, 'execution', 'outcomes'),
440
+ ...contracts.map((c) => c.outcomes),
441
+ ...capabilities.map((c) => c.outcomes),
442
+ ]);
443
+ const outcomeContracts = outcomeIds.map((id) => this.outcome(id, node));
444
+ const allowedOutcomes = outcomeContracts.reduce((allowed, c) => allowed.filter((kind) => c.kinds.includes(kind)), outcomeKinds);
445
+ const obligations = unique(outcomeContracts.map((o) => o.completion).filter((v) => v !== 'response'));
446
+ if (!allowedOutcomes.length || obligations.length > 1)
447
+ fail('IA-COMPOSITION-CONFLICT', 'Incompatible outcome or completion obligations', node, 'execution.outcomes');
448
+ const effectiveEffects = contracts.reduce((allowed, c) => allowed.filter((e) => this.effectList(c.effects, node, 'execution.mandate-contract').includes(e)), this.host.effects);
449
+ if (capabilities.some((c) => c.effects.some((e) => !effectiveEffects.includes(e))))
450
+ fail('IA-COMPOSITION-CONFLICT', 'Capability effects exceed the host or mandate restriction', node, 'composition.capabilities');
451
+ const modelId = field(node, 'execution', 'model-profile', this.host.defaults.model), model = this.use('models', modelId, node, 'execution.model-profile');
452
+ if (!model.model ||
453
+ !this.host.models.includes(modelId) ||
454
+ contracts.some((c) => c.models && !c.models.includes(modelId)))
455
+ fail('IA-COMPOSITION-CONFLICT', 'Model profile exceeds the host or mandate restriction', node, 'execution.model-profile');
456
+ const contexts = unique([...contracts.map((c) => c.context), ...capabilities.map((c) => c.context)]);
457
+ const checks = unique([...contracts.flatMap((c) => c.checks), ...capabilities.flatMap((c) => c.checks)]);
458
+ for (const id of checks)
459
+ this.use('evaluators', id, node, 'execution.checks');
460
+ const instructions = [this.recordText(agent)];
461
+ if (mandate)
462
+ instructions.push(this.recordText(mandate));
463
+ for (const contextId of contexts) {
464
+ const contract = this.use('contexts', contextId, node, 'execution.context-profile');
465
+ if (contract.scope !== 'captured-workspace' ||
466
+ !Number.isSafeInteger(contract.tokens) ||
467
+ contract.tokens <= 0 ||
468
+ contract.tokens > 131_072 ||
469
+ !Number.isSafeInteger(contract.records) ||
470
+ contract.records <= 0 ||
471
+ contract.records > 2000)
472
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Unsupported context contract', node);
473
+ // Native runtime chooses cells and applicable governance. Never flatten conditional playbook text.
474
+ const packet = context(this.reader, { within: this.scope, text: '', coordinate: contract.coordinate }, { tokens: contract.tokens, records: contract.records });
475
+ if (!packet.ok)
476
+ fail('IA-COMPOSITION-UNAVAILABLE', packet.message, node, 'execution.context-profile');
477
+ for (const entry of packet.packet.included.filter((e) => e.kind === 'governance')) {
478
+ this.pin(this.reader.get(entry.identity, { within: this.scope }));
479
+ instructions.push(entry.text);
480
+ }
481
+ for (const id of unique(capabilities.flatMap((c) => c.playbooks))) {
482
+ const scoped = this.reader.resolveScope({ within: this.scope, identities: [id] });
483
+ const method = context(this.reader, { within: scoped.token, text: '', subject: id, coordinate: contract.coordinate }, { tokens: contract.tokens, records: contract.records }, { purpose: true });
484
+ const selected = method.ok ? method.packet.included.find((e) => e.identity === id) : undefined;
485
+ if (!selected ||
486
+ !selected.address.startsWith(`${id}#${contract.coordinate.phase}/`) ||
487
+ !method.ok ||
488
+ method.packet.omitted.some((e) => e.reason === 'budget'))
489
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Required method is unavailable at the installed coordinate/budget', node, 'composition.playbooks');
490
+ // The method's says/answers lead its cell, so the agent reads what the step is for before the step.
491
+ instructions.push(selected.purpose === undefined ? selected.text : `${selected.purpose}\n${selected.text}`);
492
+ }
493
+ }
494
+ const inputContracts = unique([...contracts.map((c) => c.input), ...capabilities.map((c) => c.input)]).map((id) => ({ id, schema: this.input(id, node, 'execution.input') }));
495
+ if (!compatibleInputs(inputContracts.map((c) => c.schema)))
496
+ fail('IA-COMPOSITION-CONFLICT', 'Required input contracts have no common value', node, 'execution.input');
497
+ // Every declared input contract is retained for conjunction at runtime; none is silently preferred.
498
+ const result = {
499
+ id: node.identity,
500
+ native: node.identity,
501
+ agent: agent.identity,
502
+ role: field(node, 'execution', 'role'),
503
+ voice: voice
504
+ ? ['tone', 'terminology', 'explanation', 'uncertainty', 'audience', 'citations']
505
+ .flatMap((key) => value(voice, 'communication', key) ? [`${key}: ${field(voice, 'communication', key)}`] : [])
506
+ .join('\n')
507
+ : '',
508
+ instructions: unique(instructions),
509
+ operations: unique(capabilities.flatMap((c) => c.operations)),
510
+ capabilities: capabilities.map((c) => c.identity),
511
+ delegates: [],
512
+ outcomes: allowedOutcomes,
513
+ completion: obligations[0] ?? 'response',
514
+ checks,
515
+ model: model.model,
516
+ ...(this.host.requestBytes === undefined ? {} : { requestBytes: this.host.requestBytes }),
517
+ mandate: mandate?.identity ?? null,
518
+ mandateContracts: contractIds,
519
+ inputContracts,
520
+ effects: effectiveEffects,
521
+ limits: minimum(this.bounds(this.host.limits, node), limits(this.harness), ...contracts.map((c) => this.bounds(c.limits, node)), ...(mandate ? [limits(mandate)] : []), limits(node), ...capabilities.map((c) => c.limits)),
522
+ contexts,
523
+ templates: unique(capabilities.flatMap((c) => c.templates)),
524
+ delegation: [],
525
+ };
526
+ for (const childNode of this.refs(node, 'composition', 'delegates', 'agent-profile')) {
527
+ if (!this.profileNodes.has(childNode.identity))
528
+ fail('IA-COMPOSITION-REFERENCE', 'Delegate is outside the harness', node, 'composition.delegates');
529
+ const child = this.profile(childNode);
530
+ if (child.agent === result.agent ||
531
+ child.operations.some((id) => !result.operations.includes(id)) ||
532
+ child.effects.some((e) => !result.effects.includes(e)))
533
+ fail('IA-COMPOSITION-CONFLICT', 'Delegate repeats the agent or widens parent work/effects', node, 'composition.delegates');
534
+ result.delegates.push(child.id);
535
+ result.delegation.push({ profile: child.id, limits: minimum(result.limits, child.limits) });
536
+ }
537
+ const contributors = {
538
+ ...(this.host.requestBytes === undefined
539
+ ? {}
540
+ : { requestBytes: [`hosts:${field(this.harness, 'execution', 'host-profile')}`] }),
541
+ agent: [agent.identity],
542
+ role: [node.identity],
543
+ voice: [voice?.identity ?? node.identity],
544
+ instructions: unique([
545
+ agent.identity,
546
+ ...(mandate ? [mandate.identity] : []),
547
+ ...capabilities.flatMap((c) => c.playbooks),
548
+ ...[...this.components.values()].filter((p) => p.identity.includes('/governance/')).map((p) => p.identity),
549
+ ]),
550
+ capabilities: capabilities.map((c) => c.identity),
551
+ operations: result.operations,
552
+ delegates: [node.identity, ...result.delegates],
553
+ limits: [
554
+ this.harness.identity,
555
+ node.identity,
556
+ ...(mandate ? [mandate.identity] : []),
557
+ ...capabilities.map((c) => c.identity),
558
+ ...contractIds.map((id) => `mandates:${id}`),
559
+ `hosts:${field(this.harness, 'execution', 'host-profile')}`,
560
+ ],
561
+ effects: [
562
+ node.identity,
563
+ ...capabilities.map((c) => c.identity),
564
+ ...contractIds.map((id) => `mandates:${id}`),
565
+ `hosts:${field(this.harness, 'execution', 'host-profile')}`,
566
+ ],
567
+ model: [`models:${modelId}`],
568
+ checks: checks.map((id) => `evaluators:${id}`),
569
+ inputContracts: inputContracts.map((c) => `validators:${c.id}`),
570
+ outcomes: outcomeIds.map((id) => `outcomes:${id}`),
571
+ completion: outcomeIds.map((id) => `outcomes:${id}`),
572
+ contexts: contexts.map((id) => `contexts:${id}`),
573
+ templates: result.templates,
574
+ mandateContracts: contractIds.map((id) => `mandates:${id}`),
575
+ };
576
+ for (const [key, sources] of Object.entries(contributors))
577
+ this.provenance[`normalized:${node.identity}:${key}`] = sources;
578
+ this.profiles[node.identity] = result;
579
+ this.compilingProfiles.delete(node.identity);
580
+ return result;
581
+ }
582
+ recordText(node) {
583
+ const source = this.definitions.sources.find((s) => s.path === node.source.path);
584
+ return source.text
585
+ .split('\n')
586
+ .slice(node.source.line - 1, node.source.endLine)
587
+ .join('\n');
588
+ }
589
+ compile() {
590
+ this.harness = this.select(this.options.harness, 'harness');
591
+ closedFields(this.harness);
592
+ const workspace = this.reference(value(this.harness, 'composition', 'workspace', true), this.harness, 'composition.workspace', 'workspace');
593
+ for (const system of this.refs(workspace, 'composition', 'systems', 'system'))
594
+ this.pinSystem(system.name);
595
+ const hostId = field(this.harness, 'execution', 'host-profile');
596
+ this.host = this.use('hosts', hostId, this.harness, 'execution.host-profile');
597
+ if (this.host.requestBytes !== undefined &&
598
+ (!Number.isSafeInteger(this.host.requestBytes) ||
599
+ this.host.requestBytes <= 0 ||
600
+ this.host.requestBytes > MAX_MODEL_REQUEST_BYTES))
601
+ fail('IA-COMPOSITION-CONFLICT', 'Invalid installed model request ceiling', this.harness, 'execution.host-profile');
602
+ this.effectList(this.host.effects, this.harness, 'execution.host-profile');
603
+ this.bounds(this.host.limits, this.harness);
604
+ const roles = new Set();
605
+ for (const node of this.refs(this.harness, 'composition', 'profiles', 'agent-profile')) {
606
+ const role = field(node, 'execution', 'role');
607
+ if (roles.has(role))
608
+ fail('IA-COMPOSITION-ROLE', 'Profile roles must be unique in a harness', node, 'execution.role');
609
+ roles.add(role);
610
+ this.profileNodes.set(node.identity, node);
611
+ }
612
+ const bindings = this.refs(this.harness, 'composition', 'bindings', 'execution-binding');
613
+ for (const binding of bindings) {
614
+ closedFields(binding);
615
+ const kind = field(binding, 'binding', 'kind');
616
+ if (!['entry', 'operation'].includes(kind))
617
+ fail('IA-COMPOSITION-UNAVAILABLE', `Binding profile ${kind} has no installed consumer in this compiler version`, binding, 'binding.kind');
618
+ for (const key of ['event', 'guard', 'tools', 'filters'])
619
+ if (value(binding, 'binding', key))
620
+ fail('IA-COMPOSITION-CONFLICT', `Field ${key} is not valid for ${kind}`, binding, `binding.${key}`);
621
+ if (kind === 'operation') {
622
+ const target = this.reference(value(binding, 'binding', 'target', true), binding, 'binding.target', 'operation');
623
+ this.operationBindings.set(target.identity, [...(this.operationBindings.get(target.identity) ?? []), binding]);
624
+ }
625
+ }
626
+ const entries = bindings.filter((b) => field(b, 'binding', 'kind') === 'entry' && (b.identity === this.options.entry || b.name === this.options.entry));
627
+ if (entries.length !== 1)
628
+ fail('IA-COMPOSITION-REFERENCE', 'Select one admitted entry binding in the harness', this.harness, 'composition.bindings');
629
+ const entry = entries[0], implementation = field(entry, 'binding', 'implementation'), entryContract = this.use('entries', implementation, entry, 'binding.implementation');
630
+ if (entryContract.target !== 'agent-profile')
631
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Entry target contract is unsupported', entry);
632
+ const mapping = field(entry, 'binding', 'mapping', entryContract.mapping);
633
+ this.mapping(mapping, entry);
634
+ if (mapping !== entryContract.mapping)
635
+ fail('IA-COMPOSITION-CONFLICT', 'Entry mapping differs from the installed transport', entry);
636
+ const target = this.reference(value(entry, 'binding', 'target', true), entry, 'binding.target', 'agent-profile');
637
+ if (!this.profileNodes.has(target.identity))
638
+ fail('IA-COMPOSITION-REFERENCE', 'Entry profile is outside the harness', entry);
639
+ this.profile(target);
640
+ const ancestry = (id, agents, checked = new Set()) => {
641
+ const profile = this.profiles[id];
642
+ if (agents.includes(profile.agent))
643
+ fail('IA-COMPOSITION-CYCLE', 'Agent repeats in its active ancestor chain', this.profileNodes.get(id), 'composition.delegates');
644
+ const state = canonical([id, [...agents].sort()]);
645
+ if (checked.has(state))
646
+ return;
647
+ if (checked.size >= 2000)
648
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Delegate ancestry exceeds 2,000 states', this.profileNodes.get(id));
649
+ checked.add(state);
650
+ for (const child of profile.delegates)
651
+ ancestry(child, [...agents, profile.agent], checked);
652
+ };
653
+ ancestry(target.identity, []);
654
+ this.bindings.push({
655
+ identity: entry.identity,
656
+ kind: 'entry',
657
+ implementation,
658
+ target: target.identity,
659
+ digest: this.components.get(entry.identity).digest,
660
+ });
661
+ const components = sort([...this.components.values()], (c) => c.identity), sources = sort([...this.sources].map(([path, hash]) => ({ path, digest: hash })), (s) => s.path), installed = sort([...this.implementations.values()], (c) => `${c.group}:${c.id}`);
662
+ const provenance = {
663
+ executableDigest: digest({ components, sources, installed }),
664
+ components,
665
+ sources,
666
+ installed,
667
+ fields: this.provenance,
668
+ };
669
+ const body = {
670
+ format: 'ia.compiled-harness.v1',
671
+ id: this.harness.identity,
672
+ workspace: workspace.identity,
673
+ sourceDigest: this.task.revision,
674
+ entry: { binding: entry.identity, profile: target.identity, mapping },
675
+ profiles: this.profiles,
676
+ capabilities: this.capabilities,
677
+ operations: this.operations,
678
+ bindings: sort(this.bindings, (b) => b.identity),
679
+ provenance,
680
+ };
681
+ if (Buffer.byteLength(canonical(body)) > 2 * 1024 * 1024)
682
+ fail('IA-COMPOSITION-UNAVAILABLE', 'Compiled manifest exceeds 2 MiB', this.harness);
683
+ return { ...body, digest: digest(body) };
684
+ }
685
+ }
686
+ /** Pure admission/compilation. No provider, implementation callback, installation or filesystem write. */
687
+ export function compileHarness(capture, options) {
688
+ let compiler;
689
+ try {
690
+ const task = verifyCapture(capture), definitions = verifyCapture(options.definitions ?? capture);
691
+ compiler = new Compiler(task, definitions, options);
692
+ return { ok: true, manifest: compiler.compile() };
693
+ }
694
+ catch (error) {
695
+ if (!(error instanceof CompositionError))
696
+ throw error;
697
+ return { ok: false, diagnostics: [error.diagnostic] };
698
+ }
699
+ finally {
700
+ compiler?.reader.close();
701
+ }
702
+ }
703
+ //# sourceMappingURL=compile.js.map